Add guarded MCP file transfer and complete diagnostic access
CI / verify (push) Canceled after 0s

This commit is contained in:
Sucukdeluxe committed 2026-10-15 17:31:34 +02:00
1 parent d5022d2d59
commit cd2394dd22
19 files changed
+1757 -32

No files matched your search

+19
View File
@@ -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. 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 <private-code-file> <rootId> <relativePath> <destination>
node scripts/pull-mcp-file.mjs <private-code-file> --transfer <file-reference> <destination>
```
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 ## Development and Windows builds
Install dependencies and start the Electron application: Install dependencies and start the Electron application:
+2
View File
@@ -53,6 +53,8 @@ async function resolveGrantedFile(grants, rootId, relativePath, options = {}) {
if (typeof relativePath !== 'string' || relativePath.includes('\0') || path.isAbsolute(relativePath) if (typeof relativePath !== 'string' || relativePath.includes('\0') || path.isAbsolute(relativePath)
|| /(?:^|[\\/])\.\.(?:[\\/]|$)|:/.test(relativePath)) throw new McpAccessError('PATH_NOT_GRANTED'); || /(?:^|[\\/])\.\.(?:[\\/]|$)|:/.test(relativePath)) throw new McpAccessError('PATH_NOT_GRANTED');
const realRoot = await fs.realpath(grant.path); 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 || '.'); const target = path.resolve(realRoot, relativePath || '.');
if (!within(realRoot, target)) throw new McpAccessError('PATH_NOT_GRANTED'); if (!within(realRoot, target)) throw new McpAccessError('PATH_NOT_GRANTED');
const realTarget = await fs.realpath(target); const realTarget = await fs.realpath(target);
+19 -3
View File
@@ -1,6 +1,10 @@
const { randomUUID } = require('node:crypto'); const { randomUUID } = require('node:crypto');
const { McpAccessError, resolveGrantedFile } = require('./mcp-access'); const { McpAccessError, resolveGrantedFile } = require('./mcp-access');
const { createMcpFiles } = require('./mcp-files'); 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) { function page(items, args) {
const offset = args.offset || 0; 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 }; 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 => { const guard = context => {
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED'); 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); await refresh(context);
return { saved: true }; return { saved: true };
}; };
return { const handlers = {
...createMcpFiles({ getGrants, trashFile }), ...createMcpFiles({ getGrants, trashFile }),
...transfers.handlers,
...createMcpDiagnostics({ getSources: getDiagnosticSources, redact: text => sanitize(redactLogText(text, collectSecretValues(loadConfig()))) }),
mhu_app_info: () => invoke('get-app-info'), mhu_app_info: () => invoke('get-app-info'),
mhu_app_state: async (args, context) => ({ ...(await renderer('state', {}, context)), automation: await invoke('automation:get-status') }), 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_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) => { mhu_queue_add: async (args, context) => {
if (!args.paths.length || !args.hosters.length) throw new McpAccessError('INVALID_ARGUMENTS'); if (!args.paths.length || !args.hosters.length) throw new McpAccessError('INVALID_ARGUMENTS');
const files = []; 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_remove: (args, context) => renderer('queue-remove', args, context),
mhu_queue_clear: (args, context) => renderer('queue-clear', 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_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_check: (args, context) => { if (!args.accountIds.length) throw new McpAccessError('INVALID_ARGUMENTS'); return check(args.accountIds, context); },
mhu_accounts_add: async (args, context) => { mhu_accounts_add: async (args, context) => {
canWrite(); guard(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_prune: args => invoke('prune-history', { retention: args.retention, dryRun: false }),
mhu_history_summary: args => collectors.getHistory({ limit: args.limit || 20 }), mhu_history_summary: args => collectors.getHistory({ limit: args.limit || 20 }),
mhu_history_clear: () => invoke('clear-history'), 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_app_events: args => collectors.getAppEvents(args),
mhu_errors: args => collectors.listErrors(args), mhu_errors: args => collectors.listErrors(args),
mhu_logs_list: () => collectors.listLogs(), mhu_logs_list: () => collectors.listLogs(),
@@ -146,6 +160,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
mhu_app_quit: () => invoke('app:quit'), mhu_app_quit: () => invoke('app:quit'),
mhu_secrets_read: args => { const { password, apiKey } = find(args.accountId); return { accountId: args.accountId, password: password || '', apiKey: apiKey || '' }; } 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 }; module.exports = { createMcpApp, page };
+71
View File
@@ -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 };
+1 -1
View File
@@ -9,7 +9,7 @@ function createMcpFiles({ getGrants, trashFile }) {
}; };
const metadata = stat => ({ size: stat.size, modifiedAt: stat.mtime.toISOString(), directory: stat.isDirectory(), file: stat.isFile() }); const metadata = stat => ({ size: stat.size, modifiedAt: stat.mtime.toISOString(), directory: stat.isDirectory(), file: stat.isFile() });
return { 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) => { mhu_files_stat: async (args, context) => {
guard(context); guard(context);
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath); const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath);
+2 -1
View File
@@ -36,7 +36,8 @@ function createMcpProtocol({ adapter, version, getCapabilities }) {
if (message.method !== 'tools/call') return error(message.id, -32601, 'Method not found'); if (message.method !== 'tools/call') return error(message.id, -32601, 'Method not found');
try { try {
const result = await adapter.call(message.params?.name, message.params?.arguments ?? {}, { ...context, scopes: getCapabilities() }); 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) { } catch (failure) {
const code = failure instanceof McpAccessError ? failure.code : 'ACTION_FAILED'; const code = failure instanceof McpAccessError ? failure.code : 'ACTION_FAILED';
return response(message.id, { content: [{ type: 'text', text: code }], isError: true }); return response(message.id, { content: [{ type: 'text', text: code }], isError: true });
+4 -4
View File
@@ -18,10 +18,10 @@ function createMcpSanitizer(loadConfig) {
const visit = (node, depth = 0) => { const visit = (node, depth = 0) => {
if (depth > 16) throw new McpAccessError('RESULT_TOO_LARGE'); if (depth > 16) throw new McpAccessError('RESULT_TOO_LARGE');
if (typeof node === 'string') { 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]') 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[REDACTED]'); .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('[REDACTED]'); for (const secret of values) result = result.split(secret).join('\0');
return result; return result.replaceAll('\0', '[REDACTED]');
} }
if (Array.isArray(node)) return node.map(item => visit(item, depth + 1)); 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)])); if (node && typeof node === 'object') return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, sensitive.test(key) ? '[REDACTED]' : visit(item, depth + 1)]));
+4 -4
View File
@@ -69,7 +69,7 @@ class McpService {
this.connection = 'disabled'; this.connection = 'disabled';
const agent = this.agent; this.agent = null; const agent = this.agent; this.agent = null;
this.publish(); this.publish();
await agent?.stop(); await Promise.all([agent?.stop(), this.options.handlers?.dispose?.()]);
} }
async retryRevocations() { async retryRevocations() {
const pending = this.store.value.revocations; const pending = this.store.value.revocations;
@@ -139,17 +139,17 @@ class McpService {
const resolved = await fs.realpath(directory); const resolved = await fs.realpath(directory);
const stat = await fs.stat(resolved); const stat = await fs.stat(resolved);
if (!stat.isDirectory() || path.parse(resolved).root === resolved) throw new McpAccessError('PATH_NOT_GRANTED'); 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(); this.publish(); return this.state();
}); });
} }
updateGrant(id, remove, readOnly = true) { updateGrant(id, remove, readOnly = true, allowTransfer) {
const generation = this.generation; const generation = this.generation;
return this.serialize(async () => { return this.serialize(async () => {
const wasActive = this.active; const wasActive = this.active;
await this.disconnect(); await this.disconnect();
await this.store.markDisabled(); 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 }); await this.store.save({ ...this.store.value, grants });
if (wasActive && generation === this.generation) { await this.store.clearDisabled(); this.connect(); } if (wasActive && generation === this.generation) { await this.store.clearDisabled(); this.connect(); }
this.publish(); return this.state(); this.publish(); return this.state();
+2 -1
View File
@@ -25,7 +25,8 @@ class McpStore {
if (typeof value.enabled !== 'boolean' || typeof value.name !== 'string' || !value.name.trim() || value.name.length > 100 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.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) || 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 => { const decode = identity => {
if (!identity) return null; if (!identity) return null;
if (identity.relayUrl !== RELAY_URL || !/^[a-f0-9-]{36}$/.test(identity.installationId)) throw new Error('identity'); if (identity.relayUrl !== RELAY_URL || !/^[a-f0-9-]{36}$/.test(identity.installationId)) throw new Error('identity');
+18 -8
View File
@@ -1,4 +1,5 @@
const { McpAccessError, validateInput, actionDigest } = require('./mcp-access'); const { McpAccessError, validateInput, actionDigest } = require('./mcp-access');
const { sanitizeTransferResult } = require('./mcp-transfers');
const text = (maxLength = 4096) => ({ type: 'string', maxLength }); const text = (maxLength = 4096) => ({ type: 'string', maxLength });
const id = { type: 'string', minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_.:-]+$' }; 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_info', 'Read application version and runtime information.', 'read', {}, []],
['app_state', 'Read live transfer and automation summary.', '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_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_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_start', 'Start eligible queued uploads.', 'control', jobIds, []],
['queue_pause', 'Pause new uploads after current transfers.', 'control', {}, []], ['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_remove', 'Remove selected jobs without deleting source files.', 'control', jobIds, ['jobIds'], true],
['queue_clear', 'Clear inactive jobs without deleting source files.', 'control', {}, [], 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_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_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_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']], ['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']), name: enumeration(['debug', 'fileuploader', 'uploadAudit', 'accountRotation', 'crash']),
tailKb: integer(1, 256), backup: integer(0, 2), grep: text(200) tailKb: integer(1, 256), backup: integer(0, 2), grep: text(200)
}, ['name']], }, ['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_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_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_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_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], ['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_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']], ['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 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({ 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), 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'] : [])])], 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), destructiveHint: destructive, 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), openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) } 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 }) { function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit = () => {}, getCapabilities, requiresConfirmation = () => false }) {
@@ -105,9 +117,7 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit
const tool = byName.get(name); const tool = byName.get(name);
if (!tool || typeof handlers[name] !== 'function') throw new McpAccessError('TOOL_UNAVAILABLE'); if (!tool || typeof handlers[name] !== 'function') throw new McpAccessError('TOOL_UNAVAILABLE');
const allowed = () => getCapabilities ? getCapabilities() : context?.scopes; const allowed = () => getCapabilities ? getCapabilities() : context?.scopes;
const permitted = () => Array.isArray(allowed()) && allowed().includes(tool.scope) const permitted = () => Array.isArray(allowed()) && tool.requiredScopes.every(scope => allowed().includes(scope));
&& (name !== 'mhu_files_delete' || allowed().includes('control'))
&& (!['mhu_queue_add', 'mhu_automation_update'].includes(name) || allowed().includes('files'));
if (!permitted()) throw new McpAccessError('SCOPE_DENIED'); if (!permitted()) throw new McpAccessError('SCOPE_DENIED');
validateInput(args, tool.inputSchema); validateInput(args, tool.inputSchema);
if (context.signal?.aborted || !Number.isFinite(context.deadline) || context.deadline <= Date.now()) throw new McpAccessError('REQUEST_EXPIRED'); 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); const value = await handlers[name](args, context);
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED'); if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
if (!permitted()) throw new McpAccessError('SCOPE_DENIED'); if (!permitted()) throw new McpAccessError('SCOPE_DENIED');
const result = name === 'mhu_secrets_read' ? value : await sanitize(value); 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') > 1024 * 1024) throw new McpAccessError('RESULT_TOO_LARGE'); 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 }); audit({ tool: name, event: 'completed', requestId: context.requestId, durationMs: Date.now() - startedAt });
return result; return result;
}; };
+197
View File
@@ -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 };
+28 -7
View File
@@ -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', 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', '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', '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) => { const invoke = async (channel, ...args) => {
if (!allowed.has(channel) || !mcpLocalHandlers.has(channel) || !mainWindow || mainWindow.isDestroyed()) throw new McpAccessError('ACTION_UNAVAILABLE'); 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); 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); return mcpLocalHandlers.get(channel)(event, ...args);
}; };
const handlers = createMcpApp({ loadConfig: () => configStore.load(), invoke, invokeGuarded, renderer: mcpRendererAction, collectors: createAppCollectors(), 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, mcpService = new McpService({ directory: app.getPath('userData'), encrypt: secretStore.encryptField, decrypt: secretStore.decryptField,
handlers, version: app.getVersion(), loadConfig: () => configStore.load(), dialog, getWindow: () => mainWindow, handlers, version: app.getVersion(), loadConfig: () => configStore.load(), dialog, getWindow: () => mainWindow,
onStatus: status => safeSend('mcp:status', status), 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]); return chosen.canceled ? mcpService.state() : mcpService.addGrant(chosen.filePaths[0]);
}); });
ipcMain.handle('mcp:update-grant', async (event, args) => { 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 (!isTrustedOnlineBackupIpcEvent(event) || !mcpService || typeof args?.id !== 'string' || typeof args.remove !== 'boolean' || typeof args.readOnly !== 'boolean'
if (!args.remove && !args.readOnly) { || (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); const grant = mcpService.store.value.grants.find(item => item.id === args.id);
if (!grant) throw new Error('MCP_ACCESS_DENIED'); 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, 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 }); buttons: ['Abbrechen / Cancel', 'Erlauben / Allow'], defaultId: 0, cancelId: 0, noLink: true });
if (result.response !== 1) return mcpService.state(); 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 }); const retiredRemoteState = Object.freeze({ retired: true, enabled: false, running: false, token: '', code: '', port: null, clientCount: 0 });
+1087
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -17,6 +17,7 @@
"ws": "^8.21.3" "ws": "^8.21.3"
}, },
"devDependencies": { "devDependencies": {
"@modelcontextprotocol/sdk": "1.32.1",
"electron": "^41.10.6", "electron": "^41.10.6",
"electron-builder": "^26.15.3", "electron-builder": "^26.15.3",
"eslint": "^10.8.1", "eslint": "^10.8.1",
+2
View File
@@ -12,6 +12,8 @@
['Lesen und Diagnose', 'Read and diagnostics'], ['Lesen und Diagnose', 'Read and diagnostics'],
['App steuern', 'Control app'], ['App steuern', 'Control app'],
['Freigegebene Ordner', 'Granted directories'], ['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'], ['Zugangsdaten explizit auslesen', 'Explicitly reveal secrets'],
['Speichern und aktivieren', 'Save and enable'], ['Speichern und aktivieren', 'Save and enable'],
['Deaktivieren und widerrufen', 'Disable and revoke'], ['Deaktivieren und widerrufen', 'Disable and revoke'],
+7 -3
View File
@@ -96,10 +96,13 @@
const name = document.createElement('span'); name.textContent = grant.path; 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; const label = document.createElement('label'); const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = !grant.readOnly;
label.append(checkbox, text(' Schreibzugriff', ' Write access')); 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'); 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 })); 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 => { const act = async action => {
@@ -114,7 +117,8 @@
<div class="mcp-actions"><button class="btn btn-sm btn-primary" data-mcp-action="enable">${text('Speichern und aktivieren','Save and enable')}</button><button class="btn btn-sm btn-secondary" data-mcp-action="disable">${text('Deaktivieren und widerrufen','Disable and revoke')}</button><button class="btn btn-sm btn-secondary" data-mcp-action="copy">${text('Verbindungscode kopieren','Copy connection code')}</button><button class="btn btn-sm btn-secondary" data-mcp-action="rotate">${text('Zugang erneuern','Rotate access')}</button></div> <div class="mcp-actions"><button class="btn btn-sm btn-primary" data-mcp-action="enable">${text('Speichern und aktivieren','Save and enable')}</button><button class="btn btn-sm btn-secondary" data-mcp-action="disable">${text('Deaktivieren und widerrufen','Disable and revoke')}</button><button class="btn btn-sm btn-secondary" data-mcp-action="copy">${text('Verbindungscode kopieren','Copy connection code')}</button><button class="btn btn-sm btn-secondary" data-mcp-action="rotate">${text('Zugang erneuern','Rotate access')}</button></div>
<dl class="mcp-status"><div><dt>Status</dt><dd data-mcp-status>—</dd></div><div><dt>${text('Letzter Kontakt','Last contact')}</dt><dd data-mcp-contact>—</dd></div><div><dt>${text('Ausstehende Widerrufe','Pending revocations')}</dt><dd data-mcp-pending>0</dd></div></dl> <dl class="mcp-status"><div><dt>Status</dt><dd data-mcp-status>—</dd></div><div><dt>${text('Letzter Kontakt','Last contact')}</dt><dd data-mcp-contact>—</dd></div><div><dt>${text('Ausstehende Widerrufe','Pending revocations')}</dt><dd data-mcp-pending>0</dd></div></dl>
<p>${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.')}</p> <p>${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.')}</p>
<div class="mcp-actions"><button class="btn btn-sm btn-secondary" data-mcp-action="grant">${text('Ordner freigeben','Grant directory')}</button></div><div data-mcp-grants></div> <div class="mcp-actions"><button class="btn btn-sm btn-secondary" data-mcp-action="grant">${text('Ordner freigeben','Grant directory')}</button></div>
<p>${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.')}</p><div data-mcp-grants></div>
</section>`; </section>`;
window.bindMcpSettings = async () => { window.bindMcpSettings = async () => {
const area = document.getElementById('mcpControls'); if (!area) return; const area = document.getElementById('mcpControls'); if (!area) return;
+13
View File
@@ -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 };
}
+276
View File
@@ -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 <private-code-file> <rootId> <relativePath> <destination> [--resume] oder <private-code-file> --transfer <reference> <destination> [--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); }
}
+4
View File
@@ -40,6 +40,7 @@ const sourceFiles = [
'lib/log-rotation.js', 'lib/log-rotation.js',
'lib/mcp-access.js', 'lib/mcp-access.js',
'lib/mcp-app.js', 'lib/mcp-app.js',
'lib/mcp-diagnostics.js',
'lib/mcp-files.js', 'lib/mcp-files.js',
'lib/mcp-protocol.js', 'lib/mcp-protocol.js',
'lib/mcp-relay.js', 'lib/mcp-relay.js',
@@ -47,6 +48,7 @@ const sourceFiles = [
'lib/mcp-service.js', 'lib/mcp-service.js',
'lib/mcp-store.js', 'lib/mcp-store.js',
'lib/mcp-tools.js', 'lib/mcp-tools.js',
'lib/mcp-transfers.js',
'lib/online-backup.js', 'lib/online-backup.js',
'lib/online-backup-keyring.js', 'lib/online-backup-keyring.js',
'lib/online-backup-manager.js', 'lib/online-backup-manager.js',
@@ -103,6 +105,8 @@ const sourceFiles = [
'scripts/afterPack.cjs', 'scripts/afterPack.cjs',
'scripts/backup-recovery.cjs', 'scripts/backup-recovery.cjs',
'scripts/dev-runner.cjs', 'scripts/dev-runner.cjs',
'scripts/mcp-connection.mjs',
'scripts/pull-mcp-file.mjs',
'scripts/release-plan.mjs', 'scripts/release-plan.mjs',
'scripts/verify-public-release.mjs', 'scripts/verify-public-release.mjs',
'services/backup-api/package-lock.json', 'services/backup-api/package-lock.json',