Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
merge: rebase plugin downloads onto the unified downloader (#5110)
Dasheb319ffeae6a
diff --cc apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.tsindex 7058218fcc,0000000000..6656f6f4e9mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts@@@ -1,310 -1,0 +1,367 @@@+import { it, expect, vi } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++const guarded = vi.hoisted(() => ({ fetch: vi.fn() }));++vi.mock('../../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: guarded.fetch }));+import { PluginDownloadSlot } from '../downloadSlot';+import { PluginDownloadCache } from '../downloadCache';+import type { InstalledGhost } from '../../../shared/ghost';+it('a destroyed caller cannot enter Node after a delayed lease, even if the plugin remains enabled', async () => {+ let finish!: () => void;+ const barrier = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const release = vi.fn();+ const acquire = vi+ .spyOn(PluginDownloadCache.prototype, 'acquire')+ .mockImplementation(async () => {+ await barrier;+ return { path: '/fixture/artifact', release };+ });+ let active = true;+ const slot = new PluginDownloadSlot({+ root: () => '/fixture',+ scope: () => 'owner',+ send() {},+ getGhost: () => ({ enabled: true, approval: {}, manifest: { node: {} } }) as InstalledGhost,+ download: async () => {+ throw Error('unused');+ },+ });+ const run = vi.fn(async () => ({ ok: true }));+ try {+ const request = slot.withNodeDownloads(+ 'p',+ { downloadTokens: { archive: 'receipt' } },+ run,+ () => active,+ );+ expect(acquire).toHaveBeenCalledOnce();+ active = false; // runtime.stop destroys the caller before broker.stopAndWait.+ finish();+ expect(await request).toMatchObject({ ok: false });+ expect(run).not.toHaveBeenCalled();+ expect(release).toHaveBeenCalledOnce();+ expect(await slot.withNodeDownloads('p', {}, run, () => active)).toMatchObject({ ok: false });+ expect(run).not.toHaveBeenCalled();+ } finally {+ finish();+ acquire.mockRestore();+ }+});+it('shutdown drains cancelled downloads and rejects new downloads and Node handoffs', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'download-shutdown-')));+ let started!: () => void, finish!: () => void;+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const drained = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => 'anonymous',+ send() {},+ getGhost: () =>+ ({+ enabled: true,+ approval: {},+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ }) as unknown as InstalledGhost,+ download: async (options) => {+ started();+ await new Promise<void>((resolve) =>+ options.signal!.addEventListener('abort', () => resolve(), { once: true }),+ );+ await drained;+ throw Error('aborted');+ },+ });+ const request = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ const work = slot.handle('p', request);+ await ready;+ let stopped = false;+ const stop = slot.stopAndWait().then(() => {+ stopped = true;+ });+ await Promise.resolve();+ expect(stopped).toBe(false);+ expect(await slot.handle('p', { ...request, id: 'later' })).toMatchObject({ ok: false });+ expect(+ await slot.withNodeDownloads('p', {}, async () => {+ throw Error('must not run');+ }),+ ).toMatchObject({ ok: false });+ finish();+ await stop;+ await work;+ await slot.removePlugin('p');+ await expect(fs.stat(path.join(root, 'p'))).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ finish();+ await fs.rm(root, { recursive: true, force: true });+ }+});+it('restricts redirects, rejects arbitrary paths and isolates owner delivery', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));+ let scope = 'a';+ const events: unknown[] = [];+ const ghost = {+ enabled: true,+ approval: { state: 'approved' },+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ let calls = 0;+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => scope,+ getGhost: () => ghost,+ send: (_, e) => events.push(e),+ download: async (o) => {+ calls++;- expect(() => o.validateUrl!('https://evil.invalid/file')).toThrow();- expect(() => o.validateUrl!('http://github.com/file')).toThrow();++ expect(o.isUrlAllowed!('https://evil.invalid/file')).toBe(false);++ expect(o.isUrlAllowed!('http://github.com/file')).toBe(false);++ expect(o.isUrlAllowed!('https://github.com/other')).toBe(true);++ expect(o.request).toBeTypeOf('function');+ o.onProgress?.({ loaded: 1, total: 2, percent: 50, speedBps: 1 });+ scope = 'b';+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },+ });+ const req = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ expect(await slot.handle('p', { ...req, targetPath: '/tmp/arbitrary' })).toMatchObject({+ ok: false,+ });+ expect(calls).toBe(0);+ expect(await slot.handle('p', req)).toMatchObject({ ok: false });+ expect(calls).toBe(1);+ expect(events.filter((x: any) => x.data.phase === 'completed')).toHaveLength(0);+ } finally {+ await fs.rm(root, { recursive: true, force: true });+ }+});+it('cancel drains the matching request before acknowledging an immediate same-id retry', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));+ const ghost = {+ enabled: true,+ approval: {},+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ let started!: () => void;+ const ready = new Promise<void>((r) => (started = r));+ let finish!: () => void;+ const cleanup = new Promise<void>((r) => (finish = r));+ let calls = 0;+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => 'a',+ getGhost: () => ghost,+ send: () => {},+ download: async (o) => {+ if (++calls === 1) {+ await new Promise<void>((resolve) => {+ started();+ o.signal!.addEventListener('abort', () => resolve());+ });+ await cleanup;+ throw Error('aborted');+ }+ await fs.writeFile(o.targetPath, 'ok');+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },+ });+ try {+ const request = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ const work = slot.handle('p', request);+ await ready;+ let acknowledged = false;+ const cancel = slot.handle('p', { kind: 'cancel', id: 'x' }).then(() => {+ acknowledged = true;+ });+ await Promise.resolve();+ expect(acknowledged).toBe(false);+ finish();+ await cancel;+ expect(await work).toMatchObject({ ok: false, message: '下载已取消' });+ expect(await slot.handle('p', request)).toMatchObject({ ok: true });+ expect(calls).toBe(2);+ } finally {+ finish();+ await fs.rm(root, { recursive: true, force: true });+ }+});++it('hands opaque receipts only to the owning Node call and preserves legacy params', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-receipt-test-')));+ const alias = root + '-alias';+ const outside = root + '-outside';+ await fs.symlink(root, alias, process.platform === 'win32' ? 'junction' : 'dir');+ let scope = 'a';+ const ghost = {+ enabled: true,+ approval: { revision: 'a' },+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(alias, id),+ scope: () => scope,+ getGhost: () => ghost,+ send: () => {},+ download: async (o) => {+ await fs.writeFile(o.targetPath, 'ok');+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },+ });+ const req = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ const result = (await slot.handle('p', req)) as { ok: boolean; token: string };+ expect(result.ok).toBe(true);+ expect(result).not.toHaveProperty('path');+ let called = 0;+ const run = async (payload: any) => {+ called++;+ expect(await fs.readFile(payload.params.downloads.archive, 'utf8')).toBe('ok');+ return { ok: true };+ };+ const payload = {+ type: 'node-request',+ method: 'unpack',+ downloadTokens: { archive: result.token },+ params: {},+ };+ expect(await slot.withNodeDownloads('other', payload, run)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(await slot.withNodeDownloads('p', payload, run)).toEqual({ ok: true });+ expect(called).toBe(1);+ expect(+ await slot.withNodeDownloads('p', { ...payload, params: { downloads: {} } }, run),+ ).toMatchObject({ ok: false });+ scope = 'b';+ expect(await slot.withNodeDownloads('p', payload, run)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ scope = 'a';+ ghost.approval = { ...ghost.approval, revision: 'b' } as InstalledGhost['approval'];+ expect(await slot.withNodeDownloads('p', payload, run)).toMatchObject({ ok: false });+ const legacy = { type: 'node-request', params: ['legacy'] };+ expect(await slot.withNodeDownloads('p', legacy, async (p) => p)).toBe(legacy);+ await slot.removePlugin('p');+ await expect(fs.stat(path.join(root, 'p'))).rejects.toMatchObject({ code: 'ENOENT' });+ scope = 'a';+ await fs.mkdir(outside);+ await fs.symlink(+ outside,+ path.join(root, 'p'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ expect(await slot.handle('p', req)).toMatchObject({ ok: false });+ } finally {+ await fs.unlink(alias);+ await fs.rm(root, { recursive: true, force: true });+ await fs.rm(outside, { recursive: true, force: true });+ }+});++++it('sends plugin downloads through the SSRF guard without credentials and stops for a revoked owner', async () => {++ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));++ let enabled = true;++ const ghost = {++ get enabled() {++ return enabled;++ },++ approval: {},++ manifest: { node: {}, network: { hosts: ['github.com'] } },++ } as unknown as InstalledGhost;++ const release = vi.fn(async () => {});++ const dispatchChecks: Array<() => void> = [];++ guarded.fetch.mockReset().mockImplementation(async (_url: string, _init: RequestInit, check: () => void) => {++ dispatchChecks.push(check);++ check();++ return { response: new Response('ok'), release };++ });++ const slot = new PluginDownloadSlot({++ root: (id) => path.join(root, id),++ scope: () => 'a',++ getGhost: () => ghost,++ send: () => {},++ download: async (o) => {++ const init = { method: 'GET', redirect: 'manual' as const };++ const sent = await o.request!('https://github.com/file', init);++ expect(sent).toMatchObject({ release });++ expect(guarded.fetch).toHaveBeenCalledWith(++ 'https://github.com/file',++ { ...init, credentials: 'omit' },++ expect.any(Function),++ );++ enabled = false;++ // Owner revoked between DNS resolution and dispatch: final, not a retryable NETWORK error.++ expect(() => dispatchChecks[0]()).toThrow(expect.objectContaining({ code: 'URL_POLICY' }));++ throw new Error('stop');++ },++ });++ try {++ expect(++ await slot.handle('p', {++ kind: 'start',++ id: 'g',++ url: 'https://github.com/file',++ sha256: 'a'.repeat(64),++ bytes: 2,++ }),++ ).toMatchObject({ ok: false });++ expect(guarded.fetch).toHaveBeenCalledOnce();++ } finally {++ await fs.rm(root, { recursive: true, force: true });++ }++});diff --cc apps/desktop/src/main/cindy-brain/downloadSlot.tsindex 22fd8bcc6d,0000000000..0d09abaa76mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/downloadSlot.ts+++ b/apps/desktop/src/main/cindy-brain/downloadSlot.ts@@@ -1,278 -1,0 +1,297 @@@+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { ghostNetworkHostMatches, type InstalledGhost } from '../../shared/ghost.js';- import type { DownloadOptions, DownloadResult } from '../downloader/index.js';++import type { DownloadOptions, DownloadRequest, DownloadResult } from '../downloader/index.js';++import { DownloadError } from '../downloader/types.js';++import { guardedOutboundFetch } from '../maker-host/outbound-fetch.js';+import { PluginDownloadCache } from './downloadCache.js';++/** Verified public artifacts, in the requesting plugin's host-managed cache only. */+export interface PluginDownloadDeps {+ getGhost(id: string): InstalledGhost | null;+ root(id: string): string;+ scope(): string;+ send(id: string, event: unknown): void;+ download(options: DownloadOptions): Promise<DownloadResult>;+}+export class PluginDownloadSlot {+ private stopped = false;+ private cache = new PluginDownloadCache();+ private active = new Map<+ string,+ { controller: AbortController; promise: Promise<unknown>; fingerprint: string }+ >();+ constructor(private deps: PluginDownloadDeps) {}+ abortAll() {+ this.cache.revokeAll();+ for (const item of this.active.values()) item.controller.abort();+ }+ async stopAndWait() {+ this.stopped = true;+ this.abortAll();+ await Promise.allSettled([...this.active.values()].map((item) => item.promise));+ }+ async removePlugin(id: string, root = this.deps.root(id), scope = this.deps.scope()) {+ const work = [...this.active].filter(([key]) => {+ const parts = JSON.parse(key);+ return parts[0] === scope && parts[1] === id;+ });+ for (const [, item] of work) item.controller.abort();+ await Promise.allSettled(work.map(([, item]) => item.promise));+ try {+ const parent = await fs.realpath(path.dirname(root));+ await this.cache.removePlugin(path.join(parent, path.basename(root)));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+ async withNodeDownloads(+ id: string,+ payload: Record<string, unknown>,+ run: (payload: unknown) => Promise<unknown>,+ callerActive: () => boolean = () => true,+ ) {+ if (this.stopped || !callerActive())+ return { ok: false, errorCode: 'INVALID_REQUEST', message: '下载服务已停止' };+ if (payload.downloadTokens === undefined) return run(payload);+ const releases: Array<() => void> = [];+ try {+ const tokens = payload.downloadTokens;+ if (+ !tokens ||+ typeof tokens !== 'object' ||+ Array.isArray(tokens) ||+ Object.keys(tokens).length > 32+ )+ throw Error('Invalid download receipts');+ if (+ payload.params !== undefined &&+ (!payload.params ||+ typeof payload.params !== 'object' ||+ Array.isArray(payload.params) ||+ Object.hasOwn(payload.params, 'downloads'))+ )+ throw Error('Invalid download params');+ const scope = this.deps.scope(),+ ghost = this.deps.getGhost(id);+ if (!ghost?.enabled || !ghost.manifest.node) throw Error('Plugin unavailable');+ const approval = JSON.stringify(ghost.approval);+ const downloads: Record<string, string> = {};+ for (const [name, token] of Object.entries(tokens)) {+ if (+ !/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/.test(name) ||+ ['constructor', 'prototype', '__proto__'].includes(name) ||+ typeof token !== 'string'+ )+ throw Error('Invalid download receipt');+ const lease = await this.cache.acquire(token, scope, id, approval);+ releases.push(lease.release);+ downloads[name] = lease.path;+ }+ if (+ this.stopped ||+ !callerActive() ||+ this.deps.scope() !== scope ||+ !this.deps.getGhost(id)?.enabled ||+ JSON.stringify(this.deps.getGhost(id)?.approval) !== approval+ )+ throw Error('Plugin changed');+ const { downloadTokens: _tokens, ...request } = payload;+ return await run({+ ...request,+ params: { ...((payload.params as object) ?? {}), downloads },+ });+ } catch {+ return {+ ok: false,+ errorCode: 'INVALID_REQUEST',+ message: '下载凭据已失效,请重新获取文件后重试',+ };+ } finally {+ for (const release of releases) release();+ }+ }+ async handle(+ id: string,+ value: unknown,+ callerActive: () => boolean = () => true,+ ): Promise<unknown> {+ try {+ if (this.stopped) throw Error('Download service stopped');+ if (!value || typeof value !== 'object') throw Error('Invalid download request');+ const p = value as Record<string, unknown>;+ if (typeof p.id !== 'string' || !/^[\w-]{1,100}$/.test(p.id))+ throw Error('Invalid download id');+ const scope = this.deps.scope(),+ key = JSON.stringify([scope, id, p.id]);+ if (p.kind === 'cancel') {+ const item = this.active.get(key);+ item?.controller.abort();+ await item?.promise;+ return { ok: true };+ }+ if (+ p.kind !== 'start' ||+ Object.keys(p).some((k) => !['type', 'kind', 'id', 'url', 'sha256', 'bytes'].includes(k))+ )+ throw Error('Invalid download request');+ if (+ typeof p.url !== 'string' ||+ p.url.length > 8192 ||+ typeof p.sha256 !== 'string' ||+ !/^[a-f0-9]{64}$/.test(p.sha256) ||+ !Number.isSafeInteger(p.bytes) ||+ (p.bytes as number) < 1 ||+ (p.bytes as number) > 2 ** 31+ )+ throw Error('URL, SHA-256 and exact size (up to 2 GiB) are required');+ const ghost = this.deps.getGhost(id);+ if (!ghost?.enabled || !ghost.manifest.node || !ghost.manifest.network?.hosts.length)+ throw Error('Download requires node and network.hosts declarations');+ const approval = JSON.stringify(ghost.approval);+ const current = () =>+ !this.stopped &&+ callerActive() &&+ this.deps.scope() === scope &&+ this.deps.getGhost(id)?.enabled === true &&+ JSON.stringify(this.deps.getGhost(id)?.approval) === approval;+ const validateUrl = (raw: string) => {+ if (!current()) throw Error('Download owner or plugin changed');+ const u = new URL(raw);+ if (+ raw.length > 8192 ||+ /[\u0000-\u0020\u007f]/.test(raw) ||+ u.protocol !== 'https:' ||+ u.port ||+ u.username ||+ u.password ||+ !ghost.manifest.network!.hosts.some((h) => ghostNetworkHostMatches(h, u.hostname))+ )+ throw Error('Download URL is outside declared HTTPS hosts');+ };+ validateUrl(p.url);++ const isUrlAllowed = (raw: string) => {++ try {++ validateUrl(raw);++ return true;++ } catch {++ return false;++ }++ };+ const fingerprint = JSON.stringify([p.url, p.sha256, p.bytes]);+ const existing = this.active.get(key);+ if (existing) {+ if (existing.fingerprint !== fingerprint) throw Error('Download id already in use');+ return existing.promise;+ }+ if (this.active.size >= 8) throw Error('Too many active downloads');+ const controller = new AbortController();+ const emit = (data: Record<string, unknown>) => {+ if (current())+ this.deps.send(id, {+ type: 'event',+ name: 'download-progress',+ data: { id: p.id, ...data },+ });+ };+ const promise = (async () => {+ // Distinct operations cannot share the first caller's signal or progress callback.+ const suppliedRoot = this.deps.root(id);+ // Host-selected ancestors may use aliases (e.g. /var on macOS). Resolve+ // only that trusted parent; plugin/artifact entries still reject symlinks.+ await fs.mkdir(path.dirname(suppliedRoot), { recursive: true });+ const root = path.join(+ await fs.realpath(path.dirname(suppliedRoot)),+ path.basename(suppliedRoot),+ ),+ dir = path.join(+ root,+ createHash('sha256')+ .update(JSON.stringify([scope, p.id, fingerprint]))+ .digest('hex'),+ );+ await this.cache.reserve(path.dirname(root), dir, p.bytes as number);+ try {+ if ((await fs.realpath(dir)) !== path.resolve(dir))+ throw Error('Download cache must not contain symbolic links');+ const targetPath = path.join(dir, 'artifact');+ for (const file of [targetPath, targetPath + '.part', targetPath + '.meta.json']) {+ try {+ if (!(await fs.lstat(file)).isFile()) throw Error('Unsafe download cache entry');+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;+ }+ }+ if (!current() || controller.signal.aborted) throw Error('Download cancelled');+ emit({ phase: 'queued', loaded: 0, total: p.bytes, speedBps: 0 });+ const watch = setInterval(() => {+ if (!current()) controller.abort();+ }, 250);++ // Plugin-supplied URLs: one SSRF-guarded hop at a time (DNS pinning, HTTPS only,++ // no ambient cookies), re-checking the owner before every connection.++ const request: DownloadRequest = (url, init) =>++ guardedOutboundFetch(url, { ...init, credentials: 'omit' }, () => {++ controller.signal.throwIfAborted();++ // A revoked owner is final: do not let the downloader retry this hop.++ if (!isUrlAllowed(url))++ throw new DownloadError('URL_POLICY', 'Download URL is not allowed');++ });+ try {+ const result = await this.deps.download({- streaming: true,+ url: p.url as string,+ targetPath,+ sha256: p.sha256 as string,+ expectedSize: p.bytes as number,+ maxBytes: p.bytes as number,- validateUrl,++ isUrlAllowed,++ request,+ signal: controller.signal,+ logger: { debug() {}, info() {}, warn() {}, error() {} },+ onProgress: (e) => emit({ phase: 'downloading', ...e }),+ onVerifying: () =>+ emit({ phase: 'verifying', loaded: p.bytes, total: p.bytes, speedBps: 0 }),+ onRetry: (e) => emit({ phase: 'retrying', attempt: e.attempt, delayMs: e.delayMs }),+ });+ if (!current() || controller.signal.aborted) throw Error('Download cancelled');+ if (result.size !== p.bytes) throw Error('Downloaded size mismatch');+ const token = await this.cache.issue(dir, scope, id, approval);+ if (!current() || controller.signal.aborted) throw Error('Plugin changed');+ emit({+ phase: 'completed',+ loaded: result.size,+ total: result.size,+ speedBps: 0,+ fromCache: result.fromCache,+ });+ return {+ ok: true,+ token,+ bytes: result.size,+ sha256: result.sha256,+ fromCache: result.fromCache,+ };+ } finally {+ clearInterval(watch);+ }+ } finally {+ this.cache.release(dir);+ }+ })()+ .catch(() => {+ emit({ phase: controller.signal.aborted ? 'cancelled' : 'failed' });+ return {+ ok: false,+ message: controller.signal.aborted+ ? '下载已取消'+ : '下载失败,请重试(网络、权限或文件校验未通过)',+ };+ })+ .finally(() => this.active.delete(key));+ this.active.set(key, { controller, promise, fingerprint });+ return promise;+ } catch (e) {+ return { ok: false, message: (e as Error).message };+ }+ }+}diff --cc apps/desktop/src/main/downloader/__tests__/requestInjection.test.tsindex 0000000000,0000000000..be59e8f1f2new file mode 100644--- /dev/null+++ b/apps/desktop/src/main/downloader/__tests__/requestInjection.test.ts@@@ -1,0 -1,0 +1,299 @@@++import fs from 'node:fs';++import fsp from 'node:fs/promises';++import os from 'node:os';++import path from 'node:path';++import { createHash } from 'node:crypto';++import { PassThrough, addAbortSignal } from 'node:stream';++import { afterEach, expect, it, vi } from 'vitest';++++// Callers that inject `request` (plugin downloads use the SSRF-guarded fetch) must never++// fall back to Electron net.++const electron = vi.hoisted(() => ({ requestResponse: vi.fn() }));++vi.mock('../http', () => electron);++++import { executeOnce } from '../transport';++import { withRetry } from '../retry';++import { DownloadError, type DownloadOptions } from '../types';++import { readMeta, writeMeta } from '../resume';++++const BODY = 'abcdef';++const roots: string[] = [];++const release = vi.fn(async () => {});++const send = vi.fn();++++afterEach(async () => {++ vi.restoreAllMocks();++ send.mockReset();++ release.mockClear();++ expect(electron.requestResponse).not.toHaveBeenCalled();++ for (const root of roots.splice(0)) await fsp.rm(root, { recursive: true, force: true });++});++++function options(extra: Partial<DownloadOptions> = {}): DownloadOptions {++ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'download-request-test-'));++ roots.push(root);++ return {++ url: 'https://example.invalid/file',++ targetPath: path.join(root, 'artifact'),++ expectedSize: BODY.length,++ maxBytes: BODY.length,++ sha256: createHash('sha256').update(BODY).digest('hex'),++ request: async (url, init) => ({ response: await send(url, init), release }),++ ...extra,++ };++}++const execute = (opts: DownloadOptions) => executeOnce({ opts, logger: {}, resumedFromBytes: 0 });++const retrying = (opts: DownloadOptions, onRetry = vi.fn()) =>++ withRetry(() => execute(opts), {++ logger: {},++ onRetry,++ config: { baseDelayMs: 0, maxDelayMs: 0 },++ });++const resumed = (body: string) =>++ new Response(body, {++ status: 206,++ headers: {++ 'content-range': `bytes ${BODY.length - body.length}-${BODY.length - 1}/${BODY.length}`,++ 'content-length': String(body.length),++ },++ });++function partial(opts: DownloadOptions, body = 'abc', etag: string | null = 'v1') {++ fs.writeFileSync(`${opts.targetPath}.part`, body);++ writeMeta(opts.targetPath, {++ url: opts.url,++ expectedSize: opts.expectedSize ?? null,++ expectedSha256: opts.sha256,++ downloadedBytes: body.length,++ etag,++ lastModified: null,++ createdAt: '',++ updatedAt: '',++ });++}++++it('routes every hop through the injected request, validating and releasing each one', async () => {++ const urls: string[] = [];++ const opts = options({ isUrlAllowed: (u) => urls.push(u) > 0 });++ send++ .mockResolvedValueOnce(++ new Response(null, { status: 302, headers: { location: 'https://cdn.invalid/file' } }),++ )++ .mockResolvedValueOnce(new Response(BODY));++ await expect(execute(opts)).resolves.toMatchObject({ size: BODY.length });++ expect(send.mock.calls.map(([url]) => url)).toEqual([opts.url, 'https://cdn.invalid/file']);++ for (const [, init] of send.mock.calls) expect(init).toMatchObject({ redirect: 'manual' });++ // The entry URL is checked before the attempt and again at the first hop.++ expect(urls).toEqual([opts.url, opts.url, 'https://cdn.invalid/file']);++ expect(release).toHaveBeenCalledTimes(2);++ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe(BODY);++});++++it('treats a refusal from the injected request as final instead of retrying it', async () => {++ const onRetry = vi.fn();++ const opts = options({++ request: async () => {++ throw new DownloadError('URL_POLICY', 'caller revoked');++ },++ });++ await expect(retrying(opts, onRetry)).rejects.toMatchObject({ code: 'URL_POLICY' });++ expect(onRetry).not.toHaveBeenCalled();++ expect(fs.existsSync(`${opts.targetPath}.part`)).toBe(false);++});++++it('rejects a forbidden redirect before requesting it, without retrying the original URL', async () => {++ const onRetry = vi.fn();++ const opts = options({ isUrlAllowed: (u) => u.startsWith('https://example.invalid/') });++ send.mockResolvedValue(++ new Response(null, { status: 302, headers: { location: 'http://127.0.0.1/private' } }),++ );++ await expect(retrying(opts, onRetry)).rejects.toMatchObject({ code: 'URL_POLICY' });++ expect(send).toHaveBeenCalledTimes(1);++ expect(onRetry).not.toHaveBeenCalled();++});++++it('still retries a transient failure of the injected request', async () => {++ const onRetry = vi.fn();++ send.mockRejectedValueOnce(new Error('connection reset')).mockResolvedValueOnce(new Response(BODY));++ await expect(retrying(options(), onRetry)).resolves.toMatchObject({ size: BODY.length });++ expect(send).toHaveBeenCalledTimes(2);++ expect(onRetry).toHaveBeenCalledTimes(1);++});++++it('cancellation while waiting for data releases the request and publishes nothing', async () => {++ const abort = new AbortController();++ const opts = options({ signal: abort.signal });++ send.mockImplementation(++ async (_url, init: RequestInit) =>++ new Response(++ new ReadableStream({++ start(c) {++ init.signal!.addEventListener('abort', () => c.error(new Error('aborted')), {++ once: true,++ });++ },++ }),++ ),++ );++ const work = execute(opts);++ const rejected = expect(work).rejects.toMatchObject({ code: 'ABORTED' });++ await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1));++ abort.abort();++ await rejected;++ expect(release).toHaveBeenCalledOnce();++ expect(fs.existsSync(opts.targetPath)).toBe(false);++});++++it('cancelling a resumed prefix hash releases the response before settling', async () => {++ const abort = new AbortController();++ const opts = options({ signal: abort.signal });++ partial(opts);++ let entered!: () => void;++ const ready = new Promise<void>((resolve) => (entered = resolve));++ const stream = new PassThrough();++ vi.spyOn(fs, 'createReadStream').mockImplementation(((++ _path: unknown,++ config: { signal: AbortSignal },++ ) => {++ addAbortSignal(config.signal, stream);++ entered();++ return stream;++ }) as never);++ send.mockResolvedValue(resumed('def'));++ const rejected = expect(execute(opts)).rejects.toMatchObject({ code: 'ABORTED' });++ await ready;++ abort.abort();++ await rejected;++ expect(stream.destroyed).toBe(true);++ expect(release).toHaveBeenCalledOnce();++ expect(fs.existsSync(opts.targetPath)).toBe(false);++});++++it.each([++ ['network', 'NETWORK'],++ ['cancel', 'ABORTED'],++ ['timeout', 'TIMEOUT'],++] as const)('keeps the written prefix after a mid-body %s and resumes from it', async (failure, code) => {++ const abort = new AbortController();++ const opts = options({ signal: abort.signal, timeout: { idleMs: 20 } });++ let pulls = 0;++ send.mockImplementationOnce(++ async (_url, init: RequestInit) =>++ new Response(++ new ReadableStream(++ {++ pull(c) {++ if (++pulls === 1) return c.enqueue(Buffer.from('abc'));++ if (failure === 'network') return c.error(new Error('connection reset'));++ init.signal!.addEventListener('abort', () => c.error(new Error('aborted')), {++ once: true,++ });++ if (failure === 'cancel') abort.abort();++ },++ },++ { highWaterMark: 0 },++ ),++ { headers: { etag: 'v1' } },++ ),++ );++ await expect(execute(opts)).rejects.toMatchObject({ code });++ expect(fs.readFileSync(`${opts.targetPath}.part`, 'utf8')).toBe('abc');++ expect(readMeta(opts.targetPath)?.downloadedBytes).toBe(3);++ send.mockResolvedValueOnce(resumed('def'));++ await expect(execute({ ...opts, signal: undefined })).resolves.toMatchObject({ size: 6 });++ expect(send.mock.calls[1][1].headers).toMatchObject({ Range: 'bytes=3-', 'If-Range': 'v1' });++ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe(BODY);++ expect(readMeta(opts.targetPath)).toBeNull();++});++++it('discards both sidecars for short or oversized bodies, then downloads fresh', async () => {++ const opts = options();++ for (const body of ['abc', 'abcdefg']) {++ send.mockResolvedValueOnce(new Response(body));++ await expect(execute(opts)).rejects.toMatchObject({ code: 'SIZE' });++ for (const file of [opts.targetPath, `${opts.targetPath}.part`, `${opts.targetPath}.meta.json`])++ expect(fs.existsSync(file)).toBe(false);++ }++ send.mockResolvedValueOnce(new Response(BODY));++ await expect(execute(opts)).resolves.toMatchObject({ size: BODY.length });++ expect(send.mock.calls[2][1].headers).not.toHaveProperty('Range');++});++++it('reports verification once, only after every byte arrived', async () => {++ const onVerifying = vi.fn();++ send.mockResolvedValueOnce(new Response('abc'));++ await expect(execute(options({ onVerifying }))).rejects.toMatchObject({ code: 'SIZE' });++ expect(onVerifying).not.toHaveBeenCalled();++ const opts = options();++ const written: number[] = [];++ onVerifying.mockImplementation(() => written.push(fs.statSync(`${opts.targetPath}.part`).size));++ send.mockResolvedValueOnce(new Response(BODY));++ await expect(execute({ ...opts, onVerifying })).resolves.toMatchObject({ size: 6 });++ expect(written).toEqual([BODY.length]);++});++++it('does not pull another chunk while a disk write is pending', async () => {++ let pulls = 0;++ let unblock!: () => void;++ let started!: () => void;++ const writing = new Promise<void>((r) => (started = r));++ const gate = new Promise<void>((r) => (unblock = r));++ const open = fs.promises.open.bind(fs.promises);++ vi.spyOn(fs.promises, 'open').mockImplementation(async (...args: Parameters<typeof open>) => {++ const handle = await open(...args);++ const write = handle.writeFile.bind(handle);++ let first = true;++ vi.spyOn(handle, 'writeFile').mockImplementation(async (...data: Parameters<typeof write>) => {++ if (first) {++ first = false;++ started();++ await gate;++ }++ return write(...data);++ });++ return handle;++ });++ send.mockResolvedValue(++ new Response(++ new ReadableStream(++ {++ pull(c) {++ pulls++;++ if (pulls === 1) c.enqueue(Buffer.from('abc'));++ else if (pulls === 2) c.enqueue(Buffer.from('def'));++ else c.close();++ },++ },++ { highWaterMark: 0 },++ ),++ ),++ );++ const work = execute(options());++ await writing;++ try {++ expect(pulls).toBe(1);++ } finally {++ unblock();++ }++ await expect(work).resolves.toMatchObject({ size: BODY.length });++});++++it('does not persist oversized resume validators from the server', async () => {++ const opts = options();++ let pulls = 0;++ send.mockResolvedValueOnce(++ new Response(++ new ReadableStream(++ {++ pull(c) {++ if (++pulls === 1) c.enqueue(Buffer.from('abc'));++ else c.error(new Error('connection reset'));++ },++ },++ { highWaterMark: 0 },++ ),++ { headers: { etag: `"${'x'.repeat(2000)}"`, 'last-modified': 'y'.repeat(300) } },++ ),++ );++ await expect(execute(opts)).rejects.toMatchObject({ code: 'NETWORK' });++ expect(readMeta(opts.targetPath)).toMatchObject({ downloadedBytes: 3, etag: null, lastModified: null });++});diff --cc apps/desktop/src/main/downloader/__tests__/scheduler.test.tsindex db00fc605d,ba3fa34db0..6cee5b9d3d--- a/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts+++ b/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts@@@ -15,8 -18,10 +18,11 @@@ vi.mock('../../logger', () => (}));import { Scheduler } from '../scheduler';+import { createDownloader, download } from '../index';+ let root: string;+ afterEach(() => fs.rmSync(root, { recursive: true, force: true }));+const HASH_A = 'a'.repeat(64);const HASH_B = 'b'.repeat(64);@@@ -80,32 -106,27 +128,56 @@@ describe('downloader scheduler queued creleaseFirst();await expect(first).resolves.toMatchObject({ sha256: HASH_A });});+ it('holds its slot during cache hashing and starts the queue after a cache hit', async () => {+ const scheduler = new Scheduler({ maxConcurrent: 1 });+ const cached = path.join(root, 'cached');+ fs.writeFileSync(cached, 'cached');+ let finishHash!: (hash: string) => void;+ mocks.computeHash.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishHash = resolve;+ }),+ );+ mocks.executeOnce.mockResolvedValue({ size: 1, sha256: HASH_B });+ const first = scheduler.enqueue(options('https://first.invalid', cached, HASH_A));+ const second = scheduler.enqueue(+ options('https://second.invalid', path.join(root, 'next'), HASH_B),+ );+ expect(mocks.executeOnce).not.toHaveBeenCalled();+ expect(scheduler.listActive()).toHaveLength(1);+ finishHash(HASH_A);+ await expect(first).resolves.toMatchObject({ fromCache: true });+ await expect(second).resolves.toMatchObject({ sha256: HASH_B });+ expect(scheduler.listActive()).toEqual([]);+ });});++it('cancels the scheduler cache hash without entering transport or retry', async () => {+ const abort = new AbortController();+ let entered!: () => void;+ const ready = new Promise<void>((resolve) => {+ entered = resolve;+ });+ mocks.computeHash.mockImplementation(+ (_path, signal: AbortSignal) =>+ new Promise((_resolve, reject) => {- expect(signal).toBe(abort.signal);++ // The scheduler hashes under its own active-budget signal, linked to the caller's.++ expect(signal.aborted).toBe(false);+ signal.addEventListener('abort', () => reject(new Error('cancelled')), { once: true });+ entered();+ }),+ );+ mocks.withRetry.mockClear();+ mocks.executeOnce.mockClear();+ const scheduler = new Scheduler({ maxConcurrent: 1 });+ const result = scheduler.enqueue(+ options('https://example.invalid/cache', __filename, HASH_A, abort.signal),+ );+ const rejected = expect(result).rejects.toMatchObject({ code: 'ABORTED' });+ await ready;+ abort.abort();+ await rejected;+ expect(mocks.withRetry).not.toHaveBeenCalled();+ expect(mocks.executeOnce).not.toHaveBeenCalled();+});diff --cc apps/desktop/src/main/downloader/index.tsindex c460ea2714,e662d41a41..cea82c716c--- a/apps/desktop/src/main/downloader/index.ts+++ b/apps/desktop/src/main/downloader/index.ts@@@ -38,17 -34,20 +34,31 @@@ function validate(opts: DownloadOptionsif (typeof opts?.sha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(opts.sha256)) {throw new DownloadError('INVALID_ARG', 'sha256 must be 64-char hex');}+ for (const value of [opts.expectedSize, opts.maxBytes]) {+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {+ throw new DownloadError('INVALID_ARG', 'Download size must be a nonnegative integer');+ }+ }+ if ((opts.expectedSize ?? 0) > (opts.maxBytes ?? Infinity)) {+ throw new DownloadError('SIZE', 'Expected download exceeds allowed size');+ }+ for (const value of Object.values(opts.timeout ?? {})) {+ if (!Number.isSafeInteger(value) || value <= 0)+ throw new DownloadError('INVALID_ARG', 'Invalid download timeout');+ }+ }+++function normalize(opts: DownloadOptions): DownloadOptions {++ validate(opts);++ return { ...opts, targetPath: path.resolve(opts.targetPath), sha256: opts.sha256.toLowerCase() };+}++/** A consumer-owned queue; bulk plugin downloads never queue ahead of app updates. */+export function createDownloader() {+ const scheduler = new Scheduler({ maxConcurrent: 1 });- return (opts: DownloadOptions): Promise<DownloadResult> => {- validate(opts);- return scheduler.enqueue({ ...opts, sha256: opts.sha256.toLowerCase() });- };++ return (opts: DownloadOptions): Promise<DownloadResult> => scheduler.enqueue(normalize(opts));+}+/*** Download a file with single-flight dedupe, resume, retry, and SHA256 verify.*@@@ -56,8 -55,13 +66,7 @@@* resolves only after the file is at `targetPath` and verified.*/export function download(opts: DownloadOptions): Promise<DownloadResult> {-- validate(opts);- return getScheduler().enqueue({ ...opts, sha256: opts.sha256.toLowerCase() });- const normalized = {- ...opts,- targetPath: path.resolve(opts.targetPath),- sha256: opts.sha256.toLowerCase(),- };- return getScheduler().enqueue(normalized);++ return getScheduler().enqueue(normalize(opts));}/**@@@ -92,5 -94,5 +99,6 @@@ export typeRetryConfig,TimeoutConfig,Logger,++ DownloadRequest,} from './types';export { DownloadError } from './types';diff --cc apps/desktop/src/main/downloader/transport.tsindex b712b87031,c855a0769f..1b7df400e4--- a/apps/desktop/src/main/downloader/transport.ts+++ b/apps/desktop/src/main/downloader/transport.ts@@@ -1,27 -1,9 +1,9 @@@- /**- * unified-downloader — M2: HTTP transport + resumable download.- * ---------------------------------------------------------------------------- * This module owns one resumable HTTP attempt; retry policy lives in retry.ts.- *- * Single-attempt execution. The retry/backoff loop lives in retry.ts. This- * file is responsible for ONE network round-trip:- * - Decide resume vs fresh based on .meta.json + .part.- * - Send GET (with Range + If-Range when resuming).- * - Stream chunks → write to .part, feed SHA256 hasher, advance progress.- * - On EOF: verify SHA256, rename .part → targetPath, delete .meta.json.- *- * Cleanup invariants on reject:- * - CHECKSUM → delete .part + .meta.json (corrupt, retry would loop).- * - HTTP_4XX → keep .part + .meta.json (caller may want to inspect).- * - NETWORK / HTTP_5XX → keep .part + .meta.json (resumable next time).- * - ABORTED → keep .part + .meta.json (caller asked to pause).- * - DISK → keep .part + .meta.json (caller decides; cleanup() exists).- */-- import { net } from 'electron';+ /** One HTTP attempt. Callers supply policy; queueing/retries live in scheduler.+ * Await disk writes to bound memory even for multi-gigabyte runtime archives. */+ import { requestResponse } from './http';import fs from 'node:fs';import path from 'node:path';- import { DownloadError, type DownloadOptions, type Logger, type TimeoutConfig } from './types';-import { DownloadError, type DownloadOptions, type Logger } from './types';++import { DownloadError, type DownloadOptions, type DownloadRequest, type Logger } from './types';import {partPath,readMeta,@@@ -51,368 -27,276 +27,301 @@@ export interface TransportResultsha256: string;}- /**- * Headers returned by Electron's net.request can be either a string or string[].- * We normalize via this helper.- */- function pickHeader(headers: Record<string, string | string[]>, key: string): string | null {- const v = headers[key.toLowerCase()];- if (v === undefined) return null;- return Array.isArray(v) ? (v[0] ?? null) : v;+ export function assertDownloadUrl(url: string, opts: DownloadOptions): void {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ throw new DownloadError('URL_POLICY', 'Invalid download URL');+ }+ if (+ !['http:', 'https:'].includes(parsed.protocol) ||+ parsed.username ||+ parsed.password ||+ (opts.isUrlAllowed && !opts.isUrlAllowed(url))+ ) {+ throw new DownloadError('URL_POLICY', 'Download URL is not allowed');+ }}- function parseContentLength(- headers: Record<string, string | string[]>,- status: number,- resumeOffset: number | null,- ): number | null {- // 206 Partial Content: prefer Content-Range total, else Content-Length + offset.- if (status === 206) {- const range = pickHeader(headers, 'content-range');- if (range !== null) {- const m = /\/(\d+)$/.exec(range);- if (m !== null) return Number(m[1]);- }- const cl = pickHeader(headers, 'content-length');- if (cl !== null && resumeOffset !== null) return Number(cl) + resumeOffset;- }- const cl = pickHeader(headers, 'content-length');- if (cl === null) return null;- return Number(cl);++const electronRequest: DownloadRequest = async (url, init) => ({++ response: await requestResponse(url, init),++});++++/** Resume validators come from the server; cap them before persisting or echoing back. */++function boundedHeader(response: Response, name: string, max: number): string | null {++ const value = response.headers.get(name);++ return value !== null && value.length <= max ? value : null;+}+export async function executeOnce(ctx: TransportContext): Promise<TransportResult> {- if (ctx.opts.streaming) return executeStreaming(ctx);- const { opts, logger } = ctx;- const timeout: TimeoutConfig = { ...DEFAULT_TIMEOUT, ...(opts.timeout ?? {}) };-- // ── Step 0: target file already exists & matches sha256 → fast path ──- // (Scheduler also short-circuits this; the duplicate check here protects- // against scheduler bypass paths and is cheap when the file is missing.)- if (fs.existsSync(opts.targetPath)) {+ const { opts } = ctx;+ const signal = ctx.signal ?? opts.signal;++ const send = opts.request ?? electronRequest;+ const controller = new AbortController();+ let timedOut = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let response: Response | undefined;++ let release: (() => Promise<void>) | undefined;+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;+ let file: fs.promises.FileHandle | undefined;+ let meta: MetaJson | undefined;+ let loaded = 0;+ let complete = false;+ let discard = opts.resume === false;+ const abort = () => controller.abort();+ const checkAbort = () => {+ if (controller.signal.aborted)+ throw new DownloadError(+ timedOut ? 'TIMEOUT' : 'ABORTED',+ timedOut ? 'Download timed out' : 'Download aborted',+ );+ };+ const armTimer = (ms: number) => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, ms);+ };+ const network = async <T>(operation: Promise<T>): Promise<T> => {try {- const existingHash = await computeHash(opts.targetPath);- if (existingHash === opts.sha256) {- return { size: fs.statSync(opts.targetPath).size, sha256: existingHash };- }- try { fs.unlinkSync(opts.targetPath); } catch { /* ignore */ }- } catch {- try { fs.unlinkSync(opts.targetPath); } catch { /* ignore */ }+ return await operation;- } catch {++ } catch (error) {+ checkAbort();++ // An injected request may refuse a hop deliberately (e.g. the owner was revoked++ // after DNS resolution); keep that decision instead of retrying it as NETWORK.++ if (error instanceof DownloadError) throw error;+ // Native errors may contain signed URLs. Never expose those to callers/logs.+ throw new DownloadError('NETWORK', 'Download network request failed');}- }-- // ── Step 1: decide resume vs fresh ──- const resumeOffset = decideResumeOffset(- opts.targetPath,- opts.url,- opts.expectedSize,- opts.sha256,- );- if (resumeOffset === null) {- deletePart(opts.targetPath);- deleteMeta(opts.targetPath);- } else {- ctx.resumedFromBytes = resumeOffset;- opts.onResume?.({ fromBytes: resumeOffset, totalBytes: opts.expectedSize ?? null });- }-- fs.mkdirSync(path.dirname(opts.targetPath), { recursive: true });-- // ── Step 2: build headers ──- const headers: Record<string, string> = {};- if (resumeOffset !== null) {- headers['Range'] = `bytes=${resumeOffset}-`;- const meta = readMeta(opts.targetPath);- if (meta?.etag) headers['If-Range'] = meta.etag;- else if (meta?.lastModified) headers['If-Range'] = meta.lastModified;- }-- // ── Step 3: HTTP request via Electron net (auto-respects system proxy) ──- return await new Promise<TransportResult>((resolve, reject) => {- opts.validateUrl?.(opts.url);- const request = net.request({ url: opts.url, method: 'GET', redirect: opts.validateUrl ? 'manual' : 'follow', ...(opts.validateUrl ? { useSessionCookies: false, credentials: 'omit' as const } : {}) });- Object.entries(headers).forEach(([k, v]) => request.setHeader(k, v));-- let connectTimer: ReturnType<typeof setTimeout> | null = null;- let idleTimer: ReturnType<typeof setTimeout> | null = null;- let settled = false;-- const cleanupTimers = (): void => {- if (connectTimer !== null) { clearTimeout(connectTimer); connectTimer = null; }- if (idleTimer !== null) { clearTimeout(idleTimer); idleTimer = null; }- };-- const safeReject = (err: DownloadError): void => {- if (settled) return;- settled = true;- cleanupTimers();- if (opts.signal !== undefined) opts.signal.removeEventListener('abort', onAbort);- reject(err);- };-- const safeResolve = (r: TransportResult): void => {- if (settled) return;- settled = true;- cleanupTimers();- if (opts.signal !== undefined) opts.signal.removeEventListener('abort', onAbort);- resolve(r);- };-- const onAbort = (): void => {- try { request.abort(); } catch { /* ignore */ }- // Keep .part + .meta — caller asked to pause.- safeReject(new DownloadError('ABORTED', 'download aborted by caller'));- };-- if (opts.signal !== undefined) {- if (opts.signal.aborted) {- onAbort();- return;- }- opts.signal.addEventListener('abort', onAbort, { once: true });+ };+ signal?.addEventListener('abort', abort, { once: true });+ if (signal?.aborted) abort();+ try {+ checkAbort();+ assertDownloadUrl(opts.url, opts);+ if (opts.existingTarget === 'error' && fs.existsSync(opts.targetPath)) {+ throw new DownloadError('EXISTS', 'Download target already exists');}-- connectTimer = setTimeout(() => {- try { request.abort(); } catch { /* ignore */ }- safeReject(new DownloadError('NETWORK', `connect timeout after ${timeout.connectMs}ms`));- }, timeout.connectMs);-- const resetIdleTimer = (): void => {- if (idleTimer !== null) clearTimeout(idleTimer);- idleTimer = setTimeout(() => {- try { request.abort(); } catch { /* ignore */ }- safeReject(new DownloadError('NETWORK', `idle timeout after ${timeout.idleMs}ms`));- }, timeout.idleMs);- };-- let redirectCount = 0;- if (opts.validateUrl) request.on('redirect', (_status, _method, redirectUrl) => {+ let offset =+ opts.resume === false+ ? null+ : decideResumeOffset(opts.targetPath, opts.url, opts.expectedSize, opts.sha256);+ if (+ offset !== null &&+ (offset >= (opts.expectedSize ?? Infinity) || offset > (opts.maxBytes ?? Infinity))+ )+ offset = null;+ if (offset === null) {+ deletePart(opts.targetPath);+ deleteMeta(opts.targetPath);+ }+ ctx.resumedFromBytes = offset ?? 0;+ loaded = offset ?? 0;+ await fs.promises.mkdir(path.dirname(opts.targetPath), { recursive: true });+ checkAbort();+ const headers: Record<string, string> = { 'Accept-Encoding': 'identity' };+ if (offset !== null) {+ headers.Range = `bytes=${offset}-`;+ const prior = readMeta(opts.targetPath);+ if (prior?.etag) headers['If-Range'] = prior.etag;+ else if (prior?.lastModified) headers['If-Range'] = prior.lastModified;+ }+ let url = opts.url;+ for (let hops = 0; ; hops++) {+ assertDownloadUrl(url, opts);+ armTimer(opts.timeout?.connectMs ?? 10_000);- response = await network(- requestResponse(url, {++ const sent = await network(++ send(url, {+ method: 'GET',+ cache: 'no-store',+ redirect: opts.redirect === 'error' ? 'error' : 'manual',+ headers,+ signal: controller.signal,+ }),+ );++ response = sent.response;++ release = sent.release;+ clearTimeout(timer);+ checkAbort();+ if (![301, 302, 303, 307, 308].includes(response.status)) break;+ const location = response.headers.get('location');+ await response.body?.cancel();+ response = undefined;++ await release?.();++ release = undefined;+ if (opts.redirect === 'error' || !location || hops >= 5) {+ throw new DownloadError('URL_POLICY', 'Download redirect is not allowed');+ }try {- if (++redirectCount > 5) throw new Error('Too many redirects');- opts.validateUrl!(redirectUrl);- request.followRedirect();+ url = new URL(location, url).href;} catch {- safeReject(new DownloadError('INVALID_ARG', 'Download redirect rejected'));- request.abort();+ throw new DownloadError('URL_POLICY', 'Invalid redirect URL');}- });- request.on('response', (response) => {- if (settled) return;-- if (connectTimer !== null) { clearTimeout(connectTimer); connectTimer = null; }-- const status = response.statusCode;- const responseHeaders = response.headers as Record<string, string | string[]>;-- // 4xx → permanent failure for this URL (not retried).- if (status >= 400 && status < 500) {- try { request.abort(); } catch { /* ignore */ }- safeReject(new DownloadError('HTTP_4XX', `HTTP ${status}`, undefined, status));- return;- }- // 5xx → transient; retry layer decides.- if (status >= 500) {- try { request.abort(); } catch { /* ignore */ }- safeReject(new DownloadError('HTTP_5XX', `HTTP ${status}`, undefined, status));- return;- }-- // We asked for Range but server returned full body → restart fresh next attempt.- if (resumeOffset !== null && status === 200) {- try { request.abort(); } catch { /* ignore */ }- deletePart(opts.targetPath);- deleteMeta(opts.targetPath);- safeReject(new DownloadError('NETWORK', 'server does not support Range, restarting'));- return;+ }+ if (response.status >= 500)+ throw new DownloadError('HTTP_5XX', `HTTP ${response.status}`, undefined, response.status);+ if (response.status >= 400) {+ if (response.status === 416 && offset !== null) {+ discard = true;+ throw new DownloadError('NETWORK', 'Invalid resume range; restarting');}-- const totalBytes = parseContentLength(responseHeaders, status, resumeOffset);- const etag = pickHeader(responseHeaders, 'etag');- const lastModified = pickHeader(responseHeaders, 'last-modified');-- // For fresh downloads, Content-Length must match expectedSize when both known.+ throw new DownloadError('HTTP_4XX', `HTTP ${response.status}`, undefined, response.status);+ }+ if (offset !== null && response.status === 200) {+ // Server ignored Range (or If-Range changed): use this full response fresh.+ offset = null;+ loaded = 0;+ ctx.resumedFromBytes = 0;+ deletePart(opts.targetPath);+ deleteMeta(opts.targetPath);+ }+ if (response.status !== (offset === null ? 200 : 206)) {+ discard = true;+ throw new DownloadError('NETWORK', 'Unexpected download response');+ }+ const lengthHeader = response.headers.get('content-length');+ const length = lengthHeader === null ? null : Number(lengthHeader);+ if (length !== null && (!Number.isSafeInteger(length) || length < 0))+ throw new DownloadError('SIZE', 'Invalid Content-Length');+ let total = length === null ? null : length + (offset ?? 0);+ if (offset !== null) {+ const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get('content-range') ?? '');if (- resumeOffset === null &&- opts.expectedSize !== undefined &&- totalBytes !== null &&- totalBytes !== opts.expectedSize+ !range ||+ Number(range[1]) !== offset ||+ Number(range[2]) < offset ||+ Number(range[2]) + 1 !== Number(range[3]) ||+ !Number.isSafeInteger(Number(range[3])) ||+ (length !== null && length !== Number(range[2]) - offset + 1)) {- try { request.abort(); } catch { /* ignore */ }- deletePart(opts.targetPath);- deleteMeta(opts.targetPath);- safeReject(- new DownloadError(- 'NETWORK',- `Content-Length ${totalBytes} != expectedSize ${opts.expectedSize}`,- ),- );- return;+ discard = true;+ throw new DownloadError('NETWORK', 'Invalid Content-Range; restarting');}-- // ── Open .part for append (resume) or truncate (fresh) ──- const isResume = resumeOffset !== null && status === 206;- const writeStream = fs.createWriteStream(partPath(opts.targetPath), {- flags: isResume ? 'a' : 'w',- });-- const tracker = new ProgressTracker({- initialLoaded: isResume ? resumeOffset : 0,- total: totalBytes,- onProgress: opts.onProgress,- });-- const hasher = createStreamingHasher(isResume ? partPath(opts.targetPath) : null);-- const meta: MetaJson = {- url: opts.url,- expectedSize: opts.expectedSize ?? totalBytes,- expectedSha256: opts.sha256,- downloadedBytes: tracker.getLoaded(),- etag,- lastModified,- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- };- try {- writeMeta(opts.targetPath, meta);- } catch (err) {- logger.warn?.('[downloader] writeMeta failed (non-fatal)', { err: (err as Error).message });+ total = Number(range[3]);+ opts.onResume?.({ fromBytes: offset, totalBytes: total });+ }+ if (+ (opts.expectedSize !== undefined && total !== null && total !== opts.expectedSize) ||+ (total !== null && total > (opts.maxBytes ?? Infinity))+ ) {+ throw new DownloadError('SIZE', 'Content-Length does not match the allowed size');+ }+ if (!response.body) throw new DownloadError('NETWORK', 'Download response body is empty');+ reader = response.body.getReader();+ const hasher = createStreamingHasher(+ offset === null ? null : partPath(opts.targetPath),+ controller.signal,+ );+ await hasher.update(Buffer.alloc(0));+ file = await fs.promises.open(partPath(opts.targetPath), offset === null ? 'w' : 'a', 0o600);+ const tracker = new ProgressTracker({+ initialLoaded: loaded,+ total: opts.expectedSize ?? total,+ onProgress: opts.onProgress,+ });+ meta = {+ url: opts.url,+ expectedSize: opts.expectedSize ?? total,+ expectedSha256: opts.sha256,+ downloadedBytes: loaded,- etag: response.headers.get('etag'),- lastModified: response.headers.get('last-modified'),++ etag: boundedHeader(response, 'etag', 1024),++ lastModified: boundedHeader(response, 'last-modified', 256),+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ };+ let lastMetaWriteAt = 0;+ armTimer(opts.timeout?.idleMs ?? 30_000);+ while (true) {+ checkAbort();+ const { done, value } = await network(reader.read());+ checkAbort();+ if (done) break;+ if (!value.byteLength) continue;+ if (+ loaded + value.byteLength >+ Math.min(opts.expectedSize ?? Infinity, opts.maxBytes ?? Infinity)+ ) {+ throw new DownloadError('SIZE', 'Download exceeds allowed size');}-- let lastMetaWriteAt = Date.now();-- writeStream.on('error', (err) => {- try { request.abort(); } catch { /* ignore */ }- safeReject(new DownloadError('DISK', `write stream failed: ${err.message}`, err));- });-- response.on('data', (chunk: Buffer) => {- if (settled) return;- if (opts.maxBytes !== undefined && tracker.getLoaded() + chunk.length > opts.maxBytes) {- safeReject(new DownloadError('INVALID_ARG', 'Download exceeds declared size'));- writeStream.destroy(); request.abort(); return;+ armTimer(opts.timeout?.idleMs ?? 30_000);+ await file.writeFile(value);+ await hasher.update(Buffer.from(value));+ loaded += value.byteLength;+ tracker.advance(value.byteLength);+ if (Date.now() - lastMetaWriteAt >= 2000) {+ try {+ writeMeta(opts.targetPath, {+ ...meta,+ downloadedBytes: loaded,+ updatedAt: new Date().toISOString(),+ });+ } catch {+ /* A failed checkpoint only disables resume, not the active transfer. */}- resetIdleTimer();- // 1. Persist to disk. Electron's IncomingMessage isn't a Node Readable- // stream (no pause/resume/destroy on it directly), so we can't apply- // Node-style backpressure here; we accept the buffer and let the- // fs.WriteStream queue it. For the tens-of-MB payloads we ship- // (app patch / claude bin), this stays well within the default- // highWaterMark budget.- writeStream.write(chunk);- // 2. Feed hasher (async because of priming, but we don't await here —- // the write order is preserved by hasher's internal `await primed`).- void hasher.update(chunk).catch((err: Error) => {- try { request.abort(); } catch { /* ignore */ }- try { writeStream.destroy(); } catch { /* ignore */ }- safeReject(new DownloadError('DISK', `hash update failed: ${err.message}`, err));- });- // 3. Advance progress.- tracker.advance(chunk.length);- // 4. Throttled meta update.- const now = Date.now();- if (now - lastMetaWriteAt > META_WRITE_INTERVAL_MS) {- lastMetaWriteAt = now;- try {- writeMeta(opts.targetPath, {- ...meta,- downloadedBytes: tracker.getLoaded(),- updatedAt: new Date().toISOString(),- });- } catch (err) {- logger.debug?.('[downloader] writeMeta tick failed', { err: (err as Error).message });- }+ lastMetaWriteAt = Date.now();+ }+ }+ clearTimeout(timer);+ if (loaded !== (opts.expectedSize ?? total ?? loaded))+ throw new DownloadError('SIZE', 'Download size mismatch');++ try {++ opts.onVerifying?.();++ } catch {++ /* observer only */++ }+ const sha256 = await hasher.digest();+ if (sha256 !== opts.sha256) throw new DownloadError('CHECKSUM', 'Download SHA-256 mismatch');+ await file.close();+ file = undefined;+ checkAbort();+ if (opts.existingTarget === 'error') {+ // Atomic no-clobber publication, even if another process created the target meanwhile.+ await fs.promises.link(partPath(opts.targetPath), opts.targetPath);+ deletePart(opts.targetPath);+ } else {+ await fs.promises.rename(partPath(opts.targetPath), opts.targetPath);+ }+ complete = true;+ deleteMeta(opts.targetPath);+ tracker.flush();+ return { size: loaded, sha256 };+ } catch (error) {+ checkAbort();+ const failure =+ error instanceof DownloadError+ ? error+ : new DownloadError(+ (error as NodeJS.ErrnoException).code === 'EEXIST' ? 'EXISTS' : 'DISK',+ 'Download file operation failed',+ );+ if (['SIZE', 'CHECKSUM', 'URL_POLICY'].includes(failure.code)) discard = true;+ throw failure;+ } finally {+ clearTimeout(timer);+ signal?.removeEventListener('abort', abort);+ if (!complete) controller.abort();+ await reader?.cancel().catch(() => undefined);+ reader?.releaseLock();+ if (!reader) await response?.body?.cancel().catch(() => undefined);+ await file?.close().catch(() => undefined);++ await release?.().catch(() => undefined);+ if (!complete) {+ if (discard) {+ deletePart(opts.targetPath);+ deleteMeta(opts.targetPath);+ } else if (meta) {+ try {+ writeMeta(opts.targetPath, {+ ...meta,+ downloadedBytes: loaded,+ updatedAt: new Date().toISOString(),+ });+ } catch {+ /* A failed checkpoint only disables resume. */}- });-- response.on('end', () => {- if (settled) { writeStream.destroy(); return; }- try { opts.onVerifying?.(); } catch { /* observer only */ }- // close the stream and finalize- writeStream.end(() => {- (async () => {- try {- const finalHash = await hasher.digest();- const finalSize = tracker.getLoaded();-- if (settled || opts.signal?.aborted) return;- if (opts.expectedSize !== undefined && finalSize !== opts.expectedSize) {- deletePart(opts.targetPath);- deleteMeta(opts.targetPath);- safeReject(new DownloadError('CHECKSUM', 'Downloaded size mismatch'));- return;- }- if (finalHash !== opts.sha256) {- // Corrupt body — wipe both .part and .meta so a future attempt- // starts truly fresh (CHECKSUM is not retried inside withRetry).- deletePart(opts.targetPath);- deleteMeta(opts.targetPath);- safeReject(- new DownloadError(- 'CHECKSUM',- `sha256 mismatch: got ${finalHash}, expected ${opts.sha256}`,- ),- );- return;- }-- // Good. Move .part into place and drop the sidecar.- try {- if (fs.existsSync(opts.targetPath)) fs.unlinkSync(opts.targetPath);- fs.renameSync(partPath(opts.targetPath), opts.targetPath);- } catch (err) {- safeReject(- new DownloadError(- 'DISK',- `rename .part failed: ${(err as Error).message}`,- err as Error,- ),- );- return;- }- deleteMeta(opts.targetPath);- tracker.flush();- safeResolve({ size: finalSize, sha256: finalHash });- } catch (err) {- safeReject(- new DownloadError(- 'DISK',- `finalize failed: ${(err as Error).message}`,- err as Error,- ),- );- }- })();- });- });-- response.on('error', (err: Error) => {- try { writeStream.destroy(); } catch { /* ignore */ }- safeReject(new DownloadError('NETWORK', `stream error: ${err.message}`, err));- });-- // Net response sometimes emits 'aborted' on socket reset rather than 'error'.- // Cast: Electron typings don't list 'aborted' but it's a real event.- (response as unknown as { on(ev: string, cb: () => void): void }).on('aborted', () => {- try { writeStream.destroy(); } catch { /* ignore */ }- if (settled) return;- safeReject(new DownloadError('NETWORK', 'response aborted mid-stream'));- });-- // Kick off the idle timer once the response stream begins.- resetIdleTimer();- });-- request.on('error', (err: Error) => {- safeReject(new DownloadError('NETWORK', `request error: ${err.message}`, err));- });-- // Guard: an abort that sneaks in before request.end() finished.- request.on('abort' as 'error', () => {- if (settled) return;- safeReject(new DownloadError('ABORTED', 'request aborted'));- });-- request.end();- });+ }+ }+ }}diff --cc apps/desktop/src/main/downloader/types.tsindex 73f783dbe0,f89886a284..122009b9e5--- a/apps/desktop/src/main/downloader/types.ts+++ b/apps/desktop/src/main/downloader/types.ts@@@ -25,12 -17,21 +17,29 @@@ export interface DownloadOptionssha256: string;/** Optional. When provided, Content-Length must match for fresh downloads. */expectedSize?: number;+ /** Reject before writing beyond this limit (also enforced for cache/resume). */+ maxBytes?: number;+ /** Defaults to follow. A predicate is checked before every redirect request. */+ redirect?: 'follow' | 'error';+ isUrlAllowed?: (url: string) => boolean;++ /**++ * Optional single-hop request implementation. Defaults to Electron net (system proxy).++ * Callers fetching untrusted URLs inject a guarded fetch (SSRF / DNS pinning). It must++ * not follow redirects: the transport validates every hop with `isUrlAllowed` first.++ */++ request?: DownloadRequest;+ /** Defaults to true. False discards partial data after failure/cancellation. */+ resume?: boolean;+ /** Defaults to replace. Exclusive publication never overwrites an existing file. */+ existingTarget?: 'replace' | 'error';/** Raw progress events (no clamping / no smoothing — caller-side concern). */onProgress?: (e: ProgressEvent) => void;/** Fired before each backoff sleep. Use for logging/telemetry. */onRetry?: (e: RetryEvent) => void;/** Fired once per attempt that resumes from a non-zero offset. */onResume?: (e: ResumeEvent) => void;++ /** Fired once all bytes of an attempt have arrived, before SHA-256 verification. */++ onVerifying?: () => void;/** Caller can abort the in-flight download (queued, executing, or backing off). */signal?: AbortSignal;/** Logger; falls back to console when omitted. */@@@ -41,6 -42,6 +50,12 @@@timeout?: Partial<TimeoutConfig>;}++/** One request without redirect following; `release` frees per-request resources. */++export type DownloadRequest = (++ url: string,++ init: RequestInit,++) => Promise<{ response: Response; release?: () => Promise<void> }>;++export interface DownloadResult {/** Final file path (== targetPath when resolve fires). */path: string;diff --cc apps/desktop/src/preload/preload.tsindex 2fcaae8c3c,9208af6f90..99ae166aa0--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@@ -5828,14 -5891,15 +5891,20 @@@ contextBridge.exposeInMainWorld('electrtaskId: string,): Promise<import('../shared/workflow-progress').WorkflowProgress | null> =>ipcRenderer.invoke('maker:get-workflow-progress', sessionId, taskId),+ readBackgroundTaskOutputTail: (+ sessionId: string,+ taskId: string,+ ): Promise<import('../shared/backgroundTaskOutput').BackgroundTaskOutputTailResult> =>+ ipcRenderer.invoke('maker:background-task:output-tail', sessionId, taskId),// 模型供应商目录(只读)—— 内置目录元数据 + 各供应商实时连接状态。- setProviderPresentation: (input: { providerId?: string; action: 'rename' | 'remove' | 'restore'; name?: string; dataOwnerId: string | null; ownerGeneration: number }): Promise<void> => ipcRenderer.invoke('maker:provider:presentation:set', input),+ setProviderPresentation: (input: {+ providerId?: string;+ action: 'rename' | 'remove' | 'restore';+ name?: string;+ dataOwnerId: string | null;+ ownerGeneration: number;+ }): Promise<void> => ipcRenderer.invoke('maker:provider:presentation:set', input),listProviders: (): Promise<{dataOwnerId: string | null;ownerGeneration: number;diff --cc docs/dev-rules/plugin-download-api.mdindex 1b48e90a91,0000000000..85251a6b53mode 100644,000000..100644--- a/docs/dev-rules/plugin-download-api.md+++ b/docs/dev-rules/plugin-download-api.md@@@ -1,28 -1,0 +1,31 @@@+# 插件文件下载接口++逻辑页使用 `cindy.downloads.start({id,url,sha256,bytes})`,取消使用+`cindy.downloads.cancel({id})`。返回结构为+`{ok:true,token,bytes,sha256,fromCache}` 或 `{ok:false,message}`。++插件必须声明 node 与 network.hosts;仅允许已声明 HTTPS 主机,重定向每跳重新检查。+本接口用于匿名公开文件,不携带 Cookie、账号凭证或自定义请求头;带授权请求继续使用 fetch 槽。+SHA-256 与精确字节数必填,单文件最大 2 GiB。目标由宿主管理,不接受本机目标路径。+面板不获得宿主路径。通过 `node.request({downloadTokens:{archive:token},params:{...}})`+交接给同插件 Node,Host 校验账号、插件、批准身份和文件身份后注入 `params.downloads.archive`。+携带凭据时 params 必须为对象且不得自带 downloads;旧请求不受影响。+路径仅在本次 RPC 生命周期内有效,Node 须在返回前完成读取或复制,不得回传或记录路径。+缓存由账号、插件、请求身份隔离;id 相同且内容相同可复用经校验的文件。+每账号总预算 4 GiB(含在途预留及每项 64 KiB 管理空间),按最近使用回收;下载中和 Node 借用中的文件不淘汰。+缓存满且没有可回收空间时失败。卸载回收该插件缓存;重启后凭据失效,可重新 start 取凭据。- 下载使用独立队列和逐块写盘,不占用宿主更新队列,支持重试/续传。++下载使用独立队列(`createDownloader()`),不占用宿主更新队列;传输复用统一下载器的逐块写盘++(写完一块才拉下一块)、重试与续传。插件提供的 URL 通过下载器的 `request` 注入点走++`guardedOutboundFetch`:单跳、DNS 固定、仅 HTTPS、不带 Cookie,每次连接前复核调用方与声明主机;++调用方失效属于终局拒绝(`URL_POLICY`),不按网络错误重试。++通过 onHostMessage 订阅:+`{type:'event',name:'download-progress',data:{id,phase,loaded,total,speedBps}}`。+phase 为 queued/downloading/verifying/retrying/completed/failed/cancelled。+retrying 附带 attempt、delayMs,completed 附带 fromCache。+校验、重试等阶段不保证具有 loaded/total;界面应使用不确定进度,不能伪造百分比。+下载完成仅表示文件校验完成,插件自己的解包/内容验证应另行展示。++账号切换、插件批准身份改变或调用逻辑页销毁后中止下载,不向新账号发送进度。+旧宿主不存在 downloads 对象时,应提示升级;不能假装已接入进度。+现有 fetch、Node、Library 接口不变,存量插件无须迁移。