This commit is contained in:
1 parent
d5022d2d59
commit
cd2394dd22
19 files changed
+1757
-32
No files matched your search
@@ -53,6 +53,8 @@ async function resolveGrantedFile(grants, rootId, relativePath, options = {}) {
|
||||
if (typeof relativePath !== 'string' || relativePath.includes('\0') || path.isAbsolute(relativePath)
|
||||
|| /(?:^|[\\/])\.\.(?:[\\/]|$)|:/.test(relativePath)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
const realRoot = await fs.realpath(grant.path);
|
||||
const expectedRoot = path.resolve(grant.path);
|
||||
if (process.platform === 'win32' ? realRoot.toLowerCase() !== expectedRoot.toLowerCase() : realRoot !== expectedRoot) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
const target = path.resolve(realRoot, relativePath || '.');
|
||||
if (!within(realRoot, target)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
const realTarget = await fs.realpath(target);
|
||||
|
||||
+19
-3
@@ -1,6 +1,10 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { McpAccessError, resolveGrantedFile } = require('./mcp-access');
|
||||
const { createMcpFiles } = require('./mcp-files');
|
||||
const { createMcpTransfers } = require('./mcp-transfers');
|
||||
const { createMcpDiagnostics } = require('./mcp-diagnostics');
|
||||
const { createMcpSanitizer } = require('./mcp-security');
|
||||
const { redactLogText, collectSecretValues } = require('./support-bundle');
|
||||
|
||||
function page(items, args) {
|
||||
const offset = args.offset || 0;
|
||||
@@ -8,7 +12,10 @@ function page(items, args) {
|
||||
return { total: items.length, offset, items: items.slice(offset, offset + limit), nextOffset: offset + limit < items.length ? offset + limit : null };
|
||||
}
|
||||
|
||||
function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, ...args) => invoke(channel, ...args), renderer, collectors, getGrants, trashFile, canWrite }) {
|
||||
function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, ...args) => invoke(channel, ...args), renderer, collectors, getGrants, trashFile, canWrite,
|
||||
getCapabilities, getProtectedPaths, getInstallationId, getDiagnosticSources, getRuntimeDiagnostics = () => null }) {
|
||||
const transfers = createMcpTransfers({ getGrants, getCapabilities, getProtectedPaths, getInstallationId });
|
||||
const sanitize = createMcpSanitizer(loadConfig);
|
||||
const guard = context => {
|
||||
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
};
|
||||
@@ -45,11 +52,14 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
|
||||
await refresh(context);
|
||||
return { saved: true };
|
||||
};
|
||||
return {
|
||||
const handlers = {
|
||||
...createMcpFiles({ getGrants, trashFile }),
|
||||
...transfers.handlers,
|
||||
...createMcpDiagnostics({ getSources: getDiagnosticSources, redact: text => sanitize(redactLogText(text, collectSecretValues(loadConfig()))) }),
|
||||
mhu_app_info: () => invoke('get-app-info'),
|
||||
mhu_app_state: async (args, context) => ({ ...(await renderer('state', {}, context)), automation: await invoke('automation:get-status') }),
|
||||
mhu_queue_list: (args, context) => renderer('queue-list', args, context),
|
||||
mhu_queue_job_log: async args => page(await invoke('get-job-log', args.jobId), args),
|
||||
mhu_queue_add: async (args, context) => {
|
||||
if (!args.paths.length || !args.hosters.length) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
const files = [];
|
||||
@@ -65,6 +75,10 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
|
||||
mhu_queue_remove: (args, context) => renderer('queue-remove', args, context),
|
||||
mhu_queue_clear: (args, context) => renderer('queue-clear', args, context),
|
||||
mhu_accounts_list: args => page(accounts().filter(account => !args.hoster || args.hoster === account.hoster), args),
|
||||
mhu_accounts_runtime: async args => {
|
||||
const state = await invoke('get-session-failed-account-states');
|
||||
return { revision: state.revision, now: state.now, ...page(state.accounts.filter(account => !args.hoster || account.hoster === args.hoster), args) };
|
||||
},
|
||||
mhu_accounts_check: (args, context) => { if (!args.accountIds.length) throw new McpAccessError('INVALID_ARGUMENTS'); return check(args.accountIds, context); },
|
||||
mhu_accounts_add: async (args, context) => {
|
||||
canWrite(); guard(context);
|
||||
@@ -128,7 +142,7 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
|
||||
mhu_history_prune: args => invoke('prune-history', { retention: args.retention, dryRun: false }),
|
||||
mhu_history_summary: args => collectors.getHistory({ limit: args.limit || 20 }),
|
||||
mhu_history_clear: () => invoke('clear-history'),
|
||||
mhu_diagnostics_summary: () => ({ system: collectors.getSystemInfo(), health: collectors.getHealth(), rotation: collectors.getRotationState(), server: collectors.serverHealth({ errorLimit: 20 }) }),
|
||||
mhu_diagnostics_summary: () => ({ system: collectors.getSystemInfo(), health: collectors.getHealth(), rotation: collectors.getRotationState(), server: collectors.serverHealth({ errorLimit: 20 }), runtime: getRuntimeDiagnostics() }),
|
||||
mhu_app_events: args => collectors.getAppEvents(args),
|
||||
mhu_errors: args => collectors.listErrors(args),
|
||||
mhu_logs_list: () => collectors.listLogs(),
|
||||
@@ -146,6 +160,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
|
||||
mhu_app_quit: () => invoke('app:quit'),
|
||||
mhu_secrets_read: args => { const { password, apiKey } = find(args.accountId); return { accountId: args.accountId, password: password || '', apiKey: apiKey || '' }; }
|
||||
};
|
||||
Object.defineProperty(handlers, 'dispose', { value: () => transfers.dispose() });
|
||||
return handlers;
|
||||
}
|
||||
|
||||
module.exports = { createMcpApp, page };
|
||||
@@ -0,0 +1,71 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { constants } = require('node:fs');
|
||||
const { createHash } = require('node:crypto');
|
||||
const { McpAccessError } = require('./mcp-access');
|
||||
|
||||
function createMcpDiagnostics({ getSources = () => [], redact }) {
|
||||
let reading = 0;
|
||||
const guard = context => { if (context.signal?.aborted || !Number.isFinite(context.deadline) || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED'); };
|
||||
const sources = () => getSources().slice(0, 64).map(source => ({ ...source, id: createHash('sha256').update(source.path).digest('hex').slice(0, 24) }));
|
||||
const resolve = async source => {
|
||||
const actual = await fs.realpath(source.path);
|
||||
const parent = await fs.realpath(source.directory);
|
||||
const expectedParent = path.resolve(source.directory);
|
||||
if (process.platform === 'win32' ? parent.toLowerCase() !== expectedParent.toLowerCase() : parent !== expectedParent) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
if (actual !== path.join(parent, path.basename(source.path))) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
const stat = await fs.lstat(actual);
|
||||
if (!stat.isFile() || stat.nlink !== 1) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
return { actual, stat };
|
||||
};
|
||||
return {
|
||||
mhu_diagnostics_files: async (args, context) => {
|
||||
const files = [];
|
||||
for (const source of sources()) {
|
||||
guard(context);
|
||||
try { const { stat } = await resolve(source); files.push({ id: source.id, name: source.label, sizeBytes: stat.size, modifiedAt: stat.mtime.toISOString() }); }
|
||||
catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) files.push({ id: source.id, name: source.label, unavailable: true }); }
|
||||
}
|
||||
const offset = args.offset || 0; const limit = args.limit || 50;
|
||||
return { total: files.length, offset, files: files.slice(offset, offset + limit), nextOffset: offset + limit < files.length ? offset + limit : null };
|
||||
},
|
||||
mhu_diagnostics_read: async (args, context) => {
|
||||
guard(context);
|
||||
const source = sources().find(item => item.id === args.artifactId);
|
||||
if (!source) throw new McpAccessError('DIAGNOSTIC_NOT_FOUND');
|
||||
if (reading >= 4) throw new McpAccessError('TOO_MANY_REQUESTS');
|
||||
reading++;
|
||||
let file;
|
||||
try {
|
||||
const { actual, stat } = await resolve(source);
|
||||
if (stat.size > 8 * 1024 * 1024) throw new McpAccessError('FILE_TOO_LARGE');
|
||||
file = await fs.open(actual, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
||||
const initial = await file.stat();
|
||||
if (initial.ino !== stat.ino || initial.dev !== stat.dev || initial.size !== stat.size || !initial.isFile()) throw new McpAccessError('FILE_CHANGED');
|
||||
const buffer = Buffer.alloc(initial.size);
|
||||
let offset = 0;
|
||||
while (offset < buffer.length) {
|
||||
guard(context);
|
||||
const { bytesRead } = await file.read(buffer, offset, Math.min(256 * 1024, buffer.length - offset), offset);
|
||||
if (!bytesRead) throw new McpAccessError('FILE_CHANGED');
|
||||
offset += bytesRead;
|
||||
}
|
||||
const final = await file.stat();
|
||||
if (final.size !== initial.size || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) throw new McpAccessError('FILE_CHANGED');
|
||||
const current = await resolve(source);
|
||||
if (current.stat.ino !== initial.ino || current.stat.dev !== initial.dev) throw new McpAccessError('FILE_CHANGED');
|
||||
guard(context);
|
||||
const text = redact(buffer.toString('utf8'));
|
||||
if (typeof text !== 'string') throw new McpAccessError('REDACTION_UNAVAILABLE');
|
||||
const start = args.offset || 0; const limit = args.limit || 65536;
|
||||
if (start > text.length) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
const content = text.slice(start, start + limit);
|
||||
return { artifactId: source.id, name: source.label, sizeBytes: initial.size, modifiedAt: initial.mtime.toISOString(),
|
||||
offset: start, returnedCharacters: content.length, totalCharacters: text.length, content,
|
||||
nextOffset: start + content.length < text.length ? start + content.length : null };
|
||||
} finally { reading--; if (file) await file.close().catch(() => {}); }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createMcpDiagnostics };
|
||||
+1
-1
@@ -9,7 +9,7 @@ function createMcpFiles({ getGrants, trashFile }) {
|
||||
};
|
||||
const metadata = stat => ({ size: stat.size, modifiedAt: stat.mtime.toISOString(), directory: stat.isDirectory(), file: stat.isFile() });
|
||||
return {
|
||||
mhu_files_roots: async () => getGrants().map(({ id, label, readOnly }) => ({ id, label, readOnly: readOnly !== false })),
|
||||
mhu_files_roots: async () => getGrants().map(({ id, label, readOnly, allowTransfer }) => ({ id, label, readOnly: readOnly !== false, allowTransfer: allowTransfer === true })),
|
||||
mhu_files_stat: async (args, context) => {
|
||||
guard(context);
|
||||
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath);
|
||||
|
||||
+2
-1
@@ -36,7 +36,8 @@ function createMcpProtocol({ adapter, version, getCapabilities }) {
|
||||
if (message.method !== 'tools/call') return error(message.id, -32601, 'Method not found');
|
||||
try {
|
||||
const result = await adapter.call(message.params?.name, message.params?.arguments ?? {}, { ...context, scopes: getCapabilities() });
|
||||
return response(message.id, { content: [{ type: 'text', text: JSON.stringify(result ?? null) }], isError: false });
|
||||
const textResult = message.params?.name === 'mhu_files_transfer_read' ? { ...result, base64: undefined } : result;
|
||||
return response(message.id, { content: [{ type: 'text', text: JSON.stringify(textResult ?? null) }], structuredContent: { result: result ?? null }, isError: false });
|
||||
} catch (failure) {
|
||||
const code = failure instanceof McpAccessError ? failure.code : 'ACTION_FAILED';
|
||||
return response(message.id, { content: [{ type: 'text', text: code }], isError: true });
|
||||
|
||||
+4
-4
@@ -18,10 +18,10 @@ function createMcpSanitizer(loadConfig) {
|
||||
const visit = (node, depth = 0) => {
|
||||
if (depth > 16) throw new McpAccessError('RESULT_TOO_LARGE');
|
||||
if (typeof node === 'string') {
|
||||
let result = node.replace(/(?:Bearer\s+\S+|media-mcp:v1:[A-Za-z0-9_-]+|MHU[12]-[A-Za-z0-9_-]+)/gi, '[REDACTED]')
|
||||
.replace(/((?:password|passwd|api[_-]?key|access[_-]?token|secret|sess_id)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi, '$1[REDACTED]');
|
||||
for (const secret of values) result = result.split(secret).join('[REDACTED]');
|
||||
return result;
|
||||
let result = node.replace(/(?:Bearer\s+\S+|media-mcp:v1:[A-Za-z0-9_-]+|MHU[12]-[A-Za-z0-9_-]+)/gi, '\0')
|
||||
.replace(/((?:password|passwd|api[_-]?key|access[_-]?token|secret|sess_id)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi, '$1\0');
|
||||
for (const secret of values) result = result.split(secret).join('\0');
|
||||
return result.replaceAll('\0', '[REDACTED]');
|
||||
}
|
||||
if (Array.isArray(node)) return node.map(item => visit(item, depth + 1));
|
||||
if (node && typeof node === 'object') return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, sensitive.test(key) ? '[REDACTED]' : visit(item, depth + 1)]));
|
||||
|
||||
+4
-4
@@ -69,7 +69,7 @@ class McpService {
|
||||
this.connection = 'disabled';
|
||||
const agent = this.agent; this.agent = null;
|
||||
this.publish();
|
||||
await agent?.stop();
|
||||
await Promise.all([agent?.stop(), this.options.handlers?.dispose?.()]);
|
||||
}
|
||||
async retryRevocations() {
|
||||
const pending = this.store.value.revocations;
|
||||
@@ -139,17 +139,17 @@ class McpService {
|
||||
const resolved = await fs.realpath(directory);
|
||||
const stat = await fs.stat(resolved);
|
||||
if (!stat.isDirectory() || path.parse(resolved).root === resolved) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
if (!this.store.value.grants.some(grant => grant.path === resolved)) await this.store.save({ ...this.store.value, grants: [...this.store.value.grants, { id: randomUUID(), label: path.basename(resolved), path: resolved, readOnly: true }] });
|
||||
if (!this.store.value.grants.some(grant => grant.path === resolved)) await this.store.save({ ...this.store.value, grants: [...this.store.value.grants, { id: randomUUID(), label: path.basename(resolved), path: resolved, readOnly: true, allowTransfer: false }] });
|
||||
this.publish(); return this.state();
|
||||
});
|
||||
}
|
||||
updateGrant(id, remove, readOnly = true) {
|
||||
updateGrant(id, remove, readOnly = true, allowTransfer) {
|
||||
const generation = this.generation;
|
||||
return this.serialize(async () => {
|
||||
const wasActive = this.active;
|
||||
await this.disconnect();
|
||||
await this.store.markDisabled();
|
||||
const grants = this.store.value.grants.flatMap(grant => grant.id !== id ? [grant] : remove ? [] : [{ ...grant, readOnly }]);
|
||||
const grants = this.store.value.grants.flatMap(grant => grant.id !== id ? [grant] : remove ? [] : [{ ...grant, readOnly, ...(allowTransfer === undefined ? {} : { allowTransfer }) }]);
|
||||
await this.store.save({ ...this.store.value, grants });
|
||||
if (wasActive && generation === this.generation) { await this.store.clearDisabled(); this.connect(); }
|
||||
this.publish(); return this.state();
|
||||
|
||||
+2
-1
@@ -25,7 +25,8 @@ class McpStore {
|
||||
if (typeof value.enabled !== 'boolean' || typeof value.name !== 'string' || !value.name.trim() || value.name.length > 100
|
||||
|| value.capabilities.some(item => !CAPABILITIES.includes(item)) || value.grants.length > 30 || value.revocations.length > 32
|
||||
|| value.grants.some(grant => !grant || typeof grant.id !== 'string' || typeof grant.path !== 'string' || !path.isAbsolute(grant.path)
|
||||
|| typeof grant.label !== 'string' || typeof grant.readOnly !== 'boolean')) throw new Error('format');
|
||||
|| typeof grant.label !== 'string' || typeof grant.readOnly !== 'boolean'
|
||||
|| (grant.allowTransfer !== undefined && typeof grant.allowTransfer !== 'boolean'))) throw new Error('format');
|
||||
const decode = identity => {
|
||||
if (!identity) return null;
|
||||
if (identity.relayUrl !== RELAY_URL || !/^[a-f0-9-]{36}$/.test(identity.installationId)) throw new Error('identity');
|
||||
|
||||
+18
-8
@@ -1,4 +1,5 @@
|
||||
const { McpAccessError, validateInput, actionDigest } = require('./mcp-access');
|
||||
const { sanitizeTransferResult } = require('./mcp-transfers');
|
||||
|
||||
const text = (maxLength = 4096) => ({ type: 'string', maxLength });
|
||||
const id = { type: 'string', minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_.:-]+$' };
|
||||
@@ -18,6 +19,7 @@ const definitions = [
|
||||
['app_info', 'Read application version and runtime information.', 'read', {}, []],
|
||||
['app_state', 'Read live transfer and automation summary.', 'read', {}, []],
|
||||
['queue_list', 'Read a bounded page of upload jobs.', 'read', { ...page, status: text(40) }, []],
|
||||
['queue_job_log', 'Read a bounded, secret-filtered log for one upload job.', 'read', { jobId: id, ...page }, ['jobId']],
|
||||
['queue_add', 'Add files from a granted directory to the upload queue.', 'control', { rootId: id, paths: array(text(), 1000), hosters: array(hoster, 5) }, ['rootId', 'paths', 'hosters']],
|
||||
['queue_start', 'Start eligible queued uploads.', 'control', jobIds, []],
|
||||
['queue_pause', 'Pause new uploads after current transfers.', 'control', {}, []],
|
||||
@@ -27,6 +29,7 @@ const definitions = [
|
||||
['queue_remove', 'Remove selected jobs without deleting source files.', 'control', jobIds, ['jobIds'], true],
|
||||
['queue_clear', 'Clear inactive jobs without deleting source files.', 'control', {}, [], true],
|
||||
['accounts_list', 'Read a bounded page of configured accounts with secrets hidden.', 'read', { ...page, hoster }, []],
|
||||
['accounts_runtime', 'Read temporary account cooldowns and manual-action states.', 'read', { ...page, hoster }, []],
|
||||
['accounts_check', 'Check selected account credentials without revealing them.', 'accounts', { accountIds: array(id, 100) }, ['accountIds']],
|
||||
['accounts_add', 'Add a hoster account with explicit credentials.', 'accounts', { hoster, label: text(200), username: text(320), password: text(), apiKey: text(), authType: enumeration(['login', 'api']) }, ['hoster', 'authType']],
|
||||
['accounts_update', 'Update one account without exposing stored credentials.', 'accounts', { ...account, label: text(200), username: text(320), password: text(), apiKey: text(), enabled: boolean }, ['accountId']],
|
||||
@@ -69,10 +72,19 @@ const definitions = [
|
||||
name: enumeration(['debug', 'fileuploader', 'uploadAudit', 'accountRotation', 'crash']),
|
||||
tailKb: integer(1, 256), backup: integer(0, 2), grep: text(200)
|
||||
}, ['name']],
|
||||
['diagnostics_files', 'List startup journals, native logs and saved startup failure reports.', 'diagnostics', page, []],
|
||||
['diagnostics_read', 'Read a page of a fully secret-filtered startup diagnostic artifact. Offsets and limits count redacted characters.', 'diagnostics',
|
||||
{ artifactId: id, offset: integer(0, 100000000), limit: integer(1, 65536) }, ['artifactId']],
|
||||
['files_roots', 'List configured directory grants, without granting new access.', 'files', {}, []],
|
||||
['files_list', 'List a bounded page within a granted directory.', 'files', { ...file, ...page }, ['rootId']],
|
||||
['files_stat', 'Read metadata for a file within a granted directory.', 'files', file, ['rootId', 'relativePath']],
|
||||
['files_hash', 'Compute a bounded file checksum within a granted directory.', 'files', { ...file, algorithm: enumeration(['sha256', 'sha512']) }, ['rootId', 'relativePath']],
|
||||
['files_transfer_open', 'Prepare a stable read-only file transfer from a directory with explicit content-transfer permission. Use a receiver to stream chunks outside chat.', 'files', file, ['rootId', 'relativePath']],
|
||||
['files_transfer_get', 'Read preparation state, byte size and SHA-256 for an owned file transfer.', 'files', { transferId: id }, ['transferId']],
|
||||
['files_transfer_list', 'List this authenticated client\'s active file transfers.', 'files', {}, []],
|
||||
['files_transfer_read', 'Read one verified binary chunk of an owned prepared transfer. Intended for a streaming receiver, not rendering in chat.', 'files',
|
||||
{ transferId: id, offset: integer(0, 32 * 1024 ** 3), length: integer(1, 1024 * 1024) }, ['transferId', 'offset']],
|
||||
['files_transfer_close', 'Close an owned temporary transfer handle without modifying its source file.', 'files', { transferId: id }, ['transferId']],
|
||||
['files_delete', 'Delete a specifically selected file inside a writable grant.', 'files.write', file, ['rootId', 'relativePath'], true],
|
||||
['cloud_status', 'Read CloudDrop log synchronization state.', 'read', {}, []],
|
||||
['cloud_configure', 'Enable or disable CloudDrop log sync with the saved or supplied key.', 'settings', { enabled: boolean, apiKey: text(200) }, ['enabled']],
|
||||
@@ -91,9 +103,9 @@ const definitions = [
|
||||
const capabilities = { diagnostics: 'read', accounts: 'control', settings: 'control', backup: 'control', lifecycle: 'control', 'secrets.read': 'secrets', 'files.write': 'files' };
|
||||
const MCP_TOOLS = Object.freeze(definitions.map(([name, description, scope, properties, required, destructive = false]) => Object.freeze({
|
||||
name: 'mhu_' + name, description, scope: capabilities[scope] || scope, destructive, inputSchema: object(properties, required),
|
||||
requiredScopes: [...new Set([capabilities[scope] || scope, ...(['queue_add', 'automation_update'].includes(name) ? ['files'] : []), ...(name === 'files_delete' ? ['control'] : [])])],
|
||||
annotations: { readOnlyHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope), destructiveHint: destructive,
|
||||
idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope), openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) }
|
||||
requiredScopes: [...new Set([capabilities[scope] || scope, ...(['queue_add', 'automation_update'].includes(name) ? ['files'] : []), ...(name === 'files_delete' ? ['control'] : []), ...(name.startsWith('files_transfer_') ? ['read'] : [])])],
|
||||
annotations: { readOnlyHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && !['files_transfer_open', 'files_transfer_close'].includes(name), destructiveHint: destructive,
|
||||
idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && name !== 'files_transfer_open', openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) }
|
||||
})));
|
||||
|
||||
function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit = () => {}, getCapabilities, requiresConfirmation = () => false }) {
|
||||
@@ -105,9 +117,7 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit
|
||||
const tool = byName.get(name);
|
||||
if (!tool || typeof handlers[name] !== 'function') throw new McpAccessError('TOOL_UNAVAILABLE');
|
||||
const allowed = () => getCapabilities ? getCapabilities() : context?.scopes;
|
||||
const permitted = () => Array.isArray(allowed()) && allowed().includes(tool.scope)
|
||||
&& (name !== 'mhu_files_delete' || allowed().includes('control'))
|
||||
&& (!['mhu_queue_add', 'mhu_automation_update'].includes(name) || allowed().includes('files'));
|
||||
const permitted = () => Array.isArray(allowed()) && tool.requiredScopes.every(scope => allowed().includes(scope));
|
||||
if (!permitted()) throw new McpAccessError('SCOPE_DENIED');
|
||||
validateInput(args, tool.inputSchema);
|
||||
if (context.signal?.aborted || !Number.isFinite(context.deadline) || context.deadline <= Date.now()) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
@@ -133,8 +143,8 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit
|
||||
const value = await handlers[name](args, context);
|
||||
if (context.signal?.aborted || Date.now() >= context.deadline) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
if (!permitted()) throw new McpAccessError('SCOPE_DENIED');
|
||||
const result = name === 'mhu_secrets_read' ? value : await sanitize(value);
|
||||
if (Buffer.byteLength(JSON.stringify(result) || 'null') > 1024 * 1024) throw new McpAccessError('RESULT_TOO_LARGE');
|
||||
const result = name.startsWith('mhu_files_transfer_') ? sanitizeTransferResult(name, value, sanitize) : name === 'mhu_secrets_read' ? value : await sanitize(value);
|
||||
if (Buffer.byteLength(JSON.stringify(result) || 'null') > (name === 'mhu_files_transfer_read' ? 2 : 1) * 1024 * 1024) throw new McpAccessError('RESULT_TOO_LARGE');
|
||||
audit({ tool: name, event: 'completed', requestId: context.requestId, durationMs: Date.now() - startedAt });
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { constants } = require('node:fs');
|
||||
const { createHash, randomUUID } = require('node:crypto');
|
||||
const { McpAccessError, resolveGrantedFile } = require('./mcp-access');
|
||||
|
||||
const CHUNK_BYTES = 1024 * 1024;
|
||||
const MAX_BYTES = 32 * 1024 ** 3;
|
||||
const unchanged = (a, b) => a.isFile() && b.isFile() && a.dev === b.dev && a.ino === b.ino && a.size === b.size
|
||||
&& a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && b.nlink === 1;
|
||||
const inside = (root, file) => { const relative = path.relative(root, file); return !relative || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep)); };
|
||||
|
||||
function sanitizeTransferResult(name, value, sanitize) {
|
||||
const fail = () => { throw new McpAccessError('INVALID_TRANSFER_RESULT'); };
|
||||
const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
||||
const integer = value => Number.isSafeInteger(value) && value >= 0 && value <= MAX_BYTES;
|
||||
const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
||||
const keys = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => allowed.includes(key));
|
||||
const metadata = item => {
|
||||
if (!keys(item, ['transferId', 'fileName', 'bytes', 'state', 'sha256', 'expiresAt', 'chunkBytes', 'checkedBytes', 'error', 'reference'])
|
||||
|| !uuid(item.transferId) || typeof item.fileName !== 'string' || item.fileName.length > 1024 || !integer(item.bytes)
|
||||
|| !['preparing', 'ready', 'failed'].includes(item.state) || (item.sha256 !== null && !digest(item.sha256))
|
||||
|| (item.state === 'ready' && !digest(item.sha256)) || item.chunkBytes !== CHUNK_BYTES
|
||||
|| (item.checkedBytes !== undefined && (!integer(item.checkedBytes) || item.checkedBytes > item.bytes))
|
||||
|| typeof item.expiresAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(item.expiresAt) || !Number.isFinite(Date.parse(item.expiresAt))
|
||||
|| (item.error !== undefined && (typeof item.error !== 'string' || !/^[A-Z_]{1,60}$/.test(item.error)))) fail();
|
||||
if (item.reference !== undefined) {
|
||||
if (typeof item.reference !== 'string' || !/^media-mcp-file:v1:[A-Za-z0-9_-]{1,1000}$/.test(item.reference)) fail();
|
||||
let ref;
|
||||
try { ref = JSON.parse(Buffer.from(item.reference.slice('media-mcp-file:v1:'.length), 'base64url').toString('utf8')); } catch { fail(); }
|
||||
if (!keys(ref, ['v', 'installationId', 'kind', 'transferId']) || ref.v !== 1 || ref.kind !== 'uploader' || !uuid(ref.installationId) || ref.transferId !== item.transferId) fail();
|
||||
}
|
||||
return { ...item, fileName: sanitize(item.fileName) };
|
||||
};
|
||||
if (name === 'mhu_files_transfer_read') {
|
||||
if (!keys(value, ['transferId', 'offset', 'bytesRead', 'nextOffset', 'bytes', 'sha256', 'base64']) || !uuid(value.transferId)
|
||||
|| ![value.offset, value.bytesRead, value.bytes].every(integer) || value.bytesRead > CHUNK_BYTES
|
||||
|| value.offset + value.bytesRead > value.bytes
|
||||
|| value.nextOffset !== (value.offset + value.bytesRead < value.bytes ? value.offset + value.bytesRead : null) || !digest(value.sha256)
|
||||
|| typeof value.base64 !== 'string' || value.base64.length > 4 * Math.ceil(CHUNK_BYTES / 3)) fail();
|
||||
const bytes = Buffer.from(value.base64, 'base64');
|
||||
if (bytes.length !== value.bytesRead || bytes.toString('base64') !== value.base64 || createHash('sha256').update(bytes).digest('hex') !== value.sha256) fail();
|
||||
return value;
|
||||
}
|
||||
if (name === 'mhu_files_transfer_list') {
|
||||
if (!keys(value, ['transfers']) || !Array.isArray(value.transfers) || value.transfers.length > 4) fail();
|
||||
return { transfers: value.transfers.map(metadata) };
|
||||
}
|
||||
if (name === 'mhu_files_transfer_close') {
|
||||
if (!keys(value, ['closed']) || typeof value.closed !== 'boolean') fail();
|
||||
return { closed: value.closed };
|
||||
}
|
||||
return metadata(value);
|
||||
}
|
||||
|
||||
function createMcpTransfers({ getGrants, getCapabilities = () => [], getProtectedPaths = () => [], getInstallationId = () => null,
|
||||
now = Date.now, ttlMs = 60 * 60 * 1000, idleMs = 10 * 60 * 1000, maximum = 4 }) {
|
||||
const records = new Map();
|
||||
let opening = 0;
|
||||
let generation = 0;
|
||||
let timer = null;
|
||||
const authorized = () => ['read', 'files'].every(scope => getCapabilities().includes(scope));
|
||||
const guard = context => {
|
||||
if (!authorized()) throw new McpAccessError('SCOPE_DENIED');
|
||||
if (context && (context.signal?.aborted || !Number.isFinite(context.deadline) || now() >= context.deadline)) throw new McpAccessError('REQUEST_EXPIRED');
|
||||
};
|
||||
const closeFile = record => record.closing || (record.closing = record.file.close().catch(() => {}));
|
||||
const remove = async record => {
|
||||
if (records.get(record.id) === record) records.delete(record.id);
|
||||
record.abort.abort();
|
||||
await record.task;
|
||||
await closeFile(record);
|
||||
};
|
||||
const expired = record => now() >= record.until || now() - record.touched >= idleMs;
|
||||
const purge = async () => { await Promise.all([...records.values()].filter(expired).map(remove)); };
|
||||
const ensureTimer = () => {
|
||||
if (timer) return;
|
||||
timer = setInterval(() => { void purge().catch(() => {}); }, Math.max(10, Math.min(30000, idleMs)));
|
||||
timer.unref?.();
|
||||
};
|
||||
const protectedFile = async file => {
|
||||
for (const entry of getProtectedPaths()) {
|
||||
const blocked = path.resolve(entry);
|
||||
if (inside(blocked, file)) return true;
|
||||
try { if (inside(await fs.realpath(blocked), file)) return true; }
|
||||
catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw new McpAccessError('PATH_NOT_GRANTED'); }
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const verify = async record => {
|
||||
guard();
|
||||
if (record.abort.signal.aborted || expired(record)) throw new McpAccessError('TRANSFER_EXPIRED');
|
||||
if (!getGrants().some(grant => grant.id === record.rootId && grant.allowTransfer === true)) throw new McpAccessError('TRANSFER_NOT_GRANTED');
|
||||
const target = await resolveGrantedFile(getGrants(), record.rootId, record.relativePath, { regularFile: true });
|
||||
if (target.path !== record.path || !unchanged(record.initial, target.stat) || await protectedFile(target.path)
|
||||
|| !unchanged(record.initial, await record.file.stat())) throw new McpAccessError('FILE_CHANGED');
|
||||
};
|
||||
const metadata = record => {
|
||||
const installationId = getInstallationId();
|
||||
return { transferId: record.id, fileName: record.name, bytes: record.initial.size, state: record.state,
|
||||
sha256: record.sha256, expiresAt: new Date(record.until).toISOString(), chunkBytes: CHUNK_BYTES, checkedBytes: record.checkedBytes,
|
||||
...(record.error ? { error: record.error } : {}),
|
||||
...(installationId ? { reference: 'media-mcp-file:v1:' + Buffer.from(JSON.stringify({ v: 1, installationId, kind: 'uploader', transferId: record.id })).toString('base64url') } : {}) };
|
||||
};
|
||||
const find = async (id, context) => {
|
||||
guard(context);
|
||||
await purge();
|
||||
const record = records.get(id);
|
||||
if (!record || record.owner !== context.principalId) throw new McpAccessError('TRANSFER_NOT_FOUND');
|
||||
record.touched = now();
|
||||
if (record.state !== 'failed') {
|
||||
try { await verify(record); }
|
||||
catch (error) { record.state = 'failed'; record.error = error instanceof McpAccessError ? error.code : 'FILE_CHANGED'; record.abort.abort(); await record.task; await closeFile(record); }
|
||||
}
|
||||
guard(context);
|
||||
return record;
|
||||
};
|
||||
const hash = async record => {
|
||||
try {
|
||||
const digest = createHash('sha256');
|
||||
const buffer = Buffer.alloc(CHUNK_BYTES);
|
||||
for (let offset = 0; offset < record.initial.size;) {
|
||||
await verify(record);
|
||||
const count = Math.min(buffer.length, record.initial.size - offset);
|
||||
const result = await record.file.read(buffer, 0, count, offset);
|
||||
if (result.bytesRead !== count) throw new McpAccessError('FILE_CHANGED');
|
||||
digest.update(buffer.subarray(0, count)); offset += count; record.checkedBytes = offset;
|
||||
}
|
||||
await verify(record);
|
||||
record.sha256 = digest.digest('hex'); record.state = 'ready';
|
||||
} catch (error) {
|
||||
record.state = 'failed'; record.error = error instanceof McpAccessError ? error.code : 'FILE_UNAVAILABLE';
|
||||
await closeFile(record);
|
||||
}
|
||||
};
|
||||
const handlers = {
|
||||
mhu_files_transfer_open: async (args, context) => {
|
||||
guard(context); await purge();
|
||||
if (records.size + opening >= maximum) throw new McpAccessError('TRANSFER_LIMIT');
|
||||
if (typeof context.principalId !== 'string' || !context.principalId) throw new McpAccessError('INVALID_REQUEST');
|
||||
opening++;
|
||||
const expectedGeneration = generation;
|
||||
let file;
|
||||
try {
|
||||
if (!getGrants().some(grant => grant.id === args.rootId && grant.allowTransfer === true)) throw new McpAccessError('TRANSFER_NOT_GRANTED');
|
||||
const target = await resolveGrantedFile(getGrants(), args.rootId, args.relativePath, { regularFile: true });
|
||||
if (target.stat.size > MAX_BYTES) throw new McpAccessError('FILE_TOO_LARGE');
|
||||
if (target.stat.nlink !== 1 || await protectedFile(target.path)) throw new McpAccessError('PATH_NOT_GRANTED');
|
||||
file = await fs.open(target.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
||||
const initial = await file.stat();
|
||||
if (!unchanged(target.stat, initial)) throw new McpAccessError('FILE_CHANGED');
|
||||
const record = { id: randomUUID(), owner: context.principalId, rootId: args.rootId, relativePath: args.relativePath,
|
||||
path: target.path, name: path.basename(target.path), initial, file, state: 'preparing', sha256: null, checkedBytes: 0,
|
||||
until: now() + ttlMs, touched: now(), abort: new AbortController(), task: Promise.resolve() };
|
||||
await verify(record); guard(context);
|
||||
if (generation !== expectedGeneration) throw new McpAccessError('TRANSFER_EXPIRED');
|
||||
records.set(record.id, record); ensureTimer();
|
||||
record.task = hash(record);
|
||||
file = null;
|
||||
return metadata(record);
|
||||
} finally { opening--; if (file) await file.close().catch(() => {}); }
|
||||
},
|
||||
mhu_files_transfer_get: async (args, context) => metadata(await find(args.transferId, context)),
|
||||
mhu_files_transfer_list: async (_args, context) => {
|
||||
guard(context); await purge();
|
||||
const items = [];
|
||||
for (const record of records.values()) if (record.owner === context.principalId) items.push(metadata(await find(record.id, context)));
|
||||
return { transfers: items };
|
||||
},
|
||||
mhu_files_transfer_read: async (args, context) => {
|
||||
const record = await find(args.transferId, context);
|
||||
if (record.state !== 'ready') throw new McpAccessError(record.state === 'failed' ? record.error : 'TRANSFER_NOT_READY');
|
||||
const length = args.length ?? CHUNK_BYTES;
|
||||
if (!Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset > record.initial.size
|
||||
|| !Number.isSafeInteger(length) || length < 1 || length > CHUNK_BYTES) throw new McpAccessError('INVALID_ARGUMENTS');
|
||||
const count = Math.min(length, record.initial.size - args.offset);
|
||||
const buffer = Buffer.alloc(count);
|
||||
try {
|
||||
await verify(record); guard(context);
|
||||
const result = await record.file.read(buffer, 0, count, args.offset);
|
||||
if (result.bytesRead !== count) throw new McpAccessError('FILE_CHANGED');
|
||||
await verify(record); guard(context);
|
||||
return { transferId: record.id, offset: args.offset, bytesRead: count, nextOffset: args.offset + count < record.initial.size ? args.offset + count : null,
|
||||
bytes: record.initial.size, sha256: createHash('sha256').update(buffer).digest('hex'), base64: buffer.toString('base64') };
|
||||
} catch (error) { record.state = 'failed'; record.error = error instanceof McpAccessError ? error.code : 'FILE_UNAVAILABLE'; await remove(record); throw error; }
|
||||
},
|
||||
mhu_files_transfer_close: async (args, context) => {
|
||||
guard(context); await purge();
|
||||
const record = records.get(args.transferId);
|
||||
if (!record || record.owner !== context.principalId) return { closed: false };
|
||||
await remove(record); return { closed: true };
|
||||
}
|
||||
};
|
||||
return { handlers, async dispose() { generation++; clearInterval(timer); timer = null; await Promise.all([...records.values()].map(remove)); } };
|
||||
}
|
||||
|
||||
module.exports = { createMcpTransfers, sanitizeTransferResult, CHUNK_BYTES, MAX_BYTES };
|
||||
Reference in new issue
Block a user