feat(mcp): подготовить сервер и доступ к приёмке

This commit is contained in:
Denozordec committed 2026-11-03 03:12:03 +07:00
commit bf3d50e1ff
3835 files changed
+537122

No files matched your search

@@ -0,0 +1,134 @@
/** External SDK consumer: imports NO server/store/runtime/database module. */
import assert from 'node:assert/strict'
import { randomUUID, createHash } from 'node:crypto'
import { Client, StreamableHTTPClientTransport, auth } from '@modelcontextprotocol/client'
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
const endpoint = new URL(process.env.OWN_MCP_ENDPOINT), origin = endpoint.origin
assert.equal(endpoint.hostname, '127.0.0.1'); assert.equal(process.env.OWN_EXTERNAL_CLIENT, 'true')
let phase = 'start', next = 0, maxResponseBytes = 0, stderrBytes = 0, bridgePid = null
const pending = new Map(), cases = []
const activeClients = new Set()
let closing = false
async function closeClients() { await Promise.allSettled([...activeClients].map(client => client.close())) }
async function interrupted() { if (closing) return; closing = true; await closeClients(); process.disconnect?.(); process.exitCode = 1 }
process.on('SIGTERM', interrupted); process.on('SIGINT', interrupted); process.on('disconnect', interrupted)
process.on('message', m => { if (m?.kind === 'reply') { const p = pending.get(m.id); pending.delete(m.id); if (m.error) p?.reject(Error('Fixture control refused')); else p?.resolve(m.value) } })
const control = command => new Promise((resolve, reject) => { const id = ++next; pending.set(id, { resolve, reject }); process.send({ kind: 'control', command, id }) })
async function boundedFetch(input, init) {
const url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url)
assert.equal(url.origin, origin, 'External fixture refuses all nonlocal origins')
const response = await fetch(input, { ...init, redirect: 'manual', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000) })
const chunks = []; let count = 0
if (response.body) {
const reader = response.body.getReader()
try {
for (;;) { const item = await reader.read(); if (item.done) break; count += item.value.length; if (count >= 1048576) { await reader.cancel(); throw Error('Own external client response bound') }; chunks.push(item.value) }
} finally { reader.releaseLock() }
}
const bytes = Buffer.concat(chunks); maxResponseBytes = Math.max(maxResponseBytes, bytes.length)
return new Response(bytes.length ? bytes : null, { status: response.status, statusText: response.statusText, headers: response.headers })
}
function content(result) {
assert(!result.isError)
const text = result.content.find(c => c.type === 'text')?.text
const parsed = JSON.parse(text)
assert(!text.includes(process.env.OWN_SERVER_SECRET)); assert(Buffer.byteLength(text) < 65536)
return parsed
}
async function denied(work) { try { const r = await work(); assert.equal(r?.isError, true) } catch (e) { if (e?.code === 'ERR_ASSERTION') throw e; assert(!/timeout|timed out/i.test(String(e?.message)), 'A timeout is not authorization denial') } }
async function opened(mode, token) {
const client = new Client({ name: 'actual-external-process-' + mode, version: '1.0.0' })
activeClients.add(client)
let transport
if (mode === 'http') transport = new StreamableHTTPClientTransport(endpoint, { requestInit: { headers: { authorization: 'Bearer ' + token } }, fetch: boundedFetch })
else {
transport = new StdioClientTransport({ command: process.execPath, args: ['--import', import.meta.resolve('tsx'), process.env.OWN_BRIDGE_FILE],
cwd: process.cwd(), env: { MCP_URL: endpoint.href, MCP_TOKEN: token }, stderr: 'pipe', maxBufferSize: 131072 })
transport.stderr?.on('data', chunk => { stderrBytes += chunk.length; const text = String(chunk); assert(!text.includes(token)); assert(stderrBytes < 1048576) })
const start = transport.start.bind(transport)
transport.start = async () => { await start(); bridgePid = transport.pid; assert(bridgePid && bridgePid !== process.pid && bridgePid !== Number(process.env.OWN_SERVER_PID)); process.send({ kind: 'bridge-pid', pid: bridgePid }) }
}
const connecting = client.connect(transport, { timeout: 10000 })
try { await connecting; return client }
catch (e) { await client.close().catch(() => {}); throw e }
}
async function scoped(client) {
const list = await client.listTools({}, { timeout: 5000 })
assert.deepEqual(list.tools.map(t => t.name), ['mm_servers_list'])
const result = content(await client.callTool({ name: 'mm_servers_list', arguments: { limit: 1, offset: 0 } }, undefined, { timeout: 5000 }))
assert.equal(result.items.length, 1); assert.equal(result.items[0].id, Number(process.env.OWN_ALLOWED_SERVER))
await denied(() => client.callTool({ name: 'mm_servers_list', arguments: { serverId: Number(process.env.OWN_FORBIDDEN_SERVER) } }, undefined, { timeout: 5000 }))
await denied(() => client.callTool({ name: 'mm_servers_list', arguments: { limit: 501 } }, undefined, { timeout: 5000 }))
await denied(() => client.callTool({ name: 'mm_servers_delete_plan', arguments: { serverId: Number(process.env.OWN_ALLOWED_SERVER) } }, undefined, { timeout: 5000 }))
}
try {
assert.notEqual(process.pid, Number(process.env.OWN_SERVER_PID))
for (const mode of ['http', 'stdio']) {
phase = mode + ':issue'; const initial = await control('new-connection'); let token = initial.token
phase = mode + ':initialize'; let client = await opened(mode, token)
try {
await scoped(client); cases.push(mode + ': separate SDK process initializes, filters tool/host scope, bounds page/result and redacts credentials')
if (mode === 'stdio' && process.env.OWN_EXTERNAL_CLEANUP_FAULT === 'failure') throw Error('Owned deliberate external client failure with bridge active')
if (mode === 'stdio' && process.env.OWN_EXTERNAL_CLEANUP_FAULT === 'timeout') { process.send({ kind: 'arm-cleanup-timeout' }); await new Promise(() => {}) }
phase = mode + ':result-bound'; await control('large-result')
try {
const bounded = content(await client.callTool({ name: 'mm_servers_list', arguments: { limit: 1 } }, undefined, { timeout: 5000 }))
assert.equal(bounded.items[0].comment.length, 16000); assert(!bounded.items[0].comment.includes('OWNED_TRUNCATION_TAIL'))
cases.push(mode + ': actual production public-string16k bound truncates owned40k comment through real SDK result')
} finally { await control('reset-result') }
phase = mode + ':rotate'; const rotated = await control('rotate'); await denied(() => client.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 }))
await client.close(); await assert.rejects(opened(mode, token)); token = rotated.token; client = await opened(mode, token)
content(await client.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 })); cases.push(mode + ': old credential and reconnect refused after rotation; fresh transport reconnect succeeds')
phase = mode + ':pause'; await control('pause'); await denied(() => client.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 }))
await control('resume'); content(await client.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 })); cases.push(mode + ': established client observes pause/resume on real requests')
phase = mode + ':revoke'; await control('revoke'); await denied(() => client.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 }))
await client.close(); await assert.rejects(opened(mode, token)); cases.push(mode + ': permanent revocation blocks established and newly initialized external clients')
} finally { await client.close().catch(() => {}) }
}
phase = 'http:body-bound'; const bound = await control('new-connection')
const oversized = await fetch(endpoint, { method: 'POST', headers: { authorization: 'Bearer ' + bound.token, 'content-type': 'application/json', accept: 'application/json,text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'mm_servers_list', arguments: { padding: 'x'.repeat(1048576) } } }), signal: AbortSignal.timeout(5000) })
assert.equal(oversized.status, 413); assert((await oversized.text()).length < 65536)
cases.push('actual HTTP request envelope over1MiB refused before tool execution; successful client results remain bounded')
phase = 'sdk:pkce'; const grant = await control('new-connection')
const metadata = { client_name: 'owned-external-sdk-pkce', redirect_uris: [origin + '/owned-callback'], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', scope: 'mcp' }
const registered = await boundedFetch(origin + '/api/mcp/oauth/clients', { method: 'POST', headers: { authorization: 'Bearer ' + process.env.OWN_PORTAL_JWT, 'content-type': 'application/json' }, body: JSON.stringify({ name: metadata.client_name, redirectUris: metadata.redirect_uris }) })
assert.equal(registered.status, 200); const clientId = (await registered.json()).clientId
let tokens, verifier, authorizationCode, authorizationIssuer, discovery, consentAllowed = true
const state = randomUUID()
const provider = { redirectUrl: metadata.redirect_uris[0], clientMetadata: metadata, clientInformation: () => ({ client_id: clientId, token_endpoint_auth_method: 'none' }),
tokens: () => tokens, saveTokens: v => { tokens = v }, saveCodeVerifier: v => { verifier = v }, codeVerifier: () => verifier, state: () => state,
discoveryState: () => discovery, saveDiscoveryState: v => { discovery = v }, invalidateCredentials: scope => { if (scope === 'tokens') tokens = undefined },
redirectToAuthorization: async url => {
if (!consentAllowed) throw Error('Synthetic consent disabled after revocation')
assert.equal(url.origin, origin); assert.equal(url.searchParams.get('code_challenge_method'), 'S256')
assert.equal(url.searchParams.get('code_challenge'), createHash('sha256').update(verifier).digest('base64url'))
const response = await boundedFetch(url); assert.equal(response.status, 302)
const requestId = new URL(response.headers.get('location')).searchParams.get('oauthRequest'); assert(requestId)
const consent = await boundedFetch(origin + '/api/mcp/oauth/consent', { method: 'POST', headers: { authorization: 'Bearer ' + process.env.OWN_PORTAL_JWT, 'content-type': 'application/json' }, body: JSON.stringify({ requestId, connectionId: grant.connectionId, approve: true }) })
assert.equal(consent.status, 200); const callback = new URL((await consent.json()).redirectUrl)
assert.equal(callback.searchParams.get('state'), state); authorizationCode = callback.searchParams.get('code'); authorizationIssuer = callback.searchParams.get('iss')
} }
phase = 'sdk:pkce-redirect'; assert.equal(await auth(provider, { serverUrl: endpoint, scope: 'mcp', fetchFn: boundedFetch }), 'REDIRECT')
assert(authorizationCode && verifier); assert.equal(authorizationIssuer, origin)
phase = 'sdk:pkce-exchange'; assert.equal(await auth(provider, { serverUrl: endpoint, authorizationCode, iss: authorizationIssuer, fetchFn: boundedFetch }), 'AUTHORIZED')
assert(tokens?.access_token && tokens?.refresh_token)
const oauthClient = new Client({ name: 'external-sdk-real-pkce-mock-portal', version: '1.0.0' })
activeClients.add(oauthClient)
try {
phase = 'sdk:pkce-initialize'; await oauthClient.connect(new StreamableHTTPClientTransport(endpoint, { authProvider: provider, fetch: boundedFetch }), { timeout: 10000 })
content(await oauthClient.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 }))
cases.push('installed SDK auth() discovers actual OAuth metadata, produces PKCE/S256, exchanges one-use code and calls scoped tool; portal JWT/consent is synthetic')
phase = 'sdk:pkce-revoke'; const access = tokens.access_token, refresh = tokens.refresh_token
const revoked = await boundedFetch(origin + '/oauth/revoke', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token: refresh, client_id: clientId }).toString() }); assert.equal(revoked.status, 200)
consentAllowed = false; await assert.rejects(opened('http', access))
await denied(() => oauthClient.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 }))
cases.push('actual OAuth family revocation refuses established and fresh external transport; no implicit new consent granted')
} finally { await oauthClient.close().catch(() => {}) }
process.send({ kind: 'result', result: { cases: cases.length, names: cases, externalClientPid: process.pid, serverPid: Number(process.env.OWN_SERVER_PID), bridgePid,
sdkOnlyExternalClient: true, maxObservedHttpResponseBytes: maxResponseBytes, clientResponseLimitBytes: 1048576, stdioSdkBufferLimitBytes: 131072,
actualPublicStringLimitObserved: 16000, wholeGenericResultEnvelopeLimitAccepted: false,
syntheticPortalJwtAndConsent: true, liveAuthPortal: false, livePortalSender: false, endUserUi: false, wholeExternalDirectionComplete: false } })
} catch (error) { process.send?.({ kind: 'failure', phase, errorType: error?.name ?? 'Error', completedCases: cases }); process.exitCode = 1 }
finally { closing = true; await closeClients(); process.disconnect?.() }
@@ -0,0 +1,36 @@
import EmbeddedPostgres from 'embedded-postgres'
import { mkdtemp, rm, mkdir, readFile, writeFile } from 'node:fs/promises'
import { join, resolve, relative, isAbsolute } from 'node:path'
import { fileURLToPath } from 'node:url'
import { randomBytes, createHash } from 'node:crypto'
import { createServer } from 'node:net'
import { spawn } from 'node:child_process'
const sourceRoot = resolve(process.argv[2] ?? fileURLToPath(new URL('../../../', import.meta.url)))
const output = resolve(sourceRoot, 'tmp/mcp-external-process-acceptance'); await mkdir(output, { recursive: true })
const paths = ['backend/src/scripts/mcp-stdio.ts', 'backend/src/routes/mcp-transport.ts', 'backend/src/routes/mcp-oauth.ts', 'backend/src/modules/mcp/store.ts',
'backend/src/modules/mcp/runtime.ts', 'backend/src/modules/mcp/actions.ts', 'backend/src/modules/mcp/security.ts', 'backend/src/modules/mcp/protocol-limits.ts',
'backend/src/modules/mcp/portal-revocation.ts', 'backend/src/plugins/auth.ts', 'backend/src/index.ts', 'node_modules/@modelcontextprotocol/client/package.json', 'node_modules/@modelcontextprotocol/server/package.json']
async function pins() { const result = []; for (const path of paths) result.push({ path, sha256: createHash('sha256').update(await readFile(resolve(sourceRoot, path))).digest('hex') }); return result }
const before = await pins(), directory = await mkdtemp(join(resolve(sourceRoot, 'tmp'), 'mm-mcp-external-')), state = join(directory, 'state'); await mkdir(state)
const listener = createServer(); await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve)); const port = listener.address().port; await new Promise(resolve => listener.close(resolve))
const password = randomBytes(24).toString('hex')
const postgres = new EmbeddedPostgres({ databaseDir: join(directory, 'pg'), port, user: 'mcp_test', password, persistent: true, createPostgresUser: false,
initdbFlags: ['--encoding=UTF8'], postgresFlags: ['-h', '127.0.0.1'], onLog: () => {}, onError: () => {} })
try {
await postgres.initialise(); await postgres.start()
process.exitCode = await new Promise((done, reject) => {
const child = spawn(process.execPath, ['--import', import.meta.resolve('tsx'), fileURLToPath(new URL('./server-fixture.ts', import.meta.url))], { cwd: directory,
windowsHide: true, stdio: 'inherit', env: { ...Object.fromEntries(['SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'PATH', 'Path'].filter(k => process.env[k]).map(k => [k, process.env[k]])),
OWN_EXTERNAL_CLEANUP_FAULT: process.env.OWN_EXTERNAL_CLEANUP_FAULT, OWN_EXTERNAL_SOURCE_ROOT: sourceRoot, OWN_EXTERNAL_RESULT_FILE: join(output, 'result.json'), NODE_ENV: 'test', OWN_EXTERNAL_PROCESS_PG: 'true', DATABASE_URL: `postgresql://mcp_test:${password}@127.0.0.1:${port}/postgres`, DATABASE_PATH: join(directory, 'no-legacy.sqlite'),
MCP_STATE_DIR: state, AUTH_REQUIRED: 'true', AUTH_JWT_SECRET: 'owned-external-synthetic-issuer-test-only', AUTH_ISSUER: 'https://synthetic-portal.invalid', AUTH_PORTAL_URL: 'https://synthetic-portal.invalid' } })
child.once('error', reject); child.once('exit', code => done(code ?? 1))
})
const after = await pins(), unchanged = JSON.stringify(before) === JSON.stringify(after)
await writeFile(join(output, 'source-pins.json'), JSON.stringify({ before, after, unchanged, exitCode: process.exitCode }, null, 2))
console.log('External-client source/SDK pins unchanged:', unchanged); if (!unchanged) process.exitCode = 1
} finally {
await postgres.stop(); const target = resolve(directory), rel = relative(resolve(resolve(sourceRoot, 'tmp')), target)
if (!rel || rel.startsWith('..') || isAbsolute(rel) || !target.includes('mm-mcp-external-')) throw Error('Unsafe exact owned cleanup')
await rm(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 250 }); console.log('Owned external-client PostgreSQL stopped and exact temp directory removed')
}
process.exit(process.exitCode ?? 0)
@@ -0,0 +1,98 @@
import assert from "node:assert/strict"
import { spawn } from "node:child_process"
import { createServer } from "node:net"
import { fileURLToPath, pathToFileURL } from "node:url"
import { resolve, isAbsolute } from "node:path"
import { SignJWT } from "jose"
import { writeFile } from "node:fs/promises"
assert.equal(process.env.OWN_EXTERNAL_PROCESS_PG, "true"); assert.equal(process.env.NODE_ENV, "test")
assert(process.env.OWN_EXTERNAL_SOURCE_ROOT && isAbsolute(process.env.OWN_EXTERNAL_SOURCE_ROOT))
assert(process.env.OWN_EXTERNAL_RESULT_FILE && isAbsolute(process.env.OWN_EXTERNAL_RESULT_FILE))
const source = (path: string) => pathToFileURL(resolve(process.env.OWN_EXTERNAL_SOURCE_ROOT!, "backend/src", path)).href
const database = new URL(process.env.DATABASE_URL ?? "")
assert.equal(database.hostname, "127.0.0.1"); assert.equal(database.username, "mcp_test"); assert.equal(database.pathname, "/postgres"); assert.notEqual(database.port, "5432")
const listener = createServer(); await new Promise<void>(r => listener.listen(0, "127.0.0.1", r)); const port = (listener.address() as { port: number }).port
await new Promise<void>(r => listener.close(() => r()))
const origin = `http://127.0.0.1:${port}`, endpoint = origin + "/mcp"
process.env.MCP_PUBLIC_URL = endpoint; process.env.MCP_UI_URL = origin; process.env.CORS_ORIGIN = origin
const { pool, closePool } = await import(source("db/index.js"))
const { applySqlMigrations } = await import(source("db/migrate.js"))
const { mcpConnectionCreateSchema } = await import("@mmapp/contracts/mcp")
const { createMcpConnection, rotateConnectionToken, setConnectionStatus, updateMcpSettings } = await import(source("modules/mcp/store.js"))
const { env } = await import(source("config.js"))
const { buildApp } = await import(source("index.js"))
const actor = { id: "owned-external-process-owner", email: "external@example.invalid", name: "Owned external SDK fixture", apps: ["mm"],
permissions: ["mm:settings:admin", "mm:mcp:admin", "mm:servers:admin"], expiresAt: Date.now() + 3600000, issuedAt: Date.now() - 1000 }
let currentId: string | undefined, app: Awaited<ReturnType<typeof buildApp>> | undefined, child: ReturnType<typeof spawn> | undefined
const credentials: string[] = []
const bridgePids = new Set<number>()
let childExit: Promise<number> | undefined
const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
function alive(pid: number) { try { process.kill(pid, 0); return true } catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error } }
async function drainChildAndBridges() {
if (child && child.exitCode === null && child.signalCode === null) { child.kill(); await Promise.race([childExit, delay(5000).then(() => { throw Error("Owned external child failed to exit") })]) }
const deadline = Date.now() + 5000
while ([...bridgePids].some(alive) && Date.now() < deadline) await delay(25)
const remaining = [...bridgePids].filter(alive)
for (const pid of remaining) process.kill(pid)
const killDeadline = Date.now() + 5000
while (remaining.some(alive) && Date.now() < killDeadline) await delay(25)
assert(!remaining.some(alive), "Owned SDK bridge grandchild failed to exit")
console.log("Owned client and all observed production bridge processes exited:", JSON.stringify({ childPid: child?.pid, exitCode: child?.exitCode, signalCode: child?.signalCode, bridgePids: [...bridgePids] }))
}
try {
await applySqlMigrations(pool)
for (const table of ["traffic_settings", "uptime_settings", "traffic_flow_settings", "servers_api_ping_settings", "certificate_renew_settings", "backup_schedule_settings", "geoip_settings", "internet_path_settings", "router_log_settings"]) await pool.query(`UPDATE ${table} SET enabled=false WHERE id=1`)
const secret = "OWNED_DEVICE_CREDENTIAL_MUST_NOT_ESCAPE"
const allowed = (await pool.query("INSERT INTO servers(name,host,enabled,password) VALUES('owned allowed','192.0.2.1',false,$1) RETURNING id", [secret])).rows[0].id
const forbidden = (await pool.query("INSERT INTO servers(name,host,enabled) VALUES('owned forbidden','192.0.2.2',false) RETURNING id")).rows[0].id
await updateMcpSettings({ enabled: true }, actor)
app = await buildApp({ startScheduler: false, logger: false }); await app.listen({ port, host: "127.0.0.1" })
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions: actor.permissions }).setProtectedHeader({ alg: "HS256" }).setIssuer(env.authIssuer).setIssuedAt().setExpirationTime("1h").sign(new TextEncoder().encode(env.jwtSecret))
const transcript: unknown[] = []; let failure: unknown, result: unknown
child = spawn(process.execPath, [fileURLToPath(new URL("./client.mjs", import.meta.url))], { cwd: process.cwd(), windowsHide: true, stdio: ["ignore", "pipe", "pipe", "ipc"],
env: { ...Object.fromEntries(["SystemRoot", "WINDIR", "TEMP", "TMP", "PATH", "Path"].filter(k => process.env[k]).map(k => [k, process.env[k]!])),
OWN_EXTERNAL_CLIENT: "true", OWN_MCP_ENDPOINT: endpoint, OWN_SERVER_PID: String(process.pid), OWN_ALLOWED_SERVER: String(allowed), OWN_FORBIDDEN_SERVER: String(forbidden),
OWN_BRIDGE_FILE: fileURLToPath(new URL(source("scripts/mcp-stdio.ts"))), OWN_PORTAL_JWT: jwt, OWN_SERVER_SECRET: secret, OWN_EXTERNAL_CLEANUP_FAULT: process.env.OWN_EXTERNAL_CLEANUP_FAULT } })
childExit = new Promise<number>(resolve => { child!.once("exit", status => resolve(status ?? 1)); child!.once("error", () => resolve(1)) })
let stderr = "", stdout = ""
child.stderr?.on("data", chunk => { stderr += String(chunk); if (stderr.length > 1048576) child?.kill() })
child.stdout?.on("data", chunk => { stdout += String(chunk); if (stdout.length > 1048576) child?.kill() })
child.on("message", async (raw: unknown) => {
const message = raw as { kind: string; command?: string; id?: number; pid?: number; result?: unknown; phase?: string; errorType?: string }
if (message.kind === "bridge-pid") { assert(Number.isSafeInteger(message.pid) && message.pid! > 0 && message.pid !== process.pid && message.pid !== child?.pid); bridgePids.add(message.pid!); return }
if (message.kind === "arm-cleanup-timeout" && process.env.OWN_EXTERNAL_CLEANUP_FAULT === "timeout") { setTimeout(() => { failure = { phase: "owned-deliberate-cleanup-timeout" }; child?.kill() }, 25); return }
if (message.kind === "result") { result = message.result; return }
if (message.kind === "failure") { failure = { phase: message.phase, errorType: message.errorType }; return }
if (message.kind !== "control" || !Number.isSafeInteger(message.id)) return
try {
let value: unknown
if (message.command === "new-connection") {
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Owned external SDK process", mode: "observer", expiresAt: new Date(Date.now() + 1200000).toISOString(),
permissions: ["mm:servers:read"], scope: { serverIds: [Number(allowed)], operationIds: ["servers.list"], allowGlobal: false }, limits: { callsPerMinute: 200 } }), actor)
currentId = issued.connection.id; credentials.push(issued.token); value = { token: issued.token, connectionId: currentId }
} else if (message.command === "large-result" || message.command === "reset-result") {
await pool.query("UPDATE servers SET comment=$2 WHERE id=$1", [allowed, message.command === "large-result" ? "Z".repeat(40000) + "OWNED_TRUNCATION_TAIL" : ""])
value = { ok: true }
} else {
assert(currentId)
if (message.command === "rotate") { const rotated = await rotateConnectionToken(currentId, actor); credentials.push(rotated.token); value = rotated }
else if (message.command === "pause" || message.command === "resume" || message.command === "revoke") { await setConnectionStatus(currentId, message.command === "pause" ? "paused" : message.command === "resume" ? "active" : "revoked", actor); value = { ok: true } }
else throw Error("Unsupported exact fixture control")
}
transcript.push({ command: message.command, connectionId: currentId })
child?.send({ kind: "reply", id: message.id, value })
} catch { child?.send({ kind: "reply", id: message.id, error: true }) }
})
const timer = setTimeout(() => { failure = { phase: "whole-external-client-deadline" }; child?.kill() }, 120000)
const code = await childExit; clearTimeout(timer)
if (code !== 0 || !result) { console.log("OWNED_EXTERNAL_PROCESS_FAILURE", JSON.stringify({ code, failure, stdout: stdout.slice(0,1000), stderr: stderr.slice(0,1000) })); throw Error("External SDK process did not complete") }
const logs = JSON.stringify((await pool.query("SELECT tool,input,result,error_code FROM mcp_requests ORDER BY created_at")).rows)
for (const token of [...credentials, jwt, secret]) { assert(!logs.includes(token)); assert(!stdout.includes(token)); assert(!stderr.includes(token)) }
const final = { ...(result as object), actualOwnPg: true, actualProductionHttpServer: true, serverFixturePid: process.pid,
controlTransitions: transcript, auditCredentialLeakAbsent: true, nativeRouterCalls: 0, productionDatabaseTouched: false }
await writeFile(process.env.OWN_EXTERNAL_RESULT_FILE!, JSON.stringify(final, null, 2))
console.log("Owned external process SDK result:", JSON.stringify(final))
} finally {
try { await drainChildAndBridges() } finally { try { if (app) await app.close() } finally { await closePool() } }
}