Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): channels - default permissive CORS (#368)

Andrew Barba8470695ef661
diff --git a/.changeset/eve-channel-cors.md b/.changeset/eve-channel-cors.md
new file mode 100644
index 000000000..b5536c619
--- /dev/null
+++ b/.changeset/eve-channel-cors.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The eve HTTP channel now enables permissive browser CORS by default, including preflight handling for session routes. Custom channels can opt into CORS with `defineChannel({ cors })`, and `eveChannel({ cors })` can disable or narrow the default policy.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index 8321ea70d..46be90c48 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -55,6 +55,25 @@ Declare routes with the `POST()` and `GET()` helpers. Each route handler receive
Event handlers like `"message.completed"` are declared under the `events` key. They receive `(eventData, channel, ctx)`, where `eventData` is the event payload, `channel` carries platform handles and session continuation operations, and `ctx` is the eve `SessionContext`. Every channel kind shares this signature. The one exception is `session.failed`, which receives only `(eventData, channel)` with no `ctx`.
+## CORS
+
+Custom HTTP channels leave CORS untouched unless you opt in. Pass `cors: true`
+for permissive browser access with preflight handling, or pass a serializable
+CORS options object to narrow origins, methods, and headers:
+
+```ts
+import { defineChannel, POST } from "eve/channels";
+
+export default defineChannel({
+ cors: {
+ origin: ["https://app.example.com"],
+ methods: ["POST"],
+ allowHeaders: ["authorization", "content-type"],
+ },
+ routes: [POST("/message", async () => new Response("ok"))],
+});
+```
+
## WebSocket routes
Use `WS()` when a custom channel needs a WebSocket endpoint. The route handler runs once per upgrade request and returns lifecycle hooks for that connection:
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 6cb5a298d..441464055 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -45,6 +45,29 @@ curl -N https://<deployment>/eve/v1/session/ses_01h.../stream
See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the full request and stream flow, including the complete event set.
+## CORS
+
+The eve channel enables permissive browser CORS by default. Its session routes
+respond to preflight requests and emit wildcard CORS headers, so browser
+frontends can call the channel without extra deployment configuration. Route
+auth still runs on the actual session requests.
+
+Disable or narrow CORS only when another layer owns it:
+
+```ts title="agent/channels/eve.ts"
+import { eveChannel } from "eve/channels/eve";
+import { localDev, vercelOidc } from "eve/channels/auth";
+
+export default eveChannel({
+ auth: [vercelOidc(), localDev()],
+ cors: {
+ origin: "https://app.example.com",
+ methods: ["GET", "POST"],
+ allowedHeaders: ["authorization", "content-type"],
+ },
+});
+```
+
## Authentication
The `auth` option decides who can call these routes. The built-in helpers cover development and trusted infrastructure:
diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.ts
index a2592e98a..fba8bda54 100644
--- a/packages/eve/src/channel/compiled-channel.ts
+++ b/packages/eve/src/channel/compiled-channel.ts
@@ -1,4 +1,5 @@
import type { ChannelAdapter } from "#channel/adapter.js";
+import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
import type { RouteDefinition, SendFn } from "#channel/routes.js";
import type { Session } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
@@ -25,6 +26,7 @@ export interface CompiledChannel<
readonly __kind: typeof CHANNEL_SENTINEL;
readonly routes: readonly RouteDefinition<TState>[];
readonly adapter: ChannelAdapter<any>;
+ readonly cors?: NormalizedChannelCorsOptions;
readonly __metadata?: TMetadata;
readonly receive?: (
input: {
diff --git a/packages/eve/src/channel/cors.ts b/packages/eve/src/channel/cors.ts
new file mode 100644
index 000000000..2d9665a77
--- /dev/null
+++ b/packages/eve/src/channel/cors.ts
@@ -0,0 +1,168 @@
+/**
+ * Serializable subset of H3/Nitro CORS options supported by channel routes.
+ *
+ * Function and RegExp origins are intentionally excluded because channel
+ * definitions are compiled into JSON artifacts and virtual Nitro handlers.
+ */
+export interface ChannelCorsOptions {
+ /**
+ * Allowed request origins. Omit or pass `"*"` for all origins, pass
+ * `"null"` for the literal `null` origin, or pass an array of exact origins.
+ */
+ readonly origin?: "*" | "null" | readonly string[];
+ /** Methods emitted on preflight responses. Omit or pass `"*"` for all methods. */
+ readonly methods?: "*" | readonly string[];
+ /**
+ * Request headers emitted on preflight responses. Omit or pass `"*"` to
+ * allow requested headers.
+ */
+ readonly allowHeaders?: "*" | readonly string[];
+ /** Response headers exposed to browser callers. Omit or pass `"*"` for all headers. */
+ readonly exposeHeaders?: "*" | readonly string[];
+ /** Whether to emit `access-control-allow-credentials: true`. */
+ readonly credentials?: boolean;
+ /** Max age, in seconds, emitted on preflight responses. */
+ readonly maxAge?: string | number | false;
+ /** Preflight response customization. */
+ readonly preflight?: {
+ readonly statusCode?: number;
+ };
+}
+
+export type ChannelCors = boolean | ChannelCorsOptions;
+
+export interface NormalizedChannelCorsOptions {
+ readonly origin?: "*" | "null" | readonly string[];
+ readonly methods?: "*" | readonly string[];
+ readonly allowHeaders?: "*" | readonly string[];
+ readonly exposeHeaders?: "*" | readonly string[];
+ readonly credentials?: boolean;
+ readonly maxAge?: string | false;
+ readonly preflight?: {
+ readonly statusCode?: number;
+ };
+}
+
+export function normalizeChannelCors(
+ cors: ChannelCors | undefined,
+): NormalizedChannelCorsOptions | undefined {
+ if (cors === undefined || cors === false) {
+ return undefined;
+ }
+
+ if (cors === true) {
+ return {};
+ }
+
+ if (cors === null || typeof cors !== "object" || Array.isArray(cors)) {
+ throw new Error("Expected channel cors to be a boolean or a serializable CORS options object.");
+ }
+
+ const normalized: MutableNormalizedChannelCorsOptions = {};
+
+ if (cors.origin !== undefined) {
+ normalized.origin = normalizeOrigin(cors.origin);
+ }
+ if (cors.methods !== undefined) {
+ normalized.methods = normalizeWildcardOrStringList(cors.methods, "methods");
+ }
+ if (cors.allowHeaders !== undefined) {
+ normalized.allowHeaders = normalizeWildcardOrStringList(cors.allowHeaders, "allowHeaders");
+ }
+ if (cors.exposeHeaders !== undefined) {
+ normalized.exposeHeaders = normalizeWildcardOrStringList(cors.exposeHeaders, "exposeHeaders");
+ }
+ if (cors.credentials !== undefined) {
+ if (typeof cors.credentials !== "boolean") {
+ throw new Error("Expected channel cors.credentials to be a boolean.");
+ }
+ normalized.credentials = cors.credentials;
+ }
+ if (cors.maxAge !== undefined) {
+ normalized.maxAge = normalizeMaxAge(cors.maxAge);
+ }
+ if (cors.preflight !== undefined) {
+ normalized.preflight = normalizePreflight(cors.preflight);
+ }
+
+ return normalized;
+}
+
+type MutableNormalizedChannelCorsOptions = {
+ -readonly [K in keyof NormalizedChannelCorsOptions]: NormalizedChannelCorsOptions[K];
+};
+
+function normalizeOrigin(origin: ChannelCorsOptions["origin"]): "*" | "null" | readonly string[] {
+ if (origin === "*" || origin === "null") {
+ return origin;
+ }
+
+ if (!Array.isArray(origin)) {
+ throw new Error('Expected channel cors.origin to be "*", "null", or an array of origins.');
+ }
+
+ return origin.map((entry) => {
+ if (typeof entry !== "string" || entry.length === 0) {
+ throw new Error("Expected channel cors.origin entries to be non-empty strings.");
+ }
+ return entry;
+ });
+}
+
+function normalizeWildcardOrStringList(
+ value: "*" | readonly string[],
+ label: "allowHeaders" | "exposeHeaders" | "methods",
+): "*" | readonly string[] {
+ if (value === "*") {
+ return value;
+ }
+
+ if (!Array.isArray(value)) {
+ throw new Error(`Expected channel cors.${label} to be "*" or an array of strings.`);
+ }
+
+ return value.map((entry) => {
+ if (typeof entry !== "string" || entry.length === 0) {
+ throw new Error(`Expected channel cors.${label} entries to be non-empty strings.`);
+ }
+ return entry;
+ });
+}
+
+function normalizeMaxAge(maxAge: ChannelCorsOptions["maxAge"]): string | false {
+ if (maxAge === false) {
+ return false;
+ }
+
+ if (typeof maxAge === "number") {
+ if (!Number.isFinite(maxAge) || maxAge < 0) {
+ throw new Error("Expected channel cors.maxAge to be a non-negative finite number.");
+ }
+ return String(maxAge);
+ }
+
+ if (typeof maxAge === "string" && maxAge.length > 0) {
+ return maxAge;
+ }
+
+ throw new Error("Expected channel cors.maxAge to be false, a string, or a number.");
+}
+
+function normalizePreflight(
+ preflight: ChannelCorsOptions["preflight"],
+): NormalizedChannelCorsOptions["preflight"] {
+ if (preflight === null || typeof preflight !== "object" || Array.isArray(preflight)) {
+ throw new Error("Expected channel cors.preflight to be an object.");
+ }
+
+ const statusCode = preflight.statusCode;
+ if (statusCode === undefined) {
+ return {};
+ }
+
+ if (!Number.isInteger(statusCode) || statusCode < 100 || statusCode > 599) {
+ throw new Error("Expected channel cors.preflight.statusCode to be an HTTP status code.");
+ }
+
+ return { statusCode };
+}
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 125303a17..cb6106c25 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -9,6 +9,7 @@ import {
type CompiledRemoteAgentNode,
} from "#compiler/remote-agent-node.js";
import type { ChannelRouteMethod } from "#public/definitions/channel.js";
+import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
import { jsonObjectSchema } from "#shared/json-schemas.js";
import type { Node } from "#shared/node.js";
import type {
@@ -39,7 +40,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 30;
+export const COMPILED_AGENT_MANIFEST_VERSION = 31;
/**
* Compiled channel entry preserved in the compiled manifest.
@@ -68,6 +69,11 @@ export interface CompiledChannelDefinition {
* Omitted when the route does not register an adapter.
*/
readonly adapterKind?: string;
+ /**
+ * Serializable CORS options to apply to this channel route. Omitted when the
+ * channel leaves CORS untouched.
+ */
+ readonly cors?: NormalizedChannelCorsOptions;
}
/**
@@ -259,6 +265,23 @@ const channelMethodSchema = z.union([
z.literal("WEBSOCKET"),
]);
+const compiledChannelCorsSchema = z
+ .object({
+ origin: z.union([z.literal("*"), z.literal("null"), z.array(z.string())]).optional(),
+ methods: z.union([z.literal("*"), z.array(z.string())]).optional(),
+ allowHeaders: z.union([z.literal("*"), z.array(z.string())]).optional(),
+ exposeHeaders: z.union([z.literal("*"), z.array(z.string())]).optional(),
+ credentials: z.boolean().optional(),
+ maxAge: z.union([z.string(), z.literal(false)]).optional(),
+ preflight: z
+ .object({
+ statusCode: z.number().int().min(100).max(599).optional(),
+ })
+ .strict()
+ .optional(),
+ })
+ .strict() satisfies z.ZodType<NormalizedChannelCorsOptions>;
+
const compiledChannelDefinitionSchema = z
.object({
kind: z.literal("channel"),
@@ -270,6 +293,7 @@ const compiledChannelDefinitionSchema = z
sourceKind: z.literal("module"),
exportName: z.string().optional(),
adapterKind: z.string().optional(),
+ cors: compiledChannelCorsSchema.optional(),
})
.strict();
diff --git a/packages/eve/src/compiler/normalize-channel.ts b/packages/eve/src/compiler/normalize-channel.ts
index e3c0a9471..d35021c84 100644
--- a/packages/eve/src/compiler/normalize-channel.ts
+++ b/packages/eve/src/compiler/normalize-channel.ts
@@ -58,6 +58,7 @@ export async function compileChannelDefinition(
sourceKind: "module" as const,
exportName: source.exportName,
adapterKind: extractAdapterKind(definition.adapter),
+ cors: definition.cors,
}));
}
diff --git a/packages/eve/src/internal/nitro/host/channel-routes.test.ts b/packages/eve/src/internal/nitro/host/channel-routes.test.ts
index 2d80dc20a..44db4dcc0 100644
--- a/packages/eve/src/internal/nitro/host/channel-routes.test.ts
+++ b/packages/eve/src/internal/nitro/host/channel-routes.test.ts
@@ -3,6 +3,66 @@ import { describe, expect, it } from "vitest";
import { registerChannelVirtualHandlers } from "#internal/nitro/host/channel-routes.js";
describe("registerChannelVirtualHandlers", () => {
+ it("wraps CORS-enabled HTTP routes and registers preflight handlers", () => {
+ const nitro = {
+ options: {
+ handlers: [] as any[],
+ virtual: {} as Record<string, string>,
+ },
+ };
+
+ registerChannelVirtualHandlers(nitro, {
+ artifactsConfig: { appRoot: "/app", dev: true },
+ registrations: [{ cors: {}, method: "POST", route: "/eve/v1/session" }],
+ });
+
+ expect(nitro.options.handlers).toEqual([
+ {
+ handler: "#nitro/virtual/eve-channel/POST /eve/v1/session",
+ method: "POST",
+ route: "/eve/v1/session",
+ },
+ {
+ handler: "#nitro/virtual/eve-channel/OPTIONS /eve/v1/session",
+ method: "OPTIONS",
+ route: "/eve/v1/session",
+ },
+ ]);
+ expect(nitro.options.virtual["#nitro/virtual/eve-channel/POST /eve/v1/session"]).toContain(
+ "handleCors",
+ );
+ expect(nitro.options.virtual["#nitro/virtual/eve-channel/POST /eve/v1/session"]).toContain(
+ "dispatchChannelRequest",
+ );
+ expect(nitro.options.virtual["#nitro/virtual/eve-channel/OPTIONS /eve/v1/session"]).toContain(
+ "return new Response(null, { status: 204 });",
+ );
+ });
+
+ it("registers one preflight handler per CORS-enabled path", () => {
+ const nitro = {
+ options: {
+ handlers: [] as any[],
+ virtual: {} as Record<string, string>,
+ },
+ };
+
+ registerChannelVirtualHandlers(nitro, {
+ artifactsConfig: { appRoot: "/app", dev: true },
+ registrations: [
+ { cors: {}, method: "GET", route: "/eve/v1/session/:sessionId/events" },
+ { cors: {}, method: "POST", route: "/eve/v1/session/:sessionId/events" },
+ ],
+ });
+
+ expect(
+ nitro.options.handlers.filter(
+ (handler) =>
+ handler.method === "OPTIONS" && handler.route === "/eve/v1/session/:sessionId/events",
+ ),
+ ).toHaveLength(1);
+ });
+
it("registers websocket routes with the websocket dispatcher", () => {
const nitro = {
options: {
diff --git a/packages/eve/src/internal/nitro/host/channel-routes.ts b/packages/eve/src/internal/nitro/host/channel-routes.ts
index eb37fffb1..ec02822d3 100644
--- a/packages/eve/src/internal/nitro/host/channel-routes.ts
+++ b/packages/eve/src/internal/nitro/host/channel-routes.ts
@@ -1,5 +1,6 @@
import type { Nitro, NitroEventHandler } from "nitro/types";
+import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
import type { ChannelRouteMethod } from "#public/definitions/channel.js";
import {
getAllFrameworkChannelNames,
@@ -33,6 +34,7 @@ interface ChannelRouteNitro {
export interface NitroChannelRouteRegistration {
readonly method: ChannelRouteMethod;
readonly route: string;
+ readonly cors?: NormalizedChannelCorsOptions;
}
/**
@@ -61,7 +63,7 @@ export function computeChannelRouteRegistrations(
continue;
}
authoredNames.add(entry.name);
- authoredRoutes.push({ method: entry.method, route: entry.urlPath });
+ authoredRoutes.push({ method: entry.method, route: entry.urlPath, cors: entry.cors });
}
const activeFrameworkRoutes = getFrameworkChannelDefinitions()
@@ -70,6 +72,7 @@ export function computeChannelRouteRegistrations(
(channel): NitroChannelRouteRegistration => ({
method: channel.method,
route: channel.urlPath,
+ cors: channel.cors,
}),
);
@@ -99,10 +102,13 @@ export function registerChannelVirtualHandlers(
readonly registrations: readonly NitroChannelRouteRegistration[];
},
): void {
+ const preflightRoutes = new Set<string>();
for (const registration of input.registrations) {
addChannelVirtualHandler(nitro, {
artifactsConfig: input.artifactsConfig,
+ cors: registration.cors,
method: registration.method,
+ preflightRoutes,
route: registration.route,
});
}
@@ -158,7 +164,9 @@ function addChannelVirtualHandler(
nitro: Pick<ChannelRouteNitro, "options">,
input: {
artifactsConfig: NitroArtifactsConfigInput;
+ cors?: NormalizedChannelCorsOptions;
method: ChannelRouteMethod;
+ preflightRoutes: Set<string>;
route: string;
},
): void {
@@ -168,6 +176,7 @@ function addChannelVirtualHandler(
resolvePackageSourceFilePath("src/internal/nitro/routes/channel-dispatch.ts"),
);
const nitroModulePath = stringifyEsmImportSpecifier(resolvePackageDependencyPath("nitro"));
+ const nitroH3ModulePath = stringifyEsmImportSpecifier(resolvePackageDependencyPath("nitro/h3"));
if (input.method === "WEBSOCKET") {
nitro.options.handlers.push({
@@ -188,10 +197,65 @@ function addChannelVirtualHandler(
method: input.method,
route: input.route,
});
+ if (input.cors !== undefined) {
+ addChannelCorsPreflightHandler(nitro, {
+ cors: input.cors,
+ nitroH3ModulePath,
+ preflightRoutes: input.preflightRoutes,
+ route: input.route,
+ });
+ }
nitro.options.virtual[virtualId] = [
+ ...(input.cors === undefined
+ ? []
+ : [
+ `import { handleCors } from ${nitroH3ModulePath};`,
+ `const cors = ${JSON.stringify(input.cors)};`,
+ ]),
`import { dispatchChannelRequest } from ${dispatchModulePath};`,
`const config = ${JSON.stringify(input.artifactsConfig)};`,
- `export default (event) => dispatchChannelRequest(event, ${JSON.stringify(routeKey)}, config);`,
+ input.cors === undefined
+ ? `export default (event) => dispatchChannelRequest(event, ${JSON.stringify(routeKey)}, config);`
+ : [
+ `export default (event) => {`,
+ ` const corsResponse = handleCors(event, cors);`,
+ ` if (corsResponse !== false) return corsResponse;`,
+ ` return dispatchChannelRequest(event, ${JSON.stringify(routeKey)}, config);`,
+ `};`,
+ ].join("\n"),
+ ].join("\n");
+}
+
+function addChannelCorsPreflightHandler(
+ nitro: Pick<ChannelRouteNitro, "options">,
+ input: {
+ cors: NormalizedChannelCorsOptions;
+ nitroH3ModulePath: string;
+ preflightRoutes: Set<string>;
+ route: string;
+ },
+): void {
+ if (input.preflightRoutes.has(input.route)) {
+ return;
+ }
+ input.preflightRoutes.add(input.route);
+
+ const routeKey = `OPTIONS ${input.route}`;
+ const virtualId = `${EVE_CHANNEL_VIRTUAL_ID_PREFIX}${routeKey}`;
+
+ nitro.options.handlers.push({
+ handler: virtualId,
+ method: "OPTIONS",
+ route: input.route,
+ });
+ nitro.options.virtual[virtualId] = [
+ `import { handleCors } from ${input.nitroH3ModulePath};`,
+ `const cors = ${JSON.stringify(input.cors)};`,
+ `export default (event) => {`,
+ ` const corsResponse = handleCors(event, cors);`,
+ ` if (corsResponse !== false) return corsResponse;`,
+ ` return new Response(null, { status: 204 });`,
+ `};`,
].join("\n");
}
@@ -232,7 +296,8 @@ function areChannelRouteRegistrationsEqual(
if (
leftRegistration.method !== rightRegistration.method ||
- leftRegistration.route !== rightRegistration.route
+ leftRegistration.route !== rightRegistration.route ||
+ !areChannelCorsOptionsEqual(leftRegistration.cors, rightRegistration.cors)
) {
return false;
}
@@ -240,3 +305,10 @@ function areChannelRouteRegistrationsEqual(
return true;
}
+
+function areChannelCorsOptionsEqual(
+ left: NormalizedChannelCorsOptions | undefined,
+ right: NormalizedChannelCorsOptions | undefined,
+): boolean {
+ return JSON.stringify(left) === JSON.stringify(right);
+}
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 2b3dd146e..8a79d6e65 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -162,6 +162,52 @@ function contextAccessorFor(ctx: ContextContainer): ContextAccessor {
}
describe("eveChannel — events", () => {
+ it("defaults to permissive CORS", () => {
+ const channel = eveChannel({ auth: none() });
+ if (!isCompiledChannel(channel)) {
+ throw new Error("Expected eveChannel() to return a compiled channel.");
+ }
+
+ expect(channel.cors).toEqual({});
+ });
+
+ it("allows CORS to be disabled", () => {
+ const channel = eveChannel({ auth: none(), cors: false });
+ if (!isCompiledChannel(channel)) {
+ throw new Error("Expected eveChannel() to return a compiled channel.");
+ }
+
+ expect(channel.cors).toBeUndefined();
+ });
+
+ it("normalizes higher-level CORS options", () => {
+ const channel = eveChannel({
+ auth: none(),
+ cors: {
+ allowedHeaders: ["authorization"],
+ credentials: true,
+ exposedHeaders: ["x-eve-session-id"],
+ maxAge: 300,
+ methods: ["POST", "GET"],
+ origin: "https://app.example.com",
+ preflightStatus: 200,
+ },
+ });
+ if (!isCompiledChannel(channel)) {
+ throw new Error("Expected eveChannel() to return a compiled channel.");
+ }
+
+ expect(channel.cors).toEqual({
+ allowHeaders: ["authorization"],
+ credentials: true,
+ exposeHeaders: ["x-eve-session-id"],
+ maxAge: "300",
+ methods: ["POST", "GET"],
+ origin: ["https://app.example.com"],
+ preflight: { statusCode: 200 },
+ });
+ });
+
it("passes configured event handlers through with session context", async () => {
const observed: string[] = [];
const adapter = getEveAdapter({
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 226fc6dcc..f33991f20 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -26,9 +26,11 @@ import {
POST,
GET,
type Channel,
+ type ChannelCors,
type ChannelEvents,
type ChannelSessionOps,
} from "#public/definitions/defineChannel.js";
+import type { ChannelMethod } from "#public/definitions/channel.js";
import type { RunMode } from "#shared/run-mode.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
@@ -43,6 +45,32 @@ export type EveEventContext = ChannelSessionOps;
/** Runtime stream-event handlers supported by `eveChannel({ events })`. */
export type EveChannelEvents = ChannelEvents<EveEventContext>;
+export interface EveChannelCorsOptions {
+ /**
+ * Allowed request origin. Pass a single origin string, an exact-origin list,
+ * `"null"`, or `"*"`. Omit for `"*"`.
+ */
+ readonly origin?: "*" | "null" | string | readonly string[];
+ /** Methods emitted on preflight responses. Omit for `"*"`. */
+ readonly methods?: "*" | readonly ChannelMethod[];
+ /** Request headers emitted on preflight responses. Omit for `"*"`. */
+ readonly allowedHeaders?: "*" | readonly string[];
+ /** Response headers exposed to browser callers. Omit for `"*"`. */
+ readonly exposedHeaders?: "*" | readonly string[];
+ /** Whether to emit `access-control-allow-credentials: true`. */
+ readonly credentials?: boolean;
+ /** Max age, in seconds, emitted on preflight responses. */
+ readonly maxAge?: number | false;
+ /** Preflight response status code. Defaults to 204. */
+ readonly preflightStatus?: number;
+}
+
+/**
+ * Higher-level CORS policy for the default eve HTTP channel. Omit or pass `"*"`
+ * / `true` for fully permissive browser access; pass `false` to disable CORS.
+ */
+export type EveChannelCors = "*" | boolean | EveChannelCorsOptions;
+
/** Low-level eve HTTP handle exposed to `eveChannel({ onMessage })`. */
export interface EveHandle {
/** Route-auth result for the request; `onMessage` chooses session auth by returning `{ auth }`. */
@@ -93,6 +121,11 @@ export interface EveChannelInput {
* types); `"disabled"` rejects every attachment; a partial config is merged onto the default. Violations reject with 413 (too large) or 415 (bad type).
*/
readonly uploadPolicy?: UploadPolicyInput;
+ /**
+ * Browser CORS policy for the eve HTTP routes. Omit for fully permissive
+ * CORS (`"*"`). Pass `false` only when another layer owns CORS.
+ */
+ readonly cors?: EveChannelCors;
/**
* Pre-dispatch hook for inbound eve HTTP messages. Runs after route auth and body
* parsing, before runtime dispatch.
@@ -126,6 +159,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
const uploadPolicy = mergeUploadPolicy(input.uploadPolicy);
return defineChannel<undefined, EveEventContext>({
+ cors: normalizeEveCors(input.cors),
routes: [
POST("/eve/v1/session", async (req, { send }) => {
const authResult = await routeAuth(req, input.auth);
@@ -300,6 +334,63 @@ export function eveChannel(input: EveChannelInput): EveChannel {
});
}
+function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors {
+ if (cors === undefined || cors === "*" || cors === true) {
+ return true;
+ }
+ if (cors === false) {
+ return false;
+ }
+
+ const result: {
+ origin?: "*" | "null" | readonly string[];
+ methods?: "*" | readonly string[];
+ allowHeaders?: "*" | readonly string[];
+ exposeHeaders?: "*" | readonly string[];
+ credentials?: boolean;
+ maxAge?: number | false;
+ preflight?: {
+ statusCode?: number;
+ };
+ } = {};
+
+ if (cors.origin !== undefined) {
+ result.origin = normalizeEveCorsOrigin(cors.origin);
+ }
+ if (cors.methods !== undefined) {
+ result.methods = cors.methods;
+ }
+ if (cors.allowedHeaders !== undefined) {
+ result.allowHeaders = cors.allowedHeaders;
+ }
+ if (cors.exposedHeaders !== undefined) {
+ result.exposeHeaders = cors.exposedHeaders;
+ }
+ if (cors.credentials !== undefined) {
+ result.credentials = cors.credentials;
+ }
+ if (cors.maxAge !== undefined) {
+ result.maxAge = cors.maxAge;
+ }
+ if (cors.preflightStatus !== undefined) {
+ result.preflight = { statusCode: cors.preflightStatus };
+ }
+
+ return result;
+}
+
+function normalizeEveCorsOrigin(
+ origin: NonNullable<EveChannelCorsOptions["origin"]>,
+): "*" | "null" | readonly string[] {
+ if (origin === "*" || origin === "null") {
+ return origin;
+ }
+ if (typeof origin === "string") {
+ return [origin];
+ }
+ return origin;
+}
+
type OnMessageOutcome =
| {
readonly auth: SessionAuthContext | null;
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index e3a1ded98..3b518055d 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -7,6 +7,8 @@ export {
DELETE,
WS,
type Channel,
+ type ChannelCors,
+ type ChannelCorsOptions,
type ChannelDefinition,
type ChannelSessionOps,
type ChannelEvents,
diff --git a/packages/eve/src/public/definitions/defineChannel.test.ts b/packages/eve/src/public/definitions/defineChannel.test.ts
index 0d6029992..8cd3bcd0f 100644
--- a/packages/eve/src/public/definitions/defineChannel.test.ts
+++ b/packages/eve/src/public/definitions/defineChannel.test.ts
@@ -46,6 +46,41 @@ describe("defineChannel", () => {
const adapter = getAdapter(channel);
expect(adapter.kind).toBe("http");
expect(adapter.fetchFile).toBeUndefined();
+ expect(channel.cors).toBeUndefined();
+ });
+
+ it("normalizes channel CORS options", () => {
+ const channel = defineChannel({
+ cors: {
+ allowHeaders: ["authorization", "content-type"],
+ credentials: true,
+ exposeHeaders: ["x-eve-session-id"],
+ maxAge: 600,
+ methods: ["POST"],
+ origin: ["https://app.example.com"],
+ preflight: { statusCode: 200 },
+ },
+ routes: [POST("/x", async () => new Response("ok"))],
+ });
+
+ expect(channel.cors).toEqual({
+ allowHeaders: ["authorization", "content-type"],
+ credentials: true,
+ exposeHeaders: ["x-eve-session-id"],
+ maxAge: "600",
+ methods: ["POST"],
+ origin: ["https://app.example.com"],
+ preflight: { statusCode: 200 },
+ });
+ });
+
+ it("uses an empty options object for permissive CORS", () => {
+ const channel = defineChannel({
+ cors: true,
+ routes: [POST("/x", async () => new Response("ok"))],
+ });
+
+ expect(channel.cors).toEqual({});
});
it("declares websocket routes with an eve-owned route discriminator", () => {
diff --git a/packages/eve/src/public/definitions/defineChannel.ts b/packages/eve/src/public/definitions/defineChannel.ts
index aff40d5b2..60011e3fc 100644
--- a/packages/eve/src/public/definitions/defineChannel.ts
+++ b/packages/eve/src/public/definitions/defineChannel.ts
@@ -4,6 +4,7 @@ import type {
FetchFileResult,
} from "#channel/adapter.js";
import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";
+import { normalizeChannelCors, type ChannelCors, type ChannelCorsOptions } from "#channel/cors.js";
import { defaultDeliverResult } from "#channel/adapter.js";
import { HTTP_ADAPTER_KIND } from "#channel/http.js";
import type { TypedReceiveTarget } from "#channel/receive-target.js";
@@ -17,6 +18,7 @@ import type { Session, SessionHandle } from "#channel/session.js";
declare const CHANNEL_METADATA_TYPE: unique symbol;
export type { Session, SessionHandle } from "#channel/session.js";
+export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
export type {
HttpRouteDefinition,
@@ -115,6 +117,13 @@ export interface ChannelDefinition<
TMetadata extends Record<string, unknown> = Record<string, unknown>,
> {
readonly state?: TState;
+ /**
+ * CORS policy for this channel's HTTP routes. `true` enables H3/Nitro's
+ * permissive defaults (`origin`, methods, request headers, and exposed
+ * headers all `"*"`); `false` or omission leaves CORS untouched. Pass an
+ * object for a serializable subset of H3/Nitro CORS options.
+ */
+ readonly cors?: ChannelCors;
/**
* Builds the per-step channel context handed to `events` and `deliver`.
* Receives the live {@link SessionHandle}, so a factory can close over it to
@@ -178,6 +187,7 @@ export interface Channel<
readonly __kind: typeof CHANNEL_SENTINEL;
readonly [CHANNEL_METADATA_TYPE]?: TMetadata;
readonly routes: readonly RouteDefinition<TState>[];
+ readonly cors?: ChannelCorsOptions;
readonly receive?: (
input: ReceiveInput<TReceiveTarget>,
args: { send: SendFn<TState> },
@@ -206,11 +216,13 @@ export function defineChannel<
definition: ChannelDefinition<TState, TCtx, TReceiveTarget, TMetadata>,
): Channel<TState, TReceiveTarget, TMetadata> {
const adapter = buildAdapter(definition);
+ const cors = normalizeChannelCors(definition.cors);
const compiled: CompiledChannel<TState, TReceiveTarget, TMetadata> = {
__kind: CHANNEL_SENTINEL,
routes: definition.routes,
adapter,
+ cors,
receive: definition.receive,
};
diff --git a/packages/eve/src/runtime/framework-channels/index.ts b/packages/eve/src/runtime/framework-channels/index.ts
index 975540a00..c258fedd3 100644
--- a/packages/eve/src/runtime/framework-channels/index.ts
+++ b/packages/eve/src/runtime/framework-channels/index.ts
@@ -32,6 +32,7 @@ export function getFrameworkChannelDefinitions(): readonly ResolvedChannelDefini
name: EVE_CHANNEL_NAME,
method: route.method.toUpperCase() as "GET" | "POST",
urlPath: route.path,
+ cors: compiled.cors,
fetch: async (req: Request, ctx: any) => route.handler(req, ctx),
handler: route.handler,
adapter: compiled.adapter,
diff --git a/packages/eve/src/runtime/resolve-channel.ts b/packages/eve/src/runtime/resolve-channel.ts
index 8831edb70..358febf58 100644
--- a/packages/eve/src/runtime/resolve-channel.ts
+++ b/packages/eve/src/runtime/resolve-channel.ts
@@ -74,6 +74,7 @@ export async function resolveChannelDefinition(
name: definition.name,
method: definition.method,
urlPath: definition.urlPath,
+ cors: definition.cors,
fetch: async (req: Request, ctx: any) => {
if (httpRoute) return httpRoute.handler(req, ctx);
return Response.json({ error: "No matching route handler.", ok: false }, { status: 404 });
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index 4ec16f788..fee391404 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -2,6 +2,7 @@ import type { FlexibleSchema } from "ai";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { CompiledChannel } from "#channel/compiled-channel.js";
+import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
import type { HeadersValue } from "#client/types.js";
import type { DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
import type { ChannelRouteMethod, RouteContext } from "#public/definitions/channel.js";
@@ -221,6 +222,7 @@ export interface ResolvedChannelDefinition extends ResolvedModuleSourceRef {
readonly name: string;
readonly method: ChannelRouteMethod;
readonly adapter?: ChannelAdapter;
+ readonly cors?: NormalizedChannelCorsOptions;
readonly urlPath: string;
readonly fetch: (req: Request, ctx: RouteContext) => Promise<Response>;
/**