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/src/extension.ts b/src/extension.ts index c913888..a8a7a8a 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -15,6 +15,28 @@ 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'; +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), + 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 +90,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/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/network.ts b/src/network.ts index f553dda..0ea8a6f 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,12 +35,15 @@ 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)) throw new Error('Use SOCKS5 or SOCKS5h'); this.dispatcher = new Agent({ + connections: options.concurrency, connect: (opts, callback) => { void (async () => { let host = opts.hostname; @@ -73,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 }, @@ -96,7 +100,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 +155,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/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/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/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/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 }); + } +}); 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', 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/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', + }); +}); 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 }); + } +});