API 路由

本页内容

插件可以为其管理后台 UI 和外部集成暴露 API 路由。路由挂载在 /_emdash/api/plugins/<slug>/<route-name> 下(<slug> 是 emdash-plugin.jsonc 中插件的 slug 字段,在运行时以 ctx.plugin.id 的形式暴露),并在沙箱运行时内运行,使用与钩子所接收的相同的 PluginContext。

本页介绍沙箱化插件。原生插件使用相同的路由选项、认证和 URL 布局,但它们的处理函数接收的是一个合并后的上下文对象。该签名请参阅你的第一个原生插件。

定义路由

在 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 就是你在钩子内部获得的同一个 PluginContext,包含 ctx.storage、ctx.settings、ctx.kv、ctx.content、ctx.http 和 ctx.log。

过滤已索引的内容字段

具有 content:read 能力的插件可以过滤集合标记为 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>。路由名称可以包含斜杠,以表示嵌套路径。

插件 id路由名称URL
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 权限。当该操作属于已有的内容、媒体、模式或设置能力时,请把 permission 设置为更窄的 EmDash RBAC 权限:

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

私有路由对每种 HTTP 方法都要求其声明的权限。对于基于 Cookie 认证的请求,它们还要求 X-EmDash-Request: 1 CSRF 请求头,包括 GET 和 HEAD,因为插件路由可能对任何方法运行同一个处理函数。管理后台 UI 会自动发送该请求头。基于令牌认证的请求无需该请求头,但仍然需要 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(它们会跳过认证,因此不会绑定调用者,即使访问者碰巧拥有管理员会话也是如此);对于令牌未绑定到某个用户的基于令牌认证的请求(机器令牌),它同样是 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。输入模式是必需的;输出模式是可选的。对于会删除、覆盖、发布、扣费或以其他方式执行难以撤销的操作的工具,请设置 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 并不能作为结构化错误穿过每一种沙箱运行器的边界。对于认证、授权、CSRF 和路由缺失这几类失败,EmDash 会在处理函数运行之前分配状态码。对于预期之内的校验和业务结果,请返回 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。设置提供了完整的加载、校验、表单和加密密钥的模式。

列出插件数据的路由应当返回 ctx.storage.<collection>.query() 给出的游标。存储分页展示了如何传递游标,并在不超过每页最多 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 会使用正确的 URL 和 CSRF 请求头,把 page_load、block_action 和 form_submit 交互发送到该私有路由。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();
			}
		});
	},
};

它会解析出与请求处理函数所使用的相同的缓存运行时,因此插件存储、钩子和媒体访问的行为都与请求期间完全一致。在基于连接的数据库适配器上(例如通过 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": "[email protected]"}'

路由上下文参考

下面的接口概括了沙箱化路由处理函数可用的可移植值:

// 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
	bylines?: BylineAccess;        // when bylines: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 参数,它把这两者合并在一起。如果你打算走这条路,请参阅你的第一个原生插件。