import { B as requireRole, D as KVLike, F as hasRole, I as isSameOrigin, L as pick, M as EditorContext, N as EditorRequest, P as RoleRequest, R as requireEditor, V as safeNextPath, a as LouiseAuthEnv, i as EditorSession, n as AgentScope, r as EditorAgent, t as AgentAccess, v as RateLimitNamespace, z as requireEditorFromContext } from "../../types-B8yzm4Q0.js"; import { betterAuth } from "better-auth"; //#region src/core/auth/auth.d.ts type BetterAuthOptions$1 = Parameters[0]; type AdditionalFields$1 = NonNullable["additionalFields"]>; /** Workers KV shape the session cache needs—`get`/`put` (from KVLike) + delete. */ interface SessionKV extends KVLike { delete(key: string): Promise; } /** The rendered magic-link email a site supplies via config. */ interface MagicLinkEmail { subject: string; html: string; text: string; } /** * Multi-editor tenancy via the Better Auth organization plugin (issue #100): * multiple editors/roles per organization, org-scoped membership + invitations, * and optional teams. Enabling it adds the `organization`/`member`/`invitation` * tables (plus `team`/`teamMember` when `teams` is on) and an * `activeOrganizationId` column on `session`, so the SAME shape MUST be set on * `AuthSchemaConfig.organizations` when regenerating the migration—otherwise * the committed schema drifts from what the runtime queries ("always generate, * never hand-roll"). Editor access for members is gated by `resolveOrgEditor` * (org role), a second axis beside the global admin allowlist. */ interface LouiseOrganizationsConfig { /** Enable teams within organizations (adds the `team`/`teamMember` tables and * an `activeTeamId` column on `session`). Off by default. */ teams?: boolean; /** Let any signed-in user create an organization (Better Auth's default). * Set false to restrict creation to your own server-side/provisioning flow. * Runtime-only—does not affect the generated schema. */ allowUserToCreateOrganization?: boolean; /** Render the member-invitation email body (site branding), mirroring * `renderMagicLinkEmail`. Wiring it turns on invite emails: the factory * builds the accept `url` from the invitation id + `acceptInvitationPath`, * renders via this, and sends over the `EMAIL` binding (dev logs the link). * Omit to skip invite emails—invitations are still created and acceptable * through the API/client. Reuses the {@link MagicLinkEmail} rendered shape. */ renderInvitationEmail?: (args: { /** The accept-invitation link to embed (see `invitationAcceptUrl`). */ url: string; /** The invitee's email (the `to` address). */ toEmail: string; /** The organization the invitee is being asked to join. */ organizationName: string; /** The email of the member who sent the invite. */ inviterEmail: string; /** The org role the invitee is being granted (for example, "member", "admin"). */ role: string; }) => MagicLinkEmail; /** Path the invitation accept `url` points at, joined to the site origin with * `?id=`. Default `/organization/accept-invitation`. */ acceptInvitationPath?: string; } interface LouiseAuthConfig { /** Passkey relying-party display name, for example, "Meg Bowen Studio". */ rpName: string; /** * Passkey relying-party ID. Defaults to the request origin's hostname, which * is right for a single-origin site and wrong the moment an admin app lives on * its own subdomain: origin-derived means `example.com` and * `studio.example.com` mint **two separate passkeys** for the same person. * * Pin it to the apex (`"example.com"`) and one passkey authenticates on both, * because a credential registered for a domain is usable on its subdomains. * * **The sessions stay separate, and that is the point.** Sharing a credential * is not sharing a login. Pair this with **host-only cookies**—no `Domain` * attribute, `crossSubDomainCookies` off (the default)—and a distinct * {@link LouiseAuthConfig.cookiePrefix} per instance. Widening the cookie to * the parent domain would broadcast the admin session to every sibling * subdomain, including untrusted tenant storefronts, which is the failure this * option exists to avoid rather than cause. * * Must be the origin's own domain or a parent of it; a browser rejects a * registration whose rpID is neither, so a typo fails at enrolment rather than * silently. Note rpID is a bare **domain**, never a scheme or a port. */ rpID?: string; /** `from` address for the magic-link email. */ mailFrom: { email: string; name?: string; }; /** Render the magic-link email body (site branding). */ renderMagicLinkEmail: (args: { url: string; toEmail: string; }) => MagicLinkEmail; /** Resolve the admin allowlist. Defaults to `OWNER_EMAIL`/`ENGINEER_EMAIL` * from env; override to source it elsewhere (for example, a DB lookup). */ resolveAdmins?: (env: LouiseAuthEnv) => string[] | Promise; /** Enable customer sign-in and sign-up. Omit for an admin-only editor. */ customers?: { /** * How customers sign in. Default `"password"`: email and password, with the * password options below. * * `"magic-link"` turns email and password off and opens the magic-link * endpoint to every address instead of only the admin allowlist: anyone can * ask for a one-time link, and following it signs them in, creating the * account unless `disableSignUp` is set. The link itself verifies the * account's email. Serve the instance with `auth.handler`, not * {@link handleAuthRequest}, whose gate admits only admins. * * Because a stranger can make the site send mail, three things guard the * endpoint, and two of them are the site's to turn on: * * - **Better Auth's rate limiter**, on for every instance off localhost. * Set {@link LouiseAuthConfig.rateLimitDo} too: the KV and in-memory * fallbacks undercount under a burst. * - **Turnstile**, only when both a real secret and a real site key are * set. With the test keys, which every Worker Preview gets, or with none, * the captcha is off, so the endpoint mails any address that asks. Each * link sent that way off localhost logs an `auth.magic-link-no-captcha` * degrade. * - **{@link LouiseAuthConfig.waitUntil}**, so the send leaves the response * path and the endpoint answers in the same time whether or not it mails. */ signIn?: "password" | "magic-link"; /** Password sign-in only. Default 8. */ minPasswordLength?: number; /** Password sign-in only. A link proves the address, so it needs no flag. */ requireEmailVerification?: boolean; /** Close public sign-up—accounts are provisioned by staff instead. With * `"magic-link"`, an address with no account gets no email at all; set * {@link LouiseAuthConfig.waitUntil}, or the response time shows which * addresses have one. */ disableSignUp?: boolean; /** Password sign-in only. Revoke existing sessions when a password is * reset. Default `true`: a reset usually means the old credentials are * compromised. */ revokeSessionsOnPasswordReset?: boolean; /** Password sign-in only. Send the self-serve reset link. Omit to leave * reset unavailable. */ sendResetPassword?: (args: { user: { email: string; }; url: string; }) => Promise | void; /** * Mount Better Auth's admin endpoints on this instance. Default `false`. * * The admin plugin serves user administration at `/admin/*`: * listing, creating, and removing users, setting roles, banning, and * impersonation. Their only check is the session user's `role`, and a * customer instance has no use for them, so it leaves them off. * * Off, the instance keeps what the plugin did for every request: the `role` * and ban columns stay in the user table and on the session user, a new * account still gets its role, and a banned user can't start a new session. * A ban set in the database doesn't end the sessions the user already has; * delete their rows in the `session` table, and their entries in * {@link LouiseAuthConfig.sessionCacheKv} when it's set. The schema doesn't * change, so turning this on or off needs no migration. * * One instance that serves both editors and customers counts as a customer * instance, so it loses these endpoints too. Setting this on it gives every * editor, who holds the `admin` role, the power to list, remove, and * impersonate every customer. * * Set it only when the site administers its customers through these * endpoints, and make sure no customer row can hold an admin role. */ adminEndpoints?: boolean; }; /** * Mount point for this instance's routes. Default `/api/auth`. * * The reason this is configurable: a site can run TWO instances on one origin * (the editor studio and a customer portal), and they must not share a mount. * The studio keeps the default, because the Louise editor client hardcodes it; * a second instance takes its own. */ basePath?: string; /** * Cookie name prefix. Default Better Auth's own (`better-auth`). * * Two instances on one origin MUST differ here, or their session cookies * collide and signing into one silently signs you out of the other. */ cookiePrefix?: string; /** Extra Better Auth user columns (for example, `squareCustomerId`). */ additionalFields?: AdditionalFields$1; /** Table-name prefix for a same-D1 auth boundary (issue #15, Option B), for example, * `"auth_"`. Renames the auth tables so they're a visible namespace in one * database; MUST match the prefix passed to `generateAuthSchemaSql`. Omit for * default table names (identical to prior behavior). */ tablePrefix?: string; /** Session lifetime overrides (defaults: 45-day rolling, daily refresh). */ session?: { expiresIn?: number; updateAge?: number; }; /** Cache sessions in KV (`secondaryStorage` + `storeSessionInDatabase`): D1 * stays the source of truth, KV is the global read cache. Omit for D1-only. */ sessionCacheKv?: SessionKV; /** * Where single-use verification values—magic links, password resets—are * stored and consumed. Only meaningful alongside {@link sessionCacheKv}; * without it there is no secondary storage and these always live in D1. * * Defaults to `"database"`, and that default is a security one. Better Auth * 1.7 requires `SecondaryStorage.getAndDelete` to be atomic precisely so one * of these values cannot be consumed twice. Over KV it cannot be—there is * no atomic primitive, and KV's cross-colo convergence widens the replay * window well past a simple race. D1 is strongly consistent and deletes * atomically, so consuming from there closes it, and KV stays what it is * meant to be here: a session read cache. * * `"secondary"` restores the pre-0.27 behaviour (consume from KV). It trades * that guarantee for one less D1 read on the verification path; take it only * if you have measured that read and decided it matters. */ verificationStorage?: "database" | "secondary"; /** * Durable Object namespace backing Better Auth's own rate limiter. * * The limiter itself is on for every instance unless the host in `baseURL` * is `localhost` or `127.0.0.1`, whether or not this is set; this only * chooses where it counts. Better Auth enables it by itself only when * `NODE_ENV` is `production`, which a Worker never sets, so the factory turns * it on. It keys each count on the instance (host and `basePath`), the * `CF-Connecting-IP` header, and the path, and answers a burst with a 429. * Its default budgets, per address and path, are 100 requests per 10 * seconds, 3 per 10 seconds on sign-in and sign-up, and 5 a minute each for * sending and following a magic link. * * Wire this and rate limiting stops going through KV entirely: Better Auth * checks `rateLimit.customStorage` BEFORE secondary storage, so the KV * `increment` is never called. That matters because a DO is the only atomic * counter on Workers—it handles one request at a time, so read-decide-write * inside it cannot race. The KV path can undercount under a burst, and * Cloudflare's native Rate Limiting binding is documented as permissive, * eventually consistent, and scoped PER LOCATION, so an attacker spread across * colos gets one budget per colo. Acceptable for form spam; weak for sign-in. * * The site owns the `DurableObject` subclass and the wrangler binding—see * `createRateLimiter` in `louise-toolkit/security` for the shape. One object * per key, so no single object becomes a bottleneck. * * Omit to count in KV when `sessionCacheKv` is set, otherwise in a map in * the isolate's memory, which each isolate keeps on its own. */ rateLimitDo?: RateLimitNamespace; /** * The runtime's `waitUntil`, from `cloudflare:workers` or the request's * execution context. Better Auth hands it the work it can finish after the * response: here, sending a magic-link email. Without it the endpoint * waits for the send, so how long it takes tells a caller whether an email * went out, which matters once a customer instance mails only existing * accounts (`customers.disableSignUp` with `signIn: "magic-link"`). * * A failed send in the background is logged, not returned: the person sees * the same "check your inbox" either way. */ waitUntil?: (promise: Promise) => void; /** Enable multi-editor tenancy (organization plugin). Omit for a single-editor * site. Mirror this on `AuthSchemaConfig.organizations` when regenerating the * migration. See {@link LouiseOrganizationsConfig}. */ organizations?: LouiseOrganizationsConfig; /** Additional Better Auth plugins. */ extraPlugins?: NonNullable; /** localhost-only dev secret passed to `getSessionSecret`. */ devSecret?: string; /** Display name for newly-created non-admin users (default "Editor"). */ defaultUserName?: string; } /** The current user on a resolved session (Better Auth's user, with the admin * plugin's `role`, which a customer instance declares itself). */ interface LouiseSessionUser { id: string; email?: string; name?: string; role?: string; } /** * The slice of the Better Auth instance Louise uses and re-exposes. Hand-written * rather than the inferred `betterAuth()` type on purpose: the passkey plugin's * inferred type pulls in `@simplewebauthn/server` and `zod` internals that * aren't nameable in a published `.d.ts` (TS2742), and pinning the surface here * also insulates consumers from Better Auth's internal type churn. */ interface LouiseAuth { handler(request: Request): Promise; api: { getSession(input: { headers: Headers; }): Promise<{ user?: LouiseSessionUser | null; session?: { activeOrganizationId?: string | null; } | null; } | null>; /** * Ends the session the request's cookie names and returns Better Auth's * response, whose `set-cookie` headers expire the session cookies. Pass it * to `redirectWithCookies` to sign someone out from a server-rendered route. */ signOut(input: { headers: Headers; asResponse: true; }): Promise; }; } /** * Construct the request-scoped auth instance. `baseURL` is the site origin * (Better Auth signs callback URLs and binds the passkey rpID against it); * derive it from the request. */ declare function getLouiseAuth(env: LouiseAuthEnv, baseURL: string, config: LouiseAuthConfig): Promise; //#endregion //#region src/core/auth/admins.d.ts /** * Default admin allowlist: `OWNER_EMAIL` + optional `ENGINEER_EMAIL` from env, * lowercased, empties dropped (so a missing var never widens access). Override * via `LouiseAuthConfig.resolveAdmins` to source the allowlist elsewhere * (for example, a DB lookup) instead of env. */ declare function defaultResolveAdmins(env: LouiseAuthEnv): string[]; /** Case-insensitive membership test against a resolved allowlist. */ declare function isAllowedSignInEmail(admins: readonly string[], email: string): boolean; //#endregion //#region src/core/auth/org.d.ts /** Default org roles that may edit content: the organization plugin's `owner` * and `admin`. Plain `member` is non-editing unless a site widens this. */ declare const DEFAULT_ORG_EDITOR_ROLES: readonly ["owner", "admin"]; /** Default path the invitation-accept link points at (joined to the site * origin). Override via `LouiseOrganizationsConfig.acceptInvitationPath`. */ declare const DEFAULT_ACCEPT_INVITATION_PATH = "/organization/accept-invitation"; /** * Build the URL an invitation email links to: the site origin (`baseURL`) + * `acceptPath`, carrying the invitation id as `?id=`. Better Auth doesn't * generate invite URLs—`sendInvitationEmail` hands back only the invitation * id—so the app constructs the link the accept-invitation endpoint/page reads. * An absolute `acceptPath` resolves against the origin, ignoring any path on * `baseURL`; an empty path falls back to {@link DEFAULT_ACCEPT_INVITATION_PATH}. */ declare function invitationAcceptUrl(baseURL: string, invitationId: string, acceptPath?: string): string; /** An editor session resolved from organization membership: the base editor * fields plus the organization it's scoped to (`role` is the org role, not the * global admin-plugin role). */ interface OrgEditorSession extends EditorSession { organizationId: string; } interface ResolveOrgEditorOptions { /** The organization the request is scoped to. The site resolves this: the * sole org for a single site, or per-hostname for multi-tenant hosting (see * {@link activeOrganizationId} for the session's active org). */ organizationId: string; /** Org roles allowed to edit. Defaults to {@link DEFAULT_ORG_EDITOR_ROLES}. */ editorRoles?: readonly string[]; /** `member` table prefix—must equal the auth `tablePrefix` (Option B). * Validated as a SQL identifier before it's interpolated into the query. */ tablePrefix?: string; } /** * Resolve the editor session for `organizationId` from the signed-in user's * membership. Returns the {@link OrgEditorSession} when the user is a member * whose org role is in `editorRoles` (owner/admin by default), else null—mirroring * {@link resolveEditorSession}'s "null means not an editor" contract, * so it drops straight into `editorsRoute`/`guardEditor` as a `resolveEditor`. * Access is re-derived from the session + DB on every request; nothing is * trusted from the client. */ declare function resolveOrgEditor(auth: LouiseAuth, db: D1Database, request: Request, opts: ResolveOrgEditorOptions): Promise; /** * The organization the current session has marked active—Better Auth stores it * on the session once the client calls `setActiveOrganization`. Convenience for * the single-site case: resolve the active org, then gate with * {@link resolveOrgEditor}. Returns null when there is no session or no active * org (for example, the user hasn't selected one yet). */ declare function activeOrganizationId(auth: LouiseAuth, request: Request): Promise; //#endregion //#region src/core/auth/session.d.ts /** * Re-derive the editor (admin) session from the signed Better Auth session on * every request—edit access is never trusted from the client. Returns the * editor when the session user holds `editorRole` (the admin plugin's "admin"), * else null. The site assigns the result to its `locals`. */ declare function resolveEditorSession(auth: LouiseAuth, request: Request, editorRole?: string): Promise; /** * Re-derive the signed-in user and their role WITHOUT gating on any specific * role—for a site's own multi-role auth instance where the role is arbitrary * and access is decided per route (via {@link requireRole}) or the UI renders * per role. Returns null only when there is no session. Generic and * unopinionated: Louise bakes in no role names. (Louise Editor uses the * role-gating {@link resolveEditorSession}.) */ declare function resolveSession(auth: LouiseAuth, request: Request): Promise; interface EditorForUserOptions { /** The role an editor holds. Default `"admin"`, as in {@link resolveEditorSession}. */ editorRole?: string; /** The auth tables' prefix. Must equal `LouiseAuthConfig.tablePrefix`. */ tablePrefix?: string; /** The sign-in allowlist. Must be the same function `LouiseAuthConfig` * takes. Default `defaultResolveAdmins`, the owner and engineer emails. */ resolveAdmins?: (env: LouiseAuthEnv) => string[] | Promise; } /** * Re-derive an editor from their user ID, for a credential that isn't a * browser session, such as an agent token. Where the cookie path asks Better * Auth for the session, this reads the user row, so an editor who's lost * access loses it for every token they issued too. * * Returns null unless the user exists, holds `editorRole`, isn't banned, and * is still on the sign-in allowlist. The allowlist check matters more here than * for a session: taking an email off the list stops the next sign-in, but a * token was never going to sign in again. */ declare function editorForUser(env: LouiseAuthEnv, userId: string, options?: EditorForUserOptions): Promise; //#endregion //#region src/core/auth/handler.d.ts /** * Better Auth catch-all with the editor magic-link allowlist gate. A site's * `/api/auth/[...all]` route calls this. Non-admin magic-link requests are * rejected BEFORE Better Auth runs—no token, no mail, and (at the verify * step) no user row—and return the SAME enumeration-safe response a real send * returns, so probing the endpoint reveals nothing. Customer email/password * sign-up (when enabled) is intentionally NOT gated by this. An instance whose * customers sign in by magic link (`customers.signIn: "magic-link"`) must not * route through here, since this gate would turn every customer away: serve it * with `auth.handler`. * * `admins` is the resolved allowlist (use `defaultResolveAdmins` or the config's * `resolveAdmins`—the same source the factory uses). */ declare function handleAuthRequest(auth: LouiseAuth, request: Request, admins: readonly string[]): Promise; /** * A redirect that carries every cookie a Better Auth response set, for a * server-rendered route that calls the API with `asResponse: true` and then * sends the browser on, such as a sign-out link: * * const result = await auth.api.signOut({ headers: request.headers, asResponse: true }); * return redirectWithCookies(result, "/"); * * Better Auth sets several cookies at once; sign-out expires the session * token, the cached session, and the "don't remember me" cookie. Copying them * with `headers.get("set-cookie")` joins them into one header, and the browser * keeps all but the first, so a signed-out visitor still carries the session. * This copies each one with `getSetCookie()`. * * `location` is where the browser goes. Pass a path the route chose, never one * read from the request unchecked (see `safeNextPath`). `status` defaults to * 303, which turns a POST into a GET. */ declare function redirectWithCookies(from: Response | Headers, location: string, status?: 301 | 302 | 303 | 307 | 308): Response; //#endregion //#region src/core/auth/schema-gen.d.ts type BetterAuthOptions = Parameters[0]; type AdditionalFields = NonNullable["additionalFields"]>; interface AuthSchemaConfig { /** Enable customer email/password sign-in (widens the account/user schema). * Mirror `LouiseAuthConfig.customers` being set. */ customers?: boolean; /** Extra Better Auth user columns (for example, `squareCustomerId`). MUST match the * runtime `LouiseAuthConfig.additionalFields` so generated columns line up. */ additionalFields?: AdditionalFields; /** Enable the organization plugin's tables (`organization`/`member`/ * `invitation`, plus `team`/`teamMember` when `teams` is set) and the * `activeOrganizationId` session column. MUST mirror * `LouiseAuthConfig.organizations`—only `teams` affects the schema, so * runtime-only knobs (for example, `allowUserToCreateOrganization`) are omitted. */ organizations?: { teams?: boolean; }; /** Table-name prefix for a same-D1 auth boundary (Option B), for example, `"auth_"`. * Must equal `LouiseAuthConfig.tablePrefix` at runtime. Empty → default names. */ tablePrefix?: string; } /** * The field-affecting Better Auth options for the plugins whose columns every * Louise instance uses (magic-link, admin, passkey) plus the site's opt-in customer sign-in and extra * user fields. Runtime-only concerns (email sender, captcha secret, rpID) don't * change the schema, so they're omitted—the plugins are constructed with inert * options purely for introspection. */ declare function authSchemaOptions(config: AuthSchemaConfig): BetterAuthOptions; /** * Generate the CREATE TABLE DDL for Better Auth's tables (user, session, * account, verification, passkey—plus any `additionalFields` columns), * optionally namespaced by `tablePrefix`. Foreign keys resolve to the prefixed * target table so a namespaced schema stays internally consistent. The output is * the SQL a site commits as its auth migration. */ declare function generateAuthSchemaSql(config?: AuthSchemaConfig): string; //#endregion //#region src/core/auth/turnstile.d.ts /** Sentinel for a not-yet-configured Turnstile secret—keeps captcha OFF. */ declare const TURNSTILE_PLACEHOLDER = "DUMMY_REPLACE_ME"; /** Cloudflare's always-passing Turnstile *test* site key. Its token will not * verify against a real secret, so captcha also requires a real site key. */ declare const TURNSTILE_TEST_SITE_KEY = "1x00000000000000000000AA"; /** The two Turnstile bindings. Either might be missing. Every `LouiseAuthEnv` * fits, and so does a route's own env that has only these two. */ type CaptchaEnv = Pick; /** The public site key to render, or null to render no widget (test/unset). */ declare function turnstileSiteKey(env: CaptchaEnv): string | null; /** The stored Turnstile secret, or null while it's the placeholder/unreadable. */ declare function turnstileSecret(env: CaptchaEnv): Promise; /** The secret to enforce captcha with, or null to keep it OFF (needs a real * secret AND a real, non-test site key). */ declare function activeCaptchaSecret(env: LouiseAuthEnv, secret: string | null): string | null; /** * Is captcha on—and if so, the key to render the widget with and the secret * to verify its token against, together. `null` means OFF: render no widget and * check no token. * * One decision for both halves, because a split decision takes sign-in down. * A site key that stops resolving (say, after moving Cloudflare accounts) * renders no widget; if the server still holds a real secret, it keeps * demanding a token no visitor can produce, and every sign-in fails. Deciding * the widget and the check from the same call makes that state unreachable. * On only when both halves are real—see {@link activeCaptchaSecret}. */ declare function activeCaptcha(env: LouiseAuthEnv): Promise<{ siteKey: string; secret: string; } | null>; /** * Whether a control's captcha is on, from {@link resolveCaptcha}: * * - `off`: not provisioned. There's no site key, the site key is Cloudflare's * test key, or this is the dev server. Render no widget and check no token. * - `on`: render the widget with `siteKey` and verify its token against * `secret`. * - `unavailable`: a real site key whose secret can't be read, because the * binding is missing, holds the placeholder, or threw. The host meant the * captcha to be on. Render no widget, and decide per control whether to * refuse the request (fail closed) or let it through (fail open). */ type CaptchaDecision = { kind: "off"; } | { kind: "on"; siteKey: string; secret: string; } | { kind: "unavailable"; }; /** Options for {@link resolveCaptcha}. */ interface ResolveCaptchaOptions { /** * True when the request is served by the local dev server. Pass the build's * own flag, such as Vite's `import.meta.env.DEV`. The dev server reads the * real site key from the Wrangler config and has no Secrets Store, so a real * site key with no readable secret is `off` there rather than `unavailable`. * * A build-time flag rather than the request's host, because a local preview * of a build (`wrangler dev` on the built Worker) rewrites the host to the * route's zone: a host test would read that preview as production, and the * flag correctly reads it as a build. */ devServer: boolean; } /** The `reportDegraded` name {@link resolveCaptcha} reports an `unavailable` * captcha under. */ declare const CAPTCHA_UNAVAILABLE_DEGRADED = "auth.captcha-unavailable"; /** * Decide a control's captcha in three states, for a control that must not * quietly lose its captcha. See {@link CaptchaDecision}. * * {@link activeCaptcha} folds "not provisioned" and "provisioned but the secret * can't be read" into one `null`, which is right for the studio's sign-in: a * broken secret then keeps the owner able to sign in. A checkout can't afford * that, because a broken Secrets Store binding would silently turn its captcha * off. This call keeps the two apart, so the control can refuse while its * captcha is `unavailable`. * * Use it for the widget and the check alike, as with {@link activeCaptcha}: a * page renders the widget only for `on`, and the route verifies a token only * for `on`. An `unavailable` result is reported once per call with * `reportDegraded` under {@link CAPTCHA_UNAVAILABLE_DEGRADED}, with a cause that * says whether the binding is missing or unreadable, so the outage shows up in * the log and the incident record before a customer reports it. A binding that * throws is also reported as `security.readSecret` by the read itself. * * @example * ```ts * const captcha = await resolveCaptcha(env, { devServer: import.meta.env.DEV }); * if (captcha.kind === "unavailable") return json({ error: "Checkout isn't available right now." }, 503); * if (captcha.kind === "on" && !(await verifyTurnstileToken(captcha.secret, token, ip))) { * return json({ error: "Reload the page and try again." }, 403); * } * ``` */ declare function resolveCaptcha(env: CaptchaEnv, options: ResolveCaptchaOptions): Promise; //#endregion export { type AgentAccess, type AgentScope, type AuthSchemaConfig, CAPTCHA_UNAVAILABLE_DEGRADED, type CaptchaDecision, type CaptchaEnv, DEFAULT_ACCEPT_INVITATION_PATH, DEFAULT_ORG_EDITOR_ROLES, type EditorAgent, type EditorContext, type EditorForUserOptions, type EditorRequest, type EditorSession, type LouiseAuth, type LouiseAuthConfig, type LouiseAuthEnv, type LouiseOrganizationsConfig, type MagicLinkEmail, type OrgEditorSession, type ResolveCaptchaOptions, type ResolveOrgEditorOptions, type RoleRequest, type SessionKV, TURNSTILE_PLACEHOLDER, TURNSTILE_TEST_SITE_KEY, activeCaptcha, activeCaptchaSecret, activeOrganizationId, authSchemaOptions, defaultResolveAdmins, editorForUser, generateAuthSchemaSql, getLouiseAuth, handleAuthRequest, hasRole, invitationAcceptUrl, isAllowedSignInEmail, isSameOrigin, pick, redirectWithCookies, requireEditor, requireEditorFromContext, requireRole, resolveCaptcha, resolveEditorSession, resolveOrgEditor, resolveSession, safeNextPath, turnstileSecret, turnstileSiteKey };