`, so no `style`, `class`,
* `on*` handler, or `data-*` attribute survives.
* - An `href` must be absolute HTTP, HTTPS, or `mailto`. A link without one is
* unwrapped to its text, and a link with one gets
* `rel="noopener noreferrer nofollow"` ({@link MODEL_LINK_REL}).
*
* Synchronous and never throws, like {@link sanitizeRichHtml}, and a plain
* `(html) => string`, so you can pass it anywhere a route takes a `sanitize`
* function.
*/
declare function sanitizeModelHtml(html: string): string;
//#endregion
//#region src/core/security/text.d.ts
interface PlainTextOptions {
/**
* Decode-then-strip rounds before giving up. Stored copy that has been
* through an editor, a JSON column and a second encode holds `<p>`,
* which one decode turns INTO a tag; repeating to a fixed point strips it.
* The cap stops a crafted `&amp;lt;` chain from spinning. Default 3.
*/
maxPasses?: number;
}
/**
* Editor HTML flattened to one line of text: tags and comments removed (each
* replaced by a space, so `One
Two
` reads "One Two"), entities
* decoded, whitespace collapsed, trimmed.
*/
declare function plainText(html: string | null | undefined, options?: PlainTextOptions): string;
interface MetaDescriptionOptions extends PlainTextOptions {
/**
* Clamp to this many characters, ellipsis included, cut on a word boundary.
* Default `SEO_DESCRIPTION_MAX` (155)—about where search results truncate.
* Past it, the tag is bytes nobody reads.
*/
maxLength?: number;
}
/**
* Rich text as a meta description (or any attribute that prints its value):
* {@link plainText}, clamped to `maxLength` on a word boundary.
*
* `undefined`—not `""`—for input that is empty or was nothing but markup,
* so the caller falls back to a default. An empty `content=""` tells a crawler
* the page is described, as nothing.
*/
declare function metaDescription(html: string | null | undefined, options?: MetaDescriptionOptions): string | undefined;
/**
* Does this rich-text field have anything in it—text, or an embedded image,
* video, iframe or SVG? `false` for `null`, `""` and markup-only leftovers
* such as ``, `
` or `
`.
*
* Decodes one level only, so copy that literally says `` (stored as
* `<p>`) counts as text.
*/
declare function hasRichText(html: string | null | undefined): boolean;
/**
* Remove headings with nothing in them (by {@link hasRichText}). A screen
* reader lists every heading on a page, and an empty one is a nameless entry
* that goes nowhere. Run it on sanitized output:
* `stripEmptyHeadings(sanitizeRichHtml(html))`.
*/
declare function stripEmptyHeadings(html: string): string;
//#endregion
//#region src/core/auth/guard.d.ts
/**
* Same-origin (CSRF) check for cookie-authenticated mutations. Requires a
* same-origin `Origin` header, falling back to `Referer`, and *rejects when
* neither is present*—so a non-browser client (or a stripped header) can't
* proceed on the session cookie alone. Browsers always send `Origin` on
* cross-origin writes, so legitimate same-origin editor requests are unaffected.
*/
declare function isSameOrigin(request: Request): boolean;
/** A request plus its middleware-resolved editor session. */
interface EditorRequest {
request: Request;
editor: EditorSession | null;
}
/**
* Guard for editor-gated endpoints: a same-origin check on mutations
* (cookie-authenticated writes) plus a resolved editor session. Returns an
* error `Response`, or null when the request may proceed.
*/
declare function requireEditor(ctx: EditorRequest, mutation?: boolean): Response | null;
/** The framework-`context`-shaped slice the editor guard needs: the request
* plus the middleware-resolved editor on `locals`. Structural on purpose, so a
* site passes its own request context straight through—no framework type
* dependency here. */
interface EditorContext {
request: Request;
locals: {
editor?: EditorSession | null;
};
}
/**
* Context adapter over {@link requireEditor}: bridges a framework `context`
* (`{ request, locals.editor }`) to the package's `{ request, editor }` shape,
* so an editor-gated framework route is a one-liner—`const
* denied = requireEditorFromContext(context); if (denied) return denied;`
* rather than each site re-declaring the same bridge in its own `lib/guard`.
* A framework's route context fits as-is once its locals declare `editor`.
*
* `mutation` defaults to the request's method: a write (anything but
* GET/HEAD/OPTIONS) gets the same-origin check, a read does not. Pass it
* explicitly to override—for example, `true` for a GET that has side effects.
*/
declare function requireEditorFromContext(ctx: EditorContext, mutation?: boolean): Response | null;
/**
* A post-sign-in `?next=` target reduced to a same-origin path, or `fallback`.
*
* Handing `next` to `location.assign` or a redirect unchecked is an open
* redirect (`?next=https://evil.example`) and, in a browser, script execution
* (`?next=javascript:…`). A regex over the raw string is not enough: browsers
* strip tab and newline characters and read `\` as `/`, so `/%09/evil.example`
* and `/\evil.example` both become `//evil.example`: protocol-relative, that is,
* off-site. This resolves `raw` with the WHATWG URL parser, the same algorithm
* the browser will apply, against a placeholder origin, and accepts it only if
* it stayed on that origin. What comes back is the normalized path + query +
* hash, never the caller's original string.
*
* Staying on the origin isn't enough on its own. The parser resolves `.` and
* `..` segments and reads `\` as `/`, so `/.//evil.example` and
* `/a/..\\evil.example` both stay on the placeholder origin with the pathname
* `//evil.example`, which is off-site once the browser reads it. A normalized
* pathname that starts with `//` falls back too.
*
* `fallback` is required: where a user lands by default is the site's call.
*/
declare function safeNextPath(raw: string | null | undefined, fallback: string): string;
/** True when `role` is one of `allowed`. Roles are arbitrary, site-defined
* strings; Louise bakes none in. */
declare function hasRole(role: string | null | undefined, allowed: readonly string[]): boolean;
/** A request plus the current user's resolved role (from a session). */
interface RoleRequest {
request: Request;
role: string | null | undefined;
}
/**
* Guard for role-gated endpoints: a same-origin (CSRF) check on mutations plus
* a membership test of the session's `role` against `allowed`. Returns 401 when
* unauthenticated, 403 on a wrong role or bad origin, or null to proceed.
* Generic and unopinionated—it works with any site's roles and any auth
* instance; the content editor gate is the binary {@link requireEditor}.
*/
declare function requireRole(ctx: RoleRequest, allowed: readonly string[], mutation?: boolean): Response | null;
/** Copy only allowlisted keys from a payload. */
declare function pick(input: Record, allow: Set): Record;
//#endregion
//#region src/core/security/types.d.ts
/** The subset of a Cloudflare Secrets Store binding Louise reads. */
interface SecretBinding {
get(): Promise;
}
/**
* Minimal Workers KV shape the rate limiter needs—`get` + `put` with a TTL.
* Declared structurally so the real `KVNamespace` (from `@cloudflare/workers-types`)
* satisfies it without a hard dependency on those types.
*/
interface KVLike {
get(key: string): Promise;
put(key: string, value: string, options?: {
expirationTtl?: number;
}): Promise;
}
/**
* The subset of Cloudflare's native Rate Limiting binding Louise uses. Unlike
* the KV limiter, the budget (limit + period) is fixed in wrangler config on
* the binding itself—at runtime you only pass a `key`, and the response is
* just `{ success }` (no remaining/retryAfter). It's in-colo (no round-trip)
* and cheaper, but permissive/eventually-consistent like KV. Declared
* structurally so the real binding satisfies it without a hard dependency on
* `@cloudflare/workers-types`.
*/
interface RateLimiterBinding {
limit(options: {
key: string;
}): Promise<{
success: boolean;
}>;
}
/**
* Either backend the rate limiter accepts: the KV counter (portable, budget set
* per call) or the native binding (in-colo, budget fixed in config). Callers
* pass whichever they have—typically `env.RATE_LIMIT ?? env.KV`—so a site
* gains the native path just by provisioning the binding, and falls back to KV
* otherwise.
*/
type RateLimitBackend = KVLike | RateLimiterBinding;
/**
* Base binding contract the Louise security primitives expect on a Worker's
* `env`. A site's own `Env` can `extends LouiseEnv`; the auth extraction (#7)
* widens this into the full `LouiseAuthEnv` surface.
*/
interface LouiseEnv {
/**
* Session-signing secret. Either a Secrets Store binding or the plain string a
* `wrangler secret put` produces—`getSessionSecret` reads both, so a site
* picks whichever it provisioned rather than the one Louise happened to name.
*/
SESSION_SECRET: SecretBinding | string;
}
//#endregion
//#region src/core/security/rate-limit.d.ts
interface RateLimitResult {
ok: boolean;
/** Requests left in the current window (0 when blocked). */
remaining: number;
/** Seconds until the current window resets (for Retry-After). */
retryAfter: number;
}
/**
* Consume one unit against `key`'s current window. Returns `ok: false` once the
* budget is reached. Fails open on any backend error.
*
* The `backend` is either a KV binding or Cloudflare's native Rate Limiting
* binding:
* - **KV**—`windowSec` must be ≥ 60 (KV's minimum TTL); `limit`/`windowSec`
* define the budget here, and the result's `remaining`/`retryAfter` are exact.
* - **native binding**—the budget lives in wrangler config, so `limit` and
* `windowSec` are *advisory* (ignored beyond the key); `remaining` is
* best-effort and `retryAfter` is a bounded upper estimate. It's in-colo and
* cheaper—preferred for the hot public abuse-control surfaces.
*/
declare function rateLimit(backend: RateLimitBackend, key: string, limit: number, windowSec: number, now?: number): Promise;
/** A limited route: matched on method + pathname, with its own budget. */
interface RateRule {
name: string;
method: string;
/**
* Exact path or a prefix test. {@link matchRateRule} calls it with the path
* as given and with its {@link normalizeRatePath} form, so write it against
* the canonical path (`p === "/api/checkout"`) and the slashed and encoded
* spellings of that path match too.
*/
match: (path: string) => boolean;
limit: number;
windowSec: number;
}
/**
* The canonical form of a request path, for matching rate rules: percent-decoded
* until it stops changing, with each run of slashes collapsed to one and any
* trailing slash removed. The root path stays `/`.
*
* Routers commonly answer every one of these spellings from one endpoint: a
* trailing slash is ignored by default, and duplicate slashes and
* percent-encoded letters are normalized before routes are matched. A rule that
* tests the raw path for equality misses every other spelling, and the endpoint
* behind it gets no limit. So `/api//checkout/` and `/api/%63heckout` both
* normalize to `/api/checkout`.
*
* Decoding uses `decodeURI`, so an encoded reserved character such as `%2F`
* stays encoded and can't turn into a path separator. An invalid escape stops
* the decoding and keeps what decoded so far.
*/
declare function normalizeRatePath(path: string): string;
/**
* First matching rule for a request, or null. The site owns the `rules` array
* (its own routes + budgets); pass it in. Editor endpoints are usually
* session-gated and omitted so the editor can never lock itself out.
*
* Each rule is tested against `path` as given and against its
* {@link normalizeRatePath} form, and either one matching is a match. The
* normalized test means an exact rule for `/api/checkout` also limits
* `/api/checkout/`, which the router sends to the same endpoint. The test on
* the path as given keeps a rule written for a slashed path (a site with
* trailing slashes always on) matching.
*
* A request that matched a rule before still matches one, but not always the
* same one: rules are tried in order, and an earlier rule can now match the
* normalized path ahead of a later rule written for the spelling as given. A
* request that matched nothing before, such as a POST to `/api/checkout/`, can
* now be limited.
*/
declare function matchRateRule(rules: readonly RateRule[], method: string, path: string): RateRule | null;
//#endregion
//#region src/core/security/rate-limit-do.d.ts
/** One consume decision. Mirrors Better Auth's `BetterAuthRateLimitStorage`. */
interface DurableRateLimitResult {
allowed: boolean;
/** Seconds until the window frees up. `null` while allowed. */
retryAfter: number | null;
}
/** The budget a single consume is measured against. */
interface DurableRateLimitRule {
/** Window length in seconds. */
window: number;
/** Requests permitted per window. */
max: number;
}
/** What the site's `DurableObject` subclass delegates to. */
interface RateLimiter {
fetch(request: Request): Promise;
/** Clears the counter once its window has passed, so an idle key stops
* occupying storage. Wire this to the subclass's `alarm()`. */
alarm(): Promise;
}
/**
* The DO-side logic: a fixed-window counter that is genuinely atomic because the
* runtime serializes calls into a single object.
*
* Fixed window rather than sliding, matching `security/rate-limit`: a client can
* get up to ~2x the budget across a window boundary, which is an accepted cost
* for a counter that is one number instead of a list of timestamps.
*/
declare function createRateLimiter(ctx: DurableObjectState, now?: () => number): RateLimiter;
/** The subset of a Durable Object namespace binding this needs. Declared
* structurally so the real binding satisfies it without a hard dependency on
* `@cloudflare/workers-types`. */
interface RateLimitNamespace {
idFromName(name: string): unknown;
get(id: unknown): {
fetch(request: Request): Promise;
};
}
/** A `consume` function shaped for Better Auth's `rateLimit.customStorage`. */
interface DurableRateLimitStorage {
consume(key: string, rule: DurableRateLimitRule): Promise;
}
/**
* Consume against the DO for `key`, one object per key.
*
* **Fails open**, like `security/rate-limit`: any transport error allows the
* request. A limiter outage must never take down sign-in—the alternative is an
* unreachable DO locking every editor out of their own site. Each open is
* reported with `reportDegraded`.
*/
declare function durableRateLimitStorage(ns: RateLimitNamespace): DurableRateLimitStorage;
//#endregion
//#region src/core/security/secrets.d.ts
/**
* Anything that can back a secret value: a Secrets Store binding, a plain `vars`
* string (the shape a public key or a `wrangler secret put` value arrives in),
* or nothing at all—the binding simply isn't provisioned yet.
*/
type SecretSource = SecretBinding | string | null | undefined;
interface ReadSecretOptions {
/**
* Sentinel values that mean "not configured yet" and are read as unset. The
* caller supplies them: the package has no opinion about which string a site
* seeds its unprovisioned secrets with.
*/
placeholder?: string | readonly string[];
}
/**
* Read a secret, returning `null` whenever it is not really configured—the
* binding is absent, the store isn't provisioned (a declared-but-unset binding
* throws on `.get()`), the value is empty, or it still holds a placeholder
* sentinel. The point is that a caller can *degrade*—skip the integration,
* run a simulated path—instead of throwing or calling an upstream API with a
* dummy credential.
*
* Contrast {@link getSessionSecret}, which fails closed: a missing session
* secret is an error everywhere but localhost, not a feature to switch off.
*/
declare function readSecret(source: SecretSource, options?: ReadSecretOptions): Promise;
/**
* Session-signing secret, from either a Cloudflare Secrets Store binding or a
* plain `wrangler secret put` string. On localhost (where the store isn't
* provisioned) a fixed dev secret keeps the sign-in → session loop workable;
* any deployed hostname fails closed.
*
* "Not configured" here covers an unreadable binding, an empty value (a
* misprovisioned Secrets Store returns `""`), and—when the caller names one—a
* placeholder sentinel. That last case matters: a scaffold that seeds every
* secret with a public placeholder must never reach production still signing
* sessions with it, which is exactly what a plain non-empty check would allow.
*
* @param secret the binding or value (for example, `env.SESSION_SECRET`)
* @param url the request URL (its hostname decides the dev fallback)
* @param devSecret the localhost-only fallback value; override per site
* @param options `placeholder` sentinels to read as not-configured
*/
declare function getSessionSecret(secret: SecretSource, url: URL, devSecret?: string, options?: ReadSecretOptions): Promise;
//#endregion
//#region src/core/security/headers.d.ts
interface SecurityHeaderOptions {
/** Request hostname. Headers are skipped on localhost/127.0.0.1 so dev works. */
hostname: string;
/** Override `Permissions-Policy`; default denies camera/microphone/geolocation. */
permissionsPolicy?: string;
/** Override `Strict-Transport-Security`; default is 1y + includeSubDomains. */
hsts?: string;
/** Send `X-Robots-Tag: noindex`—for a preview or admin host. See {@link isNoindexHost}. */
noindex?: boolean;
}
/**
* Apply Louise's baseline transport/scope headers to `response` in place and
* return it. No-op on localhost so Vite's dev scripts keep working.
*/
declare function louiseSecurityHeaders(response: Response, opts: SecurityHeaderOptions): Response;
/**
* Whether `hostname` should be kept out of search indexes: any host ending in
* one of `suffixes`—by default `.workers.dev`, where Workers preview and
* per-version URLs live—or starting with one of `prefixes` (your own
* convention, for example, `["preview.", "studio."]`; none by default).
*
* A preview deploy is a complete copy of the site, so an indexed one competes
* with production for its own content. Send the answer as a header from
* middleware (`louiseSecurityHeaders(res, { hostname, noindex })`) rather than
* from a page: a streamed page has already sent its headers by the time page
* code runs, so a header set there is silently dropped.
*/
declare function isNoindexHost(hostname: string, options?: {
prefixes?: readonly string[];
suffixes?: readonly string[];
}): boolean;
/**
* Rewrite only the `style-src` directive of an existing `Content-Security-Policy`
* header, leaving every other directive (script hashes, etc.) verbatim. A host's
* `security.csp` hashes its own inline island `