From df184958170cd52c321cbed0339e7351cad43d5a Mon Sep 17 00:00:00 2001 From: Minecraft Workbench Contributor Date: Thu, 29 Oct 2026 14:56:33 +0800 Subject: [PATCH 1/5] fix(lifecycle): keep activation alive when the proxy setting is unusable A malformed `minecraftWorkbench.proxy`/`http.proxy` value, a proxy scheme other than HTTP(S)/SOCKS5, or a corrupt `proxyCredentials` secret made `activate()` throw: `new URL` or `new ProxyAgent` failed before any view, command or status item was registered, so the whole extension disappeared without an error the user could act on. Credential merging and proxy validation now happen in `src/proxy.ts`, which reports invalid input instead of throwing, and the network layer is created with a last-resort fallback to a direct connection. Both cases surface as a warning so the setting stays discoverable. --- src/extension.ts | 54 ++++++++++++++++++++++++++++++-------------- src/proxy.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++ test/proxy.test.ts | 49 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 142 insertions(+), 17 deletions(-) create mode 100644 src/proxy.ts create mode 100644 test/proxy.test.ts diff --git a/src/extension.ts b/src/extension.ts index c913888..554594e 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -15,6 +15,26 @@ import { config, t } from './config'; import { exists } from './files'; import { Workbench } from './workbench'; import { Consent } from './consent'; +import { resolveProxy } from './proxy'; +import { describeError } from './errors'; + +const text = (value: unknown) => (typeof value === 'string' ? value.trim() : ''); + +function createNetwork(proxy: string, output: vscode.LogOutputChannel): Network { + const options = { + proxy, + sources: config('sources', {}), + concurrency: Math.max(1, Math.min(32, config('downloadConcurrency', 6))), + retries: config('downloadRetries', 2), + timeout: config('networkTimeout', 30000), + }; + try { + return new Network(options); + } catch (error) { + output.error(`Proxy disabled: ${describeError(error)}`); + return new Network({ ...options, proxy: '' }); + } +} export async function activate(context: vscode.ExtensionContext) { const output = vscode.window.createOutputChannel('Minecraft Workbench', { log: true }); @@ -68,24 +88,24 @@ export async function activate(context: vscode.ExtensionContext) { return; } context.subscriptions.push(store); - let proxy = - config('proxy', '').trim() || - vscode.workspace.getConfiguration('http').get('proxy', '').trim(); + const proxySetting = + text(config('proxy', '')) || + text(vscode.workspace.getConfiguration('http').get('proxy', '')); const credentials = await context.secrets.get('minecraftWorkbench.proxyCredentials'); - if (proxy && credentials) { - const url = new URL(proxy); - const value = JSON.parse(credentials); - url.username = value.username; - url.password = value.password; - proxy = url.toString(); - } - const network = new Network({ - proxy, - sources: config('sources', {}), - concurrency: Math.max(1, Math.min(32, config('downloadConcurrency', 6))), - retries: config('downloadRetries', 2), - timeout: config('networkTimeout', 30000), - }); + const resolved = resolveProxy(proxySetting, credentials); + if (resolved.problem) + void vscode.window.showWarningMessage( + resolved.problem === 'unsupported' + ? t( + 'Ignoring the proxy setting: use an HTTP, HTTPS, SOCKS5 or SOCKS5h proxy.', + '已忽略代理设置:请使用 HTTP、HTTPS、SOCKS5 或 SOCKS5h 代理。', + ) + : t( + 'Ignoring the proxy setting: it is not a valid proxy URL.', + '已忽略代理设置:代理地址不是有效的 URL。', + ), + ); + const network = createNetwork(resolved.proxy, output); context.subscriptions.push({ dispose: () => { void network.close(); diff --git a/src/proxy.ts b/src/proxy.ts new file mode 100644 index 0000000..01bdb96 --- /dev/null +++ b/src/proxy.ts @@ -0,0 +1,56 @@ +export type ProxyProblem = 'invalid' | 'unsupported'; + +export interface ProxyResolution { + proxy: string; + problem?: ProxyProblem; +} + +const schemes = ['http:', 'https:', 'socks:', 'socks5:', 'socks5h:']; + +function parseCredentials(value: unknown): { username: string; password: string } | undefined { + let source = value; + if (typeof source === 'string') { + if (!source.trim()) return undefined; + try { + source = JSON.parse(source); + } catch { + return undefined; + } + } + if (!source || typeof source !== 'object') return undefined; + const record = source as Record; + const username = typeof record.username === 'string' ? record.username : ''; + const password = typeof record.password === 'string' ? record.password : ''; + if (!username && !password) return undefined; + return { username, password }; +} + +/** + * Turns the configured proxy plus the stored credentials into the URL handed to + * the network layer. Invalid input is reported instead of thrown so that a bad + * `http.proxy` value can never stop the extension from activating. + */ +export function resolveProxy(raw: unknown, credentials?: unknown): ProxyResolution { + const proxy = typeof raw === 'string' ? raw.trim() : ''; + if (!proxy) return { proxy: '' }; + let url: URL; + try { + url = new URL(proxy); + } catch { + return { proxy: '', problem: 'invalid' }; + } + if (!schemes.includes(url.protocol)) return { proxy: '', problem: 'unsupported' }; + const value = parseCredentials(credentials); + if (!value) return { proxy }; + url.username = value.username; + url.password = value.password; + const serialized = url.toString(); + // `URL` adds an implicit trailing slash to http(s) URLs. Drop it again so the + // value keeps the shape the user typed instead of differing from the + // credential-less branch for no functional reason. + const trimmed = + url.pathname === '/' && !url.search && !url.hash && !proxy.endsWith('/') + ? serialized.replace(/\/$/, '') + : serialized; + return { proxy: trimmed }; +} diff --git a/test/proxy.test.ts b/test/proxy.test.ts new file mode 100644 index 0000000..ecdecaa --- /dev/null +++ b/test/proxy.test.ts @@ -0,0 +1,49 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { resolveProxy } from '../src/proxy'; + +test('an unusable proxy setting is reported instead of thrown', () => { + assert.deepEqual(resolveProxy(''), { proxy: '' }); + assert.deepEqual(resolveProxy(' '), { proxy: '' }); + assert.deepEqual(resolveProxy(undefined), { proxy: '' }); + assert.deepEqual(resolveProxy('127.0.0.1:7890'), { proxy: '', problem: 'invalid' }); + assert.deepEqual(resolveProxy('not a url'), { proxy: '', problem: 'invalid' }); + assert.deepEqual(resolveProxy('ftp://proxy.test:21'), { proxy: '', problem: 'unsupported' }); + assert.deepEqual(resolveProxy('file:///tmp/socket'), { proxy: '', problem: 'unsupported' }); +}); +test('stored proxy credentials are applied without corrupting the URL', () => { + assert.deepEqual(resolveProxy('http://proxy.test:8080', '{"username":"u","password":"p"}'), { + proxy: 'http://u:p@proxy.test:8080', + }); + assert.deepEqual(resolveProxy('http://proxy.test/', { username: 'u', password: 'p' }), { + proxy: 'http://u:p@proxy.test/', + }); + assert.deepEqual(resolveProxy('http://proxy.test/path', { username: 'u' }), { + proxy: 'http://u@proxy.test/path', + }); + assert.deepEqual(resolveProxy('http://proxy.test', { username: 'u' }), { + proxy: 'http://u@proxy.test', + }); + assert.deepEqual( + resolveProxy('socks5h://proxy.test:1080', { username: 'a@b', password: 'p:w' }), + { proxy: 'socks5h://a%40b:p%3Aw@proxy.test:1080' }, + ); + assert.deepEqual(resolveProxy('socks5://proxy.test:1080', { username: 'u' }), { + proxy: 'socks5://u@proxy.test:1080', + }); +}); +test('missing or corrupt credentials leave a valid proxy untouched', () => { + assert.deepEqual(resolveProxy('http://proxy.test:8080'), { proxy: 'http://proxy.test:8080' }); + assert.deepEqual(resolveProxy('http://proxy.test:8080', 'not json'), { + proxy: 'http://proxy.test:8080', + }); + assert.deepEqual(resolveProxy('http://proxy.test:8080', '{}'), { + proxy: 'http://proxy.test:8080', + }); + assert.deepEqual(resolveProxy('http://proxy.test:8080', { username: 42 }), { + proxy: 'http://proxy.test:8080', + }); + assert.deepEqual(resolveProxy('http://proxy.test:8080', null), { + proxy: 'http://proxy.test:8080', + }); +}); From 1cf0305b98f44f7da22fe53983e4f580dd372b19 Mon Sep 17 00:00:00 2001 From: Minecraft Workbench Contributor Date: Thu, 29 Oct 2026 14:57:18 +0800 Subject: [PATCH 2/5] fix(network): take the User-Agent version from the extension manifest Both request paths hard-coded `MinecraftWorkbench/0.3.1` while the manifest already declares 0.3.3, so Mojang, Modrinth and CDN logs would keep showing a stale client version forever. The value now comes from the installed manifest through `vscode.extensions` and is passed into `Network`, which also prevents the two copies from diverging again. --- src/extension.ts | 2 ++ src/network.ts | 7 ++++-- src/user-agent.ts | 21 ++++++++++++++++++ test/preload.cjs | 5 +++++ test/user-agent.test.ts | 47 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 src/user-agent.ts create mode 100644 test/user-agent.test.ts diff --git a/src/extension.ts b/src/extension.ts index 554594e..a8a7a8a 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -17,12 +17,14 @@ import { Workbench } from './workbench'; import { Consent } from './consent'; import { resolveProxy } from './proxy'; import { describeError } from './errors'; +import { extensionVersion, userAgent } from './user-agent'; const text = (value: unknown) => (typeof value === 'string' ? value.trim() : ''); function createNetwork(proxy: string, output: vscode.LogOutputChannel): Network { const options = { proxy, + userAgent: userAgent(extensionVersion()), sources: config('sources', {}), concurrency: Math.max(1, Math.min(32, config('downloadConcurrency', 6))), retries: config('downloadRetries', 2), diff --git a/src/network.ts b/src/network.ts index f553dda..c443c8e 100644 --- a/src/network.ts +++ b/src/network.ts @@ -15,6 +15,7 @@ export interface NetworkOptions { concurrency: number; retries?: number; timeout?: number; + userAgent?: string; } interface JsonOptions { method?: 'GET' | 'POST'; @@ -34,7 +35,9 @@ export class HttpError extends Error { } export class Network { readonly dispatcher: Dispatcher; + readonly userAgent: string; constructor(readonly options: NetworkOptions) { + this.userAgent = options.userAgent?.trim() || 'MinecraftWorkbench'; if (/^socks/.test(options.proxy)) { const proxy = new URL(options.proxy); if (!['socks:', 'socks5:', 'socks5h:'].includes(proxy.protocol)) @@ -96,7 +99,7 @@ export class Network { dispatcher: this.dispatcher, method: options.method || 'GET', headers: { - 'user-agent': 'MinecraftWorkbench/0.3.1', + 'user-agent': this.userAgent, ...(options.body ? { 'content-type': 'application/json' } : {}), ...(options.form ? { 'content-type': 'application/x-www-form-urlencoded' } : {}), ...options.headers, @@ -151,7 +154,7 @@ export class Network { dispatcher: this.dispatcher, signal: options.signal, headers: { - 'user-agent': 'MinecraftWorkbench/0.3.1', + 'user-agent': this.userAgent, ...(offset ? { Range: `bytes=${offset}-`, diff --git a/src/user-agent.ts b/src/user-agent.ts new file mode 100644 index 0000000..6057165 --- /dev/null +++ b/src/user-agent.ts @@ -0,0 +1,21 @@ +import * as vscode from 'vscode'; + +export const extensionId = 'minecraft-workbench.minecraft-workbench'; + +export function userAgent(version: string): string { + const value = version.trim(); + return value ? `MinecraftWorkbench/${value}` : 'MinecraftWorkbench'; +} + +/** + * Reads the version from the installed manifest so the User-Agent always + * matches the running build instead of drifting away from package.json. + */ +export function extensionVersion(): string { + try { + const value = vscode.extensions?.getExtension?.(extensionId)?.packageJSON?.version; + return typeof value === 'string' ? value : ''; + } catch { + return ''; + } +} diff --git a/test/preload.cjs b/test/preload.cjs index 9ff3261..3af07d6 100644 --- a/test/preload.cjs +++ b/test/preload.cjs @@ -1,9 +1,14 @@ const Module = require('node:module'); const path = require('node:path'); +const manifest = require('../package.json'); const original = Module._load; const stub = { workspace: { getConfiguration: () => ({ get: (_key, fallback) => fallback }), isTrusted: true }, env: { language: 'en' }, + extensions: { + getExtension: (id) => + id === `${manifest.publisher}.${manifest.name}` ? { packageJSON: manifest } : undefined, + }, ConfigurationTarget: { Global: 1, Workspace: 2 }, TreeItem: class {}, TreeItemCollapsibleState: { None: 0, Collapsed: 1 }, diff --git a/test/user-agent.test.ts b/test/user-agent.test.ts new file mode 100644 index 0000000..51efe64 --- /dev/null +++ b/test/user-agent.test.ts @@ -0,0 +1,47 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import * as fs from 'node:fs/promises'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import manifest from '../package.json'; +import { extensionId, extensionVersion, userAgent } from '../src/user-agent'; +import { Network } from '../src/network'; + +test('the extension id and version are read from the running manifest', () => { + assert.equal(extensionId, `${manifest.publisher}.${manifest.name}`); + assert.equal(extensionVersion(), manifest.version); + assert.equal(userAgent(extensionVersion()), `MinecraftWorkbench/${manifest.version}`); + assert.equal(userAgent(''), 'MinecraftWorkbench'); +}); +test('API and download requests send the manifest version as User-Agent', async () => { + const seen: (string | undefined)[] = []; + const server = createServer((req, res) => { + seen.push(req.headers['user-agent']); + res.writeHead(200, { 'content-length': 2 }); + res.end('{}'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as { port: number }; + const base = `http://127.0.0.1:${address.port}`; + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'mc-agent-')); + const network = new Network({ + proxy: '', + sources: {}, + concurrency: 1, + userAgent: userAgent(extensionVersion()), + }); + try { + assert.equal(network.userAgent, `MinecraftWorkbench/${manifest.version}`); + await network.json(`${base}/api`); + await network.download(`${base}/file`, path.join(root, 'file')); + assert.deepEqual(seen, [ + `MinecraftWorkbench/${manifest.version}`, + `MinecraftWorkbench/${manifest.version}`, + ]); + } finally { + await network.close(); + await new Promise((resolve) => server.close(() => resolve())); + await fs.rm(root, { recursive: true, force: true }); + } +}); From 9fd81d5b90bd29b0e1c13095dae0e8f934bc8695 Mon Sep 17 00:00:00 2001 From: Minecraft Workbench Contributor Date: Thu, 29 Oct 2026 15:06:24 +0800 Subject: [PATCH 3/5] fix(ui): keep non-ASCII instance names in suggested export file names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `instance.name.replace(/[^\\w.-]/g, '_')` treats every non-ASCII letter as illegal, so exporting an instance called 我的世界 or サーバー用 offered a file named `_________.mrpack`. Only characters that Windows and macOS actually reject are rewritten now; leading and trailing dots, over-long names and the DOS device names (CON, LPT1, ...) are handled too, so the suggestion is a name the platform will accept. --- src/files.ts | 16 ++++++++++++++++ src/ui.ts | 6 +++--- test/files.test.ts | 23 ++++++++++++++++++++++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/files.ts b/src/files.ts index 748381a..b562989 100644 --- a/src/files.ts +++ b/src/files.ts @@ -29,6 +29,22 @@ export function filename(name: string): string { throw new Error('Invalid filename'); return name; } +const illegal = /[\x00-\x1f<>:"/\\|?*]+/g; +const device = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i; +/** + * Suggests a file name for an exported instance. Characters that Windows and + * macOS reject become underscores, while letters from every script are kept: + * the previous pattern rewrote CJK names into a run of underscores. Windows + * also refuses the reserved device names no matter the extension. + */ +export function suggestedFilename(value: string, fallback = 'instance'): string { + const kept = value.replace(illegal, '_').replace(/\s+/g, ' ').trim().slice(0, 80); + // A hard cut can land between the halves of a surrogate pair; dropping the + // orphan keeps the suggestion a string the file system will accept. + const name = /[\uD800-\uDBFF]$/.test(kept) ? kept.slice(0, -1) : kept; + const cleaned = name.replace(/^[.\s]+/, '').replace(/[.\s]+$/, '') || fallback; + return device.test(cleaned.split('.')[0]) ? `${cleaned}_` : cleaned; +} export async function exists(target: string): Promise { try { await fs.access(target); diff --git a/src/ui.ts b/src/ui.ts index 4fc0930..d715b83 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -13,7 +13,7 @@ import { Backups } from './backups'; import { Item } from './views'; import { Instance, Content, ContentKind, Account } from './models'; import { config, t, trusted, setLanguage } from './config'; -import { exists, writeJson } from './files'; +import { exists, suggestedFilename, writeJson } from './files'; import { describeError } from './errors'; import { InstanceFiles } from './instance-files'; import { ContentInstallOptions, contentFile } from './modrinth'; @@ -246,7 +246,7 @@ export class UI { const instance = await this.instance(item); this.idle(instance); const destination = await vscode.window.showSaveDialog({ - defaultUri: vscode.Uri.file(`${instance.name.replace(/[^\w.-]/g, '_')}.mrpack`), + defaultUri: vscode.Uri.file(`${suggestedFilename(instance.name)}.mrpack`), filters: { 'Modrinth modpack': ['mrpack'] }, }); if (!destination) return; @@ -504,7 +504,7 @@ export class UI { async exportInstance(item?: Item) { const instance = await this.instance(item); const destination = await vscode.window.showSaveDialog({ - defaultUri: vscode.Uri.file(`${instance.name.replace(/[^\w.-]/g, '_')}.json`), + defaultUri: vscode.Uri.file(`${suggestedFilename(instance.name)}.json`), filters: { JSON: ['json'] }, }); if (destination) diff --git a/test/files.test.ts b/test/files.test.ts index 5af1b61..b7087a5 100644 --- a/test/files.test.ts +++ b/test/files.test.ts @@ -4,7 +4,15 @@ import * as fs from 'node:fs/promises'; import * as path from 'node:path'; import * as os from 'node:os'; import AdmZip from 'adm-zip'; -import { extractZip, offlineUuid, readJson, redact, within, writeJson } from '../src/files'; +import { + extractZip, + offlineUuid, + readJson, + redact, + suggestedFilename, + within, + writeJson, +} from '../src/files'; import { Store } from '../src/store'; test('managed paths reject traversal, Windows paths and archive symlinks', async () => { @@ -35,6 +43,19 @@ test('offline UUID matches Java UUID.nameUUIDFromBytes', () => { assert.equal(offlineUuid('Notch'), 'b50ad385829d3141a2167e7d7539ba7f'); assert.notEqual(offlineUuid('Notch'), offlineUuid('notch')); }); +test('suggested file names keep non-ASCII names and replace characters platforms reject', () => { + assert.equal(suggestedFilename('我的世界 整合包'), '我的世界 整合包'); + assert.equal(suggestedFilename('サーバー用'), 'サーバー用'); + assert.equal(suggestedFilename('Craft/Kit: 2*?'), 'Craft_Kit_ 2_'); + assert.equal(suggestedFilename('.hidden'), 'hidden'); + assert.equal(suggestedFilename(' .. '), 'instance'); + assert.equal(suggestedFilename('', 'fallback'), 'fallback'); + assert.equal(suggestedFilename('a'.repeat(200)), 'a'.repeat(80)); + assert.equal(suggestedFilename('a'.repeat(79) + '😀'), 'a'.repeat(79)); + assert.equal(suggestedFilename('CON'), 'CON_'); + assert.equal(suggestedFilename('lpt9'), 'lpt9_'); + assert.equal(suggestedFilename('console'), 'console'); +}); test('tokens and proxy passwords are redacted', () => { const result = redact( 'Bearer secret --accessToken hidden access_token="abc" refresh_token=def https://user:pass@proxy.test socks5h://name:password@proxy.test', From 3d120518b53b4db952c5c2aced084adb83229101 Mon Sep 17 00:00:00 2001 From: Minecraft Workbench Contributor Date: Thu, 29 Oct 2026 15:06:24 +0800 Subject: [PATCH 4/5] perf(content): check installed mods against cached, parallel metadata `conflicts()` called `net.json` directly for every installed mod, so the five minute cache that every other request in this module uses was bypassed: a second Check conflicts run re-fetched everything, and a large pack paid one round trip per mod. The lookups now go through `version()` and are issued together, while the warnings are assembled per mod, so the local-then-online ordering of the previous sequential loop stays the same. --- src/content.ts | 102 +++++++++++++++++++++++--------------- test/content.test.ts | 115 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 177 insertions(+), 40 deletions(-) diff --git a/src/content.ts b/src/content.ts index fd41630..15425ef 100644 --- a/src/content.ts +++ b/src/content.ts @@ -682,12 +682,14 @@ export class ContentService { async conflicts(instance: Instance): Promise { const items = (await this.list(instance)).filter((i) => i.enabled && i.kind === 'mod'); const warnings: string[] = []; + const localWarnings = new Map(); const localModules: FabricModule[] = []; - let remoteUnavailable = false; const ids = new Map(); for (const item of items) { + const found: string[] = []; + localWarnings.set(item.file, found); if (instance.loader === 'vanilla') - warnings.push(`${item.name}: ${t('requires a mod loader', '需要模组加载器')}`); + found.push(`${item.name}: ${t('requires a mod loader', '需要模组加载器')}`); try { const zip = new AdmZip(path.join(instance.directory, 'mods', item.file)); const fabric = zip.getEntry('fabric.mod.json'); @@ -696,51 +698,73 @@ export class ContentService { ...readFabricMetadata(path.join(instance.directory, 'mods', item.file)), ); const meta = JSON.parse(fabric.getData().toString()); - if (ids.has(meta.id)) warnings.push(`${meta.id}: ${ids.get(meta.id)} / ${item.file}`); + if (ids.has(meta.id)) found.push(`${meta.id}: ${ids.get(meta.id)} / ${item.file}`); ids.set(meta.id, item.file); if (!['fabric', 'quilt'].includes(instance.loader)) - warnings.push(`${item.name}: Fabric / Quilt ${t('required', '必需')}`); + found.push(`${item.name}: Fabric / Quilt ${t('required', '必需')}`); } } catch { - warnings.push(`${item.file}: ${t('unreadable mod archive', '无法读取模组文件')}`); + found.push(`${item.file}: ${t('unreadable mod archive', '无法读取模组文件')}`); } - if (item.versionId && !remoteUnavailable) { - try { - const version = await this.net.json(`${api}/version/${item.versionId}`); - if ( - !version.game_versions.includes(instance.minecraft) || - !version.loaders.includes(instance.loader) - ) - warnings.push(`${item.name}: ${t('version or loader mismatch', '版本或加载器不匹配')}`); - for (const dep of version.dependencies) { - const found = items.some((i) => - dep.project_id - ? i.projectId === dep.project_id && - (!dep.version_id || i.versionId === dep.version_id) - : i.versionId === dep.version_id, - ); - if ( - (dep.dependency_type === 'required' && !found) || - (dep.dependency_type === 'incompatible' && found) - ) - warnings.push( - `${item.name}: ${dep.dependency_type} ${dep.project_id || dep.version_id}`, - ); - } - } catch (error) { - if (error instanceof HttpError) warnings.push(`${item.name}: HTTP ${error.status}`); - else { - remoteUnavailable = true; - warnings.push( - t( - 'Online metadata unavailable; local checks only.', - '在线元数据不可用,仅完成本地检查。', - ), - ); - } + } + const remote: ({ item: Content; version: ModVersion } | { item: Content; error: unknown })[] = + await Promise.all( + items + .filter((item) => item.versionId) + .map(async (item) => { + try { + return { item, version: await this.version(item.versionId!) }; + } catch (error) { + return { item, error }; + } + }), + ); + let remoteUnavailable = false; + const remoteWarnings = new Map(); + for (const result of remote) { + const item = result.item; + const found: string[] = []; + remoteWarnings.set(item.file, found); + if ('error' in result) { + if (result.error instanceof HttpError) + found.push(`${item.name}: HTTP ${result.error.status}`); + else if (!remoteUnavailable) { + remoteUnavailable = true; + found.push( + t( + 'Online metadata unavailable; local checks only.', + '在线元数据不可用,仅完成本地检查。', + ), + ); } + continue; + } + const version = result.version; + if ( + !version.game_versions.includes(instance.minecraft) || + !version.loaders.includes(instance.loader) + ) + found.push(`${item.name}: ${t('version or loader mismatch', '版本或加载器不匹配')}`); + for (const dep of version.dependencies) { + const installed = items.some((i) => + dep.project_id + ? i.projectId === dep.project_id && (!dep.version_id || i.versionId === dep.version_id) + : i.versionId === dep.version_id, + ); + if ( + (dep.dependency_type === 'required' && !installed) || + (dep.dependency_type === 'incompatible' && installed) + ) + found.push(`${item.name}: ${dep.dependency_type} ${dep.project_id || dep.version_id}`); } } + // Warnings keep the per-mod ordering the sequential version produced: local + // checks first, then the online ones for the same mod. + for (const item of items) + warnings.push( + ...(localWarnings.get(item.file) ?? []), + ...(remoteWarnings.get(item.file) ?? []), + ); if (['fabric', 'quilt'].includes(instance.loader)) { const native: Record = { minecraft: instance.minecraft }; if (instance.loader === 'fabric' && instance.loaderVersion) diff --git a/test/content.test.ts b/test/content.test.ts index 8393112..38ac3d1 100644 --- a/test/content.test.ts +++ b/test/content.test.ts @@ -6,7 +6,7 @@ import * as os from 'node:os'; import { createHash } from 'node:crypto'; import AdmZip from 'adm-zip'; import { ContentService } from '../src/content'; -import { Network } from '../src/network'; +import { Network, HttpError } from '../src/network'; import { Instance, ModVersion } from '../src/models'; import { writeJson } from '../src/files'; @@ -140,3 +140,116 @@ test('modpack paths cannot escape an instance and server-only files are skipped' await fs.rm(root, { recursive: true, force: true }); } }); +test('conflicts fetch online metadata once per version and reuse it across checks', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'mc-conflicts-')); + const instance: Instance = { + id: 'test', + name: 'Test', + directory: root, + minecraft: '1.21.1', + loader: 'fabric', + loaderVersion: '0.16.0', + createdAt: '', + }; + const installed = { + file: 'a.jar', + kind: 'mod' as const, + name: 'A', + projectId: 'mod-a', + versionId: 'a-v1', + hash: 'hash', + enabled: true, + }; + const other = { ...installed, file: 'b.jar', name: 'B', projectId: 'mod-b', versionId: 'b-v1' }; + let calls = 0; + let inFlight = 0; + let maxInFlight = 0; + const net = { + json: async (url: string) => { + calls++; + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + await new Promise((resolve) => setTimeout(resolve, 5)); + inFlight--; + if (url.endsWith('/version/a-v1')) return version('a-v1', 'mod-a'); + const missing = version('b-v1', 'mod-b'); + missing.dependencies.push({ project_id: 'absent', dependency_type: 'required' }); + return missing; + }, + } as unknown as Network; + const service = new ContentService(net); + try { + await fs.mkdir(path.join(root, 'mods'), { recursive: true }); + for (const name of ['a.jar', 'b.jar']) { + const zip = new AdmZip(); + zip.addFile('pack.mcmeta', Buffer.from('{}')); + zip.writeZip(path.join(root, 'mods', name)); + } + await writeJson(path.join(root, '.workbench', 'content.json'), [installed, other]); + assert.deepEqual(await service.conflicts(instance), ['B: required absent']); + assert.equal(calls, 2); + assert.equal(maxInFlight, 2); + assert.deepEqual(await service.conflicts(instance), ['B: required absent']); + assert.equal(calls, 2); + const offline = new ContentService({ + json: async () => { + throw new Error('offline'); + }, + } as unknown as Network); + assert.deepEqual(await offline.conflicts(instance), [ + 'Online metadata unavailable; local checks only.', + ]); + const missing = new ContentService({ + json: async () => { + throw new HttpError(404, 'missing'); + }, + } as unknown as Network); + assert.deepEqual(await missing.conflicts(instance), ['A: HTTP 404', 'B: HTTP 404']); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}); +test('conflict warnings keep the per-mod local-then-online order', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'mc-conflict-order-')); + const instance: Instance = { + id: 'test', + name: 'Test', + directory: root, + minecraft: '1.21.1', + loader: 'fabric', + loaderVersion: '0.16.0', + createdAt: '', + }; + const entries = ['a.jar', 'b.jar'].map((file) => ({ + file, + kind: 'mod' as const, + name: file[0].toUpperCase(), + projectId: `mod-${file[0]}`, + versionId: `${file[0]}-v1`, + hash: 'hash', + enabled: true, + })); + const net = { + json: async (url: string) => { + const broken = version(url.split('/').pop()!, 'mod-x'); + broken.dependencies.push({ project_id: 'absent', dependency_type: 'required' }); + return broken; + }, + } as unknown as Network; + const service = new ContentService(net); + try { + await fs.mkdir(path.join(root, 'mods'), { recursive: true }); + const zip = new AdmZip(); + zip.addFile('pack.mcmeta', Buffer.from('{}')); + zip.writeZip(path.join(root, 'mods', 'a.jar')); + await fs.writeFile(path.join(root, 'mods', 'b.jar'), 'not a zip'); + await writeJson(path.join(root, '.workbench', 'content.json'), entries); + assert.deepEqual(await service.conflicts(instance), [ + 'A: required absent', + 'b.jar: unreadable mod archive', + 'B: required absent', + ]); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}); From 602d2911d861fc9a5290e9800b8dd15ddabbf7f3 Mon Sep 17 00:00:00 2001 From: Minecraft Workbench Contributor Date: Thu, 29 Oct 2026 15:32:02 +0800 Subject: [PATCH 5/5] perf(network): honour downloadConcurrency on the proxy paths Only the direct connection passed `connections: concurrency`, so HTTP and SOCKS proxies kept undici's default (unbounded) client pool. Bulk work such as the installed-mod conflict check then opened one connection per request through the tunnel. Both proxy branches now carry the limit: - the SOCKS agent gets `connections` in its options; - ProxyAgent is constructed with the object form, `{ uri, connections }`, because the string form only accepts a URI. undici 7.29 forwards the value: proxy-agent.js:168 spreads the constructor options into its inner Agent, agent.js:48 keeps them in kOptions, and the per-origin factory reaches defaultAgentFactory/Pool, which stops creating clients at `connections` (pool.js:110). Credentials embedded in the proxy URI keep working with the object form - ProxyAgent still runs `new URL(uri)` and derives proxy-authorization from its username/password. --- src/network.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/network.ts b/src/network.ts index c443c8e..0ea8a6f 100644 --- a/src/network.ts +++ b/src/network.ts @@ -43,6 +43,7 @@ export class Network { if (!['socks:', 'socks5:', 'socks5h:'].includes(proxy.protocol)) throw new Error('Use SOCKS5 or SOCKS5h'); this.dispatcher = new Agent({ + connections: options.concurrency, connect: (opts, callback) => { void (async () => { let host = opts.hostname; @@ -76,7 +77,7 @@ export class Network { }); } else this.dispatcher = options.proxy - ? new ProxyAgent(options.proxy) + ? new ProxyAgent({ uri: options.proxy, connections: options.concurrency }) : new Agent({ connections: options.concurrency, connect: { timeout: options.timeout || 30000 },