@rebasepro/server 0.28.2 → 0.29.0-canary.g0e3a0e7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/{GCSStorageController-LXeAF6Ks.js → GCSStorageController-Ch3Ridyt.js} +4 -4
  2. package/dist/{GCSStorageController-LXeAF6Ks.js.map → GCSStorageController-Ch3Ridyt.js.map} +1 -1
  3. package/dist/{S3StorageController-CVKMUXo_.js → S3StorageController-CmNMg7Gu.js} +4 -4
  4. package/dist/{S3StorageController-CVKMUXo_.js.map → S3StorageController-CmNMg7Gu.js.map} +1 -1
  5. package/dist/{access-BDz4FO9D.js → access-BZjeLhf5.js} +7 -7
  6. package/dist/{access-BDz4FO9D.js.map → access-BZjeLhf5.js.map} +1 -1
  7. package/dist/api/rest/api-generator.d.ts +19 -0
  8. package/dist/{ast-schema-editor-C4bDSb61.js → ast-schema-editor-Dg7BWKE3.js} +3 -3
  9. package/dist/{ast-schema-editor-C4bDSb61.js.map → ast-schema-editor-Dg7BWKE3.js.map} +1 -1
  10. package/dist/auth/cookie-utils.d.ts +14 -6
  11. package/dist/auth/rate-limiter.d.ts +8 -0
  12. package/dist/{auth-CZGfVKcL.js → auth-CSWKaSgJ.js} +70 -18
  13. package/dist/auth-CSWKaSgJ.js.map +1 -0
  14. package/dist/{auth_adapter-B7RUMk6e.js → auth_adapter-HFv5axIT.js} +20 -2
  15. package/dist/auth_adapter-HFv5axIT.js.map +1 -0
  16. package/dist/backend/options.d.ts +3 -0
  17. package/dist/backend-CaG_Jyso.js.map +1 -1
  18. package/dist/{backup-BmzY9xdN.js → backup-woinIDjt.js} +9 -9
  19. package/dist/{backup-BmzY9xdN.js.map → backup-woinIDjt.js.map} +1 -1
  20. package/dist/boot/driver.d.ts +4 -0
  21. package/dist/boot/sources.d.ts +7 -0
  22. package/dist/{branch-routes-DpgaeTJl.js → branch-routes-F5VIJrZp.js} +3 -3
  23. package/dist/{branch-routes-DpgaeTJl.js.map → branch-routes-F5VIJrZp.js.map} +1 -1
  24. package/dist/{contract-routes-vYiBHbjI.js → contract-routes-D8Vsxjx8.js} +3 -3
  25. package/dist/{contract-routes-vYiBHbjI.js.map → contract-routes-D8Vsxjx8.js.map} +1 -1
  26. package/dist/{cron-loader-C_C-lNgG.js → cron-loader-n9Uh_E1a.js} +3 -3
  27. package/dist/{cron-loader-C_C-lNgG.js.map → cron-loader-n9Uh_E1a.js.map} +1 -1
  28. package/dist/{cron-routes-DlwOV6zl.js → cron-routes-mLexIC9F.js} +4 -4
  29. package/dist/{cron-routes-DlwOV6zl.js.map → cron-routes-mLexIC9F.js.map} +1 -1
  30. package/dist/{cron-scheduler-6ipIm5mm.js → cron-scheduler-DhxuCDuI.js} +2 -2
  31. package/dist/{cron-scheduler-6ipIm5mm.js.map → cron-scheduler-DhxuCDuI.js.map} +1 -1
  32. package/dist/{cron-store-KIOM8LCC.js → cron-store-DzKz7jXF.js} +2 -2
  33. package/dist/{cron-store-KIOM8LCC.js.map → cron-store-DzKz7jXF.js.map} +1 -1
  34. package/dist/data_driver-D0mg1Y_x.js.map +1 -1
  35. package/dist/dist-B4YtgTMh.js +19359 -0
  36. package/dist/dist-B4YtgTMh.js.map +1 -0
  37. package/dist/env.d.ts +7 -0
  38. package/dist/{errors-DIWnZIDY.js → errors-DpTMfX77.js} +58 -8
  39. package/dist/errors-DpTMfX77.js.map +1 -0
  40. package/dist/{field-access-KYk8RGOx.js → field-access-CzKjatID.js} +3 -3
  41. package/dist/{field-access-KYk8RGOx.js.map → field-access-CzKjatID.js.map} +1 -1
  42. package/dist/{filter-dialect-CE4bloug.js → filter-dialect-C5wfpopB.js} +110 -9
  43. package/dist/{filter-dialect-CE4bloug.js.map → filter-dialect-C5wfpopB.js.map} +1 -1
  44. package/dist/{function-loader-CKB9b4uP.js → function-loader-BzKo2Oiu.js} +2 -2
  45. package/dist/{function-loader-CKB9b4uP.js.map → function-loader-BzKo2Oiu.js.map} +1 -1
  46. package/dist/{function-routes-DLaXaiQA.js → function-routes-CQ0z3WDt.js} +2 -2
  47. package/dist/{function-routes-DLaXaiQA.js.map → function-routes-CQ0z3WDt.js.map} +1 -1
  48. package/dist/functions/index.d.ts +1 -0
  49. package/dist/functions/index.js +10 -29
  50. package/dist/functions/index.js.map +1 -1
  51. package/dist/functions/wait-until.d.ts +29 -1
  52. package/dist/{history-recorder-BE4HWR-M.js → history-recorder-wkBuX7Np.js} +2 -2
  53. package/dist/{history-recorder-BE4HWR-M.js.map → history-recorder-wkBuX7Np.js.map} +1 -1
  54. package/dist/index.d.ts +4 -1
  55. package/dist/index.es.js +2260 -1284
  56. package/dist/index.es.js.map +1 -1
  57. package/dist/init/surfaces.d.ts +19 -3
  58. package/dist/{jobs-CXTs9qXH.js → jobs-D61qYEGt.js} +2 -2
  59. package/dist/{jobs-CXTs9qXH.js.map → jobs-D61qYEGt.js.map} +1 -1
  60. package/dist/{jwt-5EvX3lQa.js → jwt-CBmQXYs-.js} +2 -2
  61. package/dist/{jwt-5EvX3lQa.js.map → jwt-CBmQXYs-.js.map} +1 -1
  62. package/dist/{keys-DJ1ZNcZi.js → keys-Cd_4l48g.js} +2 -2
  63. package/dist/{keys-DJ1ZNcZi.js.map → keys-Cd_4l48g.js.map} +1 -1
  64. package/dist/{logs-routes-DXLvMasE.js → logs-routes-08LiyYua.js} +2 -2
  65. package/dist/{logs-routes-DXLvMasE.js.map → logs-routes-08LiyYua.js.map} +1 -1
  66. package/dist/mcp/consent-page.d.ts +14 -1
  67. package/dist/mcp/mcp-apps.d.ts +51 -17
  68. package/dist/mcp/mcp-routes.d.ts +6 -1
  69. package/dist/mcp/mcp-tools.d.ts +44 -1
  70. package/dist/mcp/mcp-view.d.ts +107 -0
  71. package/dist/mcp/oauth-metadata.d.ts +7 -1
  72. package/dist/mcp/show-app-guide.d.ts +1 -0
  73. package/dist/metrics/database.d.ts +69 -0
  74. package/dist/metrics/db-connection-errors.d.ts +21 -0
  75. package/dist/{offline-BjJdcVBb-BOzzsnrh.js → offline-BjJdcVBb-B_bOcnDC.js} +4 -4
  76. package/dist/{offline-BjJdcVBb-BOzzsnrh.js.map → offline-BjJdcVBb-B_bOcnDC.js.map} +1 -1
  77. package/dist/{offline-store-Cxhh99Q--FB6fSf5A.js → offline-store-Cxhh99Q--DQ-M1M8d.js} +4 -4
  78. package/dist/{offline-store-Cxhh99Q--FB6fSf5A.js.map → offline-store-Cxhh99Q--DQ-M1M8d.js.map} +1 -1
  79. package/dist/{openapi-generator-B6aw_KuR.js → openapi-generator-B3LsKCon.js} +4 -4
  80. package/dist/{openapi-generator-B6aw_KuR.js.map → openapi-generator-B3LsKCon.js.map} +1 -1
  81. package/dist/{proxy-2nS5N63I.js → proxy-LUsudeht.js} +2 -2
  82. package/dist/{proxy-2nS5N63I.js.map → proxy-LUsudeht.js.map} +1 -1
  83. package/dist/{query-parser-DFVCjW5i.js → query-parser-C90z8csB.js} +6 -6
  84. package/dist/{query-parser-DFVCjW5i.js.map → query-parser-C90z8csB.js.map} +1 -1
  85. package/dist/{request-timeout-Cqm4JXtZ.js → request-timeout-DW2OBWfJ.js} +2 -2
  86. package/dist/{request-timeout-Cqm4JXtZ.js.map → request-timeout-DW2OBWfJ.js.map} +1 -1
  87. package/dist/{rls-simulator-routes-D5-XfjzW.js → rls-simulator-routes-igGu-giT.js} +4 -4
  88. package/dist/{rls-simulator-routes-D5-XfjzW.js.map → rls-simulator-routes-igGu-giT.js.map} +1 -1
  89. package/dist/{schema-editor-routes-DzSe6V0a.js → schema-editor-routes-kF1ZKCB2.js} +4 -4
  90. package/dist/{schema-editor-routes-DzSe6V0a.js.map → schema-editor-routes-kF1ZKCB2.js.map} +1 -1
  91. package/dist/serve-spa.d.ts +2 -10
  92. package/dist/{soft-delete-params-9lKBAlDw.js → soft-delete-params-DDRmxT2z.js} +2 -2
  93. package/dist/{soft-delete-params-9lKBAlDw.js.map → soft-delete-params-DDRmxT2z.js.map} +1 -1
  94. package/dist/{sql-export-routes-BxMqgAFX.js → sql-export-routes-DObpbf8x.js} +3 -3
  95. package/dist/{sql-export-routes-BxMqgAFX.js.map → sql-export-routes-DObpbf8x.js.map} +1 -1
  96. package/dist/{src-JQNz7cWv.js → src-BXDkXOtq.js} +2 -1
  97. package/dist/{src-JQNz7cWv.js.map → src-BXDkXOtq.js.map} +1 -1
  98. package/dist/{upload-validation-IYXn4xcm.js → upload-validation-B-psYLaN.js} +2 -2
  99. package/dist/{upload-validation-IYXn4xcm.js.map → upload-validation-B-psYLaN.js.map} +1 -1
  100. package/package.json +5 -5
  101. package/dist/auth-CZGfVKcL.js.map +0 -1
  102. package/dist/auth_adapter-B7RUMk6e.js.map +0 -1
  103. package/dist/dist-CT9HJehq.js +0 -22
  104. package/dist/dist-CT9HJehq.js.map +0 -1
  105. package/dist/errors-DIWnZIDY.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth_adapter-B7RUMk6e.js","names":[],"sources":["../../types/src/types/auth_adapter.ts"],"sourcesContent":["/**\n * @module AuthAdapter\n *\n * Pluggable authentication abstraction for Rebase.\n *\n * An `AuthAdapter` decouples authentication from the database layer,\n * allowing users to bring their own auth system (Clerk, Auth0, or other\n * external providers) while keeping the Rebase admin frontend fully functional.\n *\n * @example Built-in auth (default — zero config change)\n * ```ts\n * initializeRebaseBackend({\n * auth: { jwtSecret: \"...\", google: { clientId: \"...\" } },\n * database: createPostgresAdapter({ ... }),\n * });\n * ```\n *\n * @example Custom auth\n * ```ts\n * import { createCustomAuthAdapter } from \"@rebasepro/server\";\n *\n * initializeRebaseBackend({\n * auth: createCustomAuthAdapter({\n * verifyRequest: async (req) => { ... },\n * }),\n * database: createPostgresAdapter({ ... }),\n * });\n * ```\n *\n * @group Auth\n */\n\n/**\n * A sub-app an adapter hands back for the framework to mount.\n *\n * Structural on purpose. This was `Hono<any, any, any>`, and that one\n * `import type { Hono } from \"hono\"` was the whole reason `@rebasepro/types`\n * peer-depended on hono — which npm and pnpm auto-install, so **every browser\n * app that installed `@rebasepro/client` got a 2.8 MB server framework in its\n * lockfile and its security scanners**, for a type used by two optional methods\n * that a browser app can never call.\n *\n * The shape is the same duck-type the function loader already validates at\n * runtime (`isHonoLike`: a `fetch` method and a `routes` array), and a real\n * `Hono` satisfies it — asserted in `auth_adapter.test.ts`, which does import\n * hono, because a structural type is only worth having if something proves the\n * real thing still fits.\n *\n * @group Auth\n */\nexport interface MountableRouter {\n /** Handle a request. Hono, Elysia and a hand-rolled router all have this. */\n fetch: (request: Request) => Response | Promise<Response>;\n /** The routes the sub-app declares. Only its presence is contractual. */\n routes: readonly unknown[];\n}\n\n// ─── Impersonation ───────────────────────────────────────────────────────────\n\n/**\n * The request header that asks for a data-plane request to run as another\n * user, named by uid.\n *\n * The server honours it only on a signed-in administrator's own session —\n * never on an API key or the service key — and only through an adapter that\n * implements {@link AuthAdapter.resolveUser}. Everywhere else a request that\n * carries it is refused, never run as its caller.\n *\n * @group Auth\n */\nexport const IMPERSONATE_HEADER = \"x-rebase-impersonate\";\n\n// ─── Access simulation ───────────────────────────────────────────────────────\n\n/**\n * The request header that asks for a data-plane request to run as a role —\n * the RLS simulator's \"view as\". Alone it runs as a signed-in holder of that\n * role who owns no rows; with {@link SIMULATE_USER_ID_HEADER} it runs as that\n * uid holding that role, whether or not such an account exists.\n *\n * `anon` (or `anonymous`) runs as a caller with no session at all.\n *\n * Like {@link IMPERSONATE_HEADER}, only a signed-in administrator's own session\n * may send it; anyone else is refused with 403, never answered as themselves.\n *\n * @group Auth\n */\nexport const SIMULATE_ROLE_HEADER = \"x-rebase-simulate-role\";\n\n/**\n * The uid a simulated request runs as. With {@link SIMULATE_ROLE_HEADER} it is\n * a hypothetical — \"u_1 holding customer\" — and need not name an account;\n * without it, the uid must be an active user and runs with their roles now.\n *\n * @group Auth\n */\nexport const SIMULATE_USER_ID_HEADER = \"x-rebase-simulate-user-id\";\n\n/**\n * The id of a service API key a simulated request runs as: the key's identity,\n * its RLS roles and its scopes, exactly as a request presenting the key would.\n * Excludes the other two simulation headers.\n *\n * @group Auth\n */\nexport const SIMULATE_API_KEY_ID_HEADER = \"x-rebase-simulate-api-key-id\";\n\n/**\n * The response header naming what a simulated request ran as:\n * `role=<role>;sub=<uid>;masked_columns=<a,b>`, plus `api_key=<id>` and\n * `collection=<slug>` when they apply. Every value is URI-encoded. Read it\n * with {@link parseSimulatedContext}.\n *\n * @group Auth\n */\nexport const SIMULATED_CONTEXT_HEADER = \"x-rebase-simulated-context\";\n\n/**\n * What an administrator asks a request to run as. Exactly one of these\n * shapes is honoured: a role (optionally with a uid), a uid alone (an existing\n * user, with their roles), or an API key id alone.\n *\n * @group Auth\n */\nexport interface AccessSimulation {\n role?: string;\n userId?: string;\n apiKeyId?: string;\n}\n\n/**\n * The request headers for an {@link AccessSimulation}. Empty when it asks for\n * nothing, so spreading it into a header set is always safe.\n *\n * @group Auth\n */\nexport function simulationHeaders(simulation: AccessSimulation | null | undefined): Record<string, string> {\n if (!simulation) return {};\n const headers: Record<string, string> = {};\n if (simulation.role) headers[SIMULATE_ROLE_HEADER] = simulation.role;\n if (simulation.userId) headers[SIMULATE_USER_ID_HEADER] = simulation.userId;\n if (simulation.apiKeyId) headers[SIMULATE_API_KEY_ID_HEADER] = simulation.apiKeyId;\n return headers;\n}\n\n/**\n * What {@link SIMULATED_CONTEXT_HEADER} says a request ran as.\n *\n * @group Auth\n */\nexport interface SimulatedContext {\n role: string;\n sub: string;\n maskedColumns: string[];\n apiKeyId?: string;\n collection?: string;\n}\n\n/**\n * Write a {@link SimulatedContext} as the header value.\n *\n * @group Auth\n */\nexport function formatSimulatedContext(context: SimulatedContext): string {\n const parts = [\n `role=${encodeURIComponent(context.role)}`,\n `sub=${encodeURIComponent(context.sub)}`,\n `masked_columns=${context.maskedColumns.map(encodeURIComponent).join(\",\")}`\n ];\n if (context.apiKeyId) parts.push(`api_key=${encodeURIComponent(context.apiKeyId)}`);\n if (context.collection) parts.push(`collection=${encodeURIComponent(context.collection)}`);\n return parts.join(\";\");\n}\n\n/**\n * Read {@link SIMULATED_CONTEXT_HEADER}. `undefined` for an absent header or one\n * missing `role` or `sub`.\n *\n * @group Auth\n */\nexport function parseSimulatedContext(value: string | null | undefined): SimulatedContext | undefined {\n if (!value) return undefined;\n const fields = new Map<string, string>();\n for (const part of value.split(\";\")) {\n const at = part.indexOf(\"=\");\n if (at > 0) fields.set(part.slice(0, at).trim(), part.slice(at + 1).trim());\n }\n const role = fields.get(\"role\");\n const sub = fields.get(\"sub\");\n if (role === undefined || sub === undefined) return undefined;\n const decode = (raw: string) => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n };\n const masked = fields.get(\"masked_columns\") ?? \"\";\n const apiKeyId = fields.get(\"api_key\");\n const collection = fields.get(\"collection\");\n return {\n role: decode(role),\n sub: decode(sub),\n maskedColumns: masked === \"\" ? [] : masked.split(\",\").map(decode),\n ...(apiKeyId ? { apiKeyId: decode(apiKeyId) } : {}),\n ...(collection ? { collection: decode(collection) } : {})\n };\n}\n\n// ─── Authenticated User ──────────────────────────────────────────────────────\n\n/**\n * The normalized user object returned by `AuthAdapter.verifyRequest()`.\n *\n * Regardless of the auth provider, every request is resolved to this shape\n * so that downstream middleware (RLS scoping, route guards) can work uniformly.\n *\n * @group Auth\n */\nexport interface AuthenticatedUser {\n /** Unique user identifier (provider-specific). */\n uid: string;\n /** Primary email address. */\n email: string;\n /** Human-readable display name. */\n displayName?: string | null;\n /** Avatar URL. */\n photoUrl?: string | null;\n /** Role identifiers the user holds. */\n roles: string[];\n /**\n * Whether `roles` includes `admin`. Informational — every authorization\n * decision reads `roles` and the scopes they hold, so an adapter that\n * wants a user treated as an administrator gives them the `admin` role.\n */\n isAdmin: boolean;\n /**\n * Whether this session is a GUEST — anonymous sign-in rather than an\n * account.\n *\n * Optional, and absent means \"not a guest\", so an external adapter that\n * has no such concept keeps behaving exactly as it did. When present it\n * reaches the database as `rebase.is_anonymous()`, which is what lets a\n * policy say \"a signed-in person, not somebody who pressed Continue as\n * guest\" — two things that were the same principal inside every rule,\n * because anonymous sign-in mints a real user row with a real uid.\n */\n isAnonymous?: boolean;\n /** Raw bearer token from the request (for forwarding). */\n rawToken?: string;\n /** Extra claims/metadata from the auth provider. */\n claims?: Record<string, unknown>;\n /**\n * What this credential may do, when it is narrower than its person — set\n * for an API key. Absent means everything the user's roles hold\n * (`scopesForRoles`).\n */\n scopes?: string[];\n}\n\n// ─── Capabilities ────────────────────────────────────────────────────────────\n\n/**\n * Feature flags advertised by an auth adapter.\n *\n * The frontend reads these from `GET /api/auth/config` to dynamically\n * show/hide UI elements (login form, registration, password reset, etc.).\n *\n * @group Auth\n */\nexport interface AuthAdapterCapabilities {\n /**\n * Whether this adapter mounts its own `/auth/*` routes.\n *\n * - `true` for the built-in Rebase auth (login, register, refresh, etc.)\n * - `false` for external providers like Clerk or Auth0 that handle\n * auth flows outside of the Rebase backend.\n */\n hasBuiltInAuthRoutes: boolean;\n\n /** Supports email/password login. */\n emailPasswordLogin: boolean;\n /**\n * Whether self-registration is open **right now**.\n *\n * A runtime answer, not a static feature list: the built-in adapter also\n * reports `true` during the first-user bootstrap window (an empty user\n * table) and `false` the moment `disableSelfRegistration` is set. Whatever\n * this says, `POST /auth/register` does — both read the same predicate, so\n * the UI can never be sent to a form that can only 403.\n */\n registrationEnabled: boolean;\n /**\n * Supports the end-user password reset flow (emailing a reset link).\n *\n * This is about *self-service* reset, so it is typically tied to whether an\n * email service is configured. It says nothing about whether an admin can\n * reset someone else's password — see `adminPasswordReset`.\n */\n passwordReset: boolean;\n /**\n * Whether the adapter exposes `POST /admin/users/:uid/reset-password`,\n * letting an admin reset another user's password.\n *\n * Independent of `passwordReset`: the built-in adapter supports this even\n * with no email service configured (it returns a one-time temporary\n * password instead of sending a link). Adapters that mount their own admin\n * routes must set this to `true` only once that route actually exists —\n * the admin UI hides the \"Reset Password\" action when it is `false`.\n */\n adminPasswordReset: boolean;\n /** Supports session listing/revocation. */\n sessionManagement: boolean;\n /** Supports profile updates (display name, photo). */\n profileUpdate: boolean;\n /** Supports email verification. */\n emailVerification: boolean;\n /** Supports passwordless magic link login. */\n magicLink: boolean;\n /**\n * Supports passwordless sign-in with a six-digit code sent by email.\n *\n * Optional so that an external adapter written before this existed still\n * satisfies the interface; absent reads as \"no\", which is what an adapter\n * that has never heard of the flow means.\n */\n emailOtp?: boolean;\n /** Whether `POST /auth/anonymous` will mint a credential-less session. */\n anonymousLogin: boolean;\n /** List of enabled OAuth provider IDs (e.g. `[\"google\", \"github\"]`). */\n enabledProviders: string[];\n /**\n * Public client ids, by provider id, for the providers whose sign-in a\n * browser starts with one (Apple's Services ID). Absent when none does.\n */\n providerClientIds?: Record<string, string>;\n\n /**\n * For external auth (Clerk, Auth0, etc.): the URL where the user should\n * be redirected for login. The Rebase frontend will navigate here instead\n * of showing its own login form.\n */\n externalLoginUrl?: string;\n\n /**\n * True when no users exist yet — first-user bootstrap mode.\n * Only applicable for built-in auth.\n */\n needsSetup?: boolean;\n}\n\n/**\n * What `GET /api/auth/config` answers: the auth adapter's capabilities, plus\n * the optional features of the backend around it.\n *\n * The admin panel reads this document before anything else, so it is where\n * the panel learns that a feature is off, without first asking for that\n * feature and getting a refusal.\n *\n * @group Auth\n */\nexport interface AuthConfigDocument extends AuthAdapterCapabilities {\n /**\n * Whether this backend serves file storage. When it is `false`, no storage\n * backend is configured: `GET /storage/sources` lists nothing and every\n * other `/storage` route answers 501 `STORAGE_NOT_CONFIGURED`. Absent from\n * a backend that predates the field, so a client must ask\n * `GET /storage/sources` there.\n */\n storage?: boolean;\n}\n\n// ─── User Management ────────────────────────────────────────────────────────\n\n/**\n * Options for paginated user listing.\n * @group Auth\n */\nexport interface AuthUserListOptions {\n limit?: number;\n offset?: number;\n search?: string;\n orderBy?: string;\n orderDir?: \"asc\" | \"desc\";\n roleId?: string;\n}\n\n/**\n * Paginated user listing result.\n * @group Auth\n */\nexport interface AuthUserListResult {\n users: AuthUserData[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/**\n * User data exposed by the auth adapter.\n * @group Auth\n */\nexport interface AuthUserData {\n id: string;\n email: string;\n displayName?: string | null;\n photoUrl?: string | null;\n emailVerified?: boolean;\n metadata?: Record<string, unknown>;\n createdAt?: Date;\n updatedAt?: Date;\n}\n\n/**\n * Data for creating a user.\n * @group Auth\n */\nexport interface AuthCreateUserData {\n email: string;\n password?: string;\n displayName?: string;\n photoUrl?: string;\n metadata?: Record<string, unknown>;\n /**\n * Store the address as verified: whoever creates the account named it\n * (an operator, an administrator), so nobody needs to prove it.\n */\n emailVerified?: boolean;\n}\n\n/**\n * User management operations for the admin panel.\n *\n * Optional — if not provided by the adapter, the user management UI is hidden.\n *\n * @group Auth\n */\nexport interface UserManagementAdapter {\n listUsers(options?: AuthUserListOptions): Promise<AuthUserListResult>;\n getUserById(id: string): Promise<AuthUserData | null>;\n createUser(data: AuthCreateUserData): Promise<AuthUserData>;\n updateUser(id: string, data: Partial<AuthCreateUserData>): Promise<AuthUserData | null>;\n deleteUser(id: string): Promise<void>;\n getUserRoles(uid: string): Promise<string[]>;\n setUserRoles(uid: string, roleIds: string[]): Promise<void>;\n}\n\n// ─── User Creation Lifecycle ─────────────────────────────────────────────────\n\n/**\n * Result of `AuthAdapter.prepareUserCreation()`.\n *\n * Contains the processed values ready for persistence and metadata\n * needed by the finalization step.\n *\n * @group Auth\n */\nexport interface UserCreationPrepareResult {\n /** Processed values to persist (passwordHash instead of raw password, etc.). */\n values: Record<string, unknown>;\n /** Cleartext password for post-save processing (email or admin display). */\n clearPassword?: string;\n /**\n * Whether the hook already handled the invitation (email, etc.). When\n * `true`, `finalizeUserCreation` is skipped and `clearPassword` is returned\n * to the admin as the temporary password.\n */\n hookHandledEmail: boolean;\n /** Whether an invitation was sent (only relevant when hookHandledEmail is true). */\n invitationSent: boolean;\n}\n\n/**\n * What the door creating a user knows about its caller, for\n * `AuthAdapter.prepareUserCreation()`.\n *\n * @group Auth\n */\nexport interface UserCreationOptions {\n /**\n * Whether the caller may waive the password policy with\n * `skipPasswordPolicy: true` in the body. The doors set it for an\n * administrator (the service key signs in as one) and for nobody else, so\n * an adapter that reads the flag is taking an administrator at their word —\n * an import of accounts whose passwords were set under another system's\n * rules. Absent, the flag waives nothing.\n */\n mayWaivePasswordPolicy?: boolean;\n}\n\n/**\n * What a create body for an auth collection may name beyond the collection's\n * own declared fields — see `AuthAdapter.describeUserCreationContract()`.\n *\n * @group Auth\n */\nexport interface UserCreationWriteContract {\n /**\n * Whether to check the body for fields neither the collection nor\n * {@link extraFields} declares. `false` skips the check entirely.\n */\n validate: boolean;\n /**\n * Credential and provider keys the adapter consumes itself, which the\n * collection therefore does not declare as columns. `password` is the\n * canonical one: `prepareUserCreation` hashes it into `passwordHash` and\n * deletes it before the row is ever built.\n */\n extraFields: string[];\n /**\n * Each body's `prepareUserCreation` touches nothing but its own result —\n * no hook, no email, no write — so a bulk create may prepare several at\n * once. The built-in adapter's path with no `onCreateUser`, no\n * `onAdminCreateUser` and the default `hashPassword` is: it hashes a\n * password and normalizes an email, and a 1,000-row bulk spent half a\n * minute hashing one password at a time. Leave it unset when a hook runs:\n * preparations then run one at a time, in the order the rows were given.\n */\n independent?: boolean;\n}\n\n/**\n * Result of `AuthAdapter.finalizeUserCreation()`.\n *\n * Returned to the REST API for inclusion in the response.\n *\n * @group Auth\n */\nexport interface UserCreationFinalizeResult {\n /** If set, returned to the admin in the API response. */\n temporaryPassword?: string;\n /** Whether an invitation email was sent. */\n invitationSent: boolean;\n /**\n * Whether an email service was configured but delivery failed, causing the\n * fallback to `temporaryPassword`. Absent when no email service is configured.\n */\n emailDeliveryFailed?: boolean;\n}\n\n// ─── Auth Response Transform ─────────────────────────────────────────────────\n\n/**\n * The auth response payload shape that flows through `transformAuthResponse`.\n *\n * For login, register, OAuth, anonymous, and magic-link flows the payload\n * contains both `user` and `tokens`. For refresh and MFA flows the payload\n * contains only `tokens` (no `user`).\n *\n * @group Auth\n */\nexport interface AuthResponsePayload {\n user?: {\n uid: string;\n email: string;\n displayName: string | null;\n photoURL: string | null;\n providerId?: string;\n isAnonymous?: boolean;\n emailVerified?: boolean;\n roles: string[];\n metadata: Record<string, unknown>;\n };\n tokens: {\n accessToken: string;\n refreshToken: string;\n accessTokenExpiresAt: number;\n /** Additional tokens injected by `transformAuthResponse`. */\n [key: string]: unknown;\n };\n}\n\n/**\n * Context passed to the `transformAuthResponse` hook.\n *\n * @group Auth\n */\nexport interface TransformAuthResponseContext {\n /** The authenticated user's ID. */\n uid: string;\n /** The auth method that triggered this response. */\n method: \"login\" | \"register\" | \"oauth\" | \"refresh\" | \"anonymous\" | \"magic-link\" | \"otp\" | \"mfa\";\n /** The raw HTTP request (for reading headers, IP, etc.). */\n request: Request;\n}\n\n// ─── Auth Adapter ────────────────────────────────────────────────────────────\n\n/**\n * Pluggable authentication adapter for Rebase.\n *\n * This is the **key interface** that decouples authentication from the\n * database layer. Each auth adapter knows how to:\n *\n * 1. Verify incoming HTTP requests (`verifyRequest`)\n * 2. Optionally manage users (for the admin panel)\n * 3. Optionally mount auth-specific routes (login, register, etc.)\n * 4. Advertise its capabilities so the frontend can adapt\n *\n * The built-in Rebase auth implements this interface internally.\n * External providers (Clerk, Auth0, or others) provide their own adapters.\n * Users with custom auth can use `createCustomAuthAdapter()` for a minimal setup.\n *\n * @group Auth\n */\nexport interface AuthAdapter {\n /**\n * Unique identifier for this auth adapter.\n *\n * @example \"rebase-builtin\", \"clerk\", \"auth0\", \"external-provider\", \"custom\"\n */\n readonly id: string;\n\n // ── Request Authentication ──────────────────────────────────────────\n\n /**\n * Verify an incoming request and extract the authenticated user.\n *\n * This replaces the hardcoded JWT verification in server's middleware.\n * Each adapter implements its own token verification strategy:\n * - Built-in: verify Rebase JWT\n * - Clerk: call Clerk's `verifyToken()`\n * - Auth0: validate Auth0 JWT with JWKS\n * - Custom: whatever logic the user provides\n *\n * @param request - The raw `Request` object (portable across Hono, Express, Fastify)\n * @returns The authenticated user, or `null` for unauthenticated requests.\n * Throw an error to reject the request with 401.\n */\n verifyRequest(request: Request): Promise<AuthenticatedUser | null>;\n\n /**\n * Verify a raw bearer token and extract the authenticated user.\n *\n * Used for **WebSocket authentication**, where there is no HTTP `Request`\n * object — only a token string sent over the socket.\n *\n * If not implemented, the default behavior synthesizes a minimal `Request`\n * with an `Authorization: Bearer <token>` header and delegates to\n * `verifyRequest()`. Adapters should override this if their token\n * verification logic doesn't depend on request headers/cookies.\n *\n * @param token - The raw bearer token string.\n * @returns The authenticated user, or `null` if the token is invalid.\n */\n verifyToken?(token: string): Promise<AuthenticatedUser | null>;\n\n /**\n * The identity a verified request from this account would carry right\n * now, with no credential involved: its uid, its roles as they are now,\n * its guest flag, and the custom claims a token minted for it now would\n * hold. `null` when no active account has this uid — none at all, or one\n * that is disabled.\n *\n * This is what lets an administrator run a request as another user (the\n * {@link IMPERSONATE_HEADER} header). The server calls it only after it\n * has decided the caller may do that, and it calls it for the caller too,\n * so the decision rests on the caller's roles as they are now rather than\n * on the ones their token claims.\n *\n * Optional. An adapter without it cannot be impersonated through, and a\n * request carrying the header is refused rather than run as its caller.\n */\n resolveUser?(uid: string): Promise<AuthenticatedUser | null>;\n\n // ── User Management (for admin panel) ────────────────────────────\n\n /**\n * User CRUD for the admin panel's user management UI.\n * Optional — if not provided, user management UI is hidden.\n */\n userManagement?: UserManagementAdapter;\n\n // ── Auth Routes ─────────────────────────────────────────────────────\n\n /**\n * Mount adapter-specific auth routes (login, register, refresh, etc.).\n *\n * - Built-in adapter: mounts `/auth/login`, `/auth/register`, etc.\n * - External adapter: typically returns `undefined` (auth is handled externally).\n * - Custom adapter: user mounts their own routes.\n *\n * The return type is the structural {@link MountableRouter} rather than\n * `Hono`, so this package needs no hono dependency. A real `Hono<HonoEnv>`\n * satisfies it, and implementations are free to use their own env.\n *\n * @returns A Hono sub-app with auth routes, or `undefined` to skip route mounting.\n */\n createAuthRoutes?(): MountableRouter | undefined;\n\n /**\n * Mount admin routes (e.g. password reset for users).\n *\n * @returns A Hono sub-app with admin routes, or `undefined` to skip.\n */\n createAdminRoutes?(): MountableRouter | undefined;\n\n // ── Feature Detection ───────────────────────────────────────────────\n\n /**\n * Advertise what this auth adapter supports.\n *\n * The frontend reads this from `GET /api/auth/config` to dynamically\n * show/hide UI elements. This is the bridge between backend capabilities\n * and the frontend's `AuthCapabilities` type.\n */\n getCapabilities(): AuthAdapterCapabilities | Promise<AuthAdapterCapabilities>;\n\n // ── Lifecycle ───────────────────────────────────────────────────────\n\n /**\n * Called during backend initialization.\n * Use for running migrations, creating tables, seeding initial data, etc.\n */\n initialize?(): Promise<void>;\n\n /**\n * Called during graceful shutdown.\n * Use for closing connections, flushing caches, etc.\n */\n destroy?(): Promise<void>;\n\n // ── Collection User Creation (for auth collections) ───────────────\n\n /**\n * Prepare values for creating a user via the auth collection's REST API.\n *\n * Called on POST to a collection with `auth: true`. Handles password\n * hashing, email normalization, and any collection/backend-level hooks.\n *\n * If not implemented, the collection saves values as-is (no password hashing).\n *\n * A chosen `password` is held to the password policy unless the body says\n * `skipPasswordPolicy: true` and `options.mayWaivePasswordPolicy` is set.\n *\n * @param values - Raw request body from the client.\n * @param collectionAuth - The parsed `AuthCollectionConfig` from the collection (if `auth` is an object).\n * @param options - What the door knows about its caller.\n * @returns Processed values ready for `driver.save()`, plus metadata for the post-save step.\n */\n prepareUserCreation?(\n values: Record<string, unknown>,\n collectionAuth?: unknown,\n options?: UserCreationOptions\n ): Promise<UserCreationPrepareResult>;\n\n /**\n * Describe what a create body for this auth collection is allowed to name,\n * so unknown-field validation can run on it.\n *\n * A signup body is not the collection's shape: it carries credential fields\n * like `password` that the users table never declares as columns, and\n * `prepareUserCreation` maps them onto real ones. Validating the raw body\n * against the collection alone would reject every legitimate signup — which\n * is why the check used to be skipped outright for auth collections. That\n * skip was total, so an undeclared field was silently dropped and the write\n * still returned 201, while the same typo on a normal collection was a 400.\n *\n * This narrows the exemption to the fields the adapter actually consumes.\n *\n * `validate: false` disables the check for this collection, and is the right\n * answer when a custom `onCreateUser` hook is configured: the body is then\n * the hook's contract, not the collection's, and this layer cannot know what\n * the hook accepts.\n *\n * If not implemented, validation is skipped — the pre-existing behaviour.\n *\n * @param collectionAuth - The parsed `AuthCollectionConfig` from the collection (if `auth` is an object).\n */\n describeUserCreationContract?(\n collectionAuth?: unknown\n ): UserCreationWriteContract;\n\n /**\n * Finalize a user creation after the entity has been persisted.\n *\n * Handles post-save work: sending invitation emails, generating\n * password-reset tokens, or falling back to returning a temporary password.\n *\n * Not called when `prepareUserCreation` reported `hookHandledEmail`. A\n * create hook then owns delivery, and the response carries the\n * `invitationSent` and `clearPassword` the prepare step returned. This\n * holds for both ways of creating a user: a `POST` to the auth collection\n * and `POST /admin/users`.\n *\n * @param entity - The persisted entity (id + values).\n * @param clearPassword - The cleartext password from the prepare step (if any).\n * @returns Metadata for the API response (temporary password, invitation status).\n */\n finalizeUserCreation?(\n entity: { id: string; values: Record<string, unknown> },\n clearPassword?: string\n ): Promise<UserCreationFinalizeResult>;\n\n // ── User Administration Through the Auth Collection ─────────────────\n\n /**\n * Check, and put in stored form, updates to rows of the auth collection\n * that arrive through the data API — `PATCH /<users>/:id`, `PATCH /bulk`,\n * `_batch`, the realtime socket.\n *\n * Those rows are the users, so an update to one is user administration,\n * and has to hold to what the admin user routes hold to: no update that\n * leaves the project without an administrator, and an email stored the\n * way sign-in looks it up. Throws to refuse; the updates are judged\n * together, so a bulk demotion of every admin is refused even though each\n * row alone would pass.\n *\n * If not implemented, the values are written as they arrived.\n *\n * @returns Each update's values, as they should be written, in order.\n */\n prepareUserUpdates?(\n updates: ReadonlyArray<{ uid: string; values: Record<string, unknown> }>\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Check a deletion of these users through the data API before any row goes,\n * and run the hooks that may veto it (`beforeUserDelete`). Throws to\n * refuse — for one that would leave the project without an administrator,\n * among others.\n *\n * If not implemented, the rows are deleted as any other.\n */\n prepareUserDeletions?(uids: readonly string[]): Promise<void>;\n\n /**\n * After those users' rows are deleted through the data API: end their\n * sessions and run the after-delete hooks (`afterUserDelete`).\n */\n finalizeUserDeletions?(uids: readonly string[]): Promise<void>;\n\n // ── Service Key (optional) ──────────────────────────────────────────\n\n /**\n * A static secret key for server-to-server / script authentication.\n *\n * When set, requests with `Authorization: Bearer <serviceKey>` bypass\n * normal token verification and are granted admin-level access.\n */\n serviceKey?: string;\n\n // ── Response Transform ───────────────────────────────────────────────\n\n /**\n * Transform the auth response before sending it to the client.\n *\n * Called after successful login, register, refresh, OAuth, anonymous,\n * magic-link, and MFA flows. The hook receives the fully-formed\n * response and returns a (potentially enriched) response.\n *\n * Use cases:\n * - Inject tokens from external auth systems (custom provider tokens, etc.)\n * - Add project-specific metadata to the response\n * - Enrich the user object with data from external sources\n *\n * The hook runs in the request path — keep it fast.\n * Heavy work should be offloaded to `onAuthenticated` (fire-and-forget).\n */\n transformAuthResponse?(\n response: AuthResponsePayload,\n context: TransformAuthResponseContext\n ): Promise<AuthResponsePayload>;\n}\n\n// ─── Custom Auth Adapter Options ─────────────────────────────────────────────\n\n/**\n * Options for creating a minimal custom auth adapter via `createCustomAuthAdapter()`.\n *\n * This is the simplest way to plug an existing auth system into Rebase.\n * Only `verifyRequest` is required — everything else is optional.\n *\n * @group Auth\n */\nexport interface CustomAuthAdapterOptions {\n /**\n * Verify an incoming request and return the authenticated user.\n * This is the only required method.\n */\n verifyRequest: (request: Request) => Promise<AuthenticatedUser | null>;\n\n /**\n * Verify a raw bearer token for WebSocket authentication.\n * Optional — if omitted, a synthetic `Request` is constructed and passed\n * to `verifyRequest`.\n */\n verifyToken?: (token: string) => Promise<AuthenticatedUser | null>;\n\n /** Optional user management for the admin panel. */\n userManagement?: UserManagementAdapter;\n\n /** Static service key for server-to-server auth. */\n serviceKey?: string;\n\n /** Override default capabilities. */\n capabilities?: Partial<AuthAdapterCapabilities>;\n\n /**\n * Transform the auth response before sending it to the client.\n * Same semantics as `AuthAdapter.transformAuthResponse`.\n */\n transformAuthResponse?: (\n response: AuthResponsePayload,\n context: TransformAuthResponseContext\n ) => Promise<AuthResponsePayload>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsEA,IAAa,qBAAqB;;;;;;;;;;;;;;AAiBlC,IAAa,uBAAuB;;;;;;;;AASpC,IAAa,0BAA0B;;;;;;;;AASvC,IAAa,6BAA6B;;;;;;;;;AAU1C,IAAa,2BAA2B;;;;;;;AAqBxC,SAAgB,kBAAkB,YAAyE;CACvG,IAAI,CAAC,YAAY,OAAO,CAAC;CACzB,MAAM,UAAkC,CAAC;CACzC,IAAI,WAAW,MAAM,QAAQ,wBAAwB,WAAW;CAChE,IAAI,WAAW,QAAQ,QAAQ,2BAA2B,WAAW;CACrE,IAAI,WAAW,UAAU,QAAQ,8BAA8B,WAAW;CAC1E,OAAO;AACX;;;;;;AAoBA,SAAgB,uBAAuB,SAAmC;CACtE,MAAM,QAAQ;EACV,QAAQ,mBAAmB,QAAQ,IAAI;EACvC,OAAO,mBAAmB,QAAQ,GAAG;EACrC,kBAAkB,QAAQ,cAAc,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG;CAC5E;CACA,IAAI,QAAQ,UAAU,MAAM,KAAK,WAAW,mBAAmB,QAAQ,QAAQ,GAAG;CAClF,IAAI,QAAQ,YAAY,MAAM,KAAK,cAAc,mBAAmB,QAAQ,UAAU,GAAG;CACzF,OAAO,MAAM,KAAK,GAAG;AACzB"}