Skip to content
DocsconceptsDocumentation

Security

Lunora's secure-by-default posture — the protections you get for free, how to opt out, and the advisor lints that catch the gaps.

Last updated:

Lunora is secure by default. The edge protections, auth-cookie hardening, and input guards described below are on the moment you run createWorker. You don't opt in to them, you opt out. Every layer can be disabled individually for the rare case that needs it, and the advisors flag the gaps that defaults can't close on their own (a public mutation with no rate limit, a v.any() argument, a secret checked into source).

This page covers the framework defaults, the public helpers, and the full security advisor catalog with remediation.

The HTTP edge

The worker's top-level fetch is the choke point every response the Worker produces passes through: RPC, auth, admin, httpRoute handlers, and the SSR fallback alike. Static assets are the exception, covered below. Three layers are applied there, all on by default and configured through the security option on createWorker. None ever overwrites a header or decision an inner handler already made; defaults fill in, they never clobber.

Baseline response headers

Added to every response when the inner handler didn't set them:

HeaderDefault
Strict-Transport-Securitymax-age=31536000; includeSubDomains (HTTPS responses only)
X-Content-Type-Optionsnosniff
X-Frame-OptionsSAMEORIGIN
Referrer-Policystrict-origin-when-cross-origin
Permissions-Policya minimal deny list (camera, microphone, geolocation, payment, …)
Cross-Origin-Opener-Policysame-origin-allow-popups (why)
Content-Security-Policystrict on non-HTML responses, a hardening-only policy on HTML (below)

Non-HTML (API/JSON) responses get the strict default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'. HTML responses get the HTML policy, base-uri 'none'; object-src 'none'; frame-ancestors 'self' ('none' when frameOptions is DENY). It sets no default-src or script-src, so an SSR page is never broken by a policy it didn't opt into.

Configuring the headers

Set them in lunora.config.ts. That one value reaches both places headers are sent: codegen hands it to the Worker, and the build writes the same values into the static assets' _headers (see Static assets below).

// lunora.config.ts
import type { LunoraConfig } from "./lunora/_generated/app";

export default {
    security: {
        headers: {
            // Let listed origins embed your pages in a frame (drops X-Frame-Options,
            // which cannot express a list; frame-ancestors carries it instead).
            frameAncestors: ["https://partner.example"],
            crossOriginOpenerPolicy: "same-origin-allow-popups",
            hsts: { maxAge: 63072000, preload: true },
            permissionsPolicy: false, // omit one header
        },
    },
} satisfies LunoraConfig;
OptionValues
crossOriginOpenerPolicy"same-origin-allow-popups" (default), "same-origin", "unsafe-none", false
frameAncestorsorigins allowed to frame your HTML pages, e.g. ["https://a.example"]
frameOptions"SAMEORIGIN" (default), "DENY", false
cspone policy string for every response, or false
hststrue, false, or { maxAge, includeSubDomains, preload }
permissionsPolicya policy string, or false
referrerPolicya policy string, or false

headers: false turns the whole layer off. A csp string replaces both default policies, so it cannot be combined with frameAncestors; put the frame-ancestors directive in it instead.

The values must be literals, because codegen and the build read the file without running it. Codegen, the build and createWorker check them the same way: an unknown key (a typo such as frameOption), a value of the wrong type or outside the header's values (frameOptions: "ALLOW", hsts: { maxAge: "1y" }), a value that would break a header line, or a frameAncestors entry that is not an origin. In lunora.config, an unknown key or a value of the wrong kind (csp: true, hsts: { maxAge: "1y" }, frameAncestors: "https://partner.example") stops codegen with PROJECT_CONFIG_INVALID. Any other such value, or one codegen cannot read, is reported and the defaults apply. Passed to createWorker in code, it throws when the Worker is built.

Precedence. A security.headers passed in code (to createWorker, or through .extend()) wins over lunora.config, which wins over LUNORA_SECURITY_HEADERS=off in wrangler vars. The build can only see the last two, so code-level headers do not reach the static assets. Keep them in lunora.config unless you need to compute them.

An app built with the generated defineApp() gets the config value with no wiring. An app that calls createWorker itself passes it on. _generated/app exports LUNORA_SECURITY_HEADERS only while lunora.config sets security.headers:

import { LUNORA_SECURITY_HEADERS } from "../lunora/_generated/app";

createWorker({ /* … */ security: { headers: LUNORA_SECURITY_HEADERS } });

OAuth and payment popups

Cross-Origin-Opener-Policy decides whether a popup can talk back to the page that opened it. Lunora defaults to same-origin-allow-popups:

  • A cross-origin page that opens your app gets no handle on it.
  • A popup your page opens (an OAuth provider, a payment sheet) keeps window.opener, so the provider's SDK can post its result back.

same-origin would sever that link and break those SDKs. Lunora sends no Cross-Origin-Embedder-Policy, so same-origin would not buy cross-origin isolation either.

:::note[Changed default] Up to @lunora/runtime 1.0.0-alpha.277 the default was same-origin. An app that relied on it, for example to keep a page it opens from reaching back through window.opener, sets crossOriginOpenerPolicy: "same-origin" in lunora.config. :::

If the popup ends on a callback page you serve, which then calls window.opener.postMessage(...), that page needs unsafe-none. When the popup navigates from the provider to your callback, any other value on the callback response moves the popup into a new browsing context group, and window.opener becomes null. (Checked in Chromium for both same-origin-allow-popups and same-origin.) Set it on that one response, not globally:

  • A Worker route: set the header in the handler. Inner handlers win over the defaults.

    return new Response(html, {
        headers: { "content-type": "text/html", "cross-origin-opener-policy": "unsafe-none" },
    });
  • A static page: detach the default and set your own in public/_headers:

    /auth/popup-callback
      ! Cross-Origin-Opener-Policy
      Cross-Origin-Opener-Policy: unsafe-none

A page that is itself opened by another site's popup flow, or that must keep working with a third-party opener, can set crossOriginOpenerPolicy: "unsafe-none" in lunora.config, at the cost of the protection above.

Static assets

Cloudflare serves a file from the static assets directory without running the Worker. That covers your JS and CSS chunks, the SPA shell, and prerendered pages. The fetch above never sees those responses, so on its own it cannot add headers to them.

Instead, the production build writes the same headers into the assets' _headers file, which Cloudflare applies to asset responses only. With the defaults:

# BEGIN lunora-managed: rewritten on every build. Put your own rules outside this block.
/*
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  X-Content-Type-Options: nosniff
  X-Frame-Options: SAMEORIGIN
  Referrer-Policy: strict-origin-when-cross-origin
  Permissions-Policy: accelerometer=(), autoplay=(), camera=(), …
  Cross-Origin-Opener-Policy: same-origin-allow-popups
  Content-Security-Policy: base-uri 'none'; object-src 'none'; frame-ancestors 'self'
# END lunora-managed

A few things differ from the Worker's layer:

  • The CSP is the HTML policy for every file. _headers matches paths, not content types, and the strict non-HTML policy would stop a static page from loading its own scripts.
  • HSTS is sent on every response. Browsers ignore it over plain HTTP, so local development is not pinned to HTTPS.
  • No CORS headers. Static files are served to your own origin.
  • Only lunora.config and wrangler vars reach it. See the precedence above.

Your own rules in public/_headers are kept as written. The managed block goes at the top of the file, and Lunora rewrites only what sits between its two markers. Cloudflare sends both values when two matching rules set the same header (for example DENY and SAMEORIGIN), and browsers reject that. So:

  • A header one of your rules for /* sets is left out of the block. Your value applies everywhere. When that header is X-Frame-Options, the block's CSP also drops its frame-ancestors directive, which browsers would apply instead of your value.
  • For narrower paths, detach the default first, then set yours, as in the popup-callback example above. A detach only removes a header an earlier rule added, which is why the block comes first. A narrower rule that sets a managed header without detaching it is reported at build time.
/embed/*
  ! X-Frame-Options

A detach alone does not hold on a single-page app whose Worker serves its files, because the Worker adds a missing security header back. There, detach and set the value you want in the same rule.

Cloudflare applies at most 100 rules from _headers and ignores a line longer than 2,000 characters. Your rules come first in that count: when the file already holds your 100, the block is left out (with a warning) instead of pushing one of yours past the cap. A managed header line that would be too long, such as a CSP from a long frameAncestors list, fails the build, since the static pages would otherwise ship without it.

The block is written on a production build for the Cloudflare target, by whichever integration produced the output:

BuildWhereImmutable caching
@lunora/vite with @cloudflare/vite-plugin in the buildthe client environment's outDirbuild.assetsDir (assets/)
@lunora/rspack/rsbuildeach environment output that is assets.directorystatic/, when output.filenameHash is on
@lunora/nuxtNitro's public output, after Nitro's own rulesnone: Nitro manages _nuxt/ caching
@lunora/astrothe client output (astro:build:done)build.assets (_astro/)

Apart from the Vite path, whose client outDir is by definition what @cloudflare/vite-plugin uploads, the block is only written when the output is the assets.directory your wrangler config deploys (or the CLOUDFLARE_ENV block's own); anywhere else _headers would be published as a file. The plain Rspack/webpack plugin (lunoraRspack()) and Analog write none: their output layout is the project's own. Add the headers to their _headers yourself.

CORS: deny cross-origin by default

Cross-origin requests are denied unless you name an allowlist. There is no wildcard fallback:

createWorker({
    security: {
        cors: {
            allowedOrigins: ["https://app.example.com"], // or a predicate
            allowCredentials: true,
        },
    },
});

When you don't pass security.cors in code, the worker falls back to env config: LUNORA_ALLOWED_ORIGINS is a comma-separated allowlist and LUNORA_CORS_ALLOW_CREDENTIALS (true/on/1) opts credentials in. This lets a deployment set its origins through wrangler vars without a code change. Code config always wins: an explicit security.cors ignores the env vars entirely.

A * wildcard combined with credentials is rejected: browsers refuse the combination and it defeats the allowlist. Set in code it throws at construction; set through the env vars the worker keeps serving the allowlist but silently drops credentials (it can't throw in the request path), and the @lunora/config validator catches the same mistake at build time. Preflight (OPTIONS) is answered automatically for allowlisted origins.

CSRF / origin guard

State-changing, cookie-authenticated requests whose Origin/Referer is neither same-origin nor allowlisted are rejected with 403. The guard is scoped deliberately to cookie-bearing browser requests, the only vector a cross-site forgery can ride. Bearer-token and server-to-server traffic (no Cookie header) is exempt, as are safe methods (GET/HEAD/OPTIONS).

createWorker({
    security: {
        csrf: { trustedOrigins: ["https://admin.example.com"] }, // or `false` to disable
    },
});

The /_lunora/ws WebSocket upgrade is gated the same way: a cross-origin, cookie-bearing handshake is rejected before the socket opens, closing the Cross-Site WebSocket Hijacking (CSWSH) hole where a hostile page rides the victim's session cookie into a live subscription. Same-origin and bearer-token handshakes are unaffected. A genuinely cross-origin, cookie-authenticated client must add its origin to csrf.trustedOrigins, the same allowlist the HTTP guard reads.

Body cap

Request bodies on the planes the framework itself dispatches — the reserved /_lunora/* surface (RPC, REST, admin, import/export) and the /api/auth/* plane — are capped at 1 MiB before they reach a handler, so an oversized upload can't exhaust the worker's memory. This is always on, and a few routes that move real bytes declare a larger budget of their own (the Studio's KV value PUT, the storage object upload).

Your own httpRouter routes are not capped: the request body is yours to read, so the budget is yours to choose. Read it with a limit if the route accepts uploads.

Auth, cookies, and secrets

createAuth (@lunora/auth) hardens better-auth's defaults unless you override them:

  • Cookie attributes: httpOnly: true, sameSite: "lax", path: "/" are filled in when you don't supply advanced.defaultCookieAttributes.
  • Secure cookies: useSecureCookies is forced on for an HTTPS baseURL.
  • Auth secret strength: AUTH_SECRET shorter than 32 characters throws at construction, pointing at openssl rand -hex 32. The one exception is an explicitly http:// baseURL — a local dev origin — where it logs a warning instead so a prototype isn't blocked. An unset baseURL and any https:// one both count as production and throw, so a weak secret 500s every request rather than shipping. A missing secret throws everywhere.

Protecting public procedures

protectPublic (@lunora/server) is thin sugar that chains the recommended guards (a rate limit, then a CAPTCHA) into one .use()-able middleware. It is the recommended wrapper for any public mutation that creates users, sends mail, or consumes credits:

import { protectPublic } from "lunorash/server";
import { rateLimit } from "@lunora/ratelimit";
import { verifyTurnstileMiddleware } from "@lunora/auth";

export const signUp = mutation
    .use(
        protectPublic({
            rateLimit: rateLimit(limiter, "signup"),
            captcha: verifyTurnstileMiddleware({ secret: env.TURNSTILE_SECRET_KEY, token: (c) => c.args.captchaToken }),
        }),
    )
    .mutation(async ({ ctx, args }) => {
        /* ... */
    });

The rate limit runs first (the cheapest gate, shedding obvious floods before the Turnstile round-trip). Omitted fields are skipped; an empty bundle passes through unchanged.

Securing sharded access

The moment an app shards, the shard key becomes a client-supplied address, so cross-shard reads must be authorized. Lunora default-denies them: a request naming a non-default shard (shardKey !== defaultShard) or a fan-out is rejected with 403 (FORBIDDEN_SHARD / FORBIDDEN_FANOUT). A single Durable Object (DO) app never names a non-default shard and is unaffected.

A sharded app must either configure authorizeShard({ identity, shardKey }) (return true to allow), plus authorizeFanOut for cross-shard reads, or set allowUnauthenticatedShardAccess: true to opt into open access:

createWorker({
    shardDO: env.SHARD,
    // Runs for every shard the caller names, the default one included — so an
    // unsharded table (which resolves to `__root__`) needs an explicit pass, or
    // this gate 403s it. See [Sharding](/docs/concepts/sharding).
    authorizeShard: ({ identity, shardKey }) => shardKey === "__root__" || identity?.userId === shardKey,
});

allowUnauthenticatedShardAccess: true is only safe when every table is protected by per-row row-level security (RLS), so each row authorizes itself regardless of which DO served it. See Securing shard access for the full picture.

Advisor catalog

Every protection above has a matching advisor lint, so an app that opts out, or never opted in, is warned at build time. The static lints run on every lunora dev save and on deploy.

LintLevelRemediation
hardcoded_secreterrorRotate the leaked value and move it to a wrangler secret / binding, never source.
sql_injection_riskerrorKeep ctx.sql text constant and pass request input in the params array, never by concatenation.
rls_uncovered_tablewarnAdd .use(rls(...)) to the public procedure, matching the policy used elsewhere.
mask_uncovered_pii_columnwarnAdd .use(mask(...)) so the public read redacts the same columns as elsewhere.
auth_api_call_without_headerswarnPass headers to ctx.authApi.<method>(...) so better-auth authorizes the session.
public_mutation_without_ratelimitwarnWrap the public write with protectPublic({ rateLimit }) or attach rateLimit(...).
user_creating_mutation_without_captchawarnAdd verifyTurnstile / protectPublic({ captcha }) to the user-creating procedure.
public_arg_uses_anywarnReplace the v.any() argument with a concrete validator.
admin_route_without_guardwarnReference an auth/admin guard in the privileged httpRoute handler.
unbounded_string_arginfoAdd a max-length .check to the public string argument.
container_public_internetinfoSet enableInternet: false on the container if it needs no outbound egress.

Deployment-level findings

A second set is computed at runtime from the Worker env and surfaces in the Studio's Security Advisor panel. These observe the live deployment rather than the source, so they only fire once a LUNORA_ADMIN_TOKEN gates introspection:

FindingLevelFires when
admin-token-weakwarnLUNORA_ADMIN_TOKEN is set but shorter than 24 chars.
auth-secret-weakwarnAUTH_SECRET / BETTER_AUTH_SECRET is set but shorter than 32 chars.
ws-gate-openwarn*LUNORA_WS_BEARER is unset, so the WebSocket upgrade gate is open to any caller.
cors-wildcard-credentialserrorLUNORA_ALLOWED_ORIGINS includes * while LUNORA_CORS_ALLOW_CREDENTIALS is on.
security-headers-disabledwarnLUNORA_SECURITY_HEADERS is off on a production worker.
csrf-disabledwarnLUNORA_SECURITY_CSRF is off on a production worker.
cookies-insecurewarnBETTER_AUTH_URL is a plaintext http:// origin on a production worker.
dev-args-unredactedwarnThe worker reports a dev environment, so the request log keeps un-redacted args/identity.
* downgraded to info on a local dev worker, where an open gate is expected.

The LUNORA_SECURITY_HEADERS and LUNORA_SECURITY_CSRF env vars are the env-level opt-outs for the corresponding security layers; setting either to off/false/0 relaxes the secure default. Code config always wins: an explicit security.headers / security.csrf in createWorker overrides the env knob, so the audit and the running worker never disagree.

Config-time validation

@lunora/config's wrangler validator (run by the CLI and Vite plugin on every build) rejects the wildcard-CORS-with-credentials combination when it is driven through wrangler vars:

{
    "vars": {
        "LUNORA_ALLOWED_ORIGINS": "*",
        "LUNORA_CORS_ALLOW_CREDENTIALS": "true", // ← build fails here
    },
}

This is the build-time twin of the runtime construction throw, so the misconfiguration surfaces before you deploy.