Add opt-in MCP access with local authorization and revocable identities
CI / verify (push) Canceled after 0s
CI / verify (push) Canceled after 0s
This commit is contained in:
1 parent
febe654189
commit
93e0196dbe
20 files changed
+1246
-8
No files matched your search
@@ -28,3 +28,6 @@ upload-debug.log
|
||||
release-*.log
|
||||
recovery-private.pem
|
||||
recovered-online-key*.txt
|
||||
mcp-access.json
|
||||
mcp-access.json.*.tmp
|
||||
mcp-disabled.marker
|
||||
@@ -286,6 +286,23 @@ New successful upload entries for hosts with file logging enabled are synchroniz
|
||||
|
||||
The panel shows the connection state, IP folder, last successful sync and pending files. Changes are queued locally, retried after connection failures and resumed after restarting the application. Disabling sync retains pending entries but stops collecting new ones. A revoked key requires verification with a valid key. Local pending data is tied to its Clouddrop account and is never sent to another account after changing keys.
|
||||
|
||||
## MCP remote access
|
||||
|
||||
Settings → Remote control provides an optional structured MCP connection. Assign an installation name, select local permissions and choose **Save and enable**. The application connects to its HTTPS relay using outbound long polling; it does not open an incoming desktop port. Keep the application running, including minimized, while using this connection.
|
||||
|
||||
Copy the connection code only when configuring a trusted MCP client. It contains a credential. Each installation has separate encrypted credentials outside settings backups. **Disable and revoke** stops local execution immediately and revokes the credentials at the relay; an offline revocation remains pending until contact is restored. **Rotate access** invalidates the previous identity and creates a new code. Importing a settings backup does not import another installation's MCP identity.
|
||||
|
||||
Permissions are configured locally, never through remote tools:
|
||||
|
||||
- **Read and diagnostics:** application state, paginated queue/accounts/history, settings with secrets masked, and bounded application-log tails.
|
||||
- **Control app:** explicit queue, account, settings, automation, CloudDrop, backup and lifecycle operations. There is no generic script, shell or IPC execution tool.
|
||||
- **Granted directories:** list, inspect and checksum files only inside explicitly selected directories. Queue additions also require control permission. File deletion additionally requires a writable directory grant, control permission and local confirmation; it uses the operating system's trash operation.
|
||||
- **Explicitly reveal secrets:** separately enabled access to a specifically requested account's credentials. Normal diagnostics and other tool responses remain masked.
|
||||
|
||||
Destructive operations require a native local confirmation for the exact action and arguments. Cancel is the default, approval expires within 60 seconds, and no remote tool or boolean can grant it. Starting transfers also requires confirmation when current settings enable automatic source deletion or power actions. Cancellation and expiry prevent pending actions from starting; they cannot undo an action already committed.
|
||||
|
||||
The legacy screen/input connection remains available during migration. Screen streaming, granting new filesystem roots, changing MCP permissions and obtaining the connection code are not remote MCP operations. A compatible Streamable HTTP client must be configured separately. Local support-package export remains available without MCP.
|
||||
|
||||
## Development and Windows builds
|
||||
|
||||
Install dependencies and start the Electron application:
|
||||
|
||||
@@ -102,6 +102,17 @@ export default [
|
||||
},
|
||||
rules: sharedRules
|
||||
},
|
||||
{
|
||||
files: ['renderer/mcp.js'],
|
||||
languageOptions: {
|
||||
globals: Object.fromEntries([
|
||||
'getUiLocale', 'config', 'hosterSettings', 'ensureAccountStatusEntries', 'syncSelectedUploadHosters', 'renderAccounts', 'renderHosterSummary',
|
||||
'rebuildJobIndex', '_queueStatsCache', 'syncSelectedFilesFromQueue', 'renderQueueTable', 'updateUploadView', 'updateStatusBar', 'queueJobs',
|
||||
'uploading', 'selectedFiles', 'findAccountById', 'accountStatuses', 'existingImportPaths', 'createAutomationPreviewJob', 'clearDedupKeysForPaths',
|
||||
'persistQueueStateNow', 'isStartableQueueStatus', 'startSelectedUpload', '_jobIndexByUploadId', '_deletedJobIds', 'removeJobFromIndex', 'showCopyToast'
|
||||
].map(name => [name, 'writable']))
|
||||
}
|
||||
},
|
||||
{
|
||||
files: ['lib/diagnostics-collectors.js', 'lib/log-mode.js', 'lib/support-bundle.js'],
|
||||
rules: {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { createHash, timingSafeEqual } = require('node:crypto');
|
||||
|
||||
class McpAccessError extends Error {
|
||||
constructor(code) { super(code); this.code = code; }
|
||||
}
|
||||
|
||||
const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
||||
|
||||
function validateInput(value, schema, depth = 0) {
|
||||
if (depth > 12) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
if (schema.enum && !schema.enum.includes(value)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
if (schema.type === 'object') {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
const keys = Object.keys(value);
|
||||
if (keys.length > 100 || keys.some(key => ['__proto__', 'constructor', 'prototype'].includes(key))) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
for (const key of schema.required || []) if (!own(value, key)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
for (const key of keys) {
|
||||
if (!own(schema.properties || {}, key)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
validateInput(value[key], schema.properties[key], depth + 1);
|
||||
}
|
||||
} else if (schema.type === 'array') {
|
||||
if (!Array.isArray(value) || value.length > (schema.maxItems ?? 1000) || value.length < (schema.minItems ?? 0)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
for (const entry of value) validateInput(entry, schema.items, depth + 1);
|
||||
} else if (schema.type === 'string') {
|
||||
if (typeof value !== 'string' || value.length > (schema.maxLength ?? 4096) || value.length < (schema.minLength ?? 0) || value.includes('\0')) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
if (schema.pattern === '^[A-Za-z0-9_.:-]+$' && !/^[A-Za-z0-9_.:-]+$/.test(value)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
if (schema.pattern === '^[A-Za-z0-9]+$' && !/^[A-Za-z0-9]+$/.test(value)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
} else if (schema.type === 'integer' || schema.type === 'number') {
|
||||
if (!Number.isFinite(value) || (schema.type === 'integer' && !Number.isSafeInteger(value)) || value < (schema.minimum ?? -Infinity) || value > (schema.maximum ?? Infinity)) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
} else if (schema.type === 'boolean') {
|
||||
if (typeof value !== 'boolean') throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
} else throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
}
|
||||
|
||||
function canonical(value) {
|
||||
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
||||
if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key])).join(',') + '}';
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function actionDigest(name, args) { return createHash('sha256').update(canonical({ name, args })).digest('hex'); }
|
||||
|
||||
function within(root, candidate) {
|
||||
const relative = path.relative(root, candidate);
|
||||
return relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
async function resolveGrantedFile(grants, rootId, relativePath, options = {}) {
|
||||
const grant = grants.find(entry => entry.id === rootId && entry.enabled !== false);
|
||||
if (!grant || (options.write && grant.readOnly !== false)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
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 target = path.resolve(realRoot, relativePath || '.');
|
||||
if (!within(realRoot, target)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
const realTarget = await fs.realpath(target);
|
||||
if (!within(realRoot, realTarget)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
const stat = await fs.stat(realTarget);
|
||||
if (options.regularFile && !stat.isFile()) throw new McpAccessError('NOT_A_FILE');
|
||||
return { path: realTarget, stat, root: realRoot };
|
||||
}
|
||||
|
||||
function safeEqual(left, right) {
|
||||
const a = Buffer.from(String(left || ''));
|
||||
const b = Buffer.from(String(right || ''));
|
||||
return a.length > 0 && a.length === b.length && timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
module.exports = { McpAccessError, validateInput, actionDigest, canonical, resolveGrantedFile, safeEqual };
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { McpAccessError, resolveGrantedFile } = require('./mcp-access');
|
||||
const { createMcpFiles } = require('./mcp-files');
|
||||
|
||||
function page(items, args) {
|
||||
const offset = args.offset || 0;
|
||||
const limit = args.limit || 100;
|
||||
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 }) {
|
||||
const guard = context => {
|
||||
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
};
|
||||
const accounts = () => Object.entries(loadConfig().hosters).flatMap(([hoster, list]) => Array.isArray(list) ? list.map(account => ({ hoster, ...account })) : []);
|
||||
const find = id => {
|
||||
const found = accounts().find(account => account.id === id);
|
||||
if (!found) throw new McpAccessError('ACCOUNT_NOT_FOUND');
|
||||
return found;
|
||||
};
|
||||
const refresh = async context => { if (!context.signal?.aborted) await renderer('refresh', {}, context).catch(() => {}); };
|
||||
const saveAccount = async (id, patch, context, remove = false) => {
|
||||
canWrite(); guard(context);
|
||||
const latest = loadConfig();
|
||||
const found = find(id);
|
||||
const next = latest.hosters[found.hoster].filter(account => !remove || account.id !== id).map(account => account.id === id ? { ...account, ...patch } : account);
|
||||
await invoke('save-config', { hosters: { ...latest.hosters, [found.hoster]: next } });
|
||||
await refresh(context);
|
||||
return { accountId: id, saved: true };
|
||||
};
|
||||
const check = async (ids, context, options = {}) => {
|
||||
const results = [];
|
||||
for (const id of [...new Set(ids)]) {
|
||||
guard(context);
|
||||
const found = find(id);
|
||||
const result = await invoke('run-health-check', { hosters: [{ hoster: found.hoster, accountId: id, ...options }] });
|
||||
results.push(...result.results);
|
||||
}
|
||||
await renderer('account-results', { results }, context).catch(() => {});
|
||||
return { results };
|
||||
};
|
||||
const saveGlobal = async (patch, context) => {
|
||||
canWrite(); guard(context);
|
||||
await invoke('save-global-settings', { ...loadConfig().globalSettings, ...patch });
|
||||
await refresh(context);
|
||||
return { saved: true };
|
||||
};
|
||||
return {
|
||||
...createMcpFiles({ getGrants, trashFile }),
|
||||
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_add: async (args, context) => {
|
||||
if (!args.paths.length || !args.hosters.length) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
const files = [];
|
||||
for (const relativePath of args.paths) { guard(context); const target = await resolveGrantedFile(getGrants(), args.rootId, relativePath, { regularFile: true }); files.push(target.path); }
|
||||
guard(context);
|
||||
return renderer('queue-add', { paths: files, hosters: args.hosters }, context);
|
||||
},
|
||||
mhu_queue_start: (args, context) => renderer('queue-start', args, context),
|
||||
mhu_queue_pause: () => invoke('automation:pause-after-active'),
|
||||
mhu_queue_resume: async (args, context) => { guard(context); return invoke('automation:resume'); },
|
||||
mhu_queue_retry: (args, context) => renderer('queue-retry', args, context),
|
||||
mhu_queue_cancel: (args, context) => renderer('queue-cancel', args, context),
|
||||
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_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);
|
||||
if ((args.authType === 'login' && (!args.username || !args.password)) || (args.authType === 'api' && !args.apiKey)
|
||||
|| (['byse.sx', 'clouddrop.cc'].includes(args.hoster) && args.authType !== 'api') || (args.hoster === 'vidmoly.me' && args.authType !== 'login')) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
const latest = loadConfig();
|
||||
const id = randomUUID();
|
||||
const { hoster, ...account } = args;
|
||||
await invoke('save-config', { hosters: { ...latest.hosters, [hoster]: [...latest.hosters[hoster], { ...account, id, enabled: false }] } });
|
||||
await refresh(context);
|
||||
return { accountId: id, enabled: false, verificationRequired: true };
|
||||
},
|
||||
mhu_accounts_update: ({ accountId, ...patch }, context) => saveAccount(accountId, patch, context),
|
||||
mhu_accounts_otp: (args, context) => check([args.accountId], context, { otp: args.code }),
|
||||
mhu_accounts_request_otp: (args, context) => check([args.accountId], context, { requestNewOtp: true }),
|
||||
mhu_accounts_priority: async (args, context) => {
|
||||
canWrite(); guard(context);
|
||||
const found = find(args.accountId);
|
||||
const latest = loadConfig();
|
||||
const list = [...latest.hosters[found.hoster]];
|
||||
const index = list.findIndex(account => account.id === args.accountId);
|
||||
const target = Math.max(0, Math.min(list.length - 1, index + (args.direction === 'up' ? -1 : 1)));
|
||||
const [item] = list.splice(index, 1); list.splice(target, 0, item);
|
||||
await invoke('save-config', { hosters: { ...latest.hosters, [found.hoster]: list } });
|
||||
await refresh(context);
|
||||
return { saved: true, position: target };
|
||||
},
|
||||
mhu_accounts_remove: (args, context) => saveAccount(args.accountId, {}, context, true),
|
||||
mhu_accounts_reset_failure: args => { const account = find(args.accountId); return invoke('reset-session-failed-account', { hoster: account.hoster, accountId: args.accountId }); },
|
||||
mhu_settings_get: () => { const config = loadConfig(); const settings = { ...config.globalSettings }; delete settings.pendingQueue; delete settings.uploadRecovery; return { globalSettings: settings, hosterSettings: config.hosterSettings }; },
|
||||
mhu_settings_update: (args, context) => saveGlobal(args, context),
|
||||
mhu_hoster_settings_update: async ({ hoster, ...patch }, context) => {
|
||||
canWrite(); guard(context);
|
||||
const current = loadConfig().hosterSettings;
|
||||
await invoke('save-hoster-settings', { ...current, [hoster]: { ...current[hoster], ...patch } });
|
||||
await refresh(context);
|
||||
return { saved: true };
|
||||
},
|
||||
mhu_automation_status: () => invoke('automation:get-status'),
|
||||
mhu_automation_update: async ({ rootId, ...patch }, context) => {
|
||||
const folder = await resolveGrantedFile(getGrants(), rootId, '');
|
||||
if (!folder.stat.isDirectory()) throw new McpAccessError('NOT_A_DIRECTORY');
|
||||
const result = await saveGlobal({ folderMonitor: { ...loadConfig().globalSettings.folderMonitor, ...patch, folderPath: folder.path, enabled: false } }, context);
|
||||
await invoke('folder-monitor:stop');
|
||||
return { ...result, enabled: false };
|
||||
},
|
||||
mhu_automation_start: async (args, context) => {
|
||||
const settings = loadConfig().globalSettings.folderMonitor;
|
||||
if (!getGrants().some(grant => grant.path === settings.folderPath)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
await saveGlobal({ folderMonitor: { ...settings, enabled: true } }, context); guard(context);
|
||||
return invoke('folder-monitor:start', { ...settings, enabled: true });
|
||||
},
|
||||
mhu_automation_stop: async (args, context) => { await saveGlobal({ folderMonitor: { ...loadConfig().globalSettings.folderMonitor, enabled: false } }, context); return invoke('folder-monitor:stop'); },
|
||||
mhu_automation_scan: () => invoke('folder-monitor:test-scan'),
|
||||
mhu_automation_reconcile: () => invoke('folder-monitor:reconcile'),
|
||||
mhu_history_list: async args => {
|
||||
const batches = await invoke('get-history');
|
||||
const rows = batches.flatMap(batch => (batch.files || []).flatMap(file => (file.results || []).map(result => ({ timestamp: batch.timestamp, fileName: file.fileName || file.name, ...result }))));
|
||||
return page(rows, args);
|
||||
},
|
||||
mhu_history_prune: args => invoke('prune-history', { retention: args.retention, dryRun: false }),
|
||||
mhu_history_clear: () => invoke('clear-history'),
|
||||
mhu_diagnostics_summary: () => ({ system: collectors.getSystemInfo(), health: collectors.getHealth(), rotation: collectors.getRotationState() }),
|
||||
mhu_logs_list: () => collectors.listLogs(),
|
||||
mhu_logs_read: args => collectors.readLog(args),
|
||||
mhu_cloud_status: () => invoke('cloud-log:status'),
|
||||
mhu_cloud_configure: args => invoke('cloud-log:configure', args),
|
||||
mhu_cloud_backfill: () => invoke('cloud-log:backfill'),
|
||||
mhu_backup_list: () => invoke('online-backup:list-managed'),
|
||||
mhu_backup_create: args => invoke('online-backup:create-managed', args.retention),
|
||||
mhu_backup_delete: args => invoke('online-backup:delete-managed', args.id),
|
||||
mhu_backup_restore: async (args, context) => { const result = await invokeGuarded(context, 'online-backup:restore', args.key); if (!result.ok) throw new McpAccessError('RESTORE_FAILED'); await refresh(context); return { ok: true, warnings: result.warnings }; },
|
||||
mhu_update_check: () => invoke('app:check-updates', { forceRefresh: true }),
|
||||
mhu_update_install: (args, context) => invokeGuarded(context, 'app:install-update'),
|
||||
mhu_app_restart: () => invoke('app:restart'),
|
||||
mhu_app_quit: () => invoke('app:quit'),
|
||||
mhu_secrets_read: args => { const { password, apiKey } = find(args.accountId); return { accountId: args.accountId, password: password || '', apiKey: apiKey || '' }; }
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createMcpApp, page };
|
||||
@@ -0,0 +1,64 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { createHash } = require('node:crypto');
|
||||
const { McpAccessError, resolveGrantedFile } = require('./mcp-access');
|
||||
|
||||
function createMcpFiles({ getGrants, trashFile }) {
|
||||
const guard = context => {
|
||||
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
};
|
||||
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_stat: async (args, context) => {
|
||||
guard(context);
|
||||
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath);
|
||||
return { ...metadata(target.stat), relativePath: args.relativePath };
|
||||
},
|
||||
mhu_files_list: async (args, context) => {
|
||||
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath || '');
|
||||
if (!target.stat.isDirectory()) throw new McpAccessError('NOT_A_DIRECTORY');
|
||||
const names = [];
|
||||
for await (const entry of await fs.opendir(target.path)) {
|
||||
guard(context);
|
||||
if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) continue;
|
||||
names.push({ name: entry.name, directory: entry.isDirectory() });
|
||||
if (names.length > 100000) throw new McpAccessError('DIRECTORY_TOO_LARGE');
|
||||
}
|
||||
names.sort((a, b) => a.name.localeCompare(b.name));
|
||||
const offset = args.offset || 0;
|
||||
const limit = args.limit || 100;
|
||||
return { total: names.length, offset, items: names.slice(offset, offset + limit), nextOffset: offset + limit < names.length ? offset + limit : null };
|
||||
},
|
||||
mhu_files_hash: async (args, context) => {
|
||||
guard(context);
|
||||
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath, { regularFile: true });
|
||||
if (target.stat.size > 32 * 1024 ** 3) throw new McpAccessError('FILE_TOO_LARGE');
|
||||
const file = await fs.open(target.path, 'r');
|
||||
try {
|
||||
const initial = await file.stat();
|
||||
if (initial.ino !== target.stat.ino || initial.dev !== target.stat.dev || !initial.isFile()) throw new McpAccessError('FILE_CHANGED');
|
||||
const algorithm = args.algorithm || 'sha256';
|
||||
const hash = createHash(algorithm);
|
||||
for await (const chunk of file.createReadStream({ autoClose: false, highWaterMark: 256 * 1024 })) { guard(context); hash.update(chunk); }
|
||||
const final = await file.stat();
|
||||
if (initial.size !== final.size || initial.mtimeMs !== final.mtimeMs || initial.ctimeMs !== final.ctimeMs) throw new McpAccessError('FILE_CHANGED');
|
||||
return { algorithm, digest: hash.digest('hex'), size: final.size };
|
||||
} finally { await file.close(); }
|
||||
},
|
||||
mhu_files_delete: async (args, context) => {
|
||||
guard(context);
|
||||
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath, { regularFile: true, write: true });
|
||||
const checked = await fs.lstat(target.path);
|
||||
if (checked.isSymbolicLink() || checked.ino !== target.stat.ino || checked.dev !== target.stat.dev) throw new McpAccessError('FILE_CHANGED');
|
||||
const current = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath, { regularFile: true, write: true });
|
||||
if (current.path !== target.path || current.stat.ino !== checked.ino || current.stat.dev !== checked.dev) throw new McpAccessError('FILE_CHANGED');
|
||||
guard(context);
|
||||
if (typeof trashFile !== 'function') throw new McpAccessError('TOOL_UNAVAILABLE');
|
||||
await trashFile(path.normalize(target.path));
|
||||
return { trashed: true, relativePath: args.relativePath };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createMcpFiles };
|
||||
@@ -0,0 +1,48 @@
|
||||
const { McpAccessError } = require('./mcp-access');
|
||||
|
||||
function createMcpProtocol({ adapter, version, getCapabilities }) {
|
||||
const sessions = new Map();
|
||||
const error = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
|
||||
const response = (id, result) => ({ jsonrpc: '2.0', id, result });
|
||||
async function handle(message, context) {
|
||||
for (const [key, seen] of sessions) if (Date.now() - seen > 30 * 60 * 1000) sessions.delete(key);
|
||||
if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string' || Array.isArray(message)
|
||||
|| (message.id !== undefined && typeof message.id !== 'string' && !(typeof message.id === 'number' && Number.isFinite(message.id)))) return error(null, -32600, 'Invalid request');
|
||||
if (!context || typeof context.sessionId !== 'string' || typeof context.principalId !== 'string') return error(message.id, -32600, 'Invalid session');
|
||||
const sessionKey = context.principalId + ':' + context.sessionId;
|
||||
if (message.method === 'initialize') {
|
||||
if (message.id === undefined || !message.params || typeof message.params.protocolVersion !== 'string') return error(message.id, -32602, 'Invalid initialization');
|
||||
if (sessions.size >= 16 && !sessions.has(sessionKey)) return error(message.id, -32000, 'Session limit');
|
||||
sessions.set(sessionKey, Date.now());
|
||||
const requested = message.params?.protocolVersion;
|
||||
const protocolVersion = ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(requested) ? requested : '2025-11-25';
|
||||
return response(message.id, { protocolVersion, capabilities: { tools: {}, resources: {} }, serverInfo: { name: 'multi-hoster-uploader', version }, instructions: 'Tools operate on one running uploader installation. Destructive actions require a local confirmation. Secrets are masked unless explicitly revealed through the separately enabled secret tool.' });
|
||||
}
|
||||
if (!sessions.has(sessionKey)) return error(message.id, -32000, 'Session not initialized');
|
||||
sessions.set(sessionKey, Date.now());
|
||||
if (message.method.startsWith('notifications/')) return null;
|
||||
if (message.id === undefined) return error(null, -32600, 'Request id required');
|
||||
if (message.method === 'ping') return response(message.id, {});
|
||||
if (message.method === 'tools/list') return response(message.id, { tools: adapter.list().filter(tool => tool.requiredScopes.every(scope => getCapabilities().includes(scope))).map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, annotations: tool.annotations })) });
|
||||
if (message.method === 'resources/list') return response(message.id, { resources: getCapabilities().includes('read') ? [{ uri: 'mhu://installation/state', name: 'Uploader state', mimeType: 'application/json' }] : [] });
|
||||
if (message.method === 'resources/read' && message.params?.uri === 'mhu://installation/state') {
|
||||
try {
|
||||
const value = await adapter.call('mhu_app_state', {}, { ...context, scopes: getCapabilities() });
|
||||
return response(message.id, { contents: [{ uri: 'mhu://installation/state', mimeType: 'application/json', text: JSON.stringify(value) }] });
|
||||
} catch { return error(message.id, -32000, 'Resource unavailable'); }
|
||||
}
|
||||
if (message.method === 'prompts/list') return response(message.id, { prompts: [] });
|
||||
if (message.method === 'prompts/get') return error(message.id, -32602, 'Unknown prompt');
|
||||
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 });
|
||||
} catch (failure) {
|
||||
const code = failure instanceof McpAccessError ? failure.code : 'ACTION_FAILED';
|
||||
return response(message.id, { content: [{ type: 'text', text: code }], isError: true });
|
||||
}
|
||||
}
|
||||
return { handle, closeSession: (principalId, sessionId) => sessions.delete(principalId + ':' + sessionId), reset: () => sessions.clear() };
|
||||
}
|
||||
|
||||
module.exports = { createMcpProtocol };
|
||||
@@ -0,0 +1,94 @@
|
||||
const { fetch } = require('undici');
|
||||
|
||||
async function readBoundedJson(response, maximum = 2 * 1024 * 1024) {
|
||||
let length = 0;
|
||||
const chunks = [];
|
||||
try {
|
||||
for await (const chunk of response.body) {
|
||||
length += chunk.length;
|
||||
if (length > maximum) throw new Error('RELAY_RESPONSE_TOO_LARGE');
|
||||
chunks.push(Buffer.from(chunk));
|
||||
}
|
||||
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
} catch { await response.body?.cancel().catch(() => {}); throw new Error('INVALID_RELAY_RESPONSE'); }
|
||||
}
|
||||
|
||||
class RelayAgent {
|
||||
constructor({ credentials, endpoint, status, request = fetch }) {
|
||||
this.credentials = credentials;
|
||||
this.endpoint = endpoint;
|
||||
this.status = status;
|
||||
this.request = request;
|
||||
this.abort = new AbortController();
|
||||
this.active = new Map();
|
||||
this.seen = new Set();
|
||||
this.task = null;
|
||||
}
|
||||
start() { if (!this.task) this.task = this.loop(); }
|
||||
async stop() { this.abort.abort(); for (const entry of this.active.values()) entry.abort.abort(); await this.task; }
|
||||
async wait(ms) {
|
||||
if (this.abort.signal.aborted) return;
|
||||
await new Promise(resolve => {
|
||||
const done = () => { clearTimeout(timer); this.abort.signal.removeEventListener('abort', done); resolve(); };
|
||||
const timer = setTimeout(done, ms);
|
||||
this.abort.signal.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
}
|
||||
async loop() {
|
||||
let failures = 0;
|
||||
while (!this.abort.signal.aborted) {
|
||||
try {
|
||||
const response = await this.request(`${this.credentials.relayUrl}/v1/agent/${this.credentials.installationId}/poll`, {
|
||||
headers: { Authorization: `Bearer ${this.credentials.agentToken}` }, redirect: 'error', signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(30000)])
|
||||
});
|
||||
if ([401, 403].includes(response.status)) { await response.body?.cancel(); this.status('blocked', this.active.size); return; }
|
||||
if (!response.ok) { await response.body?.cancel(); throw new Error('RELAY_POLL_FAILED'); }
|
||||
const payload = await readBoundedJson(response);
|
||||
if (!Array.isArray(payload.commands) || payload.commands.length > 32 || !Array.isArray(payload.cancellations) || payload.cancellations.length > 1024 || !Array.isArray(payload.closedSessions) || payload.closedSessions.length > 1024) throw new Error('INVALID_RELAY_RESPONSE');
|
||||
failures = 0;
|
||||
this.status('online', this.active.size);
|
||||
for (const id of payload.cancellations) this.active.get(id)?.abort.abort();
|
||||
for (const id of payload.closedSessions) {
|
||||
for (const entry of this.active.values()) if (entry.sessionId === id) entry.abort.abort();
|
||||
this.endpoint.closeSession(id);
|
||||
}
|
||||
for (const command of payload.commands) this.dispatch(command);
|
||||
} catch {
|
||||
if (this.abort.signal.aborted) break;
|
||||
this.status('offline', this.active.size);
|
||||
await this.wait(Math.min(15000, 500 * 2 ** Math.min(failures++, 5)));
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatch(command) {
|
||||
const validId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
|
||||
if (this.abort.signal.aborted || !command || !validId(command.requestId) || !validId(command.sessionId)
|
||||
|| !command.message || command.message.jsonrpc !== '2.0' || command.principal?.installationId !== this.credentials.installationId
|
||||
|| command.principal.id !== `${this.credentials.installationId}:client` || command.principal.role !== 'client'
|
||||
|| !Number.isFinite(command.deadline) || command.deadline <= Date.now() || command.deadline > Date.now() + 121000
|
||||
|| Buffer.byteLength(JSON.stringify(command.message)) > 1024 * 1024
|
||||
|| this.active.size >= 32 || this.seen.has(command.requestId)) return;
|
||||
this.seen.add(command.requestId);
|
||||
if (this.seen.size > 4096) this.seen.delete(this.seen.values().next().value);
|
||||
const abort = new AbortController();
|
||||
const signal = AbortSignal.any([abort.signal, this.abort.signal, AbortSignal.timeout(Math.min(120000, command.deadline - Date.now()))]);
|
||||
this.active.set(command.requestId, { abort, sessionId: command.sessionId });
|
||||
this.status('online', this.active.size);
|
||||
void (async () => {
|
||||
let response = null;
|
||||
try { response = await this.endpoint.handle(command, signal); }
|
||||
catch { if (Object.hasOwn(command.message, 'id')) response = { jsonrpc: '2.0', id: command.message.id, error: { code: -32000, message: 'MCP request failed or was cancelled' } }; }
|
||||
try {
|
||||
if (this.abort.signal.aborted) return;
|
||||
const result = await this.request(`${this.credentials.relayUrl}/v1/agent/${this.credentials.installationId}/results`, {
|
||||
method: 'POST', headers: { Authorization: `Bearer ${this.credentials.agentToken}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: command.requestId, response }), redirect: 'error', signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(15000)])
|
||||
});
|
||||
await result.body?.cancel();
|
||||
} catch { }
|
||||
finally { this.active.delete(command.requestId); this.status(this.abort.signal.aborted ? 'offline' : 'online', this.active.size); }
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { RelayAgent, readBoundedJson };
|
||||
@@ -0,0 +1,59 @@
|
||||
const { McpAccessError } = require('./mcp-access');
|
||||
|
||||
function createMcpSanitizer(loadConfig) {
|
||||
return value => {
|
||||
const config = loadConfig();
|
||||
if (!config || typeof config !== 'object') throw new McpAccessError('REDACTION_UNAVAILABLE');
|
||||
const secrets = new Set();
|
||||
const sensitive = /password|passwd|api.?key|token|cookie|sess(?:ion)?(?:id|_id)?|secret|authorization|credential|connectionCode|webhookUrl|^key$/i;
|
||||
const gather = node => {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
for (const [key, item] of Object.entries(node)) {
|
||||
if (sensitive.test(key) && typeof item === 'string' && item) secrets.add(item);
|
||||
else if (item && typeof item === 'object') gather(item);
|
||||
}
|
||||
};
|
||||
gather(config);
|
||||
const values = [...secrets].sort((a, b) => b.length - a.length);
|
||||
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;
|
||||
}
|
||||
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)]));
|
||||
return node;
|
||||
};
|
||||
return visit(value);
|
||||
};
|
||||
}
|
||||
|
||||
function createMcpConfirmation({ dialog, getWindow, getName, sanitize, now = Date.now, ttl = 60000 }) {
|
||||
return async ({ tool, args, context }) => {
|
||||
if (context.signal?.aborted) return false;
|
||||
const until = Math.min(context.deadline, now() + ttl);
|
||||
if (until <= now()) return false;
|
||||
const abort = new AbortController();
|
||||
const cancel = () => abort.abort();
|
||||
context.signal?.addEventListener('abort', cancel, { once: true });
|
||||
const timer = setTimeout(cancel, until - now());
|
||||
try {
|
||||
const details = JSON.stringify(sanitize(args), null, 2).slice(0, 3000);
|
||||
const options = {
|
||||
type: 'warning', title: 'MCP – Lokale Freigabe / Local approval',
|
||||
message: `${getName()}\n${tool}`,
|
||||
detail: `Diese konkrete Fernaktion ausführen? / Run this exact remote action?\n${details}\n\nDie Freigabe läuft nach spätestens 60 Sekunden ab. / Approval expires within 60 seconds.`,
|
||||
buttons: ['Abbrechen / Cancel', 'Einmal erlauben / Allow once'], defaultId: 0, cancelId: 0, noLink: true, signal: abort.signal
|
||||
};
|
||||
const window = getWindow();
|
||||
const result = window && !window.isDestroyed() ? await dialog.showMessageBox(window, options) : await dialog.showMessageBox(options);
|
||||
return result.response === 1 && !abort.signal.aborted && now() < until;
|
||||
} catch { return false; }
|
||||
finally { clearTimeout(timer); context.signal?.removeEventListener('abort', cancel); }
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createMcpSanitizer, createMcpConfirmation };
|
||||
@@ -0,0 +1,161 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { fetch } = require('undici');
|
||||
const { McpStore, CAPABILITIES } = require('./mcp-store');
|
||||
const { RelayAgent } = require('./mcp-relay');
|
||||
const { createMcpProtocol } = require('./mcp-protocol');
|
||||
const { createMcpToolAdapter } = require('./mcp-tools');
|
||||
const { createMcpSanitizer, createMcpConfirmation } = require('./mcp-security');
|
||||
const { McpAccessError, validateInput } = require('./mcp-access');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
class McpService {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
this.store = new McpStore(options);
|
||||
this.request = options.request || fetch;
|
||||
this.active = false;
|
||||
this.connection = 'disabled';
|
||||
this.agent = null;
|
||||
this.lastContact = null;
|
||||
this.activeRequests = 0;
|
||||
this.tail = Promise.resolve();
|
||||
this.ready = false;
|
||||
this.retryTimer = null;
|
||||
this.protocol = null;
|
||||
this.generation = 0;
|
||||
}
|
||||
capabilities() { return this.active ? this.store.value.capabilities : []; }
|
||||
state() {
|
||||
const { name, capabilities, grants, enabled, identity, revocations } = this.store.value;
|
||||
return { name, capabilities, grants, enabled: this.active && enabled, connection: this.connection, installationId: identity?.installationId || null,
|
||||
lastContact: this.lastContact, activeRequests: this.activeRequests, pendingRevocations: revocations.length, available: this.ready };
|
||||
}
|
||||
publish() { this.options.onStatus?.(this.state()); }
|
||||
async start() {
|
||||
try {
|
||||
await this.store.load();
|
||||
this.ready = true;
|
||||
await this.retryRevocations();
|
||||
if (this.store.value.enabled && this.store.value.identity) this.connect();
|
||||
this.retryTimer = setInterval(() => { void this.serialize(() => this.retryRevocations()).catch(() => {}); }, 30000);
|
||||
this.retryTimer.unref?.();
|
||||
} catch { this.connection = 'storage-error'; }
|
||||
this.publish();
|
||||
}
|
||||
serialize(action) { const task = this.tail.then(action); this.tail = task.catch(() => {}); return task; }
|
||||
connect() {
|
||||
const identity = this.store.value.identity;
|
||||
const sanitize = createMcpSanitizer(this.options.loadConfig);
|
||||
const confirmation = createMcpConfirmation({ dialog: this.options.dialog, getWindow: this.options.getWindow, getName: () => this.store.value.name, sanitize });
|
||||
const adapter = createMcpToolAdapter({ handlers: this.options.handlers, getCapabilities: () => this.capabilities(), sanitize,
|
||||
authorizeConfirmation: confirmation, requiresConfirmation: this.options.requiresConfirmation,
|
||||
audit: event => this.options.audit?.({ ...event, installationId: identity.installationId }) });
|
||||
this.protocol = createMcpProtocol({ adapter, version: this.options.version, getCapabilities: () => this.capabilities() });
|
||||
this.active = true;
|
||||
this.connection = 'connecting';
|
||||
const protocol = this.protocol;
|
||||
this.agent = new RelayAgent({ credentials: identity, request: this.request,
|
||||
endpoint: { handle: (command, signal) => protocol.handle(command.message, { principalId: command.principal.id, sessionId: command.sessionId, requestId: command.requestId, deadline: command.deadline, signal }),
|
||||
closeSession: id => protocol.closeSession(`${identity.installationId}:client`, id) },
|
||||
status: (state, count) => { if (!this.active) return; this.connection = state; this.activeRequests = count; if (state === 'online') this.lastContact = new Date().toISOString(); this.publish(); }
|
||||
});
|
||||
this.agent.start();
|
||||
this.publish();
|
||||
}
|
||||
async disconnect() {
|
||||
this.active = false;
|
||||
this.protocol?.reset();
|
||||
this.connection = 'disabled';
|
||||
const agent = this.agent; this.agent = null;
|
||||
this.publish();
|
||||
await agent?.stop();
|
||||
}
|
||||
async retryRevocations() {
|
||||
const pending = this.store.value.revocations;
|
||||
if (!pending.length) return;
|
||||
const retained = [];
|
||||
for (const identity of pending) {
|
||||
try {
|
||||
const response = await this.request(`${identity.relayUrl}/v1/agent/${identity.installationId}`, { method: 'DELETE', headers: { Authorization: `Bearer ${identity.agentToken}` }, redirect: 'error', signal: AbortSignal.timeout(5000) });
|
||||
await response.body?.cancel();
|
||||
if (!response.ok && ![401, 404].includes(response.status)) retained.push(identity);
|
||||
} catch { retained.push(identity); }
|
||||
}
|
||||
if (retained.length !== pending.length) await this.store.save({ ...this.store.value, revocations: retained });
|
||||
}
|
||||
configure(args) {
|
||||
validateInput(args, { type: 'object', additionalProperties: false, required: ['enabled', 'name', 'capabilities'], properties: {
|
||||
enabled: { type: 'boolean' }, name: { type: 'string', minLength: 1, maxLength: 100 }, capabilities: { type: 'array', maxItems: 4, items: { type: 'string', enum: CAPABILITIES } }
|
||||
} });
|
||||
if (!args.name.trim()) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
this.active = false;
|
||||
this.agent?.abort.abort();
|
||||
const generation = ++this.generation;
|
||||
const disabled = this.store.markDisabled().then(() => null, error => error);
|
||||
return this.serialize(async () => {
|
||||
const markerError = await disabled;
|
||||
if (markerError) throw markerError;
|
||||
if (generation !== this.generation) return this.state();
|
||||
if (!this.ready) throw new McpAccessError('ACCESS_STORE_UNAVAILABLE');
|
||||
await this.disconnect();
|
||||
let current = this.store.value;
|
||||
const capabilities = [...new Set(args.capabilities)];
|
||||
if (!args.enabled) {
|
||||
if (current.identity && current.revocations.length >= 32) throw new McpAccessError('REVOCATIONS_PENDING');
|
||||
await this.store.save({ ...current, enabled: false, identity: null, revocations: [...current.revocations, ...current.identity ? [current.identity] : []], name: args.name.trim(), capabilities });
|
||||
await this.retryRevocations(); this.publish(); return this.state();
|
||||
}
|
||||
if (!capabilities.length) throw new McpAccessError('CAPABILITY_REQUIRED');
|
||||
if (current.revocations.length >= 32) throw new McpAccessError('REVOCATIONS_PENDING');
|
||||
const identity = current.identity || this.store.newIdentity();
|
||||
await this.store.save({ ...current, identity, enabled: false, name: args.name.trim(), capabilities });
|
||||
if (!current.identity) {
|
||||
try {
|
||||
const response = await this.request(`${identity.relayUrl}/v1/installations`, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ installationId: identity.installationId, kind: 'uploader', name: args.name.trim(), agentToken: identity.agentToken, clientToken: identity.clientToken }), redirect: 'error', signal: AbortSignal.timeout(15000) });
|
||||
await response.body?.cancel();
|
||||
if (response.status !== 201) throw new Error('enrollment');
|
||||
} catch {
|
||||
await this.store.save({ ...this.store.value, identity: null, revocations: [...this.store.value.revocations, identity] });
|
||||
this.connection = 'enrollment-error'; this.publish(); throw new McpAccessError('ENROLLMENT_FAILED');
|
||||
}
|
||||
}
|
||||
await this.store.save({ ...this.store.value, enabled: true });
|
||||
if (generation !== this.generation) return this.state();
|
||||
await this.store.clearDisabled();
|
||||
this.connect(); return this.state();
|
||||
});
|
||||
}
|
||||
async rotate() {
|
||||
const current = this.store.value;
|
||||
const args = { enabled: true, name: current.name, capabilities: current.capabilities };
|
||||
await this.configure({ ...args, enabled: false });
|
||||
return this.configure(args);
|
||||
}
|
||||
addGrant(directory) {
|
||||
return this.serialize(async () => {
|
||||
if (!this.ready || this.store.value.grants.length >= 30) throw new McpAccessError('GRANT_LIMIT');
|
||||
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 }] });
|
||||
this.publish(); return this.state();
|
||||
});
|
||||
}
|
||||
updateGrant(id, remove, readOnly = true) {
|
||||
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 }]);
|
||||
await this.store.save({ ...this.store.value, grants });
|
||||
if (wasActive && generation === this.generation) { await this.store.clearDisabled(); this.connect(); }
|
||||
this.publish(); return this.state();
|
||||
});
|
||||
}
|
||||
async stop() { clearInterval(this.retryTimer); await this.disconnect(); }
|
||||
}
|
||||
|
||||
module.exports = { McpService };
|
||||
@@ -0,0 +1,82 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { randomUUID, randomBytes } = require('node:crypto');
|
||||
const { McpAccessError } = require('./mcp-access');
|
||||
|
||||
const RELAY_URL = 'https://downloader.24-music.de/mcp-relay';
|
||||
const CAPABILITIES = ['read', 'control', 'files', 'secrets'];
|
||||
|
||||
class McpStore {
|
||||
constructor({ directory, encrypt, decrypt }) {
|
||||
this.file = path.join(directory, 'mcp-access.json');
|
||||
this.disabledMarker = path.join(directory, 'mcp-disabled.marker');
|
||||
this.encrypt = encrypt;
|
||||
this.decrypt = decrypt;
|
||||
this.value = { version: 1, enabled: false, name: 'Multi-Hoster-Uploader', capabilities: ['read'], grants: [], identity: null, revocations: [] };
|
||||
this.tail = Promise.resolve();
|
||||
}
|
||||
async load() {
|
||||
const disabled = await fs.stat(this.disabledMarker).then(() => true, error => { if (error.code === 'ENOENT') return false; throw new McpAccessError('ACCESS_STORE_UNAVAILABLE'); });
|
||||
try {
|
||||
const text = await fs.readFile(this.file, 'utf8');
|
||||
if (text.length > 100000) throw new Error('size');
|
||||
const value = JSON.parse(text);
|
||||
if (value.version !== 1 || !Array.isArray(value.capabilities) || !Array.isArray(value.grants) || !Array.isArray(value.revocations)) throw new Error('format');
|
||||
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');
|
||||
const decode = identity => {
|
||||
if (!identity) return null;
|
||||
if (identity.relayUrl !== RELAY_URL || !/^[a-f0-9-]{36}$/.test(identity.installationId)) throw new Error('identity');
|
||||
if (!identity.agentToken?.startsWith('enc:v1:') || !identity.clientToken?.startsWith('enc:v1:')) throw new Error('encryption');
|
||||
const decoded = { ...identity, agentToken: this.decrypt(identity.agentToken), clientToken: this.decrypt(identity.clientToken) };
|
||||
if (![decoded.agentToken, decoded.clientToken].every(token => /^[A-Za-z0-9_-]{43}$/.test(token)) || decoded.agentToken === decoded.clientToken) throw new Error('credentials');
|
||||
return decoded;
|
||||
};
|
||||
this.value = { ...value, capabilities: value.capabilities.filter(item => CAPABILITIES.includes(item)), identity: decode(value.identity), revocations: value.revocations.map(decode) };
|
||||
if (disabled) {
|
||||
this.value.enabled = false;
|
||||
if (this.value.identity) {
|
||||
if (!this.value.revocations.some(identity => identity.installationId === this.value.identity.installationId)) this.value.revocations.push(this.value.identity);
|
||||
this.value.identity = null;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw new McpAccessError('ACCESS_STORE_UNAVAILABLE');
|
||||
}
|
||||
return this.value;
|
||||
}
|
||||
async markDisabled() {
|
||||
await fs.mkdir(path.dirname(this.file), { recursive: true });
|
||||
const handle = await fs.open(this.disabledMarker, 'w', 0o600);
|
||||
try { await handle.writeFile('disabled\n'); await handle.sync(); }
|
||||
finally { await handle.close(); }
|
||||
}
|
||||
async clearDisabled() { await fs.unlink(this.disabledMarker).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
||||
async save(next) {
|
||||
const encode = identity => identity ? { ...identity, agentToken: this.encrypt(identity.agentToken), clientToken: this.encrypt(identity.clientToken) } : null;
|
||||
const disk = { ...next, identity: encode(next.identity), revocations: next.revocations.map(encode) };
|
||||
for (const identity of [disk.identity, ...disk.revocations].filter(Boolean)) {
|
||||
if (!identity.agentToken.startsWith('enc:v1:') || !identity.clientToken.startsWith('enc:v1:')) throw new McpAccessError('ENCRYPTION_UNAVAILABLE');
|
||||
}
|
||||
const task = this.tail.then(async () => {
|
||||
await fs.mkdir(path.dirname(this.file), { recursive: true });
|
||||
const temporary = this.file + '.' + randomUUID() + '.tmp';
|
||||
try { await fs.writeFile(temporary, JSON.stringify(disk), { mode: 0o600, flag: 'wx' }); await fs.rename(temporary, this.file); }
|
||||
finally { await fs.unlink(temporary).catch(() => {}); }
|
||||
this.value = next;
|
||||
});
|
||||
this.tail = task.catch(() => {});
|
||||
return task;
|
||||
}
|
||||
newIdentity() { return { relayUrl: RELAY_URL, installationId: randomUUID(), agentToken: randomBytes(32).toString('base64url'), clientToken: randomBytes(32).toString('base64url') }; }
|
||||
code() {
|
||||
const value = this.value;
|
||||
if (!value.enabled || !value.identity) throw new McpAccessError('NOT_ENABLED');
|
||||
const identity = value.identity;
|
||||
return 'media-mcp:v1:' + Buffer.from(JSON.stringify({ v: 1, url: `${identity.relayUrl}/mcp/${identity.installationId}`, installationId: identity.installationId, kind: 'uploader', name: value.name, token: identity.clientToken })).toString('base64url');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { McpStore, RELAY_URL, CAPABILITIES };
|
||||
@@ -0,0 +1,148 @@
|
||||
const { McpAccessError, validateInput, actionDigest } = require('./mcp-access');
|
||||
|
||||
const text = (maxLength = 4096) => ({ type: 'string', maxLength });
|
||||
const id = { type: 'string', minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_.:-]+$' };
|
||||
const integer = (minimum, maximum) => ({ type: 'integer', minimum, maximum });
|
||||
const boolean = { type: 'boolean' };
|
||||
const enumeration = values => ({ type: 'string', enum: values });
|
||||
const array = (items, maxItems = 100) => ({ type: 'array', items, maxItems });
|
||||
const object = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
||||
const page = { offset: integer(0, 1000000), limit: integer(1, 200) };
|
||||
const account = { accountId: id };
|
||||
const jobIds = { jobIds: array(id, 1000) };
|
||||
const hoster = enumeration(['doodstream.com', 'voe.sx', 'vidmoly.me', 'byse.sx', 'clouddrop.cc']);
|
||||
const retention = enumeration(['all', '7d', '14d', '30d', '90d', '1000', '100']);
|
||||
const file = { rootId: id, relativePath: text() };
|
||||
|
||||
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_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', {}, []],
|
||||
['queue_resume', 'Resume the shared upload and automation pause.', 'control', {}, []],
|
||||
['queue_retry', 'Retry selected failed jobs.', 'control', jobIds, ['jobIds']],
|
||||
['queue_cancel', 'Cancel selected running or queued jobs.', 'control', jobIds, ['jobIds']],
|
||||
['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_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']],
|
||||
['accounts_otp', 'Submit a one-time code for a selected account.', 'accounts', { ...account, code: { type: 'string', minLength: 4, maxLength: 12, pattern: '^[A-Za-z0-9]+$' } }, ['accountId', 'code']],
|
||||
['accounts_request_otp', 'Explicitly request a new one-time code for an account.', 'accounts', account, ['accountId']],
|
||||
['accounts_priority', 'Move an account in the hoster fallback order.', 'accounts', { ...account, direction: enumeration(['up', 'down']) }, ['accountId', 'direction']],
|
||||
['accounts_remove', 'Remove one configured account.', 'accounts', account, ['accountId'], true],
|
||||
['accounts_reset_failure', 'Reset the temporary failure state of one account.', 'accounts', account, ['accountId']],
|
||||
['settings_get', 'Read settings with secrets masked.', 'read', {}, []],
|
||||
['settings_update', 'Update explicitly supported application settings.', 'settings', {
|
||||
language: enumeration(['de', 'en']), globalMaxSpeedKbs: integer(0, 100000000), parallelUploadCount: integer(0, 100),
|
||||
autoRetryRounds: integer(0, 5), autoRetryDelayMin: integer(1, 1440), autoHealthCheckEnabled: boolean,
|
||||
resumeQueueOnLaunch: boolean, autoStartRestoredQueue: boolean, removeFromQueueOnDone: boolean,
|
||||
logMode: enumeration(['single', 'daily', 'session']), logVerbose: boolean
|
||||
}, []],
|
||||
['hoster_settings_update', 'Update one hoster transfer configuration.', 'settings', {
|
||||
hoster, retries: integer(0, 20), parallelCount: integer(1, 100), maxSpeedKbs: integer(0, 100000000),
|
||||
restartBelowKbs: integer(0, 100000000), timeIntervalSec: integer(0, 86400), maxSizeMb: integer(0, 100000000),
|
||||
rotateAccounts: boolean, logToFile: boolean
|
||||
}, ['hoster']],
|
||||
['automation_status', 'Read folder-monitor and automatic retry state.', 'read', {}, []],
|
||||
['automation_update', 'Configure monitoring for an explicitly granted directory.', 'settings', {
|
||||
rootId: id, recursive: boolean, includeExisting: boolean, filterMode: enumeration(['include', 'exclude']),
|
||||
extensions: text(200), delaySec: integer(0, 3600), autoStart: boolean, hosters: array(hoster, 5),
|
||||
queueLimitJobs: integer(0, 100000), reconcileIntervalMinutes: integer(1, 1440)
|
||||
}, ['rootId'], true],
|
||||
['automation_start', 'Start configured folder monitoring.', 'control', {}, []],
|
||||
['automation_stop', 'Stop folder monitoring without removing queued jobs.', 'control', {}, []],
|
||||
['automation_scan', 'Run a read-only folder monitoring test scan.', 'read', {}, []],
|
||||
['automation_reconcile', 'Reconcile the monitored directory with the queue.', 'control', {}, []],
|
||||
['history_list', 'Read a bounded page of upload history.', 'read', page, []],
|
||||
['history_prune', 'Apply a retention policy to upload history.', 'control', { retention }, ['retention'], true],
|
||||
['history_clear', 'Clear upload history.', 'control', {}, [], true],
|
||||
['diagnostics_summary', 'Read filtered application diagnostics.', 'diagnostics', {}, []],
|
||||
['logs_list', 'List the application-managed diagnostic logs.', 'diagnostics', {}, []],
|
||||
['logs_read', 'Read a bounded, secret-filtered application log tail.', 'diagnostics', {
|
||||
name: enumeration(['debug', 'fileuploader', 'uploadAudit', 'accountRotation', 'crash']),
|
||||
tailKb: integer(1, 256), backup: integer(0, 2), grep: text(200)
|
||||
}, ['name']],
|
||||
['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_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']],
|
||||
['cloud_backfill', 'Queue missing entries from the current local upload log.', 'control', {}, []],
|
||||
['backup_list', 'List online backups with keys masked.', 'read', {}, []],
|
||||
['backup_create', 'Create an encrypted settings-only online backup.', 'backup', { retention: enumeration(['1d', '3d', '7d', '31d', 'forever']) }, ['retention']],
|
||||
['backup_delete', 'Delete a selected managed online backup.', 'backup', { id }, ['id'], true],
|
||||
['backup_restore', 'Restore settings from an explicitly supplied online key.', 'backup', { key: text(200) }, ['key'], true],
|
||||
['update_check', 'Check for an application update without installing it.', 'read', {}, []],
|
||||
['update_install', 'Install an available application update.', 'lifecycle', {}, [], true],
|
||||
['app_restart', 'Restart the application after persisting its state.', 'lifecycle', {}, [], true],
|
||||
['app_quit', 'Close the application after persisting its state.', 'lifecycle', {}, [], true],
|
||||
['secrets_read', 'Explicitly reveal credentials for one account; disabled by default.', 'secrets.read', account, ['accountId']]
|
||||
];
|
||||
|
||||
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) }
|
||||
})));
|
||||
|
||||
function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit = () => {}, getCapabilities, requiresConfirmation = () => false }) {
|
||||
const byName = new Map(MCP_TOOLS.map(tool => [tool.name, tool]));
|
||||
const active = new Map();
|
||||
const recent = new Map();
|
||||
const mutations = { tail: Promise.resolve() };
|
||||
async function call(name, args, context) {
|
||||
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'));
|
||||
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');
|
||||
const digest = actionDigest(name, args);
|
||||
const requestKey = `${context.principalId}:${context.requestId}`;
|
||||
if (typeof context.principalId !== 'string' || !/^[A-Za-z0-9_:-]{1,128}$/.test(context.principalId)
|
||||
|| typeof context.requestId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(context.requestId)) throw new McpAccessError('INVALID_REQUEST');
|
||||
for (const [key, entry] of recent) if (entry.until < Date.now()) recent.delete(key);
|
||||
const previous = active.get(requestKey) || recent.get(requestKey);
|
||||
if (previous) {
|
||||
if (previous.digest !== digest) throw new McpAccessError('REQUEST_CONFLICT');
|
||||
return previous.promise;
|
||||
}
|
||||
if (active.size >= 32 || recent.size >= 512) throw new McpAccessError('TOO_MANY_REQUESTS');
|
||||
const execute = async () => {
|
||||
const startedAt = Date.now();
|
||||
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
if (!permitted()) throw new McpAccessError('SCOPE_DENIED');
|
||||
if ((tool.destructive || requiresConfirmation(name, args)) && (!authorizeConfirmation || !await authorizeConfirmation({ tool: name, digest, args, context }))) throw new McpAccessError('CONFIRMATION_REQUIRED');
|
||||
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
if (!permitted()) throw new McpAccessError('SCOPE_DENIED');
|
||||
audit({ tool: name, event: 'started', requestId: context.requestId, durationMs: 0 });
|
||||
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');
|
||||
audit({ tool: name, event: 'completed', requestId: context.requestId, durationMs: Date.now() - startedAt });
|
||||
return result;
|
||||
};
|
||||
const promise = tool.annotations.readOnlyHint ? execute() : mutations.tail.then(execute);
|
||||
if (!tool.annotations.readOnlyHint) mutations.tail = promise.catch(() => {});
|
||||
active.set(requestKey, { digest, promise });
|
||||
try { return await promise; }
|
||||
catch (error) { audit({ tool: name, event: 'failed', requestId: context.requestId, code: error instanceof McpAccessError ? error.code : 'ACTION_FAILED' }); throw error instanceof McpAccessError ? error : new McpAccessError('ACTION_FAILED'); }
|
||||
finally { active.delete(requestKey); recent.set(requestKey, { digest, promise, until: Date.now() + 120000 }); }
|
||||
}
|
||||
return { list: () => MCP_TOOLS.filter(tool => typeof handlers[tool.name] === 'function'), call };
|
||||
}
|
||||
|
||||
module.exports = { MCP_TOOLS, createMcpToolAdapter };
|
||||
@@ -46,6 +46,17 @@ const { createAgent } = require('./lib/diagnostics-agent');
|
||||
const { buildSessionReport, buildSessionReportCsv } = require('./lib/session-report');
|
||||
const { inspectImportEntries, inspectReadableImportPath } = require('./lib/import-preflight');
|
||||
const { normalizeAutomationSettings, automationCompletionKey, createAutomationCompletionWriter, isPathWithinAutomationFolder, normalizeAutomationCompletion } = require('./lib/automation-control');
|
||||
const { McpService } = require('./lib/mcp-service');
|
||||
const { createMcpApp } = require('./lib/mcp-app');
|
||||
const { McpAccessError } = require('./lib/mcp-access');
|
||||
const mcpLocalHandlers = new Map();
|
||||
const mcpRawHandle = ipcMain.handle.bind(ipcMain);
|
||||
ipcMain.handle = (channel, handler) => {
|
||||
mcpLocalHandlers.set(channel, handler);
|
||||
return mcpRawHandle(channel, handler);
|
||||
};
|
||||
let mcpService = null;
|
||||
const mcpRendererRequests = new Map();
|
||||
|
||||
const _eventLoopDelay = monitorEventLoopDelay({ resolution: 10 });
|
||||
_eventLoopDelay.enable();
|
||||
@@ -1919,6 +1930,7 @@ app.whenReady().then(async () => {
|
||||
createTray();
|
||||
startupDiagnostics.write('window-load-dispatched');
|
||||
void cloudLogSync.start();
|
||||
void startMcpService();
|
||||
|
||||
// Minimize to tray instead of taskbar
|
||||
mainWindow.on('minimize', () => {
|
||||
@@ -1984,6 +1996,7 @@ app.on('before-quit', (event) => {
|
||||
app.on('will-quit', () => {
|
||||
if (quitTeardownStarted) return;
|
||||
quitTeardownStarted = true;
|
||||
void mcpService?.stop();
|
||||
folderMonitorRendererReadyGeneration = null;
|
||||
if (updateCheckInterval) clearInterval(updateCheckInterval);
|
||||
updateCheckInterval = null;
|
||||
@@ -3356,11 +3369,12 @@ ipcMain.handle('online-backup:delete-managed', (event, id) => (
|
||||
})
|
||||
));
|
||||
|
||||
ipcMain.handle('online-backup:restore', async (_event, key) => {
|
||||
ipcMain.handle('online-backup:restore', async (event, key) => {
|
||||
try {
|
||||
const normalized = String(key || '').trim();
|
||||
if (normalized.length > 128) throw new Error('Online-Sicherungsschlüssel ist ungültig');
|
||||
const payload = await downloadOnlineBackup(normalized);
|
||||
assertMcpRequestLive(event);
|
||||
return { ok: true, ...await applyImportedSettings(payload.settings) };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error.message || String(error) };
|
||||
@@ -3504,14 +3518,20 @@ ipcMain.handle('app:check-updates', async (_event, options) => {
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('app:install-update', async () => {
|
||||
ipcMain.handle('app:install-update', async event => {
|
||||
if (updatePreparationPromise || preparedUpdate || updateQuitPending) {
|
||||
return { started: false, error: 'Ein Update wird bereits vorbereitet' };
|
||||
}
|
||||
updatePreparationPromise = (async () => {
|
||||
const prepared = await prepareUpdate((progress) => {
|
||||
const cancel = () => abortUpdate();
|
||||
event?.mcpContext?.signal?.addEventListener('abort', cancel, { once: true });
|
||||
let prepared;
|
||||
try {
|
||||
prepared = await prepareUpdate((progress) => {
|
||||
safeSend('app:update-progress', progress);
|
||||
});
|
||||
} finally { event?.mcpContext?.signal?.removeEventListener('abort', cancel); }
|
||||
assertMcpRequestLive(event);
|
||||
if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed() || !closeHandshakeReady) {
|
||||
throw new Error('Die Anwendung ist noch nicht bereit, das Update sicher zu installieren');
|
||||
}
|
||||
@@ -4044,6 +4064,114 @@ function _diagAgentInfo() {
|
||||
};
|
||||
}
|
||||
|
||||
function createAppCollectors() {
|
||||
return createCollectors({
|
||||
loadConfig: () => configStore.load(), loadHistory: () => configStore.loadHistory(), getAllLogPaths,
|
||||
support: { sanitizeConfig, collectSecretValues, redactLogText, valueScrub, collectFile, REDACTED },
|
||||
stats, appInfo: _diagAppInfo, systemInfo: _diagSystemInfo, agentInfo: _diagAgentInfo
|
||||
});
|
||||
}
|
||||
|
||||
function assertMcpRequestLive(event) {
|
||||
if (event?.mcpContext && (event.mcpContext.signal?.aborted || Date.now() >= event.mcpContext.deadline || !mcpService?.active)) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
}
|
||||
|
||||
function mcpRendererAction(action, args, context) {
|
||||
if (!mainWindow || mainWindow.isDestroyed() || context.signal?.aborted) return Promise.reject(new McpAccessError('RENDERER_UNAVAILABLE'));
|
||||
const id = require('node:crypto').randomUUID();
|
||||
return new Promise((resolve, reject) => {
|
||||
const finish = (error, result) => {
|
||||
clearTimeout(timer);
|
||||
context.signal?.removeEventListener('abort', cancel);
|
||||
mcpRendererRequests.delete(id);
|
||||
if (error) reject(error); else resolve(result);
|
||||
};
|
||||
const cancel = () => { safeSend('mcp:cancel', id); finish(new McpAccessError('REQUEST_EXPIRED')); };
|
||||
const timer = setTimeout(cancel, Math.max(1, Math.min(120000, context.deadline - Date.now())));
|
||||
context.signal?.addEventListener('abort', cancel, { once: true });
|
||||
mcpRendererRequests.set(id, { finish, context });
|
||||
safeSend('mcp:action', { id, action, args, deadline: context.deadline });
|
||||
});
|
||||
}
|
||||
|
||||
async function startMcpService() {
|
||||
const secretStore = require('./lib/secret-store');
|
||||
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']);
|
||||
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);
|
||||
};
|
||||
const invokeGuarded = async (context, channel, ...args) => {
|
||||
if (!allowed.has(channel) || !mcpLocalHandlers.has(channel) || !mainWindow || mainWindow.isDestroyed()) throw new McpAccessError('ACTION_UNAVAILABLE');
|
||||
const event = { sender: mainWindow.webContents, senderFrame: mainWindow.webContents.mainFrame, mcpContext: context };
|
||||
assertMcpRequestLive(event);
|
||||
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 });
|
||||
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),
|
||||
requiresConfirmation: name => {
|
||||
if (!['mhu_queue_start', 'mhu_queue_retry', 'mhu_queue_resume', 'mhu_automation_start', 'mhu_automation_reconcile'].includes(name)) return false;
|
||||
const settings = configStore.load().globalSettings;
|
||||
return settings.deleteSourceAfterSuccessfulUpload === true || !['nothing', undefined, null].includes(settings.shutdownAfterFinish);
|
||||
},
|
||||
audit: event => logInfo(`mcp ${JSON.stringify({ time: new Date().toISOString(), ...event })}`)
|
||||
});
|
||||
await mcpService.start();
|
||||
}
|
||||
|
||||
ipcMain.handle('mcp:status', event => isTrustedOnlineBackupIpcEvent(event) ? mcpService?.state() || { available: false, connection: 'starting' } : null);
|
||||
ipcMain.handle('mcp:check', (event, id) => {
|
||||
const pending = mcpRendererRequests.get(id);
|
||||
return !!(isTrustedOnlineBackupIpcEvent(event) && closeHandshakeReady && pending && !pending.context.signal?.aborted && Date.now() < pending.context.deadline && mcpService?.active);
|
||||
});
|
||||
ipcMain.on('mcp:reply', (event, payload) => {
|
||||
if (!isTrustedOnlineBackupIpcEvent(event) || typeof payload?.id !== 'string') return;
|
||||
const pending = mcpRendererRequests.get(payload.id);
|
||||
if (!pending) return;
|
||||
pending.finish(payload.ok === true ? null : new McpAccessError('ACTION_FAILED'), payload.result);
|
||||
});
|
||||
ipcMain.handle('mcp:configure', async (event, args) => {
|
||||
if (!isTrustedOnlineBackupIpcEvent(event) || !mcpService) throw new Error('MCP_ACCESS_DENIED');
|
||||
if (args?.enabled && (args.capabilities?.includes('secrets') || !mcpService.active)) {
|
||||
const result = await dialog.showMessageBox(mainWindow, { type: 'warning', title: 'MCP-Zugriff / MCP access', message: 'MCP-Zugriff mit diesen Berechtigungen aktivieren? / Enable MCP with these capabilities?',
|
||||
detail: String(args.capabilities?.join(', ') || '').slice(0, 100), buttons: ['Abbrechen / Cancel', 'Aktivieren / Enable'], defaultId: 0, cancelId: 0, noLink: true });
|
||||
if (result.response !== 1) return mcpService.state();
|
||||
}
|
||||
return mcpService.configure(args);
|
||||
});
|
||||
ipcMain.handle('mcp:rotate', async event => {
|
||||
if (!isTrustedOnlineBackupIpcEvent(event) || !mcpService) throw new Error('MCP_ACCESS_DENIED');
|
||||
const result = await dialog.showMessageBox(mainWindow, { type: 'warning', message: shellText('MCP-Zugang erneuern? Der bisherige Code wird ungültig.', 'Rotate MCP access? The previous code becomes invalid.'), buttons: ['Abbrechen / Cancel', 'Erneuern / Rotate'], defaultId: 0, cancelId: 0, noLink: true });
|
||||
return result.response === 1 ? mcpService.rotate() : mcpService.state();
|
||||
});
|
||||
ipcMain.handle('mcp:copy-code', event => {
|
||||
if (!isTrustedOnlineBackupIpcEvent(event) || !mcpService?.active) throw new Error('MCP_ACCESS_DENIED');
|
||||
clipboard.writeText(mcpService.store.code());
|
||||
return true;
|
||||
});
|
||||
ipcMain.handle('mcp:add-grant', async event => {
|
||||
if (!isTrustedOnlineBackupIpcEvent(event) || !mcpService) throw new Error('MCP_ACCESS_DENIED');
|
||||
const chosen = await dialog.showOpenDialog(mainWindow, { properties: ['openDirectory'] });
|
||||
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');
|
||||
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);
|
||||
});
|
||||
|
||||
function _buildDiagnosticHandler() {
|
||||
const collectors = createCollectors({
|
||||
loadConfig: () => configStore.load(),
|
||||
|
||||
+11
@@ -25,6 +25,17 @@ ipcRenderer.on('folder-monitor:renderer-generation', (_event, generation) => {
|
||||
});
|
||||
|
||||
contextBridge.exposeInMainWorld('api', {
|
||||
mcpStatus: () => ipcRenderer.invoke('mcp:status'),
|
||||
mcpConfigure: args => ipcRenderer.invoke('mcp:configure', args),
|
||||
mcpRotate: () => ipcRenderer.invoke('mcp:rotate'),
|
||||
mcpCopyCode: () => ipcRenderer.invoke('mcp:copy-code'),
|
||||
mcpAddGrant: () => ipcRenderer.invoke('mcp:add-grant'),
|
||||
mcpUpdateGrant: args => ipcRenderer.invoke('mcp:update-grant', args),
|
||||
mcpCheck: id => ipcRenderer.invoke('mcp:check', id),
|
||||
mcpReply: reply => ipcRenderer.send('mcp:reply', reply),
|
||||
onMcpAction: callback => ipcRenderer.on('mcp:action', (_event, value) => callback(value)),
|
||||
onMcpCancel: callback => ipcRenderer.on('mcp:cancel', (_event, value) => callback(value)),
|
||||
onMcpStatus: callback => ipcRenderer.on('mcp:status', (_event, value) => callback(value)),
|
||||
reportStartupPhase,
|
||||
// Config
|
||||
getConfig: () => ipcRenderer.invoke('get-config'),
|
||||
|
||||
+12
-5
@@ -2415,6 +2415,7 @@ function restoreQueueStateFromConfig() {
|
||||
sourceCleanupCompletedHosters: Array.isArray(job.sourceCleanupCompletedHosters) ? [...job.sourceCleanupCompletedHosters] : [],
|
||||
sourceCleanupFingerprint: job.sourceCleanupFingerprint || null,
|
||||
automationAdmission: job.automationAdmission === true,
|
||||
mcpAdmission: job.mcpAdmission === true,
|
||||
sourceFileIdentity: job.sourceFileIdentity,
|
||||
automationMtimeMs: Number.isFinite(Number(job.automationMtimeMs)) ? Number(job.automationMtimeMs) : null,
|
||||
automationSize: Number.isFinite(Number(job.automationSize)) ? Number(job.automationSize) : null,
|
||||
@@ -2447,7 +2448,7 @@ function buildPersistedQueueState() {
|
||||
const selectedFileMap = new Map(selectedFiles.map(file => [file.path, file]));
|
||||
|
||||
for (const job of persistableJobs) {
|
||||
if (job.file && job.automationAdmission !== true && !selectedFileMap.has(job.file)) {
|
||||
if (job.file && job.automationAdmission !== true && job.mcpAdmission !== true && !selectedFileMap.has(job.file)) {
|
||||
selectedFileMap.set(job.file, {
|
||||
path: job.file,
|
||||
name: job.fileName,
|
||||
@@ -2502,6 +2503,7 @@ function buildPersistedQueueState() {
|
||||
sourceCleanupCompletedHosters: Array.isArray(job.sourceCleanupCompletedHosters) ? [...job.sourceCleanupCompletedHosters] : [],
|
||||
sourceCleanupFingerprint: job.sourceCleanupFingerprint || null,
|
||||
automationAdmission: job.automationAdmission === true,
|
||||
mcpAdmission: job.mcpAdmission === true,
|
||||
sourceFileIdentity: job.sourceFileIdentity,
|
||||
automationMtimeMs: Number.isFinite(Number(job.automationMtimeMs)) ? Number(job.automationMtimeMs) : null,
|
||||
automationSize: Number.isFinite(Number(job.automationSize)) ? Number(job.automationSize) : null,
|
||||
@@ -2898,7 +2900,7 @@ function suppressPreviewKeysStillSelected(keys) {
|
||||
// Build preview jobs from selected files x selected hosters (before upload starts)
|
||||
function buildQueuePreview() {
|
||||
const hosters = getSelectedHosters();
|
||||
queueJobs = queueJobs.filter(j => j.status !== 'preview' || j.automationAdmission === true);
|
||||
queueJobs = queueJobs.filter(j => j.status !== 'preview' || j.automationAdmission === true || j.mcpAdmission === true);
|
||||
|
||||
if (hosters.length > 0) {
|
||||
const existingKeys = new Set();
|
||||
@@ -4885,8 +4887,9 @@ function _markSkippedJobs(result) {
|
||||
renderQueueTable();
|
||||
}
|
||||
|
||||
async function startSelectedUpload(explicitJobs) {
|
||||
async function startSelectedUpload(explicitJobs, options = {}) {
|
||||
if (await isAutomationPaused()) return { ok: false, error: 'Automatik ist pausiert' };
|
||||
if (options.guard) await options.guard();
|
||||
const scopedJobs = Array.isArray(explicitJobs) ? explicitJobs : _getVisibleSelectedQueueJobs();
|
||||
if (uploading) {
|
||||
_hydrateMissingJobSizes();
|
||||
@@ -4906,6 +4909,7 @@ async function startSelectedUpload(explicitJobs) {
|
||||
renderQueueTable();
|
||||
let result = null;
|
||||
try {
|
||||
if (options.guard) await options.guard();
|
||||
result = await submitAddJobsRequest(addRequest);
|
||||
} catch (err) {
|
||||
restoreSourceCleanupStates(cleanupPreparation.rollbackStates);
|
||||
@@ -4995,6 +4999,7 @@ async function startSelectedUpload(explicitJobs) {
|
||||
jobs: jobsToStart.map(serializeUploadJob),
|
||||
sourceCleanupGroups: cleanupPreparation.groups
|
||||
};
|
||||
if (options.guard) await options.guard();
|
||||
const result = await window.api.startUpload(uploadPayload);
|
||||
if (result && result.error) {
|
||||
restoreSourceCleanupStates(cleanupPreparation.rollbackStates);
|
||||
@@ -5705,7 +5710,7 @@ function moveSelectedJobs(direction) {
|
||||
function syncSelectedFilesFromQueue() {
|
||||
const fileMap = new Map();
|
||||
queueJobs
|
||||
.filter((job) => job.automationAdmission !== true && !['done', 'skipped', 'aborted'].includes(job.status))
|
||||
.filter((job) => job.automationAdmission !== true && job.mcpAdmission !== true && !['done', 'skipped', 'aborted'].includes(job.status))
|
||||
.forEach((job) => {
|
||||
if (!job.file || fileMap.has(job.file)) return;
|
||||
fileMap.set(job.file, {
|
||||
@@ -6564,7 +6569,7 @@ function renderSettings() {
|
||||
{ id: 'automatik', label: 'Automatik', group: 'base', icon: 'clock', description: 'Wiederholungen und Ordner', search: 'automatisch automation automatic retry wiederholen ordner folder monitor überwachen watch dateierweiterungen extensions unterordner subfolders duplikate duplicates' },
|
||||
{ id: 'benachrichtigungen', label: 'Benachrichtigungen', group: 'connections', icon: 'bell', description: 'Meldungen und Webhooks', search: 'benachrichtigungen notifications webhook discord meldung message ping erwähnung mention batch fertig completed' },
|
||||
{ id: 'logs', label: 'Logs & Support', group: 'management', icon: 'files', description: 'Protokolle und Supportpakete', search: 'log logs protokoll logging debug verbose diagnose diagnostics support paket package datei file ordner folder' },
|
||||
{ id: 'remote', label: 'Fernsteuerung', group: 'connections', icon: 'monitor', description: 'Server und Verbindungen', search: 'remote control fernsteuerung server input port api token verbindung connection client' },
|
||||
{ id: 'remote', label: 'Fernsteuerung', group: 'connections', icon: 'monitor', description: 'Server und Verbindungen', search: 'remote control fernsteuerung mcp server input port api token verbindung connection client' },
|
||||
{ id: 'diagnose', label: 'Diagnose-Zugriff', group: 'connections', icon: 'shield', description: 'Zugriff und Freigaben', search: 'diagnose diagnostics access zugriff lesen read allowlist netzwerk network lokal local verbindung connection code support' },
|
||||
{ id: 'backup', label: 'Backup & Übertragen', group: 'management', icon: 'archive', description: 'Sichern, importieren und exportieren', search: 'backup transfer sichern export import online schlüssel key einstellungen settings accounts übertragen' }
|
||||
];
|
||||
@@ -6948,6 +6953,7 @@ function renderSettings() {
|
||||
|
||||
pages.remote.innerHTML = `
|
||||
${pageHeader('Fernsteuerung', 'Upload-Funktionen über einen verbundenen Client steuern.')}
|
||||
${window.renderMcpSettings ? window.renderMcpSettings() : ''}
|
||||
<div class="settings-section-label">Server <span class="panel-status${remoteSettings.enabled ? ' active' : ''}" id="remoteStatusBadge">${remoteSettings.enabled ? 'Aktiv' : 'Inaktiv'}</span></div>
|
||||
<div class="settings-grid-mini">
|
||||
<div class="settings-row checkbox-row">
|
||||
@@ -7318,6 +7324,7 @@ function renderSettings() {
|
||||
|
||||
_renderLogPathsList(document.getElementById('logPathsList'));
|
||||
void refreshCloudLogStatus();
|
||||
void window.bindMcpSettings?.();
|
||||
document.getElementById('cloudLogActivateBtn')?.addEventListener('click', () => configureCloudLog(true));
|
||||
document.getElementById('cloudLogDisableBtn')?.addEventListener('click', () => configureCloudLog(false));
|
||||
document.getElementById('cloudLogBackfillBtn')?.addEventListener('click', backfillCloudLog);
|
||||
|
||||
@@ -4,6 +4,32 @@
|
||||
if (root) root.I18n = api;
|
||||
})(typeof window !== 'undefined' ? window : globalThis, function () {
|
||||
const pairs = [
|
||||
['Strukturierter Fernzugriff über HTTPS. Nur bei laufender Anwendung; keine Portfreigabe erforderlich. Berechtigungen werden ausschließlich hier vergeben.', 'Structured remote access over HTTPS. Available while the app is running; no inbound port required. Permissions can only be granted here.'],
|
||||
['Installationsname', 'Installation name'],
|
||||
['Lokale Berechtigungen', 'Local permissions'],
|
||||
['Lesen und Diagnose', 'Read and diagnostics'],
|
||||
['App steuern', 'Control app'],
|
||||
['Freigegebene Ordner', 'Granted directories'],
|
||||
['Zugangsdaten explizit auslesen', 'Explicitly reveal secrets'],
|
||||
['Speichern und aktivieren', 'Save and enable'],
|
||||
['Deaktivieren und widerrufen', 'Disable and revoke'],
|
||||
['Verbindungscode kopieren', 'Copy connection code'],
|
||||
['Zugang erneuern', 'Rotate access'],
|
||||
['Letzter Kontakt', 'Last contact'],
|
||||
['Ausstehende Widerrufe', 'Pending revocations'],
|
||||
['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.'],
|
||||
['Ordner freigeben', 'Grant directory'],
|
||||
['Schreibzugriff', 'Write access'],
|
||||
['MCP-Aktion fehlgeschlagen. Verbindung und lokale Berechtigungen prüfen.', 'MCP action failed. Check connection and local permissions.'],
|
||||
['Verbindungscode kopiert.', 'Connection code copied.'],
|
||||
['Verbindung wird hergestellt', 'Connecting'],
|
||||
['Nicht verbunden – erneuter Versuch', 'Offline – retrying'],
|
||||
['Zugang abgelehnt', 'Access rejected'],
|
||||
['Zugangsdaten nicht lesbar', 'Credentials unavailable'],
|
||||
['Registrierung fehlgeschlagen', 'Enrollment failed'],
|
||||
['Verbunden', 'Connected'],
|
||||
['Deaktiviert', 'Disabled'],
|
||||
['Wird geladen', 'Loading'],
|
||||
['Konfiguration', 'Configuration'],
|
||||
['Grundlagen', 'Basics'],
|
||||
['Verwaltung', 'Management'],
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
<meta name="theme-color" content="#0f0f0f">
|
||||
<title>Multi-Hoster-Uploader</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="mcp.css">
|
||||
</head>
|
||||
<body>
|
||||
<svg class="icon-sprite" aria-hidden="true">
|
||||
@@ -740,6 +741,7 @@
|
||||
<script src="auto-resume.js"></script>
|
||||
<script src="queue-stats.js"></script>
|
||||
<script src="i18n.js"></script>
|
||||
<script src="mcp.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,14 @@
|
||||
.mcp-controls { margin-bottom: 28px; font-size: 13px; }
|
||||
.mcp-controls p { line-height: 1.6; overflow-wrap: anywhere; }
|
||||
.mcp-controls .settings-row input { min-width: 0; flex: 1; }
|
||||
.mcp-permissions { display: flex; flex-wrap: wrap; gap: 16px 24px; border: 1px solid var(--border, #424242); border-radius: 6px; padding: 16px; margin: 16px 0; }
|
||||
.mcp-permissions label, .mcp-grant label { display: flex; align-items: center; gap: 6px; }
|
||||
.mcp-actions { display: flex; gap: 8px; flex-wrap: wrap; margin: 14px 0; }
|
||||
.mcp-actions .btn { white-space: normal; }
|
||||
.mcp-status { display: flex; flex-wrap: wrap; gap: 18px 32px; border: 1px solid var(--border, #424242); border-radius: 6px; padding: 16px; }
|
||||
.mcp-status dt { margin-bottom: 8px; }
|
||||
.mcp-status dd { margin: 0; font-weight: 600; }
|
||||
.mcp-state { padding: 5px 8px; border: 1px solid var(--border, #555); border-radius: 5px; }
|
||||
.mcp-state.connected { color: #a2edc1; background: #193829; border-color: #46735b; }
|
||||
.mcp-grant { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border, #424242); }
|
||||
.mcp-grant > span { flex: 1 1 220px; overflow-wrap: anywhere; }
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
(() => {
|
||||
const cancelled = new Set();
|
||||
const text = (de, _en) => de;
|
||||
const page = (items, args) => {
|
||||
const offset = args.offset || 0;
|
||||
const limit = args.limit || 100;
|
||||
return { total: items.length, offset, items: items.slice(offset, offset + limit), nextOffset: offset + limit < items.length ? offset + limit : null };
|
||||
};
|
||||
const refresh = async () => {
|
||||
config = await window.api.getConfig();
|
||||
hosterSettings = config.hosterSettings || {};
|
||||
ensureAccountStatusEntries(); syncSelectedUploadHosters(); renderAccounts(); renderHosterSummary();
|
||||
};
|
||||
const redraw = () => { rebuildJobIndex(); _queueStatsCache = null; syncSelectedFilesFromQueue(); renderQueueTable(); updateUploadView({ rebuildPreview: false }); updateStatusBar(); };
|
||||
const select = args => {
|
||||
const ids = new Set(args.jobIds || []);
|
||||
const jobs = queueJobs.filter(job => ids.has(job.id));
|
||||
if (jobs.length !== ids.size) throw new Error('JOB_NOT_FOUND');
|
||||
return jobs;
|
||||
};
|
||||
const handlers = {
|
||||
state: async () => ({ uploading, queueCount: queueJobs.length, selectedFileCount: selectedFiles.length, counts: queueJobs.reduce((out, job) => { out[job.status] = (out[job.status] || 0) + 1; return out; }, {}) }),
|
||||
refresh,
|
||||
'account-results': async args => { for (const row of args.results) { if (findAccountById(row.accountId)) accountStatuses[row.accountId] = { status: row.status, message: row.message, storage: row.storage, checkedAt: row.checkedAt || new Date().toISOString() }; } renderAccounts(); return { updated: args.results.length }; },
|
||||
'queue-list': async args => page(queueJobs.filter(job => !args.status || job.status === args.status).map(job => ({ id: job.id, fileName: job.fileName, hoster: job.hoster, status: job.status, bytesUploaded: job.bytesUploaded, bytesTotal: job.bytesTotal, speedKbs: job.speedKbs, error: job.error, result: job.result, attempt: job.attempt })), args),
|
||||
'queue-add': async (args, guard) => {
|
||||
const inspection = await window.api.inspectImportFiles(args.paths, existingImportPaths());
|
||||
await guard();
|
||||
const jobs = inspection.accepted.flatMap(file => args.hosters.filter(hoster => window.ImportPreflight.isImportPairEligible(file, hoster, hosterSettings)).map(hoster => ({ ...createAutomationPreviewJob(file, hoster), automationAdmission: false, mcpAdmission: true })));
|
||||
clearDedupKeysForPaths(new Set(inspection.accepted.map(file => file.path)));
|
||||
queueJobs.push(...jobs); redraw(); await persistQueueStateNow();
|
||||
return { addedJobs: jobs.length, rejectedFiles: inspection.duplicateCount + inspection.unavailableCount };
|
||||
},
|
||||
'queue-start': async (args, guard) => {
|
||||
const jobs = args.jobIds?.length ? select(args) : queueJobs.filter(job => isStartableQueueStatus(job.status));
|
||||
await guard();
|
||||
if (!jobs.length) return { started: false, reason: 'NO_ELIGIBLE_JOBS' };
|
||||
return await startSelectedUpload(jobs, { guard }) || { started: false };
|
||||
},
|
||||
'queue-retry': async (args, guard) => {
|
||||
const jobs = select(args);
|
||||
if (jobs.some(job => !['error', 'aborted', 'skipped'].includes(job.status))) throw new Error('JOB_NOT_RETRYABLE');
|
||||
await guard();
|
||||
for (const job of jobs) {
|
||||
if (job.uploadId) { _jobIndexByUploadId.delete(job.uploadId); _deletedJobIds.add(job.uploadId); }
|
||||
Object.assign(job, { status: 'preview', error: null, result: null, bytesUploaded: 0, progress: 0, uploadId: null, mcpAdmission: true });
|
||||
}
|
||||
redraw(); await persistQueueStateNow(); await guard();
|
||||
return await startSelectedUpload(jobs, { guard }) || { started: false };
|
||||
},
|
||||
'queue-cancel': async (args, guard) => {
|
||||
const jobs = select(args);
|
||||
await guard();
|
||||
await window.api.cancelSelectedJobs(jobs.map(job => job.id));
|
||||
for (const job of jobs) if (!['done', 'error', 'skipped'].includes(job.status)) Object.assign(job, { status: 'aborted', speedKbs: 0, error: 'Abgebrochen' });
|
||||
redraw(); await persistQueueStateNow(); return { cancelled: jobs.length };
|
||||
},
|
||||
'queue-remove': async (args, guard) => {
|
||||
const jobs = select(args);
|
||||
if (jobs.some(job => !['preview', 'done', 'error', 'skipped', 'aborted'].includes(job.status))) throw new Error('CANCEL_ACTIVE_JOBS_FIRST');
|
||||
await guard();
|
||||
const ids = new Set(jobs.map(job => job.id));
|
||||
jobs.forEach(job => removeJobFromIndex(job)); queueJobs = queueJobs.filter(job => !ids.has(job.id));
|
||||
redraw(); await persistQueueStateNow(); return { removed: jobs.length };
|
||||
},
|
||||
'queue-clear': async (args, guard) => handlers['queue-remove']({ jobIds: queueJobs.filter(job => ['preview', 'done', 'error', 'skipped', 'aborted'].includes(job.status)).map(job => job.id) }, guard)
|
||||
};
|
||||
window.api.onMcpCancel(id => { cancelled.add(id); if (cancelled.size > 128) cancelled.delete(cancelled.values().next().value); });
|
||||
window.api.onMcpAction(async request => {
|
||||
const guard = async () => { if (cancelled.has(request.id) || Date.now() >= request.deadline || !await window.api.mcpCheck(request.id)) throw new Error('REQUEST_EXPIRED'); };
|
||||
try {
|
||||
if (!Object.hasOwn(handlers, request.action)) throw new Error('ACTION_UNAVAILABLE');
|
||||
await guard();
|
||||
const result = await handlers[request.action](request.args, guard);
|
||||
window.api.mcpReply({ id: request.id, ok: true, result });
|
||||
} catch { window.api.mcpReply({ id: request.id, ok: false }); }
|
||||
finally { cancelled.delete(request.id); }
|
||||
});
|
||||
let current = null;
|
||||
const renderStatus = state => {
|
||||
current = state;
|
||||
const area = document.getElementById('mcpControls');
|
||||
if (!area) return;
|
||||
const states = {
|
||||
disabled: text('Deaktiviert', 'Disabled'), connecting: text('Verbindung wird hergestellt', 'Connecting'), online: text('Verbunden', 'Connected'), offline: text('Nicht verbunden – erneuter Versuch', 'Offline – retrying'),
|
||||
blocked: text('Zugang abgelehnt', 'Access rejected'), 'storage-error': text('Zugangsdaten nicht lesbar', 'Credentials unavailable'), 'enrollment-error': text('Registrierung fehlgeschlagen', 'Enrollment failed'), starting: text('Wird geladen', 'Loading')
|
||||
};
|
||||
area.querySelector('[data-mcp-status]').textContent = states[state.connection] || state.connection;
|
||||
area.querySelector('[data-mcp-status]').className = `mcp-state ${state.connection === 'online' ? 'connected' : ''}`;
|
||||
area.querySelector('[data-mcp-contact]').textContent = state.lastContact ? new Date(state.lastContact).toLocaleString(getUiLocale()) : '—';
|
||||
area.querySelector('[data-mcp-pending]').textContent = Number(state.pendingRevocations || 0).toLocaleString(getUiLocale());
|
||||
for (const action of ['copy', 'rotate']) area.querySelector(`[data-mcp-action="${action}"]`).disabled = !state.enabled;
|
||||
area.querySelector('[data-mcp-action="disable"]').disabled = !state.enabled && !state.installationId;
|
||||
area.querySelector('[data-mcp-grants]').replaceChildren(...(state.grants || []).map(grant => {
|
||||
const row = document.createElement('div'); row.className = 'mcp-grant';
|
||||
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 }));
|
||||
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;
|
||||
}));
|
||||
};
|
||||
const act = async action => {
|
||||
try { const state = await action(); if (state && typeof state === 'object') renderStatus(state); }
|
||||
catch { showCopyToast(text('MCP-Aktion fehlgeschlagen. Verbindung und lokale Berechtigungen prüfen.', 'MCP action failed. Check connection and local permissions.'), 6000, 'error'); if (current) renderStatus(current); }
|
||||
};
|
||||
window.renderMcpSettings = () => `<section id="mcpControls" class="mcp-controls">
|
||||
<div class="settings-section-label">MCP</div>
|
||||
<p>${text('Strukturierter Fernzugriff über HTTPS. Nur bei laufender Anwendung; keine Portfreigabe erforderlich. Berechtigungen werden ausschließlich hier vergeben.', 'Structured remote access over HTTPS. Available while the app is running; no inbound port required. Permissions can only be granted here.')}</p>
|
||||
<div class="settings-row"><label for="mcpName">${text('Installationsname', 'Installation name')}</label><input id="mcpName" class="key-input" maxlength="100"></div>
|
||||
<fieldset class="mcp-permissions"><legend>${text('Lokale Berechtigungen', 'Local permissions')}</legend>${[['read','Lesen und Diagnose','Read and diagnostics'],['control','App steuern','Control app'],['files','Freigegebene Ordner','Granted directories'],['secrets','Zugangsdaten explizit auslesen','Explicitly reveal secrets']].map(([value,de,en])=>`<label><input type="checkbox" value="${value}"> ${text(de,en)}</label>`).join('')}</fieldset>
|
||||
<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>
|
||||
<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>
|
||||
</section>`;
|
||||
window.bindMcpSettings = async () => {
|
||||
const area = document.getElementById('mcpControls'); if (!area) return;
|
||||
const state = await window.api.mcpStatus(); if (!state) return;
|
||||
renderStatus(state);
|
||||
area.querySelector('#mcpName').value = state.name || 'Multi-Hoster-Uploader';
|
||||
for (const input of area.querySelectorAll('.mcp-permissions input')) input.checked = state.capabilities?.includes(input.value) === true;
|
||||
const configuration = enabled => ({ enabled, name: area.querySelector('#mcpName').value.trim(), capabilities: [...area.querySelectorAll('.mcp-permissions input:checked')].map(input => input.value) });
|
||||
area.querySelector('[data-mcp-action="enable"]').onclick = () => act(() => window.api.mcpConfigure(configuration(true)));
|
||||
area.querySelector('[data-mcp-action="disable"]').onclick = () => act(() => window.api.mcpConfigure(configuration(false)));
|
||||
area.querySelector('[data-mcp-action="rotate"]').onclick = () => act(() => window.api.mcpRotate());
|
||||
area.querySelector('[data-mcp-action="copy"]').onclick = () => act(async () => { await window.api.mcpCopyCode(); showCopyToast(text('Verbindungscode kopiert.', 'Connection code copied.')); });
|
||||
area.querySelector('[data-mcp-action="grant"]').onclick = () => act(() => window.api.mcpAddGrant());
|
||||
};
|
||||
window.api.onMcpStatus(renderStatus);
|
||||
})();
|
||||
@@ -38,6 +38,15 @@ const sourceFiles = [
|
||||
'lib/log-mode.js',
|
||||
'lib/log-policy.js',
|
||||
'lib/log-rotation.js',
|
||||
'lib/mcp-access.js',
|
||||
'lib/mcp-app.js',
|
||||
'lib/mcp-files.js',
|
||||
'lib/mcp-protocol.js',
|
||||
'lib/mcp-relay.js',
|
||||
'lib/mcp-security.js',
|
||||
'lib/mcp-service.js',
|
||||
'lib/mcp-store.js',
|
||||
'lib/mcp-tools.js',
|
||||
'lib/online-backup.js',
|
||||
'lib/online-backup-keyring.js',
|
||||
'lib/online-backup-manager.js',
|
||||
@@ -86,6 +95,8 @@ const sourceFiles = [
|
||||
'renderer/drop-target.html',
|
||||
'renderer/i18n.js',
|
||||
'renderer/index.html',
|
||||
'renderer/mcp.js',
|
||||
'renderer/mcp.css',
|
||||
'renderer/history-status.js',
|
||||
'renderer/queue-stats.js',
|
||||
'renderer/styles.css',
|
||||
|
||||
Reference in new issue
Block a user