@agent-native/core 0.26.6 → 0.26.8
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/cli/skills.d.ts.map +1 -1
- package/dist/cli/skills.js +3 -1
- package/dist/cli/skills.js.map +1 -1
- package/dist/cli/workspace-dev.d.ts.map +1 -1
- package/dist/cli/workspace-dev.js +9 -2
- package/dist/cli/workspace-dev.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +2 -2
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/agent-chat.d.ts.map +1 -1
- package/dist/client/agent-chat.js +6 -5
- package/dist/client/agent-chat.js.map +1 -1
- package/dist/client/frame.d.ts +1 -0
- package/dist/client/frame.d.ts.map +1 -1
- package/dist/client/frame.js +20 -6
- package/dist/client/frame.js.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/mcp/build-server.d.ts +1 -0
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +5 -2
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/embed-app.d.ts +3 -0
- package/dist/mcp/embed-app.d.ts.map +1 -1
- package/dist/mcp/embed-app.js +255 -13
- package/dist/mcp/embed-app.js.map +1 -1
- package/dist/mcp/oauth-route.d.ts.map +1 -1
- package/dist/mcp/oauth-route.js +1 -0
- package/dist/mcp/oauth-route.js.map +1 -1
- package/dist/mcp/oauth-token.d.ts +3 -0
- package/dist/mcp/oauth-token.d.ts.map +1 -1
- package/dist/mcp/oauth-token.js +2 -0
- package/dist/mcp/oauth-token.js.map +1 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +5 -10
- package/dist/mcp/server.js.map +1 -1
- package/dist/server/deep-link.d.ts.map +1 -1
- package/dist/server/deep-link.js +16 -1
- package/dist/server/deep-link.js.map +1 -1
- package/dist/server/security-headers.d.ts.map +1 -1
- package/dist/server/security-headers.js +7 -1
- package/dist/server/security-headers.js.map +1 -1
- package/dist/shared/mcp-embed-headers.d.ts +1 -0
- package/dist/shared/mcp-embed-headers.d.ts.map +1 -1
- package/dist/shared/mcp-embed-headers.js +19 -2
- package/dist/shared/mcp-embed-headers.js.map +1 -1
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +124 -0
- package/dist/vite/client.js.map +1 -1
- package/package.json +1 -1
package/dist/mcp/oauth-token.js
CHANGED
|
@@ -35,6 +35,7 @@ export async function signMcpOAuthAccessToken(params) {
|
|
|
35
35
|
return new jose.SignJWT({
|
|
36
36
|
typ: "agent-native-mcp-oauth",
|
|
37
37
|
sub: params.ownerEmail,
|
|
38
|
+
...(params.orgId ? { org_id: params.orgId } : {}),
|
|
38
39
|
...(params.orgDomain ? { org_domain: params.orgDomain } : {}),
|
|
39
40
|
scope: params.scope,
|
|
40
41
|
client_id: params.clientId,
|
|
@@ -71,6 +72,7 @@ export async function verifyMcpOAuthAccessToken(token, resource) {
|
|
|
71
72
|
}
|
|
72
73
|
return {
|
|
73
74
|
userEmail: payload.sub,
|
|
75
|
+
orgId: typeof payload.org_id === "string" ? payload.org_id : undefined,
|
|
74
76
|
orgDomain: typeof payload.org_domain === "string" ? payload.org_domain : undefined,
|
|
75
77
|
scopes,
|
|
76
78
|
clientId: payload.client_id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-token.js","sourceRoot":"","sources":["../../src/mcp/oauth-token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAE9D,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,U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AK,EAAE,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;YACtE,SAAS,EACP,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS;YACzE,MAAM;YACN,QAAQ,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import * as jose from \"jose\";\nimport { randomUUID } from \"node:crypto\";\nimport { getAuthSecret } from \"../server/better-auth-instance.js\";\nimport { MCP_OAUTH_ACCESS_TOKEN_TTL } from \"./oauth-store.js\";\n\nexport const MCP_OAUTH_SCOPES = [\"mcp:read\", \"mcp:write\", \"mcp:apps\"] as const;\n\nexport const MCP_OAUTH_DEFAULT_SCOPE = MCP_OAUTH_SCOPES.join(\" \");\n\nexport interface McpOAuthAccessTokenClaims {\n sub: string;\n org_id?: string;\n org_domain?: string;\n scope: string;\n client_id: string;\n resource: string;\n typ: \"agent-native-mcp-oauth\";\n}\n\nfunction signingSecret(): Uint8Array {\n return new TextEncoder().encode(process.env.A2A_SECRET || getAuthSecret());\n}\n\nexport function normalizeOAuthScope(input: unknown): string | null {\n const requested =\n typeof input === \"string\"\n ? input\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n const allowed = new Set<string>(MCP_OAUTH_SCOPES);\n if (requested.length === 0) return MCP_OAUTH_DEFAULT_SCOPE;\n const selected = requested.filter((scope) => allowed.has(scope));\n return selected.length ? [...new Set(selected)].join(\" \") : null;\n}\n\nexport function scopeList(scope: string | undefined): string[] {\n return (scope ?? \"\")\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\nexport function hasMcpOAuthScope(\n scopes: string[] | undefined,\n scope: (typeof MCP_OAUTH_SCOPES)[number],\n): boolean {\n if (!scopes) return true;\n return scopes.includes(scope);\n}\n\nexport async function signMcpOAuthAccessToken(params: {\n ownerEmail: string;\n orgId?: string | null;\n orgDomain?: string | null;\n clientId: string;\n scope: string;\n resource: string;\n issuer: string;\n}): Promise<string> {\n return new jose.SignJWT({\n typ: \"agent-native-mcp-oauth\",\n sub: params.ownerEmail,\n ...(params.orgId ? { org_id: params.orgId } : {}),\n ...(params.orgDomain ? { org_domain: params.orgDomain } : {}),\n scope: params.scope,\n client_id: params.clientId,\n resource: params.resource,\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setIssuer(params.issuer)\n .setAudience(params.resource)\n .setJti(randomUUID())\n .setIssuedAt()\n .setExpirationTime(MCP_OAUTH_ACCESS_TOKEN_TTL)\n .sign(signingSecret());\n}\n\nexport async function verifyMcpOAuthAccessToken(\n token: string,\n resource: string | undefined,\n): Promise<{\n userEmail: string;\n orgId?: string;\n orgDomain?: string;\n scopes: string[];\n clientId: string;\n} | null> {\n if (!resource) return null;\n try {\n const { payload } = await jose.jwtVerify(token, signingSecret(), {\n audience: resource,\n });\n if (payload.typ !== \"agent-native-mcp-oauth\") return null;\n if (payload.resource !== resource) return null;\n if (typeof payload.sub !== \"string\" || !payload.sub) return null;\n if (typeof payload.client_id !== \"string\" || !payload.client_id) {\n return null;\n }\n const scope = typeof payload.scope === \"string\" ? payload.scope : \"\";\n const scopes = scopeList(scope);\n if (!scopes.some((s) => MCP_OAUTH_SCOPES.includes(s as any))) {\n return null;\n }\n return {\n userEmail: payload.sub,\n orgId: typeof payload.org_id === \"string\" ? payload.org_id : undefined,\n orgDomain:\n typeof payload.org_domain === \"string\" ? payload.org_domain : undefined,\n scopes,\n clientId: payload.client_id,\n };\n } catch {\n return null;\n }\n}\n"]}
|
package/dist/mcp/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAYlC,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AACF,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,cAAc,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAYlC,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AACF,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,cAAc,EAAE,CAAC;AAmJ7D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,SAAS,GAChB,OAAO,CAAC,QAAQ,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC,CA2H5D;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,QAAQ,CACtB,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,SAAS,EACjB,WAAW,SAAmB,GAC7B,IAAI,CAYN"}
|
package/dist/mcp/server.js
CHANGED
|
@@ -39,7 +39,8 @@ function shouldUseNodeFastPath(event) {
|
|
|
39
39
|
*/
|
|
40
40
|
function deriveRequestMeta(event) {
|
|
41
41
|
const forwardedProto = getRequestHeader(event, "x-forwarded-proto");
|
|
42
|
-
const host = getRequestHeader(event, "host")
|
|
42
|
+
const host = getRequestHeader(event, "x-forwarded-host") ||
|
|
43
|
+
getRequestHeader(event, "host");
|
|
43
44
|
const proto = forwardedProto?.split(",")[0]?.trim() ||
|
|
44
45
|
(host && /^(localhost|127\.0\.0\.1)(:|$)/.test(host) ? "http" : "https");
|
|
45
46
|
const origin = host ? `${proto}://${host}` : undefined;
|
|
@@ -113,18 +114,12 @@ function buildWebRequest(event, method) {
|
|
|
113
114
|
// a POST. Real MCP clients (Claude Code, `agent-native connect`) always
|
|
114
115
|
// send these; we never inject/alter them — if they're absent the SDK
|
|
115
116
|
// returns its spec-mandated 406/415, identical to the Node path.
|
|
116
|
-
const host = headers.get("host") || "localhost";
|
|
117
|
+
const host = headers.get("x-forwarded-host") || headers.get("host") || "localhost";
|
|
117
118
|
const forwardedProto = headers.get("x-forwarded-proto");
|
|
118
119
|
const proto = forwardedProto?.split(",")[0]?.trim() ||
|
|
119
120
|
(/^(localhost|127\.0\.0\.1)(:|$)/.test(host) ? "http" : "https");
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
if (src?.url)
|
|
123
|
-
url = new URL(src.url).href;
|
|
124
|
-
}
|
|
125
|
-
catch {
|
|
126
|
-
// keep the synthesized URL
|
|
127
|
-
}
|
|
121
|
+
const basePath = getConfiguredAppBasePath();
|
|
122
|
+
const url = `${proto}://${host}${basePath}/_agent-native/mcp`;
|
|
128
123
|
// No body here on purpose: the JSON-RPC payload is forwarded via the
|
|
129
124
|
// transport's `parsedBody` option (the same mechanism the Node transport
|
|
130
125
|
// uses), so the request stream is never read twice.
|
package/dist/mcp/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ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tB,QAAa,EACb,MAAiB,EACjB,WAAW,GAAG,gBAAgB;IAE9B,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CACpB,GAAG,WAAW,MAAM,EACpB,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjC,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CACH,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport { buildMcpOAuthChallenge, getMcpOAuthResource } from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host = getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host = headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n let url = `${proto}://${host}/_agent-native/mcp`;\n try {\n if (src?.url) url = new URL(src.url).href;\n } catch {\n // keep the synthesized URL\n }\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<Response | string | { error: string } | undefined> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthResource(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return { error: \"Unauthorized\" };\n }\n\n // Stateless mode: only POST is meaningful\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\" && method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions,\n * compatible with serverless deployments. Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OA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C,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport { buildMcpOAuthChallenge, getMcpOAuthResource } from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}/_agent-native/mcp`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<Response | string | { error: string } | undefined> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthResource(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return { error: \"Unauthorized\" };\n }\n\n // Stateless mode: only POST is meaningful\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\" && method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions,\n * compatible with serverless deployments. Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deep-link.d.ts","sourceRoot":"","sources":["../../src/server/deep-link.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"deep-link.d.ts","sourceRoot":"","sources":["../../src/server/deep-link.ts"],"names":[],"mappings":"AAwBA,2EAA2E;AAC3E,eAAO,MAAM,kBAAkB,UAAU,CAAC;AAE1C,8EAA8E;AAC9E,eAAO,MAAM,gBAAgB,uBAAuB,CAAC;AAErD,MAAM,WAAW,aAAa;IAC5B,uEAAuE;IACvE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAC;IACb;yEACqE;IACrE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;IACtE;uDACmD;IACnD,EAAE,CAAC,EAAE,MAAM,CAAC;CACb;AAcD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAI1D;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,GAAG,SAAS,GACzB,MAAM,CAMR;AAgBD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAI1D"}
|
package/dist/server/deep-link.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* UI already drains every 2s.
|
|
18
18
|
*/
|
|
19
19
|
import { withCollapsedAgentSidebarParam } from "../shared/agent-sidebar-url.js";
|
|
20
|
+
import { getConfiguredAppBasePath, normalizeAppBasePath, } from "./app-base-path.js";
|
|
20
21
|
/** Path of the framework deep-link route, relative to the route prefix. */
|
|
21
22
|
export const OPEN_ROUTE_SUBPATH = "/open";
|
|
22
23
|
/** Custom URL scheme the desktop app registers (`agentnative://open?...`). */
|
|
@@ -50,9 +51,23 @@ export function buildDeepLink(input) {
|
|
|
50
51
|
export function toAbsoluteOpenUrl(urlOrPath, origin) {
|
|
51
52
|
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(urlOrPath))
|
|
52
53
|
return urlOrPath;
|
|
54
|
+
const basePath = getConfiguredAppBasePath();
|
|
55
|
+
const path = withBasePath(urlOrPath, basePath);
|
|
53
56
|
if (!origin)
|
|
57
|
+
return path;
|
|
58
|
+
return `${origin.replace(/\/+$/, "")}${path.startsWith("/") ? "" : "/"}${path}`;
|
|
59
|
+
}
|
|
60
|
+
function withBasePath(urlOrPath, basePath) {
|
|
61
|
+
if (!basePath)
|
|
62
|
+
return urlOrPath;
|
|
63
|
+
const leadingPath = urlOrPath.startsWith("/") ? urlOrPath : `/${urlOrPath}`;
|
|
64
|
+
const [pathname] = leadingPath.split(/[?#]/, 1);
|
|
65
|
+
const normalizedPathname = normalizeAppBasePath(pathname);
|
|
66
|
+
if (normalizedPathname === basePath ||
|
|
67
|
+
normalizedPathname.startsWith(`${basePath}/`)) {
|
|
54
68
|
return urlOrPath;
|
|
55
|
-
|
|
69
|
+
}
|
|
70
|
+
return `${basePath}${leadingPath}`;
|
|
56
71
|
}
|
|
57
72
|
/**
|
|
58
73
|
* Rewrite a deep link to the desktop `agentnative://open?...` scheme so the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deep-link.js","sourceRoot":"","sources":["../../src/server/deep-link.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"deep-link.js","sourceRoot":"","sources":["../../src/server/deep-link.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,EACL,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAE5B,2EAA2E;AAC3E,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAO,CAAC;AAE1C,8EAA8E;AAC9E,MAAM,CAAC,MAAM,gBAAgB,GAAG,oBAAoB,CAAC;AAerD,SAAS,UAAU,CAAC,KAAoB;IACtC,MAAM,EAAE,GAAG,IAAI,eAAe,EAAE,CAAC;IACjC,IAAI,KAAK,CAAC,GAAG;QAAE,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACxC,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3B,IAAI,KAAK,CAAC,EAAE;QAAE,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;IACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM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AChD,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IAC1D,IACE,kBAAkB,KAAK,QAAQ;QAC/B,kBAAkB,CAAC,UAAU,CAAC,GAAG,QAAQ,GAAG,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,GAAG,QAAQ,GAAG,WAAW,EAAE,CAAC;AACrC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,SAAiB;IAChD,MAAM,IAAI,GAAG,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACzD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,gBAAgB,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,gBAAgB,CAAC;AACnE,CAAC","sourcesContent":["/**\n * Deep-link helpers — the single source of truth for the\n * `/_agent-native/open` URL format.\n *\n * Every artifact-producing / list action that wants an external agent (MCP /\n * A2A) to surface an \"Open in <app> →\" link returns\n * `{ url: buildDeepLink(...), label }` from its `link` builder. The MCP layer\n * turns the relative path into an absolute web URL (and an `agentnative://`\n * desktop URL) using the request origin.\n *\n * The `/_agent-native/open` route (see `open-route.ts`) consumes these: it\n * resolves the *browser session's* identity, writes the existing one-shot\n * `navigate` application-state command, and 302-redirects to the rendered SPA\n * view so any browser / inline webview lands on the right screen with the\n * record focused. We never invent a new navigation mechanism — this just\n * bridges external surfaces to the `navigate`/`application_state` contract the\n * UI already drains every 2s.\n */\nimport { withCollapsedAgentSidebarParam } from \"../shared/agent-sidebar-url.js\";\nimport {\n getConfiguredAppBasePath,\n normalizeAppBasePath,\n} from \"./app-base-path.js\";\n\n/** Path of the framework deep-link route, relative to the route prefix. */\nexport const OPEN_ROUTE_SUBPATH = \"/open\";\n\n/** Custom URL scheme the desktop app registers (`agentnative://open?...`). */\nexport const DESKTOP_OPEN_URL = \"agentnative://open\";\n\nexport interface DeepLinkInput {\n /** App id (informational + multi-app/desktop routing), e.g. \"mail\". */\n app?: string;\n /** Target view — maps to the `navigate` command `view`. */\n view: string;\n /** Record-focus + filter params, e.g. `{ threadId }`, `{ eventId, date }`,\n * `{ dashboardId }`. `undefined`/`null`/`\"\"` values are dropped. */\n params?: Record<string, string | number | boolean | null | undefined>;\n /** Explicit client-side path override (must be a same-origin, leading-slash\n * relative path — enforced by the open route). */\n to?: string;\n}\n\nfunction buildQuery(input: DeepLinkInput): string {\n const sp = new URLSearchParams();\n if (input.app) sp.set(\"app\", input.app);\n sp.set(\"view\", input.view);\n if (input.to) sp.set(\"to\", input.to);\n for (const [k, v] of Object.entries(input.params ?? {})) {\n if (v === undefined || v === null || v === \"\") continue;\n sp.set(k, String(v));\n }\n return sp.toString();\n}\n\n/**\n * Build the app-relative deep-link path:\n * `/_agent-native/open?app=mail&view=inbox&threadId=abc`.\n * Per-app `link` builders call this; never hand-format the URL.\n */\nexport function buildDeepLink(input: DeepLinkInput): string {\n return withCollapsedAgentSidebarParam(\n `/_agent-native${OPEN_ROUTE_SUBPATH}?${buildQuery(input)}`,\n );\n}\n\n/**\n * Resolve a (possibly relative) deep link to an absolute web URL using the\n * inbound request origin. Absolute URLs pass through unchanged.\n */\nexport function toAbsoluteOpenUrl(\n urlOrPath: string,\n origin: string | undefined,\n): string {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(urlOrPath)) return urlOrPath;\n const basePath = getConfiguredAppBasePath();\n const path = withBasePath(urlOrPath, basePath);\n if (!origin) return path;\n return `${origin.replace(/\\/+$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n}\n\nfunction withBasePath(urlOrPath: string, basePath: string): string {\n if (!basePath) return urlOrPath;\n const leadingPath = urlOrPath.startsWith(\"/\") ? urlOrPath : `/${urlOrPath}`;\n const [pathname] = leadingPath.split(/[?#]/, 1);\n const normalizedPathname = normalizeAppBasePath(pathname);\n if (\n normalizedPathname === basePath ||\n normalizedPathname.startsWith(`${basePath}/`)\n ) {\n return urlOrPath;\n }\n return `${basePath}${leadingPath}`;\n}\n\n/**\n * Rewrite a deep link to the desktop `agentnative://open?...` scheme so the\n * desktop app's existing `handleDeepLink` opens it inside the app webview.\n * Accepts either an app-relative `/_agent-native/open?...` path or an absolute\n * web URL; preserves the query string.\n */\nexport function toDesktopOpenUrl(urlOrPath: string): string {\n const qIdx = urlOrPath.indexOf(\"?\");\n const query = qIdx >= 0 ? urlOrPath.slice(qIdx + 1) : \"\";\n return query ? `${DESKTOP_OPEN_URL}?${query}` : DESKTOP_OPEN_URL;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"security-headers.d.ts","sourceRoot":"","sources":["../../src/server/security-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;
|
|
1
|
+
{"version":3,"file":"security-headers.d.ts","sourceRoot":"","sources":["../../src/server/security-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AA2CH;;;;;;GAMG;AACH,wBAAgB,+BAA+B,8EA6C9C"}
|
|
@@ -76,6 +76,11 @@ function isHttpsRequest(event) {
|
|
|
76
76
|
return true;
|
|
77
77
|
return false;
|
|
78
78
|
}
|
|
79
|
+
function isMcpEndpointRequest(event) {
|
|
80
|
+
const pathname = event?.url?.pathname ??
|
|
81
|
+
String(event?.node?.req?.url ?? event?.path ?? "/").split("?")[0];
|
|
82
|
+
return (pathname === "/_agent-native/mcp" || pathname.endsWith("/_agent-native/mcp"));
|
|
83
|
+
}
|
|
79
84
|
/**
|
|
80
85
|
* Create the security-headers h3 middleware. Mount this BEFORE other route
|
|
81
86
|
* handlers so the headers are present on every response (including 4xx/5xx
|
|
@@ -87,6 +92,7 @@ export function createSecurityHeadersMiddleware() {
|
|
|
87
92
|
const isProduction = process.env.NODE_ENV === "production";
|
|
88
93
|
return defineEventHandler((event) => {
|
|
89
94
|
const embedFrameRequest = requestHasEmbedAuthMarker(event);
|
|
95
|
+
const mcpEndpointRequest = isMcpEndpointRequest(event);
|
|
90
96
|
const requestOrigin = getHeader(event, "origin");
|
|
91
97
|
setResponseHeader(event, "X-Content-Type-Options", "nosniff");
|
|
92
98
|
if (isProduction && !embedFrameRequest) {
|
|
@@ -98,7 +104,7 @@ export function createSecurityHeadersMiddleware() {
|
|
|
98
104
|
if (embedFrameRequest) {
|
|
99
105
|
setResponseHeader(event, "Cross-Origin-Embedder-Policy", "require-corp");
|
|
100
106
|
}
|
|
101
|
-
setResponseHeader(event, "Cross-Origin-Resource-Policy", embedFrameRequest ? "cross-origin" : "same-site");
|
|
107
|
+
setResponseHeader(event, "Cross-Origin-Resource-Policy", embedFrameRequest || mcpEndpointRequest ? "cross-origin" : "same-site");
|
|
102
108
|
if (embedFrameRequest && isMcpEmbedCorsOrigin(requestOrigin)) {
|
|
103
109
|
setResponseHeader(event, "Access-Control-Allow-Origin", requestOrigin);
|
|
104
110
|
setResponseHeader(event, "Vary", "Origin");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"security-headers.js","sourceRoot":"","sources":["../../src/server/security-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AAEH,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AAExC,MAAM,IAAI,GAAG,8CAA8C,CAAC;AAC5D,MAAM,kBAAkB,GACtB,mEAAmE,CA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AAC;YACvC,iBAAiB,CAAC,KAAK,EAAE,iBAAiB,EAAE,MAAM,CAAC,CAAC;QACtD,CAAC;QACD,iBAAiB,CACf,KAAK,EACL,iBAAiB,EACjB,iBAAiB,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,iCAAiC,CACtE,CAAC;QACF,iBAAiB,CAAC,KAAK,EAAE,oBAAoB,EAAE,kBAAkB,CAAC,CAAC;QACnE,iBAAiB,CAAC,KAAK,EAAE,4BAA4B,EAAE,aAAa,CAAC,CAAC;QACtE,IAAI,iBAAiB,EAAE,CAAC;YACtB,iBAAiB,CAAC,KAAK,EAAE,8BAA8B,EAAE,cAAc,CAAC,CAAC;QAC3E,CAAC;QACD,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,iBAAiB,IAAI,kBAAkB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,WAAW,CACvE,CAAC;QACF,IAAI,iBAAiB,IAAI,oBAAoB,CAAC,aAAa,CAAC,EAAE,CAAC;YAC7D,iBAAiB,CAAC,KAAK,EAAE,6BAA6B,EAAE,aAAa,CAAC,CAAC;YACvE,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC3C,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,wCAAwC,CACzC,CAAC;YACF,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,4BAA4B,CAC7B,CAAC;QACJ,CAAC;QACD,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,iBAAiB,CAAC,KAAK,EAAE,2BAA2B,EAAE,IAAI,CAAC,CAAC;QAC9D,CAAC;QACD,2EAA2E;QAC3E,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Security response headers middleware.\n *\n * Sets a baseline set of \"no-brainer\" security headers on every framework HTTP\n * response. These headers are layered defenses: each one mitigates a specific\n * class of attack, and together they harden the surface against clickjacking,\n * MIME-sniffing, referrer leakage, mixed-content downgrades, and cross-origin\n * window/embed access.\n *\n * The headers we emit:\n *\n * - `Strict-Transport-Security` — forces HTTPS for the browser's lifetime\n * of the cached value, preventing SSL-strip MITM. Only emitted when the\n * request scheme is `https` (we don't want to break local-dev HTTP, and\n * emitting HSTS over HTTP is a no-op per the spec but causes confusion).\n * - `X-Content-Type-Options: nosniff` — disables browser MIME sniffing so\n * a tool /render route serving user-authored HTML can't be misinterpreted\n * as some other content type by a clever Accept header.\n * - `X-Frame-Options: DENY` — prevents the entire app from being iframed by\n * other origins (clickjacking the agent chat, booking pages, etc.). The\n * tool /render endpoint and any other route that legitimately needs to be\n * embedded in the same-origin app shell can opt out by setting its own\n * header inside the route handler — h3's `setResponseHeader` overwrites,\n * so a route emitting `SAMEORIGIN` wins over our middleware default.\n * We skip this header entirely in dev (NODE_ENV !== \"production\") so the\n * desktop app's local dev frame (localhost:3334) can iframe templates\n * running on other localhost ports (e.g. mail at 8085).\n * - `Referrer-Policy: strict-origin-when-cross-origin` — strips path/query\n * from outbound Referer headers when the request crosses origin, so a\n * public-share viewer's outbound link clicks never leak the share token.\n * - `Permissions-Policy: camera=(), microphone=(self), geolocation=(),\n * screen-wake-lock=()` — allows the app shell to request microphone access\n * for composer dictation while keeping camera/location/wake-lock blocked\n * by default. Templates that need broader media capture for recording UI\n * override this on their own routes.\n * - `Cross-Origin-Opener-Policy: same-origin` — isolates window.opener so\n * a popup-window opener reference can't read or modify our document.\n * - `Cross-Origin-Embedder-Policy: require-corp` — emitted only for\n * validated MCP embed-session page loads. COEP hosts such as Claude's MCP\n * Apps proxy require framed cross-origin documents to opt in explicitly.\n * - `Cross-Origin-Resource-Policy: same-site` — prevents other origins from\n * embedding our endpoints as `<img>` / `<script>` / `<audio>`, blocking\n * the simplest data-leak chain when combined with auth cookies. Validated\n * MCP embed-session page loads use `cross-origin` so COEP hosts such as\n * Claude's MCP Apps proxy can frame the short-lived app document.\n *\n * NOTE: We don't set `Cross-Origin-Embedder-Policy` because it requires every\n * embedded subresource to opt in via CORP/CORS, which would break Builder's\n * iframe editor and template embed use cases. COOP + CORP without COEP gives\n * us most of the protection.\n */\n\nimport { defineEventHandler, getHeader, setResponseHeader } from \"h3\";\nimport { requestHasEmbedAuthMarker } from \"./embed-session.js\";\nimport {\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n} from \"../shared/mcp-embed-headers.js\";\n\nconst HSTS = \"max-age=31536000; includeSubDomains; preload\";\nconst PERMISSIONS_POLICY =\n \"camera=(), microphone=(self), geolocation=(), screen-wake-lock=()\";\n\n/**\n * Returns true when the request was received over HTTPS. We trust both the\n * underlying connection (when the server is terminating TLS itself) and the\n * `x-forwarded-proto` header (set by Netlify, Vercel, Cloudflare, and any\n * other reverse proxy that fronts the framework).\n */\nfunction isHttpsRequest(event: any): boolean {\n const xfp =\n event?.node?.req?.headers?.[\"x-forwarded-proto\"] ??\n event?.headers?.get?.(\"x-forwarded-proto\");\n if (typeof xfp === \"string\" && xfp.split(\",\")[0].trim() === \"https\")\n return true;\n if (Array.isArray(xfp) && xfp[0] === \"https\") return true;\n // h3 sets `event.url.protocol` to \"http:\" or \"https:\".\n const proto = event?.url?.protocol;\n if (proto === \"https:\") return true;\n // Direct Node `req.connection.encrypted` (older runtimes).\n if (event?.node?.req?.connection?.encrypted) return true;\n return false;\n}\n\nfunction isMcpEndpointRequest(event: any): boolean {\n const pathname =\n event?.url?.pathname ??\n String(event?.node?.req?.url ?? event?.path ?? \"/\").split(\"?\")[0];\n return (\n pathname === \"/_agent-native/mcp\" || pathname.endsWith(\"/_agent-native/mcp\")\n );\n}\n\n/**\n * Create the security-headers h3 middleware. Mount this BEFORE other route\n * handlers so the headers are present on every response (including 4xx/5xx\n * error pages). Route handlers that need to relax a specific header (e.g.\n * `X-Frame-Options: SAMEORIGIN` on the tool render route) can call\n * `setResponseHeader` after this runs — the latest write wins.\n */\nexport function createSecurityHeadersMiddleware() {\n const isProduction = process.env.NODE_ENV === \"production\";\n return defineEventHandler((event) => {\n const embedFrameRequest = requestHasEmbedAuthMarker(event);\n const mcpEndpointRequest = isMcpEndpointRequest(event);\n const requestOrigin = getHeader(event, \"origin\");\n setResponseHeader(event, \"X-Content-Type-Options\", \"nosniff\");\n if (isProduction && !embedFrameRequest) {\n setResponseHeader(event, \"X-Frame-Options\", \"DENY\");\n }\n setResponseHeader(\n event,\n \"Referrer-Policy\",\n embedFrameRequest ? \"no-referrer\" : \"strict-origin-when-cross-origin\",\n );\n setResponseHeader(event, \"Permissions-Policy\", PERMISSIONS_POLICY);\n setResponseHeader(event, \"Cross-Origin-Opener-Policy\", \"same-origin\");\n if (embedFrameRequest) {\n setResponseHeader(event, \"Cross-Origin-Embedder-Policy\", \"require-corp\");\n }\n setResponseHeader(\n event,\n \"Cross-Origin-Resource-Policy\",\n embedFrameRequest || mcpEndpointRequest ? \"cross-origin\" : \"same-site\",\n );\n if (embedFrameRequest && isMcpEmbedCorsOrigin(requestOrigin)) {\n setResponseHeader(event, \"Access-Control-Allow-Origin\", requestOrigin);\n setResponseHeader(event, \"Vary\", \"Origin\");\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n MCP_EMBED_CORS_ALLOW_HEADERS,\n );\n }\n if (isHttpsRequest(event)) {\n setResponseHeader(event, \"Strict-Transport-Security\", HSTS);\n }\n // Continue to the next handler — we only set headers, don't return a body.\n return undefined;\n });\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const MCP_EMBED_CORS_ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant";
|
|
2
2
|
export declare const EMBED_TRANSPLANT_HEADER = "x-agent-native-embed-transplant";
|
|
3
3
|
export declare function isClaudeMcpContentOrigin(origin: string | null | undefined): boolean;
|
|
4
|
+
export declare function isChatGptMcpSandboxOrigin(origin: string | null | undefined): boolean;
|
|
4
5
|
export declare function isMcpEmbedCorsOrigin(origin: string | null | undefined): boolean;
|
|
5
6
|
export declare function shouldAllowMcpEmbedCredentials(origin: string | null | undefined): boolean;
|
|
6
7
|
export declare const MCP_EMBED_STATIC_ASSET_HEADERS: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-embed-headers.d.ts","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,4BAA4B,iKACuH,CAAC;AACjK,eAAO,MAAM,uBAAuB,oCAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"mcp-embed-headers.d.ts","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,4BAA4B,iKACuH,CAAC;AACjK,eAAO,MAAM,uBAAuB,oCAAoC,CAAC;AAMzE,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAUT;AAED,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAWT;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAMT;AAED,wBAAgB,8BAA8B,CAC5C,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAMT;AAED,eAAO,MAAM,8BAA8B;;;CAGjC,CAAC;AAoBX,wBAAgB,6BAA6B,CAC3C,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE,OAAO,8BAA8B,CAAA;CAAE,CAAC,CAapE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export const MCP_EMBED_CORS_ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant";
|
|
2
2
|
export const EMBED_TRANSPLANT_HEADER = "x-agent-native-embed-transplant";
|
|
3
3
|
const CLAUDE_MCP_CONTENT_HOST_RE = /^[a-f0-9]{32}\.claudemcpcontent\.com$/i;
|
|
4
|
+
const CHATGPT_MCP_SANDBOX_HOST_RE = /^[^.]+\.web-sandbox\.oaiusercontent\.com$/i;
|
|
4
5
|
export function isClaudeMcpContentOrigin(origin) {
|
|
5
6
|
if (!origin)
|
|
6
7
|
return false;
|
|
@@ -12,11 +13,27 @@ export function isClaudeMcpContentOrigin(origin) {
|
|
|
12
13
|
return false;
|
|
13
14
|
}
|
|
14
15
|
}
|
|
16
|
+
export function isChatGptMcpSandboxOrigin(origin) {
|
|
17
|
+
if (!origin)
|
|
18
|
+
return false;
|
|
19
|
+
try {
|
|
20
|
+
const url = new URL(origin);
|
|
21
|
+
return (url.protocol === "https:" &&
|
|
22
|
+
CHATGPT_MCP_SANDBOX_HOST_RE.test(url.hostname));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
15
28
|
export function isMcpEmbedCorsOrigin(origin) {
|
|
16
|
-
return origin === "null" ||
|
|
29
|
+
return (origin === "null" ||
|
|
30
|
+
isClaudeMcpContentOrigin(origin) ||
|
|
31
|
+
isChatGptMcpSandboxOrigin(origin));
|
|
17
32
|
}
|
|
18
33
|
export function shouldAllowMcpEmbedCredentials(origin) {
|
|
19
|
-
return origin !== "null" &&
|
|
34
|
+
return (origin !== "null" &&
|
|
35
|
+
!isClaudeMcpContentOrigin(origin) &&
|
|
36
|
+
!isChatGptMcpSandboxOrigin(origin));
|
|
20
37
|
}
|
|
21
38
|
export const MCP_EMBED_STATIC_ASSET_HEADERS = {
|
|
22
39
|
"Access-Control-Allow-Origin": "*",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-embed-headers.js","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,4BAA4B,GACvC,8JAA8J,CAAC;AACjK,MAAM,CAAC,MAAM,uBAAuB,GAAG,iCAAiC,CAAC;AAEzE,MAAM,0BAA0B,GAAG,wCAAwC,CAAC;
|
|
1
|
+
{"version":3,"file":"mcp-embed-headers.js","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,4BAA4B,GACvC,8JAA8J,CAAC;AACjK,MAAM,CAAC,MAAM,uBAAuB,GAAG,iCAAiC,CAAC;AAEzE,MAAM,0BAA0B,GAAG,wCAAwC,CAAC;AAC5E,MAAM,2BAA2B,GAC/B,4CAA4C,CAAC;AAE/C,MAAM,UAAU,wBAAwB,CACtC,MAAiC;IAEjC,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,OAAO,CACL,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,0BAA0B,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAC3E,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,MAAiC;IAEjC,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,OAAO,CACL,GAAG,CAAC,QAAQ,KAAK,QAAQ;YACzB,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAC/C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,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AE,OAAO,EAAE,8BAA8B,EAAE,CAAC;QAC7D,IAAI,IAAI,EAAE,CAAC;YACT,KAAK,CAAC,GAAG,IAAI,GAAG,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,8BAA8B,EAAE,CAAC;QAC3E,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["export const MCP_EMBED_CORS_ALLOW_HEADERS =\n \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant\";\nexport const EMBED_TRANSPLANT_HEADER = \"x-agent-native-embed-transplant\";\n\nconst CLAUDE_MCP_CONTENT_HOST_RE = /^[a-f0-9]{32}\\.claudemcpcontent\\.com$/i;\nconst CHATGPT_MCP_SANDBOX_HOST_RE =\n /^[^.]+\\.web-sandbox\\.oaiusercontent\\.com$/i;\n\nexport function isClaudeMcpContentOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"https:\" && CLAUDE_MCP_CONTENT_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isChatGptMcpSandboxOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"https:\" &&\n CHATGPT_MCP_SANDBOX_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isMcpEmbedCorsOrigin(\n origin: string | null | undefined,\n): boolean {\n return (\n origin === \"null\" ||\n isClaudeMcpContentOrigin(origin) ||\n isChatGptMcpSandboxOrigin(origin)\n );\n}\n\nexport function shouldAllowMcpEmbedCredentials(\n origin: string | null | undefined,\n): boolean {\n return (\n origin !== \"null\" &&\n !isClaudeMcpContentOrigin(origin) &&\n !isChatGptMcpSandboxOrigin(origin)\n );\n}\n\nexport const MCP_EMBED_STATIC_ASSET_HEADERS = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Cross-Origin-Resource-Policy\": \"cross-origin\",\n} as const;\n\nconst STATIC_ASSET_PATTERNS = [\n \"/assets/**\",\n \"/favicon.ico\",\n \"/favicon.svg\",\n \"/manifest.json\",\n \"/icon-*.svg\",\n \"/agent-native-*.svg\",\n \"/library-presets/**\",\n];\n\nfunction normalizeBasePath(basePath: string | undefined): string {\n const base = (basePath ?? \"\").trim();\n if (!base || base === \"/\") return \"\";\n return base.startsWith(\"/\")\n ? base.replace(/\\/+$/g, \"\")\n : `/${base.replace(/\\/+$/g, \"\")}`;\n}\n\nexport function mcpEmbedStaticAssetRouteRules(\n basePath?: string,\n): Record<string, { headers: typeof MCP_EMBED_STATIC_ASSET_HEADERS }> {\n const base = normalizeBasePath(basePath);\n const rules: Record<\n string,\n { headers: typeof MCP_EMBED_STATIC_ASSET_HEADERS }\n > = {};\n for (const pattern of STATIC_ASSET_PATTERNS) {\n rules[pattern] = { headers: MCP_EMBED_STATIC_ASSET_HEADERS };\n if (base) {\n rules[`${base}${pattern}`] = { headers: MCP_EMBED_STATIC_ASSET_HEADERS };\n }\n }\n return rules;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/vite/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/vite/client.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAU,UAAU,EAAE,MAAM,MAAM,CAAC;AAyZ/C,MAAM,WAAW,YAAY;IAC3B,sGAAsG;IACtG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oEAAoE;IACpE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4CAA4C;IAC5C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,mBAAmB;IAClC,yC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client.js
CHANGED
|
@@ -6,6 +6,8 @@ import { actionTypesPlugin } from "./action-types-plugin.js";
|
|
|
6
6
|
import { agentsBundlePlugin } from "./agents-bundle-plugin.js";
|
|
7
7
|
import { findWorkspaceRoot } from "../scripts/utils.js";
|
|
8
8
|
import { getViteDevRecoveryScript } from "../client/vite-dev-recovery-script.js";
|
|
9
|
+
import { verifyEmbedSessionToken } from "../server/embed-session.js";
|
|
10
|
+
import { EMBED_SESSION_COOKIE, EMBED_TOKEN_QUERY_PARAM, MCP_APP_CHAT_BRIDGE_QUERY_PARAM, } from "../shared/embed-auth.js";
|
|
9
11
|
import { isMcpEmbedCorsOrigin, MCP_EMBED_CORS_ALLOW_HEADERS, MCP_EMBED_STATIC_ASSET_HEADERS, mcpEmbedStaticAssetRouteRules, } from "../shared/mcp-embed-headers.js";
|
|
10
12
|
import { fileURLToPath } from "url";
|
|
11
13
|
const require = createRequire(import.meta.url);
|
|
@@ -449,6 +451,9 @@ function baseRedirectGuard() {
|
|
|
449
451
|
// original path so the normal dev-server error handling applies.
|
|
450
452
|
}
|
|
451
453
|
}
|
|
454
|
+
if (serveMountedEmbedRuntimeModule(server, req, res, base)) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
452
457
|
req.url = stripMountedDevApiPath(req.url, base);
|
|
453
458
|
if (req.method === "HEAD" &&
|
|
454
459
|
req.url &&
|
|
@@ -466,6 +471,125 @@ function baseRedirectGuard() {
|
|
|
466
471
|
},
|
|
467
472
|
};
|
|
468
473
|
}
|
|
474
|
+
const VITE_RUNTIME_PATH_PREFIXES = [
|
|
475
|
+
"/@fs/",
|
|
476
|
+
"/@id/",
|
|
477
|
+
"/@vite/",
|
|
478
|
+
"/app/",
|
|
479
|
+
"/node_modules/",
|
|
480
|
+
"/packages/",
|
|
481
|
+
"/src/",
|
|
482
|
+
];
|
|
483
|
+
function cookieValue(req, name) {
|
|
484
|
+
const header = req.headers.cookie;
|
|
485
|
+
if (typeof header !== "string" || !header)
|
|
486
|
+
return undefined;
|
|
487
|
+
for (const part of header.split(";")) {
|
|
488
|
+
const index = part.indexOf("=");
|
|
489
|
+
if (index < 0)
|
|
490
|
+
continue;
|
|
491
|
+
const key = part.slice(0, index).trim();
|
|
492
|
+
if (key !== name)
|
|
493
|
+
continue;
|
|
494
|
+
try {
|
|
495
|
+
return decodeURIComponent(part.slice(index + 1).trim());
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
return part.slice(index + 1).trim();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return undefined;
|
|
502
|
+
}
|
|
503
|
+
function hasValidEmbedRuntimeToken(req) {
|
|
504
|
+
try {
|
|
505
|
+
const url = new URL(req.url ?? "/", "http://agent-native.local");
|
|
506
|
+
const queryToken = url.searchParams.get(EMBED_TOKEN_QUERY_PARAM);
|
|
507
|
+
const cookieToken = cookieValue(req, EMBED_SESSION_COOKIE);
|
|
508
|
+
return [queryToken, cookieToken].some((token) => verifyEmbedSessionToken(token).ok);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function mountedEmbedRuntimeModuleUrl(reqUrl, base) {
|
|
515
|
+
if (!reqUrl || !base || base === "/")
|
|
516
|
+
return null;
|
|
517
|
+
const normalizedBase = base.endsWith("/") ? base : `${base}/`;
|
|
518
|
+
if (!reqUrl.startsWith(normalizedBase))
|
|
519
|
+
return null;
|
|
520
|
+
const runtimeUrl = reqUrl.slice(normalizedBase.length - 1) || "/";
|
|
521
|
+
let url;
|
|
522
|
+
try {
|
|
523
|
+
url = new URL(runtimeUrl, "http://agent-native.local");
|
|
524
|
+
}
|
|
525
|
+
catch {
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
if (!VITE_RUNTIME_PATH_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) {
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
url.searchParams.delete(EMBED_TOKEN_QUERY_PARAM);
|
|
532
|
+
url.searchParams.delete(MCP_APP_CHAT_BRIDGE_QUERY_PARAM);
|
|
533
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
534
|
+
}
|
|
535
|
+
function virtualModuleIdFromRuntimeUrl(runtimeUrl) {
|
|
536
|
+
try {
|
|
537
|
+
const pathname = new URL(runtimeUrl, "http://agent-native.local").pathname;
|
|
538
|
+
const prefix = "/@id/__x00__";
|
|
539
|
+
if (!pathname.startsWith(prefix))
|
|
540
|
+
return null;
|
|
541
|
+
return `\0${decodeURIComponent(pathname.slice(prefix.length))}`;
|
|
542
|
+
}
|
|
543
|
+
catch {
|
|
544
|
+
return null;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
async function loadMountedEmbedRuntimeModule(server, runtimeUrl) {
|
|
548
|
+
const virtualId = virtualModuleIdFromRuntimeUrl(runtimeUrl);
|
|
549
|
+
if (virtualId) {
|
|
550
|
+
const loaded = await server.pluginContainer?.load?.(virtualId);
|
|
551
|
+
if (typeof loaded === "string")
|
|
552
|
+
return loaded;
|
|
553
|
+
if (loaded && typeof loaded.code === "string")
|
|
554
|
+
return loaded.code;
|
|
555
|
+
}
|
|
556
|
+
const result = await server.transformRequest(runtimeUrl);
|
|
557
|
+
return result?.code ?? null;
|
|
558
|
+
}
|
|
559
|
+
function serveMountedEmbedRuntimeModule(server, req, res, base) {
|
|
560
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
561
|
+
return false;
|
|
562
|
+
if (!hasValidEmbedRuntimeToken(req))
|
|
563
|
+
return false;
|
|
564
|
+
const runtimeUrl = mountedEmbedRuntimeModuleUrl(req.url, base);
|
|
565
|
+
if (!runtimeUrl)
|
|
566
|
+
return false;
|
|
567
|
+
void loadMountedEmbedRuntimeModule(server, runtimeUrl)
|
|
568
|
+
.then((code) => {
|
|
569
|
+
if (!code) {
|
|
570
|
+
if (!res.headersSent) {
|
|
571
|
+
res.statusCode = 404;
|
|
572
|
+
res.end();
|
|
573
|
+
}
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
res.statusCode = 200;
|
|
577
|
+
res.setHeader("content-type", "text/javascript");
|
|
578
|
+
if (req.method === "HEAD") {
|
|
579
|
+
res.end();
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
res.end(code);
|
|
583
|
+
})
|
|
584
|
+
.catch((err) => {
|
|
585
|
+
if (res.headersSent)
|
|
586
|
+
return;
|
|
587
|
+
res.statusCode = 500;
|
|
588
|
+
res.setHeader("content-type", "text/plain");
|
|
589
|
+
res.end(err instanceof Error ? err.message : String(err));
|
|
590
|
+
});
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
469
593
|
function embedDevFrameHeaders() {
|
|
470
594
|
return {
|
|
471
595
|
name: "agent-native-embed-dev-frame-headers",
|