Add opt-in MCP access with local authorization and revocable identities
CI / verify (push) Canceled after 0s

This commit is contained in:
Sucukdeluxe committed 2026-10-15 16:57:30 +02:00
1 parent febe654189
commit 93e0196dbe
20 files changed
+1246 -8

No files matched your search

+71
View File
@@ -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
View File
@@ -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 };
+64
View File
@@ -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 };
+48
View File
@@ -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 };
+94
View File
@@ -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 };
+59
View File
@@ -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 };
+161
View File
@@ -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 };
+82
View File
@@ -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 };
+148
View File
@@ -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 };