Skip to content

A Plain Endpoint Behind Your Own Session

Running level none in production: TLS protects the bytes, your own sign-in says who the user is. What the library checks for you, what is yours, and in what order.

Level none is a production posture, not only a development one. TLS protects the bytes on the wire. Your app’s own sign-in, usually a session cookie, says who the user is. The library checks the door and seals what a failure tells the client. It is also the answer for browsers without the newer curves (Browser Support).

At level none no handshake proves who is calling, so nothing the request says about its caller can be trusted:

  • ctx.origin, in a handler, is what the request claims. A request that names itself admin is handed to the handler as admin.
  • ctx.authenticatedOrigin is undefined. It is set only for a caller a handshake proved.
  • ctx.securityLevel is "none".

So who the user is comes from your session, checked before the request reaches the server, and never from the request.

import { refuseUnlistedOrigin } from "@nice-code/action";
import { serveWorker } from "@nice-code/action/platform/cloudflare";
const ALLOWED = ["https://app.example.com"];
const server = serveWorker(appChannel, {
identity: serverCoord,
secure: false,
allowedOrigins: ALLOWED,
cors: false,
handlers: [appHandler],
});
export default {
async fetch(request: Request, env: Env) {
const refused = refuseUnlistedOrigin(request, ALLOWED);
if (refused != null) return refused;
const user = await readSession(request, env);
if (user == null) return new Response("Sign in", { status: 401 });
return server.fetch(request);
},
};
  1. Another site’s request is refused, 403. A browser sends your cookie with a cross-site request where the cookie allows it, and with a socket upgrade from any site. allowedOrigins refuses a request whose Origin is not yours. refuseUnlistedOrigin is the same check, called first so that another site’s request costs you no session lookup. A request with no Origin passes: only a browser sends one.
  2. Your session check. Read the cookie, find the user, and answer 401 without one.
  3. The content type, 415. An action POST needs Content-Type: application/json, which keeps out the “simple” cross-site POST that a browser sends with no preflight. On by default.
  4. The size, 413. maxBodyBytes, 1 MiB by default, checked before the body is parsed.
  5. The handler.

Steps 3 and 4 run inside server.fetch, before any handler. Then:

  • Set cors to false when the page and the endpoint share an origin, as a cookie session usually does. Otherwise set it to headers that name your page’s origin in place of *. The defaults are Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET, POST, OPTIONS, Access-Control-Allow-Headers: Content-Type and Access-Control-Max-Age: 86400, and a cors you pass replaces all four.
  • Set the session cookie’s SameSite yourself, to Lax or Strict, with HttpOnly and Secure. Do not rely on a browser’s default.

A handler is not given the request, so the user your session check found has to reach it another way. Carry it in AsyncLocalStorage, where your runtime has it: Node, Bun, and Cloudflare Workers with the nodejs_als or nodejs_compat compatibility flag.

import { AsyncLocalStorage } from "node:async_hooks";
export const signedIn = new AsyncLocalStorage<IUser>();
// In fetch, after the session check:
return signedIn.run(user, () => server.fetch(request));
// In a handler:
getJobs: async ({ day }) => {
const user = signedIn.getStore();
if (user == null) throw err_app.fromId("signed_out");
return jobsFor(user, day);
},

Each request keeps its own user, however many run at once through one server. Without AsyncLocalStorage, build the handlers inside fetch for each request, with the user in scope.

An endpoint that serves the secure levels also serves level none by default: securityLevel defaults to all three. So one endpoint can serve a secure office screen and a plain phone, and “this endpoint is authenticated” is not an access rule. A handler that needs a proven device reads ctx.authenticatedOrigin. To refuse plain callers, leave none out:

serveChannel(appChannel, {
identity: serverCoord,
storage,
securityLevel: [ESecurityLevel.authenticated, ESecurityLevel.encrypted],
carriers: [httpAcceptorCarrier()],
handlers: [appHandler],
});

What a client is told when a handler fails

Section titled “What a client is told when a handler fails”

Only what the action declared with .throws(), and the refusal of its input. Anything else, a thrown database error included, reaches the client as one fixed error, the sealed failure, and the detail stays in your server’s log under the request’s cuid. That is the default, and What a server tells its caller has the table and the setting.

Give the user the cuid to quote, never the error’s message. Over HTTP the client holds the same cuid as request.context.cuid.

The server keeps what it sealed. Pass a logger and its result info carries thrown, the error as the server holds it, beside the request’s cuid; with no logger, each sealed failure goes to console.error with both. See Logging served requests.

To log at the source instead, wrap a handler: log what it caught against ctx.cuid, and throw an error the client may see in its place.

import { sealedFailure } from "@nice-code/error";
closeJob: async ({ jobId }, ctx) => {
try {
return await jobs.close(jobId);
} catch (caught) {
log.error({ cuid: ctx.cuid, caught });
throw sealedFailure();
}
},

A Worker that forwards a socket upgrade to a Durable Object refuses another site’s upgrade there, before the object is woken. The forwarder takes the same list:

forwardToDurableObject(({ params }) => env.ROOM.get(env.ROOM.idFromString(params.id)), {
allowedOrigins: ["https://app.example.com"],
});

The routing around it is on Cloudflare Durable Objects.

  • allowedOrigins set, on the server and on any forwarder in front of it.
  • Your session check in front of server.fetch, answering 401 without a user.
  • cors: false, or your own origin.
  • The session cookie SameSite=Lax or Strict, HttpOnly, Secure, set explicitly.
  • maxBodyBytes raised only on an endpoint that needs it.
  • The user’s identity read from your session in the handler, never from ctx.origin.
  • A logger, or your own logging, so a sealed failure can be found by its cuid.