140 lines
9.2 KiB
TypeScript
140 lines
9.2 KiB
TypeScript
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"
|
|
import { mkdir, open, readFile, rename } from "node:fs/promises"
|
|
import path from "node:path"
|
|
import { env } from "../../config.js"
|
|
|
|
export class McpError extends Error {
|
|
constructor(public readonly code: string, message: string, public readonly statusCode = 403) { super(message) }
|
|
}
|
|
export const tokenDigest = (token: string) => createHash("sha256").update(token).digest("hex")
|
|
export const randomToken = (kind: string) => `mmcp_${kind}_${randomBytes(32).toString("base64url")}`
|
|
export function canonicalMcpUrl(): URL {
|
|
const url = new URL(process.env.MCP_PUBLIC_URL || `http://localhost:${env.PORT}/mcp`)
|
|
if (url.username || url.password || url.search || url.hash || url.pathname !== "/mcp") throw new McpError("INVALID_CONFIGURATION", "MCP_PUBLIC_URL должен указывать на /mcp без query и credentials", 503)
|
|
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) throw new McpError("INVALID_CONFIGURATION", "Удалённый MCP требует HTTPS", 503)
|
|
return url
|
|
}
|
|
export function constantEqual(a: string, b: string): boolean {
|
|
const left = Buffer.from(a), right = Buffer.from(b)
|
|
return left.length === right.length && timingSafeEqual(left, right)
|
|
}
|
|
export function mcpStateDirectory() {
|
|
return path.resolve(process.env.MCP_STATE_DIR || path.join(path.dirname(env.DATABASE_PATH), ".mcp-state"))
|
|
}
|
|
async function durableValue(name: string, bytes: number): Promise<Buffer> {
|
|
const directory = mcpStateDirectory(), filename = path.join(directory, name)
|
|
const checked = (value: Buffer) => {
|
|
if (value.length !== bytes) throw new McpError("STATE_UNAVAILABLE", "Повреждено состояние доступа MCP", 503)
|
|
return value
|
|
}
|
|
// Re-read current material on EVERY check. Existing installations need no
|
|
// mkdir/open-wx/EEXIST round trip; rotation/revocation is never cached.
|
|
try { return checked(await readFile(filename)) }
|
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error }
|
|
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
try {
|
|
const handle = await open(filename, "wx", 0o600)
|
|
try { await handle.writeFile(randomBytes(bytes)); await handle.sync() } finally { await handle.close() }
|
|
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error }
|
|
return checked(await readFile(filename))
|
|
}
|
|
export async function accessGeneration(): Promise<string> { return (await durableValue("access-generation", 32)).toString("hex") }
|
|
export async function invalidateMcpAccess(): Promise<void> {
|
|
await accessGeneration()
|
|
const filename = path.join(mcpStateDirectory(), "access-generation"), temporary = filename + "." + randomBytes(8).toString("hex")
|
|
const handle = await open(temporary, "wx", 0o600)
|
|
try { await handle.writeFile(randomBytes(32)); await handle.sync() } finally { await handle.close() }
|
|
await rename(temporary, filename)
|
|
}
|
|
export async function encryptSecret(value: string): Promise<string> {
|
|
return seal(value, await durableValue("encryption-key", 32))
|
|
}
|
|
/** Private configuration proofs must not turn a public outer fingerprint into
|
|
* an offline dictionary oracle for a human-chosen credential. */
|
|
export async function privateSecretFingerprint(value: string, domain: string): Promise<string> {
|
|
return (await privateFingerprinter(domain))(value)
|
|
}
|
|
/** One scoped batch derives its purpose key once; no key is returned to callers. */
|
|
export async function privateFingerprinter(domain: string): Promise<(value: string) => string> {
|
|
const key = createHmac("sha256", await durableValue("encryption-key", 32)).update("MCP private fingerprint:" + domain).digest()
|
|
return value => createHmac("sha256", key).update(value).digest("hex")
|
|
}
|
|
/** Read-only check of an already active purpose-key epoch. Unlike initial
|
|
* bootstrap, a missing/deleted key must refuse without recreating state. */
|
|
export async function privateFingerprinterExisting(domain: string): Promise<(value: string) => string> {
|
|
let material: Buffer
|
|
try { material = await readFile(path.join(mcpStateDirectory(), "encryption-key")) }
|
|
catch { throw new McpError("STATE_UNAVAILABLE", "Действующий ключ MCP недоступен", 503) }
|
|
try {
|
|
if (material.length !== 32) throw new McpError("STATE_UNAVAILABLE", "Действующий ключ MCP недоступен", 503)
|
|
const key = createHmac("sha256", material).update("MCP private fingerprint:" + domain).digest()
|
|
return value => createHmac("sha256", key).update(value).digest("hex")
|
|
} finally { material.fill(0) }
|
|
}
|
|
/** Purpose-separated durable material stays inside a server-owned callback;
|
|
* it must never be serialized into evidence, tool inputs or responses. */
|
|
export async function withVrfProductionSealingKey<T>(work: (secret: Uint8Array) => Promise<T>): Promise<T> {
|
|
const key = createHmac("sha256", await durableValue("encryption-key", 32)).update("MCP VRF production admission sealing:v1").digest()
|
|
try { return await work(key) } finally { key.fill(0) }
|
|
}
|
|
export function seal(value: string, key: Buffer): string {
|
|
const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, iv)
|
|
const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()])
|
|
return Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString("base64")
|
|
}
|
|
/** Historical readers must never bootstrap/recreate missing encryption state. */
|
|
export async function decryptSecretExisting(value: string): Promise<string> {
|
|
let key: Buffer
|
|
try { key = await readFile(path.join(mcpStateDirectory(), "encryption-key")) }
|
|
catch { throw new McpError("STATE_UNAVAILABLE", "Действующий ключ MCP недоступен", 503) }
|
|
try {
|
|
if (key.length !== 32) throw new McpError("STATE_UNAVAILABLE", "Действующий ключ MCP недоступен", 503)
|
|
const data = Buffer.from(value, "base64")
|
|
if (data.length < 28) throw new McpError("SECRET_UNAVAILABLE", "Секрет недоступен", 503)
|
|
const cipher = createDecipheriv("aes-256-gcm", key, data.subarray(0, 12))
|
|
cipher.setAuthTag(data.subarray(12, 28))
|
|
return Buffer.concat([cipher.update(data.subarray(28)), cipher.final()]).toString("utf8")
|
|
} finally { key.fill(0) }
|
|
}
|
|
export async function decryptSecret(value: string): Promise<string> {
|
|
const data = Buffer.from(value, "base64")
|
|
if (data.length < 28) throw new McpError("SECRET_UNAVAILABLE", "Секрет недоступен", 503)
|
|
const decipher = createDecipheriv("aes-256-gcm", await durableValue("encryption-key", 32), data.subarray(0, 12))
|
|
decipher.setAuthTag(data.subarray(12, 28))
|
|
return Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString("utf8")
|
|
}
|
|
export async function encryptBinary(value: Buffer): Promise<Buffer> {
|
|
const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", await durableValue("encryption-key", 32), iv)
|
|
const data = Buffer.concat([cipher.update(value), cipher.final()])
|
|
return Buffer.concat([iv, cipher.getAuthTag(), data])
|
|
}
|
|
export async function decryptBinary(value: Buffer): Promise<Buffer> {
|
|
if (value.length < 28) throw new McpError("SECRET_UNAVAILABLE", "Зашифрованный архив недоступен", 503)
|
|
const cipher = createDecipheriv("aes-256-gcm", await durableValue("encryption-key", 32), value.subarray(0, 12))
|
|
cipher.setAuthTag(value.subarray(12, 28))
|
|
return Buffer.concat([cipher.update(value.subarray(28)), cipher.final()])
|
|
}
|
|
const sensitive = /password|passwd|secret|private.?key|preshared|pre.shared|authorization|auth.?key|authentication.?key|tcp.?md5.?key|api.?key|certificate.?contents|token|ciphertext/i
|
|
export const MAX_MCP_PUBLIC_STRING_LENGTH = 16000
|
|
export const MAX_MCP_PUBLIC_ARRAY_ITEMS = 500
|
|
export function redact(value: unknown, depth = 0): unknown {
|
|
if (depth > 12) return "[truncated]"
|
|
if (value instanceof Date) return value.toISOString()
|
|
if (typeof value === "string") return value.slice(0, MAX_MCP_PUBLIC_STRING_LENGTH)
|
|
.replace(/\bBearer\s+[^\s,;]+/gi, "Bearer [redacted]")
|
|
.replace(/\bmmcp_[a-z]+_[A-Za-z0-9_-]+/g, "[redacted]")
|
|
.replace(/((?:password|secret|private-key|preshared-key|auth-key|authentication-key|tcp-md5-key|api-key|token)\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, "$1[redacted]")
|
|
if (Array.isArray(value)) return value.slice(0, MAX_MCP_PUBLIC_ARRAY_ITEMS).map(item => redact(item, depth + 1))
|
|
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([key]) => key !== "__mmappMcpOperationClaimV1").slice(0, 200).map(([key, item]) => [key, sensitive.test(key) && !/Ref$|Configured$/i.test(key) ? "[redacted]" : redact(item, depth + 1)]))
|
|
return value
|
|
}
|
|
export function fingerprint(value: unknown): string {
|
|
const canonical = (item: unknown): string => {
|
|
if (item instanceof Date) return JSON.stringify(item.toISOString())
|
|
if (Array.isArray(item)) return "[" + item.map(canonical).join(",") + "]"
|
|
if (item && typeof item === "object") return "{" + Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => JSON.stringify(key) + ":" + canonical(entry)).join(",") + "}"
|
|
return JSON.stringify(item) ?? "null"
|
|
}
|
|
return tokenDigest(canonical(value))
|
|
}
|