@nestjs-kit/better-auth 2.0.0 → 2.1.2

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 (133) hide show
  1. package/README.md +7 -7
  2. package/dist/admin.cjs +3 -4
  3. package/dist/admin.d.cts +1 -3
  4. package/dist/admin.d.cts.map +1 -1
  5. package/dist/admin.d.mts +1 -3
  6. package/dist/admin.d.mts.map +1 -1
  7. package/dist/admin.mjs +3 -4
  8. package/dist/api-key.cjs +4 -5
  9. package/dist/api-key.d.cts +1 -3
  10. package/dist/api-key.d.cts.map +1 -1
  11. package/dist/api-key.d.mts +1 -3
  12. package/dist/api-key.d.mts.map +1 -1
  13. package/dist/api-key.mjs +4 -5
  14. package/dist/{auth-contracts-Brh_Qko9.d.cts → auth-contracts-CADGyI0O.d.mts} +3 -53
  15. package/dist/auth-contracts-CADGyI0O.d.mts.map +1 -0
  16. package/dist/{auth-contracts-Cz7C4_Ch.d.mts → auth-contracts-zvt8ysoZ.d.cts} +3 -53
  17. package/dist/auth-contracts-zvt8ysoZ.d.cts.map +1 -0
  18. package/dist/{auth-decorators-Cu_nxWnF.cjs → auth-decorators-CJKE9wlT.cjs} +8 -10
  19. package/dist/{auth-decorators-Cu_nxWnF.cjs.map → auth-decorators-CJKE9wlT.cjs.map} +1 -1
  20. package/dist/{auth-decorators-B1mFnGJ6.mjs → auth-decorators-CkNkLNpU.mjs} +8 -10
  21. package/dist/{auth-decorators-B1mFnGJ6.mjs.map → auth-decorators-CkNkLNpU.mjs.map} +1 -1
  22. package/dist/{auth-errors-C3rbTV9p.mjs → auth-errors-JjxGDVSt.mjs} +3 -5
  23. package/dist/{auth-errors-C3rbTV9p.mjs.map → auth-errors-JjxGDVSt.mjs.map} +1 -1
  24. package/dist/{auth-errors-DmiKl0L_.cjs → auth-errors-RW7hOVI-.cjs} +3 -5
  25. package/dist/{auth-errors-DmiKl0L_.cjs.map → auth-errors-RW7hOVI-.cjs.map} +1 -1
  26. package/dist/{auth-guard-h9QB_l11.mjs → auth-guard-Da92QEK5.mjs} +4 -5
  27. package/dist/{auth-guard-h9QB_l11.mjs.map → auth-guard-Da92QEK5.mjs.map} +1 -1
  28. package/dist/{auth-guard-CLyhAEEj.cjs → auth-guard-wapEh_M_.cjs} +4 -5
  29. package/dist/{auth-guard-CLyhAEEj.cjs.map → auth-guard-wapEh_M_.cjs.map} +1 -1
  30. package/dist/{auth-module-BgcY2HpA.cjs → auth-module-ab60-WJZ.cjs} +28 -47
  31. package/dist/auth-module-ab60-WJZ.cjs.map +1 -0
  32. package/dist/{auth-module-CtHx3gRU.mjs → auth-module-uy3BBWwR.mjs} +28 -47
  33. package/dist/auth-module-uy3BBWwR.mjs.map +1 -0
  34. package/dist/{auth-scope-interceptor-BjxAL1-S.cjs → auth-scope-interceptor-Bui20-Ps.cjs} +5 -7
  35. package/dist/{auth-scope-interceptor-BjxAL1-S.cjs.map → auth-scope-interceptor-Bui20-Ps.cjs.map} +1 -1
  36. package/dist/{auth-scope-interceptor-DYPn3b8M.mjs → auth-scope-interceptor-CvCQ52dV.mjs} +5 -7
  37. package/dist/{auth-scope-interceptor-DYPn3b8M.mjs.map → auth-scope-interceptor-CvCQ52dV.mjs.map} +1 -1
  38. package/dist/{bridge-protocol-c66aEkr5.mjs → bridge-protocol-CmRsff2P.mjs} +2 -3
  39. package/dist/{bridge-protocol-BDw8opAG.cjs.map → bridge-protocol-CmRsff2P.mjs.map} +1 -1
  40. package/dist/{bridge-protocol-BDw8opAG.cjs → bridge-protocol-DNFhIKdo.cjs} +2 -3
  41. package/dist/{bridge-protocol-c66aEkr5.mjs.map → bridge-protocol-DNFhIKdo.cjs.map} +1 -1
  42. package/dist/{decorate-Dt0e9K6R.mjs → decorate-bO-rBn-G.mjs} +5 -9
  43. package/dist/{decorate-Dt0e9K6R.mjs.map → decorate-bO-rBn-G.mjs.map} +1 -1
  44. package/dist/{decorate-Cr4Q7bNE.cjs → decorate-fMNf0caZ.cjs} +5 -9
  45. package/dist/{decorate-Cr4Q7bNE.cjs.map → decorate-fMNf0caZ.cjs.map} +1 -1
  46. package/dist/express.cjs +3 -4
  47. package/dist/express.d.cts +1 -3
  48. package/dist/express.d.cts.map +1 -1
  49. package/dist/express.d.mts +1 -3
  50. package/dist/express.d.mts.map +1 -1
  51. package/dist/express.mjs +3 -4
  52. package/dist/fastify.cjs +2 -3
  53. package/dist/fastify.d.cts +1 -3
  54. package/dist/fastify.d.cts.map +1 -1
  55. package/dist/fastify.d.mts +1 -3
  56. package/dist/fastify.d.mts.map +1 -1
  57. package/dist/fastify.mjs +2 -3
  58. package/dist/graphql.cjs +7 -9
  59. package/dist/graphql.cjs.map +1 -1
  60. package/dist/graphql.d.cts +1 -3
  61. package/dist/graphql.d.cts.map +1 -1
  62. package/dist/graphql.d.mts +1 -3
  63. package/dist/graphql.d.mts.map +1 -1
  64. package/dist/graphql.mjs +7 -9
  65. package/dist/graphql.mjs.map +1 -1
  66. package/dist/index.cjs +7 -7
  67. package/dist/index.d.cts +1 -1
  68. package/dist/index.d.mts +1 -1
  69. package/dist/index.mjs +7 -7
  70. package/dist/microservices.cjs +4 -6
  71. package/dist/microservices.cjs.map +1 -1
  72. package/dist/microservices.d.cts +1 -5
  73. package/dist/microservices.d.cts.map +1 -1
  74. package/dist/microservices.d.mts +1 -5
  75. package/dist/microservices.d.mts.map +1 -1
  76. package/dist/microservices.mjs +3 -5
  77. package/dist/microservices.mjs.map +1 -1
  78. package/dist/organization.cjs +3 -4
  79. package/dist/organization.d.cts +1 -3
  80. package/dist/organization.d.cts.map +1 -1
  81. package/dist/organization.d.mts +1 -3
  82. package/dist/organization.d.mts.map +1 -1
  83. package/dist/organization.mjs +3 -4
  84. package/dist/{platform-CZl7TY8j.mjs → platform-BKYVzAv1.mjs} +3 -5
  85. package/dist/{platform-CZl7TY8j.mjs.map → platform-BKYVzAv1.mjs.map} +1 -1
  86. package/dist/{platform-YICqqYv6.cjs → platform-C67dxSls.cjs} +3 -5
  87. package/dist/{platform-YICqqYv6.cjs.map → platform-C67dxSls.cjs.map} +1 -1
  88. package/dist/platform.cjs +1 -1
  89. package/dist/platform.d.cts +0 -2
  90. package/dist/platform.d.cts.map +1 -1
  91. package/dist/platform.d.mts +0 -2
  92. package/dist/platform.d.mts.map +1 -1
  93. package/dist/platform.mjs +1 -1
  94. package/dist/plugin.cjs +4 -8
  95. package/dist/plugin.cjs.map +1 -1
  96. package/dist/plugin.d.cts +0 -4
  97. package/dist/plugin.d.cts.map +1 -1
  98. package/dist/plugin.d.mts +0 -4
  99. package/dist/plugin.d.mts.map +1 -1
  100. package/dist/plugin.mjs +4 -8
  101. package/dist/plugin.mjs.map +1 -1
  102. package/dist/{principal-readings-Ied2staw.mjs → principal-readings-BuXTU0-2.mjs} +3 -4
  103. package/dist/{principal-readings-Ied2staw.mjs.map → principal-readings-BuXTU0-2.mjs.map} +1 -1
  104. package/dist/{principal-readings-Chmt6rQV.cjs → principal-readings-JLNT58k0.cjs} +3 -4
  105. package/dist/{principal-readings-Chmt6rQV.cjs.map → principal-readings-JLNT58k0.cjs.map} +1 -1
  106. package/dist/{rolldown-runtime-VH7oDXx4.cjs → rolldown-runtime-CmQyd0Gu.cjs} +1 -2
  107. package/dist/testing/conformance.cjs +24 -31
  108. package/dist/testing/conformance.cjs.map +1 -1
  109. package/dist/testing/conformance.d.cts +4 -14
  110. package/dist/testing/conformance.d.cts.map +1 -1
  111. package/dist/testing/conformance.d.mts +4 -14
  112. package/dist/testing/conformance.d.mts.map +1 -1
  113. package/dist/testing/conformance.mjs +23 -30
  114. package/dist/testing/conformance.mjs.map +1 -1
  115. package/dist/testing.cjs +6 -7
  116. package/dist/testing.d.cts +1 -3
  117. package/dist/testing.d.cts.map +1 -1
  118. package/dist/testing.d.mts +1 -3
  119. package/dist/testing.d.mts.map +1 -1
  120. package/dist/testing.mjs +6 -7
  121. package/dist/websockets.cjs +7 -10
  122. package/dist/websockets.cjs.map +1 -1
  123. package/dist/websockets.d.cts +1 -7
  124. package/dist/websockets.d.cts.map +1 -1
  125. package/dist/websockets.d.mts +1 -7
  126. package/dist/websockets.d.mts.map +1 -1
  127. package/dist/websockets.mjs +7 -10
  128. package/dist/websockets.mjs.map +1 -1
  129. package/package.json +25 -25
  130. package/dist/auth-contracts-Brh_Qko9.d.cts.map +0 -1
  131. package/dist/auth-contracts-Cz7C4_Ch.d.mts.map +0 -1
  132. package/dist/auth-module-BgcY2HpA.cjs.map +0 -1
  133. package/dist/auth-module-CtHx3gRU.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"auth-errors-C3rbTV9p.mjs","names":[],"sources":["../src/error-redactor.ts","../src/auth-errors.ts"],"sourcesContent":["/** Inputs come from the active request's owner; the redactor retains no scope. */\nexport interface ErrorRedactorOptions {\n secrets?: readonly string[];\n headers?: Headers;\n credentialHeaders?: readonly string[];\n}\n\n/** Reading an arbitrary thrown value must not invoke another escaping fault. */\nexport function readErrorProperty(value: unknown, key: PropertyKey): unknown {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport class ErrorRedactor {\n readonly #secrets: readonly string[];\n\n constructor(options: ErrorRedactorOptions = {}) {\n const values = new Set<string>();\n const add = (value: string) => {\n if (!value) {\n return;\n }\n values.add(value);\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n values.add(decoded);\n } catch {\n // Invalid escaping must not prevent redaction of the raw credential.\n }\n for (const form of [value, decoded]) {\n const separator = form.lastIndexOf(\".\");\n if (separator >= 16) {\n values.add(form.slice(0, separator));\n }\n }\n };\n for (const value of options.secrets ?? []) {\n add(value);\n }\n const headers = options.headers;\n for (const cookie of (headers?.get(\"cookie\") ?? \"\").split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator >= 0) {\n const value = cookie.slice(separator + 1).trim();\n add(value);\n if (value.startsWith('\"') && value.endsWith('\"')) {\n add(value.slice(1, -1));\n }\n }\n }\n const authorization = headers?.get(\"authorization\");\n if (authorization) {\n add(authorization);\n const credential = /^\\S+\\s+(.+)$/.exec(authorization)?.[1];\n if (credential) {\n add(credential);\n }\n }\n for (const name of options.credentialHeaders ?? []) {\n const value = headers?.get(name);\n if (value) {\n add(value);\n }\n }\n this.#secrets = [...values].sort(\n (left, right) => right.length - left.length,\n );\n }\n\n redact(cause: unknown): Error {\n return this.redactCause(cause, 0, new Set());\n }\n\n private replaceSecrets(value: string): string {\n for (const secret of this.#secrets) {\n value = value.split(secret).join(\"[REDACTED]\");\n }\n return value;\n }\n\n private diagnostic(value: string): string {\n return this.replaceSecrets(value)\n .split(/[\\r\\n]/, 1)[0]\n .slice(0, 300);\n }\n\n private redactCause(\n cause: unknown,\n depth: number,\n seen: Set<unknown>,\n ): Error {\n const message = readErrorProperty(cause, \"message\");\n const error = new Error(\n this.diagnostic(\n typeof message === \"string\"\n ? message\n : typeof cause === \"string\"\n ? cause\n : \"Unknown authentication infrastructure failure\",\n ),\n );\n const name = readErrorProperty(cause, \"name\");\n error.name = typeof name === \"string\" ? this.diagnostic(name) : \"Error\";\n for (const key of [\"code\", \"errno\", \"syscall\"] as const) {\n const value = readErrorProperty(cause, key);\n if (\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n Object.defineProperty(error, key, {\n value: typeof value === \"string\" ? this.diagnostic(value) : value,\n enumerable: true,\n });\n }\n }\n const stack = readErrorProperty(cause, \"stack\");\n const frames =\n typeof stack === \"string\"\n ? stack\n .split(/\\r?\\n/)\n .filter((line) => /^\\s+at .+:\\d+:\\d+\\)?$/.test(line))\n .map((line) => this.replaceSecrets(line))\n : [];\n error.stack = [`${error.name}: ${error.message}`, ...frames].join(\"\\n\");\n seen.add(cause);\n const nested = readErrorProperty(cause, \"cause\");\n if (nested !== undefined && depth < 3 && !seen.has(nested)) {\n Object.defineProperty(error, \"cause\", {\n value: this.redactCause(nested, depth + 1, seen),\n enumerable: false,\n });\n }\n return error;\n }\n}\n","import type { ExecutionContext } from \"@nestjs/common\";\nimport { isAPIError } from \"better-auth/api\";\nimport {\n ErrorRedactor,\n type ErrorRedactorOptions,\n readErrorProperty,\n} from \"./error-redactor.js\";\n\nconst FAILURE_BRAND = Symbol.for(\"@nestjs-kit/better-auth:auth-failure\");\nconst INFRASTRUCTURE_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:infrastructure-error\",\n);\nconst CONFIGURATION_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:configuration-error\",\n);\nconst RAW_CAUSE = Symbol.for(\"@nestjs-kit/better-auth:raw-cause\");\n/** Unredacted causes stay module-private; only an instance's exposeRawCause opt-in attaches one (RAW_CAUSE). */\nconst ORIGINAL_CAUSES = new WeakMap<object, unknown>();\nconst SDK_HEADERS = Symbol.for(\"better-call:api-error-headers\");\n\nexport type AuthErrorCode = \"UNAUTHENTICATED\" | \"FORBIDDEN\" | \"RATE_LIMITED\";\n\n/** A transport-neutral denial. Only transports make it throwable. */\nexport interface AuthFailure {\n readonly status: 401 | 403 | 429;\n readonly code: AuthErrorCode;\n readonly reason?: string;\n readonly message: string;\n readonly challenge?: string;\n readonly headers?: Headers;\n}\n\nexport interface AuthErrorBody {\n statusCode: 401 | 403 | 429;\n error: string;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface AuthGraphqlExtensions {\n code: AuthErrorCode | \"INTERNAL_SERVER_ERROR\";\n reason?: string;\n statusCode: number;\n}\n\nexport interface AuthTransportErrorPayload {\n status: \"error\";\n statusCode: number;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface ErrorMappingOptions {\n map?: (\n failure: AuthFailure,\n context: ExecutionContext,\n transport: string,\n ) => unknown;\n exposeRawCause?: boolean;\n}\n\nfunction branded<T extends object>(value: T, brand: symbol): T {\n Object.defineProperty(value, brand, { value: true });\n return value;\n}\n\nexport function isAuthFailure(value: unknown): value is AuthFailure {\n return readErrorProperty(value, FAILURE_BRAND) === true;\n}\n\nexport function isInfrastructureError(\n value: unknown,\n): value is BetterAuthInfrastructureError {\n return readErrorProperty(value, INFRASTRUCTURE_BRAND) === true;\n}\n\nexport function isConfigurationError(\n value: unknown,\n): value is BetterAuthConfigurationError {\n return readErrorProperty(value, CONFIGURATION_BRAND) === true;\n}\n\nfunction sdkStatus(error: unknown): number | undefined {\n try {\n if (!isAPIError(error)) {\n return undefined;\n }\n const status = readErrorProperty(error, \"statusCode\");\n return typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= 100 &&\n status <= 599\n ? status\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction sdkReason(error: unknown): string | undefined {\n const reason = readErrorProperty(readErrorProperty(error, \"body\"), \"code\");\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/** Internal: preserve cookie lines for the exchange's separately governed cleanup. */\nexport function getAPIErrorHeaders(error: unknown): Headers {\n const result = new Headers();\n for (const value of [\n readErrorProperty(error, SDK_HEADERS),\n readErrorProperty(error, \"headers\"),\n ]) {\n if (value === undefined || value === null) {\n continue;\n }\n try {\n const headers = new Headers(value as HeadersInit);\n for (const [name, value] of headers) {\n if (name !== \"set-cookie\") {\n result.set(name, value);\n }\n }\n for (const cookie of headers.getSetCookie()) {\n result.append(\"set-cookie\", cookie);\n }\n } catch {\n // A malformed optional header collection must not mask the original fault.\n }\n }\n return result;\n}\n\nfunction rejection(input: {\n status: 401 | 403 | 429;\n reason?: string;\n message?: string;\n challenge?: string;\n retryAfterSeconds?: number;\n}): AuthFailure {\n const codes = {\n 401: \"UNAUTHENTICATED\",\n 403: \"FORBIDDEN\",\n 429: \"RATE_LIMITED\",\n } as const;\n const messages = {\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 429: \"Too Many Requests\",\n } as const;\n const headers = new Headers();\n const retry = input.retryAfterSeconds;\n if (retry !== undefined && Number.isFinite(retry) && retry >= 0) {\n headers.set(\"retry-after\", String(Math.ceil(retry)));\n }\n return branded(\n {\n status: input.status,\n code: codes[input.status],\n reason: input.reason,\n message: input.message ?? messages[input.status],\n challenge: input.challenge,\n ...(headers.has(\"retry-after\") ? { headers } : {}),\n },\n FAILURE_BRAND,\n );\n}\n\nexport const AuthFailures = {\n unauthenticated(message?: string): AuthFailure {\n return rejection({ status: 401, message });\n },\n rejected: rejection,\n forbidden(reason: string, message?: string): AuthFailure {\n return rejection({ status: 403, reason, message });\n },\n fromAPIError(error: unknown): AuthFailure | null {\n const status = sdkStatus(error);\n if (status !== 401 && status !== 403 && status !== 429) {\n return null;\n }\n const originalHeaders = getAPIErrorHeaders(error);\n const details = readErrorProperty(\n readErrorProperty(error, \"body\"),\n \"details\",\n );\n const delay = readErrorProperty(details, \"tryAgainIn\");\n const failure = rejection({\n status,\n reason: sdkReason(error),\n challenge: originalHeaders.get(\"www-authenticate\") ?? undefined,\n retryAfterSeconds:\n status === 429 && typeof delay === \"number\" ? delay / 1000 : undefined,\n });\n const retryAfter = originalHeaders.get(\"retry-after\");\n if (retryAfter !== null) {\n const headers = new Headers(failure.headers);\n headers.set(\"retry-after\", retryAfter);\n return branded({ ...failure, headers }, FAILURE_BRAND);\n }\n return failure;\n },\n};\n\nexport class BetterAuthConfigurationError extends Error {\n readonly code: string;\n readonly detail: string;\n readonly site?: string;\n readonly hint?: string;\n readonly phase: \"boot\" | \"request\";\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_MISCONFIGURED\",\n statusCode: 500,\n } as const;\n readonly issues?: readonly BetterAuthConfigurationError[];\n\n constructor(code: string, detail: string, hint?: string) {\n super(detail);\n this.name = \"BetterAuthConfigurationError\";\n this.code = code;\n this.detail = detail;\n this.hint = hint;\n this.phase = \"boot\";\n branded(this, CONFIGURATION_BRAND);\n }\n\n static atRequest(\n code: string,\n detail: string,\n options?: { site?: string; hint?: string },\n ): BetterAuthConfigurationError {\n const error = new BetterAuthConfigurationError(\n code,\n \"Authentication is misconfigured\",\n options?.hint,\n );\n Object.defineProperties(error, {\n detail: { value: detail, enumerable: true },\n site: { value: options?.site, enumerable: true },\n phase: { value: \"request\", enumerable: true },\n });\n return error;\n }\n}\n\nexport class BetterAuthInfrastructureError extends Error {\n readonly cause: Error;\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_UNAVAILABLE\",\n statusCode: 500,\n } as const;\n\n constructor(cause: unknown, options?: { secrets?: readonly string[] }) {\n super(\"Authentication service unavailable\");\n this.name = \"BetterAuthInfrastructureError\";\n this.cause = new ErrorRedactor(options).redact(cause);\n ORIGINAL_CAUSES.set(this, cause);\n branded(this, INFRASTRUCTURE_BRAND);\n }\n}\n\n/** Internal factory for an instance's explicit diagnostic opt-in, never global state. */\nexport function createInfrastructureError(\n cause: unknown,\n options?: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n // Preserve request-owned redaction inputs without widening the public constructor.\n const error = new BetterAuthInfrastructureError(cause, options);\n if (options?.exposeRawCause === true) {\n Object.defineProperty(error, RAW_CAUSE, {\n value: cause,\n enumerable: false,\n });\n }\n return error;\n}\n\n/**\n * Internal: the form of an already-classified infrastructure error that one request delivers. The request's cookie,\n * authorization and declared credential values are redacted on top of the thrower's own redaction, and the original\n * cause is attached only when the instance opts in, as for errors the kernel classifies itself.\n */\nexport function redactForRequest(\n error: BetterAuthInfrastructureError,\n options: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n const original = ORIGINAL_CAUSES.has(error)\n ? ORIGINAL_CAUSES.get(error)\n : readErrorProperty(error, RAW_CAUSE);\n const delivered = new BetterAuthInfrastructureError(\n readErrorProperty(error, \"cause\"),\n options,\n );\n ORIGINAL_CAUSES.set(delivered, original);\n if (options.exposeRawCause === true && original !== undefined) {\n Object.defineProperty(delivered, RAW_CAUSE, {\n value: original,\n enumerable: false,\n });\n }\n return delivered;\n}\n\nexport function getRawCause(error: BetterAuthInfrastructureError): unknown {\n return readErrorProperty(error, RAW_CAUSE);\n}\n\n/** Internal: evaluation must distinguish session loss from a failed session read. */\nexport interface SessionLossCandidate {\n readonly sessionLoss: unknown;\n readonly reason?: string;\n}\n\n/** Internal safety net. Evaluation performs the authoritative session-loss recheck. */\nexport function normalizeThrown(\n error: unknown,\n where: \"source\" | \"policy\",\n site: string,\n secrets: readonly string[],\n options?: { exposeRawCause?: boolean },\n): AuthFailure | SessionLossCandidate {\n if (isAuthFailure(error)) {\n return error;\n }\n if (isInfrastructureError(error) || isConfigurationError(error)) {\n throw error;\n }\n const status = sdkStatus(error);\n const reason = sdkReason(error);\n if (status === 429) {\n return AuthFailures.fromAPIError(error)!;\n }\n if (\n status === 401 &&\n where === \"policy\" &&\n (reason === undefined || reason === \"UNAUTHORIZED\")\n ) {\n return { sessionLoss: error, reason };\n }\n if (status === 401 || status === 403) {\n return where === \"source\"\n ? AuthFailures.fromAPIError(error)!\n : AuthFailures.forbidden(reason ?? \"FORBIDDEN\");\n }\n if (status !== undefined && status < 500) {\n throw BetterAuthConfigurationError.atRequest(\n \"BETTER_AUTH_REJECTED_CALL\",\n `better-auth rejected the library's call (${status} ${reason})`,\n { site },\n );\n }\n throw createInfrastructureError(error, {\n secrets,\n exposeRawCause: options?.exposeRawCause,\n });\n}\n"],"mappings":";;;AAQA,SAAgB,kBAAkB,OAAgB,KAA2B;CAC3E,KACG,OAAO,UAAU,YAAY,UAAU,SACxC,OAAO,UAAU,YAEjB;CAEF,IAAI;EACF,OAAO,QAAQ,IAAI,OAAO,GAAG;CAC/B,QAAQ;EACN;CACF;AACF;AAEA,IAAa,gBAAb,MAA2B;CACzB;CAEA,YAAY,UAAgC,CAAC,GAAG;EAC9C,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,UAAkB;GAC7B,IAAI,CAAC,OACH;GAEF,OAAO,IAAI,KAAK;GAChB,IAAI,UAAU;GACd,IAAI;IACF,UAAU,mBAAmB,KAAK;IAClC,OAAO,IAAI,OAAO;GACpB,QAAQ,CAER;GACA,KAAK,MAAM,QAAQ,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AW,gBAAgB,IAAI,KAAK,IACtC,gBAAgB,IAAI,KAAK,IACzB,kBAAkB,OAAO,SAAS;CACtC,MAAM,YAAY,IAAI,8BACpB,kBAAkB,OAAO,OAAO,GAChC,OACF;CACA,gBAAgB,IAAI,WAAW,QAAQ;CACvC,IAAI,QAAQ,mBAAmB,QAAQ,aAAa,KAAA,GAClD,OAAO,eAAe,WAAW,WAAW;EAC1C,OAAO;EACP,YAAY;CACd,CAAC;CAEH,OAAO;AACT;AAEA,SAAgB,YAAY,OAA+C;CACzE,OAAO,kBAAkB,OAAO,SAAS;AAC3C;;AASA,SAAgB,gBACd,OACA,OACA,MACA,SACA,SACoC;CACpC,IAAI,cAAc,KAAK,GACrB,OAAO;CAET,IAAI,sBAAsB,KAAK,KAAK,qBAAqB,KAAK,GAC5D,MAAM;CAER,MAAM,SAAS,UAAU,KAAK;CAC9B,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,WAAW,KACb,OAAO,aAAa,aAAa,KAAK;CAExC,IACE,WAAW,OACX,UAAU,aACT,WAAW,KAAA,KAAa,WAAW,iBAEpC,OAAO;EAAE,aAAa;EAAO;CAAO;CAEtC,IAAI,WAAW,OAAO,WAAW,KAC/B,OAAO,UAAU,WACb,aAAa,aAAa,KAAK,IAC/B,aAAa,UAAU,UAAU,WAAW;CAElD,IAAI,WAAW,KAAA,KAAa,SAAS,KACnC,MAAM,6BAA6B,UACjC,6BACA,4CAA4C,OAAO,GAAG,OAAO,IAC7D,EAAE,KAAK,CACT;CAEF,MAAM,0BAA0B,OAAO;EACrC;EACA,gBAAgB,SAAS;CAC3B,CAAC;AACH"}
1
+ {"version":3,"file":"auth-errors-JjxGDVSt.mjs","names":[],"sources":["../src/error-redactor.ts","../src/auth-errors.ts"],"sourcesContent":["/** Inputs come from the active request's owner; the redactor retains no scope. */\nexport interface ErrorRedactorOptions {\n secrets?: readonly string[];\n headers?: Headers;\n credentialHeaders?: readonly string[];\n}\n\n/** Reading an arbitrary thrown value must not invoke another escaping fault. */\nexport function readErrorProperty(value: unknown, key: PropertyKey): unknown {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport class ErrorRedactor {\n readonly #secrets: readonly string[];\n\n constructor(options: ErrorRedactorOptions = {}) {\n const values = new Set<string>();\n const add = (value: string) => {\n if (!value) {\n return;\n }\n values.add(value);\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n values.add(decoded);\n } catch {\n // Invalid escaping must not prevent redaction of the raw credential.\n }\n for (const form of [value, decoded]) {\n const separator = form.lastIndexOf(\".\");\n if (separator >= 16) {\n values.add(form.slice(0, separator));\n }\n }\n };\n for (const value of options.secrets ?? []) {\n add(value);\n }\n const headers = options.headers;\n for (const cookie of (headers?.get(\"cookie\") ?? \"\").split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator >= 0) {\n const value = cookie.slice(separator + 1).trim();\n add(value);\n if (value.startsWith('\"') && value.endsWith('\"')) {\n add(value.slice(1, -1));\n }\n }\n }\n const authorization = headers?.get(\"authorization\");\n if (authorization) {\n add(authorization);\n const credential = /^\\S+\\s+(.+)$/.exec(authorization)?.[1];\n if (credential) {\n add(credential);\n }\n }\n for (const name of options.credentialHeaders ?? []) {\n const value = headers?.get(name);\n if (value) {\n add(value);\n }\n }\n this.#secrets = [...values].sort(\n (left, right) => right.length - left.length,\n );\n }\n\n redact(cause: unknown): Error {\n return this.redactCause(cause, 0, new Set());\n }\n\n private replaceSecrets(value: string): string {\n for (const secret of this.#secrets) {\n value = value.split(secret).join(\"[REDACTED]\");\n }\n return value;\n }\n\n private diagnostic(value: string): string {\n return this.replaceSecrets(value)\n .split(/[\\r\\n]/, 1)[0]\n .slice(0, 300);\n }\n\n private redactCause(\n cause: unknown,\n depth: number,\n seen: Set<unknown>,\n ): Error {\n const message = readErrorProperty(cause, \"message\");\n const error = new Error(\n this.diagnostic(\n typeof message === \"string\"\n ? message\n : typeof cause === \"string\"\n ? cause\n : \"Unknown authentication infrastructure failure\",\n ),\n );\n const name = readErrorProperty(cause, \"name\");\n error.name = typeof name === \"string\" ? this.diagnostic(name) : \"Error\";\n for (const key of [\"code\", \"errno\", \"syscall\"] as const) {\n const value = readErrorProperty(cause, key);\n if (\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n Object.defineProperty(error, key, {\n value: typeof value === \"string\" ? this.diagnostic(value) : value,\n enumerable: true,\n });\n }\n }\n const stack = readErrorProperty(cause, \"stack\");\n const frames =\n typeof stack === \"string\"\n ? stack\n .split(/\\r?\\n/)\n .filter((line) => /^\\s+at .+:\\d+:\\d+\\)?$/.test(line))\n .map((line) => this.replaceSecrets(line))\n : [];\n error.stack = [`${error.name}: ${error.message}`, ...frames].join(\"\\n\");\n seen.add(cause);\n const nested = readErrorProperty(cause, \"cause\");\n if (nested !== undefined && depth < 3 && !seen.has(nested)) {\n Object.defineProperty(error, \"cause\", {\n value: this.redactCause(nested, depth + 1, seen),\n enumerable: false,\n });\n }\n return error;\n }\n}\n","import type { ExecutionContext } from \"@nestjs/common\";\nimport { isAPIError } from \"better-auth/api\";\nimport {\n ErrorRedactor,\n type ErrorRedactorOptions,\n readErrorProperty,\n} from \"./error-redactor.js\";\n\nconst FAILURE_BRAND = Symbol.for(\"@nestjs-kit/better-auth:auth-failure\");\nconst INFRASTRUCTURE_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:infrastructure-error\",\n);\nconst CONFIGURATION_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:configuration-error\",\n);\nconst RAW_CAUSE = Symbol.for(\"@nestjs-kit/better-auth:raw-cause\");\n/** Unredacted causes stay module-private; only an instance's exposeRawCause opt-in attaches one (RAW_CAUSE). */\nconst ORIGINAL_CAUSES = new WeakMap<object, unknown>();\nconst SDK_HEADERS = Symbol.for(\"better-call:api-error-headers\");\n\nexport type AuthErrorCode = \"UNAUTHENTICATED\" | \"FORBIDDEN\" | \"RATE_LIMITED\";\n\n/** A transport-neutral denial. Only transports make it throwable. */\nexport interface AuthFailure {\n readonly status: 401 | 403 | 429;\n readonly code: AuthErrorCode;\n readonly reason?: string;\n readonly message: string;\n readonly challenge?: string;\n readonly headers?: Headers;\n}\n\nexport interface AuthErrorBody {\n statusCode: 401 | 403 | 429;\n error: string;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface AuthGraphqlExtensions {\n code: AuthErrorCode | \"INTERNAL_SERVER_ERROR\";\n reason?: string;\n statusCode: number;\n}\n\nexport interface AuthTransportErrorPayload {\n status: \"error\";\n statusCode: number;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface ErrorMappingOptions {\n map?: (\n failure: AuthFailure,\n context: ExecutionContext,\n transport: string,\n ) => unknown;\n exposeRawCause?: boolean;\n}\n\nfunction branded<T extends object>(value: T, brand: symbol): T {\n Object.defineProperty(value, brand, { value: true });\n return value;\n}\n\nexport function isAuthFailure(value: unknown): value is AuthFailure {\n return readErrorProperty(value, FAILURE_BRAND) === true;\n}\n\nexport function isInfrastructureError(\n value: unknown,\n): value is BetterAuthInfrastructureError {\n return readErrorProperty(value, INFRASTRUCTURE_BRAND) === true;\n}\n\nexport function isConfigurationError(\n value: unknown,\n): value is BetterAuthConfigurationError {\n return readErrorProperty(value, CONFIGURATION_BRAND) === true;\n}\n\nfunction sdkStatus(error: unknown): number | undefined {\n try {\n if (!isAPIError(error)) {\n return undefined;\n }\n const status = readErrorProperty(error, \"statusCode\");\n return typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= 100 &&\n status <= 599\n ? status\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction sdkReason(error: unknown): string | undefined {\n const reason = readErrorProperty(readErrorProperty(error, \"body\"), \"code\");\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/** Internal: preserve cookie lines for the exchange's separately governed cleanup. */\nexport function getAPIErrorHeaders(error: unknown): Headers {\n const result = new Headers();\n for (const value of [\n readErrorProperty(error, SDK_HEADERS),\n readErrorProperty(error, \"headers\"),\n ]) {\n if (value === undefined || value === null) {\n continue;\n }\n try {\n const headers = new Headers(value as HeadersInit);\n for (const [name, value] of headers) {\n if (name !== \"set-cookie\") {\n result.set(name, value);\n }\n }\n for (const cookie of headers.getSetCookie()) {\n result.append(\"set-cookie\", cookie);\n }\n } catch {\n // A malformed optional header collection must not mask the original fault.\n }\n }\n return result;\n}\n\nfunction rejection(input: {\n status: 401 | 403 | 429;\n reason?: string;\n message?: string;\n challenge?: string;\n retryAfterSeconds?: number;\n}): AuthFailure {\n const codes = {\n 401: \"UNAUTHENTICATED\",\n 403: \"FORBIDDEN\",\n 429: \"RATE_LIMITED\",\n } as const;\n const messages = {\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 429: \"Too Many Requests\",\n } as const;\n const headers = new Headers();\n const retry = input.retryAfterSeconds;\n if (retry !== undefined && Number.isFinite(retry) && retry >= 0) {\n headers.set(\"retry-after\", String(Math.ceil(retry)));\n }\n return branded(\n {\n status: input.status,\n code: codes[input.status],\n reason: input.reason,\n message: input.message ?? messages[input.status],\n challenge: input.challenge,\n ...(headers.has(\"retry-after\") ? { headers } : {}),\n },\n FAILURE_BRAND,\n );\n}\n\nexport const AuthFailures = {\n unauthenticated(message?: string): AuthFailure {\n return rejection({ status: 401, message });\n },\n rejected: rejection,\n forbidden(reason: string, message?: string): AuthFailure {\n return rejection({ status: 403, reason, message });\n },\n fromAPIError(error: unknown): AuthFailure | null {\n const status = sdkStatus(error);\n if (status !== 401 && status !== 403 && status !== 429) {\n return null;\n }\n const originalHeaders = getAPIErrorHeaders(error);\n const details = readErrorProperty(\n readErrorProperty(error, \"body\"),\n \"details\",\n );\n const delay = readErrorProperty(details, \"tryAgainIn\");\n const failure = rejection({\n status,\n reason: sdkReason(error),\n challenge: originalHeaders.get(\"www-authenticate\") ?? undefined,\n retryAfterSeconds:\n status === 429 && typeof delay === \"number\" ? delay / 1000 : undefined,\n });\n const retryAfter = originalHeaders.get(\"retry-after\");\n if (retryAfter !== null) {\n const headers = new Headers(failure.headers);\n headers.set(\"retry-after\", retryAfter);\n return branded({ ...failure, headers }, FAILURE_BRAND);\n }\n return failure;\n },\n};\n\nexport class BetterAuthConfigurationError extends Error {\n readonly code: string;\n readonly detail: string;\n readonly site?: string;\n readonly hint?: string;\n readonly phase: \"boot\" | \"request\";\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_MISCONFIGURED\",\n statusCode: 500,\n } as const;\n readonly issues?: readonly BetterAuthConfigurationError[];\n\n constructor(code: string, detail: string, hint?: string) {\n super(detail);\n this.name = \"BetterAuthConfigurationError\";\n this.code = code;\n this.detail = detail;\n this.hint = hint;\n this.phase = \"boot\";\n branded(this, CONFIGURATION_BRAND);\n }\n\n static atRequest(\n code: string,\n detail: string,\n options?: { site?: string; hint?: string },\n ): BetterAuthConfigurationError {\n const error = new BetterAuthConfigurationError(\n code,\n \"Authentication is misconfigured\",\n options?.hint,\n );\n Object.defineProperties(error, {\n detail: { value: detail, enumerable: true },\n site: { value: options?.site, enumerable: true },\n phase: { value: \"request\", enumerable: true },\n });\n return error;\n }\n}\n\nexport class BetterAuthInfrastructureError extends Error {\n readonly cause: Error;\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_UNAVAILABLE\",\n statusCode: 500,\n } as const;\n\n constructor(cause: unknown, options?: { secrets?: readonly string[] }) {\n super(\"Authentication service unavailable\");\n this.name = \"BetterAuthInfrastructureError\";\n this.cause = new ErrorRedactor(options).redact(cause);\n ORIGINAL_CAUSES.set(this, cause);\n branded(this, INFRASTRUCTURE_BRAND);\n }\n}\n\n/** Internal factory for an instance's explicit diagnostic opt-in, never global state. */\nexport function createInfrastructureError(\n cause: unknown,\n options?: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n // Preserve request-owned redaction inputs without widening the public constructor.\n const error = new BetterAuthInfrastructureError(cause, options);\n if (options?.exposeRawCause === true) {\n Object.defineProperty(error, RAW_CAUSE, {\n value: cause,\n enumerable: false,\n });\n }\n return error;\n}\n\n/**\n * Internal: the form of an already-classified infrastructure error that one request delivers. The request's cookie,\n * authorization and declared credential values are redacted on top of the thrower's own redaction, and the original\n * cause is attached only when the instance opts in, as for errors the kernel classifies itself.\n */\nexport function redactForRequest(\n error: BetterAuthInfrastructureError,\n options: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n const original = ORIGINAL_CAUSES.has(error)\n ? ORIGINAL_CAUSES.get(error)\n : readErrorProperty(error, RAW_CAUSE);\n const delivered = new BetterAuthInfrastructureError(\n readErrorProperty(error, \"cause\"),\n options,\n );\n ORIGINAL_CAUSES.set(delivered, original);\n if (options.exposeRawCause === true && original !== undefined) {\n Object.defineProperty(delivered, RAW_CAUSE, {\n value: original,\n enumerable: false,\n });\n }\n return delivered;\n}\n\nexport function getRawCause(error: BetterAuthInfrastructureError): unknown {\n return readErrorProperty(error, RAW_CAUSE);\n}\n\n/** Internal: evaluation must distinguish session loss from a failed session read. */\nexport interface SessionLossCandidate {\n readonly sessionLoss: unknown;\n readonly reason?: string;\n}\n\n/** Internal safety net. Evaluation performs the authoritative session-loss recheck. */\nexport function normalizeThrown(\n error: unknown,\n where: \"source\" | \"policy\",\n site: string,\n secrets: readonly string[],\n options?: { exposeRawCause?: boolean },\n): AuthFailure | SessionLossCandidate {\n if (isAuthFailure(error)) {\n return error;\n }\n if (isInfrastructureError(error) || isConfigurationError(error)) {\n throw error;\n }\n const status = sdkStatus(error);\n const reason = sdkReason(error);\n if (status === 429) {\n return AuthFailures.fromAPIError(error)!;\n }\n if (\n status === 401 &&\n where === \"policy\" &&\n (reason === undefined || reason === \"UNAUTHORIZED\")\n ) {\n return { sessionLoss: error, reason };\n }\n if (status === 401 || status === 403) {\n return where === \"source\"\n ? AuthFailures.fromAPIError(error)!\n : AuthFailures.forbidden(reason ?? \"FORBIDDEN\");\n }\n if (status !== undefined && status < 500) {\n throw BetterAuthConfigurationError.atRequest(\n \"BETTER_AUTH_REJECTED_CALL\",\n `better-auth rejected the library's call (${status} ${reason})`,\n { site },\n );\n }\n throw createInfrastructureError(error, {\n secrets,\n exposeRawCause: options?.exposeRawCause,\n });\n}\n"],"mappings":";;;AAQA,SAAgB,kBAAkB,OAAgB,KAA2B;CAC3E,KACG,OAAO,UAAU,YAAY,UAAU,SACxC,OAAO,UAAU,YAEjB;CAEF,IAAI;EACF,OAAO,QAAQ,IAAI,OAAO,GAAG;CAC/B,QAAQ;EACN;CACF;AACF;AAEA,IAAa,gBAAb,MAA2B;CACzB;CAEA,YAAY,UAAgC,CAAC,GAAG;EAC9C,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,UAAkB;GAC7B,IAAI,CAAC,OACH;GAEF,OAAO,IAAI,KAAK;GAChB,IAAI,UAAU;GACd,IAAI;IACF,UAAU,mBAAmB,KAAK;IAClC,OAAO,IAAI,OAAO;GACpB,QAAQ,CAER;GACA,KAAK,MAAM,QAAQ,CAAC,OAAO,OAAO,GAAG;IACnC,MAAM,YAAY,KAAK,YAAY,GAAG;IACtC,IAAI,aAAa,IACf,OAAO,IAAI,KAAK,MAAM,GAAG,SAAS,CAAC;GAEvC;EACF;EACA,KAAK,MAAM,SAAS,QAAQ,WAAW,CAAC,GACtC,IAAI,KAAK;EAEX,MAAM,UAAU,QAAQ;EACxB,KAAK,MAAM,WAAW,SAAS,IAAI,QAAQ,KAAK,GAAA,CAAI,MAAM,GAAG,GAAG;GAC9D,MAAM,YAAY,OAAO,QAAQ,GAAG;GACpC,IAAI,aAAa,GAAG;IAClB,MAAM,QAAQ,OAAO,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK;IAC/C,IAAI,KAAK;IACT,IAAI,MAAM,WAAW,IAAG,KAAK,MAAM,SAAS,IAAG,GAC7C,IAAI,MAAM,MAAM,GAAG,EAAE,CAAC;GAE1B;EACF;EACA,MAAM,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;CAC9B,IAAI,WAAW,KACb,OAAO,aAAa,aAAa,KAAK;CAExC,IACE,WAAW,OACX,UAAU,aACT,WAAW,KAAA,KAAa,WAAW,iBAEpC,OAAO;EAAE,aAAa;EAAO;CAAO;CAEtC,IAAI,WAAW,OAAO,WAAW,KAC/B,OAAO,UAAU,WACb,aAAa,aAAa,KAAK,IAC/B,aAAa,UAAU,UAAU,WAAW;CAElD,IAAI,WAAW,KAAA,KAAa,SAAS,KACnC,MAAM,6BAA6B,UACjC,6BACA,4CAA4C,OAAO,GAAG,OAAO,IAC7D,EAAE,KAAK,CACT;CAEF,MAAM,0BAA0B,OAAO;EACrC;EACA,gBAAgB,SAAS;CAC3B,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
  let better_auth_api = require("better-auth/api");
2
- //#region src/error-redactor.ts
2
+ // src/error-redactor.ts
3
3
  /** Reading an arbitrary thrown value must not invoke another escaping fault. */
4
4
  function readErrorProperty(value, key) {
5
5
  if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
@@ -86,8 +86,7 @@ var ErrorRedactor = class {
86
86
  return error;
87
87
  }
88
88
  };
89
- //#endregion
90
- //#region src/auth-errors.ts
89
+ // src/auth-errors.ts
91
90
  const FAILURE_BRAND = Symbol.for("@nestjs-kit/better-auth:auth-failure");
92
91
  const INFRASTRUCTURE_BRAND = Symbol.for("@nestjs-kit/better-auth:infrastructure-error");
93
92
  const CONFIGURATION_BRAND = Symbol.for("@nestjs-kit/better-auth:configuration-error");
@@ -295,7 +294,6 @@ function normalizeThrown(error, where, site, secrets, options) {
295
294
  exposeRawCause: options?.exposeRawCause
296
295
  });
297
296
  }
298
- //#endregion
299
297
  Object.defineProperty(exports, "AuthFailures", {
300
298
  enumerable: true,
301
299
  get: function() {
@@ -375,4 +373,4 @@ Object.defineProperty(exports, "redactForRequest", {
375
373
  }
376
374
  });
377
375
 
378
- //# sourceMappingURL=auth-errors-DmiKl0L_.cjs.map
376
+ //# sourceMappingURL=auth-errors-RW7hOVI-.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-errors-DmiKl0L_.cjs","names":["isAPIError"],"sources":["../src/error-redactor.ts","../src/auth-errors.ts"],"sourcesContent":["/** Inputs come from the active request's owner; the redactor retains no scope. */\nexport interface ErrorRedactorOptions {\n secrets?: readonly string[];\n headers?: Headers;\n credentialHeaders?: readonly string[];\n}\n\n/** Reading an arbitrary thrown value must not invoke another escaping fault. */\nexport function readErrorProperty(value: unknown, key: PropertyKey): unknown {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport class ErrorRedactor {\n readonly #secrets: readonly string[];\n\n constructor(options: ErrorRedactorOptions = {}) {\n const values = new Set<string>();\n const add = (value: string) => {\n if (!value) {\n return;\n }\n values.add(value);\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n values.add(decoded);\n } catch {\n // Invalid escaping must not prevent redaction of the raw credential.\n }\n for (const form of [value, decoded]) {\n const separator = form.lastIndexOf(\".\");\n if (separator >= 16) {\n values.add(form.slice(0, separator));\n }\n }\n };\n for (const value of options.secrets ?? []) {\n add(value);\n }\n const headers = options.headers;\n for (const cookie of (headers?.get(\"cookie\") ?? \"\").split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator >= 0) {\n const value = cookie.slice(separator + 1).trim();\n add(value);\n if (value.startsWith('\"') && value.endsWith('\"')) {\n add(value.slice(1, -1));\n }\n }\n }\n const authorization = headers?.get(\"authorization\");\n if (authorization) {\n add(authorization);\n const credential = /^\\S+\\s+(.+)$/.exec(authorization)?.[1];\n if (credential) {\n add(credential);\n }\n }\n for (const name of options.credentialHeaders ?? []) {\n const value = headers?.get(name);\n if (value) {\n add(value);\n }\n }\n this.#secrets = [...values].sort(\n (left, right) => right.length - left.length,\n );\n }\n\n redact(cause: unknown): Error {\n return this.redactCause(cause, 0, new Set());\n }\n\n private replaceSecrets(value: string): string {\n for (const secret of this.#secrets) {\n value = value.split(secret).join(\"[REDACTED]\");\n }\n return value;\n }\n\n private diagnostic(value: string): string {\n return this.replaceSecrets(value)\n .split(/[\\r\\n]/, 1)[0]\n .slice(0, 300);\n }\n\n private redactCause(\n cause: unknown,\n depth: number,\n seen: Set<unknown>,\n ): Error {\n const message = readErrorProperty(cause, \"message\");\n const error = new Error(\n this.diagnostic(\n typeof message === \"string\"\n ? message\n : typeof cause === \"string\"\n ? cause\n : \"Unknown authentication infrastructure failure\",\n ),\n );\n const name = readErrorProperty(cause, \"name\");\n error.name = typeof name === \"string\" ? this.diagnostic(name) : \"Error\";\n for (const key of [\"code\", \"errno\", \"syscall\"] as const) {\n const value = readErrorProperty(cause, key);\n if (\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n Object.defineProperty(error, key, {\n value: typeof value === \"string\" ? this.diagnostic(value) : value,\n enumerable: true,\n });\n }\n }\n const stack = readErrorProperty(cause, \"stack\");\n const frames =\n typeof stack === \"string\"\n ? stack\n .split(/\\r?\\n/)\n .filter((line) => /^\\s+at .+:\\d+:\\d+\\)?$/.test(line))\n .map((line) => this.replaceSecrets(line))\n : [];\n error.stack = [`${error.name}: ${error.message}`, ...frames].join(\"\\n\");\n seen.add(cause);\n const nested = readErrorProperty(cause, \"cause\");\n if (nested !== undefined && depth < 3 && !seen.has(nested)) {\n Object.defineProperty(error, \"cause\", {\n value: this.redactCause(nested, depth + 1, seen),\n enumerable: false,\n });\n }\n return error;\n }\n}\n","import type { ExecutionContext } from \"@nestjs/common\";\nimport { isAPIError } from \"better-auth/api\";\nimport {\n ErrorRedactor,\n type ErrorRedactorOptions,\n readErrorProperty,\n} from \"./error-redactor.js\";\n\nconst FAILURE_BRAND = Symbol.for(\"@nestjs-kit/better-auth:auth-failure\");\nconst INFRASTRUCTURE_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:infrastructure-error\",\n);\nconst CONFIGURATION_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:configuration-error\",\n);\nconst RAW_CAUSE = Symbol.for(\"@nestjs-kit/better-auth:raw-cause\");\n/** Unredacted causes stay module-private; only an instance's exposeRawCause opt-in attaches one (RAW_CAUSE). */\nconst ORIGINAL_CAUSES = new WeakMap<object, unknown>();\nconst SDK_HEADERS = Symbol.for(\"better-call:api-error-headers\");\n\nexport type AuthErrorCode = \"UNAUTHENTICATED\" | \"FORBIDDEN\" | \"RATE_LIMITED\";\n\n/** A transport-neutral denial. Only transports make it throwable. */\nexport interface AuthFailure {\n readonly status: 401 | 403 | 429;\n readonly code: AuthErrorCode;\n readonly reason?: string;\n readonly message: string;\n readonly challenge?: string;\n readonly headers?: Headers;\n}\n\nexport interface AuthErrorBody {\n statusCode: 401 | 403 | 429;\n error: string;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface AuthGraphqlExtensions {\n code: AuthErrorCode | \"INTERNAL_SERVER_ERROR\";\n reason?: string;\n statusCode: number;\n}\n\nexport interface AuthTransportErrorPayload {\n status: \"error\";\n statusCode: number;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface ErrorMappingOptions {\n map?: (\n failure: AuthFailure,\n context: ExecutionContext,\n transport: string,\n ) => unknown;\n exposeRawCause?: boolean;\n}\n\nfunction branded<T extends object>(value: T, brand: symbol): T {\n Object.defineProperty(value, brand, { value: true });\n return value;\n}\n\nexport function isAuthFailure(value: unknown): value is AuthFailure {\n return readErrorProperty(value, FAILURE_BRAND) === true;\n}\n\nexport function isInfrastructureError(\n value: unknown,\n): value is BetterAuthInfrastructureError {\n return readErrorProperty(value, INFRASTRUCTURE_BRAND) === true;\n}\n\nexport function isConfigurationError(\n value: unknown,\n): value is BetterAuthConfigurationError {\n return readErrorProperty(value, CONFIGURATION_BRAND) === true;\n}\n\nfunction sdkStatus(error: unknown): number | undefined {\n try {\n if (!isAPIError(error)) {\n return undefined;\n }\n const status = readErrorProperty(error, \"statusCode\");\n return typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= 100 &&\n status <= 599\n ? status\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction sdkReason(error: unknown): string | undefined {\n const reason = readErrorProperty(readErrorProperty(error, \"body\"), \"code\");\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/** Internal: preserve cookie lines for the exchange's separately governed cleanup. */\nexport function getAPIErrorHeaders(error: unknown): Headers {\n const result = new Headers();\n for (const value of [\n readErrorProperty(error, SDK_HEADERS),\n readErrorProperty(error, \"headers\"),\n ]) {\n if (value === undefined || value === null) {\n continue;\n }\n try {\n const headers = new Headers(value as HeadersInit);\n for (const [name, value] of headers) {\n if (name !== \"set-cookie\") {\n result.set(name, value);\n }\n }\n for (const cookie of headers.getSetCookie()) {\n result.append(\"set-cookie\", cookie);\n }\n } catch {\n // A malformed optional header collection must not mask the original fault.\n }\n }\n return result;\n}\n\nfunction rejection(input: {\n status: 401 | 403 | 429;\n reason?: string;\n message?: string;\n challenge?: string;\n retryAfterSeconds?: number;\n}): AuthFailure {\n const codes = {\n 401: \"UNAUTHENTICATED\",\n 403: \"FORBIDDEN\",\n 429: \"RATE_LIMITED\",\n } as const;\n const messages = {\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 429: \"Too Many Requests\",\n } as const;\n const headers = new Headers();\n const retry = input.retryAfterSeconds;\n if (retry !== undefined && Number.isFinite(retry) && retry >= 0) {\n headers.set(\"retry-after\", String(Math.ceil(retry)));\n }\n return branded(\n {\n status: input.status,\n code: codes[input.status],\n reason: input.reason,\n message: input.message ?? messages[input.status],\n challenge: input.challenge,\n ...(headers.has(\"retry-after\") ? { headers } : {}),\n },\n FAILURE_BRAND,\n );\n}\n\nexport const AuthFailures = {\n unauthenticated(message?: string): AuthFailure {\n return rejection({ status: 401, message });\n },\n rejected: rejection,\n forbidden(reason: string, message?: string): AuthFailure {\n return rejection({ status: 403, reason, message });\n },\n fromAPIError(error: unknown): AuthFailure | null {\n const status = sdkStatus(error);\n if (status !== 401 && status !== 403 && status !== 429) {\n return null;\n }\n const originalHeaders = getAPIErrorHeaders(error);\n const details = readErrorProperty(\n readErrorProperty(error, \"body\"),\n \"details\",\n );\n const delay = readErrorProperty(details, \"tryAgainIn\");\n const failure = rejection({\n status,\n reason: sdkReason(error),\n challenge: originalHeaders.get(\"www-authenticate\") ?? undefined,\n retryAfterSeconds:\n status === 429 && typeof delay === \"number\" ? delay / 1000 : undefined,\n });\n const retryAfter = originalHeaders.get(\"retry-after\");\n if (retryAfter !== null) {\n const headers = new Headers(failure.headers);\n headers.set(\"retry-after\", retryAfter);\n return branded({ ...failure, headers }, FAILURE_BRAND);\n }\n return failure;\n },\n};\n\nexport class BetterAuthConfigurationError extends Error {\n readonly code: string;\n readonly detail: string;\n readonly site?: string;\n readonly hint?: string;\n readonly phase: \"boot\" | \"request\";\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_MISCONFIGURED\",\n statusCode: 500,\n } as const;\n readonly issues?: readonly BetterAuthConfigurationError[];\n\n constructor(code: string, detail: string, hint?: string) {\n super(detail);\n this.name = \"BetterAuthConfigurationError\";\n this.code = code;\n this.detail = detail;\n this.hint = hint;\n this.phase = \"boot\";\n branded(this, CONFIGURATION_BRAND);\n }\n\n static atRequest(\n code: string,\n detail: string,\n options?: { site?: string; hint?: string },\n ): BetterAuthConfigurationError {\n const error = new BetterAuthConfigurationError(\n code,\n \"Authentication is misconfigured\",\n options?.hint,\n );\n Object.defineProperties(error, {\n detail: { value: detail, enumerable: true },\n site: { value: options?.site, enumerable: true },\n phase: { value: \"request\", enumerable: true },\n });\n return error;\n }\n}\n\nexport class BetterAuthInfrastructureError extends Error {\n readonly cause: Error;\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_UNAVAILABLE\",\n statusCode: 500,\n } as const;\n\n constructor(cause: unknown, options?: { secrets?: readonly string[] }) {\n super(\"Authentication service unavailable\");\n this.name = \"BetterAuthInfrastructureError\";\n this.cause = new ErrorRedactor(options).redact(cause);\n ORIGINAL_CAUSES.set(this, cause);\n branded(this, INFRASTRUCTURE_BRAND);\n }\n}\n\n/** Internal factory for an instance's explicit diagnostic opt-in, never global state. */\nexport function createInfrastructureError(\n cause: unknown,\n options?: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n // Preserve request-owned redaction inputs without widening the public constructor.\n const error = new BetterAuthInfrastructureError(cause, options);\n if (options?.exposeRawCause === true) {\n Object.defineProperty(error, RAW_CAUSE, {\n value: cause,\n enumerable: false,\n });\n }\n return error;\n}\n\n/**\n * Internal: the form of an already-classified infrastructure error that one request delivers. The request's cookie,\n * authorization and declared credential values are redacted on top of the thrower's own redaction, and the original\n * cause is attached only when the instance opts in, as for errors the kernel classifies itself.\n */\nexport function redactForRequest(\n error: BetterAuthInfrastructureError,\n options: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n const original = ORIGINAL_CAUSES.has(error)\n ? ORIGINAL_CAUSES.get(error)\n : readErrorProperty(error, RAW_CAUSE);\n const delivered = new BetterAuthInfrastructureError(\n readErrorProperty(error, \"cause\"),\n options,\n );\n ORIGINAL_CAUSES.set(delivered, original);\n if (options.exposeRawCause === true && original !== undefined) {\n Object.defineProperty(delivered, RAW_CAUSE, {\n value: original,\n enumerable: false,\n });\n }\n return delivered;\n}\n\nexport function getRawCause(error: BetterAuthInfrastructureError): unknown {\n return readErrorProperty(error, RAW_CAUSE);\n}\n\n/** Internal: evaluation must distinguish session loss from a failed session read. */\nexport interface SessionLossCandidate {\n readonly sessionLoss: unknown;\n readonly reason?: string;\n}\n\n/** Internal safety net. Evaluation performs the authoritative session-loss recheck. */\nexport function normalizeThrown(\n error: unknown,\n where: \"source\" | \"policy\",\n site: string,\n secrets: readonly string[],\n options?: { exposeRawCause?: boolean },\n): AuthFailure | SessionLossCandidate {\n if (isAuthFailure(error)) {\n return error;\n }\n if (isInfrastructureError(error) || isConfigurationError(error)) {\n throw error;\n }\n const status = sdkStatus(error);\n const reason = sdkReason(error);\n if (status === 429) {\n return AuthFailures.fromAPIError(error)!;\n }\n if (\n status === 401 &&\n where === \"policy\" &&\n (reason === undefined || reason === \"UNAUTHORIZED\")\n ) {\n return { sessionLoss: error, reason };\n }\n if (status === 401 || status === 403) {\n return where === \"source\"\n ? AuthFailures.fromAPIError(error)!\n : AuthFailures.forbidden(reason ?? \"FORBIDDEN\");\n }\n if (status !== undefined && status < 500) {\n throw BetterAuthConfigurationError.atRequest(\n \"BETTER_AUTH_REJECTED_CALL\",\n `better-auth rejected the library's call (${status} ${reason})`,\n { site },\n );\n }\n throw createInfrastructureError(error, {\n secrets,\n exposeRawCause: options?.exposeRawCause,\n });\n}\n"],"mappings":";;;AAQA,SAAgB,kBAAkB,OAAgB,KAA2B;CAC3E,KACG,OAAO,UAAU,YAAY,UAAU,SACxC,OAAO,UAAU,YAEjB;CAEF,IAAI;EACF,OAAO,QAAQ,IAAI,OAAO,GAAG;CAC/B,QAAQ;EACN;CACF;AACF;AAEA,IAAa,gBAAb,MAA2B;CACzB;CAEA,YAAY,UAAgC,CAAC,GAAG;EAC9C,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,UAAkB;GAC7B,IAAI,CAAC,OACH;GAEF,OAAO,IAAI,KAAK;GAChB,IAAI,UAAU;GACd,IAAI;IACF,UAAU,mBAAmB,KAAK;IAClC,OAAO,IAAI,OAAO;GACpB,QAAQ,CAER;GACA,KAAK,MAAM,QAAQ,CAAC,OAAO,OAAO,GAAG;IACnC,MAAM,YAAY,KAAK,YAAY,GAAG;IACtC,IAAI,aAAa,IACf,OAAO,IAAI,KAAK,MAAM,GAAG,SAAS,CAAC;GAEvC;EACF;EACA,KAAK,MAAM,SAAS,QAAQ,WAAW,CAAC,GACtC,IAAI,KAAK;EAEX,MAAM,UAAU,QAAQ;EACxB,KAAK,MAAM,WAAW,SAAS,IAAI,QAAQ,KAAK,GAAA,CAAI,MAAM,GAAG,GAAG;GAC9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AEH,OAAO;AACT;AAEA,SAAgB,YAAY,OAA+C;CACzE,OAAO,kBAAkB,OAAO,SAAS;AAC3C;;AASA,SAAgB,gBACd,OACA,OACA,MACA,SACA,SACoC;CACpC,IAAI,cAAc,KAAK,GACrB,OAAO;CAET,IAAI,sBAAsB,KAAK,KAAK,qBAAqB,KAAK,GAC5D,MAAM;CAER,MAAM,SAAS,UAAU,KAAK;CAC9B,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,WAAW,KACb,OAAO,aAAa,aAAa,KAAK;CAExC,IACE,WAAW,OACX,UAAU,aACT,WAAW,KAAA,KAAa,WAAW,iBAEpC,OAAO;EAAE,aAAa;EAAO;CAAO;CAEtC,IAAI,WAAW,OAAO,WAAW,KAC/B,OAAO,UAAU,WACb,aAAa,aAAa,KAAK,IAC/B,aAAa,UAAU,UAAU,WAAW;CAElD,IAAI,WAAW,KAAA,KAAa,SAAS,KACnC,MAAM,6BAA6B,UACjC,6BACA,4CAA4C,OAAO,GAAG,OAAO,IAC7D,EAAE,KAAK,CACT;CAEF,MAAM,0BAA0B,OAAO;EACrC;EACA,gBAAgB,SAAS;CAC3B,CAAC;AACH"}
1
+ {"version":3,"file":"auth-errors-RW7hOVI-.cjs","names":["isAPIError"],"sources":["../src/error-redactor.ts","../src/auth-errors.ts"],"sourcesContent":["/** Inputs come from the active request's owner; the redactor retains no scope. */\nexport interface ErrorRedactorOptions {\n secrets?: readonly string[];\n headers?: Headers;\n credentialHeaders?: readonly string[];\n}\n\n/** Reading an arbitrary thrown value must not invoke another escaping fault. */\nexport function readErrorProperty(value: unknown, key: PropertyKey): unknown {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport class ErrorRedactor {\n readonly #secrets: readonly string[];\n\n constructor(options: ErrorRedactorOptions = {}) {\n const values = new Set<string>();\n const add = (value: string) => {\n if (!value) {\n return;\n }\n values.add(value);\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n values.add(decoded);\n } catch {\n // Invalid escaping must not prevent redaction of the raw credential.\n }\n for (const form of [value, decoded]) {\n const separator = form.lastIndexOf(\".\");\n if (separator >= 16) {\n values.add(form.slice(0, separator));\n }\n }\n };\n for (const value of options.secrets ?? []) {\n add(value);\n }\n const headers = options.headers;\n for (const cookie of (headers?.get(\"cookie\") ?? \"\").split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator >= 0) {\n const value = cookie.slice(separator + 1).trim();\n add(value);\n if (value.startsWith('\"') && value.endsWith('\"')) {\n add(value.slice(1, -1));\n }\n }\n }\n const authorization = headers?.get(\"authorization\");\n if (authorization) {\n add(authorization);\n const credential = /^\\S+\\s+(.+)$/.exec(authorization)?.[1];\n if (credential) {\n add(credential);\n }\n }\n for (const name of options.credentialHeaders ?? []) {\n const value = headers?.get(name);\n if (value) {\n add(value);\n }\n }\n this.#secrets = [...values].sort(\n (left, right) => right.length - left.length,\n );\n }\n\n redact(cause: unknown): Error {\n return this.redactCause(cause, 0, new Set());\n }\n\n private replaceSecrets(value: string): string {\n for (const secret of this.#secrets) {\n value = value.split(secret).join(\"[REDACTED]\");\n }\n return value;\n }\n\n private diagnostic(value: string): string {\n return this.replaceSecrets(value)\n .split(/[\\r\\n]/, 1)[0]\n .slice(0, 300);\n }\n\n private redactCause(\n cause: unknown,\n depth: number,\n seen: Set<unknown>,\n ): Error {\n const message = readErrorProperty(cause, \"message\");\n const error = new Error(\n this.diagnostic(\n typeof message === \"string\"\n ? message\n : typeof cause === \"string\"\n ? cause\n : \"Unknown authentication infrastructure failure\",\n ),\n );\n const name = readErrorProperty(cause, \"name\");\n error.name = typeof name === \"string\" ? this.diagnostic(name) : \"Error\";\n for (const key of [\"code\", \"errno\", \"syscall\"] as const) {\n const value = readErrorProperty(cause, key);\n if (\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n Object.defineProperty(error, key, {\n value: typeof value === \"string\" ? this.diagnostic(value) : value,\n enumerable: true,\n });\n }\n }\n const stack = readErrorProperty(cause, \"stack\");\n const frames =\n typeof stack === \"string\"\n ? stack\n .split(/\\r?\\n/)\n .filter((line) => /^\\s+at .+:\\d+:\\d+\\)?$/.test(line))\n .map((line) => this.replaceSecrets(line))\n : [];\n error.stack = [`${error.name}: ${error.message}`, ...frames].join(\"\\n\");\n seen.add(cause);\n const nested = readErrorProperty(cause, \"cause\");\n if (nested !== undefined && depth < 3 && !seen.has(nested)) {\n Object.defineProperty(error, \"cause\", {\n value: this.redactCause(nested, depth + 1, seen),\n enumerable: false,\n });\n }\n return error;\n }\n}\n","import type { ExecutionContext } from \"@nestjs/common\";\nimport { isAPIError } from \"better-auth/api\";\nimport {\n ErrorRedactor,\n type ErrorRedactorOptions,\n readErrorProperty,\n} from \"./error-redactor.js\";\n\nconst FAILURE_BRAND = Symbol.for(\"@nestjs-kit/better-auth:auth-failure\");\nconst INFRASTRUCTURE_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:infrastructure-error\",\n);\nconst CONFIGURATION_BRAND = Symbol.for(\n \"@nestjs-kit/better-auth:configuration-error\",\n);\nconst RAW_CAUSE = Symbol.for(\"@nestjs-kit/better-auth:raw-cause\");\n/** Unredacted causes stay module-private; only an instance's exposeRawCause opt-in attaches one (RAW_CAUSE). */\nconst ORIGINAL_CAUSES = new WeakMap<object, unknown>();\nconst SDK_HEADERS = Symbol.for(\"better-call:api-error-headers\");\n\nexport type AuthErrorCode = \"UNAUTHENTICATED\" | \"FORBIDDEN\" | \"RATE_LIMITED\";\n\n/** A transport-neutral denial. Only transports make it throwable. */\nexport interface AuthFailure {\n readonly status: 401 | 403 | 429;\n readonly code: AuthErrorCode;\n readonly reason?: string;\n readonly message: string;\n readonly challenge?: string;\n readonly headers?: Headers;\n}\n\nexport interface AuthErrorBody {\n statusCode: 401 | 403 | 429;\n error: string;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface AuthGraphqlExtensions {\n code: AuthErrorCode | \"INTERNAL_SERVER_ERROR\";\n reason?: string;\n statusCode: number;\n}\n\nexport interface AuthTransportErrorPayload {\n status: \"error\";\n statusCode: number;\n code: AuthErrorCode;\n reason?: string;\n message: string;\n}\n\nexport interface ErrorMappingOptions {\n map?: (\n failure: AuthFailure,\n context: ExecutionContext,\n transport: string,\n ) => unknown;\n exposeRawCause?: boolean;\n}\n\nfunction branded<T extends object>(value: T, brand: symbol): T {\n Object.defineProperty(value, brand, { value: true });\n return value;\n}\n\nexport function isAuthFailure(value: unknown): value is AuthFailure {\n return readErrorProperty(value, FAILURE_BRAND) === true;\n}\n\nexport function isInfrastructureError(\n value: unknown,\n): value is BetterAuthInfrastructureError {\n return readErrorProperty(value, INFRASTRUCTURE_BRAND) === true;\n}\n\nexport function isConfigurationError(\n value: unknown,\n): value is BetterAuthConfigurationError {\n return readErrorProperty(value, CONFIGURATION_BRAND) === true;\n}\n\nfunction sdkStatus(error: unknown): number | undefined {\n try {\n if (!isAPIError(error)) {\n return undefined;\n }\n const status = readErrorProperty(error, \"statusCode\");\n return typeof status === \"number\" &&\n Number.isInteger(status) &&\n status >= 100 &&\n status <= 599\n ? status\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction sdkReason(error: unknown): string | undefined {\n const reason = readErrorProperty(readErrorProperty(error, \"body\"), \"code\");\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/** Internal: preserve cookie lines for the exchange's separately governed cleanup. */\nexport function getAPIErrorHeaders(error: unknown): Headers {\n const result = new Headers();\n for (const value of [\n readErrorProperty(error, SDK_HEADERS),\n readErrorProperty(error, \"headers\"),\n ]) {\n if (value === undefined || value === null) {\n continue;\n }\n try {\n const headers = new Headers(value as HeadersInit);\n for (const [name, value] of headers) {\n if (name !== \"set-cookie\") {\n result.set(name, value);\n }\n }\n for (const cookie of headers.getSetCookie()) {\n result.append(\"set-cookie\", cookie);\n }\n } catch {\n // A malformed optional header collection must not mask the original fault.\n }\n }\n return result;\n}\n\nfunction rejection(input: {\n status: 401 | 403 | 429;\n reason?: string;\n message?: string;\n challenge?: string;\n retryAfterSeconds?: number;\n}): AuthFailure {\n const codes = {\n 401: \"UNAUTHENTICATED\",\n 403: \"FORBIDDEN\",\n 429: \"RATE_LIMITED\",\n } as const;\n const messages = {\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 429: \"Too Many Requests\",\n } as const;\n const headers = new Headers();\n const retry = input.retryAfterSeconds;\n if (retry !== undefined && Number.isFinite(retry) && retry >= 0) {\n headers.set(\"retry-after\", String(Math.ceil(retry)));\n }\n return branded(\n {\n status: input.status,\n code: codes[input.status],\n reason: input.reason,\n message: input.message ?? messages[input.status],\n challenge: input.challenge,\n ...(headers.has(\"retry-after\") ? { headers } : {}),\n },\n FAILURE_BRAND,\n );\n}\n\nexport const AuthFailures = {\n unauthenticated(message?: string): AuthFailure {\n return rejection({ status: 401, message });\n },\n rejected: rejection,\n forbidden(reason: string, message?: string): AuthFailure {\n return rejection({ status: 403, reason, message });\n },\n fromAPIError(error: unknown): AuthFailure | null {\n const status = sdkStatus(error);\n if (status !== 401 && status !== 403 && status !== 429) {\n return null;\n }\n const originalHeaders = getAPIErrorHeaders(error);\n const details = readErrorProperty(\n readErrorProperty(error, \"body\"),\n \"details\",\n );\n const delay = readErrorProperty(details, \"tryAgainIn\");\n const failure = rejection({\n status,\n reason: sdkReason(error),\n challenge: originalHeaders.get(\"www-authenticate\") ?? undefined,\n retryAfterSeconds:\n status === 429 && typeof delay === \"number\" ? delay / 1000 : undefined,\n });\n const retryAfter = originalHeaders.get(\"retry-after\");\n if (retryAfter !== null) {\n const headers = new Headers(failure.headers);\n headers.set(\"retry-after\", retryAfter);\n return branded({ ...failure, headers }, FAILURE_BRAND);\n }\n return failure;\n },\n};\n\nexport class BetterAuthConfigurationError extends Error {\n readonly code: string;\n readonly detail: string;\n readonly site?: string;\n readonly hint?: string;\n readonly phase: \"boot\" | \"request\";\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_MISCONFIGURED\",\n statusCode: 500,\n } as const;\n readonly issues?: readonly BetterAuthConfigurationError[];\n\n constructor(code: string, detail: string, hint?: string) {\n super(detail);\n this.name = \"BetterAuthConfigurationError\";\n this.code = code;\n this.detail = detail;\n this.hint = hint;\n this.phase = \"boot\";\n branded(this, CONFIGURATION_BRAND);\n }\n\n static atRequest(\n code: string,\n detail: string,\n options?: { site?: string; hint?: string },\n ): BetterAuthConfigurationError {\n const error = new BetterAuthConfigurationError(\n code,\n \"Authentication is misconfigured\",\n options?.hint,\n );\n Object.defineProperties(error, {\n detail: { value: detail, enumerable: true },\n site: { value: options?.site, enumerable: true },\n phase: { value: \"request\", enumerable: true },\n });\n return error;\n }\n}\n\nexport class BetterAuthInfrastructureError extends Error {\n readonly cause: Error;\n readonly extensions = {\n code: \"INTERNAL_SERVER_ERROR\",\n reason: \"AUTH_UNAVAILABLE\",\n statusCode: 500,\n } as const;\n\n constructor(cause: unknown, options?: { secrets?: readonly string[] }) {\n super(\"Authentication service unavailable\");\n this.name = \"BetterAuthInfrastructureError\";\n this.cause = new ErrorRedactor(options).redact(cause);\n ORIGINAL_CAUSES.set(this, cause);\n branded(this, INFRASTRUCTURE_BRAND);\n }\n}\n\n/** Internal factory for an instance's explicit diagnostic opt-in, never global state. */\nexport function createInfrastructureError(\n cause: unknown,\n options?: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n // Preserve request-owned redaction inputs without widening the public constructor.\n const error = new BetterAuthInfrastructureError(cause, options);\n if (options?.exposeRawCause === true) {\n Object.defineProperty(error, RAW_CAUSE, {\n value: cause,\n enumerable: false,\n });\n }\n return error;\n}\n\n/**\n * Internal: the form of an already-classified infrastructure error that one request delivers. The request's cookie,\n * authorization and declared credential values are redacted on top of the thrower's own redaction, and the original\n * cause is attached only when the instance opts in, as for errors the kernel classifies itself.\n */\nexport function redactForRequest(\n error: BetterAuthInfrastructureError,\n options: ErrorRedactorOptions & { exposeRawCause?: boolean },\n): BetterAuthInfrastructureError {\n const original = ORIGINAL_CAUSES.has(error)\n ? ORIGINAL_CAUSES.get(error)\n : readErrorProperty(error, RAW_CAUSE);\n const delivered = new BetterAuthInfrastructureError(\n readErrorProperty(error, \"cause\"),\n options,\n );\n ORIGINAL_CAUSES.set(delivered, original);\n if (options.exposeRawCause === true && original !== undefined) {\n Object.defineProperty(delivered, RAW_CAUSE, {\n value: original,\n enumerable: false,\n });\n }\n return delivered;\n}\n\nexport function getRawCause(error: BetterAuthInfrastructureError): unknown {\n return readErrorProperty(error, RAW_CAUSE);\n}\n\n/** Internal: evaluation must distinguish session loss from a failed session read. */\nexport interface SessionLossCandidate {\n readonly sessionLoss: unknown;\n readonly reason?: string;\n}\n\n/** Internal safety net. Evaluation performs the authoritative session-loss recheck. */\nexport function normalizeThrown(\n error: unknown,\n where: \"source\" | \"policy\",\n site: string,\n secrets: readonly string[],\n options?: { exposeRawCause?: boolean },\n): AuthFailure | SessionLossCandidate {\n if (isAuthFailure(error)) {\n return error;\n }\n if (isInfrastructureError(error) || isConfigurationError(error)) {\n throw error;\n }\n const status = sdkStatus(error);\n const reason = sdkReason(error);\n if (status === 429) {\n return AuthFailures.fromAPIError(error)!;\n }\n if (\n status === 401 &&\n where === \"policy\" &&\n (reason === undefined || reason === \"UNAUTHORIZED\")\n ) {\n return { sessionLoss: error, reason };\n }\n if (status === 401 || status === 403) {\n return where === \"source\"\n ? AuthFailures.fromAPIError(error)!\n : AuthFailures.forbidden(reason ?? \"FORBIDDEN\");\n }\n if (status !== undefined && status < 500) {\n throw BetterAuthConfigurationError.atRequest(\n \"BETTER_AUTH_REJECTED_CALL\",\n `better-auth rejected the library's call (${status} ${reason})`,\n { site },\n );\n }\n throw createInfrastructureError(error, {\n secrets,\n exposeRawCause: options?.exposeRawCause,\n });\n}\n"],"mappings":";;;AAQA,SAAgB,kBAAkB,OAAgB,KAA2B;CAC3E,KACG,OAAO,UAAU,YAAY,UAAU,SACx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AAI,WAAW,KAAA,KAAa,SAAS,KACnC,MAAM,6BAA6B,UACjC,6BACA,4CAA4C,OAAO,GAAG,OAAO,IAC7D,EAAE,KAAK,CACT;CAEF,MAAM,0BAA0B,OAAO;EACrC;EACA,gBAAgB,SAAS;CAC3B,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
- import { c as isConfigurationError, l as isInfrastructureError, n as BetterAuthConfigurationError, s as isAuthFailure, t as AuthFailures } from "./auth-errors-C3rbTV9p.mjs";
2
- import { f as GUARD_CORE, n as __decorateParam, r as __decorateMetadata, s as AUTH_ENHANCER, t as __decorate } from "./decorate-Dt0e9K6R.mjs";
1
+ import { c as isConfigurationError, l as isInfrastructureError, n as BetterAuthConfigurationError, s as isAuthFailure, t as AuthFailures } from "./auth-errors-JjxGDVSt.mjs";
2
+ import { f as GUARD_CORE, n as __decorateParam, r as __decorateMetadata, s as AUTH_ENHANCER, t as __decorate } from "./decorate-bO-rBn-G.mjs";
3
3
  import { Inject, Injectable } from "@nestjs/common";
4
- //#region src/auth-guard.ts
4
+ // src/auth-guard.ts
5
5
  let BetterAuthGuard = class BetterAuthGuard {
6
6
  core;
7
7
  static [AUTH_ENHANCER] = "guard";
@@ -119,7 +119,6 @@ var GuardCore = class {
119
119
  }
120
120
  }
121
121
  };
122
- //#endregion
123
122
  export { GuardCore as n, BetterAuthGuard as t };
124
123
 
125
- //# sourceMappingURL=auth-guard-h9QB_l11.mjs.map
124
+ //# sourceMappingURL=auth-guard-Da92QEK5.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-guard-h9QB_l11.mjs","names":[],"sources":["../src/auth-guard.ts"],"sourcesContent":["import {\n Inject,\n Injectable,\n type CanActivate,\n type ExecutionContext,\n} from \"@nestjs/common\";\nimport type {\n AuthTransport,\n PrincipalResolver,\n RoutePlan,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport {\n AuthFailures,\n BetterAuthConfigurationError,\n isAuthFailure,\n isConfigurationError,\n isInfrastructureError,\n} from \"./auth-errors.js\";\nimport { AUTH_ENHANCER, GUARD_CORE } from \"./auth-tokens.js\";\nimport type { AuthorizationEvaluator } from \"./authorization-evaluator.js\";\nimport type { InstanceLookup } from \"./instance-registry.js\";\nimport type { PrincipalReadings } from \"./principal-readings.js\";\nimport type { RequestScope } from \"./request-scope.js\";\nimport type { RoutePlanner } from \"./route-planner.js\";\nimport type { TransportRegistry } from \"./transport-registry.js\";\n\n@Injectable()\nexport class BetterAuthGuard implements CanActivate {\n static readonly [AUTH_ENHANCER] = \"guard\";\n readonly [AUTH_ENHANCER] = \"guard\";\n\n constructor(\n @Inject(GUARD_CORE) private readonly core: Pick<GuardCore, \"canActivate\">,\n ) {}\n\n canActivate(context: ExecutionContext): Promise<boolean> {\n return this.core.canActivate(context);\n }\n}\nexport class GuardCore implements CanActivate {\n constructor(\n private readonly instances: InstanceLookup,\n private readonly planner: RoutePlanner,\n private readonly transports: TransportRegistry,\n private readonly resolver: PrincipalResolver,\n private readonly evaluator: AuthorizationEvaluator,\n private readonly scope: RequestScope,\n private readonly readings: PrincipalReadings,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n let transport: AuthTransport | undefined;\n let call: TransportCall | undefined;\n let plan: RoutePlan | undefined;\n try {\n plan = this.planner.forContext(context);\n if (plan.access === \"inherit\") {\n transport = this.transports.find(context);\n const lineage = transport?.lineage?.(context);\n if (lineage && !this.readings.enclosing(lineage, context.getArgs())) {\n call = this.transports.describe(context, transport);\n throw BetterAuthConfigurationError.atRequest(\n \"NO_ENCLOSING_DECISION\",\n \"An inherited invocation has no enclosing guard decision\",\n { site: plan.site },\n );\n }\n if (plan.originCheck !== \"form\") {\n return true;\n }\n }\n if (plan.access === \"public\" && plan.originCheck !== \"form\") {\n const lineage = this.transports.find(context)?.lineage?.(context);\n if (lineage && !plan.nested) {\n this.readings.recordLineage(lineage, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n transport = this.transports.select(context);\n call = this.transports.describe(context, transport);\n const entry = this.instances.get(plan.instance);\n if (plan.originCheck !== \"off\") {\n const browser = call.browser;\n if (browser) {\n if (plan.originCheck === \"form\" || browser.enforce) {\n const failure = await entry.origin.check(browser, plan.originCheck);\n if (failure) {\n throw failure;\n }\n } else {\n await entry.origin.advisory(browser);\n }\n }\n }\n if (plan.access === \"inherit\") {\n return true;\n }\n if (plan.access === \"public\") {\n if (!plan.nested) {\n this.readings.record(call, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n const result = await this.resolver.resolve(call, {\n auth: entry.handle,\n freshness: plan.freshness,\n accepts: plan.accepts,\n sourceSet: plan.sourceSet,\n });\n this.readings.record(call, { ...result, instance: plan.instance });\n if (result.outcome === \"rejected\") {\n throw result.failure;\n }\n if (result.outcome === \"absent\") {\n if (plan.access === \"optional\") {\n return true;\n }\n throw AuthFailures.unauthenticated();\n }\n if (!plan.accepts.has(result.principal.kind)) {\n throw AuthFailures.forbidden(\"PRINCIPAL_NOT_SUPPORTED\");\n }\n const decision = await this.evaluator.evaluate(\n plan,\n result.principal,\n call,\n entry,\n context,\n transport.id,\n );\n if (decision.effect === \"deny\") {\n throw AuthFailures.rejected({\n status: decision.status ?? 403,\n reason: decision.reason,\n message: decision.message,\n challenge: decision.challenge,\n });\n }\n return true;\n } catch (error) {\n if (isAuthFailure(error) && transport) {\n const mapping =\n plan && this.instances.get(plan.instance).options.errors?.map;\n throw mapping\n ? mapping(error, context, transport.id)\n : transport.toException(error, context);\n }\n if (\n (isConfigurationError(error) || isInfrastructureError(error)) &&\n transport\n ) {\n const repeated = call\n ? this.scope.surfaced(call.key, error, {\n instance: plan?.instance ?? \"default\",\n site: plan?.site ?? \"guard\",\n lineage: call.lineage,\n })\n : false;\n throw (\n transport.toInternalException?.(error, context, { repeated }) ?? error\n );\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;AA4BO,IAAM,kBAAN,MAAM,gBAAuC;CAKX;CAJvC,QAAiB,iBAAiB;CAClC,CAAU,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AM,UACF,QAAQ,OAAO,SAAS,UAAU,EAAE,IACpC,UAAU,YAAY,OAAO,OAAO;GAC1C;GACA,KACG,qBAAqB,KAAK,KAAK,sBAAsB,KAAK,MAC3D,WACA;IACA,MAAM,WAAW,OACb,KAAK,MAAM,SAAS,KAAK,KAAK,OAAO;KACnC,UAAU,MAAM,YAAY;KAC5B,MAAM,MAAM,QAAQ;KACpB,SAAS,KAAK;IAChB,CAAC,IACD;IACJ,MACE,UAAU,sBAAsB,OAAO,SAAS,EAAE,SAAS,CAAC,KAAK;GAErE;GACA,MAAM;EACR;CACF;AACF"}
1
+ {"version":3,"file":"auth-guard-Da92QEK5.mjs","names":[],"sources":["../src/auth-guard.ts"],"sourcesContent":["import {\n Inject,\n Injectable,\n type CanActivate,\n type ExecutionContext,\n} from \"@nestjs/common\";\nimport type {\n AuthTransport,\n PrincipalResolver,\n RoutePlan,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport {\n AuthFailures,\n BetterAuthConfigurationError,\n isAuthFailure,\n isConfigurationError,\n isInfrastructureError,\n} from \"./auth-errors.js\";\nimport { AUTH_ENHANCER, GUARD_CORE } from \"./auth-tokens.js\";\nimport type { AuthorizationEvaluator } from \"./authorization-evaluator.js\";\nimport type { InstanceLookup } from \"./instance-registry.js\";\nimport type { PrincipalReadings } from \"./principal-readings.js\";\nimport type { RequestScope } from \"./request-scope.js\";\nimport type { RoutePlanner } from \"./route-planner.js\";\nimport type { TransportRegistry } from \"./transport-registry.js\";\n\n@Injectable()\nexport class BetterAuthGuard implements CanActivate {\n static readonly [AUTH_ENHANCER] = \"guard\";\n readonly [AUTH_ENHANCER] = \"guard\";\n\n constructor(\n @Inject(GUARD_CORE) private readonly core: Pick<GuardCore, \"canActivate\">,\n ) {}\n\n canActivate(context: ExecutionContext): Promise<boolean> {\n return this.core.canActivate(context);\n }\n}\nexport class GuardCore implements CanActivate {\n constructor(\n private readonly instances: InstanceLookup,\n private readonly planner: RoutePlanner,\n private readonly transports: TransportRegistry,\n private readonly resolver: PrincipalResolver,\n private readonly evaluator: AuthorizationEvaluator,\n private readonly scope: RequestScope,\n private readonly readings: PrincipalReadings,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n let transport: AuthTransport | undefined;\n let call: TransportCall | undefined;\n let plan: RoutePlan | undefined;\n try {\n plan = this.planner.forContext(context);\n if (plan.access === \"inherit\") {\n transport = this.transports.find(context);\n const lineage = transport?.lineage?.(context);\n if (lineage && !this.readings.enclosing(lineage, context.getArgs())) {\n call = this.transports.describe(context, transport);\n throw BetterAuthConfigurationError.atRequest(\n \"NO_ENCLOSING_DECISION\",\n \"An inherited invocation has no enclosing guard decision\",\n { site: plan.site },\n );\n }\n if (plan.originCheck !== \"form\") {\n return true;\n }\n }\n if (plan.access === \"public\" && plan.originCheck !== \"form\") {\n const lineage = this.transports.find(context)?.lineage?.(context);\n if (lineage && !plan.nested) {\n this.readings.recordLineage(lineage, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n transport = this.transports.select(context);\n call = this.transports.describe(context, transport);\n const entry = this.instances.get(plan.instance);\n if (plan.originCheck !== \"off\") {\n const browser = call.browser;\n if (browser) {\n if (plan.originCheck === \"form\" || browser.enforce) {\n const failure = await entry.origin.check(browser, plan.originCheck);\n if (failure) {\n throw failure;\n }\n } else {\n await entry.origin.advisory(browser);\n }\n }\n }\n if (plan.access === \"inherit\") {\n return true;\n }\n if (plan.access === \"public\") {\n if (!plan.nested) {\n this.readings.record(call, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n const result = await this.resolver.resolve(call, {\n auth: entry.handle,\n freshness: plan.freshness,\n accepts: plan.accepts,\n sourceSet: plan.sourceSet,\n });\n this.readings.record(call, { ...result, instance: plan.instance });\n if (result.outcome === \"rejected\") {\n throw result.failure;\n }\n if (result.outcome === \"absent\") {\n if (plan.access === \"optional\") {\n return true;\n }\n throw AuthFailures.unauthenticated();\n }\n if (!plan.accepts.has(result.principal.kind)) {\n throw AuthFailures.forbidden(\"PRINCIPAL_NOT_SUPPORTED\");\n }\n const decision = await this.evaluator.evaluate(\n plan,\n result.principal,\n call,\n entry,\n context,\n transport.id,\n );\n if (decision.effect === \"deny\") {\n throw AuthFailures.rejected({\n status: decision.status ?? 403,\n reason: decision.reason,\n message: decision.message,\n challenge: decision.challenge,\n });\n }\n return true;\n } catch (error) {\n if (isAuthFailure(error) && transport) {\n const mapping =\n plan && this.instances.get(plan.instance).options.errors?.map;\n throw mapping\n ? mapping(error, context, transport.id)\n : transport.toException(error, context);\n }\n if (\n (isConfigurationError(error) || isInfrastructureError(error)) &&\n transport\n ) {\n const repeated = call\n ? this.scope.surfaced(call.key, error, {\n instance: plan?.instance ?? \"default\",\n site: plan?.site ?? \"guard\",\n lineage: call.lineage,\n })\n : false;\n throw (\n transport.toInternalException?.(error, context, { repeated }) ?? error\n );\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;AA4BO,IAAM,kBAAN,MAAM,gBAAuC;CAKX;CAJvC,QAAiB,iBAAiB;CAClC,CAAU,iBAAiB;CAE3B,YACE,MACA;EADqC,KAAA,OAAA;CACpC;CAEH,YAAY,SAA6C;EACvD,OAAO,KAAK,KAAK,YAAY,OAAO;CACtC;AACF;;CAZC,WAAW;CAMP,gBAAA,GAAA,OAAO,UAAU,CAAA;;;AAOtB,IAAa,YAAb,MAA8C;CAEzB;CACA;CACA;CACA;CACA;CACA;CACA;CAPnB,YACE,WACA,SACA,YACA,UACA,WACA,OACA,UACA;EAPiB,KAAA,YAAA;EACA,KAAA,UAAA;EACA,KAAA,aAAA;EACA,KAAA,WAAA;EACA,KAAA,YAAA;EACA,KAAA,QAAA;EACA,KAAA,WAAA;CAChB;CAEH,MAAM,YAAY,SAA6C;EAC7D,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,OAAO,KAAK,QAAQ,WAAW,OAAO;GACtC,IAAI,KAAK,WAAW,WAAW;IAC7B,YAAY,KAAK,WAAW,KAA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MAAM;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACjE,IAAI,OAAO,YAAY,YACrB,MAAM,OAAO;GAEf,IAAI,OAAO,YAAY,UAAU;IAC/B,IAAI,KAAK,WAAW,YAClB,OAAO;IAET,MAAM,aAAa,gBAAgB;GACrC;GACA,IAAI,CAAC,KAAK,QAAQ,IAAI,OAAO,UAAU,IAAI,GACzC,MAAM,aAAa,UAAU,yBAAyB;GAExD,MAAM,WAAW,MAAM,KAAK,UAAU,SACpC,MACA,OAAO,WACP,MACA,OACA,SACA,UAAU,EACZ;GACA,IAAI,SAAS,WAAW,QACtB,MAAM,aAAa,SAAS;IAC1B,QAAQ,SAAS,UAAU;IAC3B,QAAQ,SAAS;IACjB,SAAS,SAAS;IAClB,WAAW,SAAS;GACtB,CAAC;GAEH,OAAO;EACT,SAAS,OAAO;GACd,IAAI,cAAc,KAAK,KAAK,WAAW;IACrC,MAAM,UACJ,QAAQ,KAAK,UAAU,IAAI,KAAK,QAAQ,CAAC,CAAC,QAAQ,QAAQ;IAC5D,MAAM,UACF,QAAQ,OAAO,SAAS,UAAU,EAAE,IACpC,UAAU,YAAY,OAAO,OAAO;GAC1C;GACA,KACG,qBAAqB,KAAK,KAAK,sBAAsB,KAAK,MAC3D,WACA;IACA,MAAM,WAAW,OACb,KAAK,MAAM,SAAS,KAAK,KAAK,OAAO;KACnC,UAAU,MAAM,YAAY;KAC5B,MAAM,MAAM,QAAQ;KACpB,SAAS,KAAK;IAChB,CAAC,IACD;IACJ,MACE,UAAU,sBAAsB,OAAO,SAAS,EAAE,SAAS,CAAC,KAAK;GAErE;GACA,MAAM;EACR;CACF;AACF"}
@@ -1,7 +1,7 @@
1
- const require_auth_errors = require("./auth-errors-DmiKl0L_.cjs");
2
- const require_decorate = require("./decorate-Cr4Q7bNE.cjs");
1
+ const require_auth_errors = require("./auth-errors-RW7hOVI-.cjs");
2
+ const require_decorate = require("./decorate-fMNf0caZ.cjs");
3
3
  let _nestjs_common = require("@nestjs/common");
4
- //#region src/auth-guard.ts
4
+ // src/auth-guard.ts
5
5
  let BetterAuthGuard = class BetterAuthGuard {
6
6
  core;
7
7
  static [require_decorate.AUTH_ENHANCER] = "guard";
@@ -119,7 +119,6 @@ var GuardCore = class {
119
119
  }
120
120
  }
121
121
  };
122
- //#endregion
123
122
  Object.defineProperty(exports, "BetterAuthGuard", {
124
123
  enumerable: true,
125
124
  get: function() {
@@ -133,4 +132,4 @@ Object.defineProperty(exports, "GuardCore", {
133
132
  }
134
133
  });
135
134
 
136
- //# sourceMappingURL=auth-guard-CLyhAEEj.cjs.map
135
+ //# sourceMappingURL=auth-guard-wapEh_M_.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-guard-CLyhAEEj.cjs","names":["AUTH_ENHANCER","Injectable","Inject","GUARD_CORE","BetterAuthConfigurationError","AuthFailures","isAuthFailure","isConfigurationError","isInfrastructureError"],"sources":["../src/auth-guard.ts"],"sourcesContent":["import {\n Inject,\n Injectable,\n type CanActivate,\n type ExecutionContext,\n} from \"@nestjs/common\";\nimport type {\n AuthTransport,\n PrincipalResolver,\n RoutePlan,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport {\n AuthFailures,\n BetterAuthConfigurationError,\n isAuthFailure,\n isConfigurationError,\n isInfrastructureError,\n} from \"./auth-errors.js\";\nimport { AUTH_ENHANCER, GUARD_CORE } from \"./auth-tokens.js\";\nimport type { AuthorizationEvaluator } from \"./authorization-evaluator.js\";\nimport type { InstanceLookup } from \"./instance-registry.js\";\nimport type { PrincipalReadings } from \"./principal-readings.js\";\nimport type { RequestScope } from \"./request-scope.js\";\nimport type { RoutePlanner } from \"./route-planner.js\";\nimport type { TransportRegistry } from \"./transport-registry.js\";\n\n@Injectable()\nexport class BetterAuthGuard implements CanActivate {\n static readonly [AUTH_ENHANCER] = \"guard\";\n readonly [AUTH_ENHANCER] = \"guard\";\n\n constructor(\n @Inject(GUARD_CORE) private readonly core: Pick<GuardCore, \"canActivate\">,\n ) {}\n\n canActivate(context: ExecutionContext): Promise<boolean> {\n return this.core.canActivate(context);\n }\n}\nexport class GuardCore implements CanActivate {\n constructor(\n private readonly instances: InstanceLookup,\n private readonly planner: RoutePlanner,\n private readonly transports: TransportRegistry,\n private readonly resolver: PrincipalResolver,\n private readonly evaluator: AuthorizationEvaluator,\n private readonly scope: RequestScope,\n private readonly readings: PrincipalReadings,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n let transport: AuthTransport | undefined;\n let call: TransportCall | undefined;\n let plan: RoutePlan | undefined;\n try {\n plan = this.planner.forContext(context);\n if (plan.access === \"inherit\") {\n transport = this.transports.find(context);\n const lineage = transport?.lineage?.(context);\n if (lineage && !this.readings.enclosing(lineage, context.getArgs())) {\n call = this.transports.describe(context, transport);\n throw BetterAuthConfigurationError.atRequest(\n \"NO_ENCLOSING_DECISION\",\n \"An inherited invocation has no enclosing guard decision\",\n { site: plan.site },\n );\n }\n if (plan.originCheck !== \"form\") {\n return true;\n }\n }\n if (plan.access === \"public\" && plan.originCheck !== \"form\") {\n const lineage = this.transports.find(context)?.lineage?.(context);\n if (lineage && !plan.nested) {\n this.readings.recordLineage(lineage, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n transport = this.transports.select(context);\n call = this.transports.describe(context, transport);\n const entry = this.instances.get(plan.instance);\n if (plan.originCheck !== \"off\") {\n const browser = call.browser;\n if (browser) {\n if (plan.originCheck === \"form\" || browser.enforce) {\n const failure = await entry.origin.check(browser, plan.originCheck);\n if (failure) {\n throw failure;\n }\n } else {\n await entry.origin.advisory(browser);\n }\n }\n }\n if (plan.access === \"inherit\") {\n return true;\n }\n if (plan.access === \"public\") {\n if (!plan.nested) {\n this.readings.record(call, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n const result = await this.resolver.resolve(call, {\n auth: entry.handle,\n freshness: plan.freshness,\n accepts: plan.accepts,\n sourceSet: plan.sourceSet,\n });\n this.readings.record(call, { ...result, instance: plan.instance });\n if (result.outcome === \"rejected\") {\n throw result.failure;\n }\n if (result.outcome === \"absent\") {\n if (plan.access === \"optional\") {\n return true;\n }\n throw AuthFailures.unauthenticated();\n }\n if (!plan.accepts.has(result.principal.kind)) {\n throw AuthFailures.forbidden(\"PRINCIPAL_NOT_SUPPORTED\");\n }\n const decision = await this.evaluator.evaluate(\n plan,\n result.principal,\n call,\n entry,\n context,\n transport.id,\n );\n if (decision.effect === \"deny\") {\n throw AuthFailures.rejected({\n status: decision.status ?? 403,\n reason: decision.reason,\n message: decision.message,\n challenge: decision.challenge,\n });\n }\n return true;\n } catch (error) {\n if (isAuthFailure(error) && transport) {\n const mapping =\n plan && this.instances.get(plan.instance).options.errors?.map;\n throw mapping\n ? mapping(error, context, transport.id)\n : transport.toException(error, context);\n }\n if (\n (isConfigurationError(error) || isInfrastructureError(error)) &&\n transport\n ) {\n const repeated = call\n ? this.scope.surfaced(call.key, error, {\n instance: plan?.instance ?? \"default\",\n site: plan?.site ?? \"guard\",\n lineage: call.lineage,\n })\n : false;\n throw (\n transport.toInternalException?.(error, context, { repeated }) ?? error\n );\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;AA4BO,IAAM,kBAAN,MAAM,gBAAuC;CAKX;CAJvC,QAAiBA,iBAAAA,iBAAiB;CAClC,CAAUA,iBAAAA,iBAAiB;CAE3B,YACE,MACA;EADqC,KAAA,OAAA;CACpC;CAEH,YAAY,SAA6C;EACvD,OAAO,KAAK,KAAK,YAAY,OAAO;CACtC;AACF;;EAZCC,GAAAA,eAAAA,WAAAA,CAAW;CAMPC,iBAAAA,gBAAAA,IAAAA,GAAAA,eAAAA,OAAAA,CAAOC,iBAAAA,UAAU,CAAA;;;AAOtB,IAAa,YAAb,MAA8C;CAEzB;CACA;CACA;CACA;CACA;CACA;CACA;CAPnB,YACE,WACA,SACA,YACA,UACA,WACA,OACA,UACA;EAPiB,KAAA,YAAA;EACA,KAAA,UAAA;EACA,KAAA,aAAA;EACA,KA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C,IACD;IACJ,MACE,UAAU,sBAAsB,OAAO,SAAS,EAAE,SAAS,CAAC,KAAK;GAErE;GACA,MAAM;EACR;CACF;AACF"}
1
+ {"version":3,"file":"auth-guard-wapEh_M_.cjs","names":["AUTH_ENHANCER","Injectable","Inject","GUARD_CORE","BetterAuthConfigurationError","AuthFailures","isAuthFailure","isConfigurationError","isInfrastructureError"],"sources":["../src/auth-guard.ts"],"sourcesContent":["import {\n Inject,\n Injectable,\n type CanActivate,\n type ExecutionContext,\n} from \"@nestjs/common\";\nimport type {\n AuthTransport,\n PrincipalResolver,\n RoutePlan,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport {\n AuthFailures,\n BetterAuthConfigurationError,\n isAuthFailure,\n isConfigurationError,\n isInfrastructureError,\n} from \"./auth-errors.js\";\nimport { AUTH_ENHANCER, GUARD_CORE } from \"./auth-tokens.js\";\nimport type { AuthorizationEvaluator } from \"./authorization-evaluator.js\";\nimport type { InstanceLookup } from \"./instance-registry.js\";\nimport type { PrincipalReadings } from \"./principal-readings.js\";\nimport type { RequestScope } from \"./request-scope.js\";\nimport type { RoutePlanner } from \"./route-planner.js\";\nimport type { TransportRegistry } from \"./transport-registry.js\";\n\n@Injectable()\nexport class BetterAuthGuard implements CanActivate {\n static readonly [AUTH_ENHANCER] = \"guard\";\n readonly [AUTH_ENHANCER] = \"guard\";\n\n constructor(\n @Inject(GUARD_CORE) private readonly core: Pick<GuardCore, \"canActivate\">,\n ) {}\n\n canActivate(context: ExecutionContext): Promise<boolean> {\n return this.core.canActivate(context);\n }\n}\nexport class GuardCore implements CanActivate {\n constructor(\n private readonly instances: InstanceLookup,\n private readonly planner: RoutePlanner,\n private readonly transports: TransportRegistry,\n private readonly resolver: PrincipalResolver,\n private readonly evaluator: AuthorizationEvaluator,\n private readonly scope: RequestScope,\n private readonly readings: PrincipalReadings,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n let transport: AuthTransport | undefined;\n let call: TransportCall | undefined;\n let plan: RoutePlan | undefined;\n try {\n plan = this.planner.forContext(context);\n if (plan.access === \"inherit\") {\n transport = this.transports.find(context);\n const lineage = transport?.lineage?.(context);\n if (lineage && !this.readings.enclosing(lineage, context.getArgs())) {\n call = this.transports.describe(context, transport);\n throw BetterAuthConfigurationError.atRequest(\n \"NO_ENCLOSING_DECISION\",\n \"An inherited invocation has no enclosing guard decision\",\n { site: plan.site },\n );\n }\n if (plan.originCheck !== \"form\") {\n return true;\n }\n }\n if (plan.access === \"public\" && plan.originCheck !== \"form\") {\n const lineage = this.transports.find(context)?.lineage?.(context);\n if (lineage && !plan.nested) {\n this.readings.recordLineage(lineage, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n transport = this.transports.select(context);\n call = this.transports.describe(context, transport);\n const entry = this.instances.get(plan.instance);\n if (plan.originCheck !== \"off\") {\n const browser = call.browser;\n if (browser) {\n if (plan.originCheck === \"form\" || browser.enforce) {\n const failure = await entry.origin.check(browser, plan.originCheck);\n if (failure) {\n throw failure;\n }\n } else {\n await entry.origin.advisory(browser);\n }\n }\n }\n if (plan.access === \"inherit\") {\n return true;\n }\n if (plan.access === \"public\") {\n if (!plan.nested) {\n this.readings.record(call, {\n outcome: \"no-identity\",\n instance: plan.instance,\n });\n }\n return true;\n }\n const result = await this.resolver.resolve(call, {\n auth: entry.handle,\n freshness: plan.freshness,\n accepts: plan.accepts,\n sourceSet: plan.sourceSet,\n });\n this.readings.record(call, { ...result, instance: plan.instance });\n if (result.outcome === \"rejected\") {\n throw result.failure;\n }\n if (result.outcome === \"absent\") {\n if (plan.access === \"optional\") {\n return true;\n }\n throw AuthFailures.unauthenticated();\n }\n if (!plan.accepts.has(result.principal.kind)) {\n throw AuthFailures.forbidden(\"PRINCIPAL_NOT_SUPPORTED\");\n }\n const decision = await this.evaluator.evaluate(\n plan,\n result.principal,\n call,\n entry,\n context,\n transport.id,\n );\n if (decision.effect === \"deny\") {\n throw AuthFailures.rejected({\n status: decision.status ?? 403,\n reason: decision.reason,\n message: decision.message,\n challenge: decision.challenge,\n });\n }\n return true;\n } catch (error) {\n if (isAuthFailure(error) && transport) {\n const mapping =\n plan && this.instances.get(plan.instance).options.errors?.map;\n throw mapping\n ? mapping(error, context, transport.id)\n : transport.toException(error, context);\n }\n if (\n (isConfigurationError(error) || isInfrastructureError(error)) &&\n transport\n ) {\n const repeated = call\n ? this.scope.surfaced(call.key, error, {\n instance: plan?.instance ?? \"default\",\n site: plan?.site ?? \"guard\",\n lineage: call.lineage,\n })\n : false;\n throw (\n transport.toInternalException?.(error, context, { repeated }) ?? error\n );\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;AA4BO,IAAM,kBAAN,MAAM,gBAAuC;CAKX;CAJvC,QAAiBA,iBAAAA,iBAAiB;CAClC,CAAUA,iBAAAA,iBAAiB;CAE3B,YACE,MACA;EADqC,KAAA,OAAA;CACpC;CAEH,YAAY,SAA6C;EACvD,OAAO,KAAK,KAAK,YAAY,OAAO;CACtC;AACF;;EAZCC,GAAAA,eAAAA,WAAAA,CAAW;CAMPC,iBAAAA,gBAAAA,IAAAA,GAAAA,eAAAA,OAAAA,CAAOC,iBAAAA,UAAU,CAAA;;;AAOtB,IAAa,YAAb,MAA8C;CAEzB;CACA;CACA;CACA;CACA;CACA;CACA;CAPnB,YACE,WACA,SACA,YACA,UACA,WACA,OACA,UACA;EAPiB,KAAA,YAAA;EACA,KAAA,UAAA;EACA,KAAA,aAAA;EACA,KAAA,WAAA;EACA,KAAA,YAAA;EACA,KAAA,QAAA;EACA,KAAA,WAAA;CAChB;CAEH,MAAM,YAAY,SAA6C;EAC7D,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,OAAO,KAAK,QAAQ,WAAW,OAAO;GACtC,IAAI,KAAK,WAAW,WAAW;IAC7B,YAAY,KAAK,WAAW,KAAK,OAAO;IACxC,MAAM,UAAU,WAAW,UAAU,OAAO;IAC5C,IAAI,WAAW,CAAC,KAAK,SAAS,UAAU,SAAS,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,OAAO;GAEf,IAAI,OAAO,YAAY,UAAU;IAC/B,IAAI,KAAK,WAAW,YAClB,OAAO;IAET,MAAMC,oBAAAA,aAAa,gBAAgB;GACrC;GACA,IAAI,CAAC,KAAK,QAAQ,IAAI,OAAO,UAAU,IAAI,GACzC,MAAMA,oBAAAA,aAAa,UAAU,yBAAyB;GAExD,MAAM,WAAW,MAAM,KAAK,UAAU,SACpC,MACA,OAAO,WACP,MACA,OACA,SACA,UAAU,EACZ;GACA,IAAI,SAAS,WAAW,QACtB,MAAMA,oBAAAA,aAAa,SAAS;IAC1B,QAAQ,SAAS,UAAU;IAC3B,QAAQ,SAAS;IACjB,SAAS,SAAS;IAClB,WAAW,SAAS;GACtB,CAAC;GAEH,OAAO;EACT,SAAS,OAAO;GACd,IAAIC,oBAAAA,cAAc,KAAK,KAAK,WAAW;IACrC,MAAM,UACJ,QAAQ,KAAK,UAAU,IAAI,KAAK,QAAQ,CAAC,CAAC,QAAQ,QAAQ;IAC5D,MAAM,UACF,QAAQ,OAAO,SAAS,UAAU,EAAE,IACpC,UAAU,YAAY,OAAO,OAAO;GAC1C;GACA,KACGC,oBAAAA,qBAAqB,KAAK,KAAKC,oBAAAA,sBAAsB,KAAK,MAC3D,WACA;IACA,MAAM,WAAW,OACb,KAAK,MAAM,SAAS,KAAK,KAAK,OAAO;KACnC,UAAU,MAAM,YAAY;KAC5B,MAAM,MAAM,QAAQ;KACpB,SAAS,KAAK;IAChB,CAAC,IACD;IACJ,MACE,UAAU,sBAAsB,OAAO,SAAS,EAAE,SAAS,CAAC,KAAK;GAErE;GACA,MAAM;EACR;CACF;AACF"}
@@ -1,15 +1,15 @@
1
- const require_auth_errors = require("./auth-errors-DmiKl0L_.cjs");
2
- const require_decorate = require("./decorate-Cr4Q7bNE.cjs");
3
- const require_auth_scope_interceptor = require("./auth-scope-interceptor-BjxAL1-S.cjs");
4
- const require_auth_guard = require("./auth-guard-CLyhAEEj.cjs");
5
- const require_bridge_protocol = require("./bridge-protocol-BDw8opAG.cjs");
6
- const require_auth_decorators = require("./auth-decorators-Cu_nxWnF.cjs");
7
- const require_principal_readings = require("./principal-readings-Chmt6rQV.cjs");
8
- const require_platform = require("./platform-YICqqYv6.cjs");
1
+ const require_auth_errors = require("./auth-errors-RW7hOVI-.cjs");
2
+ const require_decorate = require("./decorate-fMNf0caZ.cjs");
3
+ const require_auth_scope_interceptor = require("./auth-scope-interceptor-Bui20-Ps.cjs");
4
+ const require_auth_guard = require("./auth-guard-wapEh_M_.cjs");
5
+ const require_bridge_protocol = require("./bridge-protocol-DNFhIKdo.cjs");
6
+ const require_auth_decorators = require("./auth-decorators-CJKE9wlT.cjs");
7
+ const require_platform = require("./platform-C67dxSls.cjs");
8
+ const require_principal_readings = require("./principal-readings-JLNT58k0.cjs");
9
9
  let better_auth_api = require("better-auth/api");
10
10
  let _nestjs_common = require("@nestjs/common");
11
11
  let _nestjs_core = require("@nestjs/core");
12
- //#region src/route-planner.ts
12
+ // src/route-planner.ts
13
13
  function classes(target) {
14
14
  const result = [];
15
15
  for (let current = target; current && current !== Function.prototype; current = Object.getPrototypeOf(current)) result.push(current);
@@ -191,8 +191,7 @@ var RoutePlanner = class {
191
191
  function intersection(sets, universe) {
192
192
  return new Set([...universe].filter((kind) => sets.every((set) => set.has(kind))));
193
193
  }
194
- //#endregion
195
- //#region src/authorization-evaluator.ts
194
+ // src/authorization-evaluator.ts
196
195
  const allow = () => ({ effect: "allow" });
197
196
  const deny = (input) => ({
198
197
  effect: "deny",
@@ -356,8 +355,7 @@ var AuthorizationEvaluator = class {
356
355
  return allow();
357
356
  }
358
357
  };
359
- //#endregion
360
- //#region src/trusted-origins.ts
358
+ // src/trusted-origins.ts
361
359
  /** Auth route path exceptions never exempt application operations. */
362
360
  function originChecksDisabled(context) {
363
361
  return context.skipCSRFCheck || context.skipOriginCheck === true && context.options.advanced?.disableCSRFCheck === void 0;
@@ -438,8 +436,7 @@ var TrustedOrigins = class {
438
436
  return context.isTrustedOrigin.call({ trustedOrigins }, origin, { allowRelativePaths: false });
439
437
  }
440
438
  };
441
- //#endregion
442
- //#region src/bridge-client.ts
439
+ // src/bridge-client.ts
443
440
  /** Preserve capabilities lazily; spreading a ScopeView can extract credentials. */
444
441
  function derivedScope(scope, init) {
445
442
  const outer = scope.current();
@@ -522,8 +519,7 @@ var BridgeClient = class {
522
519
  this.#registrations.length = 0;
523
520
  }
524
521
  };
525
- //#endregion
526
- //#region src/origin-check.ts
522
+ // src/origin-check.ts
527
523
  const ORIGIN_PROOF = Symbol.for("@nestjs-kit/better-auth:origin-proof");
528
524
  const ORIGIN_CALCULATION_FAILURES = Symbol.for("@nestjs-kit/better-auth:origin-calculation-failures");
529
525
  function diagnosticOrigin(headers) {
@@ -668,8 +664,7 @@ var OriginCheck = class {
668
664
  return this.init.context.isTrustedOrigin.call({ trustedOrigins }, value, { allowRelativePaths: false }) ? null : require_auth_errors.AuthFailures.forbidden("INVALID_ORIGIN");
669
665
  }
670
666
  };
671
- //#endregion
672
- //#region src/instance-registry.ts
667
+ // src/instance-registry.ts
673
668
  /** Nest considers transient providers static; auth collaborators require singleton trees. */
674
669
  function isSingletonDependencyTree(root) {
675
670
  const pending = [root];
@@ -812,8 +807,7 @@ let InstanceRegistry = class InstanceRegistry {
812
807
  }
813
808
  };
814
809
  InstanceRegistry = require_decorate.__decorate([require_decorate.__decorateParam(0, (0, _nestjs_common.Inject)(require_decorate.REQUEST_SCOPE)), require_decorate.__decorateMetadata("design:paramtypes", [Object])], InstanceRegistry);
815
- //#endregion
816
- //#region src/route-paths.ts
810
+ // src/route-paths.ts
817
811
  function addLeadingSlash(path) {
818
812
  if (typeof path !== "string" || path === "") return "";
819
813
  return path.startsWith("/") || path.startsWith("{/") ? path : `/${path}`;
@@ -868,8 +862,7 @@ function composeRoutePaths(input, requestMethod, exclusions) {
868
862
  }
869
863
  return paths.map((path) => addLeadingSlash(path || "/")).map((path) => path === "/" ? path : stripEndSlash(path));
870
864
  }
871
- //#endregion
872
- //#region src/boot-validator.ts
865
+ // src/boot-validator.ts
873
866
  function requirementLeaves(expressions) {
874
867
  return expressions.flatMap((expression) => "anyOf" in expression ? requirementLeaves(expression.anyOf) : "allOf" in expression ? requirementLeaves(expression.allOf) : [expression]);
875
868
  }
@@ -1372,8 +1365,7 @@ BootValidator = require_decorate.__decorate([
1372
1365
  require_decorate.__decorateParam(8, (0, _nestjs_common.Inject)(require_decorate.TRANSPORT_REGISTRY)),
1373
1366
  require_decorate.__decorateParam(9, (0, _nestjs_common.Inject)(require_decorate.MOUNT_COORDINATOR))
1374
1367
  ], BootValidator);
1375
- //#endregion
1376
- //#region src/hook-binder.ts
1368
+ // src/hook-binder.ts
1377
1369
  const DATABASE_TARGETS = [
1378
1370
  "user",
1379
1371
  "session",
@@ -1512,8 +1504,7 @@ HookBinder = require_decorate.__decorate([
1512
1504
  require_decorate.__decorateParam(1, (0, _nestjs_common.Inject)(_nestjs_core.MetadataScanner)),
1513
1505
  require_decorate.__decorateMetadata("design:paramtypes", [typeof _nestjs_core.DiscoveryService === "undefined" ? Object : _nestjs_core.DiscoveryService, typeof _nestjs_core.MetadataScanner === "undefined" ? Object : _nestjs_core.MetadataScanner])
1514
1506
  ], HookBinder);
1515
- //#endregion
1516
- //#region src/auth-exchange.ts
1507
+ // src/auth-exchange.ts
1517
1508
  const HOP_HEADERS = [
1518
1509
  "connection",
1519
1510
  "keep-alive",
@@ -1710,8 +1701,7 @@ function betterAuthCorsOrigin(auth, options) {
1710
1701
  })().then((allow) => callback(null, allow), (error) => callback(error instanceof Error ? error : /* @__PURE__ */ new Error("Failed to resolve trusted CORS origins")));
1711
1702
  };
1712
1703
  }
1713
- //#endregion
1714
- //#region src/mount-coordinator.ts
1704
+ // src/mount-coordinator.ts
1715
1705
  const MOUNTED = Symbol.for("@nestjs-kit/better-auth:mounted");
1716
1706
  function parseBodyLimit(input) {
1717
1707
  if (input === void 0) return 1048576;
@@ -1861,8 +1851,7 @@ MountCoordinator = require_decorate.__decorate([
1861
1851
  Object
1862
1852
  ])
1863
1853
  ], MountCoordinator);
1864
- //#endregion
1865
- //#region src/policy-resolver.ts
1854
+ // src/policy-resolver.ts
1866
1855
  var PolicyResolver = class {
1867
1856
  moduleRef;
1868
1857
  cache = /* @__PURE__ */ new Map();
@@ -1883,8 +1872,7 @@ var PolicyResolver = class {
1883
1872
  return policy;
1884
1873
  }
1885
1874
  };
1886
- //#endregion
1887
- //#region src/transport-registry.ts
1875
+ // src/transport-registry.ts
1888
1876
  var TransportRegistry = class {
1889
1877
  transports = [];
1890
1878
  owners = /* @__PURE__ */ new WeakMap();
@@ -1921,8 +1909,7 @@ var TransportRegistry = class {
1921
1909
  return call;
1922
1910
  }
1923
1911
  };
1924
- //#endregion
1925
- //#region src/auth-core-module.ts
1912
+ // src/auth-core-module.ts
1926
1913
  const EVALUATOR = Symbol("authorization-evaluator");
1927
1914
  const exports$1 = [
1928
1915
  require_decorate.INSTANCE_REGISTRY,
@@ -2151,8 +2138,7 @@ BetterAuthCoreModule = require_decorate.__decorate([
2151
2138
  typeof BootValidator === "undefined" ? Object : BootValidator
2152
2139
  ])
2153
2140
  ], BetterAuthCoreModule);
2154
- //#endregion
2155
- //#region src/session-principal.ts
2141
+ // src/session-principal.ts
2156
2142
  const SESSION_PRINCIPAL_KIND = "session";
2157
2143
  const CurrentSession = require_auth_decorators.definePrincipalParam({
2158
2144
  kind: SESSION_PRINCIPAL_KIND,
@@ -2291,8 +2277,7 @@ const freshSession = (options = {}) => ({
2291
2277
  params: options
2292
2278
  });
2293
2279
  const RequireFreshSession = (options) => require_auth_decorators.Require(freshSession(options));
2294
- //#endregion
2295
- //#region src/auth-service.ts
2280
+ // src/auth-service.ts
2296
2281
  let BetterAuthService = class BetterAuthService {
2297
2282
  registry;
2298
2283
  scope;
@@ -2414,8 +2399,7 @@ BetterAuthService = require_decorate.__decorate([
2414
2399
  Object
2415
2400
  ])
2416
2401
  ], BetterAuthService);
2417
- //#endregion
2418
- //#region src/http-transport.ts
2402
+ // src/http-transport.ts
2419
2403
  let HttpTransport = class HttpTransport {
2420
2404
  adapterHost;
2421
2405
  id = "http";
@@ -2511,8 +2495,7 @@ HttpTransport = require_decorate.__decorate([require_decorate.__decorateParam(0,
2511
2495
  function httpTransport() {
2512
2496
  return HttpTransport;
2513
2497
  }
2514
- //#endregion
2515
- //#region src/auth-module-definition.ts
2498
+ // src/auth-module-definition.ts
2516
2499
  function defineExtension(definition) {
2517
2500
  return {
2518
2501
  ...definition,
@@ -2690,8 +2673,7 @@ function moduleDefinition(module, definition, async) {
2690
2673
  exports
2691
2674
  };
2692
2675
  }
2693
- //#endregion
2694
- //#region src/auth-module.ts
2676
+ // src/auth-module.ts
2695
2677
  var _BetterAuthModule;
2696
2678
  let BetterAuthModule = _BetterAuthModule = class BetterAuthModule {
2697
2679
  static forRoot(options) {
@@ -2702,7 +2684,6 @@ let BetterAuthModule = _BetterAuthModule = class BetterAuthModule {
2702
2684
  }
2703
2685
  };
2704
2686
  BetterAuthModule = _BetterAuthModule = require_decorate.__decorate([(0, _nestjs_common.Module)({})], BetterAuthModule);
2705
- //#endregion
2706
2687
  Object.defineProperty(exports, "AuthorizationEvaluator", {
2707
2688
  enumerable: true,
2708
2689
  get: function() {
@@ -2806,4 +2787,4 @@ Object.defineProperty(exports, "sessionPrincipal", {
2806
2787
  }
2807
2788
  });
2808
2789
 
2809
- //# sourceMappingURL=auth-module-BgcY2HpA.cjs.map
2790
+ //# sourceMappingURL=auth-module-ab60-WJZ.cjs.map