@abapify/adt-mcp 0.4.27 → 0.4.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/adt-mcp-http.mjs +1 -1
- package/dist/bin/adt-mcp.mjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{server-DjXoS9WZ.mjs → server-6B_nNmea.mjs} +4 -3
- package/dist/server-6B_nNmea.mjs.map +1 -0
- package/dist/{server-CnE2qNID.mjs → server-BMgXx1qL.mjs} +2 -2
- package/dist/{server-CnE2qNID.mjs.map → server-BMgXx1qL.mjs.map} +1 -1
- package/package.json +16 -16
- package/dist/server-DjXoS9WZ.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-CnE2qNID.mjs","names":["Buffer"],"sources":["../src/lib/session/registry.ts","../src/lib/http/multi-system.ts","../src/lib/http/oauth.ts","../src/lib/http/auth.ts","../src/lib/http/invocation.ts","../src/lib/http/cors.ts","../src/lib/http/server.ts"],"sourcesContent":["/**\n * In-memory session registry for the HTTP transport.\n *\n * The registry is intentionally simple: it stores `SapSessionContext`\n * instances keyed by MCP session id, tracks last-used timestamps, and\n * optionally evicts idle sessions after a TTL.\n *\n * Lifetime: a registry instance is process-scoped; it is created by the\n * HTTP bin and passed to `createMcpServer({ registry })`.\n */\n\nimport type { SapSessionContext } from './types.js';\n\nexport interface SessionRegistry {\n /**\n * Registers a new session. The caller provides everything except the\n * housekeeping fields (`createdAt`, `lastUsedAt`) and the idempotent\n * `close` handler, which is supplied as a separate argument so the\n * registry can wrap it for idempotency.\n */\n create(\n mcpSessionId: string,\n ctx: Omit<\n SapSessionContext,\n 'close' | 'createdAt' | 'lastUsedAt' | 'mcpSessionId'\n >,\n close: () => Promise<void>,\n ): SapSessionContext;\n get(mcpSessionId: string): SapSessionContext | undefined;\n touch(mcpSessionId: string): void;\n /** Removes the session and invokes its close handler. */\n delete(mcpSessionId: string): Promise<void>;\n list(): SapSessionContext[];\n /** Closes every session and stops background timers. */\n shutdown(): Promise<void>;\n}\n\nexport interface SessionRegistryOptions {\n /**\n * Idle TTL in milliseconds. Sessions with `now - lastUsedAt > ttlMs`\n * are evicted by a background sweep. Defaults to 30 minutes.\n * Set to 0 to disable TTL sweeping.\n */\n ttlMs?: number;\n /** Sweep interval in ms. Defaults to `min(ttlMs / 4, 60_000)`. */\n sweepIntervalMs?: number;\n}\n\nconst DEFAULT_TTL_MS = 30 * 60 * 1000;\n\nexport function createSessionRegistry(\n options: SessionRegistryOptions = {},\n): SessionRegistry {\n const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;\n const sessions = new Map<string, SapSessionContext>();\n let sweepTimer: NodeJS.Timeout | undefined;\n\n const wrapClose = (close: () => Promise<void>): (() => Promise<void>) => {\n let closed = false;\n return async () => {\n if (closed) return;\n closed = true;\n await close();\n };\n };\n\n const registry: SessionRegistry = {\n create(mcpSessionId, ctx, close) {\n const now = Date.now();\n const session: SapSessionContext = {\n mcpSessionId,\n createdAt: now,\n lastUsedAt: now,\n ...ctx,\n close: wrapClose(close),\n };\n sessions.set(mcpSessionId, session);\n return session;\n },\n get(mcpSessionId) {\n return sessions.get(mcpSessionId);\n },\n touch(mcpSessionId) {\n const s = sessions.get(mcpSessionId);\n if (s) s.lastUsedAt = Date.now();\n },\n async delete(mcpSessionId) {\n const s = sessions.get(mcpSessionId);\n if (!s) return;\n sessions.delete(mcpSessionId);\n try {\n await s.close();\n } catch {\n // best-effort cleanup; registry must not throw on delete\n }\n },\n list() {\n return Array.from(sessions.values());\n },\n async shutdown() {\n if (sweepTimer) {\n clearInterval(sweepTimer);\n sweepTimer = undefined;\n }\n const ids = Array.from(sessions.keys());\n await Promise.allSettled(ids.map((id) => registry.delete(id)));\n },\n };\n\n if (ttlMs > 0) {\n const interval =\n options.sweepIntervalMs ?? Math.min(Math.floor(ttlMs / 4), 60_000);\n sweepTimer = setInterval(\n () => {\n const cutoff = Date.now() - ttlMs;\n for (const s of sessions.values()) {\n if (s.lastUsedAt < cutoff) {\n void registry.delete(s.mcpSessionId);\n }\n }\n },\n Math.max(1000, interval),\n );\n // Don't hold the event loop open just for the sweeper.\n sweepTimer.unref?.();\n }\n\n return registry;\n}\n","/**\n * Multi-system configuration loader for adt-mcp HTTP transport.\n *\n * Resolves a logical system id (e.g. `DEV`, `PROD`) to concrete ADT\n * connection parameters. Sources (priority order):\n *\n * 1. `SAP_SYSTEMS_JSON` env var — inline JSON object\n * `{ \"DEV\": { \"baseUrl\": \"...\", \"client\": \"100\" }, ... }`\n * 2. `SAP_SYSTEMS_FILE` env var — path to a JSON file (YAML is NOT\n * supported in this wave to avoid adding new runtime deps).\n * 3. `~/.adt/systems.json` — default JSON file (YAML is NOT supported).\n *\n * Missing/empty config yields an empty registry, and `resolve()` returns\n * `undefined` for every id.\n *\n * Security policy: the registry holds ONLY connection metadata\n * (`baseUrl`, `client`). Credentials (`username`, `password`) MUST come\n * from the `sap_connect` tool call at runtime, never from disk. Any\n * `username`/`password` fields present in the JSON are silently dropped\n * with a warning so secrets-in-config mistakes don't leak.\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { ConnectionParams } from '../types.js';\n\nexport interface SystemEntry {\n baseUrl: string;\n client?: string;\n}\n\nexport interface MultiSystemConfig {\n systems: Record<string, SystemEntry>;\n resolve(systemId: string): ConnectionParams | undefined;\n}\n\ntype RawConfig = Record<\n string,\n { baseUrl?: string; client?: string; username?: unknown; password?: unknown }\n>;\n\nfunction parseJsonSafe(raw: string, source: string): RawConfig {\n try {\n const value = JSON.parse(raw);\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`expected a JSON object, got ${typeof value}`);\n }\n return value as RawConfig;\n } catch (err) {\n throw new Error(\n `Failed to parse multi-system config from ${source}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n}\n\nfunction normalise(raw: RawConfig): Record<string, SystemEntry> {\n const out: Record<string, SystemEntry> = {};\n for (const [id, entry] of Object.entries(raw)) {\n if (!entry || typeof entry !== 'object') continue;\n if (typeof entry.baseUrl !== 'string' || entry.baseUrl.length === 0) {\n continue;\n }\n if (entry.username || entry.password) {\n // Defence against secrets in disk config. Keep the system entry\n // but drop the credentials — caller must supply them at runtime.\n process.stderr.write(\n `[multi-system] warning: system '${id}' contains credentials ` +\n `in config; dropping them. Pass credentials via sap_connect at runtime.\\n`,\n );\n }\n out[id] = {\n baseUrl: entry.baseUrl,\n client: entry.client,\n };\n }\n return out;\n}\n\nexport function loadMultiSystemConfig(): MultiSystemConfig {\n let raw: RawConfig | undefined;\n\n if (process.env.SAP_SYSTEMS_JSON) {\n raw = parseJsonSafe(process.env.SAP_SYSTEMS_JSON, 'SAP_SYSTEMS_JSON');\n } else {\n const explicit = process.env.SAP_SYSTEMS_FILE;\n const defaultPath = join(homedir(), '.adt', 'systems.json');\n const path = explicit && explicit.length > 0 ? explicit : defaultPath;\n if (existsSync(path)) {\n raw = parseJsonSafe(readFileSync(path, 'utf8'), path);\n }\n }\n\n const systems = raw ? normalise(raw) : {};\n\n return {\n systems,\n resolve(systemId: string): ConnectionParams | undefined {\n const entry = systems[systemId];\n if (!entry) return undefined;\n return {\n baseUrl: entry.baseUrl,\n client: entry.client,\n };\n },\n };\n}\n","/**\n * OAuth 2.1 / OIDC bearer-token validator for the adt-mcp HTTP transport.\n *\n * adt-mcp is an MCP *resource server*, not an authorization server — we\n * only **validate** JWTs issued by an external IdP (Okta, Microsoft Entra\n * ID, AWS Cognito, Keycloak, Auth0, …). We do not issue tokens ourselves.\n *\n * Validation steps (per RFC 7519 + RFC 8725 + OAuth 2.1 Section 5.2):\n * 1. Extract `Authorization: Bearer <jwt>` (caller's responsibility).\n * 2. Fetch the JWKS for the configured `issuer`:\n * - If `jwksUri` is provided, use it directly.\n * - Otherwise discover via `${issuer}/.well-known/openid-configuration`.\n * 3. Verify signature + `iss` + `aud` + `exp`/`nbf` (with clock skew).\n * 4. Optionally enforce `requiredScopes` against the token's\n * `scope` (RFC 8693) or `scp` (Entra ID) claim.\n * 5. Extract a stable user identity from a configurable claim\n * (default chain: `preferred_username` → `email` → `sub`).\n *\n * The validator is stateless from the caller's perspective but internally\n * caches the JWKS (jose's `createRemoteJWKSet`) and the OIDC discovery\n * document for one hour.\n *\n * On failure the validator returns `{ valid: false, error }` — it never\n * throws. Callers translate that into an RFC 6750 401 response.\n */\n\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { JWTPayload } from 'jose';\nimport type { UserHint } from './auth.js';\n\nexport interface OAuthOptions {\n /** Expected `iss` claim, e.g. `https://company.okta.com/oauth2/default`. */\n issuer: string;\n /** Expected `aud` claim(s). Strongly recommended. */\n audience?: string | string[];\n /** Explicit JWKS endpoint; falls back to OIDC discovery when absent. */\n jwksUri?: string;\n /**\n * Scopes that must be present in the token's `scope`/`scp` claim. All\n * listed scopes are required (AND).\n */\n requiredScopes?: string[];\n /** Clock skew tolerance in seconds. Default 5. */\n clockTolerance?: number;\n /**\n * Primary claim to use as the user identity. When absent the validator\n * falls back to `preferred_username` → `email` → `sub`.\n */\n userClaim?: string;\n /** Claim to read as the user email. Default `email`. */\n emailClaim?: string;\n /** Claim to read as the groups array. Default `groups`. */\n groupsClaim?: string;\n}\n\nexport interface OAuthValidationResult {\n valid: boolean;\n claims?: JWTPayload;\n userHint?: UserHint;\n error?: string;\n}\n\nexport type OAuthValidator = (token: string) => Promise<OAuthValidationResult>;\n\ninterface DiscoveryDoc {\n issuer?: string;\n jwks_uri?: string;\n [key: string]: unknown;\n}\n\nconst DISCOVERY_TTL_MS = 60 * 60 * 1000; // 1 hour\n\ninterface DiscoveryCacheEntry {\n fetchedAt: number;\n doc: DiscoveryDoc;\n}\n\nconst discoveryCache = new Map<string, DiscoveryCacheEntry>();\n\nfunction trimTrailingSlash(s: string): string {\n return s.endsWith('/') ? s.slice(0, -1) : s;\n}\n\nasync function fetchDiscovery(issuer: string): Promise<DiscoveryDoc> {\n const now = Date.now();\n const cached = discoveryCache.get(issuer);\n if (cached && now - cached.fetchedAt < DISCOVERY_TTL_MS) {\n return cached.doc;\n }\n const url = `${trimTrailingSlash(issuer)}/.well-known/openid-configuration`;\n const res = await fetch(url, {\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) {\n throw new Error(\n `OIDC discovery failed for ${issuer}: HTTP ${res.status} ${res.statusText}`,\n );\n }\n const doc = (await res.json()) as DiscoveryDoc;\n if (!doc.jwks_uri || typeof doc.jwks_uri !== 'string') {\n throw new Error(\n `OIDC discovery document for ${issuer} is missing jwks_uri`,\n );\n }\n discoveryCache.set(issuer, { fetchedAt: now, doc });\n return doc;\n}\n\n/**\n * Extract the list of scopes from a token payload. Supports both the\n * OAuth 2.0 `scope` string claim (space-delimited) and the Entra ID\n * `scp` claim (string or array).\n */\nfunction extractScopes(claims: JWTPayload): string[] {\n const scope = (claims as Record<string, unknown>)['scope'];\n const scp = (claims as Record<string, unknown>)['scp'];\n const parts: string[] = [];\n if (typeof scope === 'string') {\n parts.push(\n ...scope\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s.length > 0),\n );\n }\n if (typeof scp === 'string') {\n parts.push(\n ...scp\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s.length > 0),\n );\n } else if (Array.isArray(scp)) {\n for (const v of scp) {\n if (typeof v === 'string' && v.length > 0) parts.push(v);\n }\n }\n return parts;\n}\n\nfunction extractUserHint(\n claims: JWTPayload,\n userClaim: string | undefined,\n emailClaim: string,\n groupsClaim: string,\n): UserHint | undefined {\n const record = claims as Record<string, unknown>;\n let user: string | undefined;\n if (userClaim) {\n const v = record[userClaim];\n if (typeof v === 'string' && v.length > 0) user = v;\n }\n if (!user) {\n for (const c of ['preferred_username', 'email', 'sub']) {\n const v = record[c];\n if (typeof v === 'string' && v.length > 0) {\n user = v;\n break;\n }\n }\n }\n if (!user) return undefined;\n\n const emailRaw = record[emailClaim];\n const email = typeof emailRaw === 'string' ? emailRaw : undefined;\n\n const groupsRaw = record[groupsClaim];\n let groups: string[] | undefined;\n if (Array.isArray(groupsRaw)) {\n groups = groupsRaw.filter((v): v is string => typeof v === 'string');\n } else if (typeof groupsRaw === 'string' && groupsRaw.length > 0) {\n groups = groupsRaw\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n return { user, email, groups };\n}\n\n/**\n * Build an OAuth/JWT validator for the configured issuer. Throws\n * synchronously on invalid options (e.g. missing issuer).\n */\nexport function createOAuthValidator(opts: OAuthOptions): OAuthValidator {\n if (!opts.issuer || opts.issuer.length === 0) {\n throw new Error('createOAuthValidator: `issuer` is required');\n }\n const issuer = opts.issuer;\n const audience = opts.audience;\n const requiredScopes = opts.requiredScopes ?? [];\n const clockTolerance = opts.clockTolerance ?? 5;\n const userClaim = opts.userClaim;\n const emailClaim = opts.emailClaim ?? 'email';\n const groupsClaim = opts.groupsClaim ?? 'groups';\n\n // JWKS URL may be known up-front (explicit config) or resolved lazily\n // from the discovery document. We cache the `createRemoteJWKSet` result\n // per URL so jose's internal key cache is reused across calls.\n let staticJwks: ReturnType<typeof createRemoteJWKSet> | undefined;\n if (opts.jwksUri) {\n staticJwks = createRemoteJWKSet(new URL(opts.jwksUri));\n }\n\n const resolvedJwks = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\n async function getJwks(): Promise<ReturnType<typeof createRemoteJWKSet>> {\n if (staticJwks) return staticJwks;\n const doc = await fetchDiscovery(issuer);\n const uri = doc.jwks_uri as string;\n let jwks = resolvedJwks.get(uri);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(uri));\n resolvedJwks.set(uri, jwks);\n }\n return jwks;\n }\n\n return async (token: string): Promise<OAuthValidationResult> => {\n if (!token || token.length === 0) {\n return { valid: false, error: 'missing_token' };\n }\n\n let jwks: ReturnType<typeof createRemoteJWKSet>;\n try {\n jwks = await getJwks();\n } catch (err) {\n return {\n valid: false,\n error: `discovery_failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n\n let payload: JWTPayload;\n try {\n const verified = await jwtVerify(token, jwks, {\n issuer,\n audience,\n clockTolerance,\n });\n payload = verified.payload;\n } catch (err) {\n return {\n valid: false,\n error: `invalid_token: ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n\n if (requiredScopes.length > 0) {\n const scopes = new Set(extractScopes(payload));\n const missing = requiredScopes.filter((s) => !scopes.has(s));\n if (missing.length > 0) {\n return {\n valid: false,\n claims: payload,\n error: `insufficient_scope: missing ${missing.join(', ')}`,\n };\n }\n }\n\n const userHint = extractUserHint(\n payload,\n userClaim,\n emailClaim,\n groupsClaim,\n );\n\n return { valid: true, claims: payload, userHint };\n };\n}\n\n/**\n * Test-only helper: reset the discovery cache. Not part of the public API.\n * @internal\n */\nexport function __resetOAuthDiscoveryCacheForTests(): void {\n discoveryCache.clear();\n}\n","/**\n * Auth middleware for the adt-mcp HTTP transport.\n *\n * Five modes:\n * - `none` — no authentication (dev / behind already-authenticated transport).\n * - `bearer` — require `Authorization: Bearer <token>` where `<token>` matches\n * the configured secret. Compared with `crypto.timingSafeEqual`.\n * - `proxy` — trust a reverse proxy (e.g. oauth2-proxy, Cloudflare Access).\n * Requires a non-empty `x-forwarded-user` header. Additional\n * identity hints (`x-forwarded-email`, `x-forwarded-groups`) are\n * collected into the returned `userHint`.\n * - `oauth` — validate an OIDC-issued JWT (Okta, Entra ID, Cognito, …)\n * against the configured issuer + audience + scopes. See\n * `./oauth.ts` for the validator implementation.\n * - `invocation` — validate an ADT-issued ES256 invocation credential and\n * surface only its immutable, trusted claims to the transport.\n *\n * The middleware writes a 401 JSON response on failure and returns\n * `{ allowed: false }`. The caller should stop processing. On success it\n * returns `{ allowed: true, userHint? }`; the caller may propagate the hint\n * to tool context for audit / per-user lock tracking.\n */\nimport http from 'node:http';\nimport { Buffer } from 'node:buffer';\nimport { timingSafeEqual } from 'node:crypto';\nimport { createOAuthValidator, type OAuthOptions } from './oauth.js';\nimport type {\n McpInvocationVerifier,\n TrustedMcpInvocationClaims,\n} from './invocation.js';\n\nexport type AuthMode = 'none' | 'bearer' | 'proxy' | 'oauth' | 'invocation';\n\nexport interface AuthMiddlewareOptions {\n mode: AuthMode;\n /** Required when mode==='bearer'. The expected bearer token secret. */\n token?: string;\n /** Required when mode==='oauth'. OIDC issuer / audience / scopes. */\n oauth?: OAuthOptions;\n /** Required when mode==='invocation'. ADT ES256 credential verifier. */\n invocationVerifier?: McpInvocationVerifier;\n /**\n * Test-only hook: invoked synchronously whenever an OAuth request\n * successfully authenticates, with the derived user hint. Production\n * code uses the normal `userHint` return value instead.\n * @internal\n */\n onUserHint?: (hint: UserHint | undefined) => void;\n}\n\nexport interface UserHint {\n user: string;\n email?: string;\n groups?: string[];\n}\n\nexport interface AuthResult {\n allowed: boolean;\n userHint?: UserHint;\n /** Immutable claims supplied only by a successful invocation verifier. */\n invocation?: TrustedMcpInvocationClaims;\n}\n\nexport type AuthMiddleware = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n) => AuthResult | Promise<AuthResult>;\n\nfunction writeUnauthorized(\n res: http.ServerResponse,\n oauthError?: string,\n): void {\n if (res.headersSent) {\n try {\n res.end();\n } catch {\n // ignore\n }\n return;\n }\n // RFC 6750 §3: the WWW-Authenticate challenge for bearer tokens. For\n // OAuth failures we include the standard `error` / `error_description`\n // parameters so clients can distinguish \"no token\", \"invalid token\",\n // and \"insufficient scope\".\n const challenge = oauthError\n ? `Bearer realm=\"adt-mcp\", error=\"${oauthError.split(':')[0].trim()}\", error_description=\"${oauthError.replaceAll('\"', \"'\")}\"`\n : 'Bearer realm=\"adt-mcp\"';\n res.writeHead(401, {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': challenge,\n });\n res.end(JSON.stringify({ error: oauthError ?? 'unauthorized' }));\n}\n\nfunction constantTimeEqualString(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n // Pad the shorter buffer so both are equal length (required for\n // timingSafeEqual). Any length mismatch is still caught by the\n // final equality check.\n const len = Math.max(ab.length, bb.length);\n const ap = Buffer.alloc(len);\n const bp = Buffer.alloc(len);\n ab.copy(ap);\n bb.copy(bp);\n const eq = timingSafeEqual(ap, bp);\n return eq && ab.length === bb.length;\n}\n\nfunction extractBearer(req: http.IncomingMessage): string | undefined {\n const h = req.headers['authorization'];\n const value = Array.isArray(h) ? h[0] : h;\n if (!value) return undefined;\n const trimmed = value.trim();\n // Case-insensitive \"Bearer\" prefix check without regex to avoid ReDoS.\n if (trimmed.length < 7) return undefined;\n const prefix = trimmed.slice(0, 6);\n if (prefix.toLowerCase() !== 'bearer') return undefined;\n // Skip a single required whitespace char, then any leading whitespace.\n const rest = trimmed.slice(6);\n if (rest.length === 0) return undefined;\n const first = rest.charCodeAt(0);\n // ASCII whitespace: space, tab, LF, CR, VT, FF.\n const isWs =\n first === 0x20 ||\n first === 0x09 ||\n first === 0x0a ||\n first === 0x0d ||\n first === 0x0b ||\n first === 0x0c;\n if (!isWs) return undefined;\n const token = rest.trimStart();\n return token.length > 0 ? token : undefined;\n}\n\nfunction headerString(\n req: http.IncomingMessage,\n name: string,\n): string | undefined {\n const raw = req.headers[name.toLowerCase()];\n if (!raw) return undefined;\n const value = Array.isArray(raw) ? raw[0] : raw;\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Build the auth middleware for the configured mode. Throws at creation\n * time for misconfiguration (e.g. `bearer` mode with no token).\n */\nexport function createAuthMiddleware(\n options: AuthMiddlewareOptions,\n): AuthMiddleware {\n if (options.mode === 'bearer') {\n if (!options.token || options.token.length === 0) {\n throw new Error(\n 'createAuthMiddleware: bearer mode requires a non-empty token',\n );\n }\n const expected = options.token;\n return (req, res) => {\n const presented = extractBearer(req);\n if (!presented || !constantTimeEqualString(presented, expected)) {\n writeUnauthorized(res);\n return { allowed: false };\n }\n return { allowed: true };\n };\n }\n\n if (options.mode === 'proxy') {\n return (req, res) => {\n const user = headerString(req, 'x-forwarded-user');\n if (!user) {\n writeUnauthorized(res);\n return { allowed: false };\n }\n const email = headerString(req, 'x-forwarded-email');\n const groupsRaw = headerString(req, 'x-forwarded-groups');\n const groups = groupsRaw\n ? groupsRaw\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0)\n : undefined;\n return { allowed: true, userHint: { user, email, groups } };\n };\n }\n\n if (options.mode === 'oauth') {\n if (!options.oauth) {\n throw new Error(\n 'createAuthMiddleware: oauth mode requires an `oauth` option',\n );\n }\n const validator = createOAuthValidator(options.oauth);\n const onUserHint = options.onUserHint;\n return async (req, res) => {\n const presented = extractBearer(req);\n if (!presented) {\n writeUnauthorized(res, 'invalid_token: missing bearer token');\n return { allowed: false };\n }\n const result = await validator(presented);\n if (!result.valid) {\n // Map to RFC 6750 error codes. `insufficient_scope` must remain\n // a distinct category so the client knows the user needs a\n // re-consent, not a re-login.\n const err = result.error ?? 'invalid_token';\n writeUnauthorized(res, err);\n return { allowed: false };\n }\n if (onUserHint) onUserHint(result.userHint);\n return { allowed: true, userHint: result.userHint };\n };\n }\n\n if (options.mode === 'invocation') {\n if (!options.invocationVerifier) {\n throw new Error(\n 'createAuthMiddleware: invocation mode requires an invocation verifier',\n );\n }\n const verifier = options.invocationVerifier;\n return async (req, res) => {\n const invocation = await verifier.verify(req.headers.authorization);\n if (!invocation) {\n // Do not expose verifier failures, decoded claims, or a distinction\n // between a missing, expired, or invalid credential.\n writeUnauthorized(res, 'invalid_token');\n return { allowed: false };\n }\n return { allowed: true, invocation };\n };\n }\n\n // mode === 'none'\n return () => ({ allowed: true });\n}\n","/**\n * Verification for ADT-issued MCP invocation credentials.\n *\n * This module is deliberately transport-independent: callers pass the\n * complete Authorization header and receive either immutable, trusted claims\n * or `undefined`. It does not log or throw token-validation failures, so a\n * bearer credential or its decoded payload can never leak through an error.\n */\nimport type { KeyObject } from 'node:crypto';\nimport { jwtVerify, type CryptoKey, type JWTPayload } from 'jose';\n\nconst INVOCATION_VERSION = 1;\nconst MAX_IDENTIFIER_LENGTH = 256;\nconst MAX_COMPONENT_IDENTIFIER_LENGTH = 512;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_TOKEN_LIFETIME_SECONDS = 5 * 60;\nconst MAX_FROZEN_SOURCES = 500;\nconst MAX_SOURCE_REFERENCE_LENGTH = 8 * 1024;\nconst MAX_FROZEN_SOURCE_BYTES = 2 * 1024 * 1024;\nconst MAX_SCOPED_OBJECT_KEYS = 100;\nconst MAX_SCOPED_TOOL_CALLS = 12;\nconst MAX_SAFE_EXECUTE_GRANT_BYTES = 16 * 1024;\nconst destinationKeyPattern = /^[a-z][a-z0-9-]{1,62}$/u;\nconst canonicalKeyPattern = /^[A-Z0-9_]+:.+$/u;\nconst scopedCanonicalObjectKeyPattern =\n /^[A-Z0-9_]{2,30}:[A-Z0-9_/$-]{1,128}$/u;\nconst compactJwsPattern = /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/u;\nconst uuidPattern =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nconst trustedAgentIds = new Set([\n 'ai-review',\n 'system-assistant',\n 'autonomous-review-agent',\n 'adt-execution',\n 'delegated-assistant',\n]);\nconst trustedOperationClasses = new Set(['server', 'read', 'safe_execute']);\nconst scopedReadTools = new Set(['get_object', 'get_object_structure']);\n\nexport type McpTrustedOperationClass = 'server' | 'read' | 'safe_execute';\n\nexport type McpInvocationJsonValue =\n | boolean\n | number\n | string\n | null\n | readonly McpInvocationJsonValue[]\n | Readonly<Record<string, McpInvocationJsonValue>>;\n\n/** Claims proved by a verified, ADT-issued invocation credential. */\nexport interface TrustedMcpInvocationClaims {\n readonly tokenId: string;\n readonly principal: string;\n readonly agentId:\n | 'ai-review'\n | 'system-assistant'\n | 'autonomous-review-agent'\n | 'adt-execution'\n | 'delegated-assistant';\n readonly classes: readonly McpTrustedOperationClass[];\n readonly destinationKeys: readonly string[];\n readonly correlationId: string;\n readonly constraint: Readonly<Record<string, McpInvocationJsonValue>>;\n readonly limits: Readonly<Record<string, McpInvocationJsonValue>>;\n}\n\n/**\n * Fully enforced narrowing policy for an AI Review source read. `sourceRef`\n * remains opaque to MCP clients and models; only ADT's private broker can\n * redeem it after this policy has selected the exact canonical object and\n * source component.\n */\nexport interface AiReviewFrozenSourcePolicy {\n readonly reviewId: string;\n readonly runId: string;\n readonly systemSid: string;\n readonly sources: readonly {\n readonly canonicalKey: string;\n readonly componentId: string;\n readonly sourceRef: string;\n }[];\n readonly maxSourceBytes: number;\n}\n\nexport type SafeExecutePolicy =\n | {\n readonly operationId: 'atc_run';\n readonly check: 'atc';\n readonly maxDurationMs: number;\n readonly maxResultBytes: number;\n readonly maxFindings: number;\n readonly maxObjects: number;\n readonly maxPackages: number;\n readonly maxVariants: number;\n }\n | {\n readonly operationId: 'run_unit_tests';\n readonly check: 'aunit';\n readonly effectiveWithCoverage: false;\n readonly effectiveCoverageFormat: null;\n readonly maxDurationMs: number;\n readonly maxResultBytes: number;\n readonly maxFindings: number;\n readonly maxObjects: number;\n readonly maxTestClasses: number;\n readonly maxTestMethods: number;\n }\n | {\n readonly operationId: 'run_unit_tests';\n readonly check: 'coverage';\n readonly effectiveWithCoverage: true;\n readonly effectiveCoverageFormat: 'jacoco' | 'sonar-generic';\n readonly maxDurationMs: number;\n readonly maxResultBytes: number;\n readonly maxFindings: number;\n readonly maxObjects: number;\n readonly maxPrograms: number;\n readonly maxMeasurements: number;\n };\n\nexport interface ScopedAdtInvocationPolicy {\n readonly scopeId: string;\n readonly executionId: string;\n readonly systemSid: string;\n readonly resourceKeys: readonly string[];\n readonly toolNames: readonly string[];\n readonly operationClass: 'read' | 'safe_execute';\n readonly maxToolCalls: number;\n readonly safeExecutePolicy?: SafeExecutePolicy;\n /** Server-owned opaque grant material; never exposed in a tool schema. */\n readonly authorizationId?: string;\n readonly authorizationToken?: string;\n}\n\nexport interface DelegatedAssistantReadPolicy {\n readonly threadId: string;\n readonly executionId: string;\n readonly systemSid: string;\n}\n\nexport interface McpInvocationVerifierOptions {\n /** ES256 public key mounted at ADT Server; it cannot issue credentials. */\n publicKey: CryptoKey | KeyObject;\n /** The exact key id required in both JWS header and JWT payload. */\n keyId: string;\n /** The exact ADT API issuer expected in `iss`. */\n issuer: string;\n /** The exact audience expected in `aud`. */\n audience: string;\n /** Test-only clock injection. Production defaults to the current time. */\n now?: () => Date | number;\n}\n\nexport interface McpInvocationVerifier {\n /**\n * Verify a complete `Authorization: Bearer <JWS>` header. Validation\n * failures are intentionally indistinguishable and return `undefined`.\n */\n verify(\n authorizationHeader: string | string[] | undefined,\n ): Promise<TrustedMcpInvocationClaims | undefined>;\n}\n\n/**\n * Reports whether this sidecar version can enforce every narrowing claim for\n * an invocation. Unsupported policies deliberately receive no MCP tool\n * access; accepting a syntactically valid policy without enforcing it would\n * widen the signed credential.\n *\n * Every admitted policy has an exact parser. Structurally incomplete or\n * unknown policies fail closed.\n */\nfunction isSystemAssistantPolicySupported(\n claims: TrustedMcpInvocationClaims,\n): boolean {\n if (\n !hasServerReadClasses(claims) ||\n Object.keys(claims.limits).length !== 0\n ) {\n return false;\n }\n const constraintKeys = Object.keys(claims.constraint);\n return (\n constraintKeys.length === 1 &&\n constraintKeys[0] === 'systemSid' &&\n requiredIdentifier(claims.constraint.systemSid) !== undefined\n );\n}\n\nfunction hasServerReadClasses(claims: TrustedMcpInvocationClaims): boolean {\n return (\n claims.classes.length === 2 &&\n claims.classes.includes('server') &&\n claims.classes.includes('read')\n );\n}\n\nexport function parseDelegatedAssistantReadPolicy(\n claims: TrustedMcpInvocationClaims,\n): DelegatedAssistantReadPolicy | undefined {\n if (\n claims.agentId !== 'delegated-assistant' ||\n claims.destinationKeys.length !== 1 ||\n !hasServerReadClasses(claims) ||\n Object.keys(claims.limits).length !== 0 ||\n !hasExactSortedKeys(claims.constraint, [\n 'kind',\n 'threadId',\n 'executionId',\n 'systemSid',\n ]) ||\n claims.constraint.kind !== 'delegated-assistant-read-v1'\n ) {\n return undefined;\n }\n\n const threadId = requiredUuid(claims.constraint.threadId);\n const executionId = requiredUuid(claims.constraint.executionId);\n const systemSid = requiredSystemSid(claims.constraint.systemSid);\n if (!threadId || !executionId || !systemSid) return undefined;\n\n return Object.freeze({ threadId, executionId, systemSid });\n}\n\nexport function isMcpInvocationDispatchPolicySupported(\n claims: TrustedMcpInvocationClaims,\n): boolean {\n if (claims.agentId === 'system-assistant') {\n return isSystemAssistantPolicySupported(claims);\n }\n if (claims.agentId === 'autonomous-review-agent') {\n return (\n hasServerReadClasses(claims) &&\n claims.destinationKeys.length === 1 &&\n parseAutonomousReviewAgentPolicy(claims) !== undefined\n );\n }\n if (claims.agentId === 'adt-execution') {\n return parseScopedAdtInvocationPolicy(claims) !== undefined;\n }\n if (claims.agentId === 'delegated-assistant') {\n return parseDelegatedAssistantReadPolicy(claims) !== undefined;\n }\n if (claims.agentId === 'ai-review') {\n return (\n hasServerReadClasses(claims) &&\n claims.destinationKeys.length === 1 &&\n parseAiReviewFrozenSourcePolicy(claims) !== undefined\n );\n }\n return false;\n}\n\n/**\n * The autonomous agent may inspect exactly one System through exactly one\n * Destination. Its execution id binds every ADT activity to ADT's durable\n * Agent Execution, while the sidecar's ordinary scope catalogue continues to\n * deny write tools. No ambient limits or additional constraints are accepted.\n */\nexport function parseAutonomousReviewAgentPolicy(\n claims: TrustedMcpInvocationClaims,\n): { readonly executionId: string; readonly systemSid: string } | undefined {\n if (claims.agentId !== 'autonomous-review-agent') return undefined;\n if (Object.keys(claims.limits).length !== 0) return undefined;\n const constraintKeys = Object.keys(claims.constraint).sort((a, b) =>\n a.localeCompare(b),\n );\n if (constraintKeys.length !== 2) return undefined;\n if (constraintKeys[0] !== 'executionId') return undefined;\n if (constraintKeys[1] !== 'systemSid') return undefined;\n const executionId = requiredUuid(claims.constraint.executionId);\n const systemSid = requiredSystemSid(claims.constraint.systemSid);\n if (!executionId || !systemSid) return undefined;\n return Object.freeze({ executionId, systemSid });\n}\n\nfunction requiredUuid(value: unknown): string | undefined {\n return typeof value === 'string' && uuidPattern.test(value)\n ? value\n : undefined;\n}\n\nfunction requiredSourceReference(value: unknown): string | undefined {\n return requiredString(value, { maxLength: MAX_SOURCE_REFERENCE_LENGTH });\n}\n\nfunction hasExactSortedKeys(\n value: Readonly<Record<string, unknown>>,\n expected: readonly string[],\n): boolean {\n const actual = Object.keys(value).sort((left, right) =>\n left.localeCompare(right),\n );\n const sortedExpected = [...expected].sort((left, right) =>\n left.localeCompare(right),\n );\n return (\n actual.length === sortedExpected.length &&\n actual.every((key, index) => key === sortedExpected[index])\n );\n}\n\nfunction positiveSafeInteger(value: unknown): number | undefined {\n return Number.isSafeInteger(value) && (value as number) > 0\n ? (value as number)\n : undefined;\n}\n\nfunction parseSafeExecuteCommon(\n value: Readonly<Record<string, McpInvocationJsonValue>>,\n):\n | {\n maxDurationMs: number;\n maxResultBytes: number;\n maxFindings: number;\n maxObjects: number;\n }\n | undefined {\n const maxDurationMs = positiveSafeInteger(value.maxDurationMs);\n const maxResultBytes = positiveSafeInteger(value.maxResultBytes);\n const maxFindings = positiveSafeInteger(value.maxFindings);\n const maxObjects = positiveSafeInteger(value.maxObjects);\n if (\n maxDurationMs === undefined ||\n maxResultBytes === undefined ||\n maxFindings === undefined ||\n maxObjects === undefined\n ) {\n return undefined;\n }\n return { maxDurationMs, maxResultBytes, maxFindings, maxObjects };\n}\n\nconst safeExecuteCommonKeys = [\n 'operationId',\n 'check',\n 'maxDurationMs',\n 'maxResultBytes',\n 'maxFindings',\n 'maxObjects',\n] as const;\n\nfunction parseAtcSafeExecutePolicy(\n cloned: Record<string, McpInvocationJsonValue>,\n common: ReturnType<typeof parseSafeExecuteCommon>,\n): SafeExecutePolicy | undefined {\n if (!common) return undefined;\n if (\n cloned.operationId !== 'atc_run' ||\n cloned.check !== 'atc' ||\n !hasExactSortedKeys(cloned, [\n ...safeExecuteCommonKeys,\n 'maxPackages',\n 'maxVariants',\n ])\n ) {\n return undefined;\n }\n const maxPackages = positiveSafeInteger(cloned.maxPackages);\n const maxVariants = positiveSafeInteger(cloned.maxVariants);\n if (maxPackages === undefined || maxVariants === undefined) {\n return undefined;\n }\n return Object.freeze({\n operationId: 'atc_run',\n check: 'atc',\n ...common,\n maxPackages,\n maxVariants,\n });\n}\n\nfunction parseAunitSafeExecutePolicy(\n cloned: Record<string, McpInvocationJsonValue>,\n common: ReturnType<typeof parseSafeExecuteCommon>,\n): SafeExecutePolicy | undefined {\n if (!common) return undefined;\n if (\n cloned.operationId !== 'run_unit_tests' ||\n cloned.check !== 'aunit' ||\n cloned.effectiveWithCoverage !== false ||\n cloned.effectiveCoverageFormat !== null ||\n !hasExactSortedKeys(cloned, [\n ...safeExecuteCommonKeys,\n 'effectiveWithCoverage',\n 'effectiveCoverageFormat',\n 'maxTestClasses',\n 'maxTestMethods',\n ])\n ) {\n return undefined;\n }\n const maxTestClasses = positiveSafeInteger(cloned.maxTestClasses);\n const maxTestMethods = positiveSafeInteger(cloned.maxTestMethods);\n if (maxTestClasses === undefined || maxTestMethods === undefined) {\n return undefined;\n }\n return Object.freeze({\n operationId: 'run_unit_tests',\n check: 'aunit',\n effectiveWithCoverage: false,\n effectiveCoverageFormat: null,\n ...common,\n maxTestClasses,\n maxTestMethods,\n });\n}\n\nfunction parseCoverageSafeExecutePolicy(\n cloned: Record<string, McpInvocationJsonValue>,\n common: ReturnType<typeof parseSafeExecuteCommon>,\n): SafeExecutePolicy | undefined {\n if (!common) return undefined;\n const format = cloned.effectiveCoverageFormat;\n if (\n cloned.operationId !== 'run_unit_tests' ||\n cloned.check !== 'coverage' ||\n cloned.effectiveWithCoverage !== true ||\n (format !== 'jacoco' && format !== 'sonar-generic') ||\n !hasExactSortedKeys(cloned, [\n ...safeExecuteCommonKeys,\n 'effectiveWithCoverage',\n 'effectiveCoverageFormat',\n 'maxPrograms',\n 'maxMeasurements',\n ])\n ) {\n return undefined;\n }\n const maxPrograms = positiveSafeInteger(cloned.maxPrograms);\n const maxMeasurements = positiveSafeInteger(cloned.maxMeasurements);\n if (maxPrograms === undefined || maxMeasurements === undefined) {\n return undefined;\n }\n return Object.freeze({\n operationId: 'run_unit_tests',\n check: 'coverage',\n effectiveWithCoverage: true,\n effectiveCoverageFormat: format,\n ...common,\n maxPrograms,\n maxMeasurements,\n });\n}\n\nexport function parseSafeExecutePolicy(\n value: unknown,\n): SafeExecutePolicy | undefined {\n if (!isPlainObject(value)) return undefined;\n const cloned = cloneJsonRecord(value);\n if (!cloned) return undefined;\n const common = parseSafeExecuteCommon(cloned);\n\n return (\n parseAtcSafeExecutePolicy(cloned, common) ??\n parseAunitSafeExecutePolicy(cloned, common) ??\n parseCoverageSafeExecutePolicy(cloned, common)\n );\n}\n\nfunction parseSortedUniqueStrings(\n value: unknown,\n options: {\n maxItems: number;\n minItems: number;\n matches: (item: string) => boolean;\n },\n): readonly string[] | undefined {\n if (\n !Array.isArray(value) ||\n value.length < options.minItems ||\n value.length > options.maxItems\n ) {\n return undefined;\n }\n const parsed: string[] = [];\n for (const item of value) {\n if (\n typeof item !== 'string' ||\n !options.matches(item) ||\n parsed.includes(item)\n ) {\n return undefined;\n }\n parsed.push(item);\n }\n const sorted = [...parsed].sort((left, right) => left.localeCompare(right));\n if (!parsed.every((item, index) => item === sorted[index])) return undefined;\n return Object.freeze(parsed);\n}\n\nfunction parseScopedObjectKeys(value: unknown): readonly string[] | undefined {\n return parseSortedUniqueStrings(value, {\n maxItems: MAX_SCOPED_OBJECT_KEYS,\n minItems: 1,\n matches: (item) => scopedCanonicalObjectKeyPattern.test(item),\n });\n}\n\nfunction parseScopedToolNames(\n value: unknown,\n operationClass: 'read' | 'safe_execute',\n safeExecutePolicy: SafeExecutePolicy | undefined,\n): readonly string[] | undefined {\n const toolNames = parseSortedUniqueStrings(value, {\n maxItems: operationClass === 'read' ? scopedReadTools.size : 1,\n minItems: 1,\n matches: (item) =>\n operationClass === 'read'\n ? scopedReadTools.has(item)\n : item === 'atc_run' || item === 'run_unit_tests',\n });\n if (!toolNames) return undefined;\n if (operationClass === 'read') {\n return safeExecutePolicy === undefined ? toolNames : undefined;\n }\n return safeExecutePolicy && toolNames[0] === safeExecutePolicy.operationId\n ? toolNames\n : undefined;\n}\n\nfunction parseExecutionAuthorizationToken(value: unknown): string | undefined {\n return typeof value === 'string' &&\n value.length <= MAX_SAFE_EXECUTE_GRANT_BYTES &&\n compactJwsPattern.test(value)\n ? value\n : undefined;\n}\n\nexport function parseScopedAdtInvocationPolicy(\n claims: TrustedMcpInvocationClaims,\n): ScopedAdtInvocationPolicy | undefined {\n if (\n claims.agentId !== 'adt-execution' ||\n claims.destinationKeys.length !== 1\n ) {\n return undefined;\n }\n if (\n claims.classes.length !== 2 ||\n claims.classes[0] !== 'server' ||\n (claims.classes[1] !== 'read' && claims.classes[1] !== 'safe_execute')\n ) {\n return undefined;\n }\n const operationClass = claims.classes[1];\n const safeExecute = operationClass === 'safe_execute';\n const expectedConstraintKeys = [\n 'kind',\n 'scopeId',\n 'executionId',\n 'systemSid',\n 'resourceKeys',\n 'toolNames',\n ...(safeExecute\n ? ['safeExecutePolicy', 'authorizationId', 'authorizationToken']\n : []),\n ];\n if (!hasExactSortedKeys(claims.constraint, expectedConstraintKeys)) {\n return undefined;\n }\n if (\n claims.constraint.kind !== 'adt-execution-v1' ||\n !hasExactSortedKeys(claims.limits, ['maxToolCalls'])\n ) {\n return undefined;\n }\n\n const scopeId = requiredUuid(claims.constraint.scopeId);\n const executionId = requiredUuid(claims.constraint.executionId);\n const systemSid = requiredSystemSid(claims.constraint.systemSid);\n const resourceKeys = parseScopedObjectKeys(claims.constraint.resourceKeys);\n const maxToolCalls = positiveSafeInteger(claims.limits.maxToolCalls);\n if (\n !scopeId ||\n !executionId ||\n !systemSid ||\n !resourceKeys ||\n maxToolCalls === undefined ||\n maxToolCalls > MAX_SCOPED_TOOL_CALLS\n ) {\n return undefined;\n }\n\n const safeExecutePolicy = safeExecute\n ? parseSafeExecutePolicy(claims.constraint.safeExecutePolicy)\n : undefined;\n const toolNames = parseScopedToolNames(\n claims.constraint.toolNames,\n operationClass,\n safeExecutePolicy,\n );\n if (!toolNames) return undefined;\n\n if (!safeExecute) {\n return Object.freeze({\n scopeId,\n executionId,\n systemSid,\n resourceKeys,\n toolNames,\n operationClass,\n maxToolCalls,\n });\n }\n\n const authorizationId = requiredUuid(claims.constraint.authorizationId);\n const authorizationToken = parseExecutionAuthorizationToken(\n claims.constraint.authorizationToken,\n );\n if (!safeExecutePolicy || !authorizationId || !authorizationToken) {\n return undefined;\n }\n return Object.freeze({\n scopeId,\n executionId,\n systemSid,\n resourceKeys,\n toolNames,\n operationClass,\n maxToolCalls,\n safeExecutePolicy,\n authorizationId,\n authorizationToken,\n });\n}\n\nexport function parseFrozenSource(\n source: unknown,\n sourceKeys: Set<string>,\n sourceRefs: Set<string>,\n):\n | {\n readonly canonicalKey: string;\n readonly componentId: string;\n readonly sourceRef: string;\n }\n | undefined {\n if (!isPlainObject(source)) return undefined;\n const canonicalKey = source.canonicalKey;\n const componentId = requiredComponentIdentifier(source.componentId);\n const sourceRef = requiredSourceReference(source.sourceRef);\n if (typeof canonicalKey !== 'string') return undefined;\n if (!canonicalKeyPattern.test(canonicalKey)) return undefined;\n if (!componentId || !sourceRef) return undefined;\n const key = `${canonicalKey}\\u0000${componentId}`;\n if (sourceKeys.has(key) || sourceRefs.has(sourceRef)) return undefined;\n sourceKeys.add(key);\n sourceRefs.add(sourceRef);\n return Object.freeze({ canonicalKey, componentId, sourceRef });\n}\n\n/**\n * Parse the only AI Review policy currently safe to dispatch. Every property\n * is deliberately exact: accepting a valid JWS with one ignored narrowing\n * field would widen the Review beyond its frozen materialisation.\n */\nconst expectedAiReviewConstraintKeys = [\n 'frozenSources',\n 'kind',\n 'reviewId',\n 'runId',\n 'systemSid',\n];\n\nfunction isSortedKeysEqual(\n keys: readonly string[],\n expected: readonly string[],\n): boolean {\n return (\n keys.length === expected.length &&\n keys.every((key, index) => key === expected[index])\n );\n}\n\nfunction parseAiReviewSources(rawSources: unknown):\n | {\n readonly canonicalKey: string;\n readonly componentId: string;\n readonly sourceRef: string;\n }[]\n | undefined {\n if (!Array.isArray(rawSources)) return undefined;\n if (rawSources.length === 0 || rawSources.length > MAX_FROZEN_SOURCES) {\n return undefined;\n }\n const sourceKeys = new Set<string>();\n const sourceRefs = new Set<string>();\n const sources: {\n canonicalKey: string;\n componentId: string;\n sourceRef: string;\n }[] = [];\n for (const rawSource of rawSources) {\n if (!isPlainObject(rawSource)) return undefined;\n const rawSourceKeys = Object.keys(rawSource).sort((a, b) =>\n a.localeCompare(b),\n );\n if (rawSourceKeys.length !== 3) return undefined;\n if (rawSourceKeys[0] !== 'canonicalKey') return undefined;\n if (rawSourceKeys[1] !== 'componentId') return undefined;\n if (rawSourceKeys[2] !== 'sourceRef') return undefined;\n const parsed = parseFrozenSource(rawSource, sourceKeys, sourceRefs);\n if (!parsed) return undefined;\n sources.push(parsed);\n }\n return sources;\n}\n\nfunction parseMaxSourceBytes(\n limits: Readonly<Record<string, McpInvocationJsonValue>>,\n): number | undefined {\n const limitKeys = Object.keys(limits);\n if (limitKeys.length !== 1) return undefined;\n if (limitKeys[0] !== 'maxSourceBytes') return undefined;\n const maxSourceBytes = limits.maxSourceBytes;\n if (typeof maxSourceBytes !== 'number') return undefined;\n if (!Number.isSafeInteger(maxSourceBytes)) return undefined;\n if (maxSourceBytes < 1) return undefined;\n if (maxSourceBytes > MAX_FROZEN_SOURCE_BYTES) return undefined;\n return maxSourceBytes;\n}\n\nfunction parseAiReviewIdentity(\n constraint: Readonly<Record<string, McpInvocationJsonValue>>,\n):\n | {\n readonly reviewId: string;\n readonly runId: string;\n readonly systemSid: string;\n }\n | undefined {\n const reviewId = requiredUuid(constraint.reviewId);\n const runId = requiredUuid(constraint.runId);\n const systemSid = requiredIdentifier(constraint.systemSid);\n if (!reviewId) return undefined;\n if (!runId) return undefined;\n if (!systemSid) return undefined;\n if (systemSid.length > 16) return undefined;\n return Object.freeze({ reviewId, runId, systemSid });\n}\n\nexport function parseAiReviewFrozenSourcePolicy(\n claims: TrustedMcpInvocationClaims,\n): AiReviewFrozenSourcePolicy | undefined {\n if (claims.agentId !== 'ai-review') return undefined;\n const constraint = claims.constraint;\n const constraintKeys = Object.keys(constraint).sort((a, b) =>\n a.localeCompare(b),\n );\n if (!isSortedKeysEqual(constraintKeys, expectedAiReviewConstraintKeys)) {\n return undefined;\n }\n if (constraint.kind !== 'ai-review-frozen-v1') return undefined;\n\n const identity = parseAiReviewIdentity(constraint);\n if (!identity) return undefined;\n\n const sources = parseAiReviewSources(constraint.frozenSources);\n if (!sources) return undefined;\n\n const maxSourceBytes = parseMaxSourceBytes(claims.limits);\n if (maxSourceBytes === undefined) return undefined;\n\n return Object.freeze({\n reviewId: identity.reviewId,\n runId: identity.runId,\n systemSid: identity.systemSid,\n sources: Object.freeze(sources),\n maxSourceBytes,\n });\n}\n\nfunction requiredString(\n value: unknown,\n options: {\n readonly maxLength: number;\n readonly trim?: boolean;\n readonly allowControlChars?: boolean;\n },\n): string | undefined {\n if (typeof value !== 'string') return undefined;\n if (value.length === 0 || value.length > options.maxLength) return undefined;\n if (options.trim && value.trim().length === 0) return undefined;\n if (\n !options.allowControlChars &&\n // eslint-disable-next-line no-control-regex\n /[\\s\\u0000-\\u0008\\u000e-\\u001f\\u007f]/u.test(value)\n ) {\n return undefined;\n }\n return value;\n}\n\nfunction requiredIdentifier(value: unknown): string | undefined {\n return requiredString(value, {\n maxLength: MAX_IDENTIFIER_LENGTH,\n trim: true,\n allowControlChars: true,\n });\n}\n\nfunction requiredSystemSid(value: unknown): string | undefined {\n const systemSid = requiredIdentifier(value);\n return systemSid &&\n systemSid.length <= 16 &&\n /^[A-Za-z0-9_-]+$/u.test(systemSid)\n ? systemSid\n : undefined;\n}\n\nfunction requiredComponentIdentifier(value: unknown): string | undefined {\n return requiredString(value, { maxLength: MAX_COMPONENT_IDENTIFIER_LENGTH });\n}\n\nfunction requiredConfigurationIdentifier(value: unknown, name: string): string {\n const identifier = requiredIdentifier(value);\n if (!identifier) {\n throw new Error(`MCP invocation verifier requires a valid ${name}`);\n }\n return identifier;\n}\n\nfunction extractBearerCredential(\n authorizationHeader: string | string[] | undefined,\n): string | undefined {\n if (Array.isArray(authorizationHeader)) return undefined;\n if (typeof authorizationHeader !== 'string') return undefined;\n const header = authorizationHeader.trim();\n if (header.length < 8 || header.slice(0, 7).toLowerCase() !== 'bearer ') {\n return undefined;\n }\n const credential = header.slice(7).trim();\n return credential.length > 0 ? credential : undefined;\n}\n\nfunction isTrustedOperationClass(\n value: unknown,\n): value is McpTrustedOperationClass {\n return typeof value === 'string' && trustedOperationClasses.has(value);\n}\n\nfunction cloneTrustedClasses(\n value: unknown,\n): readonly McpTrustedOperationClass[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n const classes: McpTrustedOperationClass[] = [];\n for (const item of value) {\n if (!isTrustedOperationClass(item) || classes.includes(item)) {\n return undefined;\n }\n classes.push(item);\n }\n return Object.freeze(classes);\n}\n\nfunction cloneDestinationKeys(value: unknown): readonly string[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n const destinationKeys: string[] = [];\n for (const item of value) {\n if (\n typeof item !== 'string' ||\n !destinationKeyPattern.test(item) ||\n destinationKeys.includes(item)\n ) {\n return undefined;\n }\n destinationKeys.push(item);\n }\n return Object.freeze(destinationKeys);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null) return false;\n if (typeof value !== 'object') return false;\n if (Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction cloneJsonScalar(value: unknown): McpInvocationJsonValue | undefined {\n if (value === null) return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : undefined;\n }\n return undefined;\n}\n\nfunction cloneJsonArray(\n value: unknown[],\n depth: number,\n): McpInvocationJsonValue[] | undefined {\n const cloned: McpInvocationJsonValue[] = [];\n for (const item of value) {\n const clonedItem = cloneJsonValue(item, depth + 1);\n if (clonedItem === undefined) return undefined;\n cloned.push(clonedItem);\n }\n return Object.freeze(cloned);\n}\n\nfunction cloneJsonObject(\n value: Record<string, unknown>,\n depth: number,\n): Readonly<Record<string, McpInvocationJsonValue>> | undefined {\n const cloned = Object.create(null) as Record<string, McpInvocationJsonValue>;\n for (const [key, item] of Object.entries(value)) {\n const clonedItem = cloneJsonValue(item, depth + 1);\n if (clonedItem === undefined) return undefined;\n cloned[key] = clonedItem;\n }\n return Object.freeze(cloned);\n}\n\nfunction cloneJsonValue(\n value: unknown,\n depth = 0,\n): McpInvocationJsonValue | undefined {\n if (depth > MAX_JSON_DEPTH) return undefined;\n const scalar = cloneJsonScalar(value);\n if (scalar !== undefined) return scalar;\n if (Array.isArray(value)) return cloneJsonArray(value, depth);\n if (isPlainObject(value)) return cloneJsonObject(value, depth);\n return undefined;\n}\n\nfunction cloneJsonRecord(\n value: unknown,\n): Readonly<Record<string, McpInvocationJsonValue>> | undefined {\n const cloned = cloneJsonValue(value);\n return cloned !== null && !Array.isArray(cloned) && typeof cloned === 'object'\n ? (cloned as Readonly<Record<string, McpInvocationJsonValue>>)\n : undefined;\n}\n\nfunction isUnixTimestamp(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isValidTokenTimestamps(record: Record<string, unknown>): boolean {\n if (!isUnixTimestamp(record.iat)) return false;\n if (!isUnixTimestamp(record.nbf)) return false;\n if (!isUnixTimestamp(record.exp)) return false;\n if (record.nbf < record.iat) return false;\n if (record.exp < record.nbf) return false;\n if (record.exp - record.iat > MAX_TOKEN_LIFETIME_SECONDS) return false;\n return true;\n}\n\nfunction isValidTokenHeader(\n record: Record<string, unknown>,\n expectedKeyId: string,\n expectedIssuer: string,\n expectedAudience: string,\n): boolean {\n if (record.v !== INVOCATION_VERSION) return false;\n if (record.kid !== expectedKeyId) return false;\n if (record.iss !== expectedIssuer) return false;\n if (record.aud !== expectedAudience) return false;\n return isValidTokenTimestamps(record);\n}\n\nfunction isValidTokenAgent(\n agentId: unknown,\n): agentId is TrustedMcpInvocationClaims['agentId'] {\n return typeof agentId === 'string' && trustedAgentIds.has(agentId);\n}\n\nfunction parseInvocationActors(record: Record<string, unknown>):\n | {\n tokenId: string;\n principal: string;\n agentId: TrustedMcpInvocationClaims['agentId'];\n correlationId: string;\n }\n | undefined {\n const tokenId = requiredIdentifier(record.jti);\n const principal = requiredIdentifier(record.principal);\n const correlationId = requiredIdentifier(record.correlationId);\n const agentId = record.agentId;\n if (!tokenId || !principal || !correlationId || !isValidTokenAgent(agentId)) {\n return undefined;\n }\n return Object.freeze({ tokenId, principal, agentId, correlationId });\n}\n\nfunction buildInvocationClaims(\n record: Record<string, unknown>,\n): TrustedMcpInvocationClaims | undefined {\n const actors = parseInvocationActors(record);\n if (!actors) return undefined;\n\n const classes = cloneTrustedClasses(record.classes);\n const destinationKeys = cloneDestinationKeys(record.destinationKeys);\n const constraint = cloneJsonRecord(record.constraint);\n const limits = cloneJsonRecord(record.limits);\n if (!classes) return undefined;\n if (!destinationKeys) return undefined;\n if (!constraint) return undefined;\n if (!limits) return undefined;\n\n return Object.freeze({\n tokenId: actors.tokenId,\n principal: actors.principal,\n agentId: actors.agentId,\n classes,\n destinationKeys,\n correlationId: actors.correlationId,\n constraint,\n limits,\n });\n}\n\nfunction claimsFromPayload(\n payload: JWTPayload,\n expectedKeyId: string,\n expectedIssuer: string,\n expectedAudience: string,\n): TrustedMcpInvocationClaims | undefined {\n const record = payload as Record<string, unknown>;\n if (\n !isValidTokenHeader(record, expectedKeyId, expectedIssuer, expectedAudience)\n ) {\n return undefined;\n }\n return buildInvocationClaims(record);\n}\n\nfunction currentDate(now: (() => Date | number) | undefined): Date {\n const value = now?.() ?? new Date();\n return value instanceof Date ? value : new Date(value);\n}\n\n/**\n * Build a fail-closed verifier for the one ADT-Server invocation key.\n * Configuration failures throw before serving traffic; credential failures\n * always resolve to `undefined` without logging token-derived information.\n */\nexport function createMcpInvocationVerifier(\n options: McpInvocationVerifierOptions,\n): McpInvocationVerifier {\n if (!options?.publicKey) {\n throw new Error('MCP invocation verifier requires an ES256 public key');\n }\n const publicKey = options.publicKey;\n const keyId = requiredConfigurationIdentifier(options.keyId, 'key id');\n const issuer = requiredConfigurationIdentifier(options.issuer, 'issuer');\n const audience = requiredConfigurationIdentifier(\n options.audience,\n 'audience',\n );\n const now = options.now;\n\n return {\n async verify(authorizationHeader) {\n const credential = extractBearerCredential(authorizationHeader);\n if (!credential) return undefined;\n\n try {\n const verified = await jwtVerify(credential, publicKey, {\n algorithms: ['ES256'],\n issuer,\n audience,\n currentDate: currentDate(now),\n });\n const protectedHeader = verified.protectedHeader;\n if (\n protectedHeader.alg !== 'ES256' ||\n protectedHeader.kid !== keyId ||\n protectedHeader.typ !== 'JWT'\n ) {\n return undefined;\n }\n return claimsFromPayload(verified.payload, keyId, issuer, audience);\n } catch {\n return undefined;\n }\n },\n };\n}\n","/**\n * CORS handler for the adt-mcp HTTP transport.\n *\n * Only engages when the request carries an `Origin` header.\n * The allow-list is exact-match (plus the `*` wildcard shortcut for dev).\n * Preflight (`OPTIONS`) requests are terminated here with the appropriate\n * headers; non-preflight requests get response headers applied to `res`\n * so the caller can continue the normal pipeline.\n *\n * Per the MCP spec, `Mcp-Session-Id` must be exposed via\n * `Access-Control-Expose-Headers` so browser clients can read it off the\n * `initialize` response.\n */\nimport http from 'node:http';\n\nconst ALLOW_METHODS = 'POST, GET, DELETE, OPTIONS';\nconst ALLOW_HEADERS = 'content-type, accept, mcp-session-id, authorization';\nconst EXPOSE_HEADERS = 'mcp-session-id';\nconst MAX_AGE = '600';\n\nexport interface CorsOptions {\n /**\n * Exact-match allow-list of origins. The single entry `'*'` disables\n * matching and mirrors any origin (intended for local dev only).\n * An empty / undefined list disables CORS entirely (no headers added).\n */\n allowedOrigins?: string[];\n}\n\nexport interface CorsHandler {\n /**\n * Apply CORS handling to a request.\n *\n * Returns `true` if the response has been fully handled (preflight\n * short-circuit) and the caller MUST stop processing. Returns `false`\n * otherwise — the caller should continue; any non-preflight response\n * headers have already been written to `res.setHeader()` and will be\n * flushed with the final response.\n */\n handle(req: http.IncomingMessage, res: http.ServerResponse): boolean;\n}\n\nfunction getOrigin(req: http.IncomingMessage): string | undefined {\n const raw = req.headers['origin'];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value?.trim() && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction isAllowed(origin: string, allowed: string[]): boolean {\n if (allowed.length === 1 && allowed[0] === '*') return true;\n return allowed.includes(origin);\n}\n\nexport function createCorsHandler(options: CorsOptions = {}): CorsHandler {\n const allowed = (options.allowedOrigins ?? []).filter((s) => s.length > 0);\n const enabled = allowed.length > 0;\n\n return {\n handle(req, res) {\n if (!enabled) {\n // No CORS configured — if a preflight arrives it's not our concern\n // but we shouldn't crash the pipeline. Let the outer handler 404/405.\n return false;\n }\n const origin = getOrigin(req);\n const isPreflight = req.method === 'OPTIONS';\n\n if (!origin) {\n // Non-browser client, no CORS needed. Preflight without Origin is\n // malformed — fall through and let routing handle the 405.\n return false;\n }\n\n if (!isAllowed(origin, allowed)) {\n res.writeHead(403, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'origin not allowed' }));\n return true;\n }\n\n // Always mirror the request Origin — using the literal `*` would be\n // incompatible with credentialed requests, and mirroring is spec-compliant\n // in both wildcard and explicit-allow-list cases.\n res.setHeader('Access-Control-Allow-Origin', origin);\n res.setHeader('Vary', 'Origin');\n res.setHeader('Access-Control-Expose-Headers', EXPOSE_HEADERS);\n\n if (isPreflight) {\n res.setHeader('Access-Control-Allow-Methods', ALLOW_METHODS);\n res.setHeader('Access-Control-Allow-Headers', ALLOW_HEADERS);\n res.setHeader('Access-Control-Max-Age', MAX_AGE);\n res.writeHead(204);\n res.end();\n return true;\n }\n\n return false;\n },\n };\n}\n","/**\n * HTTP transport for the adt-mcp server.\n *\n * Implements the Streamable HTTP pattern recommended by the MCP SDK:\n *\n * - POST /mcp with `initialize` and no `Mcp-Session-Id` header\n * → spin up a new McpServer + StreamableHTTPServerTransport pair,\n * register them under the generated session id.\n * - Subsequent POST /mcp / GET /mcp / DELETE /mcp with `Mcp-Session-Id`\n * → route to the stored transport.\n *\n * A small middleware pipeline (`host validation → auth → route`) is kept\n * simple and composable so that future waves can drop in real auth.\n */\n\nimport https from 'node:https';\nimport http from 'node:http';\nimport { readFile } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { createMcpServer } from '../server.js';\nimport { createSessionRegistry } from '../session/registry.js';\nimport type { SessionRegistry } from '../session/registry.js';\nimport type {\n DestinationContextRegistry,\n RequestIdentity,\n} from '../session/destination-registry.js';\nimport {\n isMcpDestinationKey,\n isMcpOperationClass,\n type McpDelegatedAccess,\n type McpFrozenSourceAccess,\n type McpScopedAccess,\n type McpRequestAccess,\n} from '../tools/scope-catalogue.js';\nimport {\n loadMultiSystemConfig,\n type MultiSystemConfig,\n} from './multi-system.js';\nimport { createAuthMiddleware, type AuthMode, type UserHint } from './auth.js';\nimport {\n isMcpInvocationDispatchPolicySupported,\n parseAiReviewFrozenSourcePolicy,\n parseDelegatedAssistantReadPolicy,\n parseFrozenSource,\n parseScopedAdtInvocationPolicy,\n parseSafeExecutePolicy,\n} from './invocation.js';\nimport type {\n McpInvocationVerifier,\n TrustedMcpInvocationClaims,\n} from './invocation.js';\nimport type { OAuthOptions } from './oauth.js';\nimport { createCorsHandler } from './cors.js';\n\nexport interface HttpServerOptions {\n /** Port to listen on. Default: `MCP_PORT` env or 3000. */\n port?: number;\n /** Host to bind to. Default: `MCP_HOST` env or `127.0.0.1`. */\n host?: string;\n /** Idle session TTL in ms. Default: 30 minutes. */\n ttlMs?: number;\n /**\n * Extra host names to accept in the `Host` header. The bound host is\n * always accepted; `localhost`, `127.0.0.1`, and `[::1]` are accepted\n * by default.\n */\n allowedHosts?: string[];\n /**\n * Authentication mode for incoming requests. Defaults to `'none'` when\n * no token / forwarded-auth flag is configured. Misconfiguration (e.g.\n * `bearer` without a token) throws synchronously when the handler is\n * created, including through `startHttpServer`.\n */\n authMode?: AuthMode;\n /** Bearer token (required when `authMode === 'bearer'`). */\n authToken?: string;\n /**\n * Convenience flag — when true, forces `authMode='proxy'` and trusts\n * `x-forwarded-user` from the caller. Intended for deployments behind\n * an authenticating reverse proxy (oauth2-proxy, Cloudflare Access).\n */\n trustForwardedAuth?: boolean;\n /**\n * OAuth / OIDC validation options (required when `authMode === 'oauth'`).\n * Issuer, audience, JWKS, required scopes, user-claim mapping. See\n * `./oauth.ts` for the full option list.\n */\n oauth?: OAuthOptions;\n /**\n * ADT-issued invocation verifier (required when `authMode ===\n * 'invocation'`). Its trusted claims are the only source for identity and\n * scope in destination-aware sidecar mode.\n */\n invocationVerifier?: McpInvocationVerifier;\n /**\n * Internal test hook — called with each successful OAuth `userHint`.\n * Not part of the public API.\n * @internal\n */\n onOAuthUserHint?: (hint: import('./auth.js').UserHint | undefined) => void;\n /**\n * CORS allow-list. Exact-match origins only (plus `'*'` for dev).\n * Undefined or empty = CORS disabled (no headers added).\n */\n allowedOrigins?: string[];\n /** Override the multi-system config loader (mainly for tests). */\n multiSystem?: MultiSystemConfig;\n /** Override the session registry (mainly for tests). */\n registry?: SessionRegistry;\n /** Path to the PEM-encoded TLS certificate; also read from MCP_TLS_CERT. */\n tlsCert?: string;\n /** Path to the PEM-encoded TLS private key; also read from MCP_TLS_KEY. */\n tlsKey?: string;\n /** Inline PEM-encoded TLS certificate (useful for embedders and tests). */\n tlsCertContent?: string;\n /** Inline PEM-encoded TLS private key (useful for embedders and tests). */\n tlsKeyContent?: string;\n /**\n * Enables destination-aware shared-server mode. Access and identity are\n * derived only from the authenticated request's trusted `UserHint` at MCP\n * session initialization, then captured for the life of that session.\n */\n destinationServer?: {\n destinationRegistry: DestinationContextRegistry;\n requestIdentity: (input: {\n userHint?: UserHint;\n invocation?: TrustedMcpInvocationClaims;\n }) => RequestIdentity;\n requestAccess: (input: {\n userHint?: UserHint;\n invocation?: TrustedMcpInvocationClaims;\n }) => McpRequestAccess | undefined;\n resolveFrozenSource?: NonNullable<\n import('../types.js').ToolContext['resolveFrozenSource']\n >;\n consumeExecutionAuthorization?: NonNullable<\n import('../types.js').ToolContext['consumeExecutionAuthorization']\n >;\n reportExecutionOutcome?: NonNullable<\n import('../types.js').ToolContext['reportExecutionOutcome']\n >;\n executeWithDeadline?: NonNullable<\n import('../types.js').ToolContext['executeWithDeadline']\n >;\n };\n /** Inject a logger that writes to stderr by default. */\n log?: (level: 'info' | 'warn' | 'error', msg: string) => void;\n}\n\nexport interface RunningHttpServer {\n readonly url: string;\n readonly port: number;\n readonly host: string;\n readonly registry: SessionRegistry;\n close(): Promise<void>;\n}\n\n/**\n * A reusable Streamable HTTP MCP request handler.\n *\n * The embedding application owns its Node listener and delegates only the\n * requests routed to MCP to `handle`. Calling `close` releases MCP sessions\n * and transports, but deliberately never closes that listener.\n */\nexport interface HttpMcpHandler {\n readonly registry: SessionRegistry;\n handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>;\n close(): Promise<void>;\n}\n\ntype Middleware = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n) => Promise<boolean> | boolean;\n\n/**\n * Captures trusted access at initialization so a provider cannot change a\n * session's authorization by mutating the object it returned later.\n */\nfunction snapshotRequestAccess(\n access: McpRequestAccess | undefined,\n): McpRequestAccess | undefined {\n if (!access) return undefined;\n\n const classes = access.classes;\n const destinationKeys = access.destinationKeys;\n if (!Array.isArray(classes) || !Array.isArray(destinationKeys)) {\n return undefined;\n }\n\n if (\n !classes.every(isMcpOperationClass) ||\n !destinationKeys.every(isMcpDestinationKey)\n ) {\n return undefined;\n }\n\n const frozenSource = snapshotFrozenSourceAccess(access.frozenSource);\n if (access.frozenSource && !frozenSource) return undefined;\n const scoped = snapshotScopedAccess(access.scoped);\n if (access.scoped && !scoped) return undefined;\n const delegated = snapshotDelegatedAccess(access.delegated);\n if (access.delegated && !delegated) return undefined;\n if (\n scoped &&\n (classes.length !== 2 ||\n classes[0] !== 'server' ||\n classes[1] !== scoped.operationClass)\n ) {\n return undefined;\n }\n\n return Object.freeze({\n classes: Object.freeze([...classes]),\n destinationKeys: Object.freeze([...destinationKeys]),\n ...(frozenSource ? { frozenSource } : {}),\n ...(scoped ? { scoped } : {}),\n ...(delegated ? { delegated } : {}),\n });\n}\n\nconst UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\nconst OBJECT_KEY_REGEX = /^[A-Z0-9_]{2,30}:[A-Z0-9_/$-]{1,128}$/u;\nconst READ_SCOPED_TOOLS = new Set(['get_object', 'get_object_structure']);\nconst SYSTEM_SID_REGEX = /^[A-Za-z0-9_-]{1,16}$/u;\nconst AUTHORIZATION_TOKEN_REGEX =\n /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/u;\n\nfunction normalizeAndValidateStrings(values: unknown[]): string[] | undefined {\n if (!Array.isArray(values)) return undefined;\n const result: string[] = [];\n for (const value of values) {\n if (typeof value !== 'string' || !value) return undefined;\n result.push(value);\n }\n return result;\n}\n\nfunction isSortedUniqueStrings(values: string[]): boolean {\n const sorted = [...values].sort((left, right) => left.localeCompare(right));\n return (\n new Set(values).size === values.length &&\n values.every((value, index) => value === sorted[index])\n );\n}\n\nfunction validateCommonScopedFields(\n access: McpScopedAccess,\n): { resourceKeys: string[]; toolNames: string[] } | undefined {\n if (typeof access.tokenId !== 'string' || !access.tokenId) return undefined;\n if (typeof access.principal !== 'string' || !access.principal)\n return undefined;\n if (typeof access.correlationId !== 'string' || !access.correlationId)\n return undefined;\n if (typeof access.scopeId !== 'string' || !UUID_REGEX.test(access.scopeId)) {\n return undefined;\n }\n if (\n typeof access.executionId !== 'string' ||\n !UUID_REGEX.test(access.executionId)\n ) {\n return undefined;\n }\n if (\n typeof access.systemSid !== 'string' ||\n !SYSTEM_SID_REGEX.test(access.systemSid)\n ) {\n return undefined;\n }\n if (\n !Number.isSafeInteger(access.maxToolCalls) ||\n access.maxToolCalls < 1 ||\n access.maxToolCalls > 12\n ) {\n return undefined;\n }\n\n const resourceKeys = normalizeAndValidateStrings(access.resourceKeys);\n const toolNames = normalizeAndValidateStrings(access.toolNames);\n if (\n !resourceKeys ||\n resourceKeys.length > 100 ||\n resourceKeys.some((key) => !OBJECT_KEY_REGEX.test(key)) ||\n !isSortedUniqueStrings(resourceKeys) ||\n !toolNames ||\n toolNames.length === 0 ||\n !isSortedUniqueStrings(toolNames)\n ) {\n return undefined;\n }\n\n return { resourceKeys, toolNames };\n}\n\nfunction buildScopedAccess(\n access: McpScopedAccess,\n resourceKeys: string[],\n toolNames: string[],\n overrides: Record<string, unknown> = {},\n): McpScopedAccess {\n return Object.freeze({\n ...access,\n resourceKeys: Object.freeze(resourceKeys),\n toolNames: Object.freeze(toolNames),\n ...overrides,\n }) as McpScopedAccess;\n}\n\nfunction snapshotReadScope(\n access: McpScopedAccess,\n resourceKeys: string[],\n toolNames: string[],\n): McpScopedAccess | undefined {\n if (\n resourceKeys.length === 0 ||\n toolNames.some((name) => !READ_SCOPED_TOOLS.has(name)) ||\n access.safeExecutePolicy !== undefined ||\n access.authorizationId !== undefined ||\n access.authorizationToken !== undefined\n ) {\n return undefined;\n }\n return buildScopedAccess(access, resourceKeys, toolNames);\n}\n\nfunction snapshotSafeExecuteScope(\n access: McpScopedAccess,\n resourceKeys: string[],\n toolNames: string[],\n): McpScopedAccess | undefined {\n const safeExecutePolicy = parseSafeExecutePolicy(access.safeExecutePolicy);\n if (\n !safeExecutePolicy ||\n resourceKeys.length === 0 ||\n toolNames.length !== 1 ||\n toolNames[0] !== safeExecutePolicy.operationId ||\n typeof access.authorizationId !== 'string' ||\n !UUID_REGEX.test(access.authorizationId) ||\n typeof access.authorizationToken !== 'string' ||\n access.authorizationToken.length > 16 * 1024 ||\n !AUTHORIZATION_TOKEN_REGEX.test(access.authorizationToken)\n ) {\n return undefined;\n }\n return buildScopedAccess(access, resourceKeys, toolNames, {\n safeExecutePolicy,\n });\n}\n\nfunction snapshotScopedAccess(\n access: McpScopedAccess | undefined,\n): McpScopedAccess | undefined {\n if (!access) return undefined;\n const validated = validateCommonScopedFields(access);\n if (!validated) return undefined;\n const { resourceKeys, toolNames } = validated;\n\n if (access.operationClass === 'read') {\n return snapshotReadScope(access, resourceKeys, toolNames);\n }\n if (access.operationClass === 'safe_execute') {\n return snapshotSafeExecuteScope(access, resourceKeys, toolNames);\n }\n return undefined;\n}\n\nfunction snapshotDelegatedAccess(\n access: McpDelegatedAccess | undefined,\n): McpDelegatedAccess | undefined {\n if (!access) return undefined;\n if (\n typeof access.threadId !== 'string' ||\n !UUID_REGEX.test(access.threadId) ||\n typeof access.executionId !== 'string' ||\n !UUID_REGEX.test(access.executionId) ||\n typeof access.systemSid !== 'string' ||\n access.systemSid.length === 0 ||\n access.systemSid.length > 16\n ) {\n return undefined;\n }\n return Object.freeze({\n threadId: access.threadId,\n executionId: access.executionId,\n systemSid: access.systemSid,\n });\n}\n\nfunction snapshotFrozenSourceAccess(\n access: McpFrozenSourceAccess | undefined,\n): McpFrozenSourceAccess | undefined {\n if (!access) return undefined;\n if (\n typeof access.systemSid !== 'string' ||\n access.systemSid.length === 0 ||\n access.systemSid.length > 16 ||\n !Number.isSafeInteger(access.maxSourceBytes) ||\n access.maxSourceBytes < 1 ||\n access.maxSourceBytes > 2 * 1024 * 1024 ||\n !Array.isArray(access.sources) ||\n access.sources.length === 0 ||\n access.sources.length > 500\n ) {\n return undefined;\n }\n const sourceKeys = new Set<string>();\n const sourceRefs = new Set<string>();\n const sources: {\n canonicalKey: string;\n componentId: string;\n sourceRef: string;\n }[] = [];\n for (const source of access.sources) {\n const parsed = parseFrozenSource(source, sourceKeys, sourceRefs);\n if (!parsed) return undefined;\n sources.push(parsed);\n }\n return Object.freeze({\n systemSid: access.systemSid,\n sources: Object.freeze(sources),\n maxSourceBytes: access.maxSourceBytes,\n });\n}\n\n/** A deterministic, non-secret value used only for session affinity checks. */\nfunction sessionIdentityBinding(\n identity: RequestIdentity,\n invocationTokenId?: string,\n): string {\n if (!identity.principal || typeof identity.principal !== 'string') {\n throw new Error('Trusted request identity is missing a principal');\n }\n if (identity.agentId !== undefined && typeof identity.agentId !== 'string') {\n throw new Error('Trusted request identity has an invalid agent id');\n }\n return JSON.stringify([\n identity.principal,\n identity.agentId ?? null,\n invocationTokenId ?? null,\n ]);\n}\n\nfunction invocationRequestIdentity(\n invocation: TrustedMcpInvocationClaims | undefined,\n): RequestIdentity {\n if (!invocation) {\n throw new Error('Trusted MCP invocation identity is missing');\n }\n return {\n principal: invocation.principal,\n agentId: invocation.agentId,\n };\n}\n\nfunction invocationRequestAccess(\n invocation: TrustedMcpInvocationClaims | undefined,\n): McpRequestAccess | undefined {\n if (!invocation || !isMcpInvocationDispatchPolicySupported(invocation)) {\n return undefined;\n }\n const frozenSource = parseAiReviewFrozenSourcePolicy(invocation);\n const scopedPolicy = parseScopedAdtInvocationPolicy(invocation);\n const delegated = parseDelegatedAssistantReadPolicy(invocation);\n return snapshotRequestAccess({\n classes: invocation.classes,\n destinationKeys: invocation.destinationKeys,\n ...(frozenSource ? { frozenSource } : {}),\n ...(scopedPolicy\n ? {\n scoped: {\n tokenId: invocation.tokenId,\n principal: invocation.principal,\n correlationId: invocation.correlationId,\n ...scopedPolicy,\n },\n }\n : {}),\n ...(delegated ? { delegated } : {}),\n });\n}\n\nfunction defaultLog(level: 'info' | 'warn' | 'error', msg: string): void {\n // Write to stderr to avoid polluting any stdout-based transport on the\n // same process.\n const line = `[adt-mcp-http] ${level}: ${msg}\\n`;\n process.stderr.write(line);\n}\n\nfunction normaliseHostAllowlist(\n bindHost: string,\n extra?: string[],\n): Set<string> {\n const set = new Set<string>(['localhost', '127.0.0.1', '[::1]', '::1']);\n if (bindHost) set.add(bindHost.toLowerCase());\n for (const h of extra ?? []) set.add(h.toLowerCase());\n return set;\n}\n\n/**\n * Host-header validation middleware — protects against DNS-rebinding\n * attacks when the server binds to a loopback interface. Returns `true`\n * when the request has been rejected (caller should stop processing).\n */\nfunction makeHostValidator(allowed: Set<string>): Middleware {\n return (req, res) => {\n const hostHeader = req.headers.host ?? '';\n // Strip port.\n const host = hostHeader.replace(/:\\d+$/u, '').toLowerCase();\n if (!host || !allowed.has(host)) {\n res.writeHead(403, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: `Host header '${hostHeader}' not allowed`,\n },\n id: null,\n }),\n );\n return true;\n }\n return false;\n };\n}\n\nasync function readJsonBody(\n req: http.IncomingMessage,\n limitBytes = 4 * 1024 * 1024,\n): Promise<unknown> {\n return await new Promise((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > limitBytes) {\n reject(new Error('Request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n if (chunks.length === 0) {\n resolve(undefined);\n return;\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n try {\n resolve(raw.length === 0 ? undefined : JSON.parse(raw));\n } catch (err) {\n reject(err);\n }\n });\n req.on('error', reject);\n });\n}\n\nfunction isInitializeRequest(body: unknown): boolean {\n if (!body) return false;\n const msgs = Array.isArray(body) ? body : [body];\n return msgs.some(\n (m) =>\n m &&\n typeof m === 'object' &&\n (m as { method?: unknown }).method === 'initialize',\n );\n}\n\nfunction writeJsonError(\n res: http.ServerResponse,\n status: number,\n message: string,\n): void {\n if (res.headersSent) {\n try {\n res.end();\n } catch {\n // ignore\n }\n return;\n }\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32000, message },\n id: null,\n }),\n );\n}\n\n/**\n * Creates a reusable MCP HTTP handler without binding a Node listener.\n */\nexport function createHttpMcpHandler(\n options: HttpServerOptions = {},\n): HttpMcpHandler {\n const host = options.host ?? process.env.MCP_HOST ?? '127.0.0.1';\n const log = options.log ?? defaultLog;\n\n const registry =\n options.registry ??\n createSessionRegistry({ ttlMs: options.ttlMs ?? 30 * 60 * 1000 });\n const multiSystem = options.multiSystem ?? loadMultiSystemConfig();\n const destinationServer = options.destinationServer;\n\n // One transport per MCP session, plus the paired McpServer that owns it.\n // The SDK expects `server.connect(transport)` to be called once per pair.\n const transports = new Map<string, StreamableHTTPServerTransport>();\n const servers = new Map<string, McpServer>();\n const sessionIdentityBindings = new Map<string, string>();\n\n async function releaseSessionResources(sessionId: string): Promise<void> {\n const server = servers.get(sessionId);\n transports.delete(sessionId);\n sessionIdentityBindings.delete(sessionId);\n servers.delete(sessionId);\n await registry.delete(sessionId);\n await destinationServer?.destinationRegistry.releaseAll(sessionId);\n try {\n await server?.close();\n } catch {\n // ignore\n }\n }\n\n const hostAllow = normaliseHostAllowlist(host, options.allowedHosts);\n const hostValidator = makeHostValidator(hostAllow);\n\n // Resolve auth mode. `trustForwardedAuth` is a convenience alias for\n // `authMode='proxy'` and may only promote an *unset* auth mode to\n // 'proxy'. It must NOT silently downgrade an explicit authMode (e.g.\n // 'oauth'), or the JWT validation layer would be bypassed.\n let authMode: AuthMode =\n options.authMode ?? (options.authToken ? 'bearer' : 'none');\n if (options.trustForwardedAuth && authMode === 'none') authMode = 'proxy';\n if (authMode === 'oauth' && !options.oauth) {\n throw new Error(\n 'startHttpServer: authMode=oauth requires `oauth` options (issuer at minimum)',\n );\n }\n if (authMode === 'invocation' && !options.invocationVerifier) {\n throw new Error(\n 'createHttpMcpHandler: authMode=invocation requires an invocation verifier',\n );\n }\n if (authMode === 'invocation' && !destinationServer) {\n throw new Error(\n 'createHttpMcpHandler: authMode=invocation requires destinationServer scope enforcement',\n );\n }\n const authMw = createAuthMiddleware({\n mode: authMode,\n token: options.authToken,\n oauth: options.oauth,\n invocationVerifier: options.invocationVerifier,\n onUserHint: options.onOAuthUserHint,\n });\n const cors = createCorsHandler({ allowedOrigins: options.allowedOrigins });\n\n const sessionMatchesAuthenticatedIdentity = (\n sessionId: string,\n userHint: UserHint | undefined,\n invocation: TrustedMcpInvocationClaims | undefined,\n res: http.ServerResponse,\n ): boolean => {\n if (!destinationServer) return true;\n const expected = sessionIdentityBindings.get(sessionId);\n if (!expected) {\n writeJsonError(res, 403, 'mcp_session_identity_mismatch');\n return false;\n }\n try {\n const identity =\n authMode === 'invocation'\n ? invocationRequestIdentity(invocation)\n : destinationServer.requestIdentity({ userHint, invocation });\n const actual = sessionIdentityBinding(identity, invocation?.tokenId);\n if (actual === expected) return true;\n } catch {\n // Treat a failed or malformed trusted identity derivation exactly like\n // a mismatch. Never fall back to a client field or session contents.\n }\n writeJsonError(res, 403, 'mcp_session_identity_mismatch');\n return false;\n };\n\n const handleMcp = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n userHint: UserHint | undefined,\n invocation: TrustedMcpInvocationClaims | undefined,\n ): Promise<void> => {\n const sessionHeader = req.headers['mcp-session-id'];\n const sessionId = Array.isArray(sessionHeader)\n ? sessionHeader[0]\n : sessionHeader;\n\n if (req.method === 'POST') {\n // Body must be parsed up-front to decide whether this is an\n // `initialize` request that should spawn a new transport.\n let body: unknown;\n try {\n body = await readJsonBody(req);\n } catch (err) {\n writeJsonError(\n res,\n 400,\n `Invalid JSON body: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n return;\n }\n\n if (sessionId && transports.has(sessionId)) {\n if (\n !sessionMatchesAuthenticatedIdentity(\n sessionId,\n userHint,\n invocation,\n res,\n )\n ) {\n return;\n }\n // Refresh the session's last-used timestamp so the TTL sweep\n // doesn't evict an actively-used session between tool calls.\n registry.touch(sessionId);\n const transport = transports.get(sessionId)!;\n await transport.handleRequest(req, res, body);\n return;\n }\n\n if (!sessionId && isInitializeRequest(body)) {\n let initializedSessionBinding: string | undefined;\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: (id) => {\n transports.set(id, transport);\n if (initializedSessionBinding) {\n sessionIdentityBindings.set(id, initializedSessionBinding);\n }\n log('info', `session initialized: ${id}`);\n },\n onsessionclosed: async (id) => {\n log('info', `session closed by client: ${id}`);\n await releaseSessionResources(id);\n },\n });\n\n transport.onclose = () => {\n const id = transport.sessionId;\n if (!id) return;\n void releaseSessionResources(id);\n };\n\n let sessionIdentity: RequestIdentity | undefined;\n let sessionAccess: McpRequestAccess | undefined;\n if (destinationServer) {\n let identityDerivationFailed = false;\n try {\n sessionIdentity =\n authMode === 'invocation'\n ? invocationRequestIdentity(invocation)\n : destinationServer.requestIdentity({ userHint, invocation });\n initializedSessionBinding = sessionIdentityBinding(\n sessionIdentity,\n invocation?.tokenId,\n );\n } catch {\n // A failed identity derivation must not turn into caller-selected\n // identity material. The fallback is audit-safe and fail-closed\n // once the lease provider applies its ordinary authorization.\n sessionIdentity = { principal: 'unknown' };\n identityDerivationFailed = true;\n }\n if (!identityDerivationFailed) {\n try {\n sessionAccess =\n authMode === 'invocation'\n ? invocationRequestAccess(invocation)\n : snapshotRequestAccess(\n destinationServer.requestAccess({ userHint, invocation }),\n );\n } catch {\n // Missing or failed trusted access derivation is intentionally\n // indistinguishable from no access at dispatch time.\n sessionAccess = undefined;\n }\n }\n }\n\n const mcp = createMcpServer({\n registry,\n resolveSystem: (id) => multiSystem.resolve(id),\n ...(destinationServer\n ? {\n destinationRegistry: destinationServer.destinationRegistry,\n requestIdentity: () =>\n sessionIdentity ?? { principal: 'unknown' },\n requestAccess: () => sessionAccess,\n ...(destinationServer.resolveFrozenSource\n ? {\n resolveFrozenSource:\n destinationServer.resolveFrozenSource,\n }\n : {}),\n ...(destinationServer.consumeExecutionAuthorization\n ? {\n consumeExecutionAuthorization:\n destinationServer.consumeExecutionAuthorization,\n }\n : {}),\n ...(destinationServer.reportExecutionOutcome\n ? {\n reportExecutionOutcome:\n destinationServer.reportExecutionOutcome,\n }\n : {}),\n ...(destinationServer.executeWithDeadline\n ? {\n executeWithDeadline:\n destinationServer.executeWithDeadline,\n }\n : {}),\n }\n : {}),\n });\n await mcp.connect(transport);\n // Store under the generated session id as soon as it exists.\n // `onsessioninitialized` also stores it, but we want the mapping\n // available for any in-flight follow-up immediately.\n if (transport.sessionId) {\n transports.set(transport.sessionId, transport);\n servers.set(transport.sessionId, mcp);\n }\n await transport.handleRequest(req, res, body);\n if (transport.sessionId && !servers.has(transport.sessionId)) {\n servers.set(transport.sessionId, mcp);\n }\n return;\n }\n\n writeJsonError(\n res,\n 400,\n sessionId\n ? `Unknown Mcp-Session-Id: ${sessionId}`\n : 'Missing Mcp-Session-Id header (non-initialize request)',\n );\n return;\n }\n\n if (req.method === 'GET' || req.method === 'DELETE') {\n if (!sessionId || !transports.has(sessionId)) {\n writeJsonError(res, 400, 'Missing or unknown Mcp-Session-Id header');\n return;\n }\n if (\n !sessionMatchesAuthenticatedIdentity(\n sessionId,\n userHint,\n invocation,\n res,\n )\n ) {\n return;\n }\n registry.touch(sessionId);\n const transport = transports.get(sessionId)!;\n await transport.handleRequest(req, res);\n return;\n }\n\n res.writeHead(405, { Allow: 'POST, GET, DELETE' });\n res.end();\n };\n\n const handle = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> => {\n try {\n // Pipeline order (security-critical):\n // 1. CORS — handles preflight short-circuit.\n // 2. Host-header validation — DNS-rebind protection.\n // 3. /healthz — NOT behind auth so monitoring probes work.\n // 4. Auth — bearer / proxy / none.\n // 5. Route to /mcp.\n if (cors.handle(req, res)) return;\n if (hostValidator(req, res)) return;\n\n const url = req.url ?? '/';\n const pathOnly = url.split('?')[0];\n\n if (pathOnly === '/healthz' && req.method === 'GET') {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n status: 'ok',\n sessions: registry.list().length,\n }),\n );\n return;\n }\n\n const authResult = await authMw(req, res);\n if (!authResult.allowed) return;\n // Accept /mcp and /mcp/ — ignore query string.\n if (pathOnly === '/mcp' || pathOnly === '/mcp/') {\n await handleMcp(req, res, authResult.userHint, authResult.invocation);\n return;\n }\n\n res.writeHead(404, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Not found' }));\n } catch (err) {\n log(\n 'error',\n `unhandled error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`,\n );\n writeJsonError(res, 500, 'Internal server error');\n }\n };\n\n let closed = false;\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n log('info', 'shutting down');\n await registry.shutdown();\n // Close each outstanding transport + server pair.\n const pairs = Array.from(transports.entries());\n transports.clear();\n for (const [sessionId] of pairs) sessionIdentityBindings.delete(sessionId);\n if (destinationServer) {\n await Promise.allSettled(\n pairs.map(\n async ([sessionId]) =>\n await destinationServer.destinationRegistry.releaseAll(sessionId),\n ),\n );\n }\n await Promise.allSettled(\n pairs.map(async ([, t]) => {\n try {\n await t.close();\n } catch {\n // ignore\n }\n }),\n );\n const srvs = Array.from(servers.values());\n servers.clear();\n await Promise.allSettled(\n srvs.map(async (s) => {\n try {\n await s.close();\n } catch {\n // ignore\n }\n }),\n );\n };\n\n return {\n registry,\n handle,\n close,\n };\n}\n\n/**\n * Starts the HTTP transport and returns a handle that can be used to close\n * both the listener and all active MCP sessions gracefully.\n *\n * This is a backwards-compatible listener adapter around\n * `createHttpMcpHandler` for standalone deployments.\n */\nexport async function startHttpServer(\n options: HttpServerOptions = {},\n): Promise<RunningHttpServer> {\n const port =\n options.port ??\n (process.env.MCP_PORT ? Number(process.env.MCP_PORT) : 3000);\n const host = options.host ?? process.env.MCP_HOST ?? '127.0.0.1';\n const log = options.log ?? defaultLog;\n // Resolve and validate TLS material before allocating the handler — a\n // missing or malformed certificate must not leak the session registry.\n const certPath = options.tlsCert ?? process.env.MCP_TLS_CERT;\n const keyPath = options.tlsKey ?? process.env.MCP_TLS_KEY;\n const cert =\n options.tlsCertContent ??\n (certPath ? await readFile(certPath, 'utf8') : undefined);\n const key =\n options.tlsKeyContent ??\n (keyPath ? await readFile(keyPath, 'utf8') : undefined);\n\n if (!cert || !key) {\n throw new Error(\n 'startHttpServer: TLS certificate and key are required. Provide tlsCert/tlsKey, ' +\n 'tlsCertContent/tlsKeyContent, or MCP_TLS_CERT/MCP_TLS_KEY.',\n );\n }\n if (\n !cert.includes('-----BEGIN CERTIFICATE-----') ||\n !cert.includes('-----END CERTIFICATE-----')\n ) {\n throw new Error(\n 'startHttpServer: TLS certificate is not valid PEM — expected a ' +\n '\"-----BEGIN CERTIFICATE-----\" block' +\n (certPath ? ` in ${certPath}` : ' in tlsCertContent') +\n '.',\n );\n }\n if (!key.includes('PRIVATE KEY-----')) {\n throw new Error(\n 'startHttpServer: TLS private key is not valid PEM — expected a ' +\n '\"-----BEGIN ... PRIVATE KEY-----\" block' +\n (keyPath ? ` in ${keyPath}` : ' in tlsKeyContent') +\n '.',\n );\n }\n\n const handler = createHttpMcpHandler(options);\n let server: https.Server;\n try {\n server = https.createServer({ cert, key }, (req, res) => {\n void handler.handle(req, res);\n });\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => reject(err);\n server.once('error', onError);\n server.listen(port, host, () => {\n server.removeListener('error', onError);\n resolve();\n });\n });\n } catch (err) {\n await handler.close().catch(() => undefined);\n throw err;\n }\n\n const boundPort = (server.address() as { port: number } | null)?.port ?? port;\n log('info', `listening on https://${host}:${boundPort}/mcp`);\n\n let closed = false;\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n await handler.close();\n // `server.close()` stops accepting new requests but can otherwise wait\n // indefinitely for a keep-alive socket which never created an MCP\n // transport (for example, a rejected bearer credential). Handler-owned\n // MCP transports have already been closed above, so force remaining HTTP\n // sockets closed before awaiting the listener callback.\n server.closeAllConnections();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n };\n\n return {\n url: `https://${host}:${boundPort}/mcp`,\n port: boundPort,\n host,\n registry: handler.registry,\n close,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,MAAM,iBAAiB;AAEvB,SAAgB,sBACd,UAAkC,CAAC,GAClB;CACjB,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,2BAAW,IAAI,IAA+B;CACpD,IAAI;CAEJ,MAAM,aAAa,UAAsD;EACvE,IAAI,SAAS;EACb,OAAO,YAAY;GACjB,IAAI,QAAQ;GACZ,SAAS;GACT,MAAM,MAAM;EACd;CACF;CAEA,MAAM,WAA4B;EAChC,OAAO,cAAc,KAAK,OAAO;GAC/B,MAAM,MAAM,KAAK,IAAI;GACrB,MAAM,UAA6B;IACjC;IACA,WAAW;IACX,YAAY;IACZ,GAAG;IACH,OAAO,UAAU,KAAK;GACxB;GACA,SAAS,IAAI,cAAc,OAAO;GAClC,OAAO;EACT;EACA,IAAI,cAAc;GAChB,OAAO,SAAS,IAAI,YAAY;EAClC;EACA,MAAM,cAAc;GAClB,MAAM,IAAI,SAAS,IAAI,YAAY;GACnC,IAAI,GAAG,EAAE,aAAa,KAAK,IAAI;EACjC;EACA,MAAM,OAAO,cAAc;GACzB,MAAM,IAAI,SAAS,IAAI,YAAY;GACnC,IAAI,CAAC,GAAG;GACR,SAAS,OAAO,YAAY;GAC5B,IAAI;IACF,MAAM,EAAE,MAAM;GAChB,QAAQ,CAER;EACF;EACA,OAAO;GACL,OAAO,MAAM,KAAK,SAAS,OAAO,CAAC;EACrC;EACA,MAAM,WAAW;GACf,IAAI,YAAY;IACd,cAAc,UAAU;IACxB,aAAa;GACf;GACA,MAAM,MAAM,MAAM,KAAK,SAAS,KAAK,CAAC;GACtC,MAAM,QAAQ,WAAW,IAAI,KAAK,OAAO,SAAS,OAAO,EAAE,CAAC,CAAC;EAC/D;CACF;CAEA,IAAI,QAAQ,GAAG;EACb,MAAM,WACJ,QAAQ,mBAAmB,KAAK,IAAI,KAAK,MAA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Xx1qL.mjs","names":["Buffer"],"sources":["../src/lib/session/registry.ts","../src/lib/http/multi-system.ts","../src/lib/http/oauth.ts","../src/lib/http/auth.ts","../src/lib/http/invocation.ts","../src/lib/http/cors.ts","../src/lib/http/server.ts"],"sourcesContent":["/**\n * In-memory session registry for the HTTP transport.\n *\n * The registry is intentionally simple: it stores `SapSessionContext`\n * instances keyed by MCP session id, tracks last-used timestamps, and\n * optionally evicts idle sessions after a TTL.\n *\n * Lifetime: a registry instance is process-scoped; it is created by the\n * HTTP bin and passed to `createMcpServer({ registry })`.\n */\n\nimport type { SapSessionContext } from './types.js';\n\nexport interface SessionRegistry {\n /**\n * Registers a new session. The caller provides everything except the\n * housekeeping fields (`createdAt`, `lastUsedAt`) and the idempotent\n * `close` handler, which is supplied as a separate argument so the\n * registry can wrap it for idempotency.\n */\n create(\n mcpSessionId: string,\n ctx: Omit<\n SapSessionContext,\n 'close' | 'createdAt' | 'lastUsedAt' | 'mcpSessionId'\n >,\n close: () => Promise<void>,\n ): SapSessionContext;\n get(mcpSessionId: string): SapSessionContext | undefined;\n touch(mcpSessionId: string): void;\n /** Removes the session and invokes its close handler. */\n delete(mcpSessionId: string): Promise<void>;\n list(): SapSessionContext[];\n /** Closes every session and stops background timers. */\n shutdown(): Promise<void>;\n}\n\nexport interface SessionRegistryOptions {\n /**\n * Idle TTL in milliseconds. Sessions with `now - lastUsedAt > ttlMs`\n * are evicted by a background sweep. Defaults to 30 minutes.\n * Set to 0 to disable TTL sweeping.\n */\n ttlMs?: number;\n /** Sweep interval in ms. Defaults to `min(ttlMs / 4, 60_000)`. */\n sweepIntervalMs?: number;\n}\n\nconst DEFAULT_TTL_MS = 30 * 60 * 1000;\n\nexport function createSessionRegistry(\n options: SessionRegistryOptions = {},\n): SessionRegistry {\n const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;\n const sessions = new Map<string, SapSessionContext>();\n let sweepTimer: NodeJS.Timeout | undefined;\n\n const wrapClose = (close: () => Promise<void>): (() => Promise<void>) => {\n let closed = false;\n return async () => {\n if (closed) return;\n closed = true;\n await close();\n };\n };\n\n const registry: SessionRegistry = {\n create(mcpSessionId, ctx, close) {\n const now = Date.now();\n const session: SapSessionContext = {\n mcpSessionId,\n createdAt: now,\n lastUsedAt: now,\n ...ctx,\n close: wrapClose(close),\n };\n sessions.set(mcpSessionId, session);\n return session;\n },\n get(mcpSessionId) {\n return sessions.get(mcpSessionId);\n },\n touch(mcpSessionId) {\n const s = sessions.get(mcpSessionId);\n if (s) s.lastUsedAt = Date.now();\n },\n async delete(mcpSessionId) {\n const s = sessions.get(mcpSessionId);\n if (!s) return;\n sessions.delete(mcpSessionId);\n try {\n await s.close();\n } catch {\n // best-effort cleanup; registry must not throw on delete\n }\n },\n list() {\n return Array.from(sessions.values());\n },\n async shutdown() {\n if (sweepTimer) {\n clearInterval(sweepTimer);\n sweepTimer = undefined;\n }\n const ids = Array.from(sessions.keys());\n await Promise.allSettled(ids.map((id) => registry.delete(id)));\n },\n };\n\n if (ttlMs > 0) {\n const interval =\n options.sweepIntervalMs ?? Math.min(Math.floor(ttlMs / 4), 60_000);\n sweepTimer = setInterval(\n () => {\n const cutoff = Date.now() - ttlMs;\n for (const s of sessions.values()) {\n if (s.lastUsedAt < cutoff) {\n void registry.delete(s.mcpSessionId);\n }\n }\n },\n Math.max(1000, interval),\n );\n // Don't hold the event loop open just for the sweeper.\n sweepTimer.unref?.();\n }\n\n return registry;\n}\n","/**\n * Multi-system configuration loader for adt-mcp HTTP transport.\n *\n * Resolves a logical system id (e.g. `DEV`, `PROD`) to concrete ADT\n * connection parameters. Sources (priority order):\n *\n * 1. `SAP_SYSTEMS_JSON` env var — inline JSON object\n * `{ \"DEV\": { \"baseUrl\": \"...\", \"client\": \"100\" }, ... }`\n * 2. `SAP_SYSTEMS_FILE` env var — path to a JSON file (YAML is NOT\n * supported in this wave to avoid adding new runtime deps).\n * 3. `~/.adt/systems.json` — default JSON file (YAML is NOT supported).\n *\n * Missing/empty config yields an empty registry, and `resolve()` returns\n * `undefined` for every id.\n *\n * Security policy: the registry holds ONLY connection metadata\n * (`baseUrl`, `client`). Credentials (`username`, `password`) MUST come\n * from the `sap_connect` tool call at runtime, never from disk. Any\n * `username`/`password` fields present in the JSON are silently dropped\n * with a warning so secrets-in-config mistakes don't leak.\n */\n\nimport { readFileSync, existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { ConnectionParams } from '../types.js';\n\nexport interface SystemEntry {\n baseUrl: string;\n client?: string;\n}\n\nexport interface MultiSystemConfig {\n systems: Record<string, SystemEntry>;\n resolve(systemId: string): ConnectionParams | undefined;\n}\n\ntype RawConfig = Record<\n string,\n { baseUrl?: string; client?: string; username?: unknown; password?: unknown }\n>;\n\nfunction parseJsonSafe(raw: string, source: string): RawConfig {\n try {\n const value = JSON.parse(raw);\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`expected a JSON object, got ${typeof value}`);\n }\n return value as RawConfig;\n } catch (err) {\n throw new Error(\n `Failed to parse multi-system config from ${source}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n}\n\nfunction normalise(raw: RawConfig): Record<string, SystemEntry> {\n const out: Record<string, SystemEntry> = {};\n for (const [id, entry] of Object.entries(raw)) {\n if (!entry || typeof entry !== 'object') continue;\n if (typeof entry.baseUrl !== 'string' || entry.baseUrl.length === 0) {\n continue;\n }\n if (entry.username || entry.password) {\n // Defence against secrets in disk config. Keep the system entry\n // but drop the credentials — caller must supply them at runtime.\n process.stderr.write(\n `[multi-system] warning: system '${id}' contains credentials ` +\n `in config; dropping them. Pass credentials via sap_connect at runtime.\\n`,\n );\n }\n out[id] = {\n baseUrl: entry.baseUrl,\n client: entry.client,\n };\n }\n return out;\n}\n\nexport function loadMultiSystemConfig(): MultiSystemConfig {\n let raw: RawConfig | undefined;\n\n if (process.env.SAP_SYSTEMS_JSON) {\n raw = parseJsonSafe(process.env.SAP_SYSTEMS_JSON, 'SAP_SYSTEMS_JSON');\n } else {\n const explicit = process.env.SAP_SYSTEMS_FILE;\n const defaultPath = join(homedir(), '.adt', 'systems.json');\n const path = explicit && explicit.length > 0 ? explicit : defaultPath;\n if (existsSync(path)) {\n raw = parseJsonSafe(readFileSync(path, 'utf8'), path);\n }\n }\n\n const systems = raw ? normalise(raw) : {};\n\n return {\n systems,\n resolve(systemId: string): ConnectionParams | undefined {\n const entry = systems[systemId];\n if (!entry) return undefined;\n return {\n baseUrl: entry.baseUrl,\n client: entry.client,\n };\n },\n };\n}\n","/**\n * OAuth 2.1 / OIDC bearer-token validator for the adt-mcp HTTP transport.\n *\n * adt-mcp is an MCP *resource server*, not an authorization server — we\n * only **validate** JWTs issued by an external IdP (Okta, Microsoft Entra\n * ID, AWS Cognito, Keycloak, Auth0, …). We do not issue tokens ourselves.\n *\n * Validation steps (per RFC 7519 + RFC 8725 + OAuth 2.1 Section 5.2):\n * 1. Extract `Authorization: Bearer <jwt>` (caller's responsibility).\n * 2. Fetch the JWKS for the configured `issuer`:\n * - If `jwksUri` is provided, use it directly.\n * - Otherwise discover via `${issuer}/.well-known/openid-configuration`.\n * 3. Verify signature + `iss` + `aud` + `exp`/`nbf` (with clock skew).\n * 4. Optionally enforce `requiredScopes` against the token's\n * `scope` (RFC 8693) or `scp` (Entra ID) claim.\n * 5. Extract a stable user identity from a configurable claim\n * (default chain: `preferred_username` → `email` → `sub`).\n *\n * The validator is stateless from the caller's perspective but internally\n * caches the JWKS (jose's `createRemoteJWKSet`) and the OIDC discovery\n * document for one hour.\n *\n * On failure the validator returns `{ valid: false, error }` — it never\n * throws. Callers translate that into an RFC 6750 401 response.\n */\n\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { JWTPayload } from 'jose';\nimport type { UserHint } from './auth.js';\n\nexport interface OAuthOptions {\n /** Expected `iss` claim, e.g. `https://company.okta.com/oauth2/default`. */\n issuer: string;\n /** Expected `aud` claim(s). Strongly recommended. */\n audience?: string | string[];\n /** Explicit JWKS endpoint; falls back to OIDC discovery when absent. */\n jwksUri?: string;\n /**\n * Scopes that must be present in the token's `scope`/`scp` claim. All\n * listed scopes are required (AND).\n */\n requiredScopes?: string[];\n /** Clock skew tolerance in seconds. Default 5. */\n clockTolerance?: number;\n /**\n * Primary claim to use as the user identity. When absent the validator\n * falls back to `preferred_username` → `email` → `sub`.\n */\n userClaim?: string;\n /** Claim to read as the user email. Default `email`. */\n emailClaim?: string;\n /** Claim to read as the groups array. Default `groups`. */\n groupsClaim?: string;\n}\n\nexport interface OAuthValidationResult {\n valid: boolean;\n claims?: JWTPayload;\n userHint?: UserHint;\n error?: string;\n}\n\nexport type OAuthValidator = (token: string) => Promise<OAuthValidationResult>;\n\ninterface DiscoveryDoc {\n issuer?: string;\n jwks_uri?: string;\n [key: string]: unknown;\n}\n\nconst DISCOVERY_TTL_MS = 60 * 60 * 1000; // 1 hour\n\ninterface DiscoveryCacheEntry {\n fetchedAt: number;\n doc: DiscoveryDoc;\n}\n\nconst discoveryCache = new Map<string, DiscoveryCacheEntry>();\n\nfunction trimTrailingSlash(s: string): string {\n return s.endsWith('/') ? s.slice(0, -1) : s;\n}\n\nasync function fetchDiscovery(issuer: string): Promise<DiscoveryDoc> {\n const now = Date.now();\n const cached = discoveryCache.get(issuer);\n if (cached && now - cached.fetchedAt < DISCOVERY_TTL_MS) {\n return cached.doc;\n }\n const url = `${trimTrailingSlash(issuer)}/.well-known/openid-configuration`;\n const res = await fetch(url, {\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) {\n throw new Error(\n `OIDC discovery failed for ${issuer}: HTTP ${res.status} ${res.statusText}`,\n );\n }\n const doc = (await res.json()) as DiscoveryDoc;\n if (!doc.jwks_uri || typeof doc.jwks_uri !== 'string') {\n throw new Error(\n `OIDC discovery document for ${issuer} is missing jwks_uri`,\n );\n }\n discoveryCache.set(issuer, { fetchedAt: now, doc });\n return doc;\n}\n\n/**\n * Extract the list of scopes from a token payload. Supports both the\n * OAuth 2.0 `scope` string claim (space-delimited) and the Entra ID\n * `scp` claim (string or array).\n */\nfunction extractScopes(claims: JWTPayload): string[] {\n const scope = (claims as Record<string, unknown>)['scope'];\n const scp = (claims as Record<string, unknown>)['scp'];\n const parts: string[] = [];\n if (typeof scope === 'string') {\n parts.push(\n ...scope\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s.length > 0),\n );\n }\n if (typeof scp === 'string') {\n parts.push(\n ...scp\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s.length > 0),\n );\n } else if (Array.isArray(scp)) {\n for (const v of scp) {\n if (typeof v === 'string' && v.length > 0) parts.push(v);\n }\n }\n return parts;\n}\n\nfunction extractUserHint(\n claims: JWTPayload,\n userClaim: string | undefined,\n emailClaim: string,\n groupsClaim: string,\n): UserHint | undefined {\n const record = claims as Record<string, unknown>;\n let user: string | undefined;\n if (userClaim) {\n const v = record[userClaim];\n if (typeof v === 'string' && v.length > 0) user = v;\n }\n if (!user) {\n for (const c of ['preferred_username', 'email', 'sub']) {\n const v = record[c];\n if (typeof v === 'string' && v.length > 0) {\n user = v;\n break;\n }\n }\n }\n if (!user) return undefined;\n\n const emailRaw = record[emailClaim];\n const email = typeof emailRaw === 'string' ? emailRaw : undefined;\n\n const groupsRaw = record[groupsClaim];\n let groups: string[] | undefined;\n if (Array.isArray(groupsRaw)) {\n groups = groupsRaw.filter((v): v is string => typeof v === 'string');\n } else if (typeof groupsRaw === 'string' && groupsRaw.length > 0) {\n groups = groupsRaw\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n return { user, email, groups };\n}\n\n/**\n * Build an OAuth/JWT validator for the configured issuer. Throws\n * synchronously on invalid options (e.g. missing issuer).\n */\nexport function createOAuthValidator(opts: OAuthOptions): OAuthValidator {\n if (!opts.issuer || opts.issuer.length === 0) {\n throw new Error('createOAuthValidator: `issuer` is required');\n }\n const issuer = opts.issuer;\n const audience = opts.audience;\n const requiredScopes = opts.requiredScopes ?? [];\n const clockTolerance = opts.clockTolerance ?? 5;\n const userClaim = opts.userClaim;\n const emailClaim = opts.emailClaim ?? 'email';\n const groupsClaim = opts.groupsClaim ?? 'groups';\n\n // JWKS URL may be known up-front (explicit config) or resolved lazily\n // from the discovery document. We cache the `createRemoteJWKSet` result\n // per URL so jose's internal key cache is reused across calls.\n let staticJwks: ReturnType<typeof createRemoteJWKSet> | undefined;\n if (opts.jwksUri) {\n staticJwks = createRemoteJWKSet(new URL(opts.jwksUri));\n }\n\n const resolvedJwks = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\n async function getJwks(): Promise<ReturnType<typeof createRemoteJWKSet>> {\n if (staticJwks) return staticJwks;\n const doc = await fetchDiscovery(issuer);\n const uri = doc.jwks_uri as string;\n let jwks = resolvedJwks.get(uri);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(uri));\n resolvedJwks.set(uri, jwks);\n }\n return jwks;\n }\n\n return async (token: string): Promise<OAuthValidationResult> => {\n if (!token || token.length === 0) {\n return { valid: false, error: 'missing_token' };\n }\n\n let jwks: ReturnType<typeof createRemoteJWKSet>;\n try {\n jwks = await getJwks();\n } catch (err) {\n return {\n valid: false,\n error: `discovery_failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n\n let payload: JWTPayload;\n try {\n const verified = await jwtVerify(token, jwks, {\n issuer,\n audience,\n clockTolerance,\n });\n payload = verified.payload;\n } catch (err) {\n return {\n valid: false,\n error: `invalid_token: ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n\n if (requiredScopes.length > 0) {\n const scopes = new Set(extractScopes(payload));\n const missing = requiredScopes.filter((s) => !scopes.has(s));\n if (missing.length > 0) {\n return {\n valid: false,\n claims: payload,\n error: `insufficient_scope: missing ${missing.join(', ')}`,\n };\n }\n }\n\n const userHint = extractUserHint(\n payload,\n userClaim,\n emailClaim,\n groupsClaim,\n );\n\n return { valid: true, claims: payload, userHint };\n };\n}\n\n/**\n * Test-only helper: reset the discovery cache. Not part of the public API.\n * @internal\n */\nexport function __resetOAuthDiscoveryCacheForTests(): void {\n discoveryCache.clear();\n}\n","/**\n * Auth middleware for the adt-mcp HTTP transport.\n *\n * Five modes:\n * - `none` — no authentication (dev / behind already-authenticated transport).\n * - `bearer` — require `Authorization: Bearer <token>` where `<token>` matches\n * the configured secret. Compared with `crypto.timingSafeEqual`.\n * - `proxy` — trust a reverse proxy (e.g. oauth2-proxy, Cloudflare Access).\n * Requires a non-empty `x-forwarded-user` header. Additional\n * identity hints (`x-forwarded-email`, `x-forwarded-groups`) are\n * collected into the returned `userHint`.\n * - `oauth` — validate an OIDC-issued JWT (Okta, Entra ID, Cognito, …)\n * against the configured issuer + audience + scopes. See\n * `./oauth.ts` for the validator implementation.\n * - `invocation` — validate an ADT-issued ES256 invocation credential and\n * surface only its immutable, trusted claims to the transport.\n *\n * The middleware writes a 401 JSON response on failure and returns\n * `{ allowed: false }`. The caller should stop processing. On success it\n * returns `{ allowed: true, userHint? }`; the caller may propagate the hint\n * to tool context for audit / per-user lock tracking.\n */\nimport http from 'node:http';\nimport { Buffer } from 'node:buffer';\nimport { timingSafeEqual } from 'node:crypto';\nimport { createOAuthValidator, type OAuthOptions } from './oauth.js';\nimport type {\n McpInvocationVerifier,\n TrustedMcpInvocationClaims,\n} from './invocation.js';\n\nexport type AuthMode = 'none' | 'bearer' | 'proxy' | 'oauth' | 'invocation';\n\nexport interface AuthMiddlewareOptions {\n mode: AuthMode;\n /** Required when mode==='bearer'. The expected bearer token secret. */\n token?: string;\n /** Required when mode==='oauth'. OIDC issuer / audience / scopes. */\n oauth?: OAuthOptions;\n /** Required when mode==='invocation'. ADT ES256 credential verifier. */\n invocationVerifier?: McpInvocationVerifier;\n /**\n * Test-only hook: invoked synchronously whenever an OAuth request\n * successfully authenticates, with the derived user hint. Production\n * code uses the normal `userHint` return value instead.\n * @internal\n */\n onUserHint?: (hint: UserHint | undefined) => void;\n}\n\nexport interface UserHint {\n user: string;\n email?: string;\n groups?: string[];\n}\n\nexport interface AuthResult {\n allowed: boolean;\n userHint?: UserHint;\n /** Immutable claims supplied only by a successful invocation verifier. */\n invocation?: TrustedMcpInvocationClaims;\n}\n\nexport type AuthMiddleware = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n) => AuthResult | Promise<AuthResult>;\n\nfunction writeUnauthorized(\n res: http.ServerResponse,\n oauthError?: string,\n): void {\n if (res.headersSent) {\n try {\n res.end();\n } catch {\n // ignore\n }\n return;\n }\n // RFC 6750 §3: the WWW-Authenticate challenge for bearer tokens. For\n // OAuth failures we include the standard `error` / `error_description`\n // parameters so clients can distinguish \"no token\", \"invalid token\",\n // and \"insufficient scope\".\n const challenge = oauthError\n ? `Bearer realm=\"adt-mcp\", error=\"${oauthError.split(':')[0].trim()}\", error_description=\"${oauthError.replaceAll('\"', \"'\")}\"`\n : 'Bearer realm=\"adt-mcp\"';\n res.writeHead(401, {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': challenge,\n });\n res.end(JSON.stringify({ error: oauthError ?? 'unauthorized' }));\n}\n\nfunction constantTimeEqualString(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n // Pad the shorter buffer so both are equal length (required for\n // timingSafeEqual). Any length mismatch is still caught by the\n // final equality check.\n const len = Math.max(ab.length, bb.length);\n const ap = Buffer.alloc(len);\n const bp = Buffer.alloc(len);\n ab.copy(ap);\n bb.copy(bp);\n const eq = timingSafeEqual(ap, bp);\n return eq && ab.length === bb.length;\n}\n\nfunction extractBearer(req: http.IncomingMessage): string | undefined {\n const h = req.headers['authorization'];\n const value = Array.isArray(h) ? h[0] : h;\n if (!value) return undefined;\n const trimmed = value.trim();\n // Case-insensitive \"Bearer\" prefix check without regex to avoid ReDoS.\n if (trimmed.length < 7) return undefined;\n const prefix = trimmed.slice(0, 6);\n if (prefix.toLowerCase() !== 'bearer') return undefined;\n // Skip a single required whitespace char, then any leading whitespace.\n const rest = trimmed.slice(6);\n if (rest.length === 0) return undefined;\n const first = rest.charCodeAt(0);\n // ASCII whitespace: space, tab, LF, CR, VT, FF.\n const isWs =\n first === 0x20 ||\n first === 0x09 ||\n first === 0x0a ||\n first === 0x0d ||\n first === 0x0b ||\n first === 0x0c;\n if (!isWs) return undefined;\n const token = rest.trimStart();\n return token.length > 0 ? token : undefined;\n}\n\nfunction headerString(\n req: http.IncomingMessage,\n name: string,\n): string | undefined {\n const raw = req.headers[name.toLowerCase()];\n if (!raw) return undefined;\n const value = Array.isArray(raw) ? raw[0] : raw;\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Build the auth middleware for the configured mode. Throws at creation\n * time for misconfiguration (e.g. `bearer` mode with no token).\n */\nexport function createAuthMiddleware(\n options: AuthMiddlewareOptions,\n): AuthMiddleware {\n if (options.mode === 'bearer') {\n if (!options.token || options.token.length === 0) {\n throw new Error(\n 'createAuthMiddleware: bearer mode requires a non-empty token',\n );\n }\n const expected = options.token;\n return (req, res) => {\n const presented = extractBearer(req);\n if (!presented || !constantTimeEqualString(presented, expected)) {\n writeUnauthorized(res);\n return { allowed: false };\n }\n return { allowed: true };\n };\n }\n\n if (options.mode === 'proxy') {\n return (req, res) => {\n const user = headerString(req, 'x-forwarded-user');\n if (!user) {\n writeUnauthorized(res);\n return { allowed: false };\n }\n const email = headerString(req, 'x-forwarded-email');\n const groupsRaw = headerString(req, 'x-forwarded-groups');\n const groups = groupsRaw\n ? groupsRaw\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0)\n : undefined;\n return { allowed: true, userHint: { user, email, groups } };\n };\n }\n\n if (options.mode === 'oauth') {\n if (!options.oauth) {\n throw new Error(\n 'createAuthMiddleware: oauth mode requires an `oauth` option',\n );\n }\n const validator = createOAuthValidator(options.oauth);\n const onUserHint = options.onUserHint;\n return async (req, res) => {\n const presented = extractBearer(req);\n if (!presented) {\n writeUnauthorized(res, 'invalid_token: missing bearer token');\n return { allowed: false };\n }\n const result = await validator(presented);\n if (!result.valid) {\n // Map to RFC 6750 error codes. `insufficient_scope` must remain\n // a distinct category so the client knows the user needs a\n // re-consent, not a re-login.\n const err = result.error ?? 'invalid_token';\n writeUnauthorized(res, err);\n return { allowed: false };\n }\n if (onUserHint) onUserHint(result.userHint);\n return { allowed: true, userHint: result.userHint };\n };\n }\n\n if (options.mode === 'invocation') {\n if (!options.invocationVerifier) {\n throw new Error(\n 'createAuthMiddleware: invocation mode requires an invocation verifier',\n );\n }\n const verifier = options.invocationVerifier;\n return async (req, res) => {\n const invocation = await verifier.verify(req.headers.authorization);\n if (!invocation) {\n // Do not expose verifier failures, decoded claims, or a distinction\n // between a missing, expired, or invalid credential.\n writeUnauthorized(res, 'invalid_token');\n return { allowed: false };\n }\n return { allowed: true, invocation };\n };\n }\n\n // mode === 'none'\n return () => ({ allowed: true });\n}\n","/**\n * Verification for ADT-issued MCP invocation credentials.\n *\n * This module is deliberately transport-independent: callers pass the\n * complete Authorization header and receive either immutable, trusted claims\n * or `undefined`. It does not log or throw token-validation failures, so a\n * bearer credential or its decoded payload can never leak through an error.\n */\nimport type { KeyObject } from 'node:crypto';\nimport { jwtVerify, type CryptoKey, type JWTPayload } from 'jose';\n\nconst INVOCATION_VERSION = 1;\nconst MAX_IDENTIFIER_LENGTH = 256;\nconst MAX_COMPONENT_IDENTIFIER_LENGTH = 512;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_TOKEN_LIFETIME_SECONDS = 5 * 60;\nconst MAX_FROZEN_SOURCES = 500;\nconst MAX_SOURCE_REFERENCE_LENGTH = 8 * 1024;\nconst MAX_FROZEN_SOURCE_BYTES = 2 * 1024 * 1024;\nconst MAX_SCOPED_OBJECT_KEYS = 100;\nconst MAX_SCOPED_TOOL_CALLS = 12;\nconst MAX_SAFE_EXECUTE_GRANT_BYTES = 16 * 1024;\nconst destinationKeyPattern = /^[a-z][a-z0-9-]{1,62}$/u;\nconst canonicalKeyPattern = /^[A-Z0-9_]+:.+$/u;\nconst scopedCanonicalObjectKeyPattern =\n /^[A-Z0-9_]{2,30}:[A-Z0-9_/$-]{1,128}$/u;\nconst compactJwsPattern = /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/u;\nconst uuidPattern =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nconst trustedAgentIds = new Set([\n 'ai-review',\n 'system-assistant',\n 'autonomous-review-agent',\n 'adt-execution',\n 'delegated-assistant',\n]);\nconst trustedOperationClasses = new Set(['server', 'read', 'safe_execute']);\nconst scopedReadTools = new Set(['get_object', 'get_object_structure']);\n\nexport type McpTrustedOperationClass = 'server' | 'read' | 'safe_execute';\n\nexport type McpInvocationJsonValue =\n | boolean\n | number\n | string\n | null\n | readonly McpInvocationJsonValue[]\n | Readonly<Record<string, McpInvocationJsonValue>>;\n\n/** Claims proved by a verified, ADT-issued invocation credential. */\nexport interface TrustedMcpInvocationClaims {\n readonly tokenId: string;\n readonly principal: string;\n readonly agentId:\n | 'ai-review'\n | 'system-assistant'\n | 'autonomous-review-agent'\n | 'adt-execution'\n | 'delegated-assistant';\n readonly classes: readonly McpTrustedOperationClass[];\n readonly destinationKeys: readonly string[];\n readonly correlationId: string;\n readonly constraint: Readonly<Record<string, McpInvocationJsonValue>>;\n readonly limits: Readonly<Record<string, McpInvocationJsonValue>>;\n}\n\n/**\n * Fully enforced narrowing policy for an AI Review source read. `sourceRef`\n * remains opaque to MCP clients and models; only ADT's private broker can\n * redeem it after this policy has selected the exact canonical object and\n * source component.\n */\nexport interface AiReviewFrozenSourcePolicy {\n readonly reviewId: string;\n readonly runId: string;\n readonly systemSid: string;\n readonly sources: readonly {\n readonly canonicalKey: string;\n readonly componentId: string;\n readonly sourceRef: string;\n }[];\n readonly maxSourceBytes: number;\n}\n\nexport type SafeExecutePolicy =\n | {\n readonly operationId: 'atc_run';\n readonly check: 'atc';\n readonly maxDurationMs: number;\n readonly maxResultBytes: number;\n readonly maxFindings: number;\n readonly maxObjects: number;\n readonly maxPackages: number;\n readonly maxVariants: number;\n }\n | {\n readonly operationId: 'run_unit_tests';\n readonly check: 'aunit';\n readonly effectiveWithCoverage: false;\n readonly effectiveCoverageFormat: null;\n readonly maxDurationMs: number;\n readonly maxResultBytes: number;\n readonly maxFindings: number;\n readonly maxObjects: number;\n readonly maxTestClasses: number;\n readonly maxTestMethods: number;\n }\n | {\n readonly operationId: 'run_unit_tests';\n readonly check: 'coverage';\n readonly effectiveWithCoverage: true;\n readonly effectiveCoverageFormat: 'jacoco' | 'sonar-generic';\n readonly maxDurationMs: number;\n readonly maxResultBytes: number;\n readonly maxFindings: number;\n readonly maxObjects: number;\n readonly maxPrograms: number;\n readonly maxMeasurements: number;\n };\n\nexport interface ScopedAdtInvocationPolicy {\n readonly scopeId: string;\n readonly executionId: string;\n readonly systemSid: string;\n readonly resourceKeys: readonly string[];\n readonly toolNames: readonly string[];\n readonly operationClass: 'read' | 'safe_execute';\n readonly maxToolCalls: number;\n readonly safeExecutePolicy?: SafeExecutePolicy;\n /** Server-owned opaque grant material; never exposed in a tool schema. */\n readonly authorizationId?: string;\n readonly authorizationToken?: string;\n}\n\nexport interface DelegatedAssistantReadPolicy {\n readonly threadId: string;\n readonly executionId: string;\n readonly systemSid: string;\n}\n\nexport interface McpInvocationVerifierOptions {\n /** ES256 public key mounted at ADT Server; it cannot issue credentials. */\n publicKey: CryptoKey | KeyObject;\n /** The exact key id required in both JWS header and JWT payload. */\n keyId: string;\n /** The exact ADT API issuer expected in `iss`. */\n issuer: string;\n /** The exact audience expected in `aud`. */\n audience: string;\n /** Test-only clock injection. Production defaults to the current time. */\n now?: () => Date | number;\n}\n\nexport interface McpInvocationVerifier {\n /**\n * Verify a complete `Authorization: Bearer <JWS>` header. Validation\n * failures are intentionally indistinguishable and return `undefined`.\n */\n verify(\n authorizationHeader: string | string[] | undefined,\n ): Promise<TrustedMcpInvocationClaims | undefined>;\n}\n\n/**\n * Reports whether this sidecar version can enforce every narrowing claim for\n * an invocation. Unsupported policies deliberately receive no MCP tool\n * access; accepting a syntactically valid policy without enforcing it would\n * widen the signed credential.\n *\n * Every admitted policy has an exact parser. Structurally incomplete or\n * unknown policies fail closed.\n */\nfunction isSystemAssistantPolicySupported(\n claims: TrustedMcpInvocationClaims,\n): boolean {\n if (\n !hasServerReadClasses(claims) ||\n Object.keys(claims.limits).length !== 0\n ) {\n return false;\n }\n const constraintKeys = Object.keys(claims.constraint);\n return (\n constraintKeys.length === 1 &&\n constraintKeys[0] === 'systemSid' &&\n requiredIdentifier(claims.constraint.systemSid) !== undefined\n );\n}\n\nfunction hasServerReadClasses(claims: TrustedMcpInvocationClaims): boolean {\n return (\n claims.classes.length === 2 &&\n claims.classes.includes('server') &&\n claims.classes.includes('read')\n );\n}\n\nexport function parseDelegatedAssistantReadPolicy(\n claims: TrustedMcpInvocationClaims,\n): DelegatedAssistantReadPolicy | undefined {\n if (\n claims.agentId !== 'delegated-assistant' ||\n claims.destinationKeys.length !== 1 ||\n !hasServerReadClasses(claims) ||\n Object.keys(claims.limits).length !== 0 ||\n !hasExactSortedKeys(claims.constraint, [\n 'kind',\n 'threadId',\n 'executionId',\n 'systemSid',\n ]) ||\n claims.constraint.kind !== 'delegated-assistant-read-v1'\n ) {\n return undefined;\n }\n\n const threadId = requiredUuid(claims.constraint.threadId);\n const executionId = requiredUuid(claims.constraint.executionId);\n const systemSid = requiredSystemSid(claims.constraint.systemSid);\n if (!threadId || !executionId || !systemSid) return undefined;\n\n return Object.freeze({ threadId, executionId, systemSid });\n}\n\nexport function isMcpInvocationDispatchPolicySupported(\n claims: TrustedMcpInvocationClaims,\n): boolean {\n if (claims.agentId === 'system-assistant') {\n return isSystemAssistantPolicySupported(claims);\n }\n if (claims.agentId === 'autonomous-review-agent') {\n return (\n hasServerReadClasses(claims) &&\n claims.destinationKeys.length === 1 &&\n parseAutonomousReviewAgentPolicy(claims) !== undefined\n );\n }\n if (claims.agentId === 'adt-execution') {\n return parseScopedAdtInvocationPolicy(claims) !== undefined;\n }\n if (claims.agentId === 'delegated-assistant') {\n return parseDelegatedAssistantReadPolicy(claims) !== undefined;\n }\n if (claims.agentId === 'ai-review') {\n return (\n hasServerReadClasses(claims) &&\n claims.destinationKeys.length === 1 &&\n parseAiReviewFrozenSourcePolicy(claims) !== undefined\n );\n }\n return false;\n}\n\n/**\n * The autonomous agent may inspect exactly one System through exactly one\n * Destination. Its execution id binds every ADT activity to ADT's durable\n * Agent Execution, while the sidecar's ordinary scope catalogue continues to\n * deny write tools. No ambient limits or additional constraints are accepted.\n */\nexport function parseAutonomousReviewAgentPolicy(\n claims: TrustedMcpInvocationClaims,\n): { readonly executionId: string; readonly systemSid: string } | undefined {\n if (claims.agentId !== 'autonomous-review-agent') return undefined;\n if (Object.keys(claims.limits).length !== 0) return undefined;\n const constraintKeys = Object.keys(claims.constraint).sort((a, b) =>\n a.localeCompare(b),\n );\n if (constraintKeys.length !== 2) return undefined;\n if (constraintKeys[0] !== 'executionId') return undefined;\n if (constraintKeys[1] !== 'systemSid') return undefined;\n const executionId = requiredUuid(claims.constraint.executionId);\n const systemSid = requiredSystemSid(claims.constraint.systemSid);\n if (!executionId || !systemSid) return undefined;\n return Object.freeze({ executionId, systemSid });\n}\n\nfunction requiredUuid(value: unknown): string | undefined {\n return typeof value === 'string' && uuidPattern.test(value)\n ? value\n : undefined;\n}\n\nfunction requiredSourceReference(value: unknown): string | undefined {\n return requiredString(value, { maxLength: MAX_SOURCE_REFERENCE_LENGTH });\n}\n\nfunction hasExactSortedKeys(\n value: Readonly<Record<string, unknown>>,\n expected: readonly string[],\n): boolean {\n const actual = Object.keys(value).sort((left, right) =>\n left.localeCompare(right),\n );\n const sortedExpected = [...expected].sort((left, right) =>\n left.localeCompare(right),\n );\n return (\n actual.length === sortedExpected.length &&\n actual.every((key, index) => key === sortedExpected[index])\n );\n}\n\nfunction positiveSafeInteger(value: unknown): number | undefined {\n return Number.isSafeInteger(value) && (value as number) > 0\n ? (value as number)\n : undefined;\n}\n\nfunction parseSafeExecuteCommon(\n value: Readonly<Record<string, McpInvocationJsonValue>>,\n):\n | {\n maxDurationMs: number;\n maxResultBytes: number;\n maxFindings: number;\n maxObjects: number;\n }\n | undefined {\n const maxDurationMs = positiveSafeInteger(value.maxDurationMs);\n const maxResultBytes = positiveSafeInteger(value.maxResultBytes);\n const maxFindings = positiveSafeInteger(value.maxFindings);\n const maxObjects = positiveSafeInteger(value.maxObjects);\n if (\n maxDurationMs === undefined ||\n maxResultBytes === undefined ||\n maxFindings === undefined ||\n maxObjects === undefined\n ) {\n return undefined;\n }\n return { maxDurationMs, maxResultBytes, maxFindings, maxObjects };\n}\n\nconst safeExecuteCommonKeys = [\n 'operationId',\n 'check',\n 'maxDurationMs',\n 'maxResultBytes',\n 'maxFindings',\n 'maxObjects',\n] as const;\n\nfunction parseAtcSafeExecutePolicy(\n cloned: Record<string, McpInvocationJsonValue>,\n common: ReturnType<typeof parseSafeExecuteCommon>,\n): SafeExecutePolicy | undefined {\n if (!common) return undefined;\n if (\n cloned.operationId !== 'atc_run' ||\n cloned.check !== 'atc' ||\n !hasExactSortedKeys(cloned, [\n ...safeExecuteCommonKeys,\n 'maxPackages',\n 'maxVariants',\n ])\n ) {\n return undefined;\n }\n const maxPackages = positiveSafeInteger(cloned.maxPackages);\n const maxVariants = positiveSafeInteger(cloned.maxVariants);\n if (maxPackages === undefined || maxVariants === undefined) {\n return undefined;\n }\n return Object.freeze({\n operationId: 'atc_run',\n check: 'atc',\n ...common,\n maxPackages,\n maxVariants,\n });\n}\n\nfunction parseAunitSafeExecutePolicy(\n cloned: Record<string, McpInvocationJsonValue>,\n common: ReturnType<typeof parseSafeExecuteCommon>,\n): SafeExecutePolicy | undefined {\n if (!common) return undefined;\n if (\n cloned.operationId !== 'run_unit_tests' ||\n cloned.check !== 'aunit' ||\n cloned.effectiveWithCoverage !== false ||\n cloned.effectiveCoverageFormat !== null ||\n !hasExactSortedKeys(cloned, [\n ...safeExecuteCommonKeys,\n 'effectiveWithCoverage',\n 'effectiveCoverageFormat',\n 'maxTestClasses',\n 'maxTestMethods',\n ])\n ) {\n return undefined;\n }\n const maxTestClasses = positiveSafeInteger(cloned.maxTestClasses);\n const maxTestMethods = positiveSafeInteger(cloned.maxTestMethods);\n if (maxTestClasses === undefined || maxTestMethods === undefined) {\n return undefined;\n }\n return Object.freeze({\n operationId: 'run_unit_tests',\n check: 'aunit',\n effectiveWithCoverage: false,\n effectiveCoverageFormat: null,\n ...common,\n maxTestClasses,\n maxTestMethods,\n });\n}\n\nfunction parseCoverageSafeExecutePolicy(\n cloned: Record<string, McpInvocationJsonValue>,\n common: ReturnType<typeof parseSafeExecuteCommon>,\n): SafeExecutePolicy | undefined {\n if (!common) return undefined;\n const format = cloned.effectiveCoverageFormat;\n if (\n cloned.operationId !== 'run_unit_tests' ||\n cloned.check !== 'coverage' ||\n cloned.effectiveWithCoverage !== true ||\n (format !== 'jacoco' && format !== 'sonar-generic') ||\n !hasExactSortedKeys(cloned, [\n ...safeExecuteCommonKeys,\n 'effectiveWithCoverage',\n 'effectiveCoverageFormat',\n 'maxPrograms',\n 'maxMeasurements',\n ])\n ) {\n return undefined;\n }\n const maxPrograms = positiveSafeInteger(cloned.maxPrograms);\n const maxMeasurements = positiveSafeInteger(cloned.maxMeasurements);\n if (maxPrograms === undefined || maxMeasurements === undefined) {\n return undefined;\n }\n return Object.freeze({\n operationId: 'run_unit_tests',\n check: 'coverage',\n effectiveWithCoverage: true,\n effectiveCoverageFormat: format,\n ...common,\n maxPrograms,\n maxMeasurements,\n });\n}\n\nexport function parseSafeExecutePolicy(\n value: unknown,\n): SafeExecutePolicy | undefined {\n if (!isPlainObject(value)) return undefined;\n const cloned = cloneJsonRecord(value);\n if (!cloned) return undefined;\n const common = parseSafeExecuteCommon(cloned);\n\n return (\n parseAtcSafeExecutePolicy(cloned, common) ??\n parseAunitSafeExecutePolicy(cloned, common) ??\n parseCoverageSafeExecutePolicy(cloned, common)\n );\n}\n\nfunction parseSortedUniqueStrings(\n value: unknown,\n options: {\n maxItems: number;\n minItems: number;\n matches: (item: string) => boolean;\n },\n): readonly string[] | undefined {\n if (\n !Array.isArray(value) ||\n value.length < options.minItems ||\n value.length > options.maxItems\n ) {\n return undefined;\n }\n const parsed: string[] = [];\n for (const item of value) {\n if (\n typeof item !== 'string' ||\n !options.matches(item) ||\n parsed.includes(item)\n ) {\n return undefined;\n }\n parsed.push(item);\n }\n const sorted = [...parsed].sort((left, right) => left.localeCompare(right));\n if (!parsed.every((item, index) => item === sorted[index])) return undefined;\n return Object.freeze(parsed);\n}\n\nfunction parseScopedObjectKeys(value: unknown): readonly string[] | undefined {\n return parseSortedUniqueStrings(value, {\n maxItems: MAX_SCOPED_OBJECT_KEYS,\n minItems: 1,\n matches: (item) => scopedCanonicalObjectKeyPattern.test(item),\n });\n}\n\nfunction parseScopedToolNames(\n value: unknown,\n operationClass: 'read' | 'safe_execute',\n safeExecutePolicy: SafeExecutePolicy | undefined,\n): readonly string[] | undefined {\n const toolNames = parseSortedUniqueStrings(value, {\n maxItems: operationClass === 'read' ? scopedReadTools.size : 1,\n minItems: 1,\n matches: (item) =>\n operationClass === 'read'\n ? scopedReadTools.has(item)\n : item === 'atc_run' || item === 'run_unit_tests',\n });\n if (!toolNames) return undefined;\n if (operationClass === 'read') {\n return safeExecutePolicy === undefined ? toolNames : undefined;\n }\n return safeExecutePolicy && toolNames[0] === safeExecutePolicy.operationId\n ? toolNames\n : undefined;\n}\n\nfunction parseExecutionAuthorizationToken(value: unknown): string | undefined {\n return typeof value === 'string' &&\n value.length <= MAX_SAFE_EXECUTE_GRANT_BYTES &&\n compactJwsPattern.test(value)\n ? value\n : undefined;\n}\n\nexport function parseScopedAdtInvocationPolicy(\n claims: TrustedMcpInvocationClaims,\n): ScopedAdtInvocationPolicy | undefined {\n if (\n claims.agentId !== 'adt-execution' ||\n claims.destinationKeys.length !== 1\n ) {\n return undefined;\n }\n if (\n claims.classes.length !== 2 ||\n claims.classes[0] !== 'server' ||\n (claims.classes[1] !== 'read' && claims.classes[1] !== 'safe_execute')\n ) {\n return undefined;\n }\n const operationClass = claims.classes[1];\n const safeExecute = operationClass === 'safe_execute';\n const expectedConstraintKeys = [\n 'kind',\n 'scopeId',\n 'executionId',\n 'systemSid',\n 'resourceKeys',\n 'toolNames',\n ...(safeExecute\n ? ['safeExecutePolicy', 'authorizationId', 'authorizationToken']\n : []),\n ];\n if (!hasExactSortedKeys(claims.constraint, expectedConstraintKeys)) {\n return undefined;\n }\n if (\n claims.constraint.kind !== 'adt-execution-v1' ||\n !hasExactSortedKeys(claims.limits, ['maxToolCalls'])\n ) {\n return undefined;\n }\n\n const scopeId = requiredUuid(claims.constraint.scopeId);\n const executionId = requiredUuid(claims.constraint.executionId);\n const systemSid = requiredSystemSid(claims.constraint.systemSid);\n const resourceKeys = parseScopedObjectKeys(claims.constraint.resourceKeys);\n const maxToolCalls = positiveSafeInteger(claims.limits.maxToolCalls);\n if (\n !scopeId ||\n !executionId ||\n !systemSid ||\n !resourceKeys ||\n maxToolCalls === undefined ||\n maxToolCalls > MAX_SCOPED_TOOL_CALLS\n ) {\n return undefined;\n }\n\n const safeExecutePolicy = safeExecute\n ? parseSafeExecutePolicy(claims.constraint.safeExecutePolicy)\n : undefined;\n const toolNames = parseScopedToolNames(\n claims.constraint.toolNames,\n operationClass,\n safeExecutePolicy,\n );\n if (!toolNames) return undefined;\n\n if (!safeExecute) {\n return Object.freeze({\n scopeId,\n executionId,\n systemSid,\n resourceKeys,\n toolNames,\n operationClass,\n maxToolCalls,\n });\n }\n\n const authorizationId = requiredUuid(claims.constraint.authorizationId);\n const authorizationToken = parseExecutionAuthorizationToken(\n claims.constraint.authorizationToken,\n );\n if (!safeExecutePolicy || !authorizationId || !authorizationToken) {\n return undefined;\n }\n return Object.freeze({\n scopeId,\n executionId,\n systemSid,\n resourceKeys,\n toolNames,\n operationClass,\n maxToolCalls,\n safeExecutePolicy,\n authorizationId,\n authorizationToken,\n });\n}\n\nexport function parseFrozenSource(\n source: unknown,\n sourceKeys: Set<string>,\n sourceRefs: Set<string>,\n):\n | {\n readonly canonicalKey: string;\n readonly componentId: string;\n readonly sourceRef: string;\n }\n | undefined {\n if (!isPlainObject(source)) return undefined;\n const canonicalKey = source.canonicalKey;\n const componentId = requiredComponentIdentifier(source.componentId);\n const sourceRef = requiredSourceReference(source.sourceRef);\n if (typeof canonicalKey !== 'string') return undefined;\n if (!canonicalKeyPattern.test(canonicalKey)) return undefined;\n if (!componentId || !sourceRef) return undefined;\n const key = `${canonicalKey}\\u0000${componentId}`;\n if (sourceKeys.has(key) || sourceRefs.has(sourceRef)) return undefined;\n sourceKeys.add(key);\n sourceRefs.add(sourceRef);\n return Object.freeze({ canonicalKey, componentId, sourceRef });\n}\n\n/**\n * Parse the only AI Review policy currently safe to dispatch. Every property\n * is deliberately exact: accepting a valid JWS with one ignored narrowing\n * field would widen the Review beyond its frozen materialisation.\n */\nconst expectedAiReviewConstraintKeys = [\n 'frozenSources',\n 'kind',\n 'reviewId',\n 'runId',\n 'systemSid',\n];\n\nfunction isSortedKeysEqual(\n keys: readonly string[],\n expected: readonly string[],\n): boolean {\n return (\n keys.length === expected.length &&\n keys.every((key, index) => key === expected[index])\n );\n}\n\nfunction parseAiReviewSources(rawSources: unknown):\n | {\n readonly canonicalKey: string;\n readonly componentId: string;\n readonly sourceRef: string;\n }[]\n | undefined {\n if (!Array.isArray(rawSources)) return undefined;\n if (rawSources.length === 0 || rawSources.length > MAX_FROZEN_SOURCES) {\n return undefined;\n }\n const sourceKeys = new Set<string>();\n const sourceRefs = new Set<string>();\n const sources: {\n canonicalKey: string;\n componentId: string;\n sourceRef: string;\n }[] = [];\n for (const rawSource of rawSources) {\n if (!isPlainObject(rawSource)) return undefined;\n const rawSourceKeys = Object.keys(rawSource).sort((a, b) =>\n a.localeCompare(b),\n );\n if (rawSourceKeys.length !== 3) return undefined;\n if (rawSourceKeys[0] !== 'canonicalKey') return undefined;\n if (rawSourceKeys[1] !== 'componentId') return undefined;\n if (rawSourceKeys[2] !== 'sourceRef') return undefined;\n const parsed = parseFrozenSource(rawSource, sourceKeys, sourceRefs);\n if (!parsed) return undefined;\n sources.push(parsed);\n }\n return sources;\n}\n\nfunction parseMaxSourceBytes(\n limits: Readonly<Record<string, McpInvocationJsonValue>>,\n): number | undefined {\n const limitKeys = Object.keys(limits);\n if (limitKeys.length !== 1) return undefined;\n if (limitKeys[0] !== 'maxSourceBytes') return undefined;\n const maxSourceBytes = limits.maxSourceBytes;\n if (typeof maxSourceBytes !== 'number') return undefined;\n if (!Number.isSafeInteger(maxSourceBytes)) return undefined;\n if (maxSourceBytes < 1) return undefined;\n if (maxSourceBytes > MAX_FROZEN_SOURCE_BYTES) return undefined;\n return maxSourceBytes;\n}\n\nfunction parseAiReviewIdentity(\n constraint: Readonly<Record<string, McpInvocationJsonValue>>,\n):\n | {\n readonly reviewId: string;\n readonly runId: string;\n readonly systemSid: string;\n }\n | undefined {\n const reviewId = requiredUuid(constraint.reviewId);\n const runId = requiredUuid(constraint.runId);\n const systemSid = requiredIdentifier(constraint.systemSid);\n if (!reviewId) return undefined;\n if (!runId) return undefined;\n if (!systemSid) return undefined;\n if (systemSid.length > 16) return undefined;\n return Object.freeze({ reviewId, runId, systemSid });\n}\n\nexport function parseAiReviewFrozenSourcePolicy(\n claims: TrustedMcpInvocationClaims,\n): AiReviewFrozenSourcePolicy | undefined {\n if (claims.agentId !== 'ai-review') return undefined;\n const constraint = claims.constraint;\n const constraintKeys = Object.keys(constraint).sort((a, b) =>\n a.localeCompare(b),\n );\n if (!isSortedKeysEqual(constraintKeys, expectedAiReviewConstraintKeys)) {\n return undefined;\n }\n if (constraint.kind !== 'ai-review-frozen-v1') return undefined;\n\n const identity = parseAiReviewIdentity(constraint);\n if (!identity) return undefined;\n\n const sources = parseAiReviewSources(constraint.frozenSources);\n if (!sources) return undefined;\n\n const maxSourceBytes = parseMaxSourceBytes(claims.limits);\n if (maxSourceBytes === undefined) return undefined;\n\n return Object.freeze({\n reviewId: identity.reviewId,\n runId: identity.runId,\n systemSid: identity.systemSid,\n sources: Object.freeze(sources),\n maxSourceBytes,\n });\n}\n\nfunction requiredString(\n value: unknown,\n options: {\n readonly maxLength: number;\n readonly trim?: boolean;\n readonly allowControlChars?: boolean;\n },\n): string | undefined {\n if (typeof value !== 'string') return undefined;\n if (value.length === 0 || value.length > options.maxLength) return undefined;\n if (options.trim && value.trim().length === 0) return undefined;\n if (\n !options.allowControlChars &&\n // eslint-disable-next-line no-control-regex\n /[\\s\\u0000-\\u0008\\u000e-\\u001f\\u007f]/u.test(value)\n ) {\n return undefined;\n }\n return value;\n}\n\nfunction requiredIdentifier(value: unknown): string | undefined {\n return requiredString(value, {\n maxLength: MAX_IDENTIFIER_LENGTH,\n trim: true,\n allowControlChars: true,\n });\n}\n\nfunction requiredSystemSid(value: unknown): string | undefined {\n const systemSid = requiredIdentifier(value);\n return systemSid &&\n systemSid.length <= 16 &&\n /^[A-Za-z0-9_-]+$/u.test(systemSid)\n ? systemSid\n : undefined;\n}\n\nfunction requiredComponentIdentifier(value: unknown): string | undefined {\n return requiredString(value, { maxLength: MAX_COMPONENT_IDENTIFIER_LENGTH });\n}\n\nfunction requiredConfigurationIdentifier(value: unknown, name: string): string {\n const identifier = requiredIdentifier(value);\n if (!identifier) {\n throw new Error(`MCP invocation verifier requires a valid ${name}`);\n }\n return identifier;\n}\n\nfunction extractBearerCredential(\n authorizationHeader: string | string[] | undefined,\n): string | undefined {\n if (Array.isArray(authorizationHeader)) return undefined;\n if (typeof authorizationHeader !== 'string') return undefined;\n const header = authorizationHeader.trim();\n if (header.length < 8 || header.slice(0, 7).toLowerCase() !== 'bearer ') {\n return undefined;\n }\n const credential = header.slice(7).trim();\n return credential.length > 0 ? credential : undefined;\n}\n\nfunction isTrustedOperationClass(\n value: unknown,\n): value is McpTrustedOperationClass {\n return typeof value === 'string' && trustedOperationClasses.has(value);\n}\n\nfunction cloneTrustedClasses(\n value: unknown,\n): readonly McpTrustedOperationClass[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n const classes: McpTrustedOperationClass[] = [];\n for (const item of value) {\n if (!isTrustedOperationClass(item) || classes.includes(item)) {\n return undefined;\n }\n classes.push(item);\n }\n return Object.freeze(classes);\n}\n\nfunction cloneDestinationKeys(value: unknown): readonly string[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n const destinationKeys: string[] = [];\n for (const item of value) {\n if (\n typeof item !== 'string' ||\n !destinationKeyPattern.test(item) ||\n destinationKeys.includes(item)\n ) {\n return undefined;\n }\n destinationKeys.push(item);\n }\n return Object.freeze(destinationKeys);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null) return false;\n if (typeof value !== 'object') return false;\n if (Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction cloneJsonScalar(value: unknown): McpInvocationJsonValue | undefined {\n if (value === null) return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : undefined;\n }\n return undefined;\n}\n\nfunction cloneJsonArray(\n value: unknown[],\n depth: number,\n): McpInvocationJsonValue[] | undefined {\n const cloned: McpInvocationJsonValue[] = [];\n for (const item of value) {\n const clonedItem = cloneJsonValue(item, depth + 1);\n if (clonedItem === undefined) return undefined;\n cloned.push(clonedItem);\n }\n return Object.freeze(cloned);\n}\n\nfunction cloneJsonObject(\n value: Record<string, unknown>,\n depth: number,\n): Readonly<Record<string, McpInvocationJsonValue>> | undefined {\n const cloned = Object.create(null) as Record<string, McpInvocationJsonValue>;\n for (const [key, item] of Object.entries(value)) {\n const clonedItem = cloneJsonValue(item, depth + 1);\n if (clonedItem === undefined) return undefined;\n cloned[key] = clonedItem;\n }\n return Object.freeze(cloned);\n}\n\nfunction cloneJsonValue(\n value: unknown,\n depth = 0,\n): McpInvocationJsonValue | undefined {\n if (depth > MAX_JSON_DEPTH) return undefined;\n const scalar = cloneJsonScalar(value);\n if (scalar !== undefined) return scalar;\n if (Array.isArray(value)) return cloneJsonArray(value, depth);\n if (isPlainObject(value)) return cloneJsonObject(value, depth);\n return undefined;\n}\n\nfunction cloneJsonRecord(\n value: unknown,\n): Readonly<Record<string, McpInvocationJsonValue>> | undefined {\n const cloned = cloneJsonValue(value);\n return cloned !== null && !Array.isArray(cloned) && typeof cloned === 'object'\n ? (cloned as Readonly<Record<string, McpInvocationJsonValue>>)\n : undefined;\n}\n\nfunction isUnixTimestamp(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isValidTokenTimestamps(record: Record<string, unknown>): boolean {\n if (!isUnixTimestamp(record.iat)) return false;\n if (!isUnixTimestamp(record.nbf)) return false;\n if (!isUnixTimestamp(record.exp)) return false;\n if (record.nbf < record.iat) return false;\n if (record.exp < record.nbf) return false;\n if (record.exp - record.iat > MAX_TOKEN_LIFETIME_SECONDS) return false;\n return true;\n}\n\nfunction isValidTokenHeader(\n record: Record<string, unknown>,\n expectedKeyId: string,\n expectedIssuer: string,\n expectedAudience: string,\n): boolean {\n if (record.v !== INVOCATION_VERSION) return false;\n if (record.kid !== expectedKeyId) return false;\n if (record.iss !== expectedIssuer) return false;\n if (record.aud !== expectedAudience) return false;\n return isValidTokenTimestamps(record);\n}\n\nfunction isValidTokenAgent(\n agentId: unknown,\n): agentId is TrustedMcpInvocationClaims['agentId'] {\n return typeof agentId === 'string' && trustedAgentIds.has(agentId);\n}\n\nfunction parseInvocationActors(record: Record<string, unknown>):\n | {\n tokenId: string;\n principal: string;\n agentId: TrustedMcpInvocationClaims['agentId'];\n correlationId: string;\n }\n | undefined {\n const tokenId = requiredIdentifier(record.jti);\n const principal = requiredIdentifier(record.principal);\n const correlationId = requiredIdentifier(record.correlationId);\n const agentId = record.agentId;\n if (!tokenId || !principal || !correlationId || !isValidTokenAgent(agentId)) {\n return undefined;\n }\n return Object.freeze({ tokenId, principal, agentId, correlationId });\n}\n\nfunction buildInvocationClaims(\n record: Record<string, unknown>,\n): TrustedMcpInvocationClaims | undefined {\n const actors = parseInvocationActors(record);\n if (!actors) return undefined;\n\n const classes = cloneTrustedClasses(record.classes);\n const destinationKeys = cloneDestinationKeys(record.destinationKeys);\n const constraint = cloneJsonRecord(record.constraint);\n const limits = cloneJsonRecord(record.limits);\n if (!classes) return undefined;\n if (!destinationKeys) return undefined;\n if (!constraint) return undefined;\n if (!limits) return undefined;\n\n return Object.freeze({\n tokenId: actors.tokenId,\n principal: actors.principal,\n agentId: actors.agentId,\n classes,\n destinationKeys,\n correlationId: actors.correlationId,\n constraint,\n limits,\n });\n}\n\nfunction claimsFromPayload(\n payload: JWTPayload,\n expectedKeyId: string,\n expectedIssuer: string,\n expectedAudience: string,\n): TrustedMcpInvocationClaims | undefined {\n const record = payload as Record<string, unknown>;\n if (\n !isValidTokenHeader(record, expectedKeyId, expectedIssuer, expectedAudience)\n ) {\n return undefined;\n }\n return buildInvocationClaims(record);\n}\n\nfunction currentDate(now: (() => Date | number) | undefined): Date {\n const value = now?.() ?? new Date();\n return value instanceof Date ? value : new Date(value);\n}\n\n/**\n * Build a fail-closed verifier for the one ADT-Server invocation key.\n * Configuration failures throw before serving traffic; credential failures\n * always resolve to `undefined` without logging token-derived information.\n */\nexport function createMcpInvocationVerifier(\n options: McpInvocationVerifierOptions,\n): McpInvocationVerifier {\n if (!options?.publicKey) {\n throw new Error('MCP invocation verifier requires an ES256 public key');\n }\n const publicKey = options.publicKey;\n const keyId = requiredConfigurationIdentifier(options.keyId, 'key id');\n const issuer = requiredConfigurationIdentifier(options.issuer, 'issuer');\n const audience = requiredConfigurationIdentifier(\n options.audience,\n 'audience',\n );\n const now = options.now;\n\n return {\n async verify(authorizationHeader) {\n const credential = extractBearerCredential(authorizationHeader);\n if (!credential) return undefined;\n\n try {\n const verified = await jwtVerify(credential, publicKey, {\n algorithms: ['ES256'],\n issuer,\n audience,\n currentDate: currentDate(now),\n });\n const protectedHeader = verified.protectedHeader;\n if (\n protectedHeader.alg !== 'ES256' ||\n protectedHeader.kid !== keyId ||\n protectedHeader.typ !== 'JWT'\n ) {\n return undefined;\n }\n return claimsFromPayload(verified.payload, keyId, issuer, audience);\n } catch {\n return undefined;\n }\n },\n };\n}\n","/**\n * CORS handler for the adt-mcp HTTP transport.\n *\n * Only engages when the request carries an `Origin` header.\n * The allow-list is exact-match (plus the `*` wildcard shortcut for dev).\n * Preflight (`OPTIONS`) requests are terminated here with the appropriate\n * headers; non-preflight requests get response headers applied to `res`\n * so the caller can continue the normal pipeline.\n *\n * Per the MCP spec, `Mcp-Session-Id` must be exposed via\n * `Access-Control-Expose-Headers` so browser clients can read it off the\n * `initialize` response.\n */\nimport http from 'node:http';\n\nconst ALLOW_METHODS = 'POST, GET, DELETE, OPTIONS';\nconst ALLOW_HEADERS = 'content-type, accept, mcp-session-id, authorization';\nconst EXPOSE_HEADERS = 'mcp-session-id';\nconst MAX_AGE = '600';\n\nexport interface CorsOptions {\n /**\n * Exact-match allow-list of origins. The single entry `'*'` disables\n * matching and mirrors any origin (intended for local dev only).\n * An empty / undefined list disables CORS entirely (no headers added).\n */\n allowedOrigins?: string[];\n}\n\nexport interface CorsHandler {\n /**\n * Apply CORS handling to a request.\n *\n * Returns `true` if the response has been fully handled (preflight\n * short-circuit) and the caller MUST stop processing. Returns `false`\n * otherwise — the caller should continue; any non-preflight response\n * headers have already been written to `res.setHeader()` and will be\n * flushed with the final response.\n */\n handle(req: http.IncomingMessage, res: http.ServerResponse): boolean;\n}\n\nfunction getOrigin(req: http.IncomingMessage): string | undefined {\n const raw = req.headers['origin'];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value?.trim() && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction isAllowed(origin: string, allowed: string[]): boolean {\n if (allowed.length === 1 && allowed[0] === '*') return true;\n return allowed.includes(origin);\n}\n\nexport function createCorsHandler(options: CorsOptions = {}): CorsHandler {\n const allowed = (options.allowedOrigins ?? []).filter((s) => s.length > 0);\n const enabled = allowed.length > 0;\n\n return {\n handle(req, res) {\n if (!enabled) {\n // No CORS configured — if a preflight arrives it's not our concern\n // but we shouldn't crash the pipeline. Let the outer handler 404/405.\n return false;\n }\n const origin = getOrigin(req);\n const isPreflight = req.method === 'OPTIONS';\n\n if (!origin) {\n // Non-browser client, no CORS needed. Preflight without Origin is\n // malformed — fall through and let routing handle the 405.\n return false;\n }\n\n if (!isAllowed(origin, allowed)) {\n res.writeHead(403, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'origin not allowed' }));\n return true;\n }\n\n // Always mirror the request Origin — using the literal `*` would be\n // incompatible with credentialed requests, and mirroring is spec-compliant\n // in both wildcard and explicit-allow-list cases.\n res.setHeader('Access-Control-Allow-Origin', origin);\n res.setHeader('Vary', 'Origin');\n res.setHeader('Access-Control-Expose-Headers', EXPOSE_HEADERS);\n\n if (isPreflight) {\n res.setHeader('Access-Control-Allow-Methods', ALLOW_METHODS);\n res.setHeader('Access-Control-Allow-Headers', ALLOW_HEADERS);\n res.setHeader('Access-Control-Max-Age', MAX_AGE);\n res.writeHead(204);\n res.end();\n return true;\n }\n\n return false;\n },\n };\n}\n","/**\n * HTTP transport for the adt-mcp server.\n *\n * Implements the Streamable HTTP pattern recommended by the MCP SDK:\n *\n * - POST /mcp with `initialize` and no `Mcp-Session-Id` header\n * → spin up a new McpServer + StreamableHTTPServerTransport pair,\n * register them under the generated session id.\n * - Subsequent POST /mcp / GET /mcp / DELETE /mcp with `Mcp-Session-Id`\n * → route to the stored transport.\n *\n * A small middleware pipeline (`host validation → auth → route`) is kept\n * simple and composable so that future waves can drop in real auth.\n */\n\nimport https from 'node:https';\nimport http from 'node:http';\nimport { readFile } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { createMcpServer } from '../server.js';\nimport { createSessionRegistry } from '../session/registry.js';\nimport type { SessionRegistry } from '../session/registry.js';\nimport type {\n DestinationContextRegistry,\n RequestIdentity,\n} from '../session/destination-registry.js';\nimport {\n isMcpDestinationKey,\n isMcpOperationClass,\n type McpDelegatedAccess,\n type McpFrozenSourceAccess,\n type McpScopedAccess,\n type McpRequestAccess,\n} from '../tools/scope-catalogue.js';\nimport {\n loadMultiSystemConfig,\n type MultiSystemConfig,\n} from './multi-system.js';\nimport { createAuthMiddleware, type AuthMode, type UserHint } from './auth.js';\nimport {\n isMcpInvocationDispatchPolicySupported,\n parseAiReviewFrozenSourcePolicy,\n parseDelegatedAssistantReadPolicy,\n parseFrozenSource,\n parseScopedAdtInvocationPolicy,\n parseSafeExecutePolicy,\n} from './invocation.js';\nimport type {\n McpInvocationVerifier,\n TrustedMcpInvocationClaims,\n} from './invocation.js';\nimport type { OAuthOptions } from './oauth.js';\nimport { createCorsHandler } from './cors.js';\n\nexport interface HttpServerOptions {\n /** Port to listen on. Default: `MCP_PORT` env or 3000. */\n port?: number;\n /** Host to bind to. Default: `MCP_HOST` env or `127.0.0.1`. */\n host?: string;\n /** Idle session TTL in ms. Default: 30 minutes. */\n ttlMs?: number;\n /**\n * Extra host names to accept in the `Host` header. The bound host is\n * always accepted; `localhost`, `127.0.0.1`, and `[::1]` are accepted\n * by default.\n */\n allowedHosts?: string[];\n /**\n * Authentication mode for incoming requests. Defaults to `'none'` when\n * no token / forwarded-auth flag is configured. Misconfiguration (e.g.\n * `bearer` without a token) throws synchronously when the handler is\n * created, including through `startHttpServer`.\n */\n authMode?: AuthMode;\n /** Bearer token (required when `authMode === 'bearer'`). */\n authToken?: string;\n /**\n * Convenience flag — when true, forces `authMode='proxy'` and trusts\n * `x-forwarded-user` from the caller. Intended for deployments behind\n * an authenticating reverse proxy (oauth2-proxy, Cloudflare Access).\n */\n trustForwardedAuth?: boolean;\n /**\n * OAuth / OIDC validation options (required when `authMode === 'oauth'`).\n * Issuer, audience, JWKS, required scopes, user-claim mapping. See\n * `./oauth.ts` for the full option list.\n */\n oauth?: OAuthOptions;\n /**\n * ADT-issued invocation verifier (required when `authMode ===\n * 'invocation'`). Its trusted claims are the only source for identity and\n * scope in destination-aware sidecar mode.\n */\n invocationVerifier?: McpInvocationVerifier;\n /**\n * Internal test hook — called with each successful OAuth `userHint`.\n * Not part of the public API.\n * @internal\n */\n onOAuthUserHint?: (hint: import('./auth.js').UserHint | undefined) => void;\n /**\n * CORS allow-list. Exact-match origins only (plus `'*'` for dev).\n * Undefined or empty = CORS disabled (no headers added).\n */\n allowedOrigins?: string[];\n /** Override the multi-system config loader (mainly for tests). */\n multiSystem?: MultiSystemConfig;\n /** Override the session registry (mainly for tests). */\n registry?: SessionRegistry;\n /** Path to the PEM-encoded TLS certificate; also read from MCP_TLS_CERT. */\n tlsCert?: string;\n /** Path to the PEM-encoded TLS private key; also read from MCP_TLS_KEY. */\n tlsKey?: string;\n /** Inline PEM-encoded TLS certificate (useful for embedders and tests). */\n tlsCertContent?: string;\n /** Inline PEM-encoded TLS private key (useful for embedders and tests). */\n tlsKeyContent?: string;\n /**\n * Enables destination-aware shared-server mode. Access and identity are\n * derived only from the authenticated request's trusted `UserHint` at MCP\n * session initialization, then captured for the life of that session.\n */\n destinationServer?: {\n destinationRegistry: DestinationContextRegistry;\n requestIdentity: (input: {\n userHint?: UserHint;\n invocation?: TrustedMcpInvocationClaims;\n }) => RequestIdentity;\n requestAccess: (input: {\n userHint?: UserHint;\n invocation?: TrustedMcpInvocationClaims;\n }) => McpRequestAccess | undefined;\n resolveFrozenSource?: NonNullable<\n import('../types.js').ToolContext['resolveFrozenSource']\n >;\n consumeExecutionAuthorization?: NonNullable<\n import('../types.js').ToolContext['consumeExecutionAuthorization']\n >;\n reportExecutionOutcome?: NonNullable<\n import('../types.js').ToolContext['reportExecutionOutcome']\n >;\n executeWithDeadline?: NonNullable<\n import('../types.js').ToolContext['executeWithDeadline']\n >;\n };\n /** Inject a logger that writes to stderr by default. */\n log?: (level: 'info' | 'warn' | 'error', msg: string) => void;\n}\n\nexport interface RunningHttpServer {\n readonly url: string;\n readonly port: number;\n readonly host: string;\n readonly registry: SessionRegistry;\n close(): Promise<void>;\n}\n\n/**\n * A reusable Streamable HTTP MCP request handler.\n *\n * The embedding application owns its Node listener and delegates only the\n * requests routed to MCP to `handle`. Calling `close` releases MCP sessions\n * and transports, but deliberately never closes that listener.\n */\nexport interface HttpMcpHandler {\n readonly registry: SessionRegistry;\n handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>;\n close(): Promise<void>;\n}\n\ntype Middleware = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n) => Promise<boolean> | boolean;\n\n/**\n * Captures trusted access at initialization so a provider cannot change a\n * session's authorization by mutating the object it returned later.\n */\nfunction snapshotRequestAccess(\n access: McpRequestAccess | undefined,\n): McpRequestAccess | undefined {\n if (!access) return undefined;\n\n const classes = access.classes;\n const destinationKeys = access.destinationKeys;\n if (!Array.isArray(classes) || !Array.isArray(destinationKeys)) {\n return undefined;\n }\n\n if (\n !classes.every(isMcpOperationClass) ||\n !destinationKeys.every(isMcpDestinationKey)\n ) {\n return undefined;\n }\n\n const frozenSource = snapshotFrozenSourceAccess(access.frozenSource);\n if (access.frozenSource && !frozenSource) return undefined;\n const scoped = snapshotScopedAccess(access.scoped);\n if (access.scoped && !scoped) return undefined;\n const delegated = snapshotDelegatedAccess(access.delegated);\n if (access.delegated && !delegated) return undefined;\n if (\n scoped &&\n (classes.length !== 2 ||\n classes[0] !== 'server' ||\n classes[1] !== scoped.operationClass)\n ) {\n return undefined;\n }\n\n return Object.freeze({\n classes: Object.freeze([...classes]),\n destinationKeys: Object.freeze([...destinationKeys]),\n ...(frozenSource ? { frozenSource } : {}),\n ...(scoped ? { scoped } : {}),\n ...(delegated ? { delegated } : {}),\n });\n}\n\nconst UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\nconst OBJECT_KEY_REGEX = /^[A-Z0-9_]{2,30}:[A-Z0-9_/$-]{1,128}$/u;\nconst READ_SCOPED_TOOLS = new Set(['get_object', 'get_object_structure']);\nconst SYSTEM_SID_REGEX = /^[A-Za-z0-9_-]{1,16}$/u;\nconst AUTHORIZATION_TOKEN_REGEX =\n /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/u;\n\nfunction normalizeAndValidateStrings(values: unknown[]): string[] | undefined {\n if (!Array.isArray(values)) return undefined;\n const result: string[] = [];\n for (const value of values) {\n if (typeof value !== 'string' || !value) return undefined;\n result.push(value);\n }\n return result;\n}\n\nfunction isSortedUniqueStrings(values: string[]): boolean {\n const sorted = [...values].sort((left, right) => left.localeCompare(right));\n return (\n new Set(values).size === values.length &&\n values.every((value, index) => value === sorted[index])\n );\n}\n\nfunction validateCommonScopedFields(\n access: McpScopedAccess,\n): { resourceKeys: string[]; toolNames: string[] } | undefined {\n if (typeof access.tokenId !== 'string' || !access.tokenId) return undefined;\n if (typeof access.principal !== 'string' || !access.principal)\n return undefined;\n if (typeof access.correlationId !== 'string' || !access.correlationId)\n return undefined;\n if (typeof access.scopeId !== 'string' || !UUID_REGEX.test(access.scopeId)) {\n return undefined;\n }\n if (\n typeof access.executionId !== 'string' ||\n !UUID_REGEX.test(access.executionId)\n ) {\n return undefined;\n }\n if (\n typeof access.systemSid !== 'string' ||\n !SYSTEM_SID_REGEX.test(access.systemSid)\n ) {\n return undefined;\n }\n if (\n !Number.isSafeInteger(access.maxToolCalls) ||\n access.maxToolCalls < 1 ||\n access.maxToolCalls > 12\n ) {\n return undefined;\n }\n\n const resourceKeys = normalizeAndValidateStrings(access.resourceKeys);\n const toolNames = normalizeAndValidateStrings(access.toolNames);\n if (\n !resourceKeys ||\n resourceKeys.length > 100 ||\n resourceKeys.some((key) => !OBJECT_KEY_REGEX.test(key)) ||\n !isSortedUniqueStrings(resourceKeys) ||\n !toolNames ||\n toolNames.length === 0 ||\n !isSortedUniqueStrings(toolNames)\n ) {\n return undefined;\n }\n\n return { resourceKeys, toolNames };\n}\n\nfunction buildScopedAccess(\n access: McpScopedAccess,\n resourceKeys: string[],\n toolNames: string[],\n overrides: Record<string, unknown> = {},\n): McpScopedAccess {\n return Object.freeze({\n ...access,\n resourceKeys: Object.freeze(resourceKeys),\n toolNames: Object.freeze(toolNames),\n ...overrides,\n }) as McpScopedAccess;\n}\n\nfunction snapshotReadScope(\n access: McpScopedAccess,\n resourceKeys: string[],\n toolNames: string[],\n): McpScopedAccess | undefined {\n if (\n resourceKeys.length === 0 ||\n toolNames.some((name) => !READ_SCOPED_TOOLS.has(name)) ||\n access.safeExecutePolicy !== undefined ||\n access.authorizationId !== undefined ||\n access.authorizationToken !== undefined\n ) {\n return undefined;\n }\n return buildScopedAccess(access, resourceKeys, toolNames);\n}\n\nfunction snapshotSafeExecuteScope(\n access: McpScopedAccess,\n resourceKeys: string[],\n toolNames: string[],\n): McpScopedAccess | undefined {\n const safeExecutePolicy = parseSafeExecutePolicy(access.safeExecutePolicy);\n if (\n !safeExecutePolicy ||\n resourceKeys.length === 0 ||\n toolNames.length !== 1 ||\n toolNames[0] !== safeExecutePolicy.operationId ||\n typeof access.authorizationId !== 'string' ||\n !UUID_REGEX.test(access.authorizationId) ||\n typeof access.authorizationToken !== 'string' ||\n access.authorizationToken.length > 16 * 1024 ||\n !AUTHORIZATION_TOKEN_REGEX.test(access.authorizationToken)\n ) {\n return undefined;\n }\n return buildScopedAccess(access, resourceKeys, toolNames, {\n safeExecutePolicy,\n });\n}\n\nfunction snapshotScopedAccess(\n access: McpScopedAccess | undefined,\n): McpScopedAccess | undefined {\n if (!access) return undefined;\n const validated = validateCommonScopedFields(access);\n if (!validated) return undefined;\n const { resourceKeys, toolNames } = validated;\n\n if (access.operationClass === 'read') {\n return snapshotReadScope(access, resourceKeys, toolNames);\n }\n if (access.operationClass === 'safe_execute') {\n return snapshotSafeExecuteScope(access, resourceKeys, toolNames);\n }\n return undefined;\n}\n\nfunction snapshotDelegatedAccess(\n access: McpDelegatedAccess | undefined,\n): McpDelegatedAccess | undefined {\n if (!access) return undefined;\n if (\n typeof access.threadId !== 'string' ||\n !UUID_REGEX.test(access.threadId) ||\n typeof access.executionId !== 'string' ||\n !UUID_REGEX.test(access.executionId) ||\n typeof access.systemSid !== 'string' ||\n access.systemSid.length === 0 ||\n access.systemSid.length > 16\n ) {\n return undefined;\n }\n return Object.freeze({\n threadId: access.threadId,\n executionId: access.executionId,\n systemSid: access.systemSid,\n });\n}\n\nfunction snapshotFrozenSourceAccess(\n access: McpFrozenSourceAccess | undefined,\n): McpFrozenSourceAccess | undefined {\n if (!access) return undefined;\n if (\n typeof access.systemSid !== 'string' ||\n access.systemSid.length === 0 ||\n access.systemSid.length > 16 ||\n !Number.isSafeInteger(access.maxSourceBytes) ||\n access.maxSourceBytes < 1 ||\n access.maxSourceBytes > 2 * 1024 * 1024 ||\n !Array.isArray(access.sources) ||\n access.sources.length === 0 ||\n access.sources.length > 500\n ) {\n return undefined;\n }\n const sourceKeys = new Set<string>();\n const sourceRefs = new Set<string>();\n const sources: {\n canonicalKey: string;\n componentId: string;\n sourceRef: string;\n }[] = [];\n for (const source of access.sources) {\n const parsed = parseFrozenSource(source, sourceKeys, sourceRefs);\n if (!parsed) return undefined;\n sources.push(parsed);\n }\n return Object.freeze({\n systemSid: access.systemSid,\n sources: Object.freeze(sources),\n maxSourceBytes: access.maxSourceBytes,\n });\n}\n\n/** A deterministic, non-secret value used only for session affinity checks. */\nfunction sessionIdentityBinding(\n identity: RequestIdentity,\n invocationTokenId?: string,\n): string {\n if (!identity.principal || typeof identity.principal !== 'string') {\n throw new Error('Trusted request identity is missing a principal');\n }\n if (identity.agentId !== undefined && typeof identity.agentId !== 'string') {\n throw new Error('Trusted request identity has an invalid agent id');\n }\n return JSON.stringify([\n identity.principal,\n identity.agentId ?? null,\n invocationTokenId ?? null,\n ]);\n}\n\nfunction invocationRequestIdentity(\n invocation: TrustedMcpInvocationClaims | undefined,\n): RequestIdentity {\n if (!invocation) {\n throw new Error('Trusted MCP invocation identity is missing');\n }\n return {\n principal: invocation.principal,\n agentId: invocation.agentId,\n };\n}\n\nfunction invocationRequestAccess(\n invocation: TrustedMcpInvocationClaims | undefined,\n): McpRequestAccess | undefined {\n if (!invocation || !isMcpInvocationDispatchPolicySupported(invocation)) {\n return undefined;\n }\n const frozenSource = parseAiReviewFrozenSourcePolicy(invocation);\n const scopedPolicy = parseScopedAdtInvocationPolicy(invocation);\n const delegated = parseDelegatedAssistantReadPolicy(invocation);\n return snapshotRequestAccess({\n classes: invocation.classes,\n destinationKeys: invocation.destinationKeys,\n ...(frozenSource ? { frozenSource } : {}),\n ...(scopedPolicy\n ? {\n scoped: {\n tokenId: invocation.tokenId,\n principal: invocation.principal,\n correlationId: invocation.correlationId,\n ...scopedPolicy,\n },\n }\n : {}),\n ...(delegated ? { delegated } : {}),\n });\n}\n\nfunction defaultLog(level: 'info' | 'warn' | 'error', msg: string): void {\n // Write to stderr to avoid polluting any stdout-based transport on the\n // same process.\n const line = `[adt-mcp-http] ${level}: ${msg}\\n`;\n process.stderr.write(line);\n}\n\nfunction normaliseHostAllowlist(\n bindHost: string,\n extra?: string[],\n): Set<string> {\n const set = new Set<string>(['localhost', '127.0.0.1', '[::1]', '::1']);\n if (bindHost) set.add(bindHost.toLowerCase());\n for (const h of extra ?? []) set.add(h.toLowerCase());\n return set;\n}\n\n/**\n * Host-header validation middleware — protects against DNS-rebinding\n * attacks when the server binds to a loopback interface. Returns `true`\n * when the request has been rejected (caller should stop processing).\n */\nfunction makeHostValidator(allowed: Set<string>): Middleware {\n return (req, res) => {\n const hostHeader = req.headers.host ?? '';\n // Strip port.\n const host = hostHeader.replace(/:\\d+$/u, '').toLowerCase();\n if (!host || !allowed.has(host)) {\n res.writeHead(403, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: `Host header '${hostHeader}' not allowed`,\n },\n id: null,\n }),\n );\n return true;\n }\n return false;\n };\n}\n\nasync function readJsonBody(\n req: http.IncomingMessage,\n limitBytes = 4 * 1024 * 1024,\n): Promise<unknown> {\n return await new Promise((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > limitBytes) {\n reject(new Error('Request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n if (chunks.length === 0) {\n resolve(undefined);\n return;\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n try {\n resolve(raw.length === 0 ? undefined : JSON.parse(raw));\n } catch (err) {\n reject(err);\n }\n });\n req.on('error', reject);\n });\n}\n\nfunction isInitializeRequest(body: unknown): boolean {\n if (!body) return false;\n const msgs = Array.isArray(body) ? body : [body];\n return msgs.some(\n (m) =>\n m &&\n typeof m === 'object' &&\n (m as { method?: unknown }).method === 'initialize',\n );\n}\n\nfunction writeJsonError(\n res: http.ServerResponse,\n status: number,\n message: string,\n): void {\n if (res.headersSent) {\n try {\n res.end();\n } catch {\n // ignore\n }\n return;\n }\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32000, message },\n id: null,\n }),\n );\n}\n\n/**\n * Creates a reusable MCP HTTP handler without binding a Node listener.\n */\nexport function createHttpMcpHandler(\n options: HttpServerOptions = {},\n): HttpMcpHandler {\n const host = options.host ?? process.env.MCP_HOST ?? '127.0.0.1';\n const log = options.log ?? defaultLog;\n\n const registry =\n options.registry ??\n createSessionRegistry({ ttlMs: options.ttlMs ?? 30 * 60 * 1000 });\n const multiSystem = options.multiSystem ?? loadMultiSystemConfig();\n const destinationServer = options.destinationServer;\n\n // One transport per MCP session, plus the paired McpServer that owns it.\n // The SDK expects `server.connect(transport)` to be called once per pair.\n const transports = new Map<string, StreamableHTTPServerTransport>();\n const servers = new Map<string, McpServer>();\n const sessionIdentityBindings = new Map<string, string>();\n\n async function releaseSessionResources(sessionId: string): Promise<void> {\n const server = servers.get(sessionId);\n transports.delete(sessionId);\n sessionIdentityBindings.delete(sessionId);\n servers.delete(sessionId);\n await registry.delete(sessionId);\n await destinationServer?.destinationRegistry.releaseAll(sessionId);\n try {\n await server?.close();\n } catch {\n // ignore\n }\n }\n\n const hostAllow = normaliseHostAllowlist(host, options.allowedHosts);\n const hostValidator = makeHostValidator(hostAllow);\n\n // Resolve auth mode. `trustForwardedAuth` is a convenience alias for\n // `authMode='proxy'` and may only promote an *unset* auth mode to\n // 'proxy'. It must NOT silently downgrade an explicit authMode (e.g.\n // 'oauth'), or the JWT validation layer would be bypassed.\n let authMode: AuthMode =\n options.authMode ?? (options.authToken ? 'bearer' : 'none');\n if (options.trustForwardedAuth && authMode === 'none') authMode = 'proxy';\n if (authMode === 'oauth' && !options.oauth) {\n throw new Error(\n 'startHttpServer: authMode=oauth requires `oauth` options (issuer at minimum)',\n );\n }\n if (authMode === 'invocation' && !options.invocationVerifier) {\n throw new Error(\n 'createHttpMcpHandler: authMode=invocation requires an invocation verifier',\n );\n }\n if (authMode === 'invocation' && !destinationServer) {\n throw new Error(\n 'createHttpMcpHandler: authMode=invocation requires destinationServer scope enforcement',\n );\n }\n const authMw = createAuthMiddleware({\n mode: authMode,\n token: options.authToken,\n oauth: options.oauth,\n invocationVerifier: options.invocationVerifier,\n onUserHint: options.onOAuthUserHint,\n });\n const cors = createCorsHandler({ allowedOrigins: options.allowedOrigins });\n\n const sessionMatchesAuthenticatedIdentity = (\n sessionId: string,\n userHint: UserHint | undefined,\n invocation: TrustedMcpInvocationClaims | undefined,\n res: http.ServerResponse,\n ): boolean => {\n if (!destinationServer) return true;\n const expected = sessionIdentityBindings.get(sessionId);\n if (!expected) {\n writeJsonError(res, 403, 'mcp_session_identity_mismatch');\n return false;\n }\n try {\n const identity =\n authMode === 'invocation'\n ? invocationRequestIdentity(invocation)\n : destinationServer.requestIdentity({ userHint, invocation });\n const actual = sessionIdentityBinding(identity, invocation?.tokenId);\n if (actual === expected) return true;\n } catch {\n // Treat a failed or malformed trusted identity derivation exactly like\n // a mismatch. Never fall back to a client field or session contents.\n }\n writeJsonError(res, 403, 'mcp_session_identity_mismatch');\n return false;\n };\n\n const handleMcp = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n userHint: UserHint | undefined,\n invocation: TrustedMcpInvocationClaims | undefined,\n ): Promise<void> => {\n const sessionHeader = req.headers['mcp-session-id'];\n const sessionId = Array.isArray(sessionHeader)\n ? sessionHeader[0]\n : sessionHeader;\n\n if (req.method === 'POST') {\n // Body must be parsed up-front to decide whether this is an\n // `initialize` request that should spawn a new transport.\n let body: unknown;\n try {\n body = await readJsonBody(req);\n } catch (err) {\n writeJsonError(\n res,\n 400,\n `Invalid JSON body: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n return;\n }\n\n if (sessionId && transports.has(sessionId)) {\n if (\n !sessionMatchesAuthenticatedIdentity(\n sessionId,\n userHint,\n invocation,\n res,\n )\n ) {\n return;\n }\n // Refresh the session's last-used timestamp so the TTL sweep\n // doesn't evict an actively-used session between tool calls.\n registry.touch(sessionId);\n const transport = transports.get(sessionId)!;\n await transport.handleRequest(req, res, body);\n return;\n }\n\n if (!sessionId && isInitializeRequest(body)) {\n let initializedSessionBinding: string | undefined;\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: (id) => {\n transports.set(id, transport);\n if (initializedSessionBinding) {\n sessionIdentityBindings.set(id, initializedSessionBinding);\n }\n log('info', `session initialized: ${id}`);\n },\n onsessionclosed: async (id) => {\n log('info', `session closed by client: ${id}`);\n await releaseSessionResources(id);\n },\n });\n\n transport.onclose = () => {\n const id = transport.sessionId;\n if (!id) return;\n void releaseSessionResources(id);\n };\n\n let sessionIdentity: RequestIdentity | undefined;\n let sessionAccess: McpRequestAccess | undefined;\n if (destinationServer) {\n let identityDerivationFailed = false;\n try {\n sessionIdentity =\n authMode === 'invocation'\n ? invocationRequestIdentity(invocation)\n : destinationServer.requestIdentity({ userHint, invocation });\n initializedSessionBinding = sessionIdentityBinding(\n sessionIdentity,\n invocation?.tokenId,\n );\n } catch {\n // A failed identity derivation must not turn into caller-selected\n // identity material. The fallback is audit-safe and fail-closed\n // once the lease provider applies its ordinary authorization.\n sessionIdentity = { principal: 'unknown' };\n identityDerivationFailed = true;\n }\n if (!identityDerivationFailed) {\n try {\n sessionAccess =\n authMode === 'invocation'\n ? invocationRequestAccess(invocation)\n : snapshotRequestAccess(\n destinationServer.requestAccess({ userHint, invocation }),\n );\n } catch {\n // Missing or failed trusted access derivation is intentionally\n // indistinguishable from no access at dispatch time.\n sessionAccess = undefined;\n }\n }\n }\n\n const mcp = createMcpServer({\n registry,\n resolveSystem: (id) => multiSystem.resolve(id),\n ...(destinationServer\n ? {\n destinationRegistry: destinationServer.destinationRegistry,\n requestIdentity: () =>\n sessionIdentity ?? { principal: 'unknown' },\n requestAccess: () => sessionAccess,\n ...(destinationServer.resolveFrozenSource\n ? {\n resolveFrozenSource:\n destinationServer.resolveFrozenSource,\n }\n : {}),\n ...(destinationServer.consumeExecutionAuthorization\n ? {\n consumeExecutionAuthorization:\n destinationServer.consumeExecutionAuthorization,\n }\n : {}),\n ...(destinationServer.reportExecutionOutcome\n ? {\n reportExecutionOutcome:\n destinationServer.reportExecutionOutcome,\n }\n : {}),\n ...(destinationServer.executeWithDeadline\n ? {\n executeWithDeadline:\n destinationServer.executeWithDeadline,\n }\n : {}),\n }\n : {}),\n });\n await mcp.connect(transport);\n // Store under the generated session id as soon as it exists.\n // `onsessioninitialized` also stores it, but we want the mapping\n // available for any in-flight follow-up immediately.\n if (transport.sessionId) {\n transports.set(transport.sessionId, transport);\n servers.set(transport.sessionId, mcp);\n }\n await transport.handleRequest(req, res, body);\n if (transport.sessionId && !servers.has(transport.sessionId)) {\n servers.set(transport.sessionId, mcp);\n }\n return;\n }\n\n writeJsonError(\n res,\n 400,\n sessionId\n ? `Unknown Mcp-Session-Id: ${sessionId}`\n : 'Missing Mcp-Session-Id header (non-initialize request)',\n );\n return;\n }\n\n if (req.method === 'GET' || req.method === 'DELETE') {\n if (!sessionId || !transports.has(sessionId)) {\n writeJsonError(res, 400, 'Missing or unknown Mcp-Session-Id header');\n return;\n }\n if (\n !sessionMatchesAuthenticatedIdentity(\n sessionId,\n userHint,\n invocation,\n res,\n )\n ) {\n return;\n }\n registry.touch(sessionId);\n const transport = transports.get(sessionId)!;\n await transport.handleRequest(req, res);\n return;\n }\n\n res.writeHead(405, { Allow: 'POST, GET, DELETE' });\n res.end();\n };\n\n const handle = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> => {\n try {\n // Pipeline order (security-critical):\n // 1. CORS — handles preflight short-circuit.\n // 2. Host-header validation — DNS-rebind protection.\n // 3. /healthz — NOT behind auth so monitoring probes work.\n // 4. Auth — bearer / proxy / none.\n // 5. Route to /mcp.\n if (cors.handle(req, res)) return;\n if (hostValidator(req, res)) return;\n\n const url = req.url ?? '/';\n const pathOnly = url.split('?')[0];\n\n if (pathOnly === '/healthz' && req.method === 'GET') {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n status: 'ok',\n sessions: registry.list().length,\n }),\n );\n return;\n }\n\n const authResult = await authMw(req, res);\n if (!authResult.allowed) return;\n // Accept /mcp and /mcp/ — ignore query string.\n if (pathOnly === '/mcp' || pathOnly === '/mcp/') {\n await handleMcp(req, res, authResult.userHint, authResult.invocation);\n return;\n }\n\n res.writeHead(404, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Not found' }));\n } catch (err) {\n log(\n 'error',\n `unhandled error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`,\n );\n writeJsonError(res, 500, 'Internal server error');\n }\n };\n\n let closed = false;\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n log('info', 'shutting down');\n await registry.shutdown();\n // Close each outstanding transport + server pair.\n const pairs = Array.from(transports.entries());\n transports.clear();\n for (const [sessionId] of pairs) sessionIdentityBindings.delete(sessionId);\n if (destinationServer) {\n await Promise.allSettled(\n pairs.map(\n async ([sessionId]) =>\n await destinationServer.destinationRegistry.releaseAll(sessionId),\n ),\n );\n }\n await Promise.allSettled(\n pairs.map(async ([, t]) => {\n try {\n await t.close();\n } catch {\n // ignore\n }\n }),\n );\n const srvs = Array.from(servers.values());\n servers.clear();\n await Promise.allSettled(\n srvs.map(async (s) => {\n try {\n await s.close();\n } catch {\n // ignore\n }\n }),\n );\n };\n\n return {\n registry,\n handle,\n close,\n };\n}\n\n/**\n * Starts the HTTP transport and returns a handle that can be used to close\n * both the listener and all active MCP sessions gracefully.\n *\n * This is a backwards-compatible listener adapter around\n * `createHttpMcpHandler` for standalone deployments.\n */\nexport async function startHttpServer(\n options: HttpServerOptions = {},\n): Promise<RunningHttpServer> {\n const port =\n options.port ??\n (process.env.MCP_PORT ? Number(process.env.MCP_PORT) : 3000);\n const host = options.host ?? process.env.MCP_HOST ?? '127.0.0.1';\n const log = options.log ?? defaultLog;\n // Resolve and validate TLS material before allocating the handler — a\n // missing or malformed certificate must not leak the session registry.\n const certPath = options.tlsCert ?? process.env.MCP_TLS_CERT;\n const keyPath = options.tlsKey ?? process.env.MCP_TLS_KEY;\n const cert =\n options.tlsCertContent ??\n (certPath ? await readFile(certPath, 'utf8') : undefined);\n const key =\n options.tlsKeyContent ??\n (keyPath ? await readFile(keyPath, 'utf8') : undefined);\n\n if (!cert || !key) {\n throw new Error(\n 'startHttpServer: TLS certificate and key are required. Provide tlsCert/tlsKey, ' +\n 'tlsCertContent/tlsKeyContent, or MCP_TLS_CERT/MCP_TLS_KEY.',\n );\n }\n if (\n !cert.includes('-----BEGIN CERTIFICATE-----') ||\n !cert.includes('-----END CERTIFICATE-----')\n ) {\n throw new Error(\n 'startHttpServer: TLS certificate is not valid PEM — expected a ' +\n '\"-----BEGIN CERTIFICATE-----\" block' +\n (certPath ? ` in ${certPath}` : ' in tlsCertContent') +\n '.',\n );\n }\n if (!key.includes('PRIVATE KEY-----')) {\n throw new Error(\n 'startHttpServer: TLS private key is not valid PEM — expected a ' +\n '\"-----BEGIN ... PRIVATE KEY-----\" block' +\n (keyPath ? ` in ${keyPath}` : ' in tlsKeyContent') +\n '.',\n );\n }\n\n const handler = createHttpMcpHandler(options);\n let server: https.Server;\n try {\n server = https.createServer({ cert, key }, (req, res) => {\n void handler.handle(req, res);\n });\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => reject(err);\n server.once('error', onError);\n server.listen(port, host, () => {\n server.removeListener('error', onError);\n resolve();\n });\n });\n } catch (err) {\n await handler.close().catch(() => undefined);\n throw err;\n }\n\n const boundPort = (server.address() as { port: number } | null)?.port ?? port;\n log('info', `listening on https://${host}:${boundPort}/mcp`);\n\n let closed = false;\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n await handler.close();\n // `server.close()` stops accepting new requests but can otherwise wait\n // indefinitely for a keep-alive socket which never created an MCP\n // transport (for example, a rejected bearer credential). Handler-owned\n // MCP transports have already been closed above, so force remaining HTTP\n // sockets closed before awaiting the listener callback.\n server.closeAllConnections();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n };\n\n return {\n url: `https://${host}:${boundPort}/mcp`,\n port: boundPort,\n host,\n registry: handler.registry,\n close,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,MAAM,iBAAiB;AAEvB,SAAgB,sBACd,UAAkC,CAAC,GAClB;CACjB,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,2BAAW,IAAI,IAA+B;CACpD,IAAI;CAEJ,MAAM,aAAa,UAAsD;EACvE,IAAI,SAAS;EACb,OAAO,YAAY;GACjB,IAAI,QAAQ;GACZ,SAAS;GACT,MAAM,MAAM;EACd;CACF;CAEA,MAAM,WAA4B;EAChC,OAAO,cAAc,KAAK,OAAO;GAC/B,MAAM,MAAM,KAAK,IAAI;GACrB,MAAM,UAA6B;IACjC;IACA,WAAW;IACX,Y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