Skip to content

A full-featured download manager.

fix(plugins): apply dedicated proxy scope to plugin networking (#2360)

Dr_rOotbf401a60ee58
diff --git a/scripts/server-package-size-budgets.json b/scripts/server-package-size-budgets.json
index 0ffbee90..7e2548d6 100644
--- a/scripts/server-package-size-budgets.json
+++ b/scripts/server-package-size-budgets.json
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
- "artifactBytes": 50331648,
+ "artifactBytes": 50397184,
"dependencyBytes": 26214400,
"packageInstances": 131,
"unexpectedRuntimeRoots": 0,
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index a05181ed..38e684b4 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -91,7 +91,12 @@ function createMockSettingsManager(): SettingsManager {
user: '',
password: '',
bypass: [],
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})),
update: vi.fn().mockResolvedValue(undefined),
} as unknown as SettingsManager
@@ -355,6 +360,7 @@ describe('EngineSupervisor', () => {
download: true,
updateApp: false,
updateTrackers: false,
+ plugins: false,
},
}
const after = { ...before, host: 'after.example' }
diff --git a/src/core/plugin/install/github-fetcher.test.ts b/src/core/plugin/install/github-fetcher.test.ts
index 5af73c8e..469213ba 100644
--- a/src/core/plugin/install/github-fetcher.test.ts
+++ b/src/core/plugin/install/github-fetcher.test.ts
@@ -4,11 +4,7 @@ import path from 'node:path'
import { Readable } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-// Stub undici.request before importing the SUT.
const mockRequest = vi.fn()
-vi.mock('undici', () => ({
- request: (...a: unknown[]) => mockRequest(...a),
-}))
const { downloadGithubMoext, parseGithubSpec } = await import(
'./github-fetcher'
@@ -19,17 +15,16 @@ let tmp: string
beforeEach(async () => {
tmp = await mkdtemp(path.join(tmpdir(), 'motrix-gh-'))
mockRequest.mockReset()
+ vi.stubGlobal('fetch', mockRequest)
})
afterEach(async () => {
+ vi.unstubAllGlobals()
await rm(tmp, { recursive: true, force: true })
})
function jsonResponse(payload: unknown, statusCode = 200) {
- return {
- statusCode,
- body: { json: async () => payload },
- }
+ return new Response(JSON.stringify(payload), { status: statusCode })
}
function streamResponse(
@@ -37,7 +32,7 @@ function streamResponse(
statusCode = 200,
headers: Record<string, string> = {}
) {
- return { statusCode, body: Readable.from(bytes), headers }
+ return new Response(Uint8Array.from(bytes), { status: statusCode, headers })
}
describe('parseGithubSpec', () => {
@@ -149,8 +144,8 @@ describe('downloadGithubMoext', () => {
it('rejects when GitHub returns non-200', async () => {
const destroy = vi.fn()
mockRequest.mockResolvedValueOnce({
- statusCode: 404,
- body: { json: async () => ({ message: 'not found' }), destroy },
+ status: 404,
+ body: { cancel: async () => destroy() },
})
await expect(
downloadGithubMoext(
@@ -163,26 +158,14 @@ describe('downloadGithubMoext', () => {
expect(destroy).toHaveBeenCalledOnce()
})
- it('cancels the metadata body when JSON decoding fails', async () => {
- const destroy = vi.fn()
- mockRequest.mockResolvedValueOnce({
- statusCode: 200,
- body: {
- json: async () => {
- throw new SyntaxError('invalid JSON')
- },
- destroy,
- },
- })
-
+ it('rejects invalid metadata JSON after consuming its bounded body', async () => {
+ mockRequest.mockResolvedValueOnce(new Response('invalid JSON'))
await expect(
downloadGithubMoext(
{ owner: 'acme', repo: 'widget' },
path.join(tmp, 'x.moext')
)
- ).rejects.toThrow('invalid JSON')
-
- expect(destroy).toHaveBeenCalledOnce()
+ ).rejects.toBeInstanceOf(SyntaxError)
})
it('rejects when no asset ends with .moext', async () => {
@@ -206,9 +189,8 @@ describe('downloadGithubMoext', () => {
})
it('rejects when asset download itself fails', async () => {
- const failedBody = Readable.from(Buffer.alloc(0))
- const once = vi.spyOn(failedBody, 'once')
- const destroy = vi.spyOn(failedBody, 'destroy')
+ const destroy = vi.fn()
+ const failedBody = new ReadableStream({ cancel: destroy })
mockRequest
.mockResolvedValueOnce(
jsonResponse({
@@ -221,7 +203,7 @@ describe('downloadGithubMoext', () => {
],
})
)
- .mockResolvedValueOnce({ statusCode: 500, body: failedBody, headers: {} })
+ .mockResolvedValueOnce(new Response(failedBody, { status: 500 }))
await expect(
downloadGithubMoext(
{ owner: 'acme', repo: 'widget' },
@@ -230,11 +212,7 @@ describe('downloadGithubMoext', () => {
).rejects.toMatchObject({
message: 'plugin.install.gh_asset_download_failed: 500',
})
- expect(once).toHaveBeenCalledWith('error', expect.any(Function))
expect(destroy).toHaveBeenCalledOnce()
- expect(once.mock.invocationCallOrder[0]).toBeLessThan(
- destroy.mock.invocationCallOrder[0] as number
- )
})
it('cancels a failing asset stream and removes any destination file', async () => {
@@ -260,11 +238,9 @@ describe('downloadGithubMoext', () => {
],
})
)
- .mockResolvedValueOnce({
- statusCode: 200,
- body: failedBody,
- headers: {},
- })
+ .mockResolvedValueOnce(
+ new Response(Readable.toWeb(failedBody) as ReadableStream<Uint8Array>)
+ )
const destination = path.join(tmp, 'x.moext')
await expect(
diff --git a/src/core/plugin/install/github-fetcher.ts b/src/core/plugin/install/github-fetcher.ts
index 5f523aea..f616f82e 100644
--- a/src/core/plugin/install/github-fetcher.ts
+++ b/src/core/plugin/install/github-fetcher.ts
@@ -1,5 +1,5 @@
// Resolves `github:owner/repo[@tag]` install specs by hitting the GitHub
-// Releases API, locating a `*.moext` asset, and streaming it to disk.
+// Releases API, locating a `*.moext` asset, and downloading it with a size limit.
//
// We don't read the manifest here — that happens later in `extractMoext`.
// We just provide a clean tarball-style "bring me the bytes" boundary.
@@ -7,7 +7,7 @@
import { mkdir, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { AppError, ErrorCode } from '@shared/errors'
-import { request } from 'undici'
+import { readPluginResponse } from './read-plugin-response'
export interface GhReleaseSpec {
owner: string
@@ -55,33 +55,8 @@ function requireHttpsUrl(rawUrl: string, errorKey: string): URL {
return url
}
-function responseHeader(
- headers: Record<string, string | string[] | undefined>,
- name: string
-): string | undefined {
- const value = headers[name]
- return Array.isArray(value) ? value[0] : value
-}
-
-async function cancelBody(body: unknown): Promise<void> {
- const stream = body as {
- destroy?: (error?: Error) => unknown
- cancel?: (reason?: unknown) => Promise<void>
- once?: (event: 'error', listener: () => void) => unknown
- }
- try {
- if (typeof stream.destroy === 'function') {
- // Undici BodyReadable emits RequestAbortedError asynchronously for an
- // intentional destroy. Swallow that cleanup signal without waiting for
- // a close event that can itself depend on dispatcher teardown.
- stream.once?.('error', () => undefined)
- stream.destroy()
- } else if (typeof stream.cancel === 'function') {
- await stream.cancel()
- }
- } catch {
- // Response cleanup is best-effort and must not mask the install error.
- }
+async function cancelBody(response: Response): Promise<void> {
+ await response.body?.cancel().catch(() => undefined)
}
function resolveHttpsRedirect(location: string, current: URL): URL {
@@ -105,30 +80,34 @@ function resolveHttpsRedirect(location: string, current: URL): URL {
export async function downloadGithubMoext(
spec: GhReleaseSpec,
- destFile: string
+ destFile: string,
+ fetchImpl: typeof fetch = fetch
): Promise<DownloadResult> {
const apiUrl = spec.tag
? `https://api.github.com/repos/${spec.owner}/${spec.repo}/releases/tags/${encodeURIComponent(spec.tag)}`
: `https://api.github.com/repos/${spec.owner}/${spec.repo}/releases/latest`
- const meta = await request(apiUrl, {
+ const meta = await fetchImpl(apiUrl, {
+ redirect: 'error',
headers: {
'user-agent': USER_AGENT,
accept: 'application/vnd.github+json',
},
})
- if (meta.statusCode !== 200) {
- await cancelBody(meta.body)
+ if (meta.status !== 200) {
+ await cancelBody(meta)
throw new AppError(
ErrorCode.PluginManifestInvalid,
- `plugin.install.gh_release_unavailable: ${meta.statusCode}`
+ `plugin.install.gh_release_unavailable: ${meta.status}`
)
}
let body: GhReleaseResponse
try {
- body = (await meta.body.json()) as GhReleaseResponse
+ body = JSON.parse(
+ (await readPluginResponse(meta)).toString('utf8')
+ ) as GhReleaseResponse
} catch (cause) {
- await cancelBody(meta.body)
+ await cancelBody(meta)
throw cause
}
const asset = body.assets.find((a) => a.name.endsWith('.moext'))
@@ -146,57 +125,47 @@ export async function downloadGithubMoext(
asset.browser_download_url,
'plugin.install.gh_asset_insecure_url'
)
- let dl: Awaited<ReturnType<typeof request>> | undefined
+ let dl: Response | undefined
for (let redirects = 0; ; redirects += 1) {
- const response = await request(assetUrl.href, {
+ const response = await fetchImpl(assetUrl.href, {
+ redirect: 'manual',
headers: { 'user-agent': USER_AGENT },
})
- if (!REDIRECT_STATUSES.has(response.statusCode)) {
+ if (!REDIRECT_STATUSES.has(response.status)) {
dl = response
break
}
if (redirects >= MAX_REDIRECTS) {
- await cancelBody(response.body)
+ await cancelBody(response)
throw new AppError(
ErrorCode.PluginManifestInvalid,
'plugin.install.too_many_redirects'
)
}
- const location = responseHeader(response.headers, 'location')
+ const location = response.headers.get('location')
if (!location) {
- await cancelBody(response.body)
+ await cancelBody(response)
throw new AppError(
ErrorCode.PluginManifestInvalid,
'plugin.install.invalid_redirect'
)
}
- await cancelBody(response.body)
+ await cancelBody(response)
assetUrl = resolveHttpsRedirect(location, assetUrl)
}
- if (dl.statusCode !== 200) {
- await cancelBody(dl.body)
+ if (dl.status !== 200) {
+ await cancelBody(dl)
throw new AppError(
ErrorCode.PluginManifestInvalid,
- `plugin.install.gh_asset_download_failed: ${dl.statusCode}`
+ `plugin.install.gh_asset_download_failed: ${dl.status}`
)
}
- const chunks: Buffer[] = []
- let total = 0
try {
- for await (const chunk of dl.body) {
- const bytes = Buffer.from(chunk)
- total += bytes.byteLength
- if (total > MAX_MOEXT_BYTES) {
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- 'plugin.install.package_too_large'
- )
- }
- chunks.push(bytes)
- }
- await writeFile(destFile, Buffer.concat(chunks, total), { mode: 0o600 })
+ await writeFile(destFile, await readPluginResponse(dl, MAX_MOEXT_BYTES), {
+ mode: 0o600,
+ })
} catch (cause) {
- await cancelBody(dl.body)
+ await cancelBody(dl)
await rm(destFile, { force: true }).catch(() => undefined)
throw cause
}
diff --git a/src/core/plugin/install/read-plugin-response.ts b/src/core/plugin/install/read-plugin-response.ts
new file mode 100644
index 00000000..fefb66a9
--- /dev/null
+++ b/src/core/plugin/install/read-plugin-response.ts
@@ -0,0 +1,42 @@
+import { AppError, ErrorCode } from '@shared/errors'
+
+/** Release the response on every bounded-read failure, including stream errors. */
+export async function readPluginResponse(
+ response: Response,
+ limit = 5 * 1024 * 1024
+): Promise<Buffer> {
+ if (Number(response.headers.get('content-length')) > limit) {
+ await response.body?.cancel().catch(() => undefined)
+ throw new AppError(
+ ErrorCode.PluginManifestInvalid,
+ 'plugin.install.package_too_large'
+ )
+ }
+ if (!response.body)
+ throw new AppError(
+ ErrorCode.PluginManifestInvalid,
+ 'plugin.install.url_download_failed: empty body'
+ )
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let total = 0
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ total += value.byteLength
+ if (total > limit)
+ throw new AppError(
+ ErrorCode.PluginManifestInvalid,
+ 'plugin.install.package_too_large'
+ )
+ chunks.push(value)
+ }
+ return Buffer.concat(chunks, total)
+ } catch (error) {
+ await reader.cancel().catch(() => undefined)
+ throw error
+ } finally {
+ reader.releaseLock()
+ }
+}
diff --git a/src/core/plugin/install/url-fetcher.test.ts b/src/core/plugin/install/url-fetcher.test.ts
index 958a70d1..9cf75f4a 100644
--- a/src/core/plugin/install/url-fetcher.test.ts
+++ b/src/core/plugin/install/url-fetcher.test.ts
@@ -1,131 +1,74 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
-import { Readable } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { downloadUrlMoext } from './url-fetcher'
-const mocks = vi.hoisted(() => ({
- request: vi.fn(),
- compose: vi.fn(),
- destroy: vi.fn(async () => undefined),
- redirect: vi.fn(),
- dispatcher: { kind: 'composed-dispatcher' },
- interceptor: { kind: 'redirect-interceptor' },
-}))
-
-vi.mock('undici', () => ({
- Agent: class MockAgent {
- compose(interceptor: unknown) {
- mocks.compose(interceptor)
- return mocks.dispatcher
- }
-
- destroy() {
- return mocks.destroy()
- }
- },
- interceptors: {
- redirect(options: unknown) {
- mocks.redirect(options)
- return mocks.interceptor
- },
- },
- request: (...args: unknown[]) => mocks.request(...args),
-}))
-
-const { downloadUrlMoext } = await import('./url-fetcher')
-
-let tempDir: string
-
+let directory: string
beforeEach(async () => {
- tempDir = await mkdtemp(path.join(tmpdir(), 'motrix-url-fetcher-'))
- mocks.request.mockReset()
- mocks.compose.mockClear()
- mocks.destroy.mockClear()
- mocks.redirect.mockClear()
+ directory = await mkdtemp(path.join(tmpdir(), 'plugin-url-'))
})
-
afterEach(async () => {
- await rm(tempDir, { recursive: true, force: true })
+ await rm(directory, { recursive: true, force: true })
})
describe('downloadUrlMoext', () => {
- it('streams a successful response and destroys its owned Agent', async () => {
- mocks.request.mockResolvedValueOnce({
- statusCode: 200,
- body: Readable.from(Buffer.from('plugin-bytes')),
+ it('uses the supplied transport and writes the bounded package', async () => {
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response('plugin'))
+ const dest = path.join(directory, 'nested', 'plugin.moext')
+ await downloadUrlMoext('https://plugins.example/package', dest, fetcher)
+ expect(fetcher).toHaveBeenCalledWith('https://plugins.example/package', {
+ redirect: 'follow',
})
- const destination = path.join(tempDir, 'nested', 'plugin.moext')
-
- await downloadUrlMoext('https://plugins.example/plugin.moext', destination)
-
- expect((await readFile(destination)).toString()).toBe('plugin-bytes')
- expect(mocks.redirect).toHaveBeenCalledWith({ maxRedirections: 5 })
- expect(mocks.compose).toHaveBeenCalledWith(mocks.interceptor)
- expect(mocks.request).toHaveBeenCalledWith(
- 'https://plugins.example/plugin.moext',
- { dispatcher: mocks.dispatcher }
- )
- expect(mocks.destroy).toHaveBeenCalledOnce()
+ expect(await readFile(dest, 'utf8')).toBe('plugin')
})
-
- it('cancels a non-200 response body before destroying the Agent', async () => {
- const body = Readable.from(Buffer.from('server error'))
- const once = vi.spyOn(body, 'once')
- const destroy = vi.spyOn(body, 'destroy')
- mocks.request.mockResolvedValueOnce({ statusCode: 503, body })
- const destination = path.join(tempDir, 'plugin.moext')
-
+ it('cancels an unsuccessful response', async () => {
+ const cancel = vi.fn()
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(
+ new Response(new ReadableStream({ cancel }), { status: 503 })
+ )
await expect(
- downloadUrlMoext('https://plugins.example/plugin.moext', destination)
- ).rejects.toMatchObject({
- message: 'plugin.install.url_download_failed: 503',
- })
-
- expect(once).toHaveBeenCalledWith('error', expect.any(Function))
- expect(destroy).toHaveBeenCalled()
- expect(once.mock.invocationCallOrder[0]).toBeLessThan(
- destroy.mock.invocationCallOrder[0] as number
- )
- expect(mocks.destroy).toHaveBeenCalledOnce()
- await expect(readFile(destination)).rejects.toMatchObject({
- code: 'ENOENT',
- })
+ downloadUrlMoext(
+ 'https://plugins.example/package',
+ path.join(directory, 'plugin'),
+ fetcher
+ )
+ ).rejects.toThrow('url_download_failed: 503')
+ expect(cancel).toHaveBeenCalledOnce()
})
-
- it('removes a partial file and destroys the Agent on a body stream error', async () => {
- let emitted = false
- const body = new Readable({
- read() {
- if (emitted) return
- emitted = true
- this.push(Buffer.from('partial'))
- this.destroy(new Error('stream failed'))
- },
- })
- mocks.request.mockResolvedValueOnce({ statusCode: 200, body })
- const destination = path.join(tempDir, 'plugin.moext')
-
+ it('rejects an oversized stream without leaving a partial package', async () => {
+ const cancel = vi.fn()
+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array(5 * 1024 * 1024 + 1))
+ },
+ cancel,
+ })
+ )
+ )
+ const dest = path.join(directory, 'plugin')
await expect(
- downloadUrlMoext('https://plugins.example/plugin.moext', destination)
- ).rejects.toThrow('stream failed')
-
- expect(mocks.destroy).toHaveBeenCalledOnce()
- await expect(readFile(destination)).rejects.toMatchObject({
- code: 'ENOENT',
- })
+ downloadUrlMoext('https://plugins.example/package', dest, fetcher)
+ ).rejects.toThrow('package_too_large')
+ expect(cancel).toHaveBeenCalledOnce()
+ await expect(readFile(dest)).rejects.toMatchObject({ code: 'ENOENT' })
})
-
- it('destroys the Agent when request fails before returning a response', async () => {
- mocks.request.mockRejectedValueOnce(new Error('connect failed'))
-
+ it('preserves transport errors', async () => {
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockRejectedValue(new Error('proxy unavailable'))
await expect(
downloadUrlMoext(
- 'https://plugins.example/plugin.moext',
- path.join(tempDir, 'plugin.moext')
+ 'https://plugins.example/package',
+ path.join(directory, 'plugin'),
+ fetcher
)
- ).rejects.toThrow('connect failed')
-
- expect(mocks.destroy).toHaveBeenCalledOnce()
+ ).rejects.toThrow('proxy unavailable')
})
})
diff --git a/src/core/plugin/install/url-fetcher.ts b/src/core/plugin/install/url-fetcher.ts
index c94b3752..37e79405 100644
--- a/src/core/plugin/install/url-fetcher.ts
+++ b/src/core/plugin/install/url-fetcher.ts
@@ -1,67 +1,28 @@
-import { createWriteStream } from 'node:fs'
-import { mkdir, rm } from 'node:fs/promises'
+import { mkdir, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
-import { pipeline } from 'node:stream/promises'
import { AppError, ErrorCode } from '@shared/errors'
-import { Agent, interceptors, request } from 'undici'
+import { readPluginResponse } from './read-plugin-response'
-const MAX_REDIRECTS = 5
-
-async function cancelBody(body: unknown): Promise<void> {
- const responseBody = body as {
- destroy?: (error?: Error) => unknown
- cancel?: (reason?: unknown) => Promise<void>
- once?: (event: 'error', listener: () => void) => unknown
- }
- try {
- if (typeof responseBody.destroy === 'function') {
- // Undici BodyReadable reports an intentional destroy as an asynchronous
- // RequestAbortedError. Install the listener before destroy so cleanup of
- // a non-200/partial response cannot become an uncaught process error.
- responseBody.once?.('error', () => undefined)
- responseBody.destroy()
- return
- }
- if (typeof responseBody.cancel === 'function') {
- await responseBody.cancel()
- }
- } catch {
- // Preserve the download error when response cancellation also fails.
- }
-}
-
-/** Download a URL-sourced plugin package and release every owned socket. */
+/** Download through the host-owned transport, bounded before writing to disk. */
export async function downloadUrlMoext(
url: string,
- destFile: string
+ destFile: string,
+ fetchImpl: typeof fetch = fetch
): Promise<void> {
- const agent = new Agent()
- let body: unknown
-
+ const response = await fetchImpl(url, { redirect: 'follow' })
try {
- const dispatcher = agent.compose(
- interceptors.redirect({ maxRedirections: MAX_REDIRECTS })
- )
- const response = await request(url, { dispatcher })
- body = response.body
- if (response.statusCode !== 200) {
- await cancelBody(body)
+ if (!response.ok) {
throw new AppError(
ErrorCode.PluginManifestInvalid,
- `plugin.install.url_download_failed: ${response.statusCode}`
+ `plugin.install.url_download_failed: ${response.status}`
)
}
-
+ const bytes = await readPluginResponse(response)
await mkdir(path.dirname(destFile), { recursive: true })
- await pipeline(response.body, createWriteStream(destFile, { mode: 0o600 }))
- body = undefined
+ await writeFile(destFile, bytes, { mode: 0o600 })
} catch (cause) {
- await cancelBody(body)
+ await response.body?.cancel().catch(() => undefined)
await rm(destFile, { force: true }).catch(() => undefined)
throw cause
- } finally {
- // The interceptor wrapper delegates to this Agent. Destroy the owner, not
- // an implementation-detail wrapper whose lifecycle differs by Undici ABI.
- await agent.destroy().catch(() => undefined)
}
}
diff --git a/src/core/plugin/network/plugin-http-client.test.ts b/src/core/plugin/network/plugin-http-client.test.ts
new file mode 100644
index 00000000..ba1bf328
--- /dev/null
+++ b/src/core/plugin/network/plugin-http-client.test.ts
@@ -0,0 +1,423 @@
+// @vitest-environment node
+import {
+ createServer,
+ type IncomingMessage,
+ type ServerResponse,
+} from 'node:http'
+import { createServer as createHttpsServer } from 'node:https'
+import {
+ type AddressInfo,
+ connect,
+ createServer as createSocksServer,
+ type Server,
+ type Socket,
+} from 'node:net'
+import { getCACertificates, setDefaultCACertificates } from 'node:tls'
+import { proxySettingsSchema } from '@shared/schemas/proxy-settings'
+import type { ProxySettings } from '@shared/types/settings'
+import { TEST_TLS_CERT, TEST_TLS_KEY } from '@test-utils/plugin-test-tls'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { PluginHttpClient } from './plugin-http-client'
+
+const servers: Server[] = []
+const sockets = new Set<Socket>()
+const clients: PluginHttpClient[] = []
+const originalCAs = getCACertificates()
+
+async function listen(server: Server): Promise<number> {
+ servers.push(server)
+ server.on('connection', (socket) => {
+ sockets.add(socket)
+ socket.on('error', () => undefined)
+ socket.once('close', () => sockets.delete(socket))
+ })
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ return (server.address() as AddressInfo).port
+}
+
+function client(settings: ProxySettings) {
+ const instance = new PluginHttpClient(() => settings)
+ clients.push(instance)
+ return instance
+}
+
+async function proxy(secure = false) {
+ const requests: string[] = []
+ const credentials: (string | undefined)[] = []
+ const handler = (req: IncomingMessage, res: ServerResponse) => {
+ requests.push(req.url ?? '')
+ credentials.push(req.headers['proxy-authorization'])
+ if (req.url?.endsWith('/redirect')) {
+ res.writeHead(302, { location: 'http://cdn.invalid/package' }).end()
+ } else res.end('proxied')
+ }
+ const server = secure
+ ? createHttpsServer({ key: TEST_TLS_KEY, cert: TEST_TLS_CERT }, handler)
+ : createServer(handler)
+ server.on('connect', (req, socket, head) => {
+ requests.push(req.url ?? '')
+ credentials.push(req.headers['proxy-authorization'])
+ const target = new URL(`http://${req.url}`)
+ const upstream = connect(Number(target.port), target.hostname, () => {
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+ if (head.length) upstream.write(head)
+ upstream.pipe(socket)
+ socket.pipe(upstream)
+ })
+ sockets.add(upstream)
+ upstream.once('close', () => sockets.delete(upstream))
+ upstream.on('error', () => socket.destroy())
+ socket.on('close', () => upstream.destroy())
+ })
+ const port = await listen(server)
+ return {
+ requests,
+ credentials,
+ port,
+ settings: proxySettingsSchema.parse({
+ enabled: true,
+ protocol: secure ? 'https' : 'http',
+ host: '127.0.0.1',
+ port,
+ scopes: { plugins: true },
+ }),
+ }
+}
+
+afterEach(async () => {
+ vi.useRealTimers()
+ await Promise.all(clients.splice(0).map((value) => value.close()))
+ for (const socket of sockets) socket.destroy()
+ await Promise.all(
+ servers
+ .splice(0)
+ .map(
+ (server) =>
+ new Promise<void>((resolve) => server.close(() => resolve()))
+ )
+ )
+ setDefaultCACertificates(originalCAs)
+ vi.unstubAllEnvs()
+})
+
+describe('plugin HTTP routing', () => {
+ it('uses only the plugins scope, authenticates, and follows CDN redirects through the proxy', async () => {
+ const fixture = await proxy()
+ fixture.settings.user = 'test user'
+ fixture.settings.password = 'p@ss:word'
+ const result = await client(fixture.settings).fetch(
+ 'http://plugins.invalid/redirect'
+ )
+ expect(await result.text()).toBe('proxied')
+ expect(fixture.requests).toEqual([
+ 'http://plugins.invalid/redirect',
+ 'http://cdn.invalid/package',
+ ])
+ expect(fixture.credentials).toEqual(
+ Array(2).fill(
+ `Basic ${Buffer.from('test user:p@ss:word').toString('base64')}`
+ )
+ )
+ })
+
+ it.each([false, true])(
+ 'tunnels HTTPS and preserves conditional headers (secure proxy: %s)',
+ async (secure) => {
+ setDefaultCACertificates([...originalCAs, TEST_TLS_CERT])
+ const origin = await listen(
+ createHttpsServer(
+ { key: TEST_TLS_KEY, cert: TEST_TLS_CERT },
+ (req, res) => {
+ expect(req.headers['proxy-authorization']).toBeUndefined()
+ res
+ .writeHead(req.headers['if-none-match'] ? 304 : 200, {
+ etag: 'registry-v2',
+ })
+ .end('registry')
+ }
+ )
+ )
+ const fixture = await proxy(secure)
+ const http = client(fixture.settings)
+ const url = `https://127.0.0.1:${origin}/registry`
+ const response = await http.fetch(url)
+ expect(await response.text()).toBe('registry')
+ expect(response.headers.get('etag')).toBe('registry-v2')
+ const cached = await http.fetch(url, {
+ headers: { 'if-none-match': 'registry-v2' },
+ })
+ expect(cached.status).toBe(304)
+ expect(fixture.requests).toEqual([
+ `127.0.0.1:${origin}`,
+ `127.0.0.1:${origin}`,
+ ])
+ }
+ )
+
+ it.each(['download', 'updateApp', 'updateTrackers'] as const)(
+ 'does not use the proxy when only %s is enabled, even with environment proxies',
+ async (scope) => {
+ const origin = await listen(
+ createServer((_req, res) => res.end('direct'))
+ )
+ const fixture = await proxy()
+ fixture.settings.scopes.plugins = false
+ fixture.settings.scopes[scope] = true
+ vi.stubEnv('HTTP_PROXY', `http://127.0.0.1:${fixture.port}`)
+ vi.stubEnv('NODE_USE_ENV_PROXY', '1')
+ const response = await client(fixture.settings).fetch(
+ `http://127.0.0.1:${origin}/`
+ )
+ expect(await response.text()).toBe('direct')
+ expect(fixture.requests).toEqual([])
+ }
+ )
+
+ it('re-evaluates bypass for redirects and never sends proxy credentials to the origin', async () => {
+ const origin = await listen(
+ createServer((req, res) => {
+ expect(req.headers['proxy-authorization']).toBeUndefined()
+ res.writeHead(302, { location: 'http://cdn.invalid/package' }).end()
+ })
+ )
+ const fixture = await proxy()
+ fixture.settings.bypass = ['127.0.0.1']
+ const response = await client(fixture.settings).fetch(
+ `http://127.0.0.1:${origin}/`
+ )
+ expect(await response.text()).toBe('proxied')
+ expect(fixture.requests).toEqual(['http://cdn.invalid/package'])
+ })
+
+ it('uses updated settings for the next request without affecting an active response', async () => {
+ let end!: () => void
+ const origin = await listen(
+ createServer((_req, res) => {
+ res.write('first')
+ end = () => res.end('-finished')
+ })
+ )
+ const fixture = await proxy()
+ const http = client(fixture.settings)
+ fixture.settings.enabled = false
+ const active = await http.fetch(`http://127.0.0.1:${origin}/`)
+ fixture.settings.enabled = true
+ expect(
+ await (await http.fetch('http://plugins.invalid/package')).text()
+ ).toBe('proxied')
+ end()
+ expect(await active.text()).toBe('first-finished')
+ })
+
+ it('uses an owned authenticated SOCKS5 connection when only plugins are enabled', async () => {
+ const credentials: string[][] = []
+ const origin = await listen(
+ createServer((_req, res) => res.end('socks-download'))
+ )
+ const socks = createSocksServer((socket) => {
+ let stage = 0
+ let buffer = Buffer.alloc(0)
+ const read = (chunk: Buffer) => {
+ buffer = Buffer.concat([buffer, chunk])
+ if (stage === 0) {
+ if (buffer.length < 2 || buffer.length < 2 + buffer[1]) return
+ buffer = buffer.subarray(2 + buffer[1])
+ socket.write(Buffer.from([5, 2]))
+ stage = 1
+ }
+ if (stage === 1) {
+ if (buffer.length < 2) return
+ const userLength = buffer[1]
+ if (buffer.length < 3 + userLength) return
+ const passwordLength = buffer[2 + userLength]
+ if (buffer.length < 3 + userLength + passwordLength) return
+ credentials.push([
+ buffer.subarray(2, 2 + userLength).toString(),
+ buffer
+ .subarray(3 + userLength, 3 + userLength + passwordLength)
+ .toString(),
+ ])
+ buffer = buffer.subarray(3 + userLength + passwordLength)
+ socket.write(Buffer.from([1, 0]))
+ stage = 2
+ }
+ if (stage !== 2 || buffer.length < 5) return
+ const ipv4 = buffer[3] === 1
+ const size = ipv4 ? 10 : 7 + buffer[4]
+ if (buffer.length < size) return
+ const host = ipv4
+ ? [...buffer.subarray(4, 8)].join('.')
+ : buffer.subarray(5, 5 + buffer[4]).toString()
+ const port = buffer.readUInt16BE(size - 2)
+ buffer = buffer.subarray(size)
+ stage = 3
+ socket.off('data', read)
+ const upstream = connect(port, host, () => {
+ socket.write(Buffer.from([5, 0, 0, 1, 127, 0, 0, 1, 0, 0]))
+ if (buffer.length) upstream.write(buffer)
+ upstream.pipe(socket)
+ socket.pipe(upstream)
+ })
+ sockets.add(upstream)
+ upstream.once('close', () => sockets.delete(upstream))
+ upstream.on('error', () => socket.destroy())
+ socket.on('close', () => upstream.destroy())
+ }
+ socket.on('data', read)
+ })
+ const port = await listen(socks)
+ const http = client(
+ proxySettingsSchema.parse({
+ enabled: true,
+ protocol: 'socks5',
+ host: '127.0.0.1',
+ port,
+ user: 'socks-user',
+ password: 'p@ss word',
+ scopes: { plugins: true },
+ })
+ )
+ expect(await (await http.fetch(`http://127.0.0.1:${origin}/`)).text()).toBe(
+ 'socks-download'
+ )
+ expect(credentials).toEqual([['socks-user', 'p@ss word']])
+ })
+
+ it('cancels a stalled SOCKS5 handshake and closes the connection', async () => {
+ const port = await listen(createSocksServer(() => undefined))
+ const http = client(
+ proxySettingsSchema.parse({
+ enabled: true,
+ protocol: 'socks5',
+ host: '127.0.0.1',
+ port,
+ scopes: { plugins: true },
+ })
+ )
+ const abort = new AbortController()
+ const pending = expect(
+ http.fetch('http://plugins.invalid/', { signal: abort.signal })
+ ).rejects.toMatchObject({ failure: { reason: 'cancelled' } })
+ await vi.waitFor(() => expect(sockets.size).toBeGreaterThan(0))
+ abort.abort()
+ await pending
+ await http.close()
+ await vi.waitFor(() => expect(sockets.size).toBe(0))
+ })
+
+ it('reports rejected SOCKS5 authentication', async () => {
+ const port = await listen(
+ createSocksServer((socket) => {
+ socket.once('data', () => socket.write(Buffer.from([5, 255])))
+ })
+ )
+ const http = client(
+ proxySettingsSchema.parse({
+ enabled: true,
+ protocol: 'socks5',
+ host: '127.0.0.1',
+ port,
+ scopes: { plugins: true },
+ })
+ )
+ await expect(http.fetch('http://plugins.invalid/')).rejects.toMatchObject({
+ failure: { reason: 'proxyAuth', route: 'proxy' },
+ })
+ })
+
+ it('reports an unavailable proxy without falling back or leaking credentials', async () => {
+ const fixture = await proxy()
+ await new Promise<void>((resolve) => servers[0].close(() => resolve()))
+ fixture.settings.user = 'private-user'
+ fixture.settings.password = 'private-password'
+ await expect(
+ client(fixture.settings).fetch(
+ 'http://plugins.invalid/package?token=secret'
+ )
+ ).rejects.toMatchObject({
+ failure: {
+ route: 'proxy',
+ reason: 'proxyConnect',
+ targetHost: 'plugins.invalid',
+ proxyEndpoint: `127.0.0.1:${fixture.port}`,
+ },
+ })
+ try {
+ await client(fixture.settings).fetch(
+ 'http://plugins.invalid/?token=secret'
+ )
+ } catch (error) {
+ expect(JSON.stringify(error)).not.toMatch(
+ /private-user|private-password|token=secret/
+ )
+ }
+ })
+
+ it('reports authentication and HTTP status failures', async () => {
+ const port = await listen(
+ createServer((_req, res) => res.writeHead(407).end())
+ )
+ const settings = proxySettingsSchema.parse({
+ enabled: true,
+ host: '127.0.0.1',
+ port,
+ scopes: { plugins: true },
+ })
+ await expect(
+ client(settings).fetch('http://plugins.invalid/')
+ ).rejects.toMatchObject({ failure: { reason: 'proxyAuth' } })
+ const origin = await listen(
+ createServer((_req, res) => res.writeHead(503).end())
+ )
+ settings.enabled = false
+ await expect(
+ client(settings).fetch(`http://127.0.0.1:${origin}/`)
+ ).rejects.toMatchObject({ failure: { reason: 'http', status: 503 } })
+ })
+
+ it('does not follow a security-policy redirect', async () => {
+ const fixture = await proxy()
+ await expect(
+ client(fixture.settings).fetch('http://plugins.invalid/redirect', {
+ redirect: 'error',
+ })
+ ).rejects.toMatchObject({ failure: { reason: 'network' } })
+ expect(fixture.requests).toHaveLength(1)
+ })
+
+ it('aborts stalled headers and body reads and drains them on shutdown', async () => {
+ const origin = await listen(
+ createServer((req, res) => {
+ if (req.url === '/body') res.write('partial')
+ })
+ )
+ const http = client(proxySettingsSchema.parse({}))
+ const response = await http.fetch(`http://127.0.0.1:${origin}/body`)
+ const body = expect(response.text()).rejects.toMatchObject({
+ failure: { reason: 'cancelled' },
+ })
+ const header = expect(
+ http.fetch(`http://127.0.0.1:${origin}/headers`)
+ ).rejects.toMatchObject({ failure: { reason: 'cancelled' } })
+ await http.close()
+ await Promise.all([body, header])
+ })
+
+ it('retains the deadline until a slow response body ends', async () => {
+ const origin = await listen(
+ createServer((_req, res) => res.write('partial'))
+ )
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ const response = await client(proxySettingsSchema.parse({})).fetch(
+ `http://127.0.0.1:${origin}/`
+ )
+ const pending = expect(response.text()).rejects.toMatchObject({
+ failure: { reason: 'timeout' },
+ })
+ await vi.advanceTimersByTimeAsync(60_000)
+ await pending
+ })
+})
diff --git a/src/core/plugin/network/plugin-http-client.ts b/src/core/plugin/network/plugin-http-client.ts
new file mode 100644
index 00000000..870c40c0
--- /dev/null
+++ b/src/core/plugin/network/plugin-http-client.ts
@@ -0,0 +1,245 @@
+import type { Socket } from 'node:net'
+import { decideAria2ProxyRoute } from '@core/proxy/aria2-proxy-routing'
+import { proxyToUrl } from '@core/proxy/serializers'
+import type { PluginNetworkFailure } from '@shared/schemas/plugin-network'
+import type { ProxySettings } from '@shared/types/settings'
+import {
+ Agent,
+ buildConnector,
+ ProxyAgent,
+ Socks5ProxyAgent,
+ fetch as undiciFetch,
+} from 'undici'
+import { networkFailure, PluginNetworkError } from './plugin-network-error'
+
+const REDIRECTS = new Set([301, 302, 303, 307, 308])
+const REQUEST_TIMEOUT_MS = 60_000
+
+/** Host-owned GET transport, independent of aria2 and Electron session policy. */
+export class PluginHttpClient {
+ private readonly active = new Map<AbortController, Promise<void>>()
+ private closed = false
+
+ constructor(private readonly getSettings: () => ProxySettings) {}
+
+ readonly fetch: typeof fetch = async (input, init) => {
+ if (
+ !(typeof input === 'string' || input instanceof URL) ||
+ (init?.method && init.method !== 'GET') ||
+ init?.body
+ ) {
+ throw new TypeError('Unsupported plugin network request')
+ }
+ let url = new URL(String(input))
+ const settings = structuredClone(this.getSettings())
+ const proxied = settings.enabled && settings.scopes.plugins
+ const context: Omit<PluginNetworkFailure, 'reason'> = {
+ route: 'direct',
+ targetHost: url.hostname,
+ }
+ const controller = new AbortController()
+ const abort = () => controller.abort(init?.signal?.reason)
+ init?.signal?.addEventListener('abort', abort, { once: true })
+ if (init?.signal?.aborted) abort()
+ if (this.closed) controller.abort()
+ const timer = setTimeout(
+ () =>
+ controller.abort(
+ new DOMException('Plugin request timed out', 'TimeoutError')
+ ),
+ REQUEST_TIMEOUT_MS
+ )
+ timer.unref?.()
+ // A request owns its dispatchers. Settings changes affect the next
+ // request, never an active stream or the engine/Tracker network policy.
+ const socksSockets = new Set<Socket>()
+ let disposed = false
+ const direct = new Agent()
+ let proxy: ProxyAgent | Socks5ProxyAgent | undefined
+ let cleanupPromise: Promise<void> | undefined
+ let release!: () => void
+ const finished = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ this.active.set(controller, finished)
+ const cleanup = (): Promise<void> => {
+ cleanupPromise ??= (async () => {
+ clearTimeout(timer)
+ init?.signal?.removeEventListener('abort', abort)
+ controller.signal.removeEventListener('abort', onAbort)
+ disposed = true
+ for (const socket of socksSockets)
+ socket.destroy(
+ new DOMException('Plugin request closed', 'AbortError')
+ )
+ await Promise.allSettled([direct.destroy(), proxy?.destroy()])
+ this.active.delete(controller)
+ release()
+ })()
+ return cleanupPromise
+ }
+ const failure = (error: unknown) =>
+ new PluginNetworkError(
+ networkFailure(
+ controller.signal.aborted ? controller.signal.reason : error,
+ context
+ )
+ )
+ let bodyController: ReadableStreamDefaultController<Uint8Array> | undefined
+ const onAbort = () => {
+ bodyController?.error(failure(controller.signal.reason))
+ bodyController = undefined
+ void cleanup()
+ }
+ controller.signal.addEventListener('abort', onAbort, { once: true })
+ try {
+ controller.signal.throwIfAborted()
+ if (proxied) context.proxyEndpoint = new URL(proxyToUrl(settings)).host
+ const headers = new Headers(init?.headers)
+ headers.delete('proxy-authorization')
+ for (let redirects = 0; ; redirects++) {
+ controller.signal.throwIfAborted()
+ context.targetHost = url.hostname
+ if (
+ !['http:', 'https:'].includes(url.protocol) ||
+ url.username ||
+ url.password
+ ) {
+ throw new TypeError('Invalid plugin request URL')
+ }
+ const route = proxied
+ ? decideAria2ProxyRoute(url, settings.bypass.join(','))
+ : 'direct'
+ if (route === 'unsupported')
+ throw new TypeError('Unsupported plugin proxy route')
+ context.route = route
+ if (route === 'proxy' && !proxy) {
+ const endpoint = new URL(proxyToUrl(settings))
+ if (settings.protocol === 'socks5') {
+ const baseConnect = buildConnector({})
+ const connect: typeof baseConnect = (options, callback) => {
+ const hostname = options.hostname.replace(/^\[|\]$/g, '')
+ baseConnect(
+ { ...options, hostname, host: hostname },
+ (error, socket) => {
+ if (error || !socket) {
+ callback(error ?? new Error('Missing proxy socket'), null)
+ return
+ }
+ if (disposed) {
+ socket.destroy()
+ callback(
+ new DOMException('Plugin request closed', 'AbortError'),
+ null
+ )
+ return
+ }
+ // Undici does not own this socket until SOCKS negotiation
+ // finishes. Retain it so abort also closes a stalled greeting.
+ socksSockets.add(socket)
+ socket.once('close', () => socksSockets.delete(socket))
+ callback(null, socket)
+ }
+ )
+ }
+ proxy = new Socks5ProxyAgent(endpoint, { connect })
+ } else proxy = new ProxyAgent(endpoint.toString())
+ }
+ // The current Undici SOCKS connector treats bracketed IPv6 targets
+ // as DNS names. Fail closed instead of silently changing the route.
+ if (
+ route === 'proxy' &&
+ settings.protocol === 'socks5' &&
+ url.hostname.startsWith('[')
+ ) {
+ throw new TypeError('Unsupported IPv6 SOCKS target')
+ }
+ const response = await undiciFetch(url, {
+ method: 'GET',
+ headers: Object.fromEntries(headers),
+ signal: controller.signal,
+ redirect: 'manual',
+ credentials: 'omit',
+ dispatcher: route === 'proxy' ? proxy : direct,
+ })
+ if (REDIRECTS.has(response.status) && init?.redirect !== 'manual') {
+ await response.body?.cancel()
+ if (init?.redirect === 'error' || redirects >= 5)
+ throw new TypeError('Plugin redirect rejected')
+ const location = response.headers.get('location')
+ if (!location) throw new TypeError('Missing plugin redirect location')
+ const next = new URL(location, url)
+ if (url.protocol === 'https:' && next.protocol !== 'https:')
+ throw new TypeError('Plugin redirect protocol downgrade')
+ if (url.origin !== next.origin) {
+ headers.delete('authorization')
+ headers.delete('cookie')
+ }
+ url = next
+ continue
+ }
+ if (
+ !response.ok &&
+ response.status !== 304 &&
+ !REDIRECTS.has(response.status)
+ ) {
+ await response.body?.cancel()
+ throw new PluginNetworkError({
+ ...context,
+ reason:
+ response.status === 407 && route === 'proxy'
+ ? 'proxyAuth'
+ : 'http',
+ status: response.status,
+ })
+ }
+ const responseInit = {
+ status: response.status,
+ headers: Object.fromEntries(response.headers),
+ }
+ if (!response.body) {
+ await cleanup()
+ return new Response(null, responseInit)
+ }
+ const reader = response.body.getReader()
+ const body = new ReadableStream<Uint8Array>({
+ start(streamController) {
+ bodyController = streamController
+ },
+ async pull(streamController) {
+ try {
+ const { done, value } = await reader.read()
+ if (!bodyController) return
+ if (done) {
+ bodyController = undefined
+ streamController.close()
+ await cleanup()
+ } else streamController.enqueue(value)
+ } catch (error) {
+ if (bodyController) {
+ bodyController = undefined
+ streamController.error(failure(error))
+ }
+ await cleanup()
+ }
+ },
+ async cancel() {
+ bodyController = undefined
+ await Promise.allSettled([reader.cancel(), cleanup()])
+ },
+ })
+ return new Response(body, responseInit)
+ }
+ } catch (error) {
+ await cleanup()
+ throw failure(error)
+ }
+ }
+
+ async close(): Promise<void> {
+ this.closed = true
+ const pending = [...this.active.values()]
+ for (const controller of this.active.keys()) controller.abort()
+ await Promise.all(pending)
+ }
+}
diff --git a/src/core/plugin/network/plugin-network-error.ts b/src/core/plugin/network/plugin-network-error.ts
new file mode 100644
index 00000000..2a87f8ca
--- /dev/null
+++ b/src/core/plugin/network/plugin-network-error.ts
@@ -0,0 +1,45 @@
+import { AppError, ErrorCode } from '@shared/errors'
+import type { PluginNetworkFailure } from '@shared/schemas/plugin-network'
+
+/** Only sanitized diagnostic data crosses the shell or logging boundary. */
+export class PluginNetworkError extends AppError {
+ constructor(readonly failure: PluginNetworkFailure) {
+ super(ErrorCode.PluginNetworkFailed, `plugin.network.${failure.reason}`)
+ }
+}
+
+export function networkFailure(
+ error: unknown,
+ context: Omit<PluginNetworkFailure, 'reason'>
+): PluginNetworkFailure {
+ if (error instanceof PluginNetworkError) return error.failure
+ const codes: string[] = []
+ const messages: string[] = []
+ let cause = error
+ for (let i = 0; i < 8 && cause && typeof cause === 'object'; i++) {
+ const value = cause as {
+ code?: string
+ name?: string
+ message?: string
+ cause?: unknown
+ }
+ codes.push(String(value.code ?? ''), String(value.name ?? ''))
+ messages.push(String(value.message ?? ''))
+ cause = value.cause
+ }
+ const code = codes.join(' ')
+ const message = messages.join(' ')
+ let reason: PluginNetworkFailure['reason'] = 'network'
+ if (/TIMEOUT|TIMEDOUT|TimeoutError/.test(code)) reason = 'timeout'
+ else if (/ENOTFOUND|EAI_AGAIN/.test(code)) reason = 'dns'
+ else if (/CERT|TLS|SSL/.test(code)) reason = 'certificate'
+ else if (
+ context.route === 'proxy' &&
+ (/Proxy.*\b407\b/i.test(message) || /UND_ERR_SOCKS5_AUTH/.test(code))
+ )
+ reason = 'proxyAuth'
+ else if (context.route === 'proxy' && /ECONNREFUSED|UND_ERR_PRX/.test(code))
+ reason = 'proxyConnect'
+ else if (/AbortError/.test(code)) reason = 'cancelled'
+ return { ...context, reason }
+}
diff --git a/src/core/plugin/registry/registry-client.test.ts b/src/core/plugin/registry/registry-client.test.ts
index 5999245a..98f8ec7e 100644
--- a/src/core/plugin/registry/registry-client.test.ts
+++ b/src/core/plugin/registry/registry-client.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'
import path from 'node:path'
import fixture from '@shared/schemas/registry.fixture.json'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { PluginNetworkError } from '../network/plugin-network-error'
import {
MAX_REGISTRY_BYTES,
RegistryClient,
@@ -85,6 +86,34 @@ describe('RegistryClient', () => {
})
}
+ it('reports network failure without losing the last-good cache and clears status on recovery', async () => {
+ const failure = {
+ reason: 'timeout' as const,
+ route: 'proxy' as const,
+ targetHost: 'dl.motrix.app',
+ proxyEndpoint: '127.0.0.1:7897',
+ }
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockRejectedValueOnce(new PluginNetworkError(failure))
+ .mockResolvedValueOnce(new Response(JSON.stringify(fixture)))
+ .mockRejectedValueOnce(new PluginNetworkError(failure))
+ .mockResolvedValueOnce(new Response(null, { status: 304 }))
+ const client = makeClient(fetcher)
+ expect(await client.load()).toBeNull()
+ expect(client.status()).toEqual({
+ cached: false,
+ lastSuccessAt: null,
+ error: failure,
+ })
+ expect(await client.refresh()).not.toBeNull()
+ expect(client.status().error).toBeNull()
+ expect(await client.refresh()).not.toBeNull()
+ expect(client.status()).toMatchObject({ cached: true, error: failure })
+ await client.refresh()
+ expect(client.status().error).toBeNull()
+ })
+
it('annotates the media-merge beta requirement with the actual host version', async () => {
const body = structuredClone(fixture)
body.plugins[0].id = 'motrix.media-merge'
@@ -386,17 +415,21 @@ describe('RegistryClient', () => {
return new Promise<Response>(() => {})
}) as unknown as typeof fetch
- const pending = makeClient(impl, {
+ const client = makeClient(impl, {
statImpl: async () => {
throw new Error('no cache')
},
- }).load()
+ })
+ const pending = client.load()
await vi.advanceTimersByTimeAsync(0)
expect(impl).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(15_000)
expect(await pending).toBeNull()
expect(signal?.aborted).toBe(true)
+ expect(client.status().error?.reason).toBe('timeout')
+ // A consumer deadline must not misreport a proxied fetch as direct.
+ expect(client.status().error?.route).toBeUndefined()
})
it('cancels a late response from a fetch implementation that ignores abort', async () => {
diff --git a/src/core/plugin/registry/registry-client.ts b/src/core/plugin/registry/registry-client.ts
index 49a11c0f..b238eff0 100644
--- a/src/core/plugin/registry/registry-client.ts
+++ b/src/core/plugin/registry/registry-client.ts
@@ -1,5 +1,6 @@
import { readFile, stat } from 'node:fs/promises'
import { getLogger } from '@core/logger'
+import type { RegistryStatus } from '@shared/schemas/plugin-network'
import {
REGISTRY_URL,
type RegistryFile,
@@ -9,6 +10,7 @@ import {
import writeFileAtomic from 'write-file-atomic'
import { z } from 'zod'
import { semverSatisfies } from '../manifest/parse'
+import { networkFailure } from '../network/plugin-network-error'
const DEFAULT_TTL_MS = 6 * 60 * 60 * 1000
const FETCH_TIMEOUT_MS = 15_000
@@ -72,6 +74,7 @@ export class RegistryClient {
private readonly readFileImpl: RegistryReadFile
private readonly log = getLogger('plugin-registry')
+ private lastError: RegistryStatus['error'] = null
private cache: CacheState | null = null
private diskLoadPromise: Promise<void> | null = null
private inflight: Promise<RegistryFile | null> | null = null
@@ -94,6 +97,14 @@ export class RegistryClient {
options.readFileImpl ?? ((cachePath) => readFile(cachePath, 'utf8'))
}
+ status(): RegistryStatus {
+ return {
+ cached: this.cache !== null,
+ lastSuccessAt: this.cache?.fetchedAt ?? null,
+ error: this.lastError,
+ }
+ }
+
/** Last-good registry, refreshed over the network only when stale. */
async load(): Promise<RegistryFile | null> {
await this.loadDiskOnce()
@@ -150,7 +161,10 @@ export class RegistryClient {
let timer: ReturnType<typeof setTimeout> | undefined
const deadline = new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => {
- const error = new Error('registry request timed out')
+ const error = new DOMException(
+ 'registry request timed out',
+ 'TimeoutError'
+ )
controller.abort(error)
reject(error)
}, FETCH_TIMEOUT_MS)
@@ -179,6 +193,7 @@ export class RegistryClient {
await cancelResponseBody(res)
this.cache = { ...this.cache, fetchedAt: this.now() }
await this.persist()
+ this.lastError = null
return this.cache.file
}
if (!res.ok) {
@@ -200,9 +215,16 @@ export class RegistryClient {
file,
}
await this.persist()
+ this.lastError = null
return file
} catch (error) {
- this.log.warn({ error }, 'registry refresh failed; keeping last-good')
+ this.lastError = networkFailure(error, {
+ targetHost: new URL(this.url).hostname,
+ })
+ this.log.warn(
+ { failure: this.lastError },
+ 'registry refresh failed; keeping last-good'
+ )
return this.cache?.file ?? null
} finally {
if (timer !== undefined) clearTimeout(timer)
diff --git a/src/core/proxy/applier.test.ts b/src/core/proxy/applier.test.ts
index a4256a92..6f8eb4f9 100644
--- a/src/core/proxy/applier.test.ts
+++ b/src/core/proxy/applier.test.ts
@@ -31,11 +31,21 @@ describe('proxyApplier.apply', () => {
const result = await applier.apply(
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
)
expect(deps.engineSupervisor.applyProxyChange).toHaveBeenCalledWith({
@@ -54,11 +64,21 @@ describe('proxyApplier.apply', () => {
await applier.apply(
{
...baseProxy,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
)
expect(deps.engineSupervisor.applyProxyChange).toHaveBeenCalledWith(null)
@@ -75,12 +95,22 @@ describe('proxyApplier.apply', () => {
const result = await applier.apply(
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
protocol: 'socks5',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
)
@@ -102,7 +132,12 @@ describe('proxyApplier.apply', () => {
const applier = createProxyApplier(deps)
const both = {
...baseProxy,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const result = await applier.apply(both, both)
expect(deps.engineSupervisor.applyProxyChange).not.toHaveBeenCalled()
@@ -115,11 +150,21 @@ describe('proxyApplier.apply', () => {
await applier.apply(
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
- scopes: { download: false, updateApp: true, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: true,
+ updateTrackers: false,
+ plugins: false,
+ },
}
)
expect(deps.applyUpdateAppProxy).toHaveBeenCalled()
@@ -140,11 +185,21 @@ describe('proxyApplier.apply', () => {
await applier.apply(
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
- scopes: { download: false, updateApp: true, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: true,
+ updateTrackers: false,
+ plugins: false,
+ },
}
)
})
@@ -155,11 +210,21 @@ describe('proxyApplier.apply', () => {
await applier.apply(
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
}
)
expect(deps.trackerManager.invalidateProxyCache).toHaveBeenCalled()
@@ -172,14 +237,24 @@ describe('proxyApplier.apply', () => {
...baseProxy,
protocol: 'socks5' as const,
enabled: false,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
await applier.apply(
{
...baseProxy,
protocol: 'socks5',
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
},
next
)
@@ -194,7 +269,12 @@ describe('proxyApplier.apply', () => {
const applier = createProxyApplier(deps)
await applier.applyAll({
...baseProxy,
- scopes: { download: true, updateApp: true, updateTrackers: true },
+ scopes: {
+ download: true,
+ updateApp: true,
+ updateTrackers: true,
+ plugins: false,
+ },
})
expect(deps.engineSupervisor.applyProxyChange).toHaveBeenCalled()
expect(deps.applyUpdateAppProxy).toHaveBeenCalled()
@@ -211,6 +291,7 @@ describe('proxyApplier.apply', () => {
download: false,
updateApp: false,
updateTrackers: false,
+ plugins: false,
},
})
@@ -233,11 +314,21 @@ describe('proxyApplier.apply', () => {
const result = await applier.apply(
{
...baseProxy,
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
{
...baseProxy,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
)
diff --git a/src/core/proxy/proxy-bridge-manager.test.ts b/src/core/proxy/proxy-bridge-manager.test.ts
index 7e453549..81f5d2b5 100644
--- a/src/core/proxy/proxy-bridge-manager.test.ts
+++ b/src/core/proxy/proxy-bridge-manager.test.ts
@@ -56,7 +56,12 @@ describe('ProxyBridgeManager', () => {
manager.resolveForDownload({
...enabledProxy,
protocol: 'http',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
).resolves.toEqual({
allProxy: 'http://proxy.example.com:1080',
@@ -76,7 +81,12 @@ describe('ProxyBridgeManager', () => {
user: 'a@b',
password: 'p:s',
bypass: ['localhost', '127.0.0.1'],
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
).resolves.toEqual({
allProxy: 'http://local-user-1:[email protected]:43123',
@@ -95,7 +105,12 @@ describe('ProxyBridgeManager', () => {
const first = {
...enabledProxy,
protocol: 'socks5' as const,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
await manager.resolveForDownload(first)
@@ -113,13 +128,23 @@ describe('ProxyBridgeManager', () => {
await manager.resolveForDownload({
...enabledProxy,
protocol: 'socks5',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
await expect(
manager.resolveForDownload({
...enabledProxy,
protocol: 'socks5',
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
).resolves.toBeNull()
@@ -135,7 +160,12 @@ describe('ProxyBridgeManager', () => {
manager.resolveForFetch({
...enabledProxy,
protocol: 'socks5',
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
).resolves.toBe('http://local-user-1:[email protected]:43123')
})
@@ -166,13 +196,23 @@ describe('ProxyBridgeManager', () => {
await manager.resolveForDownload({
...enabledProxy,
protocol: 'socks5',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
const stopping = manager.reconcile({
...enabledProxy,
protocol: 'http',
- scopes: { download: true, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
await vi.waitFor(() => expect(server.close).toHaveBeenCalledWith(true))
@@ -196,7 +236,12 @@ describe('ProxyBridgeManager', () => {
const resolving = manager.resolveForDownload({
...enabledProxy,
protocol: 'socks5',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
await vi.waitFor(() => expect(server.listen).toHaveBeenCalledOnce())
const closing = manager.close()
@@ -216,7 +261,12 @@ describe('ProxyBridgeManager', () => {
const settings = {
...enabledProxy,
protocol: 'socks5' as const,
- scopes: { download: true, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
}
const [downloadProxy, fetchProxy] = await Promise.all([
@@ -235,7 +285,12 @@ describe('ProxyBridgeManager', () => {
await manager.resolveForFetch({
...enabledProxy,
protocol: 'socks5',
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
await manager.close()
diff --git a/src/core/proxy/serializers.test.ts b/src/core/proxy/serializers.test.ts
index 54426591..8a30a1b5 100644
--- a/src/core/proxy/serializers.test.ts
+++ b/src/core/proxy/serializers.test.ts
@@ -27,7 +27,12 @@ describe('proxyToAria2Options', () => {
it('returns options when enabled and scope on', () => {
const r = proxyToAria2Options({
...enabledHttp,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
expect(r).toEqual({ allProxy: 'http://p.example.com:8080', noProxy: '' })
})
@@ -37,7 +42,12 @@ describe('proxyToAria2Options', () => {
proxyToAria2Options({
...enabledHttp,
protocol: 'socks5',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
).toBeNull()
})
@@ -45,7 +55,12 @@ describe('proxyToAria2Options', () => {
it('joins bypass with comma', () => {
const r = proxyToAria2Options({
...enabledHttp,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
bypass: ['localhost', '127.0.0.1'],
})
expect(r?.noProxy).toBe('localhost,127.0.0.1')
@@ -56,7 +71,12 @@ describe('proxyToAria2Options', () => {
...enabledHttp,
user: 'a@b',
password: 'p:s',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
expect(r?.allProxy).toBe('http://a%40b:p%[email protected]:8080')
})
@@ -65,7 +85,12 @@ describe('proxyToAria2Options', () => {
const r = proxyToAria2Options({
...enabledHttp,
host: '2001:db8::1',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
expect(r?.allProxy).toBe('http://[2001:db8::1]:8080')
})
@@ -75,14 +100,24 @@ describe('proxyToAria2Options', () => {
proxyToAria2Options({
...enabledHttp,
bypass: ['localhost\nhttp-proxy=http://evil'],
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
).toBeNull()
expect(
proxyToAria2Options({
...enabledHttp,
user: 'user\nhttp-proxy=http://evil',
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
).toBeNull()
})
@@ -96,7 +131,12 @@ describe('proxyToElectronConfig', () => {
it('emits proxyRules with HTTP url', () => {
const r = proxyToElectronConfig({
...enabledHttp,
- scopes: { download: false, updateApp: true, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: true,
+ updateTrackers: false,
+ plugins: false,
+ },
})
expect(r?.proxyRules).toBe('http://p.example.com:8080')
})
@@ -105,7 +145,12 @@ describe('proxyToElectronConfig', () => {
const r = proxyToElectronConfig({
...enabledHttp,
protocol: 'socks5',
- scopes: { download: false, updateApp: true, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: true,
+ updateTrackers: false,
+ plugins: false,
+ },
})
expect(r?.proxyRules).toBe('socks5=socks5://p.example.com:8080')
})
@@ -125,7 +170,12 @@ describe('proxyToDownloadRequestOptions', () => {
user: 'a@b',
password: 'p:s',
bypass: ['localhost', '127.0.0.0/8'],
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
})
).toEqual({
proxy: 'socks5://a%40b:p%[email protected]:8080',
@@ -143,7 +193,12 @@ describe('proxyToFetchUrl', () => {
expect(
proxyToFetchUrl({
...enabledHttp,
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
).toBe('http://p.example.com:8080')
})
diff --git a/src/core/tracker/tracker-manager.test.ts b/src/core/tracker/tracker-manager.test.ts
index 07bb40dd..0fcc5917 100644
--- a/src/core/tracker/tracker-manager.test.ts
+++ b/src/core/tracker/tracker-manager.test.ts
@@ -73,7 +73,12 @@ function createMockSettingsManager() {
user: '',
password: '',
bypass: [],
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}),
}
}
@@ -587,7 +592,12 @@ describe('TrackerManager', () => {
user: '',
password: '',
bypass: [],
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
await manager.syncAndCurate()
expect(syncer.fetch).toHaveBeenCalledWith(
@@ -617,7 +627,12 @@ describe('TrackerManager', () => {
user: '',
password: '',
bypass: [],
- scopes: { download: false, updateApp: false, updateTrackers: true },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: true,
+ plugins: false,
+ },
})
const resolveProxyUrl = vi.fn().mockResolvedValue('http://127.0.0.1:43123')
const bridgedManager = new TrackerManager(
diff --git a/src/main/index.ts b/src/main/index.ts
index 862aeeee..4c47a43f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -61,6 +61,7 @@ import {
parsePluginIdleDisposeMs,
} from '@core/plugin/host/plugin-host'
import { PluginInstaller } from '@core/plugin/install/plugin-installer'
+import { PluginHttpClient } from '@core/plugin/network/plugin-http-client'
import { PluginRegistry } from '@core/plugin/plugin-registry'
import { RegistryClient } from '@core/plugin/registry/registry-client'
import type { PluginHookRuntime } from '@core/plugin/runtime/plugin-hook-runtime'
@@ -499,6 +500,7 @@ const fileCleanupService = new FileCleanupServiceImpl({
let rpcClient: Aria2RpcClient
let supervisor: EngineSupervisor
+let pluginHttpClient: PluginHttpClient | undefined
let proxyBridge: ProxyBridgeManager
let speedLimitController: SpeedLimitController
let sessionManager: SessionManager
@@ -610,6 +612,7 @@ function performCleanup(): Promise<void> {
devWatcherHandle = null
await handle?.close()
}),
+ safely('plugin-network', () => pluginHttpClient?.close()),
safely('plugin-host', async () => {
await postDeliveryLoop
postDeliveryLoop = null
@@ -1574,6 +1577,7 @@ async function initializeMainProcess(): Promise<void> {
// settings (for window bounds/run mode) and WindowManager.
await settingsManager.load()
+ pluginHttpClient = new PluginHttpClient(() => settingsManager.getProxy())
if (!mainProcessWork.isAccepting()) return
let pluginLocaleTargets: {
@@ -2032,6 +2036,7 @@ async function initializeMainProcess(): Promise<void> {
const overlayDir = path.join(platform.userDataDir, 'builtin-updates')
const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH
const pluginSecurity = new PluginSecurityService({
+ fetchImpl: pluginHttpClient.fetch,
cachePath: path.join(platform.userDataDir, 'plugin-security.json'),
})
await pluginSecurity.initialize()
@@ -2791,9 +2796,11 @@ async function initializeMainProcess(): Promise<void> {
await activePluginHost.enforceSecurityPolicy()
pluginSecurity.start()
const registryClient = new RegistryClient({
+ fetchImpl: pluginHttpClient.fetch,
cachePath: path.join(platform.userDataDir, REGISTRY_CACHE_FILENAME),
})
const builtinUpdater = new BuiltinUpdater({
+ fetchImpl: pluginHttpClient.fetch,
security: pluginSecurity,
overlayDir,
hostVersion: app.getVersion(),
@@ -2940,6 +2947,7 @@ async function initializeMainProcess(): Promise<void> {
publishTaskUpdate,
publishTaskUpdateNow,
registryClient,
+ pluginFetch: pluginHttpClient.fetch,
hostVersion: app.getVersion(),
builtinUpdater,
overlayDir,
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 2ad7fc9b..952de4bb 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { access, mkdir, mkdtemp, realpath, rm, symlink } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
@@ -5,6 +6,7 @@ import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'
import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'
import { EventBus } from '@core/events/event-bus'
import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'
+import { PluginNetworkError } from '@core/plugin/network/plugin-network-error'
import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
import { SettingsManager } from '@core/settings/settings-manager'
import { ErrorCode } from '@shared/errors'
@@ -301,6 +303,60 @@ function fakeCtx() {
}
describe('buildCommandHandlers', () => {
+ it('downloads registry packages through the injected plugin transport and serializes failures', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'plugin-network-command-'))
+ try {
+ const bytes = new Uint8Array([1, 2, 3])
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response(bytes))
+ const entry = {
+ id: 'acme.plugin',
+ version: '1.0.0',
+ compatible: true,
+ engines: { motrix: '^2.0.0' },
+ permissions: [],
+ optionalPermissions: [],
+ hostPermissions: [],
+ package: {
+ url: 'https://github.com/acme/plugin/package.moext',
+ size: 3,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ },
+ }
+ const ctx = {
+ ...fakeCtx(),
+ userDataDir: dir,
+ pluginFetch: fetcher,
+ registryClient: { get: vi.fn().mockResolvedValue(entry) },
+ }
+ ctx.pluginInstaller.stage.mockResolvedValue({
+ committed: true,
+ pluginId: 'acme.plugin',
+ })
+ const handler = buildCommandHandlers(ctx as unknown as CommandContext)[
+ Commands.InstallPlugin
+ ]
+ await handler?.({ sourceType: 'registry', pluginId: 'acme.plugin' })
+ expect(fetcher).toHaveBeenCalledOnce()
+ expect(String(fetcher.mock.calls[0]?.[0])).toBe(entry.package.url)
+ expect(ctx.pluginInstaller.stage).toHaveBeenCalledOnce()
+ const failure = {
+ reason: 'proxyAuth' as const,
+ route: 'proxy' as const,
+ proxyEndpoint: '127.0.0.1:7897',
+ targetHost: 'github.com',
+ }
+ fetcher.mockRejectedValueOnce(new PluginNetworkError(failure))
+ await expect(
+ handler?.({ sourceType: 'registry', pluginId: 'acme.plugin' })
+ ).resolves.toEqual({ networkError: failure })
+ expect(ctx.pluginInstaller.stage).toHaveBeenCalledOnce()
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
it('returns the exact media-merge version requirement before downloading or requesting consent', async () => {
const ctx = {
...fakeCtx(),
@@ -1779,7 +1835,12 @@ describe('Commands.UpdateSettings', () => {
user: '',
password: '',
bypass: [],
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const PROXY_ON = { ...PROXY_OFF, enabled: true, host: 'p.example', port: 80 }
@@ -2034,11 +2095,21 @@ describe('Commands.UpdateSettings', () => {
const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })
const proxyA = {
...PROXY_ON,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const proxyB = {
...proxyA,
- scopes: { download: true, updateApp: true, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: true,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const before = makeSettingsLike(PROXY_OFF)
const afterA = makeSettingsLike(proxyA)
@@ -2097,7 +2168,12 @@ describe('Commands.UpdateSettings', () => {
const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })
const proxy = {
...PROXY_ON,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const before = makeSettingsLike(PROXY_OFF, {
app: { browserBridgeEnabled: false },
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 2e0bae0c..6c245cfe 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -31,6 +31,7 @@ import {
import type { SourceInput } from '@core/plugin/install/source-resolver'
import { downloadUrlMoext } from '@core/plugin/install/url-fetcher'
import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'
+import { PluginNetworkError } from '@core/plugin/network/plugin-network-error'
import type { OperationService } from '@core/plugin/operations/operation-service'
import type { PluginRegistry } from '@core/plugin/plugin-registry'
import type { RegistryClient } from '@core/plugin/registry/registry-client'
@@ -224,6 +225,7 @@ export interface CommandContext {
pluginStateStore: PluginStateStore
pluginHost: PluginHost
pluginInstaller: PluginInstaller
+ pluginFetch: typeof fetch
registryClient: RegistryClient
hostVersion: string
builtinUpdater: BuiltinUpdater
@@ -320,6 +322,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
pluginStateStore,
pluginHost,
pluginInstaller,
+ pluginFetch,
registryClient,
hostVersion,
builtinUpdater,
@@ -580,12 +583,12 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
downloadDir,
`${spec.owner}-${spec.repo}-${Date.now()}.moext`
)
- await downloadGithubMoext(spec, target)
+ await downloadGithubMoext(spec, target, pluginFetch)
return target
}
case 'url': {
const target = path.join(downloadDir, `download-${Date.now()}.moext`)
- await downloadUrlMoext(p.url, target)
+ await downloadUrlMoext(p.url, target, pluginFetch)
return target
}
case 'local':
@@ -1733,6 +1736,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
if (parsed.sourceType === 'registry') {
const entry = await registryClient.get(parsed.pluginId, hostVersion)
if (!entry) {
+ const failure = registryClient.status().error
+ if (failure) throw new PluginNetworkError(failure)
throw new AppError(
ErrorCode.PluginManifestInvalid,
'plugin.install.registry_entry_missing'
@@ -1751,7 +1756,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
'plugin-downloads',
`registry-${parsed.pluginId}-${Date.now()}.moext`
)
- await downloadRegistryMoext(entry, moextPath)
+ await downloadRegistryMoext(entry, moextPath, pluginFetch)
expect = buildRegistryExpectation(entry)
} else {
moextPath = await materializeMoext(parsed)
@@ -1771,6 +1776,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
}
return result
} catch (error) {
+ if (error instanceof PluginNetworkError)
+ return { networkError: error.failure }
if (error instanceof PluginEngineVersionTooOld) {
return {
incompatible: {
@@ -1792,38 +1799,48 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
},
[Commands.InstallBuiltinUpdate]: async (payload: unknown) => {
- const parsed = builtinUpdatePayloadSchema.parse(payload)
- const entry = await registryClient.get(parsed.pluginId, hostVersion)
- if (entry?.origin !== 'builtin') {
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- 'plugin.update.builtin_entry_missing'
- )
- }
- const effective = pluginRegistry.get(parsed.pluginId)?.manifest
- if (!effective) {
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- 'plugin.update.builtin_entry_missing'
+ try {
+ const parsed = builtinUpdatePayloadSchema.parse(payload)
+ const entry = await registryClient.get(parsed.pluginId, hostVersion)
+ if (!entry) {
+ const failure = registryClient.status().error
+ if (failure) throw new PluginNetworkError(failure)
+ }
+ if (entry?.origin !== 'builtin') {
+ throw new AppError(
+ ErrorCode.PluginManifestInvalid,
+ 'plugin.update.builtin_entry_missing'
+ )
+ }
+ const effective = pluginRegistry.get(parsed.pluginId)?.manifest
+ if (!effective) {
+ throw new AppError(
+ ErrorCode.PluginManifestInvalid,
+ 'plugin.update.builtin_entry_missing'
+ )
+ }
+ const staged = await builtinUpdater.stage(entry, effective)
+ if (staged.trustChanged) {
+ return { needsConsent: true, ...staged }
+ }
+ const wasActive = pluginHost.isActive(parsed.pluginId)
+ await builtinUpdater.commit(staged.stagingId)
+ const restartRequired = await reactivateBuiltin(
+ parsed.pluginId,
+ wasActive
)
+ // Same event ConfirmPluginInstall emits after a community install
+ // commits: usePlugins.onLifecycle refetches ListPlugins so the
+ // plugin's version/status/source.type (builtin -> builtin-update)
+ // update live, without a remount. Only on the committed path — a
+ // needsConsent return above has not touched disk yet.
+ eventBus.emit(Events.PluginInstalled, { pluginId: parsed.pluginId })
+ return { ok: true, restartRequired }
+ } catch (error) {
+ if (error instanceof PluginNetworkError)
+ return { networkError: error.failure }
+ throw error
}
- const staged = await builtinUpdater.stage(entry, effective)
- if (staged.trustChanged) {
- return { needsConsent: true, ...staged }
- }
- const wasActive = pluginHost.isActive(parsed.pluginId)
- await builtinUpdater.commit(staged.stagingId)
- const restartRequired = await reactivateBuiltin(
- parsed.pluginId,
- wasActive
- )
- // Same event ConfirmPluginInstall emits after a community install
- // commits: usePlugins.onLifecycle refetches ListPlugins so the
- // plugin's version/status/source.type (builtin -> builtin-update)
- // update live, without a remount. Only on the committed path — a
- // needsConsent return above has not touched disk yet.
- eventBus.emit(Events.PluginInstalled, { pluginId: parsed.pluginId })
- return { ok: true, restartRequired }
},
[Commands.ConfirmBuiltinUpdate]: async (payload: unknown) => {
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 59268689..8e176409 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -296,6 +296,8 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
[Queries.GetPluginManifest]: async (id: string) =>
pluginRegistry.get(id)?.manifest ?? null,
+ [Queries.GetRegistryStatus]: async () => registryClient.status(),
+
[Queries.ListRegistryPlugins]: async () => registryClient.list(hostVersion),
[Queries.GetRegistryPlugin]: async (id: string) =>
diff --git a/src/renderer/routes/plugins/components/builtin-update-dialog.tsx b/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
index 4a59c5b1..38986c06 100644
--- a/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
+++ b/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
@@ -10,8 +10,10 @@ import {
} from '@renderer/components/ui/dialog'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
+import type { PluginNetworkFailure } from '@shared/schemas/plugin-network'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { formatPluginNetworkFailure } from '../lib/network-error'
import { usePluginsStore } from '../store'
interface Props {
@@ -44,12 +46,20 @@ export function BuiltinUpdateDialog({ pluginId, open, onOpenChange }: Props) {
.invoke(Commands.InstallBuiltinUpdate, { pluginId })
.then((resp) => {
const r = resp as {
+ networkError?: PluginNetworkFailure
needsConsent?: boolean
stagingId?: string
added?: string[]
newVersion?: string
restartRequired?: boolean
}
+ if (r.networkError) {
+ setPhase({
+ kind: 'error',
+ message: formatPluginNetworkFailure(t, r.networkError),
+ })
+ return
+ }
if (r.needsConsent && r.stagingId) {
setPhase({
kind: 'consent',
@@ -73,7 +83,7 @@ export function BuiltinUpdateDialog({ pluginId, open, onOpenChange }: Props) {
message: e instanceof Error ? e.message : String(e),
})
})
- }, [open, pluginId, clearUpdate])
+ }, [open, pluginId, clearUpdate, t])
async function confirm() {
if (phase.kind !== 'consent') return
diff --git a/src/renderer/routes/plugins/components/registry-network-notice.tsx b/src/renderer/routes/plugins/components/registry-network-notice.tsx
new file mode 100644
index 00000000..6d31b421
--- /dev/null
+++ b/src/renderer/routes/plugins/components/registry-network-notice.tsx
@@ -0,0 +1,49 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from '@renderer/components/ui/alert'
+import { Button } from '@renderer/components/ui/button'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+import { formatPluginNetworkFailure } from '../lib/network-error'
+import { usePluginsStore } from '../store'
+
+export function RegistryNetworkNotice({
+ retry,
+ pending,
+}: {
+ retry(): Promise<void>
+ pending: boolean
+}) {
+ const { t } = useTranslation()
+ const status = usePluginsStore((state) => state.registryStatus)
+ if (!status?.error) return null
+ return (
+ <Alert>
+ <AlertTitle>
+ {t(
+ status.cached
+ ? 'plugins.network.cached'
+ : 'plugins.network.unavailable'
+ )}
+ </AlertTitle>
+ <AlertDescription>
+ {formatPluginNetworkFailure(t, status.error)}
+ </AlertDescription>
+ <div className="mt-2 flex gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={pending}
+ onClick={() => void retry()}
+ >
+ {t('common.retry')}
+ </Button>
+ <Button size="sm" variant="outline" render={<Link to="/settings" />}>
+ {t('nav.settings')}
+ </Button>
+ </div>
+ </Alert>
+ )
+}
diff --git a/src/renderer/routes/plugins/hooks/use-plugin-install.ts b/src/renderer/routes/plugins/hooks/use-plugin-install.ts
index fd521076..e3ee3b97 100644
--- a/src/renderer/routes/plugins/hooks/use-plugin-install.ts
+++ b/src/renderer/routes/plugins/hooks/use-plugin-install.ts
@@ -1,5 +1,6 @@
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
+import type { PluginNetworkFailureResult } from '@shared/schemas/plugin-network'
import type {
ConsentPayload,
GrantsMap,
@@ -7,6 +8,7 @@ import type {
} from '@shared/types/plugin-install'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { formatPluginNetworkFailure } from '../lib/network-error'
// Wire shape mirrors installPluginPayloadSchema in src/main/ipc/commands.ts.
// `fileHash` is the SHA-256 hex digest of the .moext file content — it
@@ -96,6 +98,12 @@ export function usePluginInstall() {
const r = (await transport.invoke(Commands.InstallPlugin, input)) as
| InstallResult
| PluginInstallCompatibilityFailure
+ | PluginNetworkFailureResult
+ if ('networkError' in r) {
+ if (request === requestRef.current && mountedRef.current)
+ setError(formatPluginNetworkFailure(t, r.networkError))
+ return false
+ }
// A dismissed download may finish after another install has started.
// Dispose its staging result without replacing the new dialog's state.
if (request !== requestRef.current || !mountedRef.current) {
diff --git a/src/renderer/routes/plugins/hooks/use-registry-updates.test.tsx b/src/renderer/routes/plugins/hooks/use-registry-updates.test.tsx
index 18d08042..75b8a5eb 100644
--- a/src/renderer/routes/plugins/hooks/use-registry-updates.test.tsx
+++ b/src/renderer/routes/plugins/hooks/use-registry-updates.test.tsx
@@ -32,7 +32,11 @@ const MIXED_UPDATES = [
describe('useRegistryUpdates', () => {
beforeEach(() => {
- usePluginsStore.setState({ updates: {}, registry: [] })
+ usePluginsStore.setState({
+ updates: {},
+ registry: [],
+ registryStatus: null,
+ })
mockInvoke.mockReset()
mockInvoke.mockImplementation((channel: string) => {
if (channel === Commands.CheckPluginUpdates) {
@@ -45,6 +49,35 @@ describe('useRegistryUpdates', () => {
})
})
+ it('exposes cached refresh errors and clears them after recovery', async () => {
+ let status = {
+ cached: true,
+ lastSuccessAt: 123,
+ error: {
+ reason: 'timeout',
+ route: 'proxy',
+ targetHost: 'dl.motrix.app',
+ proxyEndpoint: '127.0.0.1:7897',
+ } as unknown,
+ }
+ const original = mockInvoke.getMockImplementation()
+ mockInvoke.mockImplementation((channel: string) =>
+ channel === Queries.GetRegistryStatus
+ ? Promise.resolve(status)
+ : original?.(channel)
+ )
+ const { result } = renderHook(() => useRegistryUpdates(true))
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(usePluginsStore.getState().registryStatus?.error?.reason).toBe(
+ 'timeout'
+ )
+ status = { ...status, error: null }
+ await act(async () => result.current.refresh())
+ expect(usePluginsStore.getState().registryStatus?.error).toBeNull()
+ })
+
it('never invokes CheckPluginUpdates when enabled=false, even via refresh()', async () => {
const { result } = renderHook(() => useRegistryUpdates(false))
@@ -64,7 +97,8 @@ describe('useRegistryUpdates', () => {
await Promise.resolve()
})
- expect(mockInvoke).toHaveBeenCalledTimes(1)
+ expect(mockInvoke).toHaveBeenCalledTimes(2)
+ expect(mockInvoke).toHaveBeenCalledWith(Queries.GetRegistryStatus)
expect(mockInvoke).toHaveBeenCalledWith(Commands.CheckPluginUpdates, {})
expect(usePluginsStore.getState().updates).toEqual({
'acme.speed-boost': { latestVersion: '1.1.0', channel: 'community' },
diff --git a/src/renderer/routes/plugins/hooks/use-registry.ts b/src/renderer/routes/plugins/hooks/use-registry.ts
index 79bd73fa..73c8ace2 100644
--- a/src/renderer/routes/plugins/hooks/use-registry.ts
+++ b/src/renderer/routes/plugins/hooks/use-registry.ts
@@ -1,10 +1,18 @@
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
+import { registryStatusSchema } from '@shared/schemas/plugin-network'
import type { RegistryPluginDTO } from '@shared/schemas/registry'
import { useEffect, useState } from 'react'
import { type UpdateChannel, usePluginsStore } from '../store'
+async function readRegistryStatus(): Promise<void> {
+ const result = registryStatusSchema.safeParse(
+ await transport.invoke(Queries.GetRegistryStatus)
+ )
+ if (result.success) usePluginsStore.getState().setRegistryStatus(result.data)
+}
+
/**
* Remote-registry directory for the marketplace list. The main process
* serves last-good cached data (RegistryClient), so this resolves offline;
@@ -16,10 +24,14 @@ export function useRegistryPlugins(): RegistryPluginDTO[] {
useEffect(() => {
let cancelled = false
- void transport.invoke(Queries.ListRegistryPlugins).then((resp) => {
- if (cancelled) return
- setRegistry((resp as RegistryPluginDTO[]) ?? [])
- })
+ void transport
+ .invoke(Queries.ListRegistryPlugins)
+ .then(async (resp) => {
+ if (cancelled) return
+ setRegistry((resp as RegistryPluginDTO[]) ?? [])
+ await readRegistryStatus()
+ })
+ .catch(() => undefined)
return () => {
cancelled = true
}
@@ -51,10 +63,15 @@ export function useRegistryEntry(id: string): {
useEffect(() => {
if (fromStore) return
let cancelled = false
- void transport.invoke(Queries.GetRegistryPlugin, id).then((resp) => {
- if (cancelled) return
- setFetched({ id, entry: (resp as RegistryPluginDTO | null) ?? null })
- })
+ void transport
+ .invoke(Queries.GetRegistryPlugin, id)
+ .then(async (resp) => {
+ if (cancelled) return
+ await readRegistryStatus()
+ if (!cancelled)
+ setFetched({ id, entry: (resp as RegistryPluginDTO | null) ?? null })
+ })
+ .catch(() => undefined)
return () => {
cancelled = true
}
@@ -99,10 +116,14 @@ export function useRegistryUpdates(enabled: boolean): {
useEffect(() => {
if (!enabled) return
let cancelled = false
- void transport.invoke(Commands.CheckPluginUpdates, {}).then((resp) => {
- if (cancelled) return
- setUpdates(toUpdatesMap(resp))
- })
+ void transport
+ .invoke(Commands.CheckPluginUpdates, {})
+ .then(async (resp) => {
+ if (cancelled) return
+ setUpdates(toUpdatesMap(resp))
+ await readRegistryStatus()
+ })
+ .catch(() => undefined)
return () => {
cancelled = true
}
@@ -118,6 +139,7 @@ export function useRegistryUpdates(enabled: boolean): {
const entries = await transport.invoke(Queries.ListRegistryPlugins)
setUpdates(toUpdatesMap(updates))
setRegistry((entries as RegistryPluginDTO[]) ?? [])
+ await readRegistryStatus()
} catch {
// Silent degrade per the registry client contract: last-good data
// keeps serving; a failed manual refresh must not surface as an
diff --git a/src/renderer/routes/plugins/lib/network-error.ts b/src/renderer/routes/plugins/lib/network-error.ts
new file mode 100644
index 00000000..e9c8496e
--- /dev/null
+++ b/src/renderer/routes/plugins/lib/network-error.ts
@@ -0,0 +1,22 @@
+import type { PluginNetworkFailure } from '@shared/schemas/plugin-network'
+import type { TFunction } from 'i18next'
+
+export function formatPluginNetworkFailure(
+ t: TFunction,
+ failure: PluginNetworkFailure
+): string {
+ const reason = t(`plugins.network.${failure.reason}`, {
+ status: failure.status ?? '',
+ })
+ if (!failure.route) return reason
+ return t(
+ failure.route === 'proxy'
+ ? 'plugins.network.viaProxy'
+ : 'plugins.network.direct',
+ {
+ host: failure.targetHost,
+ proxy: failure.proxyEndpoint ?? '',
+ reason,
+ }
+ )
+}
diff --git a/src/renderer/routes/plugins/plugin-detail-page.tsx b/src/renderer/routes/plugins/plugin-detail-page.tsx
index 4cfdd9f0..8850979f 100644
--- a/src/renderer/routes/plugins/plugin-detail-page.tsx
+++ b/src/renderer/routes/plugins/plugin-detail-page.tsx
@@ -50,6 +50,7 @@ import { PluginSettingsForm } from './components/plugin-settings-form'
import { PluginStatusDot } from './components/plugin-status-dot'
import { RegistryDetailPanel } from './components/registry-detail-panel'
import { RegistryInstallAction } from './components/registry-install-action'
+import { RegistryNetworkNotice } from './components/registry-network-notice'
import { UninstallSection } from './components/uninstall-section'
import { usePluginDetail } from './hooks/use-plugin-detail'
import { usePlugins } from './hooks/use-plugins'
@@ -98,8 +99,12 @@ export function PluginDetailPage() {
// installed list nor the registry do we bounce to the list with a toast.
const { checked: registryChecked, entry: registryEntry } =
useRegistryEntry(id)
+ const registryFailure = usePluginsStore(
+ (state) => state.registryStatus?.error
+ )
useEffect(() => {
if (pluginsLoaded && !listEntry && registryChecked && !registryEntry) {
+ if (registryFailure) return
toast.add({ title: t('plugins.registry.notFound', { id }) })
navigate('/plugins', { replace: true })
}
@@ -107,6 +112,7 @@ export function PluginDetailPage() {
pluginsLoaded,
listEntry,
registryChecked,
+ registryFailure,
registryEntry,
navigate,
t,
@@ -114,6 +120,8 @@ export function PluginDetailPage() {
])
if (!detail || !listEntry) {
+ if (registryFailure && !registryEntry)
+ return <RegistryNetworkNotice retry={refresh} pending={refreshing} />
if (pluginsLoaded && !listEntry && registryEntry) {
return <RegistryDetailPanel entry={registryEntry} />
}
diff --git a/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx b/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx
index 5e34793f..4c490a1d 100644
--- a/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx
+++ b/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx
@@ -88,6 +88,32 @@ describe('PluginInstallDialog with fixedSource', () => {
expect(mockInvoke).toHaveBeenCalledTimes(1)
})
+ it('renders a structured proxy timeout without exposing an IPC error', async () => {
+ mockInvoke.mockResolvedValueOnce({
+ networkError: {
+ reason: 'timeout',
+ route: 'proxy',
+ proxyEndpoint: '127.0.0.1:7897',
+ targetHost: 'github.com',
+ },
+ })
+ render(
+ <PluginInstallDialog
+ open
+ onOpenChange={vi.fn()}
+ fixedSource={{ sourceType: 'registry', pluginId: 'acme.speed-boost' }}
+ />
+ )
+ expect(
+ await screen.findByText(
+ 'Connection to github.com via proxy 127.0.0.1:7897 failed: Connection timed out'
+ )
+ ).toBeVisible()
+ expect(screen.queryByTestId('consent-panel')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ expect(await screen.findByTestId('consent-panel')).toBeVisible()
+ })
+
it('offers retry after a download fails without returning to manual source entry', async () => {
mockInvoke.mockRejectedValueOnce(new Error('Download failed'))
render(
diff --git a/src/renderer/routes/plugins/plugins-page.tsx b/src/renderer/routes/plugins/plugins-page.tsx
index 9d254e71..a08cb132 100644
--- a/src/renderer/routes/plugins/plugins-page.tsx
+++ b/src/renderer/routes/plugins/plugins-page.tsx
@@ -20,6 +20,7 @@ import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
import { PluginCard } from './components/plugin-card'
import { PluginGuidance } from './components/plugin-guidance'
+import { RegistryNetworkNotice } from './components/registry-network-notice'
import { RegistryPluginCard } from './components/registry-plugin-card'
import { useCallGraphPreload } from './hooks/use-call-graph-preload'
import { usePlugins } from './hooks/use-plugins'
@@ -144,6 +145,7 @@ export function PluginsPage() {
</div>
) : (
<div className="flex w-full flex-col gap-4">
+ <RegistryNetworkNotice retry={refresh} pending={refreshing} />
<PluginGuidance hasUserManagedPlugin={hasUserManagedPlugin} />
{plugins.length === 0 ? null : filtered.length === 0 ? (
diff --git a/src/renderer/routes/plugins/store.ts b/src/renderer/routes/plugins/store.ts
index 8d3cc09c..f08234b4 100644
--- a/src/renderer/routes/plugins/store.ts
+++ b/src/renderer/routes/plugins/store.ts
@@ -1,3 +1,4 @@
+import type { RegistryStatus } from '@shared/schemas/plugin-network'
import type { RegistryPluginDTO } from '@shared/schemas/registry'
import type {
PluginListDTO,
@@ -28,6 +29,8 @@ interface PluginsState {
// Remote-registry directory (dl.motrix.app via RegistryClient in main).
// Kept beside the installed list so the page can partition
// installed-vs-available by id.
+ registryStatus: RegistryStatus | null
+ setRegistryStatus(status: RegistryStatus): void
registry: RegistryPluginDTO[]
// pluginId → latest version + channel, from Commands.CheckPluginUpdates.
// channel distinguishes a community-registry update (routes to
@@ -57,6 +60,8 @@ export const usePluginsStore = create<PluginsState>((set) => ({
detail: {},
grants: {},
registry: [],
+ registryStatus: null,
+ setRegistryStatus: (registryStatus) => set({ registryStatus }),
updates: {},
setList: (list) => set({ list, loaded: true }),
setRegistry: (registry) => set({ registry }),
diff --git a/src/renderer/routes/settings/cards/network-dialog.test.tsx b/src/renderer/routes/settings/cards/network-dialog.test.tsx
index 32e6968a..14681179 100644
--- a/src/renderer/routes/settings/cards/network-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/network-dialog.test.tsx
@@ -38,7 +38,12 @@ const FIXTURE = {
user: '',
password: '',
bypass: [],
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
},
nat: {
enabled: true,
@@ -271,10 +276,40 @@ describe('<NetworkDialog>', () => {
await screen.findByRole('menuitemcheckbox', { name: 'File downloads' })
).toHaveAttribute('aria-checked', 'true')
expect(
- screen.getByText('BT peers, DHT and UDP trackers connect directly.')
+ screen.getByText(/BT peers, DHT and UDP trackers connect directly\./)
).toBeVisible()
})
+ it('saves plugin proxying independently of the other uses', async () => {
+ render(<NetworkDialog open onClose={vi.fn()} labelKey="" descKey="" />)
+ const user = userEvent.setup()
+ await user.click(
+ await screen.findByRole('button', { name: /import from system/i })
+ )
+ await user.click(screen.getByRole('button', { name: 'Use proxy for' }))
+ const plugins = await screen.findByRole('menuitemcheckbox', {
+ name: 'Plugin installation and updates',
+ })
+ expect(plugins).toHaveAttribute('aria-checked', 'false')
+ await user.click(plugins)
+ expect(plugins).toHaveAttribute('aria-checked', 'true')
+ expect(
+ screen.getByRole('menuitemcheckbox', { name: 'File downloads' })
+ ).toHaveAttribute('aria-checked', 'false')
+ await user.keyboard('{Escape}')
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.UpdateSettings,
+ expect.objectContaining({
+ proxy: expect.objectContaining({
+ scopes: { plugins: true },
+ }),
+ })
+ )
+ )
+ })
+
it('shows an actionable error for an enabled proxy without a server', async () => {
const onClose = vi.fn()
render(<NetworkDialog open onClose={onClose} labelKey="" descKey="" />)
diff --git a/src/renderer/routes/settings/cards/proxy-section.tsx b/src/renderer/routes/settings/cards/proxy-section.tsx
index 1d5e9ca0..02950163 100644
--- a/src/renderer/routes/settings/cards/proxy-section.tsx
+++ b/src/renderer/routes/settings/cards/proxy-section.tsx
@@ -43,13 +43,19 @@ import { useTranslation } from 'react-i18next'
import type { NetworkFields } from './network-dialog'
type ProxyScope = keyof ProxySettings['scopes']
-const PROXY_SCOPES: ProxyScope[] = ['download', 'updateApp', 'updateTrackers']
+const PROXY_SCOPES: ProxyScope[] = [
+ 'download',
+ 'plugins',
+ 'updateApp',
+ 'updateTrackers',
+]
export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {
const { t } = useTranslation()
const scopes = form.watch('proxy.scopes')
const scopeLabels: Record<ProxyScope, string> = {
download: t('settings.network.proxy.scopeDownload'),
+ plugins: t('settings.network.proxy.scopePlugins'),
updateApp: t('settings.network.proxy.scopeUpdateApp'),
updateTrackers: t('settings.network.proxy.scopeUpdateTrackers'),
}
@@ -433,6 +439,8 @@ export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {
))}
<DropdownMenuSeparator />
<p className="px-2 py-1.5 text-xs leading-relaxed text-muted-foreground">
+ {t('settings.network.proxy.scopePluginsDesc')}
+ <br />
{t('settings.network.proxy.scopeHint')}
</p>
</DropdownMenuContent>
diff --git a/src/server/index.ts b/src/server/index.ts
index d4d38191..1b5dba70 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -66,6 +66,7 @@ import {
parsePluginIdleDisposeMs,
} from '@core/plugin/host/plugin-host'
import { PluginInstaller } from '@core/plugin/install/plugin-installer'
+import { PluginHttpClient } from '@core/plugin/network/plugin-http-client'
import { PluginRegistry } from '@core/plugin/plugin-registry'
import { RegistryClient } from '@core/plugin/registry/registry-client'
import type { PluginHookRuntime } from '@core/plugin/runtime/plugin-hook-runtime'
@@ -377,6 +378,10 @@ async function main() {
}
)
await settingsManager.load()
+ const pluginHttpClient = new PluginHttpClient(() =>
+ settingsManager.getProxy()
+ )
+ shutdownActions.closePluginNetwork = () => pluginHttpClient.close()
if (!shellAsyncWork.isAccepting()) return
const activeGeoipManager = new GeoIPManager({
settingsManager,
@@ -541,6 +546,7 @@ async function main() {
const pluginStateStore = new PluginStateStore(db.database)
const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH
const pluginSecurity = new PluginSecurityService({
+ fetchImpl: pluginHttpClient.fetch,
cachePath: path.join(platform.userDataDir, 'plugin-security.json'),
})
await pluginSecurity.initialize()
@@ -633,6 +639,7 @@ async function main() {
const hostVersion = appVersion
const registryClient = new RegistryClient({
+ fetchImpl: pluginHttpClient.fetch,
cachePath: path.join(platform.userDataDir, REGISTRY_CACHE_FILENAME),
})
const pluginInstaller = new PluginInstaller({
@@ -651,6 +658,7 @@ async function main() {
await pluginUploadStore.cleanupExpired()
shutdownActions.closeIngress = () => pluginUploadStore.dispose()
const pluginInstallService = new ServerPluginInstallService({
+ fetchImpl: pluginHttpClient.fetch,
installer: pluginInstaller,
registryClient,
hostVersion,
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index d46b76ae..4fde89d5 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -53,7 +53,12 @@ const PROXY_OFF = {
user: '',
password: '',
bypass: [] as string[],
- scopes: { download: false, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const PROXY_ON = { ...PROXY_OFF, enabled: true, host: 'p.example', port: 80 }
@@ -766,11 +771,21 @@ describe('server Commands.UpdateSettings', () => {
const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })
const proxyA = {
...PROXY_ON,
- scopes: { download: true, updateApp: false, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const proxyB = {
...proxyA,
- scopes: { download: true, updateApp: true, updateTrackers: false },
+ scopes: {
+ download: true,
+ updateApp: true,
+ updateTrackers: false,
+ plugins: false,
+ },
}
const before = makeSettings(PROXY_OFF)
const afterA = makeSettings(proxyA)
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index d31e4735..d56ae561 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -19,6 +19,7 @@ import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatch
import type { PluginHost } from '@core/plugin/host/plugin-host'
import type { PluginInstaller } from '@core/plugin/install/plugin-installer'
import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'
+import { PluginNetworkError } from '@core/plugin/network/plugin-network-error'
import { operationHandlers } from '@core/plugin/operations/operation-handlers'
import type { OperationService } from '@core/plugin/operations/operation-service'
import type { PluginRegistry } from '@core/plugin/plugin-registry'
@@ -1049,6 +1050,8 @@ export function buildServerCommandHandlers(
}
return result
} catch (error) {
+ if (error instanceof PluginNetworkError)
+ return { networkError: error.failure }
if (error instanceof PluginEngineVersionTooOld) {
return {
incompatible: {
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index c9aa9778..8815e68a 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -341,6 +341,8 @@ export function buildServerQueryHandlers(
[Queries.ListPlugins]: async () => pluginRegistry.list(),
// Parity with the Electron shell: remote-registry directory reads.
+ [Queries.GetRegistryStatus]: async () => registryClient.status(),
+
[Queries.ListRegistryPlugins]: async () => registryClient.list(hostVersion),
[Queries.GetRegistryPlugin]: async (id: string) =>
diff --git a/src/server/plugin/install-service.test.ts b/src/server/plugin/install-service.test.ts
index 9be78f5b..ba85d8f2 100644
--- a/src/server/plugin/install-service.test.ts
+++ b/src/server/plugin/install-service.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import {
mkdir,
mkdtemp,
@@ -46,6 +47,50 @@ function makeService(overrides: Record<string, unknown> = {}) {
}
describe('ServerPluginInstallService', () => {
+ it('uses the injected transport for registry and GitHub installation', async () => {
+ const bytes = new Uint8Array([1, 2, 3])
+ const entry = {
+ id: 'acme.plugin',
+ version: '1.0.0',
+ compatible: true,
+ engines: { motrix: '^2.0.0' },
+ permissions: [],
+ optionalPermissions: [],
+ hostPermissions: [],
+ package: {
+ url: 'https://github.com/acme/plugin/package.moext',
+ size: 3,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ },
+ }
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response(bytes))
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ tag_name: 'v1',
+ assets: [
+ { name: 'plugin.moext', browser_download_url: entry.package.url },
+ ],
+ })
+ )
+ )
+ .mockResolvedValueOnce(new Response(bytes))
+ const { service, stage } = makeService({
+ fetchImpl,
+ registryClient: { get: vi.fn().mockResolvedValue(entry) },
+ })
+ await service.stage({ sourceType: 'registry', pluginId: 'acme.plugin' })
+ await service.stage({ sourceType: 'github', spec: 'acme/plugin' })
+ expect(fetchImpl).toHaveBeenCalledTimes(3)
+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe(entry.package.url)
+ expect(fetchImpl.mock.calls[1]?.[0]).toBe(
+ 'https://api.github.com/repos/acme/plugin/releases/latest'
+ )
+ expect(stage).toHaveBeenCalledTimes(2)
+ })
+
it('rejects incompatible media-merge before downloading or staging its package', async () => {
const fetchImpl = vi.fn()
const { service, stage } = makeService({
diff --git a/src/server/plugin/install-service.ts b/src/server/plugin/install-service.ts
index e17ad726..aeed9f3d 100644
--- a/src/server/plugin/install-service.ts
+++ b/src/server/plugin/install-service.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto'
-import { mkdir, realpath, rm, stat, writeFile } from 'node:fs/promises'
+import { mkdir, realpath, rm, stat } from 'node:fs/promises'
import path from 'node:path'
import {
downloadGithubMoext,
@@ -15,7 +15,9 @@ import {
type RegistryExpectation,
} from '@core/plugin/install/registry-expectation'
import type { SourceInput } from '@core/plugin/install/source-resolver'
+import { downloadUrlMoext } from '@core/plugin/install/url-fetcher'
import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'
+import { PluginNetworkError } from '@core/plugin/network/plugin-network-error'
import type { RegistryClient } from '@core/plugin/registry/registry-client'
import { downloadRegistryMoext } from '@core/plugin/registry/registry-fetcher'
import { AppError, ErrorCode } from '@shared/errors'
@@ -23,8 +25,6 @@ import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'
import { z } from 'zod'
import type { PluginUploadStore } from './upload-store'
-const MAX_PLUGIN_PACKAGE_BYTES = 5 * 1024 * 1024
-
export const serverInstallPluginPayloadSchema = z.discriminatedUnion(
'sourceType',
[
@@ -71,68 +71,6 @@ function pathIsInside(root: string, candidate: string): boolean {
)
}
-async function cancelResponseBody(response: Response): Promise<void> {
- try {
- await response.body?.cancel()
- } catch {
- // Preserve the install error if cancellation races a closed/erroring body.
- }
-}
-
-async function cancelReader(
- reader: ReadableStreamDefaultReader<Uint8Array>
-): Promise<void> {
- try {
- await reader.cancel()
- } catch {
- // Cancellation is best-effort and must not mask the bounded-read error.
- }
-}
-
-async function readResponseBounded(response: Response): Promise<Buffer> {
- const declaredLength = Number(response.headers.get('content-length'))
- if (
- Number.isFinite(declaredLength) &&
- declaredLength > MAX_PLUGIN_PACKAGE_BYTES
- ) {
- await cancelResponseBody(response)
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- 'plugin.install.package_too_large'
- )
- }
- if (!response.body) {
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- 'plugin.install.url_download_failed: empty body'
- )
- }
-
- const chunks: Uint8Array[] = []
- let total = 0
- const reader = response.body.getReader()
- try {
- for (;;) {
- const { done, value } = await reader.read()
- if (done) break
- total += value.byteLength
- if (total > MAX_PLUGIN_PACKAGE_BYTES) {
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- 'plugin.install.package_too_large'
- )
- }
- chunks.push(value)
- }
- } catch (cause) {
- await cancelReader(reader)
- throw cause
- } finally {
- reader.releaseLock()
- }
- return Buffer.concat(chunks, total)
-}
-
export class ServerPluginInstallService {
private readonly downloadsDir: string
private readonly allowedLocalRoots: readonly string[]
@@ -177,7 +115,7 @@ export class ServerPluginInstallService {
case 'github': {
const spec = parseGithubSpec(payload.spec)
const target = this.downloadPath('github')
- await downloadGithubMoext(spec, target)
+ await downloadGithubMoext(spec, target, this.fetchImpl)
return {
moextPath: target,
source: { type: 'github', spec: payload.spec },
@@ -186,18 +124,8 @@ export class ServerPluginInstallService {
}
case 'url': {
const url = this.parseHttpUrl(payload.url)
- const response = await this.fetchImpl(url, { redirect: 'follow' })
- if (!response.ok) {
- await cancelResponseBody(response)
- throw new AppError(
- ErrorCode.PluginManifestInvalid,
- `plugin.install.url_download_failed: ${response.status}`
- )
- }
const target = this.downloadPath('url')
- await writeFile(target, await readResponseBounded(response), {
- mode: 0o600,
- })
+ await downloadUrlMoext(url.toString(), target, this.fetchImpl)
return {
moextPath: target,
source: { type: 'url', url: payload.url },
@@ -243,6 +171,8 @@ export class ServerPluginInstallService {
this.options.hostVersion
)
if (!entry) {
+ const failure = this.options.registryClient.status().error
+ if (failure) throw new PluginNetworkError(failure)
throw new AppError(
ErrorCode.PluginManifestInvalid,
'plugin.install.registry_entry_missing'
diff --git a/src/server/shutdown.ts b/src/server/shutdown.ts
index b80975fc..034ae76f 100644
--- a/src/server/shutdown.ts
+++ b/src/server/shutdown.ts
@@ -8,6 +8,7 @@ export interface ServerShutdownActions {
* the emit-coalescing design; runs before every ingress teardown.
*/
flushTaskUpdates?: ShutdownAction
+ closePluginNetwork?: ShutdownAction
stopPolling: ShutdownAction
closeIngress: ShutdownAction
closeBridge: ShutdownAction
@@ -74,6 +75,7 @@ export function createServerShutdown(
safely('rpc-notifications', actions.unsubscribeProducers),
safely('dev-watcher', actions.drainDevWatcher),
safely('plugin-host', actions.drainPluginHost),
+ safely('plugin-network', () => actions.closePluginNetwork?.()),
safely('magnet', actions.drainMagnet),
safely('geoip', actions.stopGeoIP),
safely('speed-limit', actions.stopSpeedLimit),
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 559653a7..0f66edd3 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -14,6 +14,7 @@ export enum ErrorCode {
TaskPathTooLong = 'TASK_PATH_TOO_LONG',
SessionRestoreFailed = 'SESSION_RESTORE_FAILED',
SettingsInvalid = 'SETTINGS_INVALID',
+ PluginNetworkFailed = 'PLUGIN_NETWORK_FAILED',
PluginTimeout = 'PLUGIN_TIMEOUT',
PluginExecutionFailed = 'PLUGIN_EXECUTION_FAILED',
PluginLoadFailed = 'PLUGIN_LOAD_FAILED',
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 15aebf7d..15ff16be 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -1762,6 +1762,20 @@
"compromised": "تم اختراق قناة توزيع هذه الإضافة.",
"fixedVersion": "يتوفر إصلاح في الإصدار {{version}}.",
"details": "عرض التنبيه الأمني"
+ },
+ "network": {
+ "timeout": "انتهت مهلة الاتصال",
+ "dns": "فشل البحث عن DNS",
+ "proxyAuth": "فشلت مصادقة الوكيل",
+ "proxyConnect": "تعذر الاتصال بالوكيل",
+ "certificate": "خطأ في الشهادة أو TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "تم إلغاء الطلب",
+ "network": "فشل طلب الشبكة",
+ "cached": "فشل التحديث؛ تُعرض الإضافات المخزنة مؤقتًا",
+ "unavailable": "تعذر تحميل كتالوج الإضافات",
+ "direct": "فشل الاتصال المباشر بـ {{host}}: {{reason}}",
+ "viaProxy": "فشل الاتصال بـ {{host}} عبر الوكيل {{proxy}}: {{reason}}"
}
},
"quit": {
@@ -2670,7 +2684,7 @@
"bypass": "الاتصال مباشرةً بـ",
"bypassDesc": "نطاق أو عنوان IP أو CIDR واحد في كل سطر. ابدأ بنقطة لمطابقة النطاقات الفرعية فقط. لا تدعم تنزيلات الملفات محرف البدل *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "تنزيلات الملفات وتحديثات التطبيق فقط",
+ "bypassScopeNote": "التنزيلات والإضافات وتحديثات التطبيق فقط",
"enable": "تفعيل الوكيل",
"enableDesc": "استخدام وكيل للاتصالات المحددة أدناه.",
"hidePassword": "إخفاء كلمة المرور",
@@ -2697,7 +2711,9 @@
"server": "الخادم",
"showPassword": "إظهار كلمة المرور",
"title": "الوكيل",
- "user": "اسم المستخدم"
+ "user": "اسم المستخدم",
+ "scopePlugins": "تثبيت الإضافات وتحديثها",
+ "scopePluginsDesc": "استخدام الوكيل لكتالوج الإضافات وحزم التثبيت والتحديثات وطلبات سياسة الأمان."
},
"reachability": {
"addEndpoint": "إضافة خدمة فحص",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 67a514ae..a9f0fea0 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -1690,6 +1690,20 @@
"compromised": "Каналът за разпространение на тази добавка е компрометиран.",
"fixedVersion": "Поправка е налична във версия {{version}}.",
"details": "Преглед на известието за сигурност"
+ },
+ "network": {
+ "timeout": "Времето за връзка изтече",
+ "dns": "Неуспешно DNS разрешаване",
+ "proxyAuth": "Неуспешно удостоверяване на прокси",
+ "proxyConnect": "Няма връзка с прокси сървъра",
+ "certificate": "Грешка в сертификата или TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Заявката е отменена",
+ "network": "Неуспешна мрежова заявка",
+ "cached": "Обновяването е неуспешно; показват се кеширани добавки",
+ "unavailable": "Каталогът с добавки не може да се зареди",
+ "direct": "Неуспешна директна връзка с {{host}}: {{reason}}",
+ "viaProxy": "Неуспешна връзка с {{host}} чрез прокси {{proxy}}: {{reason}}"
}
},
"quit": {
@@ -2590,7 +2604,7 @@
"bypass": "Директно свързване към",
"bypassDesc": "По един домейн, IP адрес или CIDR на ред. Започнете с . за съвпадение само с поддомейни. Изтеглянето на файлове не поддържа заместващия знак *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Само за изтегляне на файлове и актуализации на приложението",
+ "bypassScopeNote": "Само изтегляния, добавки и обновявания на приложението",
"enable": "Включване на прокси",
"enableDesc": "Използва прокси за избраните по-долу връзки.",
"hidePassword": "Скриване на паролата",
@@ -2617,7 +2631,9 @@
"server": "Сървър",
"showPassword": "Показване на паролата",
"title": "Прокси",
- "user": "Потребителско име"
+ "user": "Потребителско име",
+ "scopePlugins": "Инсталиране и обновяване на добавки",
+ "scopePluginsDesc": "Използвайте прокси за каталога, пакетите, обновяванията и правилата за сигурност на добавките."
},
"reachability": {
"addEndpoint": "Добавяне на услуга за проверка",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index bc084081..78eefcf4 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -1708,6 +1708,20 @@
"compromised": "La distribució d’aquest connector s’ha vist compromesa.",
"fixedVersion": "Hi ha una correcció disponible a la versió {{version}}.",
"details": "Mostra l’avís de seguretat"
+ },
+ "network": {
+ "timeout": "S’ha esgotat el temps de connexió",
+ "dns": "Error de resolució DNS",
+ "proxyAuth": "Error d’autenticació del servidor intermediari",
+ "proxyConnect": "No s’ha pogut connectar al servidor intermediari",
+ "certificate": "Error de certificat o TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Sol·licitud cancel·lada",
+ "network": "Error de sol·licitud de xarxa",
+ "cached": "No s’ha pogut actualitzar; es mostren els connectors de la memòria cau",
+ "unavailable": "No s’ha pogut carregar el catàleg de connectors",
+ "direct": "Ha fallat la connexió directa a {{host}}: {{reason}}",
+ "viaProxy": "Ha fallat la connexió a {{host}} mitjançant el servidor intermediari {{proxy}}: {{reason}}"
}
},
"quit": {
@@ -2610,7 +2624,7 @@
"bypass": "Connectar directament a",
"bypassDesc": "Un domini, una IP o un CIDR per línia. Comenceu amb . per incloure només els subdominis. Les baixades de fitxers no admeten comodins *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Només baixades de fitxers i actualitzacions de l'aplicació",
+ "bypassScopeNote": "Només baixades, connectors i actualitzacions de l’aplicació",
"enable": "Activar el servidor intermediari",
"enableDesc": "Utilitza un servidor intermediari per a les connexions seleccionades a continuació.",
"hidePassword": "Amagar la contrasenya",
@@ -2637,7 +2651,9 @@
"server": "Servidor",
"showPassword": "Mostrar la contrasenya",
"title": "Servidor intermediari",
- "user": "Nom d'usuari"
+ "user": "Nom d'usuari",
+ "scopePlugins": "Instal·lació i actualització de connectors",
+ "scopePluginsDesc": "Utilitza el servidor intermediari per al catàleg, els paquets, les actualitzacions i les polítiques de seguretat dels connectors."
},
"reachability": {
"addEndpoint": "Afegir un servei de comprovació",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index 7b780f2f..7346a509 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1707,7 +1707,7 @@
"hidePassword": "Passwort ausblenden",
"bypass": "Direkt verbinden mit",
"bypassDesc": "Eine Domain, IP-Adresse oder CIDR-Angabe pro Zeile. Mit . beginnen, um nur Subdomains zu erfassen. Datei-Downloads unterstützen keine *-Platzhalter.",
- "bypassScopeNote": "Nur Datei-Downloads und App-Updates",
+ "bypassScopeNote": "Nur Downloads, Plugins und App-Updates",
"scopes": "Proxy verwenden für",
"scopesDesc": "Wählen Sie aus, welcher Datenverkehr über den Proxy läuft.",
"scopeDownload": "Datei-Downloads",
@@ -1723,7 +1723,9 @@
"scopeHint": "BT-Peers, DHT und UDP-Tracker verbinden sich direkt.",
"scopeNone": "Nichts ausgewählt",
"scopeChoose": "Auswählen…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Plugin-Installation und Updates",
+ "scopePluginsDesc": "Proxy für den Plugin-Katalog, Installationspakete, Updates und Sicherheitsrichtlinien verwenden."
},
"nat": {
"title": "Portweiterleitung (NAT)",
@@ -2721,6 +2723,20 @@
"compromised": "Der Vertriebsweg dieses Plugins wurde kompromittiert.",
"fixedVersion": "Eine Korrektur ist in Version {{version}} verfügbar.",
"details": "Sicherheitshinweis anzeigen"
+ },
+ "network": {
+ "timeout": "Zeitüberschreitung beim Verbindungsaufbau",
+ "dns": "DNS-Auflösung fehlgeschlagen",
+ "proxyAuth": "Proxy-Authentifizierung fehlgeschlagen",
+ "proxyConnect": "Verbindung zum Proxy nicht möglich",
+ "certificate": "Zertifikats- oder TLS-Fehler",
+ "http": "HTTP {{status}}",
+ "cancelled": "Anfrage abgebrochen",
+ "network": "Netzwerkanfrage fehlgeschlagen",
+ "cached": "Aktualisierung fehlgeschlagen; zwischengespeicherte Plugins werden angezeigt",
+ "unavailable": "Plugin-Katalog konnte nicht geladen werden",
+ "direct": "Direkte Verbindung zu {{host}} fehlgeschlagen: {{reason}}",
+ "viaProxy": "Verbindung zu {{host}} über Proxy {{proxy}} fehlgeschlagen: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index bea41ec3..0ea0ec09 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -1690,6 +1690,20 @@
"compromised": "Η διανομή αυτού του πρόσθετου έχει παραβιαστεί.",
"fixedVersion": "Διατίθεται διόρθωση στην έκδοση {{version}}.",
"details": "Προβολή ανακοίνωσης ασφαλείας"
+ },
+ "network": {
+ "timeout": "Λήξη χρονικού ορίου σύνδεσης",
+ "dns": "Αποτυχία επίλυσης DNS",
+ "proxyAuth": "Αποτυχία ελέγχου ταυτότητας διακομιστή μεσολάβησης",
+ "proxyConnect": "Αδυναμία σύνδεσης στον διακομιστή μεσολάβησης",
+ "certificate": "Σφάλμα πιστοποιητικού ή TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Το αίτημα ακυρώθηκε",
+ "network": "Αποτυχία αιτήματος δικτύου",
+ "cached": "Η ανανέωση απέτυχε· εμφανίζονται αποθηκευμένα πρόσθετα",
+ "unavailable": "Αδυναμία φόρτωσης καταλόγου πρόσθετων",
+ "direct": "Αποτυχία απευθείας σύνδεσης στο {{host}}: {{reason}}",
+ "viaProxy": "Αποτυχία σύνδεσης στο {{host}} μέσω {{proxy}}: {{reason}}"
}
},
"quit": {
@@ -2590,7 +2604,7 @@
"bypass": "Απευθείας σύνδεση προς",
"bypassDesc": "Ένας τομέας, IP ή CIDR ανά γραμμή. Ξεκινήστε με . για αντιστοίχιση μόνο υποτομέων. Οι λήψεις αρχείων δεν υποστηρίζουν χαρακτήρες μπαλαντέρ *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Μόνο για λήψεις αρχείων και ενημερώσεις εφαρμογής",
+ "bypassScopeNote": "Μόνο λήψεις, πρόσθετα και ενημερώσεις εφαρμογής",
"enable": "Ενεργοποίηση διακομιστή μεσολάβησης",
"enableDesc": "Χρήση διακομιστή μεσολάβησης για τις παρακάτω επιλεγμένες συνδέσεις.",
"hidePassword": "Απόκρυψη κωδικού πρόσβασης",
@@ -2617,7 +2631,9 @@
"server": "Διακομιστής",
"showPassword": "Εμφάνιση κωδικού πρόσβασης",
"title": "Διακομιστής μεσολάβησης",
- "user": "Όνομα χρήστη"
+ "user": "Όνομα χρήστη",
+ "scopePlugins": "Εγκατάσταση και ενημέρωση πρόσθετων",
+ "scopePluginsDesc": "Χρήση διακομιστή μεσολάβησης για τον κατάλογο, τα πακέτα, τις ενημερώσεις και τις πολιτικές ασφαλείας των πρόσθετων."
},
"reachability": {
"addEndpoint": "Προσθήκη υπηρεσίας ελέγχου",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 6c413b7e..b122f4bb 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1707,7 +1707,7 @@
"hidePassword": "Hide password",
"bypass": "Connect directly to",
"bypassDesc": "One domain, IP or CIDR per line. Start with . to match subdomains only. File downloads don’t support * wildcards.",
- "bypassScopeNote": "File downloads and app updates only",
+ "bypassScopeNote": "Downloads, plugins, and app updates only",
"scopes": "Use proxy for",
"scopesDesc": "Choose which kinds of traffic go through the proxy.",
"scopeDownload": "File downloads",
@@ -1723,7 +1723,9 @@
"scopeHint": "BT peers, DHT and UDP trackers connect directly.",
"scopeNone": "None selected",
"scopeChoose": "Select…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Plugin installation and updates",
+ "scopePluginsDesc": "Use the proxy for the plugin catalog, installation packages, updates, and security policy requests."
},
"nat": {
"title": "Port mapping (NAT)",
@@ -2721,6 +2723,20 @@
"compromised": "This plugin’s distribution was compromised.",
"fixedVersion": "A fix is available in version {{version}}.",
"details": "View security advisory"
+ },
+ "network": {
+ "timeout": "Connection timed out",
+ "dns": "DNS lookup failed",
+ "proxyAuth": "Proxy authentication failed",
+ "proxyConnect": "Could not connect to the proxy",
+ "certificate": "Certificate or TLS error",
+ "http": "HTTP {{status}}",
+ "cancelled": "Request cancelled",
+ "network": "Network request failed",
+ "cached": "Refresh failed; showing cached plugins",
+ "unavailable": "Could not load the plugin catalog",
+ "direct": "Direct connection to {{host}} failed: {{reason}}",
+ "viaProxy": "Connection to {{host}} via proxy {{proxy}} failed: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 7d0a656b..42e6e967 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1721,7 +1721,7 @@
"hidePassword": "Ocultar contraseña",
"bypass": "Conectar directamente a",
"bypassDesc": "Un dominio, una IP o un bloque CIDR por línea. Empieza por . para incluir solo subdominios. Las descargas de archivos no admiten comodines *.",
- "bypassScopeNote": "Solo descargas de archivos y actualizaciones de la aplicación",
+ "bypassScopeNote": "Solo descargas, plugins y actualizaciones de la aplicación",
"scopes": "Usar proxy para",
"scopesDesc": "Elige qué tipos de tráfico pasan por el proxy.",
"scopeDownload": "Descargas de archivos",
@@ -1737,7 +1737,9 @@
"scopeHint": "Los pares BT, DHT y los trackers UDP se conectan directamente.",
"scopeNone": "Ninguno seleccionado",
"scopeChoose": "Seleccionar…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Instalación y actualización de plugins",
+ "scopePluginsDesc": "Usar el proxy para el catálogo, los paquetes, las actualizaciones y las políticas de seguridad de los plugins."
},
"nat": {
"title": "Redirección de puertos (NAT)",
@@ -2742,6 +2744,20 @@
"compromised": "La distribución de este complemento se ha visto comprometida.",
"fixedVersion": "Hay una corrección disponible en la versión {{version}}.",
"details": "Ver aviso de seguridad"
+ },
+ "network": {
+ "timeout": "Tiempo de conexión agotado",
+ "dns": "Error de resolución DNS",
+ "proxyAuth": "Error de autenticación del proxy",
+ "proxyConnect": "No se pudo conectar al proxy",
+ "certificate": "Error de certificado o TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Solicitud cancelada",
+ "network": "Error de solicitud de red",
+ "cached": "Error al actualizar; se muestran los plugins en caché",
+ "unavailable": "No se pudo cargar el catálogo de plugins",
+ "direct": "Error de conexión directa a {{host}}: {{reason}}",
+ "viaProxy": "Error de conexión a {{host}} mediante el proxy {{proxy}}: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index d851c97d..2ee47cb5 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -1690,6 +1690,20 @@
"compromised": "کانال توزیع این افزونه مورد نفوذ قرار گرفته است.",
"fixedVersion": "اصلاحیه در نسخه {{version}} موجود است.",
"details": "مشاهده اطلاعیه امنیتی"
+ },
+ "network": {
+ "timeout": "مهلت اتصال تمام شد",
+ "dns": "جستجوی DNS ناموفق بود",
+ "proxyAuth": "احراز هویت پراکسی ناموفق بود",
+ "proxyConnect": "اتصال به پراکسی ممکن نیست",
+ "certificate": "خطای گواهی یا TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "درخواست لغو شد",
+ "network": "درخواست شبکه ناموفق بود",
+ "cached": "تازه‌سازی ناموفق بود؛ افزونه‌های ذخیره‌شده نمایش داده می‌شوند",
+ "unavailable": "بارگیری فهرست افزونه‌ها ممکن نیست",
+ "direct": "اتصال مستقیم به {{host}} ناموفق بود: {{reason}}",
+ "viaProxy": "اتصال به {{host}} از طریق پراکسی {{proxy}} ناموفق بود: {{reason}}"
}
},
"quit": {
@@ -2590,7 +2604,7 @@
"bypass": "اتصال مستقیم به",
"bypassDesc": "در هر خط یک دامنه، IP یا CIDR. برای تطبیق فقط با زیردامنه‌ها، با . شروع کنید. دانلود فایل از نویسهٔ عام * پشتیبانی نمی‌کند.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "فقط دانلود فایل‌ها و به‌روزرسانی‌های برنامه",
+ "bypassScopeNote": "فقط دانلودها، افزونه‌ها و به‌روزرسانی برنامه",
"enable": "فعال کردن پروکسی",
"enableDesc": "برای اتصال‌های انتخاب‌شده در زیر از پروکسی استفاده شود.",
"hidePassword": "پنهان کردن گذرواژه",
@@ -2617,7 +2631,9 @@
"server": "سرور",
"showPassword": "نمایش گذرواژه",
"title": "پروکسی",
- "user": "نام کاربری"
+ "user": "نام کاربری",
+ "scopePlugins": "نصب و به‌روزرسانی افزونه‌ها",
+ "scopePluginsDesc": "استفاده از پراکسی برای فهرست افزونه‌ها، بسته‌های نصب، به‌روزرسانی‌ها و درخواست‌های سیاست امنیتی."
},
"reachability": {
"addEndpoint": "افزودن سرویس بررسی",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index adceb27c..d2745d70 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -1708,6 +1708,20 @@
"compromised": "La distribution de ce plugin a été compromise.",
"fixedVersion": "Un correctif est disponible dans la version {{version}}.",
"details": "Voir l’avis de sécurité"
+ },
+ "network": {
+ "timeout": "Délai de connexion dépassé",
+ "dns": "Échec de la résolution DNS",
+ "proxyAuth": "Échec de l’authentification du proxy",
+ "proxyConnect": "Connexion au proxy impossible",
+ "certificate": "Erreur de certificat ou TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Requête annulée",
+ "network": "Échec de la requête réseau",
+ "cached": "Actualisation impossible ; plugins en cache affichés",
+ "unavailable": "Impossible de charger le catalogue des plugins",
+ "direct": "Échec de la connexion directe à {{host}} : {{reason}}",
+ "viaProxy": "Échec de la connexion à {{host}} via le proxy {{proxy}} : {{reason}}"
}
},
"quit": {
@@ -2610,7 +2624,7 @@
"bypass": "Connexion directe à",
"bypassDesc": "Un domaine, une IP ou un CIDR par ligne. Commencez par . pour ne cibler que les sous-domaines. Les téléchargements de fichiers ne prennent pas en charge le caractère générique *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Téléchargements de fichiers et mises à jour de l’application uniquement",
+ "bypassScopeNote": "Téléchargements, plugins et mises à jour de l’application uniquement",
"enable": "Activer le proxy",
"enableDesc": "Utiliser un proxy pour les connexions sélectionnées ci-dessous.",
"hidePassword": "Masquer le mot de passe",
@@ -2637,7 +2651,9 @@
"server": "Serveur",
"showPassword": "Afficher le mot de passe",
"title": "Proxy",
- "user": "Nom d’utilisateur"
+ "user": "Nom d’utilisateur",
+ "scopePlugins": "Installation et mise à jour des plugins",
+ "scopePluginsDesc": "Utiliser le proxy pour le catalogue, les paquets, les mises à jour et les règles de sécurité des plugins."
},
"reachability": {
"addEndpoint": "Ajouter un service de vérification",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 2c26fc4d..9ea51b1d 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1707,7 +1707,7 @@
"hidePassword": "Jelszó elrejtése",
"bypass": "Közvetlen kapcsolódás ezekhez",
"bypassDesc": "Soronként egy domain, IP-cím vagy CIDR-tartomány. Kezdő ponttal csak az aldomainekre illeszkedik. Fájlletöltésnél a * helyettesítő karakter nem támogatott.",
- "bypassScopeNote": "Csak fájlletöltésekhez és alkalmazásfrissítésekhez",
+ "bypassScopeNote": "Csak letöltések, bővítmények és alkalmazásfrissítések",
"scopes": "Proxy használata ezekhez",
"scopesDesc": "Válaszd ki, mely forgalomtípusok haladjanak át a proxyn.",
"scopeDownload": "Fájlletöltések",
@@ -1723,7 +1723,9 @@
"scopeHint": "A BitTorrent-partnerek, a DHT és az UDP-trackerek közvetlenül kapcsolódnak.",
"scopeNone": "Nincs kiválasztva",
"scopeChoose": "Kiválasztás…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Bővítmények telepítése és frissítése",
+ "scopePluginsDesc": "Proxy használata a bővítménykatalógushoz, csomagokhoz, frissítésekhez és biztonsági szabályzatokhoz."
},
"nat": {
"title": "Portleképezés (NAT)",
@@ -2721,6 +2723,20 @@
"compromised": "A bővítmény terjesztési csatornáját feltörték.",
"fixedVersion": "Javítás érhető el a(z) {{version}} verzióban.",
"details": "Biztonsági közlemény megtekintése"
+ },
+ "network": {
+ "timeout": "A kapcsolat időtúllépése",
+ "dns": "Sikertelen DNS-feloldás",
+ "proxyAuth": "Sikertelen proxyhitelesítés",
+ "proxyConnect": "Nem lehet kapcsolódni a proxyhoz",
+ "certificate": "Tanúsítvány- vagy TLS-hiba",
+ "http": "HTTP {{status}}",
+ "cancelled": "Kérés megszakítva",
+ "network": "Sikertelen hálózati kérés",
+ "cached": "Sikertelen frissítés; gyorsítótárazott bővítmények láthatók",
+ "unavailable": "A bővítménykatalógus nem tölthető be",
+ "direct": "Sikertelen közvetlen kapcsolat: {{host}}: {{reason}}",
+ "viaProxy": "Sikertelen kapcsolat: {{host}}, proxy: {{proxy}}: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index ab899fc5..36a8987c 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1693,7 +1693,7 @@
"hidePassword": "Sembunyikan kata sandi",
"bypass": "Hubungkan langsung ke",
"bypassDesc": "Satu domain, IP, atau CIDR per baris. Awali dengan . untuk mencocokkan subdomain saja. Unduhan berkas tidak mendukung karakter pengganti *.",
- "bypassScopeNote": "Hanya unduhan berkas dan pembaruan aplikasi",
+ "bypassScopeNote": "Hanya unduhan, plugin, dan pembaruan aplikasi",
"scopes": "Gunakan proxy untuk",
"scopesDesc": "Pilih jenis lalu lintas yang melalui proxy.",
"scopeDownload": "Unduhan berkas",
@@ -1709,7 +1709,9 @@
"scopeHint": "Peer BT, DHT, dan pelacak UDP terhubung langsung.",
"scopeNone": "Belum ada yang dipilih",
"scopeChoose": "Pilih…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Instalasi dan pembaruan plugin",
+ "scopePluginsDesc": "Gunakan proksi untuk katalog, paket, pembaruan, dan permintaan kebijakan keamanan plugin."
},
"nat": {
"title": "Pemetaan port (NAT)",
@@ -2700,6 +2702,20 @@
"compromised": "Saluran distribusi plugin ini telah disusupi.",
"fixedVersion": "Perbaikan tersedia pada versi {{version}}.",
"details": "Lihat pemberitahuan keamanan"
+ },
+ "network": {
+ "timeout": "Waktu koneksi habis",
+ "dns": "Pencarian DNS gagal",
+ "proxyAuth": "Autentikasi proksi gagal",
+ "proxyConnect": "Tidak dapat terhubung ke proksi",
+ "certificate": "Kesalahan sertifikat atau TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Permintaan dibatalkan",
+ "network": "Permintaan jaringan gagal",
+ "cached": "Penyegaran gagal; menampilkan plugin dari cache",
+ "unavailable": "Tidak dapat memuat katalog plugin",
+ "direct": "Koneksi langsung ke {{host}} gagal: {{reason}}",
+ "viaProxy": "Koneksi ke {{host}} melalui proksi {{proxy}} gagal: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index a2aa1a6f..a9751941 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1721,7 +1721,7 @@
"hidePassword": "Nascondi password",
"bypass": "Connetti direttamente a",
"bypassDesc": "Un dominio, IP o CIDR per riga. Inizia con . per includere solo i sottodomini. I download di file non supportano il carattere jolly *.",
- "bypassScopeNote": "Solo download di file e aggiornamenti dell’app",
+ "bypassScopeNote": "Solo download, plugin e aggiornamenti dell’app",
"scopes": "Usa proxy per",
"scopesDesc": "Scegli quali tipi di traffico passano attraverso il proxy.",
"scopeDownload": "Download di file",
@@ -1737,7 +1737,9 @@
"scopeHint": "Peer BT, DHT e tracker UDP si connettono direttamente.",
"scopeNone": "Nessuna selezione",
"scopeChoose": "Seleziona…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Installazione e aggiornamento dei plugin",
+ "scopePluginsDesc": "Usa il proxy per il catalogo, i pacchetti, gli aggiornamenti e le politiche di sicurezza dei plugin."
},
"nat": {
"title": "Mappatura delle porte (NAT)",
@@ -2742,6 +2744,20 @@
"compromised": "La distribuzione di questo plugin è stata compromessa.",
"fixedVersion": "Una correzione è disponibile nella versione {{version}}.",
"details": "Visualizza avviso di sicurezza"
+ },
+ "network": {
+ "timeout": "Connessione scaduta",
+ "dns": "Risoluzione DNS non riuscita",
+ "proxyAuth": "Autenticazione del proxy non riuscita",
+ "proxyConnect": "Impossibile connettersi al proxy",
+ "certificate": "Errore di certificato o TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Richiesta annullata",
+ "network": "Richiesta di rete non riuscita",
+ "cached": "Aggiornamento non riuscito; vengono mostrati i plugin in cache",
+ "unavailable": "Impossibile caricare il catalogo dei plugin",
+ "direct": "Connessione diretta a {{host}} non riuscita: {{reason}}",
+ "viaProxy": "Connessione a {{host}} tramite il proxy {{proxy}} non riuscita: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 7af3717e..14511193 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1693,7 +1693,7 @@
"hidePassword": "パスワードを非表示",
"bypass": "直接接続する宛先",
"bypassDesc": "ドメイン、IP、CIDR を 1 行に 1 件入力してください。先頭に . を付けるとサブドメインのみが対象になります。ファイルのダウンロードでは * ワイルドカードは使用できません。",
- "bypassScopeNote": "ファイルのダウンロードとアプリのアップデートのみ",
+ "bypassScopeNote": "ダウンロード、プラグイン、アプリ更新のみ",
"scopes": "プロキシの適用対象",
"scopesDesc": "プロキシを経由する通信の種類を選択します。",
"scopeDownload": "ファイルのダウンロード",
@@ -1709,7 +1709,9 @@
"scopeHint": "BT ピア、DHT、UDP トラッカーには直接接続します。",
"scopeNone": "未選択",
"scopeChoose": "選択…",
- "scopeSeparator": "、"
+ "scopeSeparator": "、",
+ "scopePlugins": "プラグインのインストールと更新",
+ "scopePluginsDesc": "プラグイン一覧、インストールパッケージ、更新、安全性ポリシーの取得にプロキシを使用します。"
},
"nat": {
"title": "ポートマッピング(NAT)",
@@ -2700,6 +2702,20 @@
"compromised": "このプラグインの配布元が侵害されました。",
"fixedVersion": "修正済みバージョン:{{version}}。",
"details": "セキュリティ情報を表示"
+ },
+ "network": {
+ "timeout": "接続がタイムアウトしました",
+ "dns": "DNS 名前解決に失敗しました",
+ "proxyAuth": "プロキシ認証に失敗しました",
+ "proxyConnect": "プロキシに接続できません",
+ "certificate": "証明書または TLS エラー",
+ "http": "HTTP {{status}}",
+ "cancelled": "リクエストをキャンセルしました",
+ "network": "ネットワークリクエストに失敗しました",
+ "cached": "更新に失敗したため、キャッシュしたプラグインを表示しています",
+ "unavailable": "プラグイン一覧を読み込めません",
+ "direct": "{{host}} への直接接続に失敗しました:{{reason}}",
+ "viaProxy": "プロキシ {{proxy}} 経由での {{host}} への接続に失敗しました:{{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index daceff78..e31906bb 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1693,7 +1693,7 @@
"hidePassword": "비밀번호 숨기기",
"bypass": "직접 연결할 대상",
"bypassDesc": "한 줄에 도메인, IP 또는 CIDR 하나를 입력하세요. 하위 도메인만 일치시키려면 .으로 시작하세요. 파일 다운로드에서는 * 와일드카드를 지원하지 않습니다.",
- "bypassScopeNote": "파일 다운로드 및 앱 업데이트에만 적용",
+ "bypassScopeNote": "다운로드, 플러그인 및 앱 업데이트에만 적용",
"scopes": "프록시 적용 대상",
"scopesDesc": "프록시를 거칠 트래픽 유형을 선택하세요.",
"scopeDownload": "파일 다운로드",
@@ -1709,7 +1709,9 @@
"scopeHint": "BT 피어, DHT 및 UDP 트래커는 직접 연결합니다.",
"scopeNone": "선택한 항목 없음",
"scopeChoose": "선택…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "플러그인 설치 및 업데이트",
+ "scopePluginsDesc": "플러그인 목록, 설치 패키지, 업데이트 및 보안 정책 요청에 프록시를 사용합니다."
},
"nat": {
"title": "포트 매핑(NAT)",
@@ -2700,6 +2702,20 @@
"compromised": "이 플러그인의 배포 경로가 침해되었습니다.",
"fixedVersion": "수정된 버전: {{version}}.",
"details": "보안 공지 보기"
+ },
+ "network": {
+ "timeout": "연결 시간 초과",
+ "dns": "DNS 조회 실패",
+ "proxyAuth": "프록시 인증 실패",
+ "proxyConnect": "프록시에 연결할 수 없음",
+ "certificate": "인증서 또는 TLS 오류",
+ "http": "HTTP {{status}}",
+ "cancelled": "요청 취소됨",
+ "network": "네트워크 요청 실패",
+ "cached": "새로고침 실패, 캐시된 플러그인 표시 중",
+ "unavailable": "플러그인 목록을 불러올 수 없음",
+ "direct": "{{host}} 직접 연결 실패: {{reason}}",
+ "viaProxy": "프록시 {{proxy}} 경유 {{host}} 연결 실패: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 40f8b36e..bc204365 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -1690,6 +1690,20 @@
"compromised": "Distribusjonen av denne utvidelsen er kompromittert.",
"fixedVersion": "En rettelse er tilgjengelig i versjon {{version}}.",
"details": "Vis sikkerhetsvarsel"
+ },
+ "network": {
+ "timeout": "Tidsavbrudd for tilkoblingen",
+ "dns": "DNS-oppslag mislyktes",
+ "proxyAuth": "Proxyautentisering mislyktes",
+ "proxyConnect": "Kunne ikke koble til proxyen",
+ "certificate": "Sertifikat- eller TLS-feil",
+ "http": "HTTP {{status}}",
+ "cancelled": "Forespørselen ble avbrutt",
+ "network": "Nettverksforespørselen mislyktes",
+ "cached": "Oppdatering mislyktes; viser mellomlagrede programtillegg",
+ "unavailable": "Kunne ikke laste katalogen for programtillegg",
+ "direct": "Direkte tilkobling til {{host}} mislyktes: {{reason}}",
+ "viaProxy": "Tilkobling til {{host}} via proxy {{proxy}} mislyktes: {{reason}}"
}
},
"quit": {
@@ -2590,7 +2604,7 @@
"bypass": "Koble direkte til",
"bypassDesc": "Ett domene, én IP-adresse eller ett CIDR-område per linje. Start med . for bare å samsvare med underdomener. Filnedlastinger støtter ikke jokertegnet *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Bare filnedlastinger og appoppdateringer",
+ "bypassScopeNote": "Bare nedlastinger, programtillegg og appoppdateringer",
"enable": "Aktiver mellomtjener",
"enableDesc": "Bruk en mellomtjener for tilkoblingene som er valgt nedenfor.",
"hidePassword": "Skjul passord",
@@ -2617,7 +2631,9 @@
"server": "Server",
"showPassword": "Vis passord",
"title": "Mellomtjener",
- "user": "Brukernavn"
+ "user": "Brukernavn",
+ "scopePlugins": "Installasjon og oppdatering av programtillegg",
+ "scopePluginsDesc": "Bruk proxy for katalogen, pakker, oppdateringer og sikkerhetsregler for programtillegg."
},
"reachability": {
"addEndpoint": "Legg til kontrolltjeneste",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 58d3b6f3..6964b0cc 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -1690,6 +1690,20 @@
"compromised": "De distributie van deze plug-in is gecompromitteerd.",
"fixedVersion": "Een oplossing is beschikbaar in versie {{version}}.",
"details": "Beveiligingsmelding bekijken"
+ },
+ "network": {
+ "timeout": "Verbinding verlopen",
+ "dns": "DNS-opzoeking mislukt",
+ "proxyAuth": "Proxyverificatie mislukt",
+ "proxyConnect": "Kan geen verbinding maken met de proxy",
+ "certificate": "Certificaat- of TLS-fout",
+ "http": "HTTP {{status}}",
+ "cancelled": "Verzoek geannuleerd",
+ "network": "Netwerkverzoek mislukt",
+ "cached": "Vernieuwen mislukt; plugins uit de cache worden getoond",
+ "unavailable": "Kan de plugincatalogus niet laden",
+ "direct": "Directe verbinding met {{host}} mislukt: {{reason}}",
+ "viaProxy": "Verbinding met {{host}} via proxy {{proxy}} mislukt: {{reason}}"
}
},
"quit": {
@@ -2590,7 +2604,7 @@
"bypass": "Rechtstreeks verbinden met",
"bypassDesc": "Eén domein, IP-adres of CIDR per regel. Begin met . om alleen subdomeinen te selecteren. Bestandsdownloads ondersteunen geen *-jokertekens.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Alleen bestandsdownloads en appupdates",
+ "bypassScopeNote": "Alleen downloads, plugins en app-updates",
"enable": "Proxy inschakelen",
"enableDesc": "Een proxy gebruiken voor de hieronder geselecteerde verbindingen.",
"hidePassword": "Wachtwoord verbergen",
@@ -2617,7 +2631,9 @@
"server": "Server",
"showPassword": "Wachtwoord tonen",
"title": "Proxy",
- "user": "Gebruikersnaam"
+ "user": "Gebruikersnaam",
+ "scopePlugins": "Plugins installeren en bijwerken",
+ "scopePluginsDesc": "Gebruik de proxy voor de plugincatalogus, pakketten, updates en beveiligingsbeleid."
},
"reachability": {
"addEndpoint": "Controledienst toevoegen",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index adc1b447..4eda3e7c 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1735,7 +1735,7 @@
"hidePassword": "Ukryj hasło",
"bypass": "Łącz bezpośrednio z",
"bypassDesc": "Jedna domena, adres IP lub CIDR w wierszu. Zacznij od ., aby dopasować tylko subdomeny. Pobieranie plików nie obsługuje symbolu wieloznacznego *.",
- "bypassScopeNote": "Tylko pobieranie plików i aktualizacje aplikacji",
+ "bypassScopeNote": "Tylko pobieranie, wtyczki i aktualizacje aplikacji",
"scopes": "Używaj proxy do",
"scopesDesc": "Wybierz, które rodzaje ruchu przechodzą przez proxy.",
"scopeDownload": "Pobieranie plików",
@@ -1751,7 +1751,9 @@
"scopeHint": "Peery BT, DHT i trackery UDP łączą się bezpośrednio.",
"scopeNone": "Nic nie wybrano",
"scopeChoose": "Wybierz…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Instalacja i aktualizacja wtyczek",
+ "scopePluginsDesc": "Używaj proxy do katalogu, pakietów, aktualizacji i zasad bezpieczeństwa wtyczek."
},
"nat": {
"title": "Mapowanie portów (NAT)",
@@ -2763,6 +2765,20 @@
"compromised": "Kanał dystrybucji tej wtyczki został naruszony.",
"fixedVersion": "Poprawka jest dostępna w wersji {{version}}.",
"details": "Wyświetl komunikat bezpieczeństwa"
+ },
+ "network": {
+ "timeout": "Przekroczono czas połączenia",
+ "dns": "Błąd rozpoznawania DNS",
+ "proxyAuth": "Błąd uwierzytelniania proxy",
+ "proxyConnect": "Nie można połączyć się z proxy",
+ "certificate": "Błąd certyfikatu lub TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Żądanie anulowane",
+ "network": "Błąd żądania sieciowego",
+ "cached": "Aktualizacja nie powiodła się; wyświetlono wtyczki z pamięci podręcznej",
+ "unavailable": "Nie można wczytać katalogu wtyczek",
+ "direct": "Błąd bezpośredniego połączenia z {{host}}: {{reason}}",
+ "viaProxy": "Błąd połączenia z {{host}} przez proxy {{proxy}}: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 98691f6b..70243499 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1721,7 +1721,7 @@
"hidePassword": "Ocultar senha",
"bypass": "Conectar diretamente a",
"bypassDesc": "Um domínio, IP ou CIDR por linha. Comece com . para corresponder apenas a subdomínios. Downloads de arquivos não aceitam curingas *.",
- "bypassScopeNote": "Somente downloads de arquivos e atualizações do aplicativo",
+ "bypassScopeNote": "Somente downloads, plugins e atualizações do aplicativo",
"scopes": "Usar proxy para",
"scopesDesc": "Escolha quais tipos de tráfego passam pelo proxy.",
"scopeDownload": "Downloads de arquivos",
@@ -1737,7 +1737,9 @@
"scopeHint": "Pares BT, DHT e rastreadores UDP se conectam diretamente.",
"scopeNone": "Nenhum selecionado",
"scopeChoose": "Selecionar…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Instalação e atualização de plugins",
+ "scopePluginsDesc": "Usar o proxy para o catálogo, pacotes, atualizações e políticas de segurança dos plugins."
},
"nat": {
"title": "Mapeamento de portas (NAT)",
@@ -2742,6 +2744,20 @@
"compromised": "A distribuição deste plugin foi comprometida.",
"fixedVersion": "Uma correção está disponível na versão {{version}}.",
"details": "Ver aviso de segurança"
+ },
+ "network": {
+ "timeout": "Tempo de conexão esgotado",
+ "dns": "Falha na resolução de DNS",
+ "proxyAuth": "Falha na autenticação do proxy",
+ "proxyConnect": "Não foi possível conectar ao proxy",
+ "certificate": "Erro de certificado ou TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Solicitação cancelada",
+ "network": "Falha na solicitação de rede",
+ "cached": "Falha ao atualizar; exibindo plugins em cache",
+ "unavailable": "Não foi possível carregar o catálogo de plugins",
+ "direct": "Falha na conexão direta com {{host}}: {{reason}}",
+ "viaProxy": "Falha na conexão com {{host}} pelo proxy {{proxy}}: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 2bbd72c3..c24dcdd3 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -1708,6 +1708,20 @@
"compromised": "Canalul de distribuție al acestui plugin a fost compromis.",
"fixedVersion": "O remediere este disponibilă în versiunea {{version}}.",
"details": "Vedeți anunțul de securitate"
+ },
+ "network": {
+ "timeout": "Conexiunea a expirat",
+ "dns": "Rezolvarea DNS a eșuat",
+ "proxyAuth": "Autentificarea proxy a eșuat",
+ "proxyConnect": "Nu se poate conecta la proxy",
+ "certificate": "Eroare de certificat sau TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Cerere anulată",
+ "network": "Cererea de rețea a eșuat",
+ "cached": "Actualizarea a eșuat; se afișează extensiile din cache",
+ "unavailable": "Catalogul de extensii nu a putut fi încărcat",
+ "direct": "Conexiunea directă la {{host}} a eșuat: {{reason}}",
+ "viaProxy": "Conexiunea la {{host}} prin proxy-ul {{proxy}} a eșuat: {{reason}}"
}
},
"quit": {
@@ -2610,7 +2624,7 @@
"bypass": "Conectează direct la",
"bypassDesc": "Un domeniu, IP sau CIDR pe linie. Începe cu . pentru a include doar subdomenii. Descărcările de fișiere nu acceptă metacaracterul *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Doar descărcări de fișiere și actualizări ale aplicației",
+ "bypassScopeNote": "Doar descărcări, extensii și actualizări ale aplicației",
"enable": "Activează proxy-ul",
"enableDesc": "Folosește un proxy pentru conexiunile selectate mai jos.",
"hidePassword": "Ascunde parola",
@@ -2637,7 +2651,9 @@
"server": "Server",
"showPassword": "Arată parola",
"title": "Proxy",
- "user": "Nume de utilizator"
+ "user": "Nume de utilizator",
+ "scopePlugins": "Instalarea și actualizarea extensiilor",
+ "scopePluginsDesc": "Folosește proxy-ul pentru catalog, pachete, actualizări și politicile de securitate ale extensiilor."
},
"reachability": {
"addEndpoint": "Adaugă serviciu de verificare",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 088dc4ab..1ac7b667 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1735,7 +1735,7 @@
"hidePassword": "Скрыть пароль",
"bypass": "Подключаться напрямую к",
"bypassDesc": "Один домен, IP-адрес или CIDR на строку. Начните с . для совпадения только с поддоменами. При загрузке файлов подстановочный знак * не поддерживается.",
- "bypassScopeNote": "Только загрузки файлов и обновления приложения",
+ "bypassScopeNote": "Только загрузки, плагины и обновления приложения",
"scopes": "Использовать прокси для",
"scopesDesc": "Выберите, какие виды трафика направлять через прокси.",
"scopeDownload": "Загрузки файлов",
@@ -1751,7 +1751,9 @@
"scopeHint": "Пиры BT, DHT и UDP-трекеры подключаются напрямую.",
"scopeNone": "Ничего не выбрано",
"scopeChoose": "Выбрать…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Установка и обновление плагинов",
+ "scopePluginsDesc": "Использовать прокси для каталога, пакетов, обновлений и политик безопасности плагинов."
},
"nat": {
"title": "Проброс портов (NAT)",
@@ -2763,6 +2765,20 @@
"compromised": "Канал распространения этого плагина был скомпрометирован.",
"fixedVersion": "Исправление доступно в версии {{version}}.",
"details": "Открыть уведомление о безопасности"
+ },
+ "network": {
+ "timeout": "Время ожидания соединения истекло",
+ "dns": "Ошибка DNS",
+ "proxyAuth": "Ошибка аутентификации прокси",
+ "proxyConnect": "Не удалось подключиться к прокси",
+ "certificate": "Ошибка сертификата или TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Запрос отменён",
+ "network": "Ошибка сетевого запроса",
+ "cached": "Обновление не удалось; показаны плагины из кэша",
+ "unavailable": "Не удалось загрузить каталог плагинов",
+ "direct": "Ошибка прямого подключения к {{host}}: {{reason}}",
+ "viaProxy": "Ошибка подключения к {{host}} через прокси {{proxy}}: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index f94bd044..badc2f7b 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -1672,6 +1672,20 @@
"compromised": "ช่องทางเผยแพร่ปลั๊กอินนี้ถูกบุกรุก",
"fixedVersion": "มีการแก้ไขในเวอร์ชัน {{version}}",
"details": "ดูประกาศความปลอดภัย"
+ },
+ "network": {
+ "timeout": "การเชื่อมต่อหมดเวลา",
+ "dns": "ค้นหา DNS ไม่สำเร็จ",
+ "proxyAuth": "ยืนยันตัวตนพร็อกซีไม่สำเร็จ",
+ "proxyConnect": "เชื่อมต่อพร็อกซีไม่ได้",
+ "certificate": "ข้อผิดพลาดใบรับรองหรือ TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "ยกเลิกคำขอแล้ว",
+ "network": "คำขอเครือข่ายไม่สำเร็จ",
+ "cached": "รีเฟรชไม่สำเร็จ กำลังแสดงปลั๊กอินจากแคช",
+ "unavailable": "โหลดรายการปลั๊กอินไม่ได้",
+ "direct": "เชื่อมต่อโดยตรงกับ {{host}} ไม่สำเร็จ: {{reason}}",
+ "viaProxy": "เชื่อมต่อกับ {{host}} ผ่านพร็อกซี {{proxy}} ไม่สำเร็จ: {{reason}}"
}
},
"quit": {
@@ -2570,7 +2584,7 @@
"bypass": "เชื่อมต่อโดยตรงไปยัง",
"bypassDesc": "หนึ่งโดเมน IP หรือ CIDR ต่อบรรทัด เริ่มด้วย . เพื่อจับคู่เฉพาะโดเมนย่อย การดาวน์โหลดไฟล์ไม่รองรับอักขระตัวแทน *",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "เฉพาะการดาวน์โหลดไฟล์และการอัปเดตแอป",
+ "bypassScopeNote": "เฉพาะการดาวน์โหลด ปลั๊กอิน และการอัปเดตแอป",
"enable": "เปิดใช้พร็อกซี",
"enableDesc": "ใช้พร็อกซีสำหรับการเชื่อมต่อที่เลือกด้านล่าง",
"hidePassword": "ซ่อนรหัสผ่าน",
@@ -2597,7 +2611,9 @@
"server": "เซิร์ฟเวอร์",
"showPassword": "แสดงรหัสผ่าน",
"title": "พร็อกซี",
- "user": "ชื่อผู้ใช้"
+ "user": "ชื่อผู้ใช้",
+ "scopePlugins": "การติดตั้งและอัปเดตปลั๊กอิน",
+ "scopePluginsDesc": "ใช้พร็อกซีสำหรับรายการปลั๊กอิน แพ็กเกจติดตั้ง การอัปเดต และคำขอนโยบายความปลอดภัย"
},
"reachability": {
"addEndpoint": "เพิ่มบริการตรวจสอบ",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 1fba0b30..8a7d12b5 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1707,7 +1707,7 @@
"hidePassword": "Parolayı gizle",
"bypass": "Doğrudan bağlanılacak adresler",
"bypassDesc": "Her satıra bir alan adı, IP veya CIDR girin. Yalnızca alt alan adlarını eşleştirmek için . ile başlayın. Dosya indirmeleri * joker karakterini desteklemez.",
- "bypassScopeNote": "Yalnızca dosya indirmeleri ve uygulama güncellemeleri",
+ "bypassScopeNote": "Yalnızca indirmeler, eklentiler ve uygulama güncellemeleri",
"scopes": "Vekil sunucunun kullanılacağı işlemler",
"scopesDesc": "Vekil sunucudan geçecek trafik türlerini seçin.",
"scopeDownload": "Dosya indirmeleri",
@@ -1723,7 +1723,9 @@
"scopeHint": "BT eşleri, DHT ve UDP izleyicileri doğrudan bağlanır.",
"scopeNone": "Hiçbiri seçilmedi",
"scopeChoose": "Seç…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Eklenti kurulumu ve güncellemeleri",
+ "scopePluginsDesc": "Eklenti kataloğu, paketleri, güncellemeleri ve güvenlik ilkesi istekleri için proxy kullanın."
},
"nat": {
"title": "Bağlantı noktası eşlemesi (NAT)",
@@ -2721,6 +2723,20 @@
"compromised": "Bu eklentinin dağıtım kanalı ele geçirildi.",
"fixedVersion": "Düzeltme {{version}} sürümünde mevcut.",
"details": "Güvenlik duyurusunu görüntüle"
+ },
+ "network": {
+ "timeout": "Bağlantı zaman aşımına uğradı",
+ "dns": "DNS çözümlemesi başarısız",
+ "proxyAuth": "Proxy kimlik doğrulaması başarısız",
+ "proxyConnect": "Proxy sunucusuna bağlanılamadı",
+ "certificate": "Sertifika veya TLS hatası",
+ "http": "HTTP {{status}}",
+ "cancelled": "İstek iptal edildi",
+ "network": "Ağ isteği başarısız",
+ "cached": "Yenileme başarısız; önbellekteki eklentiler gösteriliyor",
+ "unavailable": "Eklenti kataloğu yüklenemedi",
+ "direct": "{{host}} doğrudan bağlantısı başarısız: {{reason}}",
+ "viaProxy": "{{proxy}} proxy sunucusu üzerinden {{host}} bağlantısı başarısız: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index a8d54824..2693b48e 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -1726,6 +1726,20 @@
"compromised": "Канал розповсюдження цього плагіна було скомпрометовано.",
"fixedVersion": "Виправлення доступне у версії {{version}}.",
"details": "Переглянути повідомлення про безпеку"
+ },
+ "network": {
+ "timeout": "Час очікування з’єднання минув",
+ "dns": "Помилка DNS",
+ "proxyAuth": "Помилка автентифікації проксі",
+ "proxyConnect": "Не вдалося підключитися до проксі",
+ "certificate": "Помилка сертифіката або TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Запит скасовано",
+ "network": "Помилка мережевого запиту",
+ "cached": "Оновлення не вдалося; показано плагіни з кешу",
+ "unavailable": "Не вдалося завантажити каталог плагінів",
+ "direct": "Помилка прямого підключення до {{host}}: {{reason}}",
+ "viaProxy": "Помилка підключення до {{host}} через проксі {{proxy}}: {{reason}}"
}
},
"quit": {
@@ -2630,7 +2644,7 @@
"bypass": "Підключатися напряму до",
"bypassDesc": "Один домен, IP-адреса або CIDR на рядок. Почніть із крапки, щоб охопити лише піддомени. Завантаження файлів не підтримує шаблон *.",
"bypassPlaceholder": "localhost\n127.0.0.1\n.local",
- "bypassScopeNote": "Лише завантаження файлів і оновлення програми",
+ "bypassScopeNote": "Лише завантаження, плагіни й оновлення застосунку",
"enable": "Увімкнути проксі",
"enableDesc": "Використовувати проксі для вибраних нижче з'єднань.",
"hidePassword": "Приховати пароль",
@@ -2657,7 +2671,9 @@
"server": "Сервер",
"showPassword": "Показати пароль",
"title": "Проксі",
- "user": "Ім'я користувача"
+ "user": "Ім'я користувача",
+ "scopePlugins": "Встановлення й оновлення плагінів",
+ "scopePluginsDesc": "Використовувати проксі для каталогу, пакетів, оновлень і політик безпеки плагінів."
},
"reachability": {
"addEndpoint": "Додати службу перевірки",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 083ce15a..bdf0d457 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1693,7 +1693,7 @@
"hidePassword": "Ẩn mật khẩu",
"bypass": "Kết nối trực tiếp đến",
"bypassDesc": "Mỗi dòng một tên miền, IP hoặc CIDR. Bắt đầu bằng dấu . để chỉ khớp tên miền con. Tải tệp không hỗ trợ ký tự đại diện *.",
- "bypassScopeNote": "Chỉ áp dụng cho tải tệp và cập nhật ứng dụng",
+ "bypassScopeNote": "Chỉ tải xuống, tiện ích và cập nhật ứng dụng",
"scopes": "Dùng proxy cho",
"scopesDesc": "Chọn các loại lưu lượng đi qua proxy.",
"scopeDownload": "Tải tệp",
@@ -1709,7 +1709,9 @@
"scopeHint": "Máy ngang hàng BT, DHT và máy chủ theo dõi UDP kết nối trực tiếp.",
"scopeNone": "Chưa chọn",
"scopeChoose": "Chọn…",
- "scopeSeparator": ", "
+ "scopeSeparator": ", ",
+ "scopePlugins": "Cài đặt và cập nhật tiện ích",
+ "scopePluginsDesc": "Dùng proxy cho danh mục, gói cài đặt, bản cập nhật và yêu cầu chính sách bảo mật của tiện ích."
},
"nat": {
"title": "Ánh xạ cổng (NAT)",
@@ -2700,6 +2702,20 @@
"compromised": "Kênh phân phối tiện ích này đã bị xâm phạm.",
"fixedVersion": "Bản sửa lỗi có trong phiên bản {{version}}.",
"details": "Xem thông báo bảo mật"
+ },
+ "network": {
+ "timeout": "Kết nối hết thời gian chờ",
+ "dns": "Tra cứu DNS thất bại",
+ "proxyAuth": "Xác thực proxy thất bại",
+ "proxyConnect": "Không thể kết nối tới proxy",
+ "certificate": "Lỗi chứng chỉ hoặc TLS",
+ "http": "HTTP {{status}}",
+ "cancelled": "Yêu cầu đã bị hủy",
+ "network": "Yêu cầu mạng thất bại",
+ "cached": "Làm mới thất bại; đang hiển thị tiện ích đã lưu đệm",
+ "unavailable": "Không thể tải danh mục tiện ích",
+ "direct": "Kết nối trực tiếp tới {{host}} thất bại: {{reason}}",
+ "viaProxy": "Kết nối tới {{host}} qua proxy {{proxy}} thất bại: {{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index cf7ea8b3..71d7d860 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1693,7 +1693,7 @@
"hidePassword": "隐藏密码",
"bypass": "不使用代理的地址",
"bypassDesc": "每行填写一个域名、IP 或 CIDR。开头加 . 仅匹配子域名。文件下载不支持 * 通配符。",
- "bypassScopeNote": "仅下载文件和更新应用",
+ "bypassScopeNote": "仅下载文件、插件和更新应用",
"scopes": "代理用途",
"scopesDesc": "选择哪些流量通过代理。",
"scopeDownload": "下载文件",
@@ -1709,7 +1709,9 @@
"scopeHint": "BT 节点、DHT 和 UDP Tracker 仍直接连接。",
"scopeNone": "未选择",
"scopeChoose": "选择…",
- "scopeSeparator": "、"
+ "scopeSeparator": "、",
+ "scopePlugins": "插件安装与更新",
+ "scopePluginsDesc": "为插件市场、安装包、插件更新和安全策略请求使用代理。"
},
"nat": {
"title": "端口映射(NAT)",
@@ -2700,6 +2702,20 @@
"compromised": "此插件的分发渠道已遭入侵。",
"fixedVersion": "修复版本:{{version}}。",
"details": "查看安全公告"
+ },
+ "network": {
+ "timeout": "连接超时",
+ "dns": "DNS 解析失败",
+ "proxyAuth": "代理认证失败",
+ "proxyConnect": "无法连接代理",
+ "certificate": "证书或 TLS 错误",
+ "http": "HTTP {{status}}",
+ "cancelled": "请求已取消",
+ "network": "网络请求失败",
+ "cached": "刷新失败,正在显示缓存的插件",
+ "unavailable": "无法加载插件市场",
+ "direct": "直连 {{host}} 失败:{{reason}}",
+ "viaProxy": "通过代理 {{proxy}} 连接 {{host}} 失败:{{reason}}"
}
},
"plugin": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 701a98cd..6eb1522d 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1693,7 +1693,7 @@
"hidePassword": "隱藏密碼",
"bypass": "不使用代理的位址",
"bypassDesc": "每行填寫一個網域、IP 或 CIDR。開頭加 . 僅比對子網域。檔案下載不支援 * 萬用字元。",
- "bypassScopeNote": "僅下載檔案和更新應用程式",
+ "bypassScopeNote": "僅下載檔案、外掛和更新應用程式",
"scopes": "代理用途",
"scopesDesc": "選擇哪些流量要通過 Proxy。",
"scopeDownload": "下載檔案",
@@ -1709,7 +1709,9 @@
"scopeHint": "BT 節點、DHT 和 UDP Tracker 仍直接連線。",
"scopeNone": "未選取",
"scopeChoose": "選擇…",
- "scopeSeparator": "、"
+ "scopeSeparator": "、",
+ "scopePlugins": "外掛安裝與更新",
+ "scopePluginsDesc": "為外掛市集、安裝套件、外掛更新和安全性原則請求使用代理。"
},
"nat": {
"title": "連接埠對映(NAT)",
@@ -2800,6 +2802,20 @@
"compromised": "此外掛的散布管道已遭入侵。",
"fixedVersion": "修復版本:{{version}}。",
"details": "檢視安全公告"
+ },
+ "network": {
+ "timeout": "連線逾時",
+ "dns": "DNS 解析失敗",
+ "proxyAuth": "代理驗證失敗",
+ "proxyConnect": "無法連線至代理",
+ "certificate": "憑證或 TLS 錯誤",
+ "http": "HTTP {{status}}",
+ "cancelled": "請求已取消",
+ "network": "網路請求失敗",
+ "cached": "重新整理失敗,正在顯示快取的外掛",
+ "unavailable": "無法載入外掛市集",
+ "direct": "直接連線至 {{host}} 失敗:{{reason}}",
+ "viaProxy": "透過代理 {{proxy}} 連線至 {{host}} 失敗:{{reason}}"
}
},
"applicationMenu": {
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index 4c69ba9c..b27b4bb9 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -39,6 +39,7 @@ export const Queries = {
// Entries come back annotated with a `compatible` host-version flag.
// Contract: .claude/rules/plugin-registry.md.
ListRegistryPlugins: 'query:listRegistryPlugins',
+ GetRegistryStatus: 'query:getRegistryStatus',
GetRegistryPlugin: 'query:getRegistryPlugin',
// Spec §10 L2877 — aggregate snapshot of all enabled plugins'
// contributions (commands, hooks, configurations). Drives the renderer's
diff --git a/src/shared/schemas/plugin-network.ts b/src/shared/schemas/plugin-network.ts
new file mode 100644
index 00000000..0c2fd9c2
--- /dev/null
+++ b/src/shared/schemas/plugin-network.ts
@@ -0,0 +1,34 @@
+import { z } from 'zod'
+
+export const pluginNetworkFailureSchema = z.object({
+ reason: z.enum([
+ 'timeout',
+ 'dns',
+ 'proxyAuth',
+ 'proxyConnect',
+ 'certificate',
+ 'http',
+ 'cancelled',
+ 'network',
+ ]),
+ // Consumer deadlines or response validation can fail outside the transport.
+ // Only report a route when the transport supplied that information.
+ route: z.enum(['direct', 'proxy']).optional(),
+ proxyEndpoint: z.string().optional(),
+ targetHost: z.string(),
+ status: z.number().int().optional(),
+})
+
+export type PluginNetworkFailure = z.infer<typeof pluginNetworkFailureSchema>
+
+export const registryStatusSchema = z.object({
+ cached: z.boolean(),
+ lastSuccessAt: z.number().nullable(),
+ error: pluginNetworkFailureSchema.nullable(),
+})
+
+export type RegistryStatus = z.infer<typeof registryStatusSchema>
+
+export interface PluginNetworkFailureResult {
+ networkError: PluginNetworkFailure
+}
diff --git a/src/shared/schemas/proxy-settings.test.ts b/src/shared/schemas/proxy-settings.test.ts
index 515bebdd..0fcbe341 100644
--- a/src/shared/schemas/proxy-settings.test.ts
+++ b/src/shared/schemas/proxy-settings.test.ts
@@ -15,6 +15,7 @@ describe('proxySettingsSchema', () => {
download: false,
updateApp: false,
updateTrackers: false,
+ plugins: false,
})
})
@@ -71,6 +72,21 @@ describe('proxySettingsSchema', () => {
expect(parsed.bypass).toEqual([])
})
+ it('preserves an explicitly disabled plugin scope during migration', () => {
+ expect(
+ proxySettingsSchema.parse({ scopes: { download: true, plugins: false } })
+ .scopes.plugins
+ ).toBe(false)
+ })
+
+ it('does not inherit other proxy scopes', () => {
+ expect(
+ proxySettingsSchema.parse({
+ scopes: { updateApp: true, updateTrackers: true },
+ }).scopes.plugins
+ ).toBe(false)
+ })
+
it('parses partial scopes', () => {
const r = proxySettingsSchema.parse({
scopes: { download: true },
@@ -79,6 +95,7 @@ describe('proxySettingsSchema', () => {
download: true,
updateApp: false,
updateTrackers: false,
+ plugins: true,
})
})
})
diff --git a/src/shared/schemas/proxy-settings.ts b/src/shared/schemas/proxy-settings.ts
index 1bfc0db0..a7e40437 100644
--- a/src/shared/schemas/proxy-settings.ts
+++ b/src/shared/schemas/proxy-settings.ts
@@ -16,6 +16,22 @@ function hasC0OrDel(value: string): boolean {
return false
}
+const proxyScopesSchema = z.object({
+ download: z.boolean().catch(false),
+ updateApp: z.boolean().catch(false),
+ updateTrackers: z.boolean().catch(false),
+ plugins: z.boolean().catch(false),
+})
+
+function migrateProxyScopes(input: unknown): unknown {
+ if (typeof input !== 'object' || input === null || Array.isArray(input))
+ return input
+ const scopes = input as Record<string, unknown>
+ return Object.hasOwn(scopes, 'plugins')
+ ? scopes
+ : { ...scopes, plugins: scopes.download === true }
+}
+
export const proxySettingsSchema = z.object({
enabled: z.boolean().catch(false),
protocol: z.enum(['http', 'https', 'socks5']).catch('http'),
@@ -24,13 +40,12 @@ export const proxySettingsSchema = z.object({
user: withoutControlCharacters(256).catch(''),
password: withoutControlCharacters(256).catch(''),
bypass: z.array(withoutControlCharacters(253)).max(64).catch([]),
- scopes: z
- .object({
- download: z.boolean().catch(false),
- updateApp: z.boolean().catch(false),
- updateTrackers: z.boolean().catch(false),
- })
- .catch({ download: false, updateApp: false, updateTrackers: false }),
+ scopes: z.preprocess(migrateProxyScopes, proxyScopesSchema).catch({
+ download: false,
+ updateApp: false,
+ updateTrackers: false,
+ plugins: false,
+ }),
})
export const DEFAULT_PROXY_SETTINGS: ProxySettings = proxySettingsSchema.parse(
@@ -56,7 +71,7 @@ function isProxyHost(host: string): boolean {
export const proxySettingsInputSchema = settingsInputObject(proxySettingsSchema)
.extend({
- scopes: settingsInputObject(proxySettingsSchema.shape.scopes.removeCatch()),
+ scopes: settingsInputObject(proxyScopesSchema),
})
.superRefine((value, ctx) => {
if (value.enabled && !isProxyHost(value.host)) {
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index bdb449e4..2825bf00 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -311,5 +311,6 @@ export interface ProxySettings {
download: boolean
updateApp: boolean
updateTrackers: boolean
+ plugins: boolean
}
}
diff --git a/src/test-utils/plugin-test-tls.ts b/src/test-utils/plugin-test-tls.ts
new file mode 100644
index 00000000..2305d165
--- /dev/null
+++ b/src/test-utils/plugin-test-tls.ts
@@ -0,0 +1,49 @@
+// Localhost-only TLS identity for proxy integration tests.
+export const TEST_TLS_KEY = `-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCzMvQoVep4eh5K
++yQsBf6kaWJOj8Pzpr7aBxnoHR5NJeQBpg3h4J5pBSyoNdLKbFV6vSnt8IMLhlU+
+jTPgx9oPPUjNgijiF+Q+3cx+k+NnJKxxO1vWB7IYkvIHuqVuWwA856Ya/ipZb1o4
+xK9oQgEXhsAglTCT7SRJJgJ4a7sM+4acKSvb7zoml0mLwvbFoldt6hOw+TYbAtzo
+kSP+SqVUyuO8tndn4ZdFHLQ2SEEUT2lJj29XQHU9qbu1TguFMZEcMIjAGiY6f7be
+gTpaC1In9iQq7Gdu6ILNMOe8a1NdjrKy/UqxkB4p3YpvvRwf3uCwRWS3BxBW6HuH
+j7A+Y/OxAgMBAAECggEAATOkxoZ4+ZDcFiWkAvWRVRnt0lgNeNtT6VNl3ZQgaWUJ
+J+esrSib91lVCNW/kaLzWczd9J4JyvB+Ltq0j9vXPwXqsJIgYw/E9JT5M5obSsxI
+qcO7pG5Nx/NoUxvx0xEiKcZl60VsFEh2Yu4SvRDAQB+jtzQ47K0I8sKh/pu+V+Jv
+D4F7bWCunhaOM0WVvoFPQ6KQPccoJaRL0EvCykpSUZTzwHmJ1BJL/dFxp+BsABCL
+g26gomB72qJhbSCY5owx5F5iLKQUy7EU2QYAIHg+v6tuLpdugZq+JtvMQQnTMI74
+dkL8rWWpBsmKRL99qfj27SCHYQCflb04T7CtQ1XO5wKBgQDbrq0FAR7q7tVfmavP
+oGU/7TsjXbE8EWs9REAmBU5usiz1ZjGzGNUcCWTs3JhLpssh7hGJgYfLqvFh88tS
+CRfCxO5x05uRaOEsI1hovj74KlLLNv84ytC+9i+PP940Lp6fjxK0T0aCxqUruZT0
+SDkHKbfo/jQXO011wobSBlzyywKBgQDQ0vUOLlX9ze/DBSVqFAYuivomlp3vq44J
+5A306hEehMCveQHSzon4G7gVzGQESfWGkd8iHnZqmLMSsFBS4kU8ZH6kc8WuSfkY
+NnFAAYP/LGxjt0hIilGSj65G0PcAFqvppiFgR+EYpr/DmqEST9rqEqpQBIuRgac5
+qao+B6PX8wKBgEDlOPdhfWCpbR7wpnCPUVmxGuc3pkO4YZWXs9uHdcP9nopfxg7C
+JzJBFC9kexjeDOPZEBUuzo670NK+0jFJvlsrEcVOXYZ3FQ2U42kNykxFNHATrxF3
+2HKRBzuqAlon63P3L+9T++BmDiT8jaQcMbyL9mg9r+Ws/xTqgilI9+xBAoGANcD3
+/8yBqjGmtEbQ2LuK09RGjERdJ2K7z2P7C75s5bQ6fXDivUcZUNqhykqwvEHlh9xo
+2bmJterUvczRAGTqeZ9M0jxS+IhmLItnH5jER51B0XFOlA227ck6jVQhIM61NhHj
+qYsXMGdMGafmKnaP3Y0sdiiVXMFJMJiyEAGbdW0CgYBCkkVR3Qa3LhqhgHOPW98n
+RAMHTNmhgGOEDq1vzT61ApiW3WlQxwwjTfELY6ynqxRSeXKYVude2iRIT78MJtT4
+CLjJyy6J2Gj19g1Wj0DWmoxvTsCu9RKi+O02AVXm/HXV3HhIyfO7ggBbF+MLr+tl
+oBhOGFOBD2dWzgKDbyy6hw==
+-----END PRIVATE KEY-----`
+
+export const TEST_TLS_CERT = `-----BEGIN CERTIFICATE-----
+MIIDJTCCAg2gAwIBAgIUF4ztfsfVGCjAspx3wLeWkRvmQ6AwDQYJKoZIhvcNAQEL
+BQAwFDESMBAGA1UEAwwJMTI3LjAuMC4xMB4XDTI2MDgyOTAxNDEzNFoXDTM2MDgy
+NjAxNDEzNFowFDESMBAGA1UEAwwJMTI3LjAuMC4xMIIBIjANBgkqhkiG9w0BAQEF
+AAOCAQ8AMIIBCgKCAQEAszL0KFXqeHoeSvskLAX+pGliTo/D86a+2gcZ6B0eTSXk
+AaYN4eCeaQUsqDXSymxVer0p7fCDC4ZVPo0z4MfaDz1IzYIo4hfkPt3MfpPjZySs
+cTtb1geyGJLyB7qlblsAPOemGv4qWW9aOMSvaEIBF4bAIJUwk+0kSSYCeGu7DPuG
+nCkr2+86JpdJi8L2xaJXbeoTsPk2GwLc6JEj/kqlVMrjvLZ3Z+GXRRy0NkhBFE9p
+SY9vV0B1Pam7tU4LhTGRHDCIwBomOn+23oE6WgtSJ/YkKuxnbuiCzTDnvGtTXY6y
+sv1KsZAeKd2Kb70cH97gsEVktwcQVuh7h4+wPmPzsQIDAQABo28wbTAdBgNVHQ4E
+FgQUvtf3LJ4KQlKUHYglQPJnzriNmXkwHwYDVR0jBBgwFoAUvtf3LJ4KQlKUHYgl
+QPJnzriNmXkwDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARhwR/AAABgglsb2Nh
+bGhvc3QwDQYJKoZIhvcNAQELBQADggEBAD91BW2leyuWHz4XVE/kY+KXhyWr189q
+76JVkJvXSpe1xxfj05mj5h4tug1ScqoTM9LRN4zfxyO4Sg2VdFx26UnJewFUvMdo
+8y2xgNt3E1BZvmFeSVqs4xZBYJN755/K4DGKKyxUNGpMwj2mRTx1+d5+RuEuwQ3h
+lXLsEqlkYSRsOePFt1FG7S3lqvvp0FZIhm6OfJSwonFzyLUy4a2N/2UIk75ppjS2
+lTv1/xRVw+/pxmhhc+8i/YrbEdtgNk8Q+qBo1HMYXQxiTMm1nNBIWx/A0BNhlSh5
+1RW5cFDUfeI1TKinPDbPqqqYkOZQ55kzjk4OrCN+WW4e2+3xayAfOWY=
+-----END CERTIFICATE-----`