doccupine 0.0.139 → 0.0.141
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/README.md +14 -7
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +191 -0
- package/dist/index.d.ts +3 -7
- package/dist/index.js +5 -1895
- package/dist/lib/config-manager.d.ts +1 -0
- package/dist/lib/config-manager.js +63 -3
- package/dist/lib/generated-artifacts.d.ts +26 -0
- package/dist/lib/generated-artifacts.js +147 -0
- package/dist/lib/layout.js +30 -30
- package/dist/lib/metadata.js +58 -30
- package/dist/lib/openapi-types.d.ts +2 -2
- package/dist/lib/openapi.d.ts +6 -3
- package/dist/lib/openapi.js +330 -50
- package/dist/lib/output-safety.d.ts +15 -0
- package/dist/lib/output-safety.js +428 -0
- package/dist/lib/structures.js +11 -0
- package/dist/lib/utils.d.ts +18 -0
- package/dist/lib/utils.js +125 -0
- package/dist/mdx-to-nextjs-generator.d.ts +166 -0
- package/dist/mdx-to-nextjs-generator.js +2229 -0
- package/dist/templates/app/api/gate/route.d.ts +1 -1
- package/dist/templates/app/api/gate/route.js +18 -6
- package/dist/templates/app/api/mcp/route.d.ts +1 -1
- package/dist/templates/app/api/mcp/route.js +181 -111
- package/dist/templates/app/api/playground/route.d.ts +1 -1
- package/dist/templates/app/api/playground/route.js +45 -13
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +102 -25
- package/dist/templates/app/api/search/route.d.ts +1 -1
- package/dist/templates/app/api/search/route.js +5 -0
- package/dist/templates/app/robots.d.ts +1 -1
- package/dist/templates/app/robots.js +1 -26
- package/dist/templates/app/theme.d.ts +1 -1
- package/dist/templates/app/theme.js +31 -19
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +411 -104
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +56 -13
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +63 -11
- package/dist/templates/components/SearchModalContent.d.ts +1 -1
- package/dist/templates/components/SearchModalContent.js +191 -49
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +8 -2
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +26 -3
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +4 -7
- package/dist/templates/components/layout/Badge.d.ts +1 -1
- package/dist/templates/components/layout/Badge.js +1 -1
- package/dist/templates/components/layout/Button.d.ts +1 -1
- package/dist/templates/components/layout/Button.js +4 -4
- package/dist/templates/components/layout/Callout.d.ts +1 -1
- package/dist/templates/components/layout/Callout.js +6 -6
- package/dist/templates/components/layout/Card.d.ts +1 -1
- package/dist/templates/components/layout/Card.js +9 -4
- package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
- package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
- package/dist/templates/components/layout/Code.d.ts +1 -1
- package/dist/templates/components/layout/Code.js +5 -5
- package/dist/templates/components/layout/CopyButton.d.ts +1 -1
- package/dist/templates/components/layout/CopyButton.js +1 -1
- package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
- package/dist/templates/components/layout/DemoTheme.js +8 -28
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +57 -18
- package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
- package/dist/templates/components/layout/GlobalStyles.js +15 -9
- package/dist/templates/components/layout/Prompt.d.ts +1 -1
- package/dist/templates/components/layout/Prompt.js +4 -7
- package/dist/templates/components/layout/Steps.d.ts +1 -1
- package/dist/templates/components/layout/Steps.js +7 -1
- package/dist/templates/components/layout/Tabs.d.ts +1 -1
- package/dist/templates/components/layout/Tabs.js +108 -19
- package/dist/templates/env.example.d.ts +1 -1
- package/dist/templates/env.example.js +11 -0
- package/dist/templates/eslint.config.d.ts +1 -1
- package/dist/templates/eslint.config.js +20 -0
- package/dist/templates/gitignore.d.ts +1 -1
- package/dist/templates/gitignore.js +4 -3
- package/dist/templates/lib/access.d.ts +1 -0
- package/dist/templates/lib/access.js +41 -0
- package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +5 -3
- package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
- package/dist/templates/mdx/authentication.mdx.js +5 -3
- package/dist/templates/mdx/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +20 -6
- package/dist/templates/mdx/components.mdx.d.ts +1 -1
- package/dist/templates/mdx/components.mdx.js +3 -0
- package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
- package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
- package/dist/templates/mdx/globals.mdx.d.ts +1 -1
- package/dist/templates/mdx/globals.mdx.js +14 -11
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
- package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
- package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
- package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
- package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
- package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/index.mdx.js +1 -0
- package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
- package/dist/templates/mdx/sections.mdx.d.ts +1 -1
- package/dist/templates/mdx/sections.mdx.js +4 -0
- package/dist/templates/mdx/space.mdx.d.ts +1 -0
- package/dist/templates/mdx/space.mdx.js +125 -0
- package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
- package/dist/templates/mdx/tabs.mdx.js +4 -0
- package/dist/templates/next.config.js +20 -8
- package/dist/templates/package.js +3 -3
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +1 -0
- package/dist/templates/proxy.js +47 -19
- package/dist/templates/scripts/build-docs-index.d.ts +1 -1
- package/dist/templates/scripts/build-docs-index.js +1 -0
- package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
- package/dist/templates/services/mcp/docsContentStub.js +1 -0
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +140 -83
- package/dist/templates/services/mcp/tools.d.ts +1 -1
- package/dist/templates/services/mcp/tools.js +65 -137
- package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
- package/dist/templates/utils/playgroundAllowlist.js +13 -4
- package/dist/templates/utils/rateLimit.d.ts +1 -1
- package/dist/templates/utils/rateLimit.js +40 -3
- package/dist/templates/utils/requestBody.d.ts +1 -0
- package/dist/templates/utils/requestBody.js +56 -0
- package/dist/templates/utils/ssrfGuard.d.ts +1 -1
- package/dist/templates/utils/ssrfGuard.js +138 -33
- package/package.json +14 -9
- package/dist/lib/mdxToMarkdown.d.ts +0 -1
- package/dist/lib/mdxToMarkdown.js +0 -134
- package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
- 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 //
|
|
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
|
-
//
|
|
13
|
-
const
|
|
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
|
-
|
|
26
|
-
|
|
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 {
|
|
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
|
|
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
|
-
|
|
22
|
-
|
|
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
|
-
|
|
26
|
-
|
|
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,
|
|
84
|
+
sessionIdGenerator: undefined,
|
|
33
85
|
enableJsonResponse: true,
|
|
34
86
|
});
|
|
35
87
|
}
|
|
36
88
|
|
|
37
|
-
|
|
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(
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
|
62
|
-
|
|
63
|
-
|
|
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:
|
|
126
|
+
params: unknown;
|
|
83
127
|
}
|
|
84
128
|
|
|
85
|
-
|
|
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 =
|
|
151
|
+
const parsed = searchDocsArgsSchema.safeParse(params);
|
|
99
152
|
if (!parsed.success) {
|
|
100
153
|
return NextResponse.json(
|
|
101
|
-
{ error: "Invalid params"
|
|
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
|
|
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 =
|
|
174
|
+
const parsed = getDocArgsSchema.safeParse(params);
|
|
122
175
|
if (!parsed.success) {
|
|
123
176
|
return NextResponse.json(
|
|
124
|
-
{ error: "Invalid params"
|
|
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
|
|
190
|
+
return toolResponse({ content: doc });
|
|
136
191
|
}
|
|
137
192
|
|
|
138
193
|
case "list_docs": {
|
|
139
|
-
const parsed =
|
|
194
|
+
const parsed = listDocsArgsSchema.safeParse(params);
|
|
140
195
|
if (!parsed.success) {
|
|
141
196
|
return NextResponse.json(
|
|
142
|
-
{ error: "Invalid params"
|
|
197
|
+
{ error: "Invalid params" },
|
|
143
198
|
{ status: 400 },
|
|
144
199
|
);
|
|
145
200
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
return
|
|
150
|
-
content: docs.map((
|
|
151
|
-
name:
|
|
152
|
-
path:
|
|
153
|
-
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 (
|
|
165
|
-
|
|
166
|
-
return NextResponse.json(
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
182
|
-
const clonedReq = req.clone();
|
|
183
|
-
|
|
238
|
+
let body: unknown;
|
|
184
239
|
try {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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().
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
|
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
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
body,
|
|
140
|
-
|
|
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, {
|