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).
What level none does not give you
Section titled “What level none does not give you”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 itselfadminis handed to the handler asadmin.ctx.authenticatedOriginisundefined. It is set only for a caller a handshake proved.ctx.securityLevelis"none".
So who the user is comes from your session, checked before the request reaches the server, and never from the request.
In the order a request meets it
Section titled “In the order a request meets it”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); },};- 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.allowedOriginsrefuses a request whoseOriginis not yours.refuseUnlistedOriginis the same check, called first so that another site’s request costs you no session lookup. A request with noOriginpasses: only a browser sends one. - Your session check. Read the cookie, find the user, and answer
401without one. - The content type,
415. An action POST needsContent-Type: application/json, which keeps out the “simple” cross-site POST that a browser sends with no preflight. On by default. - The size,
413.maxBodyBytes, 1 MiB by default, checked before the body is parsed. - The handler.
Steps 3 and 4 run inside server.fetch, before any handler. Then:
- Set
corstofalsewhen 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 areAccess-Control-Allow-Origin: *,Access-Control-Allow-Methods: GET, POST, OPTIONS,Access-Control-Allow-Headers: Content-TypeandAccess-Control-Max-Age: 86400, and acorsyou pass replaces all four. - Set the session cookie’s
SameSiteyourself, toLaxorStrict, withHttpOnlyandSecure. Do not rely on a browser’s default.
Telling a handler who is signed in
Section titled “Telling a handler who is signed in”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.
A secure endpoint takes plain callers too
Section titled “A secure endpoint takes plain callers too”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.
Log where it fails
Section titled “Log where it fails”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 socket upgrade through a Worker
Section titled “A socket upgrade through a Worker”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.
Checklist
Section titled “Checklist”allowedOriginsset, on the server and on any forwarder in front of it.- Your session check in front of
server.fetch, answering401without a user. cors: false, or your own origin.- The session cookie
SameSite=LaxorStrict,HttpOnly,Secure, set explicitly. maxBodyBytesraised 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 itscuid.