{"version":3,"file":"auth.mjs","names":["virtualAuthenticate"],"sources":["../../../src/api/csrf.ts","../../../src/astro/middleware/csp.ts","../../../src/astro/middleware/auth.ts"],"sourcesContent":["/**\n * CSRF protection utilities.\n *\n * Two mechanisms:\n * 1. Custom header check (X-EmDash-Request: 1) — used for authenticated API routes.\n *    Browsers block cross-origin custom headers, so presence proves same-origin.\n * 2. Origin check — used for public API routes that skip auth. Compares the Origin\n *    header against the request origin. Same approach as Astro's `checkOrigin`.\n */\n\nimport { apiError } from \"./error.js\";\n\n/**\n * Origin-based CSRF check for public API routes that skip auth.\n *\n * State-changing requests (POST/PUT/DELETE) to public endpoints must either:\n *   1. Include the X-EmDash-Request: 1 header (custom header blocked cross-origin), OR\n *   2. Have an Origin header matching the request origin (or the configured public origin)\n *\n * This prevents cross-origin form submissions (which can't set custom headers)\n * and cross-origin fetch (blocked by CORS unless allowed). Same-origin requests\n * always include a matching Origin header.\n *\n * Returns a 403 Response if the check fails, or null if allowed.\n *\n * @param request  The incoming request\n * @param url      The request URL (internal origin)\n * @param publicOrigin  The public-facing origin from config.siteUrl. Must be\n *        `undefined` when absent — never `null` or `\"\"` (security invariant H-1a).\n */\nexport function checkPublicCsrf(\n\trequest: Request,\n\turl: URL,\n\tpublicOrigin?: string,\n): Response | null {\n\t// Custom header present — browser blocks cross-origin custom headers\n\tconst csrfHeader = request.headers.get(\"X-EmDash-Request\");\n\tif (csrfHeader === \"1\") return null;\n\n\t// Check Origin header — present on all POST/PUT/DELETE from browsers\n\tconst origin = request.headers.get(\"Origin\");\n\tif (origin) {\n\t\ttry {\n\t\t\tconst originUrl = new URL(origin);\n\t\t\t// Accept if Origin matches either the internal or public origin\n\t\t\tif (originUrl.origin === url.origin) return null;\n\t\t\tif (publicOrigin && originUrl.origin === publicOrigin) return null;\n\t\t} catch {\n\t\t\t// Malformed Origin — fall through to reject\n\t\t}\n\n\t\treturn apiError(\"CSRF_REJECTED\", \"Cross-origin request blocked\", 403);\n\t}\n\n\t// No Origin header — non-browser client (curl, server-to-server).\n\t// Allow these through since CSRF is a browser-specific attack vector.\n\t// Server-to-server requests don't carry ambient credentials (cookies).\n\treturn null;\n}\n","/**\n * Strict Content-Security-Policy for /_emdash routes (admin + API).\n *\n * Applied via middleware header rather than Astro's built-in CSP because\n * Astro's auto-hashing defeats 'unsafe-inline' (CSP3 ignores 'unsafe-inline'\n * when hashes are present), which would break user-facing pages.\n *\n * img-src allows any HTTPS origin because the admin renders user content that\n * may reference external images (migrations, external hosting, embeds).\n * Plugin security does not rely on img-src -- plugins run in V8 isolates with\n * no DOM access. connect-src stays at 'self' unless the experimental registry\n * and/or the configured storage endpoint (for direct-to-S3 signed uploads)\n * are configured, in which case those origins are allowed too.\n */\nimport type { RegistryConfigInput } from \"../../registry/types.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport type { StorageDescriptor } from \"../storage/types.js\";\n\n/** Entrypoint constant used by the `s3()` adapter (see `astro/storage/adapters.ts`). */\nconst S3_ADAPTER_ENTRYPOINT = \"@premium-cms/emdash/storage/s3\";\n\n/**\n * Storage entrypoints are free to shape their config however they like, so\n * `endpoint` isn't a known field on `StorageDescriptor[\"config\"]` -- only\n * S3-compatible adapters (R2, S3, Minio, ...) set it. Anything else (e.g.\n * local filesystem storage) simply has no `endpoint` to allow.\n *\n * The `s3()` adapter resolves any field omitted from its config -- including\n * `endpoint` -- from the matching `S3_*` env var at runtime (see\n * `storage/s3.ts`'s `resolveS3Config`). A site configured as `s3({ ... })`\n * with only `S3_ENDPOINT` set has no `endpoint` in the descriptor's config,\n * so fall back to that env var for S3-adapter storage. Custom adapters can\n * expose their runtime upload origin through `getClientUploadOrigin()`.\n */\nexport function getConfiguredStorageEndpoint(\n\tstorage: StorageDescriptor | undefined,\n\truntimeStorage?: Pick<Storage, \"getClientUploadOrigin\"> | null,\n): string | undefined {\n\tconst config = storage?.config;\n\tif (typeof config === \"object\" && config !== null && \"endpoint\" in config) {\n\t\tconst endpoint = config.endpoint;\n\t\tif (typeof endpoint === \"string\") return endpoint;\n\t}\n\n\tif (storage?.entrypoint === S3_ADAPTER_ENTRYPOINT) {\n\t\tconst envEndpoint =\n\t\t\ttypeof process !== \"undefined\" && process.env ? process.env.S3_ENDPOINT : undefined;\n\t\tif (envEndpoint) return envEndpoint;\n\t}\n\n\treturn runtimeStorage?.getClientUploadOrigin?.();\n}\n\nfunction getRegistryAggregatorOrigin(\n\tregistry: RegistryConfigInput | undefined,\n): string | undefined {\n\tconst aggregatorUrl = typeof registry === \"string\" ? registry : registry?.aggregatorUrl;\n\tif (!aggregatorUrl) return undefined;\n\n\ttry {\n\t\tconst url = new URL(aggregatorUrl);\n\t\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n\t\treturn url.origin;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction getHttpOrigin(rawUrl: string | undefined): string | undefined {\n\tif (!rawUrl) return undefined;\n\n\ttry {\n\t\tconst url = new URL(rawUrl);\n\t\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n\t\treturn url.origin;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function buildEmDashCsp(registry?: RegistryConfigInput, storageEndpoint?: string): string {\n\tconst connectSrc = [\"connect-src 'self'\"];\n\tconst origins = new Set<string>();\n\tconst registryAggregatorOrigin = getRegistryAggregatorOrigin(registry);\n\tif (registryAggregatorOrigin) origins.add(registryAggregatorOrigin);\n\tconst storageOrigin = getHttpOrigin(storageEndpoint);\n\tif (storageOrigin) origins.add(storageOrigin);\n\tconnectSrc.push(...origins);\n\n\treturn [\n\t\t\"default-src 'self'\",\n\t\t\"script-src 'self' 'unsafe-inline'\",\n\t\t\"style-src 'self' 'unsafe-inline'\",\n\t\tconnectSrc.join(\" \"),\n\t\t\"form-action 'self'\",\n\t\t\"frame-ancestors 'none'\",\n\t\t\"img-src 'self' https: data: blob:\",\n\t\t\"object-src 'none'\",\n\t\t\"base-uri 'self'\",\n\t].join(\"; \");\n}\n","/**\n * Auth middleware for admin routes\n *\n * Checks if the user is authenticated and has appropriate permissions.\n * Supports two auth modes:\n * - Passkey (default): Session-based auth with passkey login\n * - External providers: JWT-based auth (Cloudflare Access, etc.)\n *\n * This middleware runs AFTER the setup middleware - so if we get here,\n * we know setup is complete and users exist.\n */\n\nimport type { User, RoleLevel } from \"@premium-cms/auth\";\nimport {\n\tbuiltinRoleForLevel,\n\tgrantsAllowRoute,\n\ttoApiRelativePath,\n} from \"@premium-cms/auth\";\nimport { createKyselyAdapter } from \"@premium-cms/auth/adapters/kysely\";\nimport { defineMiddleware } from \"astro:middleware\";\nimport { ulid } from \"ulidx\";\n// Import auth provider via virtual module (statically bundled)\n// This avoids dynamic import issues in Cloudflare Workers\nimport { authenticate as virtualAuthenticate } from \"virtual:emdash/auth\";\n// @ts-ignore - virtual module\nimport virtualConfig from \"virtual:emdash/config\";\n\nimport { checkPublicCsrf } from \"../../api/csrf.js\";\nimport { apiError } from \"../../api/error.js\";\nimport { getConfiguredOrigin, getPublicOrigin } from \"../../api/public-url.js\";\nimport { OptionsRepository } from \"../../database/repositories/options.js\";\n\n/** Cache headers for middleware error responses (matches API_CACHE_HEADERS in api/error.ts) */\nconst MW_CACHE_HEADERS = {\n\t\"Cache-Control\": \"private, no-store\",\n} as const;\nimport { resolveApiToken, resolveOAuthToken } from \"../../api/handlers/api-tokens.js\";\nimport { attachRequestAuthz, type RequestAuthz } from \"../../auth/authz.js\";\nimport { getAuthMode, type ExternalAuthMode } from \"../../auth/mode.js\";\nimport type { ExternalAuthConfig } from \"../../auth/types.js\";\nimport { resolveSessionUser } from \"../session-user.js\";\nimport type { EmDashHandlers } from \"../types.js\";\nimport { buildEmDashCsp, getConfiguredStorageEndpoint } from \"./csp.js\";\n\nconst TRAILING_SLASH = /\\/$/;\n\n/**\n * Where to send an unauthenticated admin request. Behind a custom-domain\n * proxy the request URL is the instance's default host, so the canonical\n * origin (`emdash:site_url`, the Site URL setting) wins; the request origin\n * is only the fallback before setup has recorded one.\n */\nasync function loginOrigin(\n\turl: URL,\n\temdash: { config?: unknown; db?: unknown } | undefined,\n): Promise<string> {\n\tconst configured = getConfiguredOrigin(\n\t\temdash?.config as Parameters<typeof getConfiguredOrigin>[0],\n\t);\n\tif (configured) return configured;\n\tconst db = emdash?.db as ConstructorParameters<typeof OptionsRepository>[0] | undefined;\n\tif (db) {\n\t\ttry {\n\t\t\tconst stored = await new OptionsRepository(db).get<string>(\"emdash:site_url\");\n\t\t\tif (stored) return stored.replace(TRAILING_SLASH, \"\");\n\t\t} catch {\n\t\t\t// options unavailable (pre-setup) — fall through\n\t\t}\n\t}\n\treturn url.origin;\n}\n\ndeclare global {\n\tnamespace App {\n\t\tinterface Locals {\n\t\t\tuser?: User;\n\t\t\t/** Token scopes when authenticated via API token or OAuth token. Undefined for session auth. */\n\t\t\t/** Set when the request authenticated with a Bearer token (API token or OAuth). */\n\t\t\ttokenAuth?: boolean;\n\t\t\t/** Set when the Bearer token's row opts into CORS (middleware/cors.ts reflects the Origin). */\n\t\t\ttokenCors?: boolean;\n\t\t\t/**\n\t\t\t * Policy slugs carried by a policy-based API token. Null for a legacy\n\t\t\t * scoped token or an OAuth token; undefined for session auth.\n\t\t\t */\n\t\t\ttokenPolicies?: string[] | null;\n\t\t\t/** Resolved role and grants for the authenticated principal. */\n\t\t\tauthz?: RequestAuthz;\n\t\t\temdash?: EmDashHandlers;\n\t\t}\n\t\tinterface SessionData {\n\t\t\tuser: { id: string };\n\t\t\thasSeenWelcome: boolean;\n\t\t}\n\t}\n}\n\n// Role level constants (matching @premium-cms/auth)\nconst ROLE_ADMIN = 50;\nconst MCP_ENDPOINT_PATH = \"/_emdash/api/mcp\";\nconst COMMENT_SUBMISSION_PATH = /^\\/_emdash\\/api\\/comments\\/[^/]+\\/[^/]+\\/?$/;\n\nfunction isUnsafeMethod(method: string): boolean {\n\treturn method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\";\n}\n\n/**\n * Routes every signed-in principal may call regardless of policy: identity,\n * sign-out and managing one's own credentials. They are not an authorization\n * surface, and a role that could not reach them would lock its holders out\n * of the admin shell itself.\n */\nconst SELF_SERVICE_PREFIXES = [\n\t\"/_emdash/api/auth/me\",\n\t\"/_emdash/api/auth/logout\",\n\t\"/_emdash/api/auth/passkey\",\n\t\"/_emdash/api/auth/mode\",\n\t\"/_emdash/api/manifest\",\n];\n\nfunction isSelfServiceRoute(pathname: string): boolean {\n\treturn SELF_SERVICE_PREFIXES.some((p) => pathname === p || pathname.startsWith(p + \"/\"));\n}\n\n/**\n * The route gate: refuse a request whose path is outside the principal's\n * route grants. Applies to sessions and tokens alike once grants have been\n * resolved; the per-permission checks inside handlers remain the second gate.\n */\nfunction enforceRouteGrant(locals: App.Locals, pathname: string, method: string): Response | null {\n\tconst authz = locals.authz;\n\tif (!authz) return null;\n\t// MCP authenticates here but authorizes per tool.\n\tif (pathname === MCP_ENDPOINT_PATH) return null;\n\tif (isSelfServiceRoute(pathname)) return null;\n\tif (grantsAllowRoute(authz.grants, method, pathname)) return null;\n\treturn apiError(\n\t\t\"ROUTE_NOT_GRANTED\",\n\t\t`Your role does not grant ${method} ${toApiRelativePath(pathname)}`,\n\t\t403,\n\t);\n}\n\n/** Resolve grants for a user and put both on locals. */\nasync function attachAuthz(\n\tlocals: App.Locals,\n\temdash: EmDashHandlers,\n\tuser: User,\n\ttokenPolicies: readonly string[] | null,\n): Promise<RequestAuthz> {\n\tconst authz = await attachRequestAuthz(emdash.db, user, tokenPolicies);\n\tlocals.user = authz.user;\n\tlocals.authz = authz;\n\treturn authz;\n}\n\nfunction csrfRejectedResponse(): Response {\n\treturn apiError(\"CSRF_REJECTED\", \"Missing required header\", 403);\n}\n\nfunction mcpUnauthorizedResponse(\n\turl: URL,\n\tconfig?: Parameters<typeof getPublicOrigin>[1],\n): Response {\n\tconst origin = getPublicOrigin(url, config);\n\tconst response = apiError(\"NOT_AUTHENTICATED\", \"Not authenticated\", 401);\n\t// Preserve the OAuth discovery header so MCP clients can find the auth server.\n\tresponse.headers.set(\n\t\t\"WWW-Authenticate\",\n\t\t`Bearer resource_metadata=\"${origin}/.well-known/oauth-protected-resource\"`,\n\t);\n\treturn response;\n}\n\n/**\n * API routes that skip auth — each handles its own access control.\n *\n * Prefix entries match any path starting with that prefix.\n * Exact entries (no trailing slash or wildcard) match that path only.\n */\nconst PUBLIC_API_PREFIXES = [\n\t\"/_emdash/api/setup\",\n\t\"/_emdash/api/auth/login\",\n\t\"/_emdash/api/auth/register\",\n\t\"/_emdash/api/auth/dev-bypass\",\n\t\"/_emdash/api/auth/signup/\",\n\t\"/_emdash/api/auth/magic-link/\",\n\t\"/_emdash/api/auth/invite/\",\n\t\"/_emdash/api/auth/oauth/\",\n\t\"/_emdash/api/oauth/device/token\",\n\t\"/_emdash/api/oauth/device/code\",\n\t\"/_emdash/api/oauth/token\",\n\t\"/_emdash/api/oauth/register\",\n\t\"/_emdash/api/comments/\",\n\t\"/_emdash/api/media/file/\",\n\t\"/_emdash/.well-known/\",\n];\n\nconst PUBLIC_API_EXACT = new Set([\n\t\"/_emdash/api/auth/passkey/options\",\n\t\"/_emdash/api/auth/passkey/verify\",\n\t\"/_emdash/api/auth/mode\",\n\t\"/_emdash/api/oauth/token\",\n\t// Public site search — read-only. The query layer hardcodes status='published'\n\t// so unauthenticated callers only see published content. Admin endpoints\n\t// (/enable, /rebuild, /stats) remain private because they're not in this set.\n\t\"/_emdash/api/search\",\n\t\"/_emdash/api/search/suggest\",\n]);\n\n// Build merged public routes at module load from auth provider descriptors.\n// Routes ending with \"/\" are treated as prefixes; all others are exact matches.\nconst { exact: _providerExactRoutes, prefixes: _providerPrefixRoutes } = (() => {\n\tconst exact = new Set<string>();\n\tconst prefixes: string[] = [];\n\tif (!virtualConfig?.authProviders) return { exact, prefixes };\n\tfor (const route of virtualConfig.authProviders.flatMap((p) => p.publicRoutes ?? [])) {\n\t\tif (route.endsWith(\"/\")) {\n\t\t\tprefixes.push(route);\n\t\t} else {\n\t\t\texact.add(route);\n\t\t}\n\t}\n\treturn { exact, prefixes };\n})();\n\n/**\n * OAuth protocol endpoints that are CSRF-exempt by design.\n *\n * These are RFC-defined endpoints (RFC 6749 §3.2, RFC 7591 §3, RFC 8628 §3.1/§3.4)\n * specified to be called cross-origin by external clients (MCP clients, CLIs,\n * native apps). They authenticate each request on its own merits:\n *\n * - /oauth/token: requires PKCE code_verifier, device_code, or refresh_token\n * - /oauth/register: RFC 7591 dynamic client registration — anonymous by design\n * - /oauth/device/code: RFC 8628 device flow initiation — anonymous by design\n * - /oauth/device/token: requires device_code the client already holds\n *\n * None of these rely on ambient cookie credentials, so browser-based CSRF\n * attacks have nothing to exploit. The endpoints themselves advertise\n * `Access-Control-Allow-Origin: *`. Note: /oauth/device/authorize (the user\n * consent step) is NOT in this list — it is session-authenticated.\n */\nconst CSRF_EXEMPT_PUBLIC_ROUTES = new Set([\n\t\"/_emdash/api/oauth/token\",\n\t\"/_emdash/api/oauth/register\",\n\t\"/_emdash/api/oauth/device/code\",\n\t\"/_emdash/api/oauth/device/token\",\n]);\n\nfunction isPublicEmDashRoute(pathname: string): boolean {\n\tif (PUBLIC_API_EXACT.has(pathname)) return true;\n\tif (PUBLIC_API_PREFIXES.some((p) => pathname.startsWith(p))) return true;\n\tif (_providerExactRoutes.has(pathname)) return true;\n\tif (_providerPrefixRoutes.some((p) => pathname.startsWith(p))) return true;\n\tif (import.meta.env.DEV && pathname === \"/_emdash/api/typegen\") return true;\n\treturn false;\n}\n\nfunction isCsrfExemptPublicRoute(pathname: string): boolean {\n\treturn CSRF_EXEMPT_PUBLIC_ROUTES.has(pathname);\n}\n\nexport const onRequest = defineMiddleware(async (context, next) => {\n\tconst { url } = context;\n\n\t// Only check auth on admin routes and API routes\n\tconst isAdminRoute = url.pathname.startsWith(\"/_emdash/admin\");\n\tconst isSetupRoute = url.pathname.startsWith(\"/_emdash/admin/setup\");\n\tconst isApiRoute = url.pathname.startsWith(\"/_emdash/api\");\n\tconst isPublicApiRoute = isPublicEmDashRoute(url.pathname);\n\n\tconst isPublicRoute = !isAdminRoute && !isApiRoute;\n\n\t// Public API routes skip auth but still need CSRF protection on state-changing methods.\n\t// We check Origin header against the request host (same approach as Astro's checkOrigin).\n\t// This prevents cross-origin form submissions and fetch requests from malicious sites.\n\tif (isPublicApiRoute) {\n\t\tconst method = context.request.method.toUpperCase();\n\t\tif (\n\t\t\tisUnsafeMethod(method) &&\n\t\t\t!isCsrfExemptPublicRoute(url.pathname) // OAuth protocol endpoints — cross-origin by design\n\t\t) {\n\t\t\tconst publicOrigin = getPublicOrigin(url, context.locals.emdash?.config);\n\t\t\tconst csrfError = checkPublicCsrf(context.request, url, publicOrigin);\n\t\t\tif (csrfError) return csrfError;\n\t\t}\n\t\tif (method === \"POST\" && COMMENT_SUBMISSION_PATH.test(url.pathname)) {\n\t\t\treturn handlePublicRouteAuth(context, next);\n\t\t}\n\t\treturn next();\n\t}\n\n\t// Plugin routes: soft auth (resolve user if credentials present, but never block).\n\t// The catch-all handler decides per-route whether auth is required (public vs private).\n\t// Public plugin routes that accept POST are vulnerable to cross-origin form submissions,\n\t// so we apply the same Origin-based CSRF check as other public routes.\n\tconst isPluginRoute = url.pathname.startsWith(\"/_emdash/api/plugins/\");\n\tif (isPluginRoute) {\n\t\tconst method = context.request.method.toUpperCase();\n\t\tif (method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\") {\n\t\t\tconst publicOrigin = getPublicOrigin(url, context.locals.emdash?.config);\n\t\t\tconst csrfError = checkPublicCsrf(context.request, url, publicOrigin);\n\t\t\tif (csrfError) return csrfError;\n\t\t}\n\t\treturn handlePluginRouteAuth(context, next);\n\t}\n\n\t// Setup routes: skip auth but still enforce CSRF on state-changing methods\n\tif (isSetupRoute) {\n\t\tconst method = context.request.method.toUpperCase();\n\t\tif (method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\") {\n\t\t\tconst csrfHeader = context.request.headers.get(\"X-EmDash-Request\");\n\t\t\tif (csrfHeader !== \"1\") {\n\t\t\t\treturn apiError(\"CSRF_REJECTED\", \"Missing required header\", 403);\n\t\t\t}\n\t\t}\n\t\treturn next();\n\t}\n\n\t// For public routes: soft auth check (set locals.user if session exists, but never block)\n\tif (isPublicRoute) {\n\t\treturn handlePublicRouteAuth(context, next);\n\t}\n\n\t// --- Everything below is /_emdash (admin + API) ---\n\n\t// Try Bearer token auth first (API tokens and OAuth tokens).\n\t// If successful, skip CSRF (tokens aren't ambient credentials like cookies).\n\tconst bearerResult = await handleBearerAuth(context);\n\n\tif (bearerResult === \"invalid\") {\n\t\tconst response = apiError(\"INVALID_TOKEN\", \"Invalid or expired token\", 401);\n\t\t// Add WWW-Authenticate header on MCP endpoint 401s to trigger OAuth discovery\n\t\tif (url.pathname === \"/_emdash/api/mcp\") {\n\t\t\tconst origin = getPublicOrigin(url, context.locals.emdash?.config);\n\t\t\tresponse.headers.set(\n\t\t\t\t\"WWW-Authenticate\",\n\t\t\t\t`Bearer resource_metadata=\"${origin}/.well-known/oauth-protected-resource\"`,\n\t\t\t);\n\t\t}\n\t\treturn response;\n\t}\n\n\tconst isTokenAuth = bearerResult === \"authenticated\";\n\n\t// MCP discovery/tooling is bearer-only. Session/external auth should never\n\t// be consulted for this endpoint, and unauthenticated requests must return\n\t// the OAuth discovery-style 401 response.\n\tconst method = context.request.method.toUpperCase();\n\tconst isMcpEndpoint = url.pathname === MCP_ENDPOINT_PATH;\n\tif (isMcpEndpoint && !isTokenAuth) {\n\t\treturn mcpUnauthorizedResponse(url, context.locals.emdash?.config);\n\t}\n\n\t// CSRF protection: require X-EmDash-Request header on state-changing requests.\n\t// Skip for token-authenticated requests (tokens aren't ambient credentials).\n\t// Browsers block cross-origin custom headers, so this prevents CSRF without tokens.\n\t// OAuth authorize consent is exempt: it's a standard HTML form POST that can't\n\t// include custom headers. The consent flow is protected by session + single-use codes.\n\tconst isOAuthConsent = url.pathname.startsWith(\"/_emdash/oauth/authorize\");\n\tif (\n\t\tisApiRoute &&\n\t\t!isTokenAuth &&\n\t\t!isOAuthConsent &&\n\t\tisUnsafeMethod(method) &&\n\t\t!isPublicApiRoute\n\t) {\n\t\tconst csrfHeader = context.request.headers.get(\"X-EmDash-Request\");\n\t\tif (csrfHeader !== \"1\") {\n\t\t\treturn csrfRejectedResponse();\n\t\t}\n\t}\n\n\t// If already authenticated via Bearer token, enforce scope then skip session/external auth\n\tif (isTokenAuth) {\n\t\t// Policy tokens are gated by their route grants. Legacy scoped tokens\n\t\t// (and OAuth tokens) keep the prefix/method scope table as well.\n\t\tconst routeError = enforceRouteGrant(context.locals, url.pathname, method);\n\t\tif (routeError) return routeError;\n\n\t\tconst response = await next();\n\t\tif (!import.meta.env.DEV) {\n\t\t\tresponse.headers.set(\n\t\t\t\t\"Content-Security-Policy\",\n\t\t\t\tbuildEmDashCsp(\n\t\t\t\t\tcontext.locals.emdash?.config.experimental?.registry,\n\t\t\t\t\tgetConfiguredStorageEndpoint(\n\t\t\t\t\t\tcontext.locals.emdash?.config.storage,\n\t\t\t\t\t\tcontext.locals.emdash?.storage,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn response;\n\t}\n\n\tconst response = await handleEmDashAuth(context, next);\n\n\t// Set strict CSP on all /_emdash responses (prod only)\n\tif (!import.meta.env.DEV) {\n\t\tresponse.headers.set(\n\t\t\t\"Content-Security-Policy\",\n\t\t\tbuildEmDashCsp(\n\t\t\t\tcontext.locals.emdash?.config.experimental?.registry,\n\t\t\t\tgetConfiguredStorageEndpoint(\n\t\t\t\t\tcontext.locals.emdash?.config.storage,\n\t\t\t\t\tcontext.locals.emdash?.storage,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t}\n\n\treturn response;\n});\n\n/**\n * Auth handling for /_emdash routes. Returns a Response from either\n * an auth error/redirect or the downstream route handler.\n */\nasync function handleEmDashAuth(\n\tcontext: Parameters<Parameters<typeof defineMiddleware>[0]>[0],\n\tnext: Parameters<Parameters<typeof defineMiddleware>[0]>[1],\n): Promise<Response> {\n\tconst { url, locals } = context;\n\tconst { emdash } = locals;\n\n\tconst isPublicAdminRoute =\n\t\turl.pathname.startsWith(\"/_emdash/admin/login\") ||\n\t\turl.pathname.startsWith(\"/_emdash/admin/invite/accept\");\n\tconst isApiRoute = url.pathname.startsWith(\"/_emdash/api\");\n\n\tif (!emdash?.db) {\n\t\t// No database - let the admin handle this error\n\t\treturn next();\n\t}\n\n\t// Determine auth mode from config\n\tconst authMode = getAuthMode(emdash.config);\n\n\tif (authMode.type === \"external\") {\n\t\t// In dev mode, fall back to passkey auth since external JWT won't be present\n\t\tif (import.meta.env.DEV) {\n\t\t\tif (isPublicAdminRoute) {\n\t\t\t\treturn next();\n\t\t\t}\n\n\t\t\treturn handlePasskeyAuth(context, next, isApiRoute);\n\t\t}\n\n\t\t// External auth provider (Cloudflare Access, etc.)\n\t\treturn handleExternalAuth(context, next, authMode, isApiRoute);\n\t}\n\n\t// Passkey authentication (default)\n\tif (isPublicAdminRoute) {\n\t\treturn next();\n\t}\n\n\treturn handlePasskeyAuth(context, next, isApiRoute);\n}\n\n/**\n * Plugin-route auth. Resolves the user in three steps, stopping at the first that\n * applies:\n *\n * 1. Bearer token (all modes). A valid token authenticates; an invalid/expired one\n *    returns 401 (we never silently downgrade a bad token to anonymous).\n * 2. External provider — only for a *private* route in production external-auth\n *    mode. Here `handleExternalAuth` is the sole authority: the provider (e.g.\n *    Cloudflare Access) is re-verified on every request, so it hard-blocks with\n *    401 on failure. It does persist an EmDash session (so public pages can\n *    identify the user), but on these routes that session is deliberately NOT\n *    consulted as a fallback — the provider check is authoritative every time.\n * 3. Session — everything else (non-external mode, DEV, and all public routes).\n *    This is soft: it sets `locals.user` if a session exists but never blocks.\n *\n * Public routes are always allowed through. The catch-all handler still enforces\n * the `plugins:manage` permission and CSRF for private invocations.\n */\nasync function handlePluginRouteAuth(\n\tcontext: Parameters<Parameters<typeof defineMiddleware>[0]>[0],\n\tnext: Parameters<Parameters<typeof defineMiddleware>[0]>[1],\n): Promise<Response> {\n\tconst { locals, url } = context;\n\tconst { emdash } = locals;\n\n\ttry {\n\t\t// Try Bearer token auth first (API tokens and OAuth tokens)\n\t\tconst bearerResult = await handleBearerAuth(context);\n\t\tif (bearerResult === \"authenticated\") {\n\t\t\t// User and grants are set on locals by handleBearerAuth.\n\t\t\t// Private plugin routes sit inside the route grants like any other.\n\t\t\tif (!isPublicPluginApiRoute(url.pathname, emdash)) {\n\t\t\t\tconst routeError = enforceRouteGrant(\n\t\t\t\t\tlocals,\n\t\t\t\t\turl.pathname,\n\t\t\t\t\tcontext.request.method.toUpperCase(),\n\t\t\t\t);\n\t\t\t\tif (routeError) return routeError;\n\t\t\t}\n\t\t\treturn next();\n\t\t}\n\t\tif (bearerResult === \"invalid\") {\n\t\t\t// A token was presented but is invalid/expired — return 401 so the\n\t\t\t// caller knows their token is bad (don't silently downgrade to no-auth).\n\t\t\treturn apiError(\"INVALID_TOKEN\", \"Invalid or expired token\", 401);\n\t\t}\n\t\t// \"none\" — no token presented, try external/session auth below.\n\t} catch (error) {\n\t\tconsole.error(\"Plugin route bearer auth error:\", error);\n\t}\n\n\tconst authMode = getAuthMode(emdash?.config);\n\tif (\n\t\tauthMode.type === \"external\" &&\n\t\t!import.meta.env.DEV &&\n\t\t!isPublicPluginApiRoute(url.pathname, emdash)\n\t) {\n\t\treturn handleExternalAuth(context, next, authMode, true);\n\t}\n\n\ttry {\n\t\t// Try session auth (sets locals.user if session exists)\n\t\tconst { session } = context;\n\t\tconst sessionUser = await resolveSessionUser(session);\n\t\tif (sessionUser?.id && emdash?.db) {\n\t\t\tconst adapter = createKyselyAdapter(emdash.db);\n\t\t\tconst user = await adapter.getUserById(sessionUser.id);\n\t\t\tif (user && !user.disabled) {\n\t\t\t\tawait attachAuthz(locals, emdash, user, null);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\t// Log but don't block — public routes should still work without session\n\t\tconsole.error(\"Plugin route session auth error:\", error);\n\t}\n\n\tif (locals.authz && !isPublicPluginApiRoute(url.pathname, emdash)) {\n\t\tconst routeError = enforceRouteGrant(\n\t\t\tlocals,\n\t\t\turl.pathname,\n\t\t\tcontext.request.method.toUpperCase(),\n\t\t);\n\t\tif (routeError) return routeError;\n\t}\n\n\treturn next();\n}\n\nfunction isPublicPluginApiRoute(pathname: string, emdash: EmDashHandlers | undefined): boolean {\n\tconst prefix = \"/_emdash/api/plugins/\";\n\tconst route = pathname.slice(prefix.length);\n\tconst slashIndex = route.indexOf(\"/\");\n\tif (slashIndex <= 0 || !emdash?.getPluginRouteMeta) return false;\n\n\treturn (\n\t\temdash.getPluginRouteMeta(route.slice(0, slashIndex), route.slice(slashIndex))?.public === true\n\t);\n}\n\n/**\n * Soft auth check for public routes with edit mode cookie.\n * Checks the session and sets locals.user if valid, but never blocks the request.\n */\nasync function handlePublicRouteAuth(\n\tcontext: Parameters<Parameters<typeof defineMiddleware>[0]>[0],\n\tnext: Parameters<Parameters<typeof defineMiddleware>[0]>[1],\n): Promise<Response> {\n\tconst { locals, session } = context;\n\tconst { emdash } = locals;\n\n\ttry {\n\t\tconst sessionUser = await resolveSessionUser(session);\n\t\tif (sessionUser?.id && emdash?.db) {\n\t\t\tconst adapter = createKyselyAdapter(emdash.db);\n\t\t\tconst user = await adapter.getUserById(sessionUser.id);\n\t\t\tif (user && !user.disabled) {\n\t\t\t\tawait attachAuthz(locals, emdash, user, null);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Silently continue — public page should render normally\n\t}\n\n\treturn next();\n}\n\n/**\n * Handle external auth provider authentication (Cloudflare Access, etc.)\n */\nasync function handleExternalAuth(\n\tcontext: Parameters<Parameters<typeof defineMiddleware>[0]>[0],\n\tnext: Parameters<Parameters<typeof defineMiddleware>[0]>[1],\n\tauthMode: ExternalAuthMode,\n\tisApiRoute: boolean,\n): Promise<Response> {\n\tconst { locals, request, url } = context;\n\tconst { emdash } = locals;\n\n\ttry {\n\t\t// Use the authenticate function from the virtual module\n\t\t// (statically imported at build time to work with Cloudflare Workers)\n\t\tif (typeof virtualAuthenticate !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Auth provider ${authMode.entrypoint} does not export an authenticate function`,\n\t\t\t);\n\t\t}\n\n\t\t// Authenticate via the provider\n\t\tconst authResult = await virtualAuthenticate(request, authMode.config);\n\n\t\t// Get external auth config for auto-provision settings\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- narrowing AuthModeConfig to ExternalAuthConfig after provider check\n\t\tconst externalConfig = authMode.config as ExternalAuthConfig;\n\n\t\t// Find or create user\n\t\tconst adapter = createKyselyAdapter(emdash.db);\n\t\tlet user = await adapter.getUserByEmail(authResult.email);\n\n\t\tif (!user) {\n\t\t\t// User doesn't exist\n\t\t\tif (externalConfig.autoProvision === false) {\n\t\t\t\treturn new Response(\"User not authorized\", {\n\t\t\t\t\tstatus: 403,\n\t\t\t\t\theaders: { \"Content-Type\": \"text/plain\", ...MW_CACHE_HEADERS },\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Check if this is the first user (they become admin)\n\t\t\tconst userCount = await emdash.db\n\t\t\t\t.selectFrom(\"users\")\n\t\t\t\t.select(emdash.db.fn.count(\"id\").as(\"count\"))\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tconst isFirstUser = Number(userCount?.count ?? 0) === 0;\n\t\t\tconst role = isFirstUser ? ROLE_ADMIN : authResult.role;\n\n\t\t\t// Create user\n\t\t\tconst now = new Date().toISOString();\n\t\t\tconst newUser = {\n\t\t\t\tid: ulid(),\n\t\t\t\temail: authResult.email,\n\t\t\t\tname: authResult.name,\n\t\t\t\trole,\n\t\t\t\trole_id: `role:${builtinRoleForLevel(role).slug}`,\n\t\t\t\temail_verified: 1,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t};\n\n\t\t\tawait emdash.db.insertInto(\"users\").values(newUser).execute();\n\n\t\t\tuser = await adapter.getUserByEmail(authResult.email);\n\n\t\t\tconsole.log(\n\t\t\t\t`[external-auth] Provisioned user: ${authResult.email} (role: ${role}, first: ${isFirstUser})`,\n\t\t\t);\n\t\t} else {\n\t\t\t// User exists - check if we need to sync anything\n\t\t\tconst updates: Record<string, unknown> = {};\n\t\t\tlet newName: string | undefined;\n\t\t\tlet newRole: RoleLevel | undefined;\n\n\t\t\t// Sync name from provider if provider provides one and local differs\n\t\t\tif (authResult.name && user.name !== authResult.name) {\n\t\t\t\tnewName = authResult.name;\n\t\t\t\tupdates.name = newName;\n\t\t\t}\n\n\t\t\t// Sync role if enabled\n\t\t\tif (externalConfig.syncRoles && user.role !== authResult.role) {\n\t\t\t\tnewRole = authResult.role;\n\t\t\t\tupdates.role = newRole;\n\t\t\t}\n\n\t\t\tif (Object.keys(updates).length > 0) {\n\t\t\t\tupdates.updated_at = new Date().toISOString();\n\t\t\t\tawait emdash.db.updateTable(\"users\").set(updates).where(\"id\", \"=\", user.id).execute();\n\n\t\t\t\tuser = {\n\t\t\t\t\t...user,\n\t\t\t\t\t...(newName ? { name: newName } : {}),\n\t\t\t\t\t...(newRole ? { role: newRole } : {}),\n\t\t\t\t};\n\n\t\t\t\tconsole.log(\n\t\t\t\t\t`[external-auth] Updated user ${authResult.email}:`,\n\t\t\t\t\tObject.keys(updates).filter((k) => k !== \"updated_at\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (!user) {\n\t\t\t// This shouldn't happen, but handle it gracefully\n\t\t\treturn new Response(\"Failed to provision user\", {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain\", ...MW_CACHE_HEADERS },\n\t\t\t});\n\t\t}\n\n\t\t// Check if user is disabled locally\n\t\tif (user.disabled) {\n\t\t\treturn new Response(\"Account disabled\", {\n\t\t\t\tstatus: 403,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain\", ...MW_CACHE_HEADERS },\n\t\t\t});\n\t\t}\n\n\t\t// Set user in locals, with the grants their role resolves to\n\t\tawait attachAuthz(locals, emdash, user, null);\n\n\t\t// Persist to session so public pages can identify the user\n\t\t// (external auth headers are only verified on /_emdash routes)\n\t\tconst { session } = context;\n\t\tsession?.set(\"user\", { id: user.id });\n\n\t\tif (isApiRoute) {\n\t\t\tconst routeError = enforceRouteGrant(locals, url.pathname, request.method.toUpperCase());\n\t\t\tif (routeError) return routeError;\n\t\t}\n\n\t\treturn next();\n\t} catch (error) {\n\t\tconsole.error(\"[external-auth] Auth error:\", error);\n\n\t\treturn new Response(\"Authentication failed\", {\n\t\t\tstatus: 401,\n\t\t\theaders: { \"Content-Type\": \"text/plain\", ...MW_CACHE_HEADERS },\n\t\t});\n\t}\n}\n\n/**\n * Try to authenticate via Bearer token (API token or OAuth token).\n *\n * Returns:\n * - \"authenticated\" if token is valid and user is resolved\n * - \"invalid\" if a token was provided but is invalid/expired\n * - \"none\" if no Bearer token was provided\n */\nasync function handleBearerAuth(\n\tcontext: Parameters<Parameters<typeof defineMiddleware>[0]>[0],\n): Promise<\"authenticated\" | \"invalid\" | \"none\"> {\n\tconst authHeader = context.request.headers.get(\"Authorization\");\n\tif (!authHeader?.startsWith(\"Bearer \")) return \"none\";\n\n\tconst token = authHeader.slice(7);\n\tif (!token) return \"none\";\n\n\tconst { locals } = context;\n\tconst { emdash } = locals;\n\tif (!emdash?.db) return \"none\";\n\n\t// Resolve token based on prefix\n\tlet resolved: { userId: string; policies: string[] | null; cors?: boolean } | null = null;\n\n\tif (token.startsWith(\"ec_pat_\")) {\n\t\tresolved = await resolveApiToken(emdash.db, token);\n\t} else if (token.startsWith(\"ec_oat_\")) {\n\t\tresolved = await resolveOAuthToken(emdash.db, token);\n\t} else {\n\t\t// Unknown token format\n\t\treturn \"invalid\";\n\t}\n\n\tif (!resolved) return \"invalid\";\n\n\t// Look up the user\n\tconst adapter = createKyselyAdapter(emdash.db);\n\tconst user = await adapter.getUserById(resolved.userId);\n\n\tif (!user || user.disabled) return \"invalid\";\n\n\t// Resolve the owner's grants and clamp the token inside them: a token can\n\t// never do more than the user who minted it, however it was scoped.\n\tconst authz = await attachAuthz(locals, emdash, user, resolved.policies);\n\tlocals.tokenPolicies = resolved.policies;\n\tlocals.tokenAuth = true;\n\tlocals.tokenCors = resolved.cors === true;\n\n\treturn \"authenticated\";\n}\n\n/**\n * Handle passkey (session-based) authentication\n */\nasync function handlePasskeyAuth(\n\tcontext: Parameters<Parameters<typeof defineMiddleware>[0]>[0],\n\tnext: Parameters<Parameters<typeof defineMiddleware>[0]>[1],\n\tisApiRoute: boolean,\n): Promise<Response> {\n\tconst { url, locals, session } = context;\n\tconst { emdash } = locals;\n\n\ttry {\n\t\t// Check session for user (session.get returns a Promise)\n\t\tconst sessionUser = await resolveSessionUser(session);\n\n\t\tif (!sessionUser?.id) {\n\t\t\tif (isApiRoute) {\n\t\t\t\treturn apiError(\"NOT_AUTHENTICATED\", \"Not authenticated\", 401);\n\t\t\t}\n\t\t\tconst loginUrl = new URL(\"/_emdash/admin/login\", await loginOrigin(url, emdash));\n\t\t\tloginUrl.searchParams.set(\"redirect\", url.pathname);\n\t\t\treturn context.redirect(loginUrl.toString());\n\t\t}\n\n\t\t// Get full user from database\n\t\tconst adapter = createKyselyAdapter(emdash.db);\n\t\tconst user = await adapter.getUserById(sessionUser.id);\n\n\t\tif (!user) {\n\t\t\t// User no longer exists - clear session\n\t\t\tsession?.destroy();\n\t\t\tif (isApiRoute) {\n\t\t\t\treturn apiError(\"NOT_FOUND\", \"User not found\", 401);\n\t\t\t}\n\t\t\tconst loginUrl = new URL(\"/_emdash/admin/login\", await loginOrigin(url, emdash));\n\t\t\treturn context.redirect(loginUrl.toString());\n\t\t}\n\n\t\t// Check if user is disabled\n\t\tif (user.disabled) {\n\t\t\tsession?.destroy();\n\t\t\tif (isApiRoute) {\n\t\t\t\treturn apiError(\"ACCOUNT_DISABLED\", \"Account disabled\", 403);\n\t\t\t}\n\t\t\tconst loginUrl = new URL(\"/_emdash/admin/login\", await loginOrigin(url, emdash));\n\t\t\tloginUrl.searchParams.set(\"error\", \"account_disabled\");\n\t\t\treturn context.redirect(loginUrl.toString());\n\t\t}\n\n\t\t// Set user in locals for use by routes, with the grants their role resolves to\n\t\tawait attachAuthz(locals, emdash, user, null);\n\t\tif (isApiRoute) {\n\t\t\tconst routeError = enforceRouteGrant(\n\t\t\t\tlocals,\n\t\t\t\turl.pathname,\n\t\t\t\tcontext.request.method.toUpperCase(),\n\t\t\t);\n\t\t\tif (routeError) return routeError;\n\t\t}\n\t} catch (error) {\n\t\tconsole.error(\"Auth middleware error:\", error);\n\t\t// On error, redirect to login\n\t\treturn context.redirect(\"/_emdash/admin/login\");\n\t}\n\n\treturn next();\n}\n\n// =============================================================================\n// Token scope enforcement\n// =============================================================================\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,gBACf,SACA,KACA,cACkB;AAGlB,KADmB,QAAQ,QAAQ,IAAI,mBAAmB,KACvC,IAAK,QAAO;CAG/B,MAAM,SAAS,QAAQ,QAAQ,IAAI,SAAS;AAC5C,KAAI,QAAQ;AACX,MAAI;GACH,MAAM,YAAY,IAAI,IAAI,OAAO;AAEjC,OAAI,UAAU,WAAW,IAAI,OAAQ,QAAO;AAC5C,OAAI,gBAAgB,UAAU,WAAW,aAAc,QAAO;UACvD;AAIR,SAAO,SAAS,iBAAiB,gCAAgC,IAAI;;AAMtE,QAAO;;;;;;ACtCR,MAAM,wBAAwB;;;;;;;;;;;;;;AAe9B,SAAgB,6BACf,SACA,gBACqB;CACrB,MAAM,SAAS,SAAS;AACxB,KAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,cAAc,QAAQ;EAC1E,MAAM,WAAW,OAAO;AACxB,MAAI,OAAO,aAAa,SAAU,QAAO;;AAG1C,KAAI,SAAS,eAAe,uBAAuB;EAClD,MAAM,cACL,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,cAAc;AAC3E,MAAI,YAAa,QAAO;;AAGzB,QAAO,gBAAgB,yBAAyB;;AAGjD,SAAS,4BACR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