@gjermundgaraba/effect-actions 0.26.1 → 0.28.0

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.
@@ -0,0 +1,45 @@
1
+ import { HttpRouter } from "effect/http";
2
+ /** The public address and additional browser origins accepted by the policy. */
3
+ export interface Options {
4
+ /**
5
+ * The origin browsers reach this app at. The application has already validated it;
6
+ * its `host` (with port, when the scheme's default is not used) must equal the Host
7
+ * header, and its `origin` is the one Origin accepted by default.
8
+ */
9
+ readonly publicUrl: URL;
10
+ /**
11
+ * Origins accepted besides the public one, compared exactly. For a desktop shell
12
+ * whose renderer has a private scheme, such as `wtf://app`. No wildcards.
13
+ */
14
+ readonly allowedOrigins?: readonly string[];
15
+ }
16
+ /** One request, as a Node `upgrade` handler or a router middleware sees it. */
17
+ export interface Request {
18
+ /** The request target: `/a?b` or an absolute URL. Only its path is read. */
19
+ readonly target: string;
20
+ readonly host: string | undefined;
21
+ readonly origin: string | undefined;
22
+ }
23
+ /**
24
+ * Build a Host/Origin policy once at startup. `allows` takes no services, so a
25
+ * raw request or Node upgrade handler applies the same rule as the router.
26
+ * The middleware answers refused requests with status 403 and text `Forbidden`.
27
+ *
28
+ * **Gotchas**
29
+ * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
30
+ * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
31
+ * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
32
+ */
33
+ export declare const make: (options: Options) => {
34
+ allows: (request: Request) => boolean;
35
+ middleware: HttpRouter.Middleware<{
36
+ provides: never;
37
+ handles: never;
38
+ error: never;
39
+ requires: never;
40
+ layerError: never;
41
+ layerRequires: never;
42
+ }>;
43
+ };
44
+ /** A pure request decision and the matching native router middleware. */
45
+ export type Policy = ReturnType<typeof make>;
@@ -0,0 +1,44 @@
1
+ import { Effect } from "effect";
2
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
3
+ // src/http/RequestPolicy.ts
4
+ const uncheckedProbePath = "/healthz";
5
+ const pathOf = (target) => {
6
+ const authority = target.indexOf("://");
7
+ const start = authority === -1 ? 0 : target.indexOf("/", authority + 3);
8
+ if (start === -1) return "/";
9
+ const rest = target.slice(start);
10
+ const stop = rest.search(/[?#]/u);
11
+ return stop === -1 ? rest : rest.slice(0, stop);
12
+ };
13
+ const forbidden = HttpServerResponse.text("Forbidden", { status: 403 });
14
+ /**
15
+ * Build a Host/Origin policy once at startup. `allows` takes no services, so a
16
+ * raw request or Node upgrade handler applies the same rule as the router.
17
+ * The middleware answers refused requests with status 403 and text `Forbidden`.
18
+ *
19
+ * **Gotchas**
20
+ * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
21
+ * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
22
+ * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
23
+ */
24
+ const make = (options) => {
25
+ const { host } = options.publicUrl;
26
+ const origins = /* @__PURE__ */ new Set([options.publicUrl.origin, ...options.allowedOrigins ?? []]);
27
+ const allows = (request) => {
28
+ if (pathOf(request.target) === uncheckedProbePath) return true;
29
+ if (request.host !== host) return false;
30
+ return request.origin === void 0 || origins.has(request.origin);
31
+ };
32
+ return {
33
+ allows,
34
+ middleware: HttpRouter.middleware((httpEffect) => Effect.gen(function* () {
35
+ const request = yield* HttpServerRequest.HttpServerRequest;
36
+ return allows({
37
+ target: request.originalUrl,
38
+ host: request.headers["host"],
39
+ origin: request.headers["origin"]
40
+ }) ? yield* httpEffect : forbidden;
41
+ }))
42
+ };
43
+ };
44
+ export { make };
@@ -110,6 +110,36 @@ Layer.launch(server).pipe(NodeRuntime.runMain());
110
110
 
111
111
  - A service a verifier, handler or authorizer reads per request is provided by router middleware around the layer ([kitchen-sink/src/identity/workspace-header.ts](../examples/kitchen-sink/src/identity/workspace-header.ts), read by the verifier, provided in [kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts)), or, for a handler or authorizer, by `ActionHttp.LayerOptions.middleware`; declaring it, and why not `HttpRouter.provideRequest`, are on `ActionHttp.layer`.
112
112
 
113
+ ### Check Host and Origin
114
+
115
+ Import `@gjermundgaraba/effect-actions/RequestPolicy` to check incoming browser requests against the application's public URL. `RequestPolicy.make` returns `allows` for raw requests or WebSocket upgrades and `middleware` for Effect routes; its JSDoc describes the health-probe exemption and middleware scope, and `RequestPolicy.Options` defines the header comparisons. Access control remains the application's or network's responsibility. A proxy must preserve the public Host header.
116
+
117
+ Build the policy once and provide its middleware to the merged routes before serving them:
118
+
119
+ ```ts example=quickstart/src/request-policy.ts
120
+ import * as RequestPolicy from "@gjermundgaraba/effect-actions/RequestPolicy";
121
+ import { Layer } from "effect";
122
+ import { HttpRouter, HttpServerResponse } from "effect/http";
123
+
124
+ import { routes } from "./routes.js";
125
+
126
+ export const withRequestPolicy = (publicUrl: URL) => {
127
+ const policy = RequestPolicy.make({ publicUrl });
128
+
129
+ const health = HttpRouter.add(
130
+ "GET",
131
+ "/healthz",
132
+ HttpServerResponse.text("ok")
133
+ );
134
+
135
+ return Layer.mergeAll(routes, health).pipe(
136
+ Layer.provide(policy.middleware.layer)
137
+ );
138
+ };
139
+ ```
140
+
141
+ Pass the deployed public URL from the host's configuration to `withRequestPolicy`, then serve its result as in [quickstart/src/server.ts](../examples/quickstart/src/server.ts). For a raw request, pass its target, Host and Origin to `policy.allows`; use `undefined` for absent headers. Allowing an additional browser origin through `RequestPolicy.Options` does not install CORS response headers; configure `HttpRouter.cors` too when the browser needs them.
142
+
113
143
  ### Split a binding across layers, and add middleware
114
144
 
115
145
  Serve each action from exactly one layer. Files: [kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts) (`api`), [kitchen-sink/src/identity/quota.ts](../examples/kitchen-sink/src/identity/quota.ts). Where a check runs decides what it sees:
package/docs/README.md CHANGED
@@ -24,7 +24,7 @@ Where things are, in a project that installs the package: these pages in `node_m
24
24
  | [Action.md](Action.md) | define a contract and who may call it, implement it, authorize calls, fail with declared and built-in errors, answer a retried call once, call actions from a job, share one build across servers |
25
25
  | [Action-streams.md](Action-streams.md) | report progress while an action runs, answer a stream of elements |
26
26
  | [Event.md](Event.md) | define an event type, read it from an upstream you can ask or one that pushes, set up a subscription upstream, watch events in process |
27
- | [ActionHttp.md](ActionHttp.md) | bind actions to JSON routes, serve them, limit request bodies, split a binding across layers and add middleware, publish OpenAPI, call them from Effect or a browser, serve and watch events |
27
+ | [ActionHttp.md](ActionHttp.md) | bind actions to JSON routes, serve them, limit request bodies, check Host and Origin with `RequestPolicy`, split a binding across layers and add middleware, publish OpenAPI, call them from Effect or a browser, serve and watch events |
28
28
  | [ActionMcp.md](ActionMcp.md) | serve MCP tools over HTTP or stdio, describe them to a model, return images, protect them, serve events, allow browser clients, add prompts and resources, send notifications |
29
29
  | [ActionRpc.md](ActionRpc.md) | bind actions to Effect rpcs, serve them on a protocol, call them, add native rpcs, send request context with a call |
30
30
  | [ActionRpc-events.md](ActionRpc-events.md) | serve and watch events over rpcs, follow what a request names, such as a room |
package/docs/setup.md CHANGED
@@ -41,7 +41,7 @@ Node `>=26.12.0`: the package's `engines`, the Node the library is developed and
41
41
 
42
42
  ## Entry points
43
43
 
44
- There is no package root. Import one module per subpath, as a namespace, `import * as Action from "@gjermundgaraba/effect-actions/Action"`. The modules: `Action`, `Event`, `ActionHttp`, `ActionMcp`, `ActionRpc`, `ActionToolkit`, `ActionCli`, `Authentication`, `Webhook`, `Testing`.
44
+ There is no package root. Import one module per subpath, as a namespace, `import * as Action from "@gjermundgaraba/effect-actions/Action"`. The modules: `RequestPolicy`, `Action`, `Event`, `ActionHttp`, `ActionMcp`, `ActionRpc`, `ActionToolkit`, `ActionCli`, `Authentication`, `Webhook`, `Testing`.
45
45
 
46
46
  Effect's own modules are subpaths of `effect` too: `effect/http` (`HttpRouter`, `HttpClient`, `FetchHttpClient`), `effect/http-api` (`OpenApi`, `HttpApiMiddleware`), `effect/rpc` (`RpcServer`, `RpcClient`), `effect/ai` (`LanguageModel`, `Chat`), `effect/cli` (`Command`) and `effect/socket` (`Socket`).
47
47
 
@@ -25,3 +25,5 @@ src/
25
25
  └── client.ts entrypoint
26
26
  test/routes.test.ts the routes, called in memory
27
27
  ```
28
+
29
+ To check browser requests against a configured public URL, serve `withRequestPolicy(publicUrl)` from [src/request-policy.ts](src/request-policy.ts). It wraps all the routes and adds an unchecked health probe; [test/request-policy.test.ts](test/request-policy.test.ts) exercises accepted and refused requests.
@@ -0,0 +1,19 @@
1
+ import * as RequestPolicy from "@gjermundgaraba/effect-actions/RequestPolicy";
2
+ import { Layer } from "effect";
3
+ import { HttpRouter, HttpServerResponse } from "effect/http";
4
+
5
+ import { routes } from "./routes.js";
6
+
7
+ export const withRequestPolicy = (publicUrl: URL) => {
8
+ const policy = RequestPolicy.make({ publicUrl });
9
+
10
+ const health = HttpRouter.add(
11
+ "GET",
12
+ "/healthz",
13
+ HttpServerResponse.text("ok")
14
+ );
15
+
16
+ return Layer.mergeAll(routes, health).pipe(
17
+ Layer.provide(policy.middleware.layer)
18
+ );
19
+ };
@@ -0,0 +1,48 @@
1
+ import { describe, expect, it } from "@effect/vitest";
2
+ import { Layer } from "effect";
3
+ import { HttpRouter, HttpServer } from "effect/http";
4
+
5
+ import { withRequestPolicy } from "../src/request-policy.js";
6
+
7
+ describe("the quickstart request policy", () => {
8
+ it("guards the quickstart routes and leaves the health probe reachable", async () => {
9
+ const web = HttpRouter.toWebHandler(
10
+ withRequestPolicy(new URL("https://greetings.example")).pipe(
11
+ Layer.provide(HttpServer.layerServices)
12
+ ),
13
+ { disableLogger: true }
14
+ );
15
+
16
+ try {
17
+ for (const [host, origin, status, body] of [
18
+ [
19
+ "greetings.example",
20
+ "https://greetings.example",
21
+ 200,
22
+ '"Hello, Ada!"',
23
+ ],
24
+ ["other.example", "https://greetings.example", 403, "Forbidden"],
25
+ ["greetings.example", "https://other.example", 403, "Forbidden"],
26
+ ] as const) {
27
+ const response = await web.handler(
28
+ new Request("https://greetings.example/api/greet", {
29
+ method: "POST",
30
+ headers: { host, origin, "content-type": "application/json" },
31
+ body: JSON.stringify({ name: "Ada" }),
32
+ })
33
+ );
34
+
35
+ expect(response.status).toBe(status);
36
+
37
+ await expect(response.text()).resolves.toBe(body);
38
+ }
39
+
40
+ const health = await web.handler(new Request("https://internal/healthz"));
41
+
42
+ expect(health.status).toBe(200);
43
+ await expect(health.text()).resolves.toBe("ok");
44
+ } finally {
45
+ await web.dispose();
46
+ }
47
+ });
48
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.26.1",
3
+ "version": "0.28.0",
4
4
  "description": "Define Effect action contracts once and project them onto HTTP, MCP, Effect RPC, native Toolkits, and CLIs.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -43,6 +43,7 @@
43
43
  "./ActionToolkit": "./dist/ActionToolkit.mjs",
44
44
  "./Authentication": "./dist/Authentication.mjs",
45
45
  "./Event": "./dist/Event.mjs",
46
+ "./RequestPolicy": "./dist/RequestPolicy.mjs",
46
47
  "./Testing": "./dist/Testing.mjs",
47
48
  "./Webhook": "./dist/Webhook.mjs",
48
49
  "./package.json": "./package.json"