doccupine 0.0.140 → 0.0.142

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.
Files changed (145) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1894
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +10 -5
  19. package/dist/lib/utils.js +108 -5
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +72 -20
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +342 -34
  38. package/dist/templates/components/SearchDocs.d.ts +1 -1
  39. package/dist/templates/components/SearchDocs.js +63 -11
  40. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  41. package/dist/templates/components/SearchModalContent.js +191 -49
  42. package/dist/templates/components/SideBar.d.ts +1 -1
  43. package/dist/templates/components/SideBar.js +8 -2
  44. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  45. package/dist/templates/components/layout/Accordion.js +26 -3
  46. package/dist/templates/components/layout/Badge.d.ts +1 -1
  47. package/dist/templates/components/layout/Badge.js +1 -1
  48. package/dist/templates/components/layout/Button.d.ts +1 -1
  49. package/dist/templates/components/layout/Button.js +4 -4
  50. package/dist/templates/components/layout/Callout.d.ts +1 -1
  51. package/dist/templates/components/layout/Callout.js +6 -6
  52. package/dist/templates/components/layout/Card.d.ts +1 -1
  53. package/dist/templates/components/layout/Card.js +9 -4
  54. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  55. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  56. package/dist/templates/components/layout/Code.d.ts +1 -1
  57. package/dist/templates/components/layout/Code.js +5 -5
  58. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  59. package/dist/templates/components/layout/CopyButton.js +1 -1
  60. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  61. package/dist/templates/components/layout/DemoTheme.js +8 -28
  62. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  63. package/dist/templates/components/layout/DocsComponents.js +57 -6
  64. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  65. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  66. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  67. package/dist/templates/components/layout/Prompt.js +4 -7
  68. package/dist/templates/components/layout/Steps.d.ts +1 -1
  69. package/dist/templates/components/layout/Steps.js +7 -1
  70. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  71. package/dist/templates/components/layout/Tabs.js +108 -19
  72. package/dist/templates/env.example.d.ts +1 -1
  73. package/dist/templates/env.example.js +11 -0
  74. package/dist/templates/eslint.config.d.ts +1 -1
  75. package/dist/templates/eslint.config.js +20 -0
  76. package/dist/templates/gitignore.d.ts +1 -1
  77. package/dist/templates/gitignore.js +4 -3
  78. package/dist/templates/lib/access.d.ts +1 -0
  79. package/dist/templates/lib/access.js +41 -0
  80. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  82. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  84. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/authentication.mdx.js +5 -3
  86. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/commands.mdx.js +20 -6
  88. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/components.mdx.js +3 -0
  90. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  92. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/globals.mdx.js +14 -11
  94. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  96. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  98. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  100. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  101. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  102. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  104. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  105. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  106. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  108. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  110. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  114. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/sections.mdx.js +4 -0
  116. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  117. package/dist/templates/mdx/space.mdx.js +125 -0
  118. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/tabs.mdx.js +4 -0
  120. package/dist/templates/next.config.js +20 -8
  121. package/dist/templates/package.js +3 -3
  122. package/dist/templates/prettierignore.d.ts +1 -1
  123. package/dist/templates/prettierignore.js +1 -0
  124. package/dist/templates/proxy.js +47 -19
  125. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  126. package/dist/templates/scripts/build-docs-index.js +1 -0
  127. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  128. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  129. package/dist/templates/services/mcp/server.d.ts +1 -1
  130. package/dist/templates/services/mcp/server.js +140 -83
  131. package/dist/templates/services/mcp/tools.d.ts +1 -1
  132. package/dist/templates/services/mcp/tools.js +65 -137
  133. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  134. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  135. package/dist/templates/utils/rateLimit.d.ts +1 -1
  136. package/dist/templates/utils/rateLimit.js +40 -3
  137. package/dist/templates/utils/requestBody.d.ts +1 -0
  138. package/dist/templates/utils/requestBody.js +56 -0
  139. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  140. package/dist/templates/utils/ssrfGuard.js +138 -33
  141. package/package.json +13 -5
  142. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  143. package/dist/lib/mdxToMarkdown.js +0 -134
  144. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  145. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -1 +1 @@
1
- export declare const gateRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { cookies } from \"next/headers\";\nimport { GATE_COOKIE_NAME, gateToken, timingSafeEqual } from \"@/lib/siteGate\";\nimport { rateLimit } from \"@/utils/rateLimit\";\n\nexport async function POST(req: Request) {\n const password = process.env.SITE_PASSWORD;\n if (!password) {\n return NextResponse.json({ ok: true });\n }\n\n // Rate limit password attempts by IP to slow down brute-force guessing.\n const ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ?? \"unknown\";\n const { allowed, retryAfter } = rateLimit(ip);\n if (!allowed) {\n return NextResponse.json(\n { ok: false, error: \"Too many attempts\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let submitted: unknown;\n try {\n submitted = (await req.json())?.password;\n } catch {\n return NextResponse.json(\n { ok: false, error: \"Bad Request\" },\n { status: 400 },\n );\n }\n\n const expected = await gateToken(password);\n const candidate = await gateToken(\n typeof submitted === \"string\" ? submitted : \"\",\n );\n\n if (!timingSafeEqual(candidate, expected)) {\n return NextResponse.json(\n { ok: false, error: \"Incorrect password\" },\n { status: 401 },\n );\n }\n\n const cookieStore = await cookies();\n cookieStore.set(GATE_COOKIE_NAME, expected, {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n path: \"/\",\n maxAge: 60 * 60 * 24 * 30, // 30 days\n });\n\n return NextResponse.json({ ok: true });\n}\n";
1
+ export declare const gateRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { cookies } from \"next/headers\";\nimport { GATE_COOKIE_NAME, gateToken, timingSafeEqual } from \"@/lib/siteGate\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_GATE_ENVELOPE_BYTES = 8 * 1024;\n\nexport async function POST(req: Request) {\n const password = process.env.SITE_PASSWORD;\n if (!password) {\n return NextResponse.json({ ok: true });\n }\n\n // Use per-client buckets only for platform-authenticated address headers.\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { ok: false, error: \"Too many attempts\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let submitted: unknown;\n try {\n const body = await readJsonBody(req, MAX_GATE_ENVELOPE_BYTES);\n submitted =\n typeof body === \"object\" && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>).password\n : undefined;\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { ok: false, error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json(\n { ok: false, error: \"Bad Request\" },\n { status: 400 },\n );\n }\n\n const expected = await gateToken(password);\n const candidate = await gateToken(\n typeof submitted === \"string\" ? submitted : \"\",\n );\n\n if (!timingSafeEqual(candidate, expected)) {\n return NextResponse.json(\n { ok: false, error: \"Incorrect password\" },\n { status: 401 },\n );\n }\n\n const cookieStore = await cookies();\n cookieStore.set(GATE_COOKIE_NAME, expected, {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n path: \"/\",\n maxAge: 60 * 60 * 24 * 30, // 30 days\n });\n\n return NextResponse.json({ ok: true });\n}\n";
@@ -2,6 +2,9 @@ export const gateRoutesTemplate = `import { NextResponse } from "next/server";
2
2
  import { cookies } from "next/headers";
3
3
  import { GATE_COOKIE_NAME, gateToken, timingSafeEqual } from "@/lib/siteGate";
4
4
  import { rateLimit } from "@/utils/rateLimit";
5
+ import { readJsonBody, RequestTooLargeError } from "@/utils/requestBody";
6
+
7
+ const MAX_GATE_ENVELOPE_BYTES = 8 * 1024;
5
8
 
6
9
  export async function POST(req: Request) {
7
10
  const password = process.env.SITE_PASSWORD;
@@ -9,10 +12,8 @@ export async function POST(req: Request) {
9
12
  return NextResponse.json({ ok: true });
10
13
  }
11
14
 
12
- // Rate limit password attempts by IP to slow down brute-force guessing.
13
- const ip =
14
- req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
15
- const { allowed, retryAfter } = rateLimit(ip);
15
+ // Use per-client buckets only for platform-authenticated address headers.
16
+ const { allowed, retryAfter } = rateLimit(req);
16
17
  if (!allowed) {
17
18
  return NextResponse.json(
18
19
  { ok: false, error: "Too many attempts" },
@@ -22,8 +23,19 @@ export async function POST(req: Request) {
22
23
 
23
24
  let submitted: unknown;
24
25
  try {
25
- submitted = (await req.json())?.password;
26
- } catch {
26
+ const body = await readJsonBody(req, MAX_GATE_ENVELOPE_BYTES);
27
+ submitted =
28
+ typeof body === "object" && body !== null && !Array.isArray(body)
29
+ ? (body as Record<string, unknown>).password
30
+ : undefined;
31
+ } catch (error: unknown) {
32
+ if (req.signal.aborted) throw error;
33
+ if (error instanceof RequestTooLargeError) {
34
+ return NextResponse.json(
35
+ { ok: false, error: "Request body too large" },
36
+ { status: 413 },
37
+ );
38
+ }
27
39
  return NextResponse.json(
28
40
  { ok: false, error: "Bad Request" },
29
41
  { status: 400 },
@@ -1 +1 @@
1
- export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport { createMCPServer } from \"@/services/mcp/server\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\n\nconst searchDocsSchema = z.object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(50).optional(),\n});\n\nconst getDocSchema = z.object({\n path: z.string().min(1).max(500),\n});\n\nconst listDocsSchema = z.object({\n directory: z.string().max(500).optional(),\n});\n\n// Create a stateless transport for serverless environment\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // Stateless mode for serverless\n enableJsonResponse: true,\n });\n}\n\n// Handle MCP protocol requests\nasync function handleMCPRequest(req: Request) {\n const transport = createTransport();\n const server = createMCPServer();\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(req);\n\n // Clean up after response is done\n response\n .clone()\n .body?.pipeTo(\n new WritableStream({\n close() {\n transport.close();\n server.close();\n },\n }),\n )\n .catch(() => {});\n\n return response;\n } catch (error) {\n console.error(\"MCP request error:\", error);\n return new Response(\n JSON.stringify({\n jsonrpc: \"2.0\",\n error: {\n code: -32603,\n message: \"Internal server error\",\n },\n id: null,\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\n// Handle REST API requests (original JSON format)\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: Record<string, unknown>;\n}\n\nasync function handleRESTRequest(body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n if (!tool) {\n return NextResponse.json(\n { error: \"Missing 'tool' parameter\" },\n { status: 400 },\n );\n }\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n await ensureDocsIndex();\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n );\n return NextResponse.json({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const doc = await getDoc({ path: parsed.data.path });\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return NextResponse.json({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const docs = await listDocs({\n directory: parsed.data.directory,\n });\n return NextResponse.json({\n content: docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n });\n }\n\n default:\n return NextResponse.json(\n { error: `Unknown tool: ${tool}` },\n { status: 400 },\n );\n }\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : \"Unknown error\";\n return NextResponse.json({ error: message }, { status: 500 });\n }\n}\n\nexport async function POST(req: Request) {\n const ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ?? \"unknown\";\n const { allowed, retryAfter } = rateLimit(ip);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Clone the request to read body twice if needed\n const clonedReq = req.clone();\n\n try {\n const body = await clonedReq.json();\n\n // Check if this is an MCP protocol request (has jsonrpc field)\n // or a REST API request (has tool field)\n if (\"jsonrpc\" in body) {\n // MCP protocol request - use the original request\n return handleMCPRequest(req);\n } else if (\"tool\" in body) {\n // REST API request\n return handleRESTRequest(body as ToolCallRequest);\n } else {\n return NextResponse.json(\n {\n error:\n \"Invalid request format. Expected 'jsonrpc' (MCP) or 'tool' (REST) field.\",\n },\n { status: 400 },\n );\n }\n } catch {\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n}\n\nexport async function GET() {\n // GET always returns REST API format (tools list and index status)\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: {\n ready: status.ready,\n chunkCount: status.chunkCount,\n },\n });\n}\n\nexport async function DELETE(req: Request) {\n // DELETE is only used by MCP protocol\n return handleMCPRequest(req);\n}\n";
1
+ export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleMCPRequest(req: Request, parsedBody?: unknown) {\n const transport = createTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({ directory: parsed.data.directory });\n req.signal.throwIfAborted();\n return toolResponse({\n content: docs.map((doc) => ({\n name: doc.name,\n path: doc.path,\n uri: doc.uri,\n })),\n });\n }\n\n default:\n return NextResponse.json({ error: \"Unknown tool\" }, { status: 400 });\n }\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP REST tool failed:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n\nexport async function POST(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let body: unknown;\n try {\n body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n if (Array.isArray(body) || (isRecord(body) && \"jsonrpc\" in body)) {\n const validationError = protocolToolCallError(body);\n if (validationError) return protocolError(validationError);\n return handleMCPRequest(req, body);\n }\n\n if (isRecord(body) && typeof body.tool === \"string\") {\n if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return NextResponse.json(\n { error: \"Tool arguments exceed the maximum size\" },\n { status: 413 },\n );\n }\n return handleRESTRequest(req, {\n tool: body.tool as MCPToolName,\n params: body.params ?? {},\n });\n }\n\n return NextResponse.json(\n { error: \"Invalid request format\" },\n { status: 400 },\n );\n}\n\nexport async function GET(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: { ready: status.ready, chunkCount: status.chunkCount },\n });\n}\n\nexport async function DELETE(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n return handleMCPRequest(req);\n}\n";
@@ -1,113 +1,166 @@
1
1
  export const mcpRoutesTemplate = `import { NextResponse } from "next/server";
2
- import { z } from "zod";
3
2
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
4
- import { createMCPServer } from "@/services/mcp/server";
5
3
  import {
4
+ createMCPServer,
6
5
  searchDocs,
7
- ensureDocsIndex,
8
6
  getIndexStatus,
9
7
  DOCS_TOOLS,
10
8
  listDocs,
11
9
  getDoc,
10
+ MCP_MAX_REQUEST_BYTES,
11
+ MCP_MAX_TOOL_ARGUMENT_BYTES,
12
+ searchDocsArgsSchema,
13
+ getDocArgsSchema,
14
+ listDocsArgsSchema,
15
+ serializeMCPResult,
12
16
  } from "@/services/mcp";
13
17
  import type { MCPToolName } from "@/services/mcp";
14
18
  import { rateLimit } from "@/utils/rateLimit";
19
+ import { isMcpRequestAuthorized } from "@/lib/access";
20
+ import { readJsonBody, RequestTooLargeError } from "@/utils/requestBody";
15
21
 
16
- const searchDocsSchema = z.object({
17
- query: z.string().min(1).max(2000),
18
- limit: z.number().int().min(1).max(50).optional(),
19
- });
22
+ const MAX_PROTOCOL_MESSAGES = 20;
20
23
 
21
- const getDocSchema = z.object({
22
- path: z.string().min(1).max(500),
23
- });
24
+ function isRecord(value: unknown): value is Record<string, unknown> {
25
+ return typeof value === "object" && value !== null && !Array.isArray(value);
26
+ }
27
+
28
+ function jsonByteLength(value: unknown): number {
29
+ return new TextEncoder().encode(JSON.stringify(value) ?? "null").byteLength;
30
+ }
31
+
32
+ function protocolToolCallError(body: unknown): string | null {
33
+ const messages = Array.isArray(body) ? body : [body];
34
+ if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {
35
+ return "Invalid protocol batch";
36
+ }
37
+
38
+ let toolCallCount = 0;
39
+ for (const message of messages) {
40
+ if (!isRecord(message) || message.method !== "tools/call") continue;
41
+ toolCallCount++;
42
+ if (toolCallCount > 1) {
43
+ return "Only one tools/call is allowed per request";
44
+ }
45
+ if (!isRecord(message.params) || typeof message.params.name !== "string") {
46
+ return "Invalid tool call";
47
+ }
48
+
49
+ const args = message.params.arguments ?? {};
50
+ if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {
51
+ return "Tool arguments exceed the maximum size";
52
+ }
53
+
54
+ let valid = true;
55
+ switch (message.params.name) {
56
+ case "search_docs":
57
+ valid = searchDocsArgsSchema.safeParse(args).success;
58
+ break;
59
+ case "get_doc":
60
+ valid = getDocArgsSchema.safeParse(args).success;
61
+ break;
62
+ case "list_docs":
63
+ valid = listDocsArgsSchema.safeParse(args).success;
64
+ break;
65
+ }
66
+ if (!valid) return "Invalid tool arguments";
67
+ }
68
+ return null;
69
+ }
24
70
 
25
- const listDocsSchema = z.object({
26
- directory: z.string().max(500).optional(),
27
- });
71
+ function protocolError(message: string, status = 400): Response {
72
+ return Response.json(
73
+ {
74
+ jsonrpc: "2.0",
75
+ error: { code: status === 500 ? -32603 : -32602, message },
76
+ id: null,
77
+ },
78
+ { status },
79
+ );
80
+ }
28
81
 
29
- // Create a stateless transport for serverless environment
30
82
  function createTransport() {
31
83
  return new WebStandardStreamableHTTPServerTransport({
32
- sessionIdGenerator: undefined, // Stateless mode for serverless
84
+ sessionIdGenerator: undefined,
33
85
  enableJsonResponse: true,
34
86
  });
35
87
  }
36
88
 
37
- // Handle MCP protocol requests
38
- async function handleMCPRequest(req: Request) {
89
+ async function handleMCPRequest(req: Request, parsedBody?: unknown) {
39
90
  const transport = createTransport();
40
91
  const server = createMCPServer();
92
+ let closed = false;
93
+ const close = () => {
94
+ if (closed) return;
95
+ closed = true;
96
+ void Promise.allSettled([transport.close(), server.close()]);
97
+ };
98
+ req.signal.addEventListener("abort", close, { once: true });
41
99
 
42
100
  try {
43
101
  await server.connect(transport);
44
- const response = await transport.handleRequest(req);
45
-
46
- // Clean up after response is done
47
- response
48
- .clone()
49
- .body?.pipeTo(
50
- new WritableStream({
51
- close() {
52
- transport.close();
53
- server.close();
54
- },
55
- }),
56
- )
57
- .catch(() => {});
102
+ const response = await transport.handleRequest(
103
+ req,
104
+ parsedBody === undefined ? undefined : { parsedBody },
105
+ );
58
106
 
107
+ const body = response.clone().body;
108
+ if (body) {
109
+ void body
110
+ .pipeTo(new WritableStream())
111
+ .catch(() => {})
112
+ .finally(close);
113
+ } else {
114
+ close();
115
+ }
59
116
  return response;
60
- } catch (error) {
61
- console.error("MCP request error:", error);
62
- return new Response(
63
- JSON.stringify({
64
- jsonrpc: "2.0",
65
- error: {
66
- code: -32603,
67
- message: "Internal server error",
68
- },
69
- id: null,
70
- }),
71
- {
72
- status: 500,
73
- headers: { "Content-Type": "application/json" },
74
- },
75
- );
117
+ } catch (error: unknown) {
118
+ console.error("[doccupine] MCP protocol request failed:", error);
119
+ close();
120
+ return protocolError("Internal server error", 500);
76
121
  }
77
122
  }
78
123
 
79
- // Handle REST API requests (original JSON format)
80
124
  interface ToolCallRequest {
81
125
  tool: MCPToolName;
82
- params: Record<string, unknown>;
126
+ params: unknown;
83
127
  }
84
128
 
85
- async function handleRESTRequest(body: ToolCallRequest) {
129
+ function toolResponse(value: unknown): Response {
130
+ const result = serializeMCPResult(value);
131
+ if (result.tooLarge) {
132
+ return NextResponse.json(
133
+ { error: "Tool result exceeds the maximum response size" },
134
+ { status: 413 },
135
+ );
136
+ }
137
+ return new Response(result.text, {
138
+ headers: {
139
+ "Content-Type": "application/json; charset=utf-8",
140
+ "Cache-Control": "no-store",
141
+ },
142
+ });
143
+ }
144
+
145
+ async function handleRESTRequest(req: Request, body: ToolCallRequest) {
86
146
  try {
87
147
  const { tool, params } = body;
88
148
 
89
- if (!tool) {
90
- return NextResponse.json(
91
- { error: "Missing 'tool' parameter" },
92
- { status: 400 },
93
- );
94
- }
95
-
96
149
  switch (tool) {
97
150
  case "search_docs": {
98
- const parsed = searchDocsSchema.safeParse(params);
151
+ const parsed = searchDocsArgsSchema.safeParse(params);
99
152
  if (!parsed.success) {
100
153
  return NextResponse.json(
101
- { error: "Invalid params", details: parsed.error.issues },
154
+ { error: "Invalid params" },
102
155
  { status: 400 },
103
156
  );
104
157
  }
105
- await ensureDocsIndex();
106
158
  const results = await searchDocs(
107
159
  parsed.data.query,
108
160
  parsed.data.limit ?? 6,
161
+ req.signal,
109
162
  );
110
- return NextResponse.json({
163
+ return toolResponse({
111
164
  content: results.map(({ chunk, score }) => ({
112
165
  path: chunk.path,
113
166
  uri: chunk.uri,
@@ -118,59 +171,63 @@ async function handleRESTRequest(body: ToolCallRequest) {
118
171
  }
119
172
 
120
173
  case "get_doc": {
121
- const parsed = getDocSchema.safeParse(params);
174
+ const parsed = getDocArgsSchema.safeParse(params);
122
175
  if (!parsed.success) {
123
176
  return NextResponse.json(
124
- { error: "Invalid params", details: parsed.error.issues },
177
+ { error: "Invalid params" },
125
178
  { status: 400 },
126
179
  );
127
180
  }
181
+ req.signal.throwIfAborted();
128
182
  const doc = await getDoc({ path: parsed.data.path });
183
+ req.signal.throwIfAborted();
129
184
  if (!doc) {
130
185
  return NextResponse.json(
131
186
  { error: "Document not found" },
132
187
  { status: 404 },
133
188
  );
134
189
  }
135
- return NextResponse.json({ content: doc });
190
+ return toolResponse({ content: doc });
136
191
  }
137
192
 
138
193
  case "list_docs": {
139
- const parsed = listDocsSchema.safeParse(params);
194
+ const parsed = listDocsArgsSchema.safeParse(params);
140
195
  if (!parsed.success) {
141
196
  return NextResponse.json(
142
- { error: "Invalid params", details: parsed.error.issues },
197
+ { error: "Invalid params" },
143
198
  { status: 400 },
144
199
  );
145
200
  }
146
- const docs = await listDocs({
147
- directory: parsed.data.directory,
148
- });
149
- return NextResponse.json({
150
- content: docs.map((d) => ({
151
- name: d.name,
152
- path: d.path,
153
- uri: d.uri,
201
+ req.signal.throwIfAborted();
202
+ const docs = await listDocs({ directory: parsed.data.directory });
203
+ req.signal.throwIfAborted();
204
+ return toolResponse({
205
+ content: docs.map((doc) => ({
206
+ name: doc.name,
207
+ path: doc.path,
208
+ uri: doc.uri,
154
209
  })),
155
210
  });
156
211
  }
157
212
 
158
213
  default:
159
- return NextResponse.json(
160
- { error: \`Unknown tool: \${tool}\` },
161
- { status: 400 },
162
- );
214
+ return NextResponse.json({ error: "Unknown tool" }, { status: 400 });
163
215
  }
164
- } catch (e: unknown) {
165
- const message = e instanceof Error ? e.message : "Unknown error";
166
- return NextResponse.json({ error: message }, { status: 500 });
216
+ } catch (error: unknown) {
217
+ console.error("[doccupine] MCP REST tool failed:", error);
218
+ return NextResponse.json(
219
+ { error: "Internal server error" },
220
+ { status: 500 },
221
+ );
167
222
  }
168
223
  }
169
224
 
170
225
  export async function POST(req: Request) {
171
- const ip =
172
- req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
173
- const { allowed, retryAfter } = rateLimit(ip);
226
+ if (!(await isMcpRequestAuthorized(req))) {
227
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
228
+ }
229
+
230
+ const { allowed, retryAfter } = rateLimit(req);
174
231
  if (!allowed) {
175
232
  return NextResponse.json(
176
233
  { error: "Too many requests" },
@@ -178,48 +235,61 @@ export async function POST(req: Request) {
178
235
  );
179
236
  }
180
237
 
181
- // Clone the request to read body twice if needed
182
- const clonedReq = req.clone();
183
-
238
+ let body: unknown;
184
239
  try {
185
- const body = await clonedReq.json();
186
-
187
- // Check if this is an MCP protocol request (has jsonrpc field)
188
- // or a REST API request (has tool field)
189
- if ("jsonrpc" in body) {
190
- // MCP protocol request - use the original request
191
- return handleMCPRequest(req);
192
- } else if ("tool" in body) {
193
- // REST API request
194
- return handleRESTRequest(body as ToolCallRequest);
195
- } else {
240
+ body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);
241
+ } catch (error: unknown) {
242
+ if (req.signal.aborted) throw error;
243
+ if (error instanceof RequestTooLargeError) {
196
244
  return NextResponse.json(
197
- {
198
- error:
199
- "Invalid request format. Expected 'jsonrpc' (MCP) or 'tool' (REST) field.",
200
- },
201
- { status: 400 },
245
+ { error: "Request body too large" },
246
+ { status: 413 },
202
247
  );
203
248
  }
204
- } catch {
205
249
  return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
206
250
  }
251
+
252
+ if (Array.isArray(body) || (isRecord(body) && "jsonrpc" in body)) {
253
+ const validationError = protocolToolCallError(body);
254
+ if (validationError) return protocolError(validationError);
255
+ return handleMCPRequest(req, body);
256
+ }
257
+
258
+ if (isRecord(body) && typeof body.tool === "string") {
259
+ if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {
260
+ return NextResponse.json(
261
+ { error: "Tool arguments exceed the maximum size" },
262
+ { status: 413 },
263
+ );
264
+ }
265
+ return handleRESTRequest(req, {
266
+ tool: body.tool as MCPToolName,
267
+ params: body.params ?? {},
268
+ });
269
+ }
270
+
271
+ return NextResponse.json(
272
+ { error: "Invalid request format" },
273
+ { status: 400 },
274
+ );
207
275
  }
208
276
 
209
- export async function GET() {
210
- // GET always returns REST API format (tools list and index status)
277
+ export async function GET(req: Request) {
278
+ if (!(await isMcpRequestAuthorized(req))) {
279
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
280
+ }
281
+
211
282
  const status = getIndexStatus();
212
283
  return NextResponse.json({
213
284
  tools: DOCS_TOOLS,
214
- index: {
215
- ready: status.ready,
216
- chunkCount: status.chunkCount,
217
- },
285
+ index: { ready: status.ready, chunkCount: status.chunkCount },
218
286
  });
219
287
  }
220
288
 
221
289
  export async function DELETE(req: Request) {
222
- // DELETE is only used by MCP protocol
290
+ if (!(await isMcpRequestAuthorized(req))) {
291
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
292
+ }
223
293
  return handleMCPRequest(req);
224
294
  }
225
295
  `;
@@ -1 +1 @@
1
- export declare const playgroundRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { matchAllowlist } from \"@/utils/playgroundAllowlist\";\nimport { guardedFetch, BlockedError } from \"@/utils/ssrfGuard\";\n\n// The playground proxy runs server-side so it can call APIs that block\n// cross-origin browser requests. It is NOT an open forward proxy: every target\n// is gated by the build-time allowlist (derived from the OpenAPI servers) and\n// then re-validated against private/metadata IP ranges before any socket opens.\nexport const runtime = \"nodejs\";\nexport const maxDuration = 40;\n\nconst MAX_REQUEST_BYTES = 1_000_000;\nconst MAX_RESPONSE_BYTES = 5_000_000;\nconst TIMEOUT_MS = 30_000;\n\nconst envelopeSchema = z.object({\n targetUrl: z.string().url().max(4096),\n method: z.enum([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"]),\n headers: z.record(z.string().max(256), z.string().max(8192)).optional(),\n body: z.string().max(MAX_REQUEST_BYTES).optional(),\n bodyEncoding: z.enum([\"utf8\", \"base64\"]).optional(),\n});\n\n// Headers we never forward upstream: hop-by-hop, or identity/cookie headers\n// that would either leak the docs origin or be set incorrectly.\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"cookie\",\n \"origin\",\n \"referer\",\n \"forwarded\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n]);\n\n// The only response headers echoed back to the client. Notably excludes\n// set-cookie, authorization, and www-authenticate.\nconst SAFE_RESPONSE_HEADERS = new Set([\n \"content-type\",\n \"content-length\",\n \"content-language\",\n \"content-disposition\",\n \"cache-control\",\n \"etag\",\n \"last-modified\",\n \"date\",\n \"location\",\n \"retry-after\",\n]);\n\nfunction hasControlChars(value: string): boolean {\n return (\n value.includes(String.fromCharCode(10)) ||\n value.includes(String.fromCharCode(13))\n );\n}\n\nfunction isTextContentType(contentType: string | null): boolean {\n if (!contentType) return false;\n const t = contentType.toLowerCase();\n return (\n t.startsWith(\"text/\") ||\n t.includes(\"json\") ||\n t.includes(\"xml\") ||\n t.includes(\"javascript\") ||\n t.includes(\"x-www-form-urlencoded\") ||\n t.includes(\"csv\")\n );\n}\n\nexport async function POST(req: Request) {\n const ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ?? \"unknown\";\n const { allowed, retryAfter } = rateLimit(ip);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = envelopeSchema.safeParse(raw);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid request\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const { targetUrl, method, headers = {}, body, bodyEncoding } = parsed.data;\n\n const entry = matchAllowlist(targetUrl);\n if (!entry) {\n console.warn(\"[playground] blocked: non-allowlisted target\");\n return NextResponse.json(\n { error: \"This request target is not allowed by the API reference.\" },\n { status: 403 },\n );\n }\n\n if (Object.keys(headers).length > 50) {\n return NextResponse.json({ error: \"Too many headers\" }, { status: 400 });\n }\n\n const outboundHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n const lower = key.toLowerCase();\n if (BLOCKED_REQUEST_HEADERS.has(lower)) continue;\n if (hasControlChars(key) || hasControlChars(value)) continue;\n outboundHeaders[key] = value;\n }\n outboundHeaders[\"user-agent\"] =\n outboundHeaders[\"user-agent\"] ?? \"Doccupine-API-Playground\";\n // Ask for an unencoded body so the response byte cap is measured accurately.\n outboundHeaders[\"accept-encoding\"] = \"identity\";\n\n let bodyBuffer: Buffer | undefined;\n if (body !== undefined && method !== \"GET\" && method !== \"HEAD\") {\n bodyBuffer = Buffer.from(\n body,\n bodyEncoding === \"base64\" ? \"base64\" : \"utf8\",\n );\n }\n\n try {\n const result = await guardedFetch(targetUrl, entry, {\n method,\n headers: outboundHeaders,\n body: bodyBuffer,\n timeoutMs: TIMEOUT_MS,\n maxBytes: MAX_RESPONSE_BYTES,\n });\n\n const safeHeaders: Record<string, string> = {};\n let contentType: string | null = null;\n for (const [key, value] of Object.entries(result.headers)) {\n if (key === \"content-type\") contentType = value;\n if (SAFE_RESPONSE_HEADERS.has(key)) safeHeaders[key] = value;\n }\n\n const isText = isTextContentType(contentType);\n\n // Deliberately do NOT log the request/response here: the full URL (path and\n // query) and headers can carry reader secrets. Only blocked/failed attempts\n // are logged below via console.warn, and those record no sensitive values.\n return NextResponse.json({\n status: result.status,\n statusText: result.statusText,\n headers: safeHeaders,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: result.body.toString(isText ? \"utf8\" : \"base64\"),\n truncated: result.truncated,\n byteLength: result.body.length,\n durationMs: result.durationMs,\n });\n } catch (error) {\n if (error instanceof BlockedError) {\n console.warn(\"[playground] \" + error.reason);\n return NextResponse.json(\n { error: \"This request target is not allowed.\" },\n { status: 403 },\n );\n }\n const message = error instanceof Error ? error.message : \"\";\n if (message === \"timeout\") {\n console.warn(\"[playground] upstream timeout\");\n return NextResponse.json(\n { error: \"The upstream request timed out.\" },\n { status: 504 },\n );\n }\n console.warn(\"[playground] upstream request failed\");\n return NextResponse.json(\n { error: \"The upstream request failed.\" },\n { status: 502 },\n );\n }\n}\n";
1
+ export declare const playgroundRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { matchAllowlist } from \"@/utils/playgroundAllowlist\";\nimport { guardedFetch, BlockedError } from \"@/utils/ssrfGuard\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// The playground proxy runs server-side so it can call APIs that block\n// cross-origin browser requests. It is NOT an open forward proxy: every target\n// is gated by the build-time allowlist (derived from the OpenAPI servers) and\n// then re-validated against private/metadata IP ranges before any socket opens.\nexport const runtime = \"nodejs\";\nexport const maxDuration = 40;\n\nconst MAX_ENVELOPE_BYTES = 1_500_000;\nconst MAX_REQUEST_BODY_BYTES = 1_000_000;\nconst MAX_RESPONSE_BYTES = 5_000_000;\nconst TIMEOUT_MS = 30_000;\n\nconst envelopeSchema = z.object({\n targetUrl: z.string().url().max(4096),\n method: z.enum([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"]),\n headers: z.record(z.string().max(256), z.string().max(8192)).optional(),\n body: z.string().optional(),\n bodyEncoding: z.enum([\"utf8\", \"base64\"]).optional(),\n});\n\n// Headers we never forward upstream: hop-by-hop, or identity/cookie headers\n// that would either leak the docs origin or be set incorrectly.\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"cookie\",\n \"origin\",\n \"referer\",\n \"forwarded\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n]);\n\n// The only response headers echoed back to the client. Notably excludes\n// set-cookie, authorization, and www-authenticate.\nconst SAFE_RESPONSE_HEADERS = new Set([\n \"content-type\",\n \"content-length\",\n \"content-language\",\n \"content-disposition\",\n \"cache-control\",\n \"etag\",\n \"last-modified\",\n \"date\",\n \"location\",\n \"retry-after\",\n]);\n\nfunction hasControlChars(value: string): boolean {\n return (\n value.includes(String.fromCharCode(10)) ||\n value.includes(String.fromCharCode(13))\n );\n}\n\nfunction decodePlaygroundBody(\n body: string,\n encoding: \"utf8\" | \"base64\" | undefined,\n): Buffer {\n const decoded = Buffer.from(body, encoding === \"base64\" ? \"base64\" : \"utf8\");\n if (decoded.byteLength > MAX_REQUEST_BODY_BYTES) {\n throw new RequestTooLargeError();\n }\n return decoded;\n}\n\nfunction isTextContentType(contentType: string | null): boolean {\n if (!contentType) return false;\n const t = contentType.toLowerCase();\n return (\n t.startsWith(\"text/\") ||\n t.includes(\"json\") ||\n t.includes(\"xml\") ||\n t.includes(\"javascript\") ||\n t.includes(\"x-www-form-urlencoded\") ||\n t.includes(\"csv\")\n );\n}\n\nexport async function POST(req: Request) {\n if (!(await isSiteRequestAuthorized())) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let raw: unknown;\n try {\n raw = await readJsonBody(req, MAX_ENVELOPE_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = envelopeSchema.safeParse(raw);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid request\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const { targetUrl, method, headers = {}, body, bodyEncoding } = parsed.data;\n\n const entry = matchAllowlist(targetUrl);\n if (!entry) {\n console.warn(\"[playground] blocked: non-allowlisted target\");\n return NextResponse.json(\n { error: \"This request target is not allowed by the API reference.\" },\n { status: 403 },\n );\n }\n\n if (Object.keys(headers).length > 50) {\n return NextResponse.json({ error: \"Too many headers\" }, { status: 400 });\n }\n\n const outboundHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n const lower = key.toLowerCase();\n if (BLOCKED_REQUEST_HEADERS.has(lower)) continue;\n if (hasControlChars(key) || hasControlChars(value)) continue;\n outboundHeaders[key] = value;\n }\n outboundHeaders[\"user-agent\"] =\n outboundHeaders[\"user-agent\"] ?? \"Doccupine-API-Playground\";\n // Ask for an unencoded body so the response byte cap is measured accurately.\n outboundHeaders[\"accept-encoding\"] = \"identity\";\n\n let decodedBody: Buffer | undefined;\n try {\n if (body !== undefined) {\n decodedBody = decodePlaygroundBody(body, bodyEncoding);\n }\n } catch (error: unknown) {\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request payload too large\" },\n { status: 413 },\n );\n }\n throw error;\n }\n const bodyBuffer =\n method !== \"GET\" && method !== \"HEAD\" ? decodedBody : undefined;\n\n try {\n const result = await guardedFetch(targetUrl, entry, {\n method,\n headers: outboundHeaders,\n body: bodyBuffer,\n timeoutMs: TIMEOUT_MS,\n maxBytes: MAX_RESPONSE_BYTES,\n });\n\n const safeHeaders: Record<string, string> = {};\n let contentType: string | null = null;\n for (const [key, value] of Object.entries(result.headers)) {\n if (key === \"content-type\") contentType = value;\n if (SAFE_RESPONSE_HEADERS.has(key)) safeHeaders[key] = value;\n }\n\n const isText = isTextContentType(contentType);\n\n // Deliberately do NOT log the request/response here: the full URL (path and\n // query) and headers can carry reader secrets. Only blocked/failed attempts\n // are logged below via console.warn, and those record no sensitive values.\n return NextResponse.json({\n status: result.status,\n statusText: result.statusText,\n headers: safeHeaders,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: result.body.toString(isText ? \"utf8\" : \"base64\"),\n truncated: result.truncated,\n byteLength: result.body.length,\n durationMs: result.durationMs,\n });\n } catch (error) {\n if (error instanceof BlockedError) {\n console.warn(\"[playground] \" + error.reason);\n return NextResponse.json(\n { error: \"This request target is not allowed.\" },\n { status: 403 },\n );\n }\n const message = error instanceof Error ? error.message : \"\";\n if (message === \"timeout\") {\n console.warn(\"[playground] upstream timeout\");\n return NextResponse.json(\n { error: \"The upstream request timed out.\" },\n { status: 504 },\n );\n }\n console.warn(\"[playground] upstream request failed\");\n return NextResponse.json(\n { error: \"The upstream request failed.\" },\n { status: 502 },\n );\n }\n}\n";
@@ -3,6 +3,8 @@ import { z } from "zod";
3
3
  import { rateLimit } from "@/utils/rateLimit";
4
4
  import { matchAllowlist } from "@/utils/playgroundAllowlist";
5
5
  import { guardedFetch, BlockedError } from "@/utils/ssrfGuard";
6
+ import { isSiteRequestAuthorized } from "@/lib/access";
7
+ import { readJsonBody, RequestTooLargeError } from "@/utils/requestBody";
6
8
 
7
9
  // The playground proxy runs server-side so it can call APIs that block
8
10
  // cross-origin browser requests. It is NOT an open forward proxy: every target
@@ -11,7 +13,8 @@ import { guardedFetch, BlockedError } from "@/utils/ssrfGuard";
11
13
  export const runtime = "nodejs";
12
14
  export const maxDuration = 40;
13
15
 
14
- const MAX_REQUEST_BYTES = 1_000_000;
16
+ const MAX_ENVELOPE_BYTES = 1_500_000;
17
+ const MAX_REQUEST_BODY_BYTES = 1_000_000;
15
18
  const MAX_RESPONSE_BYTES = 5_000_000;
16
19
  const TIMEOUT_MS = 30_000;
17
20
 
@@ -19,7 +22,7 @@ const envelopeSchema = z.object({
19
22
  targetUrl: z.string().url().max(4096),
20
23
  method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]),
21
24
  headers: z.record(z.string().max(256), z.string().max(8192)).optional(),
22
- body: z.string().max(MAX_REQUEST_BYTES).optional(),
25
+ body: z.string().optional(),
23
26
  bodyEncoding: z.enum(["utf8", "base64"]).optional(),
24
27
  });
25
28
 
@@ -67,6 +70,17 @@ function hasControlChars(value: string): boolean {
67
70
  );
68
71
  }
69
72
 
73
+ function decodePlaygroundBody(
74
+ body: string,
75
+ encoding: "utf8" | "base64" | undefined,
76
+ ): Buffer {
77
+ const decoded = Buffer.from(body, encoding === "base64" ? "base64" : "utf8");
78
+ if (decoded.byteLength > MAX_REQUEST_BODY_BYTES) {
79
+ throw new RequestTooLargeError();
80
+ }
81
+ return decoded;
82
+ }
83
+
70
84
  function isTextContentType(contentType: string | null): boolean {
71
85
  if (!contentType) return false;
72
86
  const t = contentType.toLowerCase();
@@ -81,9 +95,11 @@ function isTextContentType(contentType: string | null): boolean {
81
95
  }
82
96
 
83
97
  export async function POST(req: Request) {
84
- const ip =
85
- req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
86
- const { allowed, retryAfter } = rateLimit(ip);
98
+ if (!(await isSiteRequestAuthorized())) {
99
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
100
+ }
101
+
102
+ const { allowed, retryAfter } = rateLimit(req);
87
103
  if (!allowed) {
88
104
  return NextResponse.json(
89
105
  { error: "Too many requests" },
@@ -93,8 +109,15 @@ export async function POST(req: Request) {
93
109
 
94
110
  let raw: unknown;
95
111
  try {
96
- raw = await req.json();
97
- } catch {
112
+ raw = await readJsonBody(req, MAX_ENVELOPE_BYTES);
113
+ } catch (error: unknown) {
114
+ if (req.signal.aborted) throw error;
115
+ if (error instanceof RequestTooLargeError) {
116
+ return NextResponse.json(
117
+ { error: "Request body too large" },
118
+ { status: 413 },
119
+ );
120
+ }
98
121
  return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
99
122
  }
100
123
 
@@ -133,13 +156,22 @@ export async function POST(req: Request) {
133
156
  // Ask for an unencoded body so the response byte cap is measured accurately.
134
157
  outboundHeaders["accept-encoding"] = "identity";
135
158
 
136
- let bodyBuffer: Buffer | undefined;
137
- if (body !== undefined && method !== "GET" && method !== "HEAD") {
138
- bodyBuffer = Buffer.from(
139
- body,
140
- bodyEncoding === "base64" ? "base64" : "utf8",
141
- );
159
+ let decodedBody: Buffer | undefined;
160
+ try {
161
+ if (body !== undefined) {
162
+ decodedBody = decodePlaygroundBody(body, bodyEncoding);
163
+ }
164
+ } catch (error: unknown) {
165
+ if (error instanceof RequestTooLargeError) {
166
+ return NextResponse.json(
167
+ { error: "Request payload too large" },
168
+ { status: 413 },
169
+ );
170
+ }
171
+ throw error;
142
172
  }
173
+ const bodyBuffer =
174
+ method !== "GET" && method !== "HEAD" ? decodedBody : undefined;
143
175
 
144
176
  try {
145
177
  const result = await guardedFetch(targetUrl, entry, {