feat(mcp): implement MCP infrastructure
- Add `mcp_settings` table to database schema - Enable internal MCP API endpoint via middleware header authentication - Introduce runtime log directory and capture utilities for diagnostics - Update build pipeline to capture build logs
This commit is contained in:
1 parent
ae9b554189
commit
b2669e2ad5
19 files changed
+3280
-20
No files matched your search
@@ -109,6 +109,21 @@ export const CORE_SCHEMA_TABLE_DDLS = [
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`,
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS mcp_settings (
|
||||
id TEXT PRIMARY KEY DEFAULT 'default',
|
||||
enabled BOOLEAN NOT NULL DEFAULT false,
|
||||
token_hash TEXT NOT NULL DEFAULT '',
|
||||
token_enc TEXT NOT NULL DEFAULT '',
|
||||
token_preview TEXT NOT NULL DEFAULT '',
|
||||
allowed_ips TEXT NOT NULL DEFAULT '',
|
||||
permissions_json TEXT NOT NULL DEFAULT '{}',
|
||||
coolify_url TEXT NOT NULL DEFAULT '',
|
||||
coolify_token_enc TEXT NOT NULL DEFAULT '',
|
||||
coolify_app_uuid TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`,
|
||||
] as const;
|
||||
|
||||
export const CORE_SCHEMA_ALTER_DDLS = [
|
||||
|
||||
@@ -22,6 +22,10 @@ export type AuditActionType =
|
||||
| "WEBHOOK_TEST_TRIGGERED"
|
||||
| "FILES_MANAGER_MUTATION"
|
||||
| "DATA_EXPORT_DOWNLOADED"
|
||||
| "MCP_SETTINGS_UPDATED"
|
||||
| "MCP_TOKEN_ROTATED"
|
||||
| "MCP_TOOL_CALLED"
|
||||
| "MCP_TOOL_DENIED"
|
||||
| string;
|
||||
|
||||
export interface AuditLogEntry {
|
||||
@@ -98,6 +102,13 @@ function sanitizeMetadata(
|
||||
"webhookSecretEnc",
|
||||
"prometheusMetricsToken",
|
||||
"prometheusMetricsTokenEnc",
|
||||
"mcpToken",
|
||||
"mcpBearerToken",
|
||||
"issuedToken",
|
||||
"tokenHash",
|
||||
"tokenEnc",
|
||||
"coolifyToken",
|
||||
"coolifyTokenEnc",
|
||||
]);
|
||||
const clean: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(metadata)) {
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const MAX_LOG_FILE_BYTES = 2 * 1024 * 1024;
|
||||
const DEFAULT_TAIL_LINES = 120;
|
||||
const MAX_TAIL_LINES = 500;
|
||||
const MAX_SCAN_TAIL_BYTES = 512 * 1024;
|
||||
|
||||
export interface RuntimeLogEntry {
|
||||
ts: string;
|
||||
service: string;
|
||||
level: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface RuntimeLogReadResult {
|
||||
entries: RuntimeLogEntry[];
|
||||
totalMatched: number;
|
||||
filesChecked: string[];
|
||||
logsDir: string;
|
||||
exists: boolean;
|
||||
code?: "LOG_CAPTURE_UNAVAILABLE";
|
||||
warning?: string;
|
||||
}
|
||||
|
||||
export interface BuildLogReadResult {
|
||||
meta: Record<string, unknown> | null;
|
||||
logFile?: string | null;
|
||||
lines: string[];
|
||||
totalLines: number;
|
||||
exists: boolean;
|
||||
code?: "LOG_CAPTURE_UNAVAILABLE";
|
||||
warning?: string;
|
||||
}
|
||||
|
||||
const SECRET_SCRUB_PATTERNS: Array<[RegExp, string]> = [
|
||||
[/\b(Bearer\s+)[A-Za-z0-9\-._~+/]+=*/gi, "$1[REDACTED]"],
|
||||
[/\b(dsmcp_)[A-Za-z0-9_-]{8,}\b/gi, "$1[REDACTED]"],
|
||||
[
|
||||
/\b(eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.)[A-Za-z0-9_-]+\b/g,
|
||||
"$1[REDACTED]",
|
||||
],
|
||||
[
|
||||
/("(?:token|secret|password|jwtSecret|s3SecretAccessKey|webhookSecret|prometheusMetricsToken|coolifyToken|mcpToken|x-datastack-internal-secret)"\s*:\s*")([^"]+)(")/gi,
|
||||
"$1[REDACTED]$3",
|
||||
],
|
||||
];
|
||||
|
||||
export function scrubSensitiveLogText(rawText: string): string {
|
||||
let clean = String(rawText ?? "");
|
||||
for (const [pattern, replacement] of SECRET_SCRUB_PATTERNS) {
|
||||
clean = clean.replace(pattern, replacement);
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
export function resolveRuntimeLogsDir(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): string {
|
||||
const explicitDir = env.DATASTACK_RUNTIME_LOGS_DIR?.trim() || "";
|
||||
if (explicitDir) {
|
||||
return path.resolve(explicitDir);
|
||||
}
|
||||
|
||||
const storageDir = env.DATASTACK_STORAGE_DIR?.trim() || "";
|
||||
if (storageDir) {
|
||||
const resolved = path.resolve(storageDir);
|
||||
if (path.basename(resolved).toLowerCase() === "data") {
|
||||
return path.join(path.dirname(resolved), ".runtime-logs");
|
||||
}
|
||||
return path.join(resolved, ".runtime-logs");
|
||||
}
|
||||
|
||||
return path.resolve(process.cwd(), "storage", ".runtime-logs");
|
||||
}
|
||||
|
||||
function normalizeServiceName(service: string): "web" | "ingestion" {
|
||||
const s = String(service || "").trim().toLowerCase();
|
||||
if (s === "ingestion" || s === "server" || s === "socket") {
|
||||
return "ingestion";
|
||||
}
|
||||
return "web";
|
||||
}
|
||||
|
||||
function getServiceLogFilePath(service: "web" | "ingestion", logsDir: string): string {
|
||||
return path.join(logsDir, `${service}.log`);
|
||||
}
|
||||
|
||||
function rotateLogFileIfNeeded(filePath: string): void {
|
||||
try {
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.size >= MAX_LOG_FILE_BYTES) {
|
||||
const backupPath = `${filePath}.1`;
|
||||
try {
|
||||
if (fs.existsSync(backupPath)) {
|
||||
fs.unlinkSync(backupPath);
|
||||
}
|
||||
} catch {
|
||||
// ignore backup cleanup error
|
||||
}
|
||||
fs.renameSync(filePath, backupPath);
|
||||
}
|
||||
} catch {
|
||||
// file does not exist yet
|
||||
}
|
||||
}
|
||||
|
||||
export function appendRuntimeLogLine(
|
||||
service: "web" | "ingestion" | string,
|
||||
streamName: "stdout" | "stderr",
|
||||
rawChunk: string,
|
||||
options?: { logsDir?: string; env?: NodeJS.ProcessEnv },
|
||||
): number {
|
||||
const logsDir = options?.logsDir || resolveRuntimeLogsDir(options?.env);
|
||||
const safeService = normalizeServiceName(service);
|
||||
const text = scrubSensitiveLogText(rawChunk);
|
||||
if (!text) return 0;
|
||||
|
||||
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
if (lines.length === 0) return 0;
|
||||
|
||||
try {
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
const filePath = getServiceLogFilePath(safeService, logsDir);
|
||||
rotateLogFileIfNeeded(filePath);
|
||||
const level = streamName === "stderr" ? "error" : "info";
|
||||
const ts = new Date().toISOString();
|
||||
const formatted =
|
||||
lines
|
||||
.map((line) =>
|
||||
JSON.stringify({ ts, service: safeService, level, message: line }),
|
||||
)
|
||||
.join("\n") + "\n";
|
||||
fs.appendFileSync(filePath, formatted, "utf8");
|
||||
return lines.length;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function installRuntimeLogHook(
|
||||
service: "web" | "ingestion",
|
||||
options?: { logsDir?: string; env?: NodeJS.ProcessEnv; force?: boolean },
|
||||
): { installed: boolean; reason?: string; service?: string } {
|
||||
const safeService = normalizeServiceName(service);
|
||||
if (process.env.DATASTACK_LOG_CAPTURED_BY_RUNNER === "1" && !options?.force) {
|
||||
return { installed: false, reason: "captured_by_runner" };
|
||||
}
|
||||
|
||||
const globals = globalThis as Record<string, unknown>;
|
||||
const guardKey = `__dataStackRuntimeLogHook_${safeService}`;
|
||||
if (globals[guardKey]) {
|
||||
return { installed: false, reason: "already_installed" };
|
||||
}
|
||||
globals[guardKey] = true;
|
||||
|
||||
let isWriting = false;
|
||||
const wrapStream = (
|
||||
stream: NodeJS.WriteStream,
|
||||
streamName: "stdout" | "stderr",
|
||||
) => {
|
||||
const originalWrite = stream.write.bind(stream) as (
|
||||
chunk: Uint8Array | string,
|
||||
encoding?: BufferEncoding,
|
||||
cb?: (err?: Error | null) => void,
|
||||
) => boolean;
|
||||
|
||||
stream.write = ((
|
||||
chunk: Uint8Array | string,
|
||||
encodingOrCb?: BufferEncoding | ((err?: Error | null) => void),
|
||||
cb?: (err?: Error | null) => void,
|
||||
): boolean => {
|
||||
const encoding =
|
||||
typeof encodingOrCb === "string" ? encodingOrCb : undefined;
|
||||
const callback = typeof encodingOrCb === "function" ? encodingOrCb : cb;
|
||||
const result = originalWrite(chunk, encoding, callback);
|
||||
if (!isWriting) {
|
||||
isWriting = true;
|
||||
try {
|
||||
const raw =
|
||||
typeof chunk === "string"
|
||||
? chunk
|
||||
: Buffer.isBuffer(chunk)
|
||||
? chunk.toString(encoding || "utf8")
|
||||
: Buffer.from(chunk).toString("utf8");
|
||||
appendRuntimeLogLine(safeService, streamName, raw, options);
|
||||
} catch {
|
||||
// Never disrupt terminal output
|
||||
} finally {
|
||||
isWriting = false;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}) as typeof stream.write;
|
||||
};
|
||||
|
||||
wrapStream(process.stdout, "stdout");
|
||||
wrapStream(process.stderr, "stderr");
|
||||
return { installed: true, service: safeService };
|
||||
}
|
||||
|
||||
function readTailLinesFromFile(
|
||||
filePath: string,
|
||||
maxBytes = MAX_SCAN_TAIL_BYTES,
|
||||
): string[] {
|
||||
if (!fs.existsSync(filePath)) return [];
|
||||
const stat = fs.statSync(filePath);
|
||||
if (!stat.isFile() || stat.size === 0) return [];
|
||||
|
||||
const readSize = Math.min(stat.size, maxBytes);
|
||||
const startPos = Math.max(0, stat.size - readSize);
|
||||
const fd = fs.openSync(filePath, "r");
|
||||
try {
|
||||
const buf = Buffer.allocUnsafe(readSize);
|
||||
const bytesRead = fs.readSync(fd, buf, 0, readSize, startPos);
|
||||
let content = buf.subarray(0, bytesRead).toString("utf8");
|
||||
if (startPos > 0) {
|
||||
const firstNewline = content.indexOf("\n");
|
||||
content = firstNewline >= 0 ? content.slice(firstNewline + 1) : "";
|
||||
}
|
||||
return content.split(/\r?\n/).filter(Boolean);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function parseStoredLogLine(
|
||||
rawLine: string,
|
||||
fallbackService: string,
|
||||
): RuntimeLogEntry {
|
||||
try {
|
||||
const parsed = JSON.parse(rawLine) as Record<string, unknown>;
|
||||
if (parsed && typeof parsed === "object" && typeof parsed.message === "string") {
|
||||
return {
|
||||
ts: typeof parsed.ts === "string" ? parsed.ts : "",
|
||||
service:
|
||||
typeof parsed.service === "string" ? parsed.service : fallbackService,
|
||||
level: typeof parsed.level === "string" ? parsed.level : "info",
|
||||
message: parsed.message,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Plain-text fallback
|
||||
}
|
||||
return {
|
||||
ts: "",
|
||||
service: fallbackService,
|
||||
level: "info",
|
||||
message: rawLine,
|
||||
};
|
||||
}
|
||||
|
||||
export function readRuntimeLogs(options?: {
|
||||
logsDir?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
service?: "web" | "ingestion" | "all";
|
||||
lines?: number;
|
||||
search?: string;
|
||||
level?: string;
|
||||
}): RuntimeLogReadResult {
|
||||
const logsDir = options?.logsDir || resolveRuntimeLogsDir(options?.env);
|
||||
const serviceFilter = String(options?.service || "all")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const requestedLines = Number(options?.lines);
|
||||
const limit = Number.isFinite(requestedLines)
|
||||
? Math.min(MAX_TAIL_LINES, Math.max(1, Math.floor(requestedLines)))
|
||||
: DEFAULT_TAIL_LINES;
|
||||
const search = options?.search?.trim().toLowerCase() || "";
|
||||
const levelFilter = options?.level?.trim().toLowerCase() || "";
|
||||
|
||||
const services: Array<"web" | "ingestion"> =
|
||||
serviceFilter === "web"
|
||||
? ["web"]
|
||||
: serviceFilter === "ingestion"
|
||||
? ["ingestion"]
|
||||
: ["web", "ingestion"];
|
||||
|
||||
const collected: RuntimeLogEntry[] = [];
|
||||
const filesChecked: string[] = [];
|
||||
|
||||
for (const svc of services) {
|
||||
const mainFile = getServiceLogFilePath(svc, logsDir);
|
||||
const backupFile = `${mainFile}.1`;
|
||||
for (const candidate of [backupFile, mainFile]) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
filesChecked.push(path.basename(candidate));
|
||||
const rawLines = readTailLinesFromFile(candidate);
|
||||
for (const rawLine of rawLines) {
|
||||
const entry = parseStoredLogLine(rawLine, svc);
|
||||
if (levelFilter && levelFilter !== "all" && entry.level !== levelFilter) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
search &&
|
||||
!entry.message.toLowerCase().includes(search) &&
|
||||
!entry.service.toLowerCase().includes(search)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
collected.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filesChecked.length === 0) {
|
||||
return {
|
||||
entries: [],
|
||||
totalMatched: 0,
|
||||
filesChecked: [],
|
||||
logsDir,
|
||||
exists: false,
|
||||
code: "LOG_CAPTURE_UNAVAILABLE",
|
||||
warning:
|
||||
"No runtime logs captured yet in .runtime-logs/. Start services or emit stdout logs first.",
|
||||
};
|
||||
}
|
||||
|
||||
collected.sort((a, b) => {
|
||||
if (a.ts && b.ts && a.ts !== b.ts) {
|
||||
return a.ts.localeCompare(b.ts);
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
return {
|
||||
entries: collected.slice(-limit),
|
||||
totalMatched: collected.length,
|
||||
filesChecked,
|
||||
logsDir,
|
||||
exists: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function readBuildLogs(options?: {
|
||||
logsDir?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
cwd?: string;
|
||||
lines?: number;
|
||||
search?: string;
|
||||
}): BuildLogReadResult {
|
||||
const logsDir = options?.logsDir || resolveRuntimeLogsDir(options?.env);
|
||||
const cwd = options?.cwd || process.cwd();
|
||||
const requestedLines = Number(options?.lines);
|
||||
const limit = Number.isFinite(requestedLines)
|
||||
? Math.min(MAX_TAIL_LINES, Math.max(1, Math.floor(requestedLines)))
|
||||
: 200;
|
||||
const search = options?.search?.trim().toLowerCase() || "";
|
||||
|
||||
const metaCandidates = [
|
||||
path.join(logsDir, "last-build-meta.json"),
|
||||
path.join(cwd, "build-meta.json"),
|
||||
path.join(cwd, ".next", "standalone", "build-meta.json"),
|
||||
];
|
||||
const logCandidates = [
|
||||
path.join(logsDir, "last-build.log"),
|
||||
path.join(cwd, "build.log"),
|
||||
path.join(cwd, ".next", "standalone", "build.log"),
|
||||
];
|
||||
|
||||
let meta: Record<string, unknown> | null = null;
|
||||
for (const metaPath of metaCandidates) {
|
||||
try {
|
||||
if (fs.existsSync(metaPath)) {
|
||||
meta = JSON.parse(fs.readFileSync(metaPath, "utf8")) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
|
||||
let logPathUsed: string | null = null;
|
||||
let allLines: string[] = [];
|
||||
for (const logPath of logCandidates) {
|
||||
try {
|
||||
if (fs.existsSync(logPath)) {
|
||||
logPathUsed = path.basename(logPath);
|
||||
allLines = readTailLinesFromFile(logPath);
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
|
||||
if (!meta && !logPathUsed) {
|
||||
return {
|
||||
meta: null,
|
||||
lines: [],
|
||||
totalLines: 0,
|
||||
exists: false,
|
||||
code: "LOG_CAPTURE_UNAVAILABLE",
|
||||
warning:
|
||||
"No captured build log or build-meta.json found yet. Run npm run build first.",
|
||||
};
|
||||
}
|
||||
|
||||
const filtered = search
|
||||
? allLines.filter((line) => line.toLowerCase().includes(search))
|
||||
: allLines;
|
||||
|
||||
return {
|
||||
meta,
|
||||
logFile: logPathUsed,
|
||||
lines: filtered.slice(-limit),
|
||||
totalLines: filtered.length,
|
||||
exists: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function syncStandaloneBuildArtifactsToLogsDir(options?: {
|
||||
logsDir?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
cwd?: string;
|
||||
}): { synced: boolean; logsDir?: string } {
|
||||
const logsDir = options?.logsDir || resolveRuntimeLogsDir(options?.env);
|
||||
const cwd = options?.cwd || process.cwd();
|
||||
const buildLogSrc = [
|
||||
path.join(cwd, "build.log"),
|
||||
path.join(cwd, ".next", "standalone", "build.log"),
|
||||
].find((candidate) => fs.existsSync(candidate));
|
||||
const buildMetaSrc = [
|
||||
path.join(cwd, "build-meta.json"),
|
||||
path.join(cwd, ".next", "standalone", "build-meta.json"),
|
||||
].find((candidate) => fs.existsSync(candidate));
|
||||
|
||||
if (!buildLogSrc && !buildMetaSrc) {
|
||||
return { synced: false };
|
||||
}
|
||||
|
||||
try {
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
if (buildLogSrc) {
|
||||
fs.copyFileSync(buildLogSrc, path.join(logsDir, "last-build.log"));
|
||||
}
|
||||
if (buildMetaSrc) {
|
||||
fs.copyFileSync(buildMetaSrc, path.join(logsDir, "last-build-meta.json"));
|
||||
}
|
||||
return { synced: true, logsDir };
|
||||
} catch {
|
||||
return { synced: false };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { DatabaseEngine } from "../Database/database";
|
||||
import { getInternalIngestionHeaders } from "../Security/security";
|
||||
import {
|
||||
decryptSecret,
|
||||
encryptSecret,
|
||||
getMaskedHintFromEncrypted,
|
||||
} from "../Security/secretVault";
|
||||
import { SSRFBlockedError, validateOutboundUrlSync } from "../Security/ssrfGuard";
|
||||
import { validateAllowedIpsInput } from "../Security/ipAllowlist";
|
||||
|
||||
export type McpPermissionKey =
|
||||
| "metrics_health_read"
|
||||
| "runtime_logs_read"
|
||||
| "build_logs_read"
|
||||
| "audit_logs_read"
|
||||
| "ingestion_events_read"
|
||||
| "clients_read"
|
||||
| "clients_create"
|
||||
| "clients_update"
|
||||
| "clients_revoke_delete"
|
||||
| "files_list_read"
|
||||
| "files_download"
|
||||
| "files_upload_create"
|
||||
| "files_edit"
|
||||
| "files_delete"
|
||||
| "settings_read"
|
||||
| "settings_write"
|
||||
| "storage_maintenance";
|
||||
|
||||
export type McpPermissions = Record<McpPermissionKey, boolean>;
|
||||
|
||||
export interface McpPermissionDefinition {
|
||||
key: McpPermissionKey;
|
||||
label: string;
|
||||
description: string;
|
||||
category:
|
||||
| "Observability & Logs"
|
||||
| "Clients & SDKs"
|
||||
| "Files & Storage"
|
||||
| "Admin & Maintenance";
|
||||
defaultEnabled: boolean;
|
||||
risk: "read" | "write" | "destructive";
|
||||
}
|
||||
|
||||
export const MCP_PERMISSION_DEFINITIONS: readonly McpPermissionDefinition[] = [
|
||||
{
|
||||
key: "metrics_health_read",
|
||||
label: "Dashboard Metrics & Health",
|
||||
description: "Inspect dashboard metrics, Redis/PG health, buffer depth, and storage usage.",
|
||||
category: "Observability & Logs",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "runtime_logs_read",
|
||||
label: "Runtime Logs (Web & Ingestion)",
|
||||
description: "Read rotating Next.js (Port 3000) and Ingestion (Port 4000) stdout/stderr logs.",
|
||||
category: "Observability & Logs",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "build_logs_read",
|
||||
label: "Build & Coolify Logs",
|
||||
description: "Read captured Next.js build manifest/logs and optional Coolify deploy logs.",
|
||||
category: "Observability & Logs",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "audit_logs_read",
|
||||
label: "Admin Audit Logs",
|
||||
description: "Search administrative, RBAC, client, and MCP action history.",
|
||||
category: "Observability & Logs",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "ingestion_events_read",
|
||||
label: "Telemetry Events Read",
|
||||
description: "Query buffered recent events and stored CSV/GZ telemetry partitions.",
|
||||
category: "Observability & Logs",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "clients_read",
|
||||
label: "List & Inspect Clients",
|
||||
description: "View registered SDK client IDs, quotas, allowlists, and token previews.",
|
||||
category: "Clients & SDKs",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "clients_create",
|
||||
label: "Create SDK Clients",
|
||||
description: "Register new SDK client credentials from an AI agent session.",
|
||||
category: "Clients & SDKs",
|
||||
defaultEnabled: false,
|
||||
risk: "write",
|
||||
},
|
||||
{
|
||||
key: "clients_update",
|
||||
label: "Update SDK Clients",
|
||||
description: "Modify client names, rate limits, storage quotas, allowed IPs, or expiry.",
|
||||
category: "Clients & SDKs",
|
||||
defaultEnabled: false,
|
||||
risk: "write",
|
||||
},
|
||||
{
|
||||
key: "clients_revoke_delete",
|
||||
label: "Rotate, Revoke & Delete Clients",
|
||||
description: "Regenerate client JWTs, revoke active client tokens, or permanently delete clients.",
|
||||
category: "Clients & SDKs",
|
||||
defaultEnabled: false,
|
||||
risk: "destructive",
|
||||
},
|
||||
{
|
||||
key: "files_list_read",
|
||||
label: "Browse & Read Storage Files",
|
||||
description: "List directories and inspect bounded lines/bytes strictly inside /app/storage.",
|
||||
category: "Files & Storage",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "files_download",
|
||||
label: "Download Storage File Chunks",
|
||||
description: "Fetch bounded text or base64 file chunks inside /app/storage.",
|
||||
category: "Files & Storage",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "files_upload_create",
|
||||
label: "Upload & Create Files",
|
||||
description: "Upload or create new files inside /app/storage (respecting .lock protection).",
|
||||
category: "Files & Storage",
|
||||
defaultEnabled: false,
|
||||
risk: "write",
|
||||
},
|
||||
{
|
||||
key: "files_edit",
|
||||
label: "Edit Storage Files",
|
||||
description: "Perform targeted search/replace edits on non-locked files inside /app/storage.",
|
||||
category: "Files & Storage",
|
||||
defaultEnabled: false,
|
||||
risk: "write",
|
||||
},
|
||||
{
|
||||
key: "files_delete",
|
||||
label: "Delete Storage Files",
|
||||
description: "Delete non-locked files inside /app/storage.",
|
||||
category: "Files & Storage",
|
||||
defaultEnabled: false,
|
||||
risk: "destructive",
|
||||
},
|
||||
{
|
||||
key: "settings_read",
|
||||
label: "Read System Settings",
|
||||
description: "Inspect masked public runtime settings (raw secrets are always hidden).",
|
||||
category: "Admin & Maintenance",
|
||||
defaultEnabled: true,
|
||||
risk: "read",
|
||||
},
|
||||
{
|
||||
key: "settings_write",
|
||||
label: "Update System Settings",
|
||||
description: "Modify ingestion/storage thresholds (SSRF-guarded; never touches admin users or JWT keys).",
|
||||
category: "Admin & Maintenance",
|
||||
defaultEnabled: false,
|
||||
risk: "destructive",
|
||||
},
|
||||
{
|
||||
key: "storage_maintenance",
|
||||
label: "Buffer Flush & S3 Archive",
|
||||
description: "Trigger manual buffer flushes to CSV or on-demand S3 cold backups.",
|
||||
category: "Admin & Maintenance",
|
||||
defaultEnabled: false,
|
||||
risk: "write",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export interface McpSettingsRecord {
|
||||
enabled: boolean;
|
||||
tokenHash: string;
|
||||
tokenEnc: string;
|
||||
tokenPreview: string;
|
||||
allowedIps: string;
|
||||
permissions: McpPermissions;
|
||||
coolifyUrl: string;
|
||||
coolifyTokenEnc: string;
|
||||
coolifyAppUuid: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PublicMcpSettings {
|
||||
enabled: boolean;
|
||||
hasToken: boolean;
|
||||
tokenPreview: string;
|
||||
allowedIps: string;
|
||||
permissions: McpPermissions;
|
||||
coolifyUrl: string;
|
||||
hasCoolifyToken: boolean;
|
||||
coolifyTokenMask: string;
|
||||
coolifyAppUuid: string;
|
||||
endpointPath: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface McpBridgeSyncResult {
|
||||
attempted: boolean;
|
||||
ok: boolean;
|
||||
synced: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
checkedAt: string;
|
||||
}
|
||||
|
||||
export type McpSettingsUpdateInput = {
|
||||
enabled?: boolean;
|
||||
allowedIps?: string;
|
||||
permissions?: Partial<Record<McpPermissionKey, boolean>>;
|
||||
rotateToken?: boolean;
|
||||
revokeToken?: boolean;
|
||||
coolifyUrl?: string;
|
||||
coolifyToken?: string;
|
||||
clearCoolifyToken?: boolean;
|
||||
coolifyAppUuid?: string;
|
||||
};
|
||||
|
||||
type McpGlobals = typeof globalThis & {
|
||||
__dataStackMcpSettings?: McpSettingsRecord;
|
||||
__dataStackLastMcpBridgeSync?: McpBridgeSyncResult;
|
||||
};
|
||||
|
||||
const globals = globalThis as McpGlobals;
|
||||
|
||||
export function getDefaultMcpPermissions(): McpPermissions {
|
||||
const out = {} as McpPermissions;
|
||||
for (const def of MCP_PERMISSION_DEFINITIONS) {
|
||||
out[def.key] = def.defaultEnabled;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeMcpPermissions(
|
||||
raw: unknown,
|
||||
base: McpPermissions = getDefaultMcpPermissions(),
|
||||
): McpPermissions {
|
||||
const merged: McpPermissions = { ...base };
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
return merged;
|
||||
}
|
||||
const source = raw as Record<string, unknown>;
|
||||
for (const def of MCP_PERMISSION_DEFINITIONS) {
|
||||
if (typeof source[def.key] === "boolean") {
|
||||
merged[def.key] = source[def.key] as boolean;
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function getDefaultMcpSettings(): McpSettingsRecord {
|
||||
return {
|
||||
enabled: false,
|
||||
tokenHash: "",
|
||||
tokenEnc: "",
|
||||
tokenPreview: "",
|
||||
allowedIps: "",
|
||||
permissions: getDefaultMcpPermissions(),
|
||||
coolifyUrl: "",
|
||||
coolifyTokenEnc: "",
|
||||
coolifyAppUuid: "",
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export function generateMcpBearerToken(): string {
|
||||
return `dsmcp_${randomBytes(32).toString("hex")}`;
|
||||
}
|
||||
|
||||
export function hashMcpToken(rawToken: string): string {
|
||||
return createHash("sha256").update(String(rawToken || ""), "utf8").digest("hex");
|
||||
}
|
||||
|
||||
export function formatMcpTokenPreview(rawToken: string): string {
|
||||
const clean = String(rawToken || "").trim();
|
||||
if (!clean) return "";
|
||||
if (clean.length <= 14) return `${clean.slice(0, 4)}...`;
|
||||
return `${clean.slice(0, 10)}...${clean.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function verifyMcpBearerTokenHash(
|
||||
presentedToken: string,
|
||||
expectedHashHex: string,
|
||||
): boolean {
|
||||
const cleanPresented = String(presentedToken || "").trim();
|
||||
const cleanExpected = String(expectedHashHex || "").trim().toLowerCase();
|
||||
if (!cleanPresented || cleanExpected.length !== 64) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const presentedBuf = Buffer.from(hashMcpToken(cleanPresented), "hex");
|
||||
const expectedBuf = Buffer.from(cleanExpected, "hex");
|
||||
if (presentedBuf.length !== expectedBuf.length) {
|
||||
return false;
|
||||
}
|
||||
return timingSafeEqual(presentedBuf, expectedBuf);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function getMcpState(): McpSettingsRecord {
|
||||
if (!globals.__dataStackMcpSettings) {
|
||||
globals.__dataStackMcpSettings = getDefaultMcpSettings();
|
||||
}
|
||||
return globals.__dataStackMcpSettings;
|
||||
}
|
||||
|
||||
export function toPublicMcpSettings(record: McpSettingsRecord): PublicMcpSettings {
|
||||
return {
|
||||
enabled: Boolean(record.enabled),
|
||||
hasToken: Boolean(record.tokenHash),
|
||||
tokenPreview: record.tokenPreview || "",
|
||||
allowedIps: record.allowedIps || "",
|
||||
permissions: normalizeMcpPermissions(record.permissions),
|
||||
coolifyUrl: record.coolifyUrl || "",
|
||||
hasCoolifyToken: Boolean(record.coolifyTokenEnc),
|
||||
coolifyTokenMask: getMaskedHintFromEncrypted(record.coolifyTokenEnc),
|
||||
coolifyAppUuid: record.coolifyAppUuid || "",
|
||||
endpointPath: "/mcp",
|
||||
updatedAt: record.updatedAt || new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export class McpSettingsManager {
|
||||
public static getSettings(): McpSettingsRecord {
|
||||
const current = getMcpState();
|
||||
return {
|
||||
...current,
|
||||
permissions: { ...current.permissions },
|
||||
};
|
||||
}
|
||||
|
||||
public static async getSettingsAsync(): Promise<McpSettingsRecord> {
|
||||
const pool = DatabaseEngine.getPool();
|
||||
if (!pool) {
|
||||
return this.getSettings();
|
||||
}
|
||||
|
||||
try {
|
||||
await DatabaseEngine.ensureSchema();
|
||||
const res = await pool.query<{
|
||||
enabled: boolean;
|
||||
token_hash: string;
|
||||
token_enc: string;
|
||||
token_preview: string;
|
||||
allowed_ips: string;
|
||||
permissions_json: string;
|
||||
coolify_url: string;
|
||||
coolify_token_enc: string;
|
||||
coolify_app_uuid: string;
|
||||
updated_at: Date | string;
|
||||
}>(
|
||||
`SELECT enabled, token_hash, token_enc, token_preview, allowed_ips,
|
||||
permissions_json, coolify_url, coolify_token_enc, coolify_app_uuid, updated_at
|
||||
FROM mcp_settings
|
||||
WHERE id = 'default'`,
|
||||
);
|
||||
|
||||
if (!res.rowCount || res.rowCount === 0) {
|
||||
return this.getSettings();
|
||||
}
|
||||
|
||||
const row = res.rows[0];
|
||||
let parsedPermissions: unknown = {};
|
||||
try {
|
||||
parsedPermissions = JSON.parse(row.permissions_json || "{}");
|
||||
} catch {
|
||||
parsedPermissions = {};
|
||||
}
|
||||
|
||||
const hydrated: McpSettingsRecord = {
|
||||
enabled: Boolean(row.enabled),
|
||||
tokenHash: String(row.token_hash || ""),
|
||||
tokenEnc: String(row.token_enc || ""),
|
||||
tokenPreview: String(row.token_preview || ""),
|
||||
allowedIps: String(row.allowed_ips || ""),
|
||||
permissions: normalizeMcpPermissions(parsedPermissions),
|
||||
coolifyUrl: String(row.coolify_url || ""),
|
||||
coolifyTokenEnc: String(row.coolify_token_enc || ""),
|
||||
coolifyAppUuid: String(row.coolify_app_uuid || ""),
|
||||
updatedAt:
|
||||
row.updated_at instanceof Date
|
||||
? row.updated_at.toISOString()
|
||||
: String(row.updated_at || new Date().toISOString()),
|
||||
};
|
||||
globals.__dataStackMcpSettings = hydrated;
|
||||
return { ...hydrated, permissions: { ...hydrated.permissions } };
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[DataStack MCP] Failed to read mcp_settings from PostgreSQL (using cached/default state):",
|
||||
err instanceof Error ? err.message : err,
|
||||
);
|
||||
return this.getSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public static async getPublicSettingsAsync(): Promise<PublicMcpSettings> {
|
||||
const settings = await this.getSettingsAsync();
|
||||
return toPublicMcpSettings(settings);
|
||||
}
|
||||
|
||||
public static getLastBridgeSyncStatus(): McpBridgeSyncResult | null {
|
||||
return globals.__dataStackLastMcpBridgeSync ?? null;
|
||||
}
|
||||
|
||||
private static async persistToDb(record: McpSettingsRecord): Promise<void> {
|
||||
const pool = DatabaseEngine.getPool();
|
||||
if (!pool) return;
|
||||
|
||||
const schemaOk = await DatabaseEngine.ensureSchema();
|
||||
if (!schemaOk) {
|
||||
throw new Error(
|
||||
"DATABASE_WRITE_FAILED: Unable to verify PostgreSQL schema for mcp_settings.",
|
||||
);
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`
|
||||
INSERT INTO mcp_settings (
|
||||
id, enabled, token_hash, token_enc, token_preview,
|
||||
allowed_ips, permissions_json, coolify_url, coolify_token_enc,
|
||||
coolify_app_uuid, updated_at
|
||||
)
|
||||
VALUES ('default', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::timestamptz)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
enabled = EXCLUDED.enabled,
|
||||
token_hash = EXCLUDED.token_hash,
|
||||
token_enc = EXCLUDED.token_enc,
|
||||
token_preview = EXCLUDED.token_preview,
|
||||
allowed_ips = EXCLUDED.allowed_ips,
|
||||
permissions_json = EXCLUDED.permissions_json,
|
||||
coolify_url = EXCLUDED.coolify_url,
|
||||
coolify_token_enc = EXCLUDED.coolify_token_enc,
|
||||
coolify_app_uuid = EXCLUDED.coolify_app_uuid,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
`,
|
||||
[
|
||||
record.enabled,
|
||||
record.tokenHash,
|
||||
record.tokenEnc,
|
||||
record.tokenPreview,
|
||||
record.allowedIps,
|
||||
JSON.stringify(record.permissions),
|
||||
record.coolifyUrl,
|
||||
record.coolifyTokenEnc,
|
||||
record.coolifyAppUuid,
|
||||
record.updatedAt,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
private static async notifyIngestionMcpSync(
|
||||
record: McpSettingsRecord,
|
||||
tokenRotated: boolean,
|
||||
): Promise<McpBridgeSyncResult> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const configuredUrl = process.env.INGESTION_INTERNAL_URL?.trim();
|
||||
if (process.env.DATASTACK_DISABLE_LISTEN === "1" && !configuredUrl) {
|
||||
const skipped: McpBridgeSyncResult = {
|
||||
attempted: false,
|
||||
ok: true,
|
||||
synced: false,
|
||||
checkedAt,
|
||||
};
|
||||
globals.__dataStackLastMcpBridgeSync = skipped;
|
||||
return skipped;
|
||||
}
|
||||
|
||||
const headers = getInternalIngestionHeaders();
|
||||
if (!headers["x-datastack-internal-secret"]) {
|
||||
const result: McpBridgeSyncResult = {
|
||||
attempted: true,
|
||||
ok: false,
|
||||
synced: false,
|
||||
error: "Internal bridge secret is not configured",
|
||||
checkedAt,
|
||||
};
|
||||
globals.__dataStackLastMcpBridgeSync = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
const ingestionBaseUrl = (
|
||||
configuredUrl || "http://127.0.0.1:4000"
|
||||
).replace(/\/$/, "");
|
||||
|
||||
let coolifyTokenPlain = "";
|
||||
if (record.coolifyTokenEnc) {
|
||||
try {
|
||||
coolifyTokenPlain = decryptSecret(record.coolifyTokenEnc);
|
||||
} catch {
|
||||
coolifyTokenPlain = "";
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${ingestionBaseUrl}/internal/mcp-sync`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
enabled: record.enabled,
|
||||
tokenHash: record.tokenHash,
|
||||
tokenPreview: record.tokenPreview,
|
||||
allowedIps: record.allowedIps,
|
||||
permissions: record.permissions,
|
||||
coolifyUrl: record.coolifyUrl,
|
||||
coolifyToken: coolifyTokenPlain,
|
||||
coolifyAppUuid: record.coolifyAppUuid,
|
||||
updatedAt: record.updatedAt,
|
||||
tokenRotated,
|
||||
}),
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(1500),
|
||||
});
|
||||
const result: McpBridgeSyncResult = {
|
||||
attempted: true,
|
||||
ok: res.ok,
|
||||
synced: res.ok,
|
||||
status: res.status,
|
||||
...(res.ok ? {} : { error: `Port 4000 mcp-sync returned HTTP ${res.status}` }),
|
||||
checkedAt,
|
||||
};
|
||||
globals.__dataStackLastMcpBridgeSync = result;
|
||||
return result;
|
||||
} catch (err: unknown) {
|
||||
const result: McpBridgeSyncResult = {
|
||||
attempted: true,
|
||||
ok: false,
|
||||
synced: false,
|
||||
error: err instanceof Error ? err.message : "Port 4000 unreachable",
|
||||
checkedAt,
|
||||
};
|
||||
globals.__dataStackLastMcpBridgeSync = result;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static async updateSettingsAsync(
|
||||
updates: McpSettingsUpdateInput,
|
||||
): Promise<{
|
||||
settings: PublicMcpSettings;
|
||||
issuedToken?: string;
|
||||
tokenRotated: boolean;
|
||||
bridgeSync: McpBridgeSyncResult;
|
||||
}> {
|
||||
const current = await this.getSettingsAsync();
|
||||
let nextEnabled =
|
||||
typeof updates.enabled === "boolean" ? updates.enabled : current.enabled;
|
||||
let nextAllowedIps = current.allowedIps;
|
||||
|
||||
if (updates.allowedIps !== undefined) {
|
||||
const ipCheck = validateAllowedIpsInput(updates.allowedIps);
|
||||
if (!ipCheck.valid) {
|
||||
throw new Error(ipCheck.error || "Invalid allowedIps list.");
|
||||
}
|
||||
nextAllowedIps = ipCheck.normalized;
|
||||
}
|
||||
|
||||
let nextCoolifyUrl = current.coolifyUrl;
|
||||
if (updates.coolifyUrl !== undefined) {
|
||||
const trimmed = String(updates.coolifyUrl || "").trim();
|
||||
if (trimmed) {
|
||||
const ssrf = validateOutboundUrlSync(trimmed, {
|
||||
fieldName: "coolifyUrl",
|
||||
});
|
||||
if (!ssrf.allowed) {
|
||||
if (ssrf.code === "SSRF_BLOCKED_HOST") {
|
||||
throw new SSRFBlockedError(
|
||||
ssrf.error || "coolifyUrl target host is blocked.",
|
||||
ssrf.hostname || "",
|
||||
);
|
||||
}
|
||||
throw new Error(ssrf.error || "Invalid coolifyUrl.");
|
||||
}
|
||||
}
|
||||
nextCoolifyUrl = trimmed;
|
||||
}
|
||||
|
||||
const nextCoolifyAppUuid =
|
||||
updates.coolifyAppUuid !== undefined
|
||||
? String(updates.coolifyAppUuid || "").trim().slice(0, 128)
|
||||
: current.coolifyAppUuid;
|
||||
|
||||
let nextCoolifyTokenEnc = current.coolifyTokenEnc;
|
||||
if (updates.clearCoolifyToken) {
|
||||
nextCoolifyTokenEnc = "";
|
||||
} else if (
|
||||
typeof updates.coolifyToken === "string" &&
|
||||
updates.coolifyToken.trim().length > 0
|
||||
) {
|
||||
nextCoolifyTokenEnc = encryptSecret(updates.coolifyToken.trim());
|
||||
}
|
||||
|
||||
const nextPermissions = normalizeMcpPermissions(
|
||||
updates.permissions,
|
||||
current.permissions,
|
||||
);
|
||||
|
||||
let nextTokenHash = current.tokenHash;
|
||||
let nextTokenEnc = current.tokenEnc;
|
||||
let nextTokenPreview = current.tokenPreview;
|
||||
let issuedToken: string | undefined;
|
||||
let tokenRotated = false;
|
||||
|
||||
if (updates.revokeToken) {
|
||||
nextTokenHash = "";
|
||||
nextTokenEnc = "";
|
||||
nextTokenPreview = "";
|
||||
nextEnabled = false;
|
||||
tokenRotated = true;
|
||||
} else if (
|
||||
updates.rotateToken ||
|
||||
(nextEnabled && !current.tokenHash)
|
||||
) {
|
||||
const freshToken = generateMcpBearerToken();
|
||||
issuedToken = freshToken;
|
||||
nextTokenHash = hashMcpToken(freshToken);
|
||||
nextTokenEnc = encryptSecret(freshToken);
|
||||
nextTokenPreview = formatMcpTokenPreview(freshToken);
|
||||
tokenRotated = true;
|
||||
}
|
||||
|
||||
const nextRecord: McpSettingsRecord = {
|
||||
enabled: nextEnabled,
|
||||
tokenHash: nextTokenHash,
|
||||
tokenEnc: nextTokenEnc,
|
||||
tokenPreview: nextTokenPreview,
|
||||
allowedIps: nextAllowedIps,
|
||||
permissions: nextPermissions,
|
||||
coolifyUrl: nextCoolifyUrl,
|
||||
coolifyTokenEnc: nextCoolifyTokenEnc,
|
||||
coolifyAppUuid: nextCoolifyAppUuid,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await this.persistToDb(nextRecord);
|
||||
globals.__dataStackMcpSettings = nextRecord;
|
||||
const bridgeSync = await this.notifyIngestionMcpSync(
|
||||
nextRecord,
|
||||
tokenRotated || updates.enabled === false,
|
||||
);
|
||||
|
||||
return {
|
||||
settings: toPublicMcpSettings(nextRecord),
|
||||
...(issuedToken ? { issuedToken } : {}),
|
||||
tokenRotated,
|
||||
bridgeSync,
|
||||
};
|
||||
}
|
||||
|
||||
public static resetForTests(): void {
|
||||
delete globals.__dataStackMcpSettings;
|
||||
delete globals.__dataStackLastMcpBridgeSync;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user