diff --git a/README.md b/README.md index 207a5b6..355e8e4 100644 --- a/README.md +++ b/README.md @@ -318,6 +318,25 @@ The previous diagnostic operations map to these MCP tools: Screen streaming and arbitrary mouse/keyboard control are intentionally not MCP operations. CAPTCHA and interactive authentication challenges remain local; supported one-time account codes can be submitted with `mhu_accounts_otp`. Granting new directories, changing MCP permissions and obtaining the connection code are local security decisions. These boundaries do not disable ordinary upload, queue, account, automation, history or backup operations exposed through the structured tool catalog. +### Diagnostic artifacts and file transfer + +`mhu_diagnostics_files` lists the application's startup journals, native Chromium logs and automatically saved startup failure reports. `mhu_diagnostics_read` reads one listed artifact with bounded pagination. Credentials are filtered from the complete text before pages are returned; offsets refer to characters in the filtered text. Files larger than 8 MiB are rejected by this reader. The existing bounded log-tail tools remain available for larger application logs. Job-specific logs, account cooldowns and manual-action states are exposed through `mhu_queue_job_log` and `mhu_accounts_runtime`; the diagnostic summary also includes current upload-manager and renderer status. + +Full file transfer needs both read and directory permissions, plus an additional local **Transfer file contents** approval for the selected directory. Existing grants do not acquire this approval automatically. Transferring a file does not require deletion permission and never changes the source. Application credential storage and hard-linked files cannot be exported through this channel. A granted user file may itself contain private information; approve only directories whose contents may be transferred. + +Use `mhu_files_transfer_open` to prepare a specific file inside an approved directory, then `mhu_files_transfer_get` until the state is `ready`. The result includes its size, SHA-256 and a token-free `media-mcp-file:v1:` reference. That reference identifies the transfer but grants no access by itself: the receiver also needs the installation's separate connection code. `mhu_files_transfer_read` supplies checked chunks to the receiver; do not paste binary chunks into a chat. `mhu_files_transfer_list` and `mhu_files_transfer_close` inspect or close the current client's handles. Transfers are limited to four at once, 32 GiB per file, one-MiB chunks, a one-hour absolute lifetime and ten minutes without activity. Removing the grant, changing local permissions or disabling access invalidates open transfers. + +On the receiving computer, install the development dependencies and keep the connection code in a private local file outside Git. The receiver uses only the fixed HTTPS relay, refuses redirects and does not send files to arbitrary URLs: + +```powershell +node scripts/pull-mcp-file.mjs +node scripts/pull-mcp-file.mjs --transfer +``` + +The receiver writes an exclusive `.mcp-part` file and a resumable checkpoint without credentials. It verifies each block, rechecks the complete file from disk, and checks size and SHA-256 before publishing the destination without overwriting an existing file. Add `--resume` to continue an interrupted transfer; the saved prefix and source identity are checked again. An expired transfer can be reopened when the original directory and relative path are supplied. Incomplete files stay available for recovery after a failure. Neither the original file nor an existing destination is deleted. + +After a hard process termination, a `.mcp-lock` file may remain. Remove only that exact lock after confirming that no receiver is still running for the destination, then retry with `--resume`. Preserve the partial file and checkpoint. The receiver does not automatically remove an unknown or potentially active lock. + ## Development and Windows builds Install dependencies and start the Electron application: diff --git a/lib/mcp-access.js b/lib/mcp-access.js index 797b16d..3b8ce9c 100644 --- a/lib/mcp-access.js +++ b/lib/mcp-access.js @@ -53,6 +53,8 @@ async function resolveGrantedFile(grants, rootId, relativePath, options = {}) { if (typeof relativePath !== 'string' || relativePath.includes('\0') || path.isAbsolute(relativePath) || /(?:^|[\\/])\.\.(?:[\\/]|$)|:/.test(relativePath)) throw new McpAccessError('PATH_NOT_GRANTED'); const realRoot = await fs.realpath(grant.path); + const expectedRoot = path.resolve(grant.path); + if (process.platform === 'win32' ? realRoot.toLowerCase() !== expectedRoot.toLowerCase() : realRoot !== expectedRoot) throw new McpAccessError('PATH_NOT_GRANTED'); const target = path.resolve(realRoot, relativePath || '.'); if (!within(realRoot, target)) throw new McpAccessError('PATH_NOT_GRANTED'); const realTarget = await fs.realpath(target); diff --git a/lib/mcp-app.js b/lib/mcp-app.js index 3d36eea..c567536 100644 --- a/lib/mcp-app.js +++ b/lib/mcp-app.js @@ -1,6 +1,10 @@ const { randomUUID } = require('node:crypto'); const { McpAccessError, resolveGrantedFile } = require('./mcp-access'); const { createMcpFiles } = require('./mcp-files'); +const { createMcpTransfers } = require('./mcp-transfers'); +const { createMcpDiagnostics } = require('./mcp-diagnostics'); +const { createMcpSanitizer } = require('./mcp-security'); +const { redactLogText, collectSecretValues } = require('./support-bundle'); function page(items, args) { const offset = args.offset || 0; @@ -8,7 +12,10 @@ function page(items, args) { return { total: items.length, offset, items: items.slice(offset, offset + limit), nextOffset: offset + limit < items.length ? offset + limit : null }; } -function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, ...args) => invoke(channel, ...args), renderer, collectors, getGrants, trashFile, canWrite }) { +function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, ...args) => invoke(channel, ...args), renderer, collectors, getGrants, trashFile, canWrite, + getCapabilities, getProtectedPaths, getInstallationId, getDiagnosticSources, getRuntimeDiagnostics = () => null }) { + const transfers = createMcpTransfers({ getGrants, getCapabilities, getProtectedPaths, getInstallationId }); + const sanitize = createMcpSanitizer(loadConfig); const guard = context => { if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED'); }; @@ -45,11 +52,14 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, await refresh(context); return { saved: true }; }; - return { + const handlers = { ...createMcpFiles({ getGrants, trashFile }), + ...transfers.handlers, + ...createMcpDiagnostics({ getSources: getDiagnosticSources, redact: text => sanitize(redactLogText(text, collectSecretValues(loadConfig()))) }), mhu_app_info: () => invoke('get-app-info'), mhu_app_state: async (args, context) => ({ ...(await renderer('state', {}, context)), automation: await invoke('automation:get-status') }), mhu_queue_list: (args, context) => renderer('queue-list', args, context), + mhu_queue_job_log: async args => page(await invoke('get-job-log', args.jobId), args), mhu_queue_add: async (args, context) => { if (!args.paths.length || !args.hosters.length) throw new McpAccessError('INVALID_ARGUMENTS'); const files = []; @@ -65,6 +75,10 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, mhu_queue_remove: (args, context) => renderer('queue-remove', args, context), mhu_queue_clear: (args, context) => renderer('queue-clear', args, context), mhu_accounts_list: args => page(accounts().filter(account => !args.hoster || args.hoster === account.hoster), args), + mhu_accounts_runtime: async args => { + const state = await invoke('get-session-failed-account-states'); + return { revision: state.revision, now: state.now, ...page(state.accounts.filter(account => !args.hoster || account.hoster === args.hoster), args) }; + }, mhu_accounts_check: (args, context) => { if (!args.accountIds.length) throw new McpAccessError('INVALID_ARGUMENTS'); return check(args.accountIds, context); }, mhu_accounts_add: async (args, context) => { canWrite(); guard(context); @@ -128,7 +142,7 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, mhu_history_prune: args => invoke('prune-history', { retention: args.retention, dryRun: false }), mhu_history_summary: args => collectors.getHistory({ limit: args.limit || 20 }), mhu_history_clear: () => invoke('clear-history'), - mhu_diagnostics_summary: () => ({ system: collectors.getSystemInfo(), health: collectors.getHealth(), rotation: collectors.getRotationState(), server: collectors.serverHealth({ errorLimit: 20 }) }), + mhu_diagnostics_summary: () => ({ system: collectors.getSystemInfo(), health: collectors.getHealth(), rotation: collectors.getRotationState(), server: collectors.serverHealth({ errorLimit: 20 }), runtime: getRuntimeDiagnostics() }), mhu_app_events: args => collectors.getAppEvents(args), mhu_errors: args => collectors.listErrors(args), mhu_logs_list: () => collectors.listLogs(), @@ -146,6 +160,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, mhu_app_quit: () => invoke('app:quit'), mhu_secrets_read: args => { const { password, apiKey } = find(args.accountId); return { accountId: args.accountId, password: password || '', apiKey: apiKey || '' }; } }; + Object.defineProperty(handlers, 'dispose', { value: () => transfers.dispose() }); + return handlers; } module.exports = { createMcpApp, page }; diff --git a/lib/mcp-diagnostics.js b/lib/mcp-diagnostics.js new file mode 100644 index 0000000..0583062 --- /dev/null +++ b/lib/mcp-diagnostics.js @@ -0,0 +1,71 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); +const { constants } = require('node:fs'); +const { createHash } = require('node:crypto'); +const { McpAccessError } = require('./mcp-access'); + +function createMcpDiagnostics({ getSources = () => [], redact }) { + let reading = 0; + const guard = context => { if (context.signal?.aborted || !Number.isFinite(context.deadline) || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED'); }; + const sources = () => getSources().slice(0, 64).map(source => ({ ...source, id: createHash('sha256').update(source.path).digest('hex').slice(0, 24) })); + const resolve = async source => { + const actual = await fs.realpath(source.path); + const parent = await fs.realpath(source.directory); + const expectedParent = path.resolve(source.directory); + if (process.platform === 'win32' ? parent.toLowerCase() !== expectedParent.toLowerCase() : parent !== expectedParent) throw new McpAccessError('PATH_NOT_GRANTED'); + if (actual !== path.join(parent, path.basename(source.path))) throw new McpAccessError('PATH_NOT_GRANTED'); + const stat = await fs.lstat(actual); + if (!stat.isFile() || stat.nlink !== 1) throw new McpAccessError('PATH_NOT_GRANTED'); + return { actual, stat }; + }; + return { + mhu_diagnostics_files: async (args, context) => { + const files = []; + for (const source of sources()) { + guard(context); + try { const { stat } = await resolve(source); files.push({ id: source.id, name: source.label, sizeBytes: stat.size, modifiedAt: stat.mtime.toISOString() }); } + catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) files.push({ id: source.id, name: source.label, unavailable: true }); } + } + const offset = args.offset || 0; const limit = args.limit || 50; + return { total: files.length, offset, files: files.slice(offset, offset + limit), nextOffset: offset + limit < files.length ? offset + limit : null }; + }, + mhu_diagnostics_read: async (args, context) => { + guard(context); + const source = sources().find(item => item.id === args.artifactId); + if (!source) throw new McpAccessError('DIAGNOSTIC_NOT_FOUND'); + if (reading >= 4) throw new McpAccessError('TOO_MANY_REQUESTS'); + reading++; + let file; + try { + const { actual, stat } = await resolve(source); + if (stat.size > 8 * 1024 * 1024) throw new McpAccessError('FILE_TOO_LARGE'); + file = await fs.open(actual, constants.O_RDONLY | (constants.O_NOFOLLOW || 0)); + const initial = await file.stat(); + if (initial.ino !== stat.ino || initial.dev !== stat.dev || initial.size !== stat.size || !initial.isFile()) throw new McpAccessError('FILE_CHANGED'); + const buffer = Buffer.alloc(initial.size); + let offset = 0; + while (offset < buffer.length) { + guard(context); + const { bytesRead } = await file.read(buffer, offset, Math.min(256 * 1024, buffer.length - offset), offset); + if (!bytesRead) throw new McpAccessError('FILE_CHANGED'); + offset += bytesRead; + } + const final = await file.stat(); + if (final.size !== initial.size || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) throw new McpAccessError('FILE_CHANGED'); + const current = await resolve(source); + if (current.stat.ino !== initial.ino || current.stat.dev !== initial.dev) throw new McpAccessError('FILE_CHANGED'); + guard(context); + const text = redact(buffer.toString('utf8')); + if (typeof text !== 'string') throw new McpAccessError('REDACTION_UNAVAILABLE'); + const start = args.offset || 0; const limit = args.limit || 65536; + if (start > text.length) throw new McpAccessError('INVALID_ARGUMENTS'); + const content = text.slice(start, start + limit); + return { artifactId: source.id, name: source.label, sizeBytes: initial.size, modifiedAt: initial.mtime.toISOString(), + offset: start, returnedCharacters: content.length, totalCharacters: text.length, content, + nextOffset: start + content.length < text.length ? start + content.length : null }; + } finally { reading--; if (file) await file.close().catch(() => {}); } + } + }; +} + +module.exports = { createMcpDiagnostics }; diff --git a/lib/mcp-files.js b/lib/mcp-files.js index 775addd..d67c0fd 100644 --- a/lib/mcp-files.js +++ b/lib/mcp-files.js @@ -9,7 +9,7 @@ function createMcpFiles({ getGrants, trashFile }) { }; const metadata = stat => ({ size: stat.size, modifiedAt: stat.mtime.toISOString(), directory: stat.isDirectory(), file: stat.isFile() }); return { - mhu_files_roots: async () => getGrants().map(({ id, label, readOnly }) => ({ id, label, readOnly: readOnly !== false })), + mhu_files_roots: async () => getGrants().map(({ id, label, readOnly, allowTransfer }) => ({ id, label, readOnly: readOnly !== false, allowTransfer: allowTransfer === true })), mhu_files_stat: async (args, context) => { guard(context); const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath); diff --git a/lib/mcp-protocol.js b/lib/mcp-protocol.js index 45b00b0..9cf9b9f 100644 --- a/lib/mcp-protocol.js +++ b/lib/mcp-protocol.js @@ -36,7 +36,8 @@ function createMcpProtocol({ adapter, version, getCapabilities }) { if (message.method !== 'tools/call') return error(message.id, -32601, 'Method not found'); try { const result = await adapter.call(message.params?.name, message.params?.arguments ?? {}, { ...context, scopes: getCapabilities() }); - return response(message.id, { content: [{ type: 'text', text: JSON.stringify(result ?? null) }], isError: false }); + const textResult = message.params?.name === 'mhu_files_transfer_read' ? { ...result, base64: undefined } : result; + return response(message.id, { content: [{ type: 'text', text: JSON.stringify(textResult ?? null) }], structuredContent: { result: result ?? null }, isError: false }); } catch (failure) { const code = failure instanceof McpAccessError ? failure.code : 'ACTION_FAILED'; return response(message.id, { content: [{ type: 'text', text: code }], isError: true }); diff --git a/lib/mcp-security.js b/lib/mcp-security.js index c004998..be32c3d 100644 --- a/lib/mcp-security.js +++ b/lib/mcp-security.js @@ -18,10 +18,10 @@ function createMcpSanitizer(loadConfig) { const visit = (node, depth = 0) => { if (depth > 16) throw new McpAccessError('RESULT_TOO_LARGE'); if (typeof node === 'string') { - let result = node.replace(/(?:Bearer\s+\S+|media-mcp:v1:[A-Za-z0-9_-]+|MHU[12]-[A-Za-z0-9_-]+)/gi, '[REDACTED]') - .replace(/((?:password|passwd|api[_-]?key|access[_-]?token|secret|sess_id)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi, '$1[REDACTED]'); - for (const secret of values) result = result.split(secret).join('[REDACTED]'); - return result; + let result = node.replace(/(?:Bearer\s+\S+|media-mcp:v1:[A-Za-z0-9_-]+|MHU[12]-[A-Za-z0-9_-]+)/gi, '\0') + .replace(/((?:password|passwd|api[_-]?key|access[_-]?token|secret|sess_id)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi, '$1\0'); + for (const secret of values) result = result.split(secret).join('\0'); + return result.replaceAll('\0', '[REDACTED]'); } if (Array.isArray(node)) return node.map(item => visit(item, depth + 1)); if (node && typeof node === 'object') return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, sensitive.test(key) ? '[REDACTED]' : visit(item, depth + 1)])); diff --git a/lib/mcp-service.js b/lib/mcp-service.js index 88a3cb3..49deb2a 100644 --- a/lib/mcp-service.js +++ b/lib/mcp-service.js @@ -69,7 +69,7 @@ class McpService { this.connection = 'disabled'; const agent = this.agent; this.agent = null; this.publish(); - await agent?.stop(); + await Promise.all([agent?.stop(), this.options.handlers?.dispose?.()]); } async retryRevocations() { const pending = this.store.value.revocations; @@ -139,17 +139,17 @@ class McpService { const resolved = await fs.realpath(directory); const stat = await fs.stat(resolved); if (!stat.isDirectory() || path.parse(resolved).root === resolved) throw new McpAccessError('PATH_NOT_GRANTED'); - if (!this.store.value.grants.some(grant => grant.path === resolved)) await this.store.save({ ...this.store.value, grants: [...this.store.value.grants, { id: randomUUID(), label: path.basename(resolved), path: resolved, readOnly: true }] }); + if (!this.store.value.grants.some(grant => grant.path === resolved)) await this.store.save({ ...this.store.value, grants: [...this.store.value.grants, { id: randomUUID(), label: path.basename(resolved), path: resolved, readOnly: true, allowTransfer: false }] }); this.publish(); return this.state(); }); } - updateGrant(id, remove, readOnly = true) { + updateGrant(id, remove, readOnly = true, allowTransfer) { const generation = this.generation; return this.serialize(async () => { const wasActive = this.active; await this.disconnect(); await this.store.markDisabled(); - const grants = this.store.value.grants.flatMap(grant => grant.id !== id ? [grant] : remove ? [] : [{ ...grant, readOnly }]); + const grants = this.store.value.grants.flatMap(grant => grant.id !== id ? [grant] : remove ? [] : [{ ...grant, readOnly, ...(allowTransfer === undefined ? {} : { allowTransfer }) }]); await this.store.save({ ...this.store.value, grants }); if (wasActive && generation === this.generation) { await this.store.clearDisabled(); this.connect(); } this.publish(); return this.state(); diff --git a/lib/mcp-store.js b/lib/mcp-store.js index 119f9f9..ed004a0 100644 --- a/lib/mcp-store.js +++ b/lib/mcp-store.js @@ -25,7 +25,8 @@ class McpStore { if (typeof value.enabled !== 'boolean' || typeof value.name !== 'string' || !value.name.trim() || value.name.length > 100 || value.capabilities.some(item => !CAPABILITIES.includes(item)) || value.grants.length > 30 || value.revocations.length > 32 || value.grants.some(grant => !grant || typeof grant.id !== 'string' || typeof grant.path !== 'string' || !path.isAbsolute(grant.path) - || typeof grant.label !== 'string' || typeof grant.readOnly !== 'boolean')) throw new Error('format'); + || typeof grant.label !== 'string' || typeof grant.readOnly !== 'boolean' + || (grant.allowTransfer !== undefined && typeof grant.allowTransfer !== 'boolean'))) throw new Error('format'); const decode = identity => { if (!identity) return null; if (identity.relayUrl !== RELAY_URL || !/^[a-f0-9-]{36}$/.test(identity.installationId)) throw new Error('identity'); diff --git a/lib/mcp-tools.js b/lib/mcp-tools.js index 579875b..bfb93ff 100644 --- a/lib/mcp-tools.js +++ b/lib/mcp-tools.js @@ -1,4 +1,5 @@ const { McpAccessError, validateInput, actionDigest } = require('./mcp-access'); +const { sanitizeTransferResult } = require('./mcp-transfers'); const text = (maxLength = 4096) => ({ type: 'string', maxLength }); const id = { type: 'string', minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_.:-]+$' }; @@ -18,6 +19,7 @@ const definitions = [ ['app_info', 'Read application version and runtime information.', 'read', {}, []], ['app_state', 'Read live transfer and automation summary.', 'read', {}, []], ['queue_list', 'Read a bounded page of upload jobs.', 'read', { ...page, status: text(40) }, []], + ['queue_job_log', 'Read a bounded, secret-filtered log for one upload job.', 'read', { jobId: id, ...page }, ['jobId']], ['queue_add', 'Add files from a granted directory to the upload queue.', 'control', { rootId: id, paths: array(text(), 1000), hosters: array(hoster, 5) }, ['rootId', 'paths', 'hosters']], ['queue_start', 'Start eligible queued uploads.', 'control', jobIds, []], ['queue_pause', 'Pause new uploads after current transfers.', 'control', {}, []], @@ -27,6 +29,7 @@ const definitions = [ ['queue_remove', 'Remove selected jobs without deleting source files.', 'control', jobIds, ['jobIds'], true], ['queue_clear', 'Clear inactive jobs without deleting source files.', 'control', {}, [], true], ['accounts_list', 'Read a bounded page of configured accounts with secrets hidden.', 'read', { ...page, hoster }, []], + ['accounts_runtime', 'Read temporary account cooldowns and manual-action states.', 'read', { ...page, hoster }, []], ['accounts_check', 'Check selected account credentials without revealing them.', 'accounts', { accountIds: array(id, 100) }, ['accountIds']], ['accounts_add', 'Add a hoster account with explicit credentials.', 'accounts', { hoster, label: text(200), username: text(320), password: text(), apiKey: text(), authType: enumeration(['login', 'api']) }, ['hoster', 'authType']], ['accounts_update', 'Update one account without exposing stored credentials.', 'accounts', { ...account, label: text(200), username: text(320), password: text(), apiKey: text(), enabled: boolean }, ['accountId']], @@ -69,10 +72,19 @@ const definitions = [ name: enumeration(['debug', 'fileuploader', 'uploadAudit', 'accountRotation', 'crash']), tailKb: integer(1, 256), backup: integer(0, 2), grep: text(200) }, ['name']], + ['diagnostics_files', 'List startup journals, native logs and saved startup failure reports.', 'diagnostics', page, []], + ['diagnostics_read', 'Read a page of a fully secret-filtered startup diagnostic artifact. Offsets and limits count redacted characters.', 'diagnostics', + { artifactId: id, offset: integer(0, 100000000), limit: integer(1, 65536) }, ['artifactId']], ['files_roots', 'List configured directory grants, without granting new access.', 'files', {}, []], ['files_list', 'List a bounded page within a granted directory.', 'files', { ...file, ...page }, ['rootId']], ['files_stat', 'Read metadata for a file within a granted directory.', 'files', file, ['rootId', 'relativePath']], ['files_hash', 'Compute a bounded file checksum within a granted directory.', 'files', { ...file, algorithm: enumeration(['sha256', 'sha512']) }, ['rootId', 'relativePath']], + ['files_transfer_open', 'Prepare a stable read-only file transfer from a directory with explicit content-transfer permission. Use a receiver to stream chunks outside chat.', 'files', file, ['rootId', 'relativePath']], + ['files_transfer_get', 'Read preparation state, byte size and SHA-256 for an owned file transfer.', 'files', { transferId: id }, ['transferId']], + ['files_transfer_list', 'List this authenticated client\'s active file transfers.', 'files', {}, []], + ['files_transfer_read', 'Read one verified binary chunk of an owned prepared transfer. Intended for a streaming receiver, not rendering in chat.', 'files', + { transferId: id, offset: integer(0, 32 * 1024 ** 3), length: integer(1, 1024 * 1024) }, ['transferId', 'offset']], + ['files_transfer_close', 'Close an owned temporary transfer handle without modifying its source file.', 'files', { transferId: id }, ['transferId']], ['files_delete', 'Delete a specifically selected file inside a writable grant.', 'files.write', file, ['rootId', 'relativePath'], true], ['cloud_status', 'Read CloudDrop log synchronization state.', 'read', {}, []], ['cloud_configure', 'Enable or disable CloudDrop log sync with the saved or supplied key.', 'settings', { enabled: boolean, apiKey: text(200) }, ['enabled']], @@ -91,9 +103,9 @@ const definitions = [ const capabilities = { diagnostics: 'read', accounts: 'control', settings: 'control', backup: 'control', lifecycle: 'control', 'secrets.read': 'secrets', 'files.write': 'files' }; const MCP_TOOLS = Object.freeze(definitions.map(([name, description, scope, properties, required, destructive = false]) => Object.freeze({ name: 'mhu_' + name, description, scope: capabilities[scope] || scope, destructive, inputSchema: object(properties, required), - requiredScopes: [...new Set([capabilities[scope] || scope, ...(['queue_add', 'automation_update'].includes(name) ? ['files'] : []), ...(name === 'files_delete' ? ['control'] : [])])], - annotations: { readOnlyHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope), destructiveHint: destructive, - idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope), openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) } + requiredScopes: [...new Set([capabilities[scope] || scope, ...(['queue_add', 'automation_update'].includes(name) ? ['files'] : []), ...(name === 'files_delete' ? ['control'] : []), ...(name.startsWith('files_transfer_') ? ['read'] : [])])], + annotations: { readOnlyHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && !['files_transfer_open', 'files_transfer_close'].includes(name), destructiveHint: destructive, + idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && name !== 'files_transfer_open', openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) } }))); function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit = () => {}, getCapabilities, requiresConfirmation = () => false }) { @@ -105,9 +117,7 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit const tool = byName.get(name); if (!tool || typeof handlers[name] !== 'function') throw new McpAccessError('TOOL_UNAVAILABLE'); const allowed = () => getCapabilities ? getCapabilities() : context?.scopes; - const permitted = () => Array.isArray(allowed()) && allowed().includes(tool.scope) - && (name !== 'mhu_files_delete' || allowed().includes('control')) - && (!['mhu_queue_add', 'mhu_automation_update'].includes(name) || allowed().includes('files')); + const permitted = () => Array.isArray(allowed()) && tool.requiredScopes.every(scope => allowed().includes(scope)); if (!permitted()) throw new McpAccessError('SCOPE_DENIED'); validateInput(args, tool.inputSchema); if (context.signal?.aborted || !Number.isFinite(context.deadline) || context.deadline <= Date.now()) throw new McpAccessError('REQUEST_EXPIRED'); @@ -133,8 +143,8 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit const value = await handlers[name](args, context); if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED'); if (!permitted()) throw new McpAccessError('SCOPE_DENIED'); - const result = name === 'mhu_secrets_read' ? value : await sanitize(value); - if (Buffer.byteLength(JSON.stringify(result) || 'null') > 1024 * 1024) throw new McpAccessError('RESULT_TOO_LARGE'); + const result = name.startsWith('mhu_files_transfer_') ? sanitizeTransferResult(name, value, sanitize) : name === 'mhu_secrets_read' ? value : await sanitize(value); + if (Buffer.byteLength(JSON.stringify(result) || 'null') > (name === 'mhu_files_transfer_read' ? 2 : 1) * 1024 * 1024) throw new McpAccessError('RESULT_TOO_LARGE'); audit({ tool: name, event: 'completed', requestId: context.requestId, durationMs: Date.now() - startedAt }); return result; }; diff --git a/lib/mcp-transfers.js b/lib/mcp-transfers.js new file mode 100644 index 0000000..bfe0a6a --- /dev/null +++ b/lib/mcp-transfers.js @@ -0,0 +1,197 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); +const { constants } = require('node:fs'); +const { createHash, randomUUID } = require('node:crypto'); +const { McpAccessError, resolveGrantedFile } = require('./mcp-access'); + +const CHUNK_BYTES = 1024 * 1024; +const MAX_BYTES = 32 * 1024 ** 3; +const unchanged = (a, b) => a.isFile() && b.isFile() && a.dev === b.dev && a.ino === b.ino && a.size === b.size + && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && b.nlink === 1; +const inside = (root, file) => { const relative = path.relative(root, file); return !relative || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep)); }; + +function sanitizeTransferResult(name, value, sanitize) { + const fail = () => { throw new McpAccessError('INVALID_TRANSFER_RESULT'); }; + const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value); + const integer = value => Number.isSafeInteger(value) && value >= 0 && value <= MAX_BYTES; + const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value); + const keys = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => allowed.includes(key)); + const metadata = item => { + if (!keys(item, ['transferId', 'fileName', 'bytes', 'state', 'sha256', 'expiresAt', 'chunkBytes', 'checkedBytes', 'error', 'reference']) + || !uuid(item.transferId) || typeof item.fileName !== 'string' || item.fileName.length > 1024 || !integer(item.bytes) + || !['preparing', 'ready', 'failed'].includes(item.state) || (item.sha256 !== null && !digest(item.sha256)) + || (item.state === 'ready' && !digest(item.sha256)) || item.chunkBytes !== CHUNK_BYTES + || (item.checkedBytes !== undefined && (!integer(item.checkedBytes) || item.checkedBytes > item.bytes)) + || typeof item.expiresAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(item.expiresAt) || !Number.isFinite(Date.parse(item.expiresAt)) + || (item.error !== undefined && (typeof item.error !== 'string' || !/^[A-Z_]{1,60}$/.test(item.error)))) fail(); + if (item.reference !== undefined) { + if (typeof item.reference !== 'string' || !/^media-mcp-file:v1:[A-Za-z0-9_-]{1,1000}$/.test(item.reference)) fail(); + let ref; + try { ref = JSON.parse(Buffer.from(item.reference.slice('media-mcp-file:v1:'.length), 'base64url').toString('utf8')); } catch { fail(); } + if (!keys(ref, ['v', 'installationId', 'kind', 'transferId']) || ref.v !== 1 || ref.kind !== 'uploader' || !uuid(ref.installationId) || ref.transferId !== item.transferId) fail(); + } + return { ...item, fileName: sanitize(item.fileName) }; + }; + if (name === 'mhu_files_transfer_read') { + if (!keys(value, ['transferId', 'offset', 'bytesRead', 'nextOffset', 'bytes', 'sha256', 'base64']) || !uuid(value.transferId) + || ![value.offset, value.bytesRead, value.bytes].every(integer) || value.bytesRead > CHUNK_BYTES + || value.offset + value.bytesRead > value.bytes + || value.nextOffset !== (value.offset + value.bytesRead < value.bytes ? value.offset + value.bytesRead : null) || !digest(value.sha256) + || typeof value.base64 !== 'string' || value.base64.length > 4 * Math.ceil(CHUNK_BYTES / 3)) fail(); + const bytes = Buffer.from(value.base64, 'base64'); + if (bytes.length !== value.bytesRead || bytes.toString('base64') !== value.base64 || createHash('sha256').update(bytes).digest('hex') !== value.sha256) fail(); + return value; + } + if (name === 'mhu_files_transfer_list') { + if (!keys(value, ['transfers']) || !Array.isArray(value.transfers) || value.transfers.length > 4) fail(); + return { transfers: value.transfers.map(metadata) }; + } + if (name === 'mhu_files_transfer_close') { + if (!keys(value, ['closed']) || typeof value.closed !== 'boolean') fail(); + return { closed: value.closed }; + } + return metadata(value); +} + +function createMcpTransfers({ getGrants, getCapabilities = () => [], getProtectedPaths = () => [], getInstallationId = () => null, + now = Date.now, ttlMs = 60 * 60 * 1000, idleMs = 10 * 60 * 1000, maximum = 4 }) { + const records = new Map(); + let opening = 0; + let generation = 0; + let timer = null; + const authorized = () => ['read', 'files'].every(scope => getCapabilities().includes(scope)); + const guard = context => { + if (!authorized()) throw new McpAccessError('SCOPE_DENIED'); + if (context && (context.signal?.aborted || !Number.isFinite(context.deadline) || now() >= context.deadline)) throw new McpAccessError('REQUEST_EXPIRED'); + }; + const closeFile = record => record.closing || (record.closing = record.file.close().catch(() => {})); + const remove = async record => { + if (records.get(record.id) === record) records.delete(record.id); + record.abort.abort(); + await record.task; + await closeFile(record); + }; + const expired = record => now() >= record.until || now() - record.touched >= idleMs; + const purge = async () => { await Promise.all([...records.values()].filter(expired).map(remove)); }; + const ensureTimer = () => { + if (timer) return; + timer = setInterval(() => { void purge().catch(() => {}); }, Math.max(10, Math.min(30000, idleMs))); + timer.unref?.(); + }; + const protectedFile = async file => { + for (const entry of getProtectedPaths()) { + const blocked = path.resolve(entry); + if (inside(blocked, file)) return true; + try { if (inside(await fs.realpath(blocked), file)) return true; } + catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw new McpAccessError('PATH_NOT_GRANTED'); } + } + return false; + }; + const verify = async record => { + guard(); + if (record.abort.signal.aborted || expired(record)) throw new McpAccessError('TRANSFER_EXPIRED'); + if (!getGrants().some(grant => grant.id === record.rootId && grant.allowTransfer === true)) throw new McpAccessError('TRANSFER_NOT_GRANTED'); + const target = await resolveGrantedFile(getGrants(), record.rootId, record.relativePath, { regularFile: true }); + if (target.path !== record.path || !unchanged(record.initial, target.stat) || await protectedFile(target.path) + || !unchanged(record.initial, await record.file.stat())) throw new McpAccessError('FILE_CHANGED'); + }; + const metadata = record => { + const installationId = getInstallationId(); + return { transferId: record.id, fileName: record.name, bytes: record.initial.size, state: record.state, + sha256: record.sha256, expiresAt: new Date(record.until).toISOString(), chunkBytes: CHUNK_BYTES, checkedBytes: record.checkedBytes, + ...(record.error ? { error: record.error } : {}), + ...(installationId ? { reference: 'media-mcp-file:v1:' + Buffer.from(JSON.stringify({ v: 1, installationId, kind: 'uploader', transferId: record.id })).toString('base64url') } : {}) }; + }; + const find = async (id, context) => { + guard(context); + await purge(); + const record = records.get(id); + if (!record || record.owner !== context.principalId) throw new McpAccessError('TRANSFER_NOT_FOUND'); + record.touched = now(); + if (record.state !== 'failed') { + try { await verify(record); } + catch (error) { record.state = 'failed'; record.error = error instanceof McpAccessError ? error.code : 'FILE_CHANGED'; record.abort.abort(); await record.task; await closeFile(record); } + } + guard(context); + return record; + }; + const hash = async record => { + try { + const digest = createHash('sha256'); + const buffer = Buffer.alloc(CHUNK_BYTES); + for (let offset = 0; offset < record.initial.size;) { + await verify(record); + const count = Math.min(buffer.length, record.initial.size - offset); + const result = await record.file.read(buffer, 0, count, offset); + if (result.bytesRead !== count) throw new McpAccessError('FILE_CHANGED'); + digest.update(buffer.subarray(0, count)); offset += count; record.checkedBytes = offset; + } + await verify(record); + record.sha256 = digest.digest('hex'); record.state = 'ready'; + } catch (error) { + record.state = 'failed'; record.error = error instanceof McpAccessError ? error.code : 'FILE_UNAVAILABLE'; + await closeFile(record); + } + }; + const handlers = { + mhu_files_transfer_open: async (args, context) => { + guard(context); await purge(); + if (records.size + opening >= maximum) throw new McpAccessError('TRANSFER_LIMIT'); + if (typeof context.principalId !== 'string' || !context.principalId) throw new McpAccessError('INVALID_REQUEST'); + opening++; + const expectedGeneration = generation; + let file; + try { + if (!getGrants().some(grant => grant.id === args.rootId && grant.allowTransfer === true)) throw new McpAccessError('TRANSFER_NOT_GRANTED'); + const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath, { regularFile: true }); + if (target.stat.size > MAX_BYTES) throw new McpAccessError('FILE_TOO_LARGE'); + if (target.stat.nlink !== 1 || await protectedFile(target.path)) throw new McpAccessError('PATH_NOT_GRANTED'); + file = await fs.open(target.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0)); + const initial = await file.stat(); + if (!unchanged(target.stat, initial)) throw new McpAccessError('FILE_CHANGED'); + const record = { id: randomUUID(), owner: context.principalId, rootId: args.rootId, relativePath: args.relativePath, + path: target.path, name: path.basename(target.path), initial, file, state: 'preparing', sha256: null, checkedBytes: 0, + until: now() + ttlMs, touched: now(), abort: new AbortController(), task: Promise.resolve() }; + await verify(record); guard(context); + if (generation !== expectedGeneration) throw new McpAccessError('TRANSFER_EXPIRED'); + records.set(record.id, record); ensureTimer(); + record.task = hash(record); + file = null; + return metadata(record); + } finally { opening--; if (file) await file.close().catch(() => {}); } + }, + mhu_files_transfer_get: async (args, context) => metadata(await find(args.transferId, context)), + mhu_files_transfer_list: async (_args, context) => { + guard(context); await purge(); + const items = []; + for (const record of records.values()) if (record.owner === context.principalId) items.push(metadata(await find(record.id, context))); + return { transfers: items }; + }, + mhu_files_transfer_read: async (args, context) => { + const record = await find(args.transferId, context); + if (record.state !== 'ready') throw new McpAccessError(record.state === 'failed' ? record.error : 'TRANSFER_NOT_READY'); + const length = args.length ?? CHUNK_BYTES; + if (!Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset > record.initial.size + || !Number.isSafeInteger(length) || length < 1 || length > CHUNK_BYTES) throw new McpAccessError('INVALID_ARGUMENTS'); + const count = Math.min(length, record.initial.size - args.offset); + const buffer = Buffer.alloc(count); + try { + await verify(record); guard(context); + const result = await record.file.read(buffer, 0, count, args.offset); + if (result.bytesRead !== count) throw new McpAccessError('FILE_CHANGED'); + await verify(record); guard(context); + return { transferId: record.id, offset: args.offset, bytesRead: count, nextOffset: args.offset + count < record.initial.size ? args.offset + count : null, + bytes: record.initial.size, sha256: createHash('sha256').update(buffer).digest('hex'), base64: buffer.toString('base64') }; + } catch (error) { record.state = 'failed'; record.error = error instanceof McpAccessError ? error.code : 'FILE_UNAVAILABLE'; await remove(record); throw error; } + }, + mhu_files_transfer_close: async (args, context) => { + guard(context); await purge(); + const record = records.get(args.transferId); + if (!record || record.owner !== context.principalId) return { closed: false }; + await remove(record); return { closed: true }; + } + }; + return { handlers, async dispose() { generation++; clearInterval(timer); timer = null; await Promise.all([...records.values()].map(remove)); } }; +} + +module.exports = { createMcpTransfers, sanitizeTransferResult, CHUNK_BYTES, MAX_BYTES }; diff --git a/main.js b/main.js index 470a5a0..ab39121 100644 --- a/main.js +++ b/main.js @@ -4036,7 +4036,8 @@ async function startMcpService() { const allowed = new Set(['get-app-info', 'automation:get-status', 'run-health-check', 'save-config', 'save-global-settings', 'save-hoster-settings', 'automation:pause-after-active', 'automation:resume', 'reset-session-failed-account', 'folder-monitor:stop', 'folder-monitor:start', 'folder-monitor:test-scan', 'folder-monitor:reconcile', 'get-history', 'prune-history', 'clear-history', 'cloud-log:status', 'cloud-log:configure', 'cloud-log:backfill', - 'online-backup:list-managed', 'online-backup:create-managed', 'online-backup:delete-managed', 'online-backup:restore', 'app:check-updates', 'app:install-update', 'app:restart', 'app:quit']); + 'online-backup:list-managed', 'online-backup:create-managed', 'online-backup:delete-managed', 'online-backup:restore', 'app:check-updates', 'app:install-update', 'app:restart', 'app:quit', + 'get-job-log', 'get-session-failed-account-states']); const invoke = async (channel, ...args) => { if (!allowed.has(channel) || !mcpLocalHandlers.has(channel) || !mainWindow || mainWindow.isDestroyed()) throw new McpAccessError('ACTION_UNAVAILABLE'); return mcpLocalHandlers.get(channel)({ sender: mainWindow.webContents, senderFrame: mainWindow.webContents.mainFrame }, ...args); @@ -4048,7 +4049,20 @@ async function startMcpService() { return mcpLocalHandlers.get(channel)(event, ...args); }; const handlers = createMcpApp({ loadConfig: () => configStore.load(), invoke, invokeGuarded, renderer: mcpRendererAction, collectors: createAppCollectors(), - getGrants: () => mcpService?.store.value.grants || [], trashFile: file => require('electron').shell.trashItem(file), canWrite: assertConfigWriteAllowed }); + getGrants: () => mcpService?.store.value.grants || [], trashFile: file => require('electron').shell.trashItem(file), canWrite: assertConfigWriteAllowed, + getCapabilities: () => mcpService?.capabilities() || [], + getProtectedPaths: () => [app.getPath('userData'), configStore.filePath, configStore.historyPath, configStore.automationCompletionPath], + getInstallationId: () => mcpService?.store.value.identity?.installationId, + getRuntimeDiagnostics: () => ({ + uploads: uploadManager ? { ...uploadManager.getDiagnostics(), running: uploadManager.running, stoppingAfterActive: uploadManager.isStoppingAfterActive(), admissionPending: uploadManager.queueAdmissionPending } : null, + renderer: { available: !!mainWindow && !mainWindow.isDestroyed(), initialized: closeHandshakeReady, generation: folderMonitorRendererGeneration }, + memory: process.memoryUsage() + }), + getDiagnosticSources: () => [ + { label: 'startup-diagnostics.jsonl', path: startupDiagnostics.filePath, directory: path.dirname(startupDiagnostics.filePath) }, + { label: 'startup-diagnostics.jsonl.1', path: startupDiagnostics.filePath + '.1', directory: path.dirname(startupDiagnostics.filePath) }, + ...(nativeStartupLog ? [...nativeStartupLog.files(), ...nativeStartupLog.reports()].map(file => ({ ...file, directory: nativeStartupLog.logDirectory })) : []) + ] }); mcpService = new McpService({ directory: app.getPath('userData'), encrypt: secretStore.encryptField, decrypt: secretStore.decryptField, handlers, version: app.getVersion(), loadConfig: () => configStore.load(), dialog, getWindow: () => mainWindow, onStatus: status => safeSend('mcp:status', status), @@ -4098,15 +4112,22 @@ ipcMain.handle('mcp:add-grant', async event => { return chosen.canceled ? mcpService.state() : mcpService.addGrant(chosen.filePaths[0]); }); ipcMain.handle('mcp:update-grant', async (event, args) => { - if (!isTrustedOnlineBackupIpcEvent(event) || !mcpService || typeof args?.id !== 'string' || typeof args.remove !== 'boolean' || typeof args.readOnly !== 'boolean') throw new Error('MCP_ACCESS_DENIED'); - if (!args.remove && !args.readOnly) { - const grant = mcpService.store.value.grants.find(item => item.id === args.id); - if (!grant) throw new Error('MCP_ACCESS_DENIED'); + if (!isTrustedOnlineBackupIpcEvent(event) || !mcpService || typeof args?.id !== 'string' || typeof args.remove !== 'boolean' || typeof args.readOnly !== 'boolean' + || (args.allowTransfer !== undefined && typeof args.allowTransfer !== 'boolean')) throw new Error('MCP_ACCESS_DENIED'); + const grant = mcpService.store.value.grants.find(item => item.id === args.id); + if (!grant) throw new Error('MCP_ACCESS_DENIED'); + if (!args.remove && !args.readOnly && grant.readOnly !== false) { const result = await dialog.showMessageBox(mainWindow, { type: 'warning', message: shellText('Dateien in diesem Ordner per MCP löschen dürfen?', 'Allow MCP file deletion in this directory?'), detail: grant.path, buttons: ['Abbrechen / Cancel', 'Erlauben / Allow'], defaultId: 0, cancelId: 0, noLink: true }); if (result.response !== 1) return mcpService.state(); } - return mcpService.updateGrant(args.id, args.remove, args.readOnly); + if (!args.remove && args.allowTransfer === true && grant.allowTransfer !== true) { + const result = await dialog.showMessageBox(mainWindow, { type: 'warning', message: shellText('Dateiinhalte aus diesem Ordner per MCP übertragen dürfen?', 'Allow MCP to transfer file contents from this directory?'), + detail: grant.path + '\n\n' + shellText('Freigegebene Dateien können vertrauliche Inhalte enthalten. Die Originale bleiben unverändert.', 'Granted files may contain confidential content. Originals remain unchanged.'), + buttons: ['Abbrechen / Cancel', 'Erlauben / Allow'], defaultId: 0, cancelId: 0, noLink: true }); + if (result.response !== 1) return mcpService.state(); + } + return mcpService.updateGrant(args.id, args.remove, args.readOnly, args.allowTransfer); }); const retiredRemoteState = Object.freeze({ retired: true, enabled: false, running: false, token: '', code: '', port: null, clientCount: 0 }); diff --git a/package-lock.json b/package-lock.json index 22e207f..61a9937 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "ws": "^8.21.3" }, "devDependencies": { + "@modelcontextprotocol/sdk": "1.32.1", "electron": "^41.10.6", "electron-builder": "^26.15.3", "eslint": "^10.8.1", @@ -431,6 +432,19 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@hono/node-server": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.5.tgz", + "integrity": "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -565,6 +579,71 @@ "node": ">=10" } }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", + "integrity": "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/@noble/hashes": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", @@ -777,6 +856,47 @@ "node": "^20.17.0 || >=22.9.0" } }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/acorn": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", @@ -827,6 +947,48 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -1183,6 +1345,45 @@ "dev": true, "license": "MIT" }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/brace-expansion": { "version": "5.0.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", @@ -1243,6 +1444,16 @@ "node": ">=12.0.0" } }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/bytestreamjs": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz", @@ -1296,6 +1507,23 @@ "node": ">= 0.4" } }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -1449,6 +1677,50 @@ "dev": true, "license": "MIT" }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -1456,6 +1728,24 @@ "dev": true, "license": "MIT" }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/cross-dirname": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz", @@ -1640,6 +1930,16 @@ "node": ">=0.4.0" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/dir-compare": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz", @@ -1749,6 +2049,13 @@ "readable-stream": "^2.0.2" } }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, + "license": "MIT" + }, "node_modules/ejs": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", @@ -1908,6 +2215,16 @@ "dev": true, "license": "MIT" }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/end-of-stream": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", @@ -1997,6 +2314,13 @@ "node": ">=6" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, + "license": "MIT" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -2210,6 +2534,39 @@ "node": ">=0.10.0" } }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/exponential-backoff": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", @@ -2217,6 +2574,111 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.7.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.1.tgz", + "integrity": "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -2326,6 +2788,28 @@ "node": ">=10" } }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -2381,6 +2865,26 @@ "node": ">= 6" } }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/fs-extra": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", @@ -2678,6 +3182,16 @@ "node": ">= 0.4" } }, + "node_modules/hono": { + "version": "4.13.13", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", + "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/hosted-git-info": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", @@ -2698,6 +3212,27 @@ "dev": true, "license": "BSD-2-Clause" }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -2740,6 +3275,23 @@ "node": ">= 14" } }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -2779,6 +3331,26 @@ "dev": true, "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-docker": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", @@ -2828,6 +3400,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-wsl": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", @@ -2896,6 +3475,16 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-yaml": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", @@ -2933,6 +3522,13 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "dev": true, + "license": "BSD-2-Clause" + }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -3070,6 +3666,33 @@ "node": ">= 0.4" } }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/mime": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", @@ -3193,6 +3816,37 @@ "dev": true, "license": "MIT" }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/node-abi": { "version": "4.37.0", "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.37.0.tgz", @@ -3323,6 +3977,29 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", @@ -3334,6 +4011,19 @@ "node": ">= 0.4" } }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -3404,6 +4094,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3434,6 +4134,17 @@ "node": ">=8" } }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/pe-library": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz", @@ -3469,6 +4180,16 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pkijs": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.1.tgz", @@ -3598,6 +4319,24 @@ "signal-exit": "^3.0.2" } }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/pump": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", @@ -3639,6 +4378,23 @@ "node": ">=16.0.0" } }, + "node_modules/qs": { + "version": "6.16.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz", + "integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/quick-lru": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", @@ -3652,6 +4408,36 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/rcedit": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/rcedit/-/rcedit-4.0.1.tgz", @@ -3800,6 +4586,23 @@ "rimraf": "bin.js" } }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -3817,6 +4620,13 @@ "regexp-tree": "~0.1.1" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, "node_modules/sanitize-filename": { "version": "1.6.4", "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz", @@ -3850,6 +4660,60 @@ "node": ">=10" } }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/send/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/send/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/serialize-error": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", @@ -3867,6 +4731,33 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, + "license": "ISC" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -3890,6 +4781,82 @@ "node": ">=8" } }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", @@ -3941,6 +4908,16 @@ "node": ">= 6" } }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -4115,6 +5092,16 @@ "tmp": "^0.2.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, "node_modules/truncate-utf8-bytes": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz", @@ -4159,6 +5146,66 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/undici": { "version": "7.29.1", "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", @@ -4185,6 +5232,16 @@ "node": ">= 10.0.0" } }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/unzipper": { "version": "0.12.5", "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", @@ -4238,6 +5295,16 @@ "dev": true, "license": "MIT" }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/webcrypto-core": { "version": "1.9.2", "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", @@ -4392,6 +5459,26 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } } } } diff --git a/package.json b/package.json index 0744f91..154fd98 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "ws": "^8.21.3" }, "devDependencies": { + "@modelcontextprotocol/sdk": "1.32.1", "electron": "^41.10.6", "electron-builder": "^26.15.3", "eslint": "^10.8.1", diff --git a/renderer/i18n.js b/renderer/i18n.js index cd0a21d..db55045 100644 --- a/renderer/i18n.js +++ b/renderer/i18n.js @@ -12,6 +12,8 @@ ['Lesen und Diagnose', 'Read and diagnostics'], ['App steuern', 'Control app'], ['Freigegebene Ordner', 'Granted directories'], + ['Dateiinhalte übertragen', 'Transfer file contents'], + ['Dateiinhalte werden nur nach zusätzlicher Freigabe pro Ordner übertragen. Bestehende Ordnerfreigaben erlauben dies nicht automatisch.', 'File contents are transferred only after additional permission for each directory. Existing directory grants do not allow this automatically.'], ['Zugangsdaten explizit auslesen', 'Explicitly reveal secrets'], ['Speichern und aktivieren', 'Save and enable'], ['Deaktivieren und widerrufen', 'Disable and revoke'], diff --git a/renderer/mcp.js b/renderer/mcp.js index dff7da4..47b7b58 100644 --- a/renderer/mcp.js +++ b/renderer/mcp.js @@ -96,10 +96,13 @@ const name = document.createElement('span'); name.textContent = grant.path; const label = document.createElement('label'); const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = !grant.readOnly; label.append(checkbox, text(' Schreibzugriff', ' Write access')); - checkbox.onchange = () => act(() => window.api.mcpUpdateGrant({ id: grant.id, remove: false, readOnly: !checkbox.checked })); + checkbox.onchange = () => act(() => window.api.mcpUpdateGrant({ id: grant.id, remove: false, readOnly: !checkbox.checked, allowTransfer: grant.allowTransfer === true })); + const transferLabel = document.createElement('label'); const transfer = document.createElement('input'); transfer.type = 'checkbox'; transfer.checked = grant.allowTransfer === true; + transferLabel.append(transfer, text(' Dateiinhalte übertragen', ' Transfer file contents')); + transfer.onchange = () => act(() => window.api.mcpUpdateGrant({ id: grant.id, remove: false, readOnly: grant.readOnly, allowTransfer: transfer.checked })); const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'btn btn-sm btn-secondary'; remove.textContent = text('Entfernen', 'Remove'); remove.onclick = () => act(() => window.api.mcpUpdateGrant({ id: grant.id, remove: true, readOnly: true })); - row.append(name, label, remove); return row; + row.append(name, label, transferLabel, remove); return row; })); }; const act = async action => { @@ -114,7 +117,8 @@
Status
—
${text('Letzter Kontakt','Last contact')}
—
${text('Ausstehende Widerrufe','Pending revocations')}
0

${text('Der Verbindungscode ist ein Zugangsschlüssel. Er wird weder im Backup gespeichert noch auf andere Installationen übertragen. Löschungen und andere gefährliche Aktionen verlangen eine lokale Bestätigung.', 'The connection code is a credential. It is not stored in backups or transferred to other installations. Deletions and other dangerous actions require local confirmation.')}

-
+
+

${text('Dateiinhalte werden nur nach zusätzlicher Freigabe pro Ordner übertragen. Bestehende Ordnerfreigaben erlauben dies nicht automatisch.', 'File contents are transferred only after additional permission for each directory. Existing directory grants do not allow this automatically.')}

`; window.bindMcpSettings = async () => { const area = document.getElementById('mcpControls'); if (!area) return; diff --git a/scripts/mcp-connection.mjs b/scripts/mcp-connection.mjs new file mode 100644 index 0000000..55a0b10 --- /dev/null +++ b/scripts/mcp-connection.mjs @@ -0,0 +1,13 @@ +export function parseConnectionCode(raw) { + const prefix = 'media-mcp:v1:'; + if (typeof raw !== 'string' || raw.length > 16384 || !raw.trim().startsWith(prefix)) throw new Error('Ungültiger Verbindungscode.'); + let value; + let url; + try { value = JSON.parse(Buffer.from(raw.trim().slice(prefix.length), 'base64url').toString('utf8')); url = new URL(value.url); } + catch { throw new Error('Ungültiger Verbindungscode.'); } + if (value.v !== 1 || !['downloader', 'uploader'].includes(value.kind) + || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.installationId) + || !/^[A-Za-z0-9_-]{43}$/.test(value.token) || url.origin !== 'https://downloader.24-music.de' + || url.username || url.password || url.search || url.hash || url.pathname !== `/mcp-relay/mcp/${value.installationId}`) throw new Error('Ungültiger Verbindungscode.'); + return { v: 1, kind: value.kind, installationId: value.installationId, url: url.href, token: value.token }; +} diff --git a/scripts/pull-mcp-file.mjs b/scripts/pull-mcp-file.mjs new file mode 100644 index 0000000..d99ce67 --- /dev/null +++ b/scripts/pull-mcp-file.mjs @@ -0,0 +1,276 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { parseConnectionCode } from './mcp-connection.mjs'; + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const digest = /^[0-9a-f]{64}$/; +const prefixes = { downloader: 'mdd', uploader: 'mhu' }; +const chunkBytes = 1_048_576; + +async function relayFetch(input, init) { + const url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url); + if (url.origin !== 'https://downloader.24-music.de' || !url.pathname.startsWith('/mcp-relay/mcp/') || url.username || url.password || url.search || url.hash) throw new Error('Nicht erlaubtes MCP-Ziel.'); + const response = await fetch(input, { ...init, redirect: 'error' }); + const maximum = 2 * 1024 * 1024; + if (Number(response.headers.get('content-length')) > maximum) { await response.body?.cancel(); throw new Error('MCP-Antwort ist zu groß.'); } + if (!response.body) return response; + const reader = response.body.getReader(); + let bytes = 0; + return new Response(new ReadableStream({ + async pull(controller) { + try { + const part = await reader.read(); + if (part.done) { controller.close(); return; } + bytes += part.value.byteLength; + if (bytes > maximum) { await reader.cancel(); controller.error(new Error('MCP-Antwort ist zu groß.')); return; } + controller.enqueue(part.value); + } catch (error) { controller.error(error); } + }, + cancel: reason => reader.cancel(reason) + }), { status: response.status, statusText: response.statusText, headers: response.headers }); +} + +export function parseTransferReference(raw) { + const prefix = 'media-mcp-file:v1:'; + if (typeof raw !== 'string' || raw.length > 2048 || !raw.startsWith(prefix)) throw new Error('Ungültige Dateireferenz.'); + let value; + try { value = JSON.parse(Buffer.from(raw.slice(prefix.length), 'base64url').toString('utf8')); } + catch { throw new Error('Ungültige Dateireferenz.'); } + if (value?.v !== 1 || !Object.hasOwn(prefixes, value.kind) || !uuid.test(value.installationId) || !uuid.test(value.transferId)) throw new Error('Ungültige Dateireferenz.'); + return value; +} + +async function exists(file) { + try { await fs.lstat(file); return true; } + catch (error) { if (error.code === 'ENOENT') return false; throw error; } +} + +async function openRegular(file, flags) { + const handle = await fs.open(file, flags, 0o600); + try { + const [named, opened] = await Promise.all([fs.lstat(file), handle.stat()]); + if (!opened.isFile() || named.isSymbolicLink() || named.dev !== opened.dev || named.ino !== opened.ino) throw new Error('Lokale Transferdatei ist keine reguläre Datei.'); + return handle; + } catch (error) { await handle.close(); throw error; } +} + +async function removeOwned(file, identity) { + try { + const current = await fs.lstat(file); + if (current.dev !== identity.dev || current.ino !== identity.ino) return false; + await fs.unlink(file); + return true; + } catch (error) { if (error.code === 'ENOENT') return false; throw error; } +} + +async function delay(ms, signal) { + signal.throwIfAborted(); + await new Promise((resolve, reject) => { + const abort = () => { clearTimeout(timer); reject(new Error('Dateitransfer abgebrochen.')); }; + const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(); }, ms); + signal.addEventListener('abort', abort, { once: true }); + }); +} + +function validateInfo(info, expectedId) { + if (!info || !uuid.test(info.transferId) || (expectedId && info.transferId !== expectedId) || !Number.isSafeInteger(info.bytes) || info.bytes < 0 || !['preparing', 'ready', 'failed'].includes(info.state) || (info.state === 'ready' && !digest.test(info.sha256))) throw new Error('Ungültige Transfermetadaten.'); + return info; +} + +export async function receiveMcpFile({ call, installationId, kind, source, transferId, destination, resume = false, signal = new AbortController().signal, onProgress = () => {} }) { + if (!uuid.test(installationId) || !Object.hasOwn(prefixes, kind)) throw new Error('Ungültige Installation.'); + if (!source && !uuid.test(transferId || '')) throw new Error('Quelle oder Dateireferenz fehlt.'); + const requested = path.resolve(destination); + const parent = await fs.realpath(path.dirname(requested)); + const target = path.join(parent, path.basename(requested)); + const part = `${target}.mcp-part`; + const stateFile = `${target}.mcp-transfer.json`; + const lockFile = `${target}.mcp-lock`; + if (await exists(target)) throw new Error('Zieldatei existiert bereits; sie wird nicht überschrieben.'); + const lock = await openRegular(lockFile, 'wx'); + const lockIdentity = await lock.stat(); + let handle; + let stateIdentity; + let info; + let checkpoint; + let completed = 0; + const hash = crypto.createHash('sha256'); + const tool = (suffix, args) => { signal.throwIfAborted(); return call(`${prefixes[kind]}_files_transfer_${suffix}`, args, signal); }; + const safeCall = async (suffix, args) => { + for (let attempt = 0; ; attempt++) { + try { return await tool(suffix, args); } + catch (error) { if (attempt >= 2 || signal.aborted) throw error; await delay(300 * (attempt + 1), signal); } + } + }; + const save = async (create = false) => { + const value = { v: 1, installationId, kind, ...(source ? { source } : {}), transferId: info.transferId, bytes: info.bytes, sha256: info.sha256, completed, prefixSha256: hash.copy().digest('hex') }; + const temporary = `${stateFile}.${crypto.randomUUID()}.tmp`; + const saved = await fs.open(create ? stateFile : temporary, 'wx', 0o600); + let savedIdentity; + try { await saved.writeFile(JSON.stringify(value)); await saved.sync(); savedIdentity = await saved.stat(); } finally { await saved.close(); } + if (!create) { + try { + const current = await fs.lstat(stateFile); + if (!stateIdentity || current.dev !== stateIdentity.dev || current.ino !== stateIdentity.ino || current.isSymbolicLink()) throw new Error('Fortsetzungsdatei wurde ausgetauscht.'); + await fs.rename(temporary, stateFile); + } + catch (error) { await fs.unlink(temporary).catch(() => {}); throw error; } + } + stateIdentity = savedIdentity; + }; + try { + if (resume) { + const stateHandle = await openRegular(stateFile, 'r'); + try { + if ((await stateHandle.stat()).size > 32_768) throw new Error('Ungültiger Fortsetzungsstand.'); + checkpoint = JSON.parse(await stateHandle.readFile('utf8')); + stateIdentity = await stateHandle.stat(); + } finally { await stateHandle.close(); } + if (checkpoint.v !== 1 || checkpoint.installationId !== installationId || checkpoint.kind !== kind || !uuid.test(checkpoint.transferId) || !digest.test(checkpoint.sha256) || !digest.test(checkpoint.prefixSha256) || !Number.isSafeInteger(checkpoint.completed) || checkpoint.completed < 0 || !Number.isSafeInteger(checkpoint.bytes) || checkpoint.bytes < checkpoint.completed || (transferId && checkpoint.transferId !== transferId) || (source && JSON.stringify(checkpoint.source) !== JSON.stringify(source))) throw new Error('Fortsetzungsstand passt nicht zu dieser Quelle.'); + transferId = checkpoint.transferId; + } else if (await exists(part) || await exists(stateFile)) throw new Error('Unvollständiger Transfer vorhanden. Zum Fortsetzen --resume verwenden.'); + if (transferId) { + try { info = validateInfo(await safeCall('get', { transferId }), transferId); } + catch (error) { if (!source || signal.aborted) throw error; } + } + if (!info) info = validateInfo(await tool('open', source)); + const deadline = Date.now() + 1_800_000; + while (info.state === 'preparing') { + if (Date.now() >= deadline) throw new Error('Zeitlimit der Quellprüfung erreicht.'); + onProgress({ phase: 'checking', bytes: info.checkedBytes || 0, total: info.bytes }); + await delay(500, signal); + info = validateInfo(await safeCall('get', { transferId: info.transferId }), info.transferId); + } + if (info.state !== 'ready') throw new Error('Quelldatei ist nicht stabil oder konnte nicht geprüft werden.'); + if (checkpoint && (checkpoint.sha256 !== info.sha256 || checkpoint.bytes !== info.bytes)) throw new Error('Quelldatei hat sich geändert; vorhandener Teiltransfer bleibt unverändert.'); + handle = await openRegular(part, resume ? 'r+' : 'wx+'); + if (checkpoint) { + if ((await handle.stat()).size < checkpoint.completed) throw new Error('Lokale Teildatei ist kürzer als der Fortsetzungsstand.'); + const buffer = Buffer.alloc(chunkBytes); + while (completed < checkpoint.completed) { + signal.throwIfAborted(); + const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, checkpoint.completed - completed), completed); + if (!bytesRead) throw new Error('Lokale Teildatei ist unvollständig.'); + hash.update(buffer.subarray(0, bytesRead)); + completed += bytesRead; + } + if (hash.copy().digest('hex') !== checkpoint.prefixSha256) throw new Error('Prüfsumme der lokalen Teildatei stimmt nicht.'); + await handle.truncate(completed); + await handle.sync(); + await save(); + } else await save(true); + while (completed < info.bytes) { + const length = Math.min(chunkBytes, info.bytes - completed); + const chunk = await safeCall('read', { transferId: info.transferId, offset: completed, length }); + if (!chunk || chunk.transferId !== info.transferId || chunk.offset !== completed || chunk.bytes !== info.bytes || chunk.bytesRead !== length || chunk.nextOffset !== (completed + length < info.bytes ? completed + length : null) || typeof chunk.base64 !== 'string' || chunk.base64.length !== 4 * Math.ceil(length / 3) || !digest.test(chunk.sha256)) throw new Error('Ungültiger Transferblock.'); + const buffer = Buffer.from(chunk.base64, 'base64'); + if (buffer.length !== length || buffer.toString('base64') !== chunk.base64 || crypto.createHash('sha256').update(buffer).digest('hex') !== chunk.sha256) throw new Error('Prüfsumme eines Transferblocks stimmt nicht.'); + signal.throwIfAborted(); + let written = 0; + while (written < buffer.length) { + const result = await handle.write(buffer, written, buffer.length - written, completed + written); + if (!result.bytesWritten) throw new Error('Lokale Datei konnte nicht geschrieben werden.'); + written += result.bytesWritten; + } + hash.update(buffer); + completed += buffer.length; + await handle.sync(); + await save(); + onProgress({ phase: 'receiving', bytes: completed, total: info.bytes }); + } + if ((await handle.stat()).size !== info.bytes || hash.copy().digest('hex') !== info.sha256) throw new Error('Gesamtgröße oder SHA-256 stimmt nicht. Die Datei bleibt als Teiltransfer erhalten.'); + await handle.sync(); + const beforeVerify = await handle.stat(); + const diskHash = crypto.createHash('sha256'); + const verifyBuffer = Buffer.alloc(chunkBytes); + let verified = 0; + while (verified < info.bytes) { + signal.throwIfAborted(); + const { bytesRead } = await handle.read(verifyBuffer, 0, Math.min(verifyBuffer.length, info.bytes - verified), verified); + if (!bytesRead) throw new Error('Lokale Datei während der Prüfung verändert.'); + diskHash.update(verifyBuffer.subarray(0, bytesRead)); + verified += bytesRead; + onProgress({ phase: 'verifying', bytes: verified, total: info.bytes }); + } + const afterVerify = await handle.stat(); + const namedPart = await fs.lstat(part); + if (diskHash.digest('hex') !== info.sha256 || afterVerify.size !== info.bytes || afterVerify.mtimeMs !== beforeVerify.mtimeMs || afterVerify.ctimeMs !== beforeVerify.ctimeMs || namedPart.isSymbolicLink() || namedPart.dev !== afterVerify.dev || namedPart.ino !== afterVerify.ino) throw new Error('Lokale Dateiprüfung fehlgeschlagen. Die Teildatei bleibt erhalten.'); + const finalInfo = validateInfo(await safeCall('get', { transferId: info.transferId }), info.transferId); + if (finalInfo.state !== 'ready' || finalInfo.sha256 !== info.sha256 || finalInfo.bytes !== info.bytes) throw new Error('Quelldatei während des Transfers verändert.'); + signal.throwIfAborted(); + await handle.sync(); + if (await fs.realpath(path.dirname(requested)) !== parent) throw new Error('Zielordner während des Transfers verändert.'); + await fs.link(part, target); + const published = await fs.lstat(target); + const finalStat = await handle.stat(); + if (published.isSymbolicLink() || published.dev !== afterVerify.dev || published.ino !== afterVerify.ino || finalStat.size !== info.bytes || finalStat.mtimeMs !== afterVerify.mtimeMs) { + await removeOwned(target, published); + throw new Error('Zieldatei wurde während der Veröffentlichung ausgetauscht.'); + } + await handle.close(); + handle = null; + await removeOwned(part, afterVerify); + await removeOwned(stateFile, stateIdentity); + await tool('close', { transferId: info.transferId }).catch(() => {}); + return { filePath: target, bytes: completed, sha256: info.sha256, resumed: resume }; + } finally { + await handle?.close().catch(() => {}); + await lock.close(); + await removeOwned(lockFile, lockIdentity).catch(() => {}); + } +} + +export async function pullMcpFile({ codeFile, ...options }) { + if (typeof codeFile !== 'string' || !codeFile || codeFile.includes('media-mcp:')) throw new Error('Private Schlüsseldatei angeben, keinen Verbindungscode als Befehlsargument.'); + const codeHandle = await openRegular(codeFile, 'r'); + let code; + try { + if ((await codeHandle.stat()).size > 16_384) throw new Error('Ungültige Schlüsseldatei.'); + code = parseConnectionCode(await codeHandle.readFile('utf8')); + } finally { await codeHandle.close(); } + if (options.reference) { + const reference = parseTransferReference(options.reference); + if (reference.installationId !== code.installationId || reference.kind !== code.kind) throw new Error('Dateireferenz gehört zu einer anderen Installation.'); + options.transferId = reference.transferId; + } + const client = new Client({ name: 'media-mcp-file-receiver', version: '1.0.0' }); + const transport = new StreamableHTTPClientTransport(new URL(code.url), { requestInit: { headers: { Authorization: `Bearer ${code.token}` } }, fetch: relayFetch }); + try { + await client.connect(transport); + return await receiveMcpFile({ ...options, installationId: code.installationId, kind: code.kind, call: async (name, args, signal) => { + let response; + try { response = await client.callTool({ name, arguments: args }, undefined, { signal, timeout: 120_000 }); } + catch { throw new Error('MCP-Verbindung unterbrochen oder Zugriff abgewiesen.'); } + if (response.isError || !response.structuredContent || !Object.hasOwn(response.structuredContent, 'result')) throw new Error('MCP-Dateizugriff abgewiesen oder Quelldatei nicht verfügbar.'); + return response.structuredContent.result; + } }); + } finally { await client.close().catch(() => {}); } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const abort = new AbortController(); + const stop = () => abort.abort(); + process.once('SIGINT', stop); + process.once('SIGTERM', stop); + try { + const args = process.argv.slice(2); + const resume = args.includes('--resume'); + const values = args.filter(arg => arg !== '--resume'); + let options; + if (values.length === 4 && values[1] === '--transfer') options = { codeFile: values[0], reference: values[2], destination: values[3] }; + else if (values.length === 4 && !values[1].startsWith('--')) options = { codeFile: values[0], source: { rootId: values[1], relativePath: values[2] }, destination: values[3] }; + else throw new Error('Aufruf: node scripts/pull-mcp-file.mjs [--resume] oder --transfer [--resume]'); + let last = 0; + const result = await pullMcpFile({ ...options, resume, signal: abort.signal, onProgress: progress => { + if (Date.now() - last < 1000) return; + last = Date.now(); + process.stderr.write(`${progress.phase}: ${progress.bytes}/${progress.total}\n`); + } }); + process.stdout.write(`${JSON.stringify(result)}\n`); + } catch (error) { process.stderr.write(`${error instanceof Error ? error.message : 'Dateitransfer fehlgeschlagen.'}\n`); process.exitCode = 1; } + finally { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); } +} diff --git a/scripts/verify-public-release.mjs b/scripts/verify-public-release.mjs index 8ae35aa..7de97d9 100644 --- a/scripts/verify-public-release.mjs +++ b/scripts/verify-public-release.mjs @@ -40,6 +40,7 @@ const sourceFiles = [ 'lib/log-rotation.js', 'lib/mcp-access.js', 'lib/mcp-app.js', + 'lib/mcp-diagnostics.js', 'lib/mcp-files.js', 'lib/mcp-protocol.js', 'lib/mcp-relay.js', @@ -47,6 +48,7 @@ const sourceFiles = [ 'lib/mcp-service.js', 'lib/mcp-store.js', 'lib/mcp-tools.js', + 'lib/mcp-transfers.js', 'lib/online-backup.js', 'lib/online-backup-keyring.js', 'lib/online-backup-manager.js', @@ -103,6 +105,8 @@ const sourceFiles = [ 'scripts/afterPack.cjs', 'scripts/backup-recovery.cjs', 'scripts/dev-runner.cjs', + 'scripts/mcp-connection.mjs', + 'scripts/pull-mcp-file.mjs', 'scripts/release-plan.mjs', 'scripts/verify-public-release.mjs', 'services/backup-api/package-lock.json',