API 路由

本页内容

插件可以为管理界面与外部集成暴露 API 路由。路由挂载在 /_emdash/api/plugins/<slug>/<route-name> 下(<slug> 是 emdash-plugin.jsonc 中插件的 slug 字段——运行时以 ctx.plugin.id 暴露),并在沙箱运行时中执行,使用与 hooks 相同的 PluginContext。

本页介绍沙箱插件。原生插件使用相同的路由选项、认证与 URL 布局,但其处理函数接收一个合并的上下文对象。该签名见 Your first native plugin。

定义路由

在 src/plugin.ts 的默认导出中声明路由。当路由校验输入或作为 MCP 工具暴露时,将 zod 添加为运行时依赖:

pnpm add zod

以下示例校验提交请求并查询插件存储:

import type { SandboxedPlugin } from "emdash/plugin";
import { z } from "zod";

const submissionsInput = z.object({
	formId: z.string().optional(),
	limit: z.coerce.number().int().min(1).max(100).default(50),
	cursor: z.string().optional(),
});

const plugin: SandboxedPlugin = {
	routes: {
		status: {
			handler: async (_routeCtx, ctx) => {
				return { ok: true, plugin: ctx.plugin.id };
			},
		},

		submissions: {
			handler: async (routeCtx, ctx) => {
				const parsed = submissionsInput.safeParse(routeCtx.input);
				if (!parsed.success) {
					return { ok: false, error: { code: "VALIDATION_ERROR" } };
				}
				const { formId, limit, cursor } = parsed.data;

				const result = await ctx.storage.submissions.query({
					where: formId ? { formId } : undefined,
					orderBy: { createdAt: "desc" },
					limit,
					cursor,
				});

				return { ok: true, ...result };
			},
		},
	},
};

export default plugin;

SandboxedPlugin 注解会推断路由与插件上下文类型,因此参数无需注解。沙箱路由处理函数接受 两个参数:(routeCtx, ctx)。

  • routeCtx 携带请求形态的数据:{ input, request, requestMeta }。其 input 仍为 unknown,使用前请校验。
  • ctx 与 hooks 中得到的 PluginContext 相同——ctx.storage、ctx.settings、ctx.kv、ctx.content、ctx.http 和 ctx.log。

过滤已索引的内容字段

具有 content:read 能力的插件可以过滤 collection 标记为 indexed 的自定义字段。 过滤器在数据库中运行,并以 AND 语义组合:

const result = await ctx.content.list("items", {
	where: {
		fieldFilters: {
			priority: { in: ["urgent", "high"] },
			score: { gte: 80 },
			resolved: false,
		},
	},
});

标量值使用精确匹配。使用 null 进行空值匹配,使用 { in: [...] } 匹配一组精确值, 或使用 gt、gte、lt 和 lte 进行范围比较。EmDash 会拒绝未索引字段的过滤器、 与字段类型不匹配的值,以及每次查询超过 20 个字段过滤器。in 过滤器最多接受 50 个值, 且所有精确值、范围边界与 in 成员合计每次查询有 50 个操作数预算。空值匹配不消耗该预算。

路由 URL

路由挂载在 /_emdash/api/plugins/<slug>/<route-name>。路由名称可包含斜杠以表示嵌套路径。

Plugin idRoute nameURL
formsstatus/_emdash/api/plugins/forms/status
formssubmissions/_emdash/api/plugins/forms/submissions
seosettings/save/_emdash/api/plugins/seo/settings/save
analyticsevents/recent/_emdash/api/plugins/analytics/events/recent

认证与 CSRF

插件路由默认需要认证。 调度器在调用你的处理函数之前要求会话(或带有 admin 作用域的令牌)。私有路由默认使用 plugins:manage 权限以保持向后兼容。当操作属于现有的内容、媒体、schema 或设置能力时,将 permission 设为更窄的 EmDash RBAC 权限:

routes: {
	create: {
		permission: "content:create",
		handler: async (routeCtx, ctx) => {
			// Validate routeCtx.input, then create content through ctx.
		},
	},
},

私有路由对每个 HTTP 方法都要求其声明的权限。它们还要求 cookie 认证请求携带 CSRF 头 X-EmDash-Request: 1,包括 GET 和 HEAD,因为插件路由可以对任何方法运行同一处理函数。管理界面会自动发送该头。令牌认证请求免于该头,但仍需要 admin 令牌作用域与路由权限。

若要将路由退出认证,将其标记为 public: true:

routes: {
	track: {
		public: true,
		handler: async (routeCtx, ctx) => {
			const parsed = z.object({ event: z.string() }).safeParse(routeCtx.input);
			if (!parsed.success) return { ok: false, error: "INVALID_EVENT" };
			ctx.log.info("Tracked", { event: parsed.data.event });
			return { ok: true };
		},
	},
},

公开路由的暴露属于插件经审核的访问范围。安装带有公开路由的插件需要同意。添加公开路由,或将私有路由改为公开,在更新插件时需要再次同意。

已认证的调用者

在私有路由上,routeCtx.user 是发起请求的已认证用户——由 EmDash 在你的处理函数运行前解析并授权,因此你可以信任它用于按用户逻辑(按用户 API 密钥、OAuth 连接、插件管理的偏好):

routes: {
	"connect/start": {
		handler: async (routeCtx, ctx) => {
			// Never read the acting user from the request body — any authenticated
			// session could impersonate another user that way. Use routeCtx.user.
			const caller = routeCtx.user;
			if (!caller) throw new Error("No caller bound");
			await ctx.kv.set(`user:${caller.id}:connection`, { startedAt: Date.now() });
			return { userId: caller.id };
		},
	},
},

在公开路由上 routeCtx.user 为 undefined(它们跳过认证,因此没有绑定调用者——即使访问者恰好有管理会话),在令牌未绑定到用户的令牌认证请求(机器令牌)上也是如此。形状与 ctx.users 返回的 UserInfo 一致:{ id, email, name, role, createdAt }——不含敏感字段。

注意调用者身份与 users:read 能力是分开的:routeCtx.user 告诉你 谁在调用,在私有路由上始终可用;而 ctx.users 是需要该能力的用户目录 查找。

将路由暴露为 MCP 工具

插件可通过 EmDash 的 MCP 服务器显式暴露选定的私有路由。MCP 暴露绝不会从路由列表推断:

const createEventInput = z.object({
	title: z.string().min(1),
	startsAt: z.string().datetime(),
});

const plugin: SandboxedPlugin = {
	routes: {
		"events/create": {
			permission: "content:create",
			handler: async (routeCtx, ctx) => {
				const parsed = createEventInput.safeParse(routeCtx.input);
				if (!parsed.success) return { ok: false, error: "INVALID_EVENT" };
				const input = parsed.data;
				return { id: await createEvent(input, ctx) };
			},
		},
	},
	mcp: {
		tools: {
			createEvent: {
				description: "Create a calendar event when the user asks to add one.",
				route: "events/create",
				input: createEventInput,
				output: z.object({ id: z.string() }),
				destructive: false,
			},
		},
	},
};

export default plugin;

EmDash 将其暴露为 <pluginId>__createEvent。被引用的路由必须是私有的并声明 permission。输入 schema 是必需的;输出 schema 可选。对删除、覆盖、发布、收费或以其他方式执行难以撤销的操作的工具,设置 destructive: true。

管理员必须在审阅名称、描述、路由、权限与破坏性标志后,单独启用插件的 MCP 工具。随后调用该工具需要路由权限,以及 mcp:tools 令牌作用域或 mcp:tools:<pluginId>。

MCP 工具不能引用带有 response: "raw" 的路由。MCP 工具使用 JSON 路由约定。

请求体

没有 request 声明的路由保留原始输入行为。EmDash 为 POST、PUT 和 PATCH 解析 JSON 请求体, 为 GET、HEAD 和 DELETE 解析查询参数。解析后的值以 routeCtx.input: unknown 到达沙箱处理函数。

当路由需要其他正文格式或特定字节限制时,声明 request.body。可用模式为 none、json、text、bytes 和 form-data。请求体会被缓冲。 默认最大值为 1 MiB,路由可将 maxBytes 提高到最多 8 MiB。

使用 pluginRoute() 从声明的正文模式推断输入类型。该辅助函数在运行时原样返回其参数:

import { pluginRoute, type SandboxedPlugin } from "emdash/plugin";

const plugin: SandboxedPlugin = {
	routes: {
		import: pluginRoute({
			methods: ["POST"],
			request: {
				body: "bytes",
				maxBytes: 4 * 1024 * 1024,
				headers: ["content-type", "x-import-signature"],
			},
			handler: async (routeCtx) => {
				const bytes = routeCtx.input; // Uint8Array
				const signature = routeCtx.request.headers["x-import-signature"];
				return { accepted: bytes.byteLength, signature };
			},
		}),
	},
};

export default plugin;

对于 body: "none",routeCtx.input 是解析后的查询字符串记录。json 声明将输入类型保持为 unknown,因此使用前请校验。text 声明产生字符串,bytes 产生 Uint8Array。

form-data 接受 multipart/form-data 和 application/x-www-form-urlencoded。它产生有序的 entries 数组。文本条目包含 { name, kind: "text", value };文件条目包含 { name, kind: "file", filename, contentType, bytes }。EmDash 最多接受 100 个部分,每部分 1 MiB, 文件名最多 255 个 UTF-8 字节。文件名不能包含控制字符或路径分隔符。编码后的请求总量也必须符合路由的正文限制。

在读取字段或执行副作用之前校验解析后的值。当无效输入是预期的调用者错误时,使用 safeParse。 这样路由可以返回稳定的 JSON 结果,而不是将无效输入变成内部异常:

const createInput = z.object({
	title: z.string().min(1).max(200),
	email: z.string().email(),
	priority: z.enum(["low", "medium", "high"]).default("medium"),
	tags: z.array(z.string()).optional(),
});

routes: {
	create: {
		handler: async (routeCtx, ctx) => {
			const parsed = createInput.safeParse(routeCtx.input);
			if (!parsed.success) {
				return { ok: false, error: { code: "VALIDATION_ERROR" } };
			}
			const { title, email, priority, tags } = parsed.data;

			await ctx.storage.items.put(`item_${Date.now()}`, {
				title,
				email,
				priority,
				tags: tags ?? [],
				createdAt: new Date().toISOString(),
			});

			return { ok: true };
		},
	},
},

查询字符串输入(GET/HEAD/DELETE)

无正文方法没有请求体,因此其输入来自 URL 查询字符串。每个值都是字符串。重复的键会变成数组,因此 ?tag=a&tag=b 变成 { tag: ["a", "b"] };单个 ?tag=a 仍为 { tag: "a" }。对数字和其他非字符串值使用 z.coerce:

const listInput = z.object({
	status: z.enum(["open", "closed"]).optional(),
	limit: z.coerce.number().int().min(1).max(100).default(20),
	tag: z.union([z.string(), z.array(z.string())]).optional(),
});

routes: {
	list: {
		// GET /_emdash/api/plugins/<slug>/list?status=open&limit=20&tag=a&tag=b
		handler: async (routeCtx, ctx) => {
			const parsed = listInput.safeParse(routeCtx.input);
			if (!parsed.success) return { ok: false, error: "INVALID_QUERY" };
			const { status, limit, tag } = parsed.data;
			// ...
		},
	},
},

JSON 返回值

除非声明 response: "raw",否则路由使用 JSON 响应约定。返回任何可 JSON 序列化的值。 调度器将其包装在 EmDash 标准信封({ success: true, data: <your value> })中,并以 application/json 提供。

return { id: "abc", count: 42 };  // wrapped to { success: true, data: { id, count } }
return [1, 2, 3];                 // wrapped to { success: true, data: [1, 2, 3] }

错误

当沙箱路由无法完成时抛出。EmDash 会记录异常并返回 ROUTE_ERROR。抛出的消息可能包含在该响应中,因此切勿在异常消息中放入凭证、个人数据、内部路径或堆栈跟踪:

handler: async (_routeCtx, ctx) => {
	try {
		return await refreshRemoteIndex(ctx);
	} catch {
		ctx.log.error("Remote index refresh failed");
		throw new Error("Remote index refresh failed");
	}
},

沙箱插件代码不能通过抛出 Response 选择任意 HTTP 状态;Response 不会作为结构化错误跨越每个沙箱运行器的边界。EmDash 在处理函数运行前为认证、授权、CSRF 与缺失路由失败分配状态。对预期的校验与领域结果返回 JSON 结果,并将异常保留给意外失败。

作为 JSON 返回的预期错误仍使用路由的成功 HTTP 响应,并出现在 EmDash 外层 { success: true, data: ... } 信封内。包含稳定的应用级代码,以便客户端区分该结果。

HTTP 方法

路由名称选择一个处理函数。声明 methods 以限制哪些 HTTP 方法可以调用它。 当请求方法未声明时,EmDash 在调用处理函数之前返回带有 Allow 头的 405 Method Not Allowed:

routes: {
	item: {
		methods: ["GET", "DELETE"],
		handler: async (routeCtx, ctx) => {
			const parsed = z.object({ id: z.string() }).safeParse(routeCtx.input);
			if (!parsed.success) return { ok: false, error: "INVALID_ID" };
			const { id } = parsed.data;

			switch (routeCtx.request.method) {
				case "GET":
					return await ctx.storage.items.get(id);
				case "DELETE":
					await ctx.storage.items.delete(id);
					return { deleted: true };
			}
		},
	},
},

没有 methods 的路由为兼容性保持方法无关。在遗留路由中执行变更前检查 routeCtx.request.method,或添加 methods 让主机强制该限制。

原始响应

当路由必须返回带有自定义状态与安全响应头的未包装文本或字节时,声明 response: "raw"。 从 emdash/plugin 返回 pluginResponse();WHATWG Response 不会跨越沙箱边界:

import { pluginResponse, pluginRoute, type SandboxedPlugin } from "emdash/plugin";

const plugin: SandboxedPlugin = {
	routes: {
		download: pluginRoute({
			public: true,
			methods: ["GET"],
			request: { body: "none" },
			response: "raw",
			cacheControl: "public, max-age=60",
			handler: async () =>
				pluginResponse({
					status: 200,
					headers: {
						"content-type": "text/csv; charset=utf-8",
						"content-disposition": 'attachment; filename="report.csv"',
					},
					body: { kind: "text", value: "name,count\nPublished,12\n" },
				}),
		}),
	},
};

export default plugin;

响应体为 { kind: "text", value: string } 或 { kind: "bytes", value: Uint8Array },并缓冲至最多 8 MiB。原始响应可以设置 Accept-Ranges、Content-Disposition、Content-Encoding、Content-Language、Content-Range、 Content-Type、ETag、Last-Modified、Location 和 Retry-After;主机移除所有其他插件提供的头。 它添加 X-Content-Type-Options: nosniff、沙箱文档内容安全策略,以及 Referrer-Policy: no-referrer。它仅对成功的公开 GET 和 HEAD 响应应用路由的 cacheControl。 其他响应使用 private, no-store。

原始路由不能提供活动的同源内容。EmDash 拒绝 HTML、JavaScript 与 ECMAScript、XHTML、SVG、XML、CSS、WebAssembly、multipart/related 以及 multipart/x-mixed-replace 媒体类型。当响应必须运行活动浏览器内容时,使用原生插件或单独的源。

访问请求

routeCtx.request 是一个 SandboxedRequest:可移植的 { url, method, headers } 记录,在进程内与 isolate 中行为一致。headers 是以小写头名为键的 Record<string, string>——用小写名索引,或用 Object.entries 迭代。url 是字符串,因此 new URL(request.url) 可解析查询参数。可用时,routeCtx.requestMeta 携带跨平台规范化的 IP、用户代理与地理数据。

对于带有 request 声明的路由,只有 request.headers 中的名称会到达处理函数。EmDash 拒绝凭证、cookie、Cloudflare Access 头、代理授权、Set-Cookie 以及 X-EmDash-Request CSRF 头的声明。 它会从每个沙箱请求(包括遗留路由)中剥离这些头。

handler: async (routeCtx, ctx) => {
	const { request, requestMeta } = routeCtx;

	const signature = request.headers["x-import-signature"]; // lowercased key, no .get()
	const url = new URL(request.url);
	const page = url.searchParams.get("page");

	ctx.log.info("Request", { meta: requestMeta });

	if (request.method !== "POST") return { error: "POST_REQUIRED" };
},

常见模式

设置与分页数据

插件设置使用私有路由、Block Kit 表单和 ctx.settings。Settings 提供完整的加载、校验、表单与加密密钥模式。

列出插件数据的路由应返回 ctx.storage.<collection>.query() 的游标。Storage pagination 展示如何传递游标并在不超过每页 100 项上限的情况下处理多页。

外部 API 代理

通过 ctx.http 将请求代理到外部服务(需要 network:request 能力与 allowedHosts 中的条目):

routes: {
	forecast: {
		handler: async (routeCtx, ctx) => {
			const parsed = z.object({ city: z.string().min(1) }).safeParse(routeCtx.input);
			if (!parsed.success) return { ok: false, error: "INVALID_CITY" };
			if (!ctx.http) throw new Error("Network capability not granted");

			const apiKey = await ctx.settings.get<string>("apiKey");
			if (!apiKey) throw new Error("API key not configured");

			const response = await ctx.http.fetch(
				`https://api.weather.example.com/forecast?city=${encodeURIComponent(parsed.data.city)}`,
				{ headers: { "X-API-Key": apiKey } },
			);

			if (!response.ok) {
				throw new Error(`Weather API error: ${response.status}`);
			}
			return response.json();
		},
	},
},

ctx.http.fetch() 在两种沙箱运行器中都返回缓冲的 WHATWG Response。arrayBuffer() 和 blob() 等二进制方法在 Cloudflare Worker Loader 与 Node/workerd 上保留字节。请求与响应体各自限制为 8 MiB 解码数据。重定向目标在每一跳之前检查,当重定向跨源时会移除凭证头。

从 Block Kit 调用路由

沙箱插件不会向管理界面发送 React 代码。声明一个 admin 路由并返回 Block Kit 响应。EmDash 将 page_load、block_action 和 form_submit 交互以正确的 URL 与 CSRF 头发送到该私有路由。Block Kit 展示交互约定与完整路由。

从队列与定时处理函数调用路由

平台事件处理函数(Cloudflare Queue 消费者、自定义 scheduled() 处理函数)没有 HTTP 请求,因此没有 locals.emdash。使用 emdash/middleware 中的 withEmDashRuntime() 直接获取运行时,并在没有请求的情况下调用插件路由:

import { withEmDashRuntime } from "emdash/middleware";

export default {
	// ... fetch/scheduled from @emdash-cms/cloudflare/worker

	async queue(batch: MessageBatch) {
		await withEmDashRuntime(async (runtime) => {
			for (const message of batch.messages) {
				const result = await runtime.handlePluginApiRoute(
					"my-plugin",
					"POST",
					"/finishJob",
					new Request("https://internal/", {
						method: "POST",
						body: JSON.stringify(message.body),
					}),
				);
				if (result.success) message.ack();
				else message.retry();
			}
		});
	},
};

这会解析请求处理函数使用的同一缓存运行时,因此插件存储、hooks 与媒体访问的行为与请求期间完全一致。在基于连接的数据库适配器上(例如通过 Hyperdrive 的 Postgres),回调在事件范围的连接下运行,返回时提交并关闭。

从外部调用路由

公开路由可直接调用:

curl -X POST https://your-site.com/_emdash/api/plugins/forms/track \
  -H "Content-Type: application/json" \
  -d '{"event": "pageview"}'

私有路由需要会话凭证加上 X-EmDash-Request: 1,或带有 admin 作用域的 API 令牌。以下服务器到服务器请求使用令牌:

curl -X POST https://your-site.com/_emdash/api/plugins/forms/create \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"title": "Hello", "email": "user@example.com"}'

路由上下文参考

以下接口汇总沙箱路由处理函数可用的可移植值:

// What sandboxed route handlers receive as their two arguments

interface SandboxedRequest {
	url: string;
	method: string;
	headers: Record<string, string>; // lowercased keys
}

interface SandboxedRouteContext {
	input: unknown; // validate inside the handler before use
	request: SandboxedRequest;
	requestMeta?: unknown;
	user?: UserInfo; // authenticated caller on private routes; undefined on public routes
}

interface UserInfo {
	id: string;
	email: string;
	name: string | null;
	role: number;
	createdAt: string;
}

interface PluginContext {
	plugin: { id: string; version: string };
	storage: PluginStorage;
	kv: KVAccess;
	log: LogAccess;
	site: SiteInfo;
	url(path: string): string;
	cron?: CronAccess;
	content?: ContentAccess;       // when content:read or content:write declared
	schema?: SchemaAccess;         // when schema:read declared
	taxonomies?: TaxonomyAccess;   // when taxonomies:read declared
	redirects?: RedirectAccess;    // when redirects:read or redirects:write declared
	media?: MediaAccess;           // when any media capability is declared
	http?: HttpAccess;             // when network:request declared
	users?: UserAccess;            // when users:read declared
	email?: EmailAccess;           // when email:send declared and provider configured
}

原生插件接收一个将两者合并的单一 RouteContext 参数——若走那条路,见 Creating native plugins。