@nestjs-kit/better-auth 0.0.0-stage → 2.1.0

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 (142) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +1078 -2
  3. package/dist/admin.cjs +88 -0
  4. package/dist/admin.cjs.map +1 -0
  5. package/dist/admin.d.cts +14 -0
  6. package/dist/admin.d.cts.map +1 -0
  7. package/dist/admin.d.mts +14 -0
  8. package/dist/admin.d.mts.map +1 -0
  9. package/dist/admin.mjs +85 -0
  10. package/dist/admin.mjs.map +1 -0
  11. package/dist/api-key.cjs +164 -0
  12. package/dist/api-key.cjs.map +1 -0
  13. package/dist/api-key.d.cts +42 -0
  14. package/dist/api-key.d.cts.map +1 -0
  15. package/dist/api-key.d.mts +42 -0
  16. package/dist/api-key.d.mts.map +1 -0
  17. package/dist/api-key.mjs +160 -0
  18. package/dist/api-key.mjs.map +1 -0
  19. package/dist/auth-contracts-Brh_Qko9.d.cts +1654 -0
  20. package/dist/auth-contracts-Brh_Qko9.d.cts.map +1 -0
  21. package/dist/auth-contracts-Cz7C4_Ch.d.mts +1654 -0
  22. package/dist/auth-contracts-Cz7C4_Ch.d.mts.map +1 -0
  23. package/dist/auth-decorators-B1mFnGJ6.mjs +284 -0
  24. package/dist/auth-decorators-B1mFnGJ6.mjs.map +1 -0
  25. package/dist/auth-decorators-Cu_nxWnF.cjs +421 -0
  26. package/dist/auth-decorators-Cu_nxWnF.cjs.map +1 -0
  27. package/dist/auth-errors-C3rbTV9p.mjs +301 -0
  28. package/dist/auth-errors-C3rbTV9p.mjs.map +1 -0
  29. package/dist/auth-errors-DmiKl0L_.cjs +378 -0
  30. package/dist/auth-errors-DmiKl0L_.cjs.map +1 -0
  31. package/dist/auth-guard-CLyhAEEj.cjs +136 -0
  32. package/dist/auth-guard-CLyhAEEj.cjs.map +1 -0
  33. package/dist/auth-guard-h9QB_l11.mjs +125 -0
  34. package/dist/auth-guard-h9QB_l11.mjs.map +1 -0
  35. package/dist/auth-module-BgcY2HpA.cjs +2809 -0
  36. package/dist/auth-module-BgcY2HpA.cjs.map +1 -0
  37. package/dist/auth-module-CtHx3gRU.mjs +2708 -0
  38. package/dist/auth-module-CtHx3gRU.mjs.map +1 -0
  39. package/dist/auth-scope-interceptor-BjxAL1-S.cjs +290 -0
  40. package/dist/auth-scope-interceptor-BjxAL1-S.cjs.map +1 -0
  41. package/dist/auth-scope-interceptor-DYPn3b8M.mjs +231 -0
  42. package/dist/auth-scope-interceptor-DYPn3b8M.mjs.map +1 -0
  43. package/dist/bridge-protocol-BDw8opAG.cjs +25 -0
  44. package/dist/bridge-protocol-BDw8opAG.cjs.map +1 -0
  45. package/dist/bridge-protocol-c66aEkr5.mjs +8 -0
  46. package/dist/bridge-protocol-c66aEkr5.mjs.map +1 -0
  47. package/dist/decorate-Cr4Q7bNE.cjs +319 -0
  48. package/dist/decorate-Cr4Q7bNE.cjs.map +1 -0
  49. package/dist/decorate-Dt0e9K6R.mjs +80 -0
  50. package/dist/decorate-Dt0e9K6R.mjs.map +1 -0
  51. package/dist/express.cjs +256 -0
  52. package/dist/express.cjs.map +1 -0
  53. package/dist/express.d.cts +37 -0
  54. package/dist/express.d.cts.map +1 -0
  55. package/dist/express.d.mts +37 -0
  56. package/dist/express.d.mts.map +1 -0
  57. package/dist/express.mjs +254 -0
  58. package/dist/express.mjs.map +1 -0
  59. package/dist/fastify.cjs +218 -0
  60. package/dist/fastify.cjs.map +1 -0
  61. package/dist/fastify.d.cts +28 -0
  62. package/dist/fastify.d.cts.map +1 -0
  63. package/dist/fastify.d.mts +28 -0
  64. package/dist/fastify.d.mts.map +1 -0
  65. package/dist/fastify.mjs +216 -0
  66. package/dist/fastify.mjs.map +1 -0
  67. package/dist/graphql.cjs +509 -0
  68. package/dist/graphql.cjs.map +1 -0
  69. package/dist/graphql.d.cts +38 -0
  70. package/dist/graphql.d.cts.map +1 -0
  71. package/dist/graphql.d.mts +38 -0
  72. package/dist/graphql.d.mts.map +1 -0
  73. package/dist/graphql.mjs +503 -0
  74. package/dist/graphql.mjs.map +1 -0
  75. package/dist/index.cjs +86 -0
  76. package/dist/index.d.cts +2 -0
  77. package/dist/index.d.mts +2 -0
  78. package/dist/index.mjs +8 -0
  79. package/dist/microservices.cjs +231 -0
  80. package/dist/microservices.cjs.map +1 -0
  81. package/dist/microservices.d.cts +39 -0
  82. package/dist/microservices.d.cts.map +1 -0
  83. package/dist/microservices.d.mts +39 -0
  84. package/dist/microservices.d.mts.map +1 -0
  85. package/dist/microservices.mjs +222 -0
  86. package/dist/microservices.mjs.map +1 -0
  87. package/dist/organization.cjs +191 -0
  88. package/dist/organization.cjs.map +1 -0
  89. package/dist/organization.d.cts +40 -0
  90. package/dist/organization.d.cts.map +1 -0
  91. package/dist/organization.d.mts +40 -0
  92. package/dist/organization.d.mts.map +1 -0
  93. package/dist/organization.mjs +177 -0
  94. package/dist/organization.mjs.map +1 -0
  95. package/dist/platform-CZl7TY8j.mjs +414 -0
  96. package/dist/platform-CZl7TY8j.mjs.map +1 -0
  97. package/dist/platform-YICqqYv6.cjs +473 -0
  98. package/dist/platform-YICqqYv6.cjs.map +1 -0
  99. package/dist/platform.cjs +10 -0
  100. package/dist/platform.d.cts +43 -0
  101. package/dist/platform.d.cts.map +1 -0
  102. package/dist/platform.d.mts +43 -0
  103. package/dist/platform.d.mts.map +1 -0
  104. package/dist/platform.mjs +1 -0
  105. package/dist/plugin.cjs +323 -0
  106. package/dist/plugin.cjs.map +1 -0
  107. package/dist/plugin.d.cts +24 -0
  108. package/dist/plugin.d.cts.map +1 -0
  109. package/dist/plugin.d.mts +24 -0
  110. package/dist/plugin.d.mts.map +1 -0
  111. package/dist/plugin.mjs +321 -0
  112. package/dist/plugin.mjs.map +1 -0
  113. package/dist/principal-readings-Chmt6rQV.cjs +208 -0
  114. package/dist/principal-readings-Chmt6rQV.cjs.map +1 -0
  115. package/dist/principal-readings-Ied2staw.mjs +191 -0
  116. package/dist/principal-readings-Ied2staw.mjs.map +1 -0
  117. package/dist/rolldown-runtime-VH7oDXx4.cjs +28 -0
  118. package/dist/testing/conformance.cjs +6214 -0
  119. package/dist/testing/conformance.cjs.map +1 -0
  120. package/dist/testing/conformance.d.cts +528 -0
  121. package/dist/testing/conformance.d.cts.map +1 -0
  122. package/dist/testing/conformance.d.mts +528 -0
  123. package/dist/testing/conformance.d.mts.map +1 -0
  124. package/dist/testing/conformance.mjs +6204 -0
  125. package/dist/testing/conformance.mjs.map +1 -0
  126. package/dist/testing.cjs +221 -0
  127. package/dist/testing.cjs.map +1 -0
  128. package/dist/testing.d.cts +64 -0
  129. package/dist/testing.d.cts.map +1 -0
  130. package/dist/testing.d.mts +64 -0
  131. package/dist/testing.d.mts.map +1 -0
  132. package/dist/testing.mjs +214 -0
  133. package/dist/testing.mjs.map +1 -0
  134. package/dist/websockets.cjs +396 -0
  135. package/dist/websockets.cjs.map +1 -0
  136. package/dist/websockets.d.cts +67 -0
  137. package/dist/websockets.d.cts.map +1 -0
  138. package/dist/websockets.d.mts +67 -0
  139. package/dist/websockets.d.mts.map +1 -0
  140. package/dist/websockets.mjs +383 -0
  141. package/dist/websockets.mjs.map +1 -0
  142. package/package.json +327 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conformance.mjs","names":["sessionToken","request","nodeRequest","staticMember","kitModule","json","variantOf","harness","withHarness","sessionReads","API_KEY_KIND","SESSION_KIND","API_KEY_KIND","createKey","withHarness","variantOf","withHarness","sessionReads","variantOf","policyHarness"],"sources":["../../src/database-hook-dispatcher.ts","../../src/hook-dispatcher.ts","../../src/plugin.ts","../../src/conformance-fixtures.ts","../../src/conformance-http.ts","../../src/conformance-policy-harness.ts","../../src/conformance-policy-units.ts","../../src/conformance-policy.ts","../../src/conformance-principal.ts","../../src/conformance-transport.ts"],"sourcesContent":["import type { BetterAuthOptions } from \"better-auth\";\nimport type { DatabaseHookTarget } from \"./auth-contracts.js\";\nimport type {\n DatabaseHookData,\n DatabaseHookResult,\n DbHookFn,\n} from \"./auth-types.js\";\nimport type { BridgeBinding } from \"./bridge-protocol.js\";\n\n/**\n * Construct all dispatchers once; bindings supply only the late-bound methods.\n *\n * The dispatchers take the SDK's own parameter types, so they satisfy `databaseHooks` whatever\n * instance the program registers. Bound hooks declare `DatabaseHookData`, which adds the\n * registered instance's plugin and additional fields (for example admin()'s `banned`) to the\n * same rows; the dispatcher states that narrowing once when it forwards a payload.\n */\nexport function createDatabaseDispatchers(\n getBinding: () => BridgeBinding | null,\n countUnbound: () => void,\n): NonNullable<BetterAuthOptions[\"databaseHooks\"]> {\n function operation<E extends DatabaseHookTarget>(target: E) {\n const before = async (\n ...[data, ctx]: Parameters<DbHookFn<E, \"before\">>\n ): Promise<DatabaseHookResult<E, \"before\">> => {\n const binding = getBinding();\n if (!binding) {\n countUnbound();\n return undefined as DatabaseHookResult<E, \"before\">;\n }\n const hooks = binding.database[target].before;\n let accumulated: Record<string, unknown> = {};\n let changed = false;\n for (const hook of hooks) {\n const result = await hook(\n (target.endsWith(\".create\")\n ? { ...data, ...accumulated }\n : data) as DatabaseHookData<E, \"before\">,\n ctx,\n );\n if (result === false) {\n return false as DatabaseHookResult<E, \"before\">;\n }\n if (\n !target.endsWith(\".delete\") &&\n result &&\n typeof result === \"object\" &&\n \"data\" in result\n ) {\n accumulated = { ...accumulated, ...result.data };\n changed = true;\n }\n }\n // A generic target cannot express the runtime delete narrowing. Delete\n // never reaches this branch; the public binding keeps its void/false type.\n return (\n changed ? { data: accumulated } : undefined\n ) as DatabaseHookResult<E, \"before\">;\n };\n const after = async (\n ...[data, ctx]: Parameters<DbHookFn<E, \"after\">>\n ): Promise<void> => {\n const binding = getBinding();\n if (!binding) {\n countUnbound();\n return;\n }\n for (const hook of binding.database[target].after) {\n await hook(data as DatabaseHookData<E, \"after\">, ctx);\n }\n };\n return { before, after };\n }\n return {\n user: {\n create: operation(\"user.create\"),\n update: operation(\"user.update\"),\n delete: operation(\"user.delete\"),\n },\n session: {\n create: operation(\"session.create\"),\n update: operation(\"session.update\"),\n delete: operation(\"session.delete\"),\n },\n account: {\n create: operation(\"account.create\"),\n update: operation(\"account.update\"),\n delete: operation(\"account.delete\"),\n },\n verification: {\n create: operation(\"verification.create\"),\n update: operation(\"verification.update\"),\n delete: operation(\"verification.delete\"),\n },\n };\n}\n","import type { HookEndpointContext } from \"better-auth\";\nimport { APIError, createAuthMiddleware, isAPIError } from \"better-auth/api\";\nimport { createDefu } from \"defu\";\nimport type { BridgeBinding, ScopeView } from \"./bridge-protocol.js\";\n\nconst API_ERROR_HEADERS = Symbol.for(\"better-call:api-error-headers\");\nconst mergeContext = createDefu((object, key, value) => {\n if (Array.isArray(object[key]) && Array.isArray(value)) {\n object[key] = value;\n return true;\n }\n});\n\nfunction mergeHeaders(\n target: Headers,\n source: Headers | null | undefined,\n): void {\n source?.forEach((value, key) => {\n if (key === \"set-cookie\") {\n target.append(key, value);\n } else {\n target.set(key, value);\n }\n });\n}\n\nfunction errorHeaders(error: APIError): Headers | undefined {\n const attached = (error as unknown as Record<symbol, Headers | undefined>)[\n API_ERROR_HEADERS\n ];\n if (!attached && !error.headers) {\n return undefined;\n }\n const headers = new Headers(attached);\n if (error.headers && error.headers !== attached) {\n mergeHeaders(headers, new Headers(error.headers));\n }\n return headers;\n}\n\n/** Run each method through the SDK middleware so its cookie/header state is isolated. */\nexport async function runBefore(\n binding: BridgeBinding,\n ctx: HookEndpointContext,\n scope: ScopeView | undefined,\n): Promise<unknown> {\n let accumulated: Record<string, unknown> = {};\n for (const hook of binding.before) {\n let matched: boolean;\n try {\n matched = hook.matches(ctx, scope);\n } catch (error) {\n ctx.context.logger.error(\n \"An error occurred during Nest hook matcher execution:\",\n error,\n );\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message:\n \"An error occurred during hook matcher execution. Check the logs for more details.\",\n });\n }\n if (!matched) {\n continue;\n }\n let result: { response: unknown; headers: Headers };\n try {\n result = (await createAuthMiddleware(hook.run)({\n ...ctx,\n returnHeaders: true,\n })) as { response: unknown; headers: Headers };\n } catch (error) {\n if (isAPIError(error)) {\n // The enclosing SDK middleware reattaches its own header object. Keep\n // the throwing method's headers, including non-enumerable cookie state.\n ctx.responseHeaders =\n (error as unknown as Record<symbol, Headers | undefined>)[\n API_ERROR_HEADERS\n ] ?? new Headers();\n }\n throw error;\n }\n ctx.context.responseHeaders ??= new Headers();\n mergeHeaders(ctx.context.responseHeaders, result.headers);\n const value = result.response;\n if (value && typeof value === \"object\") {\n if (\"context\" in value && typeof value.context === \"object\") {\n const { headers, ...rest } = value.context as Record<string, unknown>;\n if (headers instanceof Headers) {\n const requestHeaders =\n accumulated.headers instanceof Headers\n ? accumulated.headers\n : new Headers();\n headers.forEach((header, key) => {\n requestHeaders.set(key, header);\n });\n accumulated.headers = requestHeaders;\n }\n accumulated = mergeContext(rest, accumulated);\n } else {\n return value;\n }\n }\n }\n return Object.keys(accumulated).length ? { context: accumulated } : undefined;\n}\n\nexport async function runAfter(\n binding: BridgeBinding,\n ctx: HookEndpointContext,\n scope: ScopeView | undefined,\n relayMatcherError?: (error: unknown) => void,\n): Promise<unknown> {\n for (const hook of binding.after) {\n let matched: boolean;\n try {\n matched = hook.matches(ctx, scope);\n } catch (error) {\n if (!relayMatcherError) {\n throw error;\n }\n // A surrounding SDK handler catches APIErrors as recoverable results.\n // Stop here and rethrow from the next fixed SDK matcher instead.\n relayMatcherError(error);\n return undefined;\n }\n if (!matched) {\n continue;\n }\n let result: { response: unknown; headers?: Headers | null };\n try {\n result = (await createAuthMiddleware(hook.run)({\n ...ctx,\n returnHeaders: true,\n })) as { response: unknown; headers: Headers };\n } catch (error) {\n if (!isAPIError(error)) {\n throw error;\n }\n result = { response: error, headers: errorHeaders(error) };\n }\n if (result.headers) {\n ctx.context.responseHeaders ??= new Headers();\n mergeHeaders(ctx.context.responseHeaders, result.headers);\n }\n if (result.response !== undefined) {\n ctx.context.returned = result.response;\n }\n }\n return ctx.context.returned;\n}\n","import type { BetterAuthPlugin, HookEndpointContext } from \"better-auth\";\nimport {\n createAuthMiddleware,\n setShouldSkipSessionRefresh,\n} from \"better-auth/api\";\nimport { parseCookies } from \"better-auth/cookies\";\nimport type { NestjsPluginOptions } from \"./auth-contracts.js\";\nimport {\n BRIDGE_HANDLE,\n type BridgeBinding,\n type BridgeHandle,\n type ScopeView,\n} from \"./bridge-protocol.js\";\nimport { createDatabaseDispatchers } from \"./database-hook-dispatcher.js\";\nimport { runAfter, runBefore } from \"./hook-dispatcher.js\";\n\nexport type { NestjsPluginOptions } from \"./auth-contracts.js\";\nexport const NESTJS_PLUGIN_ID = \"@nestjs-kit/better-auth\";\n\nconst isRouter = (ctx: object): boolean =>\n \"_flag\" in ctx && ctx._flag === \"router\";\nconst separator = \"\\u0000\";\n\nfunction sessionToken(\n headers: Headers | undefined,\n ctx: HookEndpointContext,\n): string {\n return (\n parseCookies(headers?.get(\"cookie\") ?? \"\").get(\n ctx.context.authCookies.sessionToken.name,\n ) ?? \"\"\n );\n}\n\nfunction credential(\n headers: Headers | undefined,\n ctx: HookEndpointContext,\n extra: readonly string[],\n): string {\n return [\n sessionToken(headers, ctx),\n headers?.get(\"authorization\") ?? \"\",\n ...extra.map((name) => headers?.get(name) ?? \"\"),\n ].join(separator);\n}\n\nfunction sameCredential(\n ctx: HookEndpointContext,\n scope: ScopeView,\n extra: readonly string[],\n): boolean {\n const call = credential(ctx.headers, ctx, extra);\n return (\n call === separator.repeat(extra.length + 1) ||\n call === credential(scope.inbound?.(), ctx, extra)\n );\n}\n\n/** Pure construction-time Better Auth plugin; the Nest kernel binds through a global symbol. */\nexport function nestjs(\n options: NestjsPluginOptions = {},\n): BetterAuthPlugin & { id: typeof NESTJS_PLUGIN_ID } {\n let binding: BridgeBinding | null = null;\n let registration: ReturnType<BridgeHandle[\"bind\"]> | undefined;\n let unboundDispatches = 0;\n const endpointResults = new WeakSet<object>();\n const afterMatcherErrors = new WeakMap<object, unknown>();\n const scope = () => binding?.current();\n const clientIpHeader =\n options.clientIpHeader === false\n ? null\n : (options.clientIpHeader ??\n `x-nestjs-kit-better-auth-ip-${globalThis.crypto.randomUUID().replaceAll(\"-\", \"\")}`);\n const handle: BridgeHandle = {\n protocol: 4,\n clientIpHeader,\n get state() {\n return binding === null\n ? \"unbound\"\n : binding.state === \"closed\"\n ? \"closed\"\n : \"bound\";\n },\n get unboundDispatches() {\n return unboundDispatches;\n },\n bind(next) {\n if (binding && binding.instance !== next.instance) {\n throw new Error(\n `PLUGIN_SHARED_BETWEEN_INSTANCES: '${binding.instance}' and '${next.instance}'`,\n );\n }\n if (binding?.owner === next.owner && registration) {\n return registration;\n }\n if (binding?.state === \"bootstrapped\") {\n throw new Error(\n `INSTANCE_ALREADY_BOUND: bound to ${binding.owner.description}`,\n );\n }\n let tookOverFrom: string | undefined;\n if (binding?.state === \"initialized\") {\n tookOverFrom = binding.owner.description;\n // Its application may still be initializing: its bootstrap must fail rather than run without hooks.\n binding.state = \"displaced\";\n }\n binding = next;\n unboundDispatches = 0;\n registration = {\n tookOverFrom,\n close: () => {\n next.state = \"closed\";\n },\n };\n return registration;\n },\n producedByEndpoint(value) {\n return (\n typeof value === \"object\" &&\n value !== null &&\n endpointResults.has(value)\n );\n },\n };\n const plugin = {\n id: NESTJS_PLUGIN_ID,\n [BRIDGE_HANDLE]: handle,\n init: () => ({\n options: {\n databaseHooks: createDatabaseDispatchers(\n () => binding,\n () => {\n unboundDispatches++;\n },\n ),\n ...(clientIpHeader\n ? { advanced: { ipAddress: { ipAddressHeaders: [clientIpHeader] } } }\n : {}),\n },\n }),\n hooks: {\n before: [\n {\n matcher: (ctx) => {\n if (!binding) {\n unboundDispatches++;\n return false;\n }\n return !isRouter(ctx) && scope()?.cookies === null;\n },\n handler: createAuthMiddleware(async () => {\n await setShouldSkipSessionRefresh(true);\n }),\n },\n {\n matcher: (ctx) => {\n if (!binding || isRouter(ctx)) {\n return false;\n }\n const current = scope();\n if (!current || current.internal) {\n return false;\n }\n // Access capabilities before testing credentials: extraction errors\n // must fail even a credential-free direct endpoint call.\n const check = current.checkCallerSession;\n current.inbound?.();\n const browser = current.browserHeaders?.();\n const token = sessionToken(ctx.headers, ctx);\n // Only the browser leg's own cookie is ambient. A session cookie that a\n // transport mapped in-band (graphql-ws connectionParams, socket\n // credentials) cannot ride a cross-site request.\n return (\n !!check && token !== \"\" && token === sessionToken(browser, ctx)\n );\n },\n handler: createAuthMiddleware(async (ctx) => {\n scope()?.checkCallerSession?.(ctx.path, binding!.instance);\n }),\n },\n {\n matcher: () => binding !== null && binding.before.length > 0,\n handler: createAuthMiddleware((ctx) =>\n runBefore(binding!, ctx, scope()),\n ),\n },\n ],\n after: [\n {\n matcher: () => binding !== null && binding.after.length > 0,\n handler: createAuthMiddleware((ctx) =>\n runAfter(binding!, ctx, scope(), (error) => {\n afterMatcherErrors.set(ctx.context, error);\n }),\n ),\n },\n {\n matcher: (ctx) => {\n // Each endpoint dispatch owns this shared context, including nested\n // calls. Rethrow outside the SDK's recoverable handler-error catch.\n if (afterMatcherErrors.has(ctx.context)) {\n const error = afterMatcherErrors.get(ctx.context);\n afterMatcherErrors.delete(ctx.context);\n throw error;\n }\n return binding !== null && !isRouter(ctx);\n },\n handler: createAuthMiddleware(async (ctx) => {\n const value = ctx.context.returned;\n if (typeof value === \"object\" && value !== null) {\n endpointResults.add(value);\n }\n }),\n },\n {\n matcher: (ctx) => {\n if (isRouter(ctx)) {\n return false;\n }\n const current = scope();\n return !!current?.cookies && current.forward !== \"none\";\n },\n handler: createAuthMiddleware(async (ctx) => {\n const current = scope()!;\n if (\n current.forward === \"same-credential\" &&\n !sameCredential(ctx, current, binding!.credentialHeaders)\n ) {\n binding!.onDropped(ctx.path);\n return;\n }\n const cookies = ctx.context.responseHeaders?.getSetCookie() ?? [];\n if (cookies.length) {\n current.cookies!.append(cookies);\n }\n }),\n },\n ],\n },\n } satisfies BetterAuthPlugin & { [BRIDGE_HANDLE]: BridgeHandle };\n return plugin;\n}\n","import {\n type IncomingHttpHeaders,\n type OutgoingHttpHeaders,\n request as nodeRequest,\n} from \"node:http\";\nimport { inspect } from \"node:util\";\nimport type { LoggerService } from \"@nestjs/common\";\nimport {\n betterAuth,\n type BetterAuthOptions,\n type BetterAuthPlugin,\n} from \"better-auth\";\nimport { memoryAdapter } from \"better-auth/adapters/memory\";\nimport {\n APIError,\n createAuthEndpoint,\n createAuthMiddleware,\n getIP,\n getShouldSkipSessionRefresh,\n} from \"better-auth/api\";\nimport { bearer, testUtils } from \"better-auth/plugins\";\nimport type {\n ConformanceCase,\n ConformanceOutcome,\n ConformanceRunner,\n ConformanceSkip,\n} from \"./auth-contracts.js\";\nimport { BetterAuthConfigurationError } from \"./auth-errors.js\";\nimport type { AuthLike } from \"./auth-types.js\";\nimport { nestjs } from \"./plugin.js\";\n\nexport type {\n ConformanceCase,\n ConformanceOutcome,\n ConformanceRunner,\n ConformanceSkip,\n} from \"./auth-contracts.js\";\n\nexport const PROBE_PLUGIN_ID = \"nestjs-kit-better-auth-conformance-probe\";\n/** The trusted origin the probe plugin contributes through init(), so origin cases see the post-init set. */\nexport const PROBE_TRUSTED_ORIGIN = \"https://probe-plugin.example\";\nexport const KIT_BASE_URL = \"http://localhost:3000\";\nexport const UNTRUSTED_ORIGIN = \"https://evil.example\";\nconst PROBE_STATE = Symbol.for(\"@nestjs-kit/better-auth:conformance-probe\");\n\n/** One database adapter operation the probe observed. */\nexport interface StorageCall {\n readonly method: string;\n readonly model: string | undefined;\n}\n\n/** The Set-Cookie lines one dispatched endpoint produced, with the request headers of that call. */\nexport interface ProducedCookies {\n readonly path: string;\n readonly setCookies: readonly string[];\n readonly headers: Headers | undefined;\n /** The instance's session cookie name, to compare the call's credential with a request's. */\n readonly sessionCookie: string;\n}\n\n/** Observations and fault injection of one conformanceProbePlugin() object. */\nexport interface ProbeState {\n /** Every endpoint path Better Auth dispatched (router and auth.api), in order. */\n readonly calls: string[];\n /** Database writes as `<model>.<create|update|delete>`. */\n readonly writes: string[];\n /** Every database adapter operation as `<method>:<model>`, reads included, transactions included. */\n readonly storage: string[];\n /** Endpoint dispatches that produced Set-Cookie lines, seen by an after hook. */\n readonly produced: ProducedCookies[];\n /** getShouldSkipSessionRefresh() observed by an after hook, per dispatched path. */\n readonly refresh: { readonly path: string; readonly skip: boolean }[];\n /** 'middleware' and 'auth' markers for ordering cases. */\n readonly order: string[];\n /** Returns a value to throw from the before hook for a path; undefined dispatches normally. */\n fault: ((path: string) => unknown) | undefined;\n /** Returns a value to throw from a database adapter operation (a storage outage); undefined runs it. */\n storageFault: ((call: StorageCall) => unknown) | undefined;\n /** Milliseconds a database adapter operation waits before it runs or throws its fault (a stalled storage). */\n storageDelay: ((call: StorageCall) => number | undefined) | undefined;\n /**\n * Returns a value the before hook answers with instead of dispatching the endpoint, as a plugin's hook that\n * short-circuits an endpoint does (apiKey's session for /get-session); undefined dispatches normally.\n */\n respond:\n | ((path: string, headers: Headers | undefined) => unknown)\n | undefined;\n /** Milliseconds the before hook waits for a path, so that concurrent sources settle in a chosen order. */\n delay: ((path: string) => number | undefined) | undefined;\n /** A response header the after hook sets on a dispatched path, beside its Set-Cookie lines; undefined sets none. */\n responseHeader: ((path: string) => [string, string] | undefined) | undefined;\n streamCancelled: boolean;\n}\n\nexport function createProbeState(): ProbeState {\n return {\n calls: [],\n writes: [],\n storage: [],\n produced: [],\n refresh: [],\n order: [],\n fault: undefined,\n storageFault: undefined,\n storageDelay: undefined,\n respond: undefined,\n delay: undefined,\n responseHeader: undefined,\n streamCancelled: false,\n };\n}\n\n/** A case result: the case does not apply to this unit, for the given reason. */\nexport function conformanceSkip(reason: string): ConformanceSkip {\n return { skipped: reason };\n}\n\nconst STORAGE_METHODS = [\n \"create\",\n \"update\",\n \"updateMany\",\n \"findOne\",\n \"findMany\",\n \"delete\",\n \"deleteMany\",\n \"consumeOne\",\n \"count\",\n] as const;\nconst INSTRUMENTED = Symbol(\"@nestjs-kit/better-auth:conformance-storage\");\n\n/** Counts and faults every data operation of a database adapter in place, including the adapters of its transactions. */\nfunction instrumentStorage(adapter: unknown, state: ProbeState): void {\n if (\n !adapter ||\n typeof adapter !== \"object\" ||\n Reflect.get(adapter, INSTRUMENTED)\n ) {\n return;\n }\n const target = adapter as Record<string, unknown>;\n Object.defineProperty(target, INSTRUMENTED, { value: true });\n for (const method of STORAGE_METHODS) {\n const original = target[method];\n if (typeof original !== \"function\") {\n continue;\n }\n target[method] = async (...args: unknown[]) => {\n const model = (args[0] as { model?: unknown } | undefined)?.model;\n const call = {\n method,\n model: typeof model === \"string\" ? model : undefined,\n };\n state.storage.push(`${method}:${call.model ?? \"\"}`);\n const stall = state.storageDelay?.(call);\n if (stall) {\n await new Promise((resolve) => setTimeout(resolve, stall));\n }\n const fault = state.storageFault?.(call);\n if (fault !== undefined) {\n throw fault;\n }\n return (original as (...values: unknown[]) => unknown).apply(\n target,\n args,\n );\n };\n }\n const transaction = target.transaction;\n if (typeof transaction === \"function\") {\n target.transaction = (callback: (adapter: unknown) => unknown) =>\n (transaction as (fn: (adapter: unknown) => unknown) => unknown).call(\n target,\n (inner: unknown) => {\n instrumentStorage(inner, state);\n return callback(inner);\n },\n );\n }\n}\n\nfunction base64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64\");\n}\n\nfunction writes(state: ProbeState) {\n const record = (entry: string) => async () => {\n state.writes.push(entry);\n };\n return Object.fromEntries(\n [\"user\", \"session\", \"account\", \"verification\"].map((model) => [\n model,\n {\n create: { after: record(`${model}.create`) },\n update: { after: record(`${model}.update`) },\n delete: { after: record(`${model}.delete`) },\n },\n ]),\n );\n}\n\n/**\n * The conformance kits' Better Auth probe: byte-exact echo, multi-cookie, redirect, stream, HTML, method, URL\n * and IP endpoints under /probe, a before hook that counts dispatches and injects faults, an after hook that\n * records refresh suppression and the Set-Cookie lines each call produced, database write counters, a storage\n * instrument that counts and faults every database adapter operation, and https://probe-plugin.example as a trusted\n * origin contributed through init(). Put it before nestjs() in the plugin list.\n */\nexport function conformanceProbePlugin(): BetterAuthPlugin {\n return probePlugin();\n}\n\nfunction probePlugin(\n options: { memoryTables?: Record<string, unknown[]> } = {},\n): BetterAuthPlugin {\n const state = createProbeState();\n const plugin = {\n id: PROBE_PLUGIN_ID,\n init(context: { adapter: unknown; tables?: object }) {\n if (options.memoryTables) {\n for (const table of Object.values(context.tables ?? {}) as {\n modelName: string;\n }[]) {\n options.memoryTables[table.modelName] ??= [];\n }\n }\n instrumentStorage(context.adapter, state);\n return {\n options: {\n trustedOrigins: [PROBE_TRUSTED_ORIGIN],\n databaseHooks: writes(state),\n },\n };\n },\n endpoints: {\n probeEchoRaw: createAuthEndpoint(\n \"/probe/echo-raw\",\n {\n method: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"],\n disableBody: true,\n requireRequest: true,\n },\n async (ctx) => {\n state.order.push(\"auth\");\n const bytes = new Uint8Array(await ctx.request.arrayBuffer());\n return Response.json({\n method: ctx.request.method,\n url: ctx.request.url,\n headers: [...ctx.request.headers],\n body: base64(bytes),\n });\n },\n ),\n probeMultiCookie: createAuthEndpoint(\n \"/probe/multi-cookie\",\n { method: \"GET\" },\n async (ctx) => {\n ctx.setCookie(\"probe_a\", \"alpha\", { path: \"/\" });\n ctx.setCookie(\"probe_b\", \"beta\", { path: \"/\" });\n ctx.setCookie(\"probe_c\", \"gamma, delta\", { path: \"/\" });\n return ctx.json({ cookies: 3 });\n },\n ),\n probeRedirect: createAuthEndpoint(\n \"/probe/redirect\",\n { method: \"GET\" },\n async () =>\n new Response(null, {\n status: 302,\n headers: [\n [\"location\", `${PROBE_TRUSTED_ORIGIN}/next`],\n [\"set-cookie\", \"probe_redirect=1; Path=/\"],\n ],\n }),\n ),\n probeStream: createAuthEndpoint(\n \"/probe/stream\",\n { method: \"GET\" },\n async () => {\n let index = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const stream = new ReadableStream<Uint8Array>({\n pull(controller) {\n return new Promise<void>((resolve) => {\n timer = setTimeout(() => {\n if (index === 3) {\n controller.close();\n } else {\n controller.enqueue(\n new TextEncoder().encode(`chunk-${index++};`),\n );\n }\n resolve();\n }, 25);\n });\n },\n cancel() {\n clearTimeout(timer);\n state.streamCancelled = true;\n },\n });\n return new Response(stream, {\n headers: { \"content-type\": \"text/plain\" },\n });\n },\n ),\n probeHtml: createAuthEndpoint(\n \"/probe/html\",\n { method: \"GET\" },\n async () =>\n new Response(\"<p>probe</p>\", {\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n vary: \"Accept\",\n },\n }),\n ),\n probePut: createAuthEndpoint(\n \"/probe/put\",\n { method: \"PUT\" },\n async (ctx) => ctx.json({ method: \"PUT\" }),\n ),\n probePatch: createAuthEndpoint(\n \"/probe/patch\",\n { method: \"PATCH\" },\n async (ctx) => ctx.json({ method: \"PATCH\" }),\n ),\n probeDelete: createAuthEndpoint(\n \"/probe/delete\",\n { method: \"DELETE\" },\n async (ctx) => ctx.json({ method: \"DELETE\" }),\n ),\n probeUrl: createAuthEndpoint(\n \"/probe/url\",\n { method: \"GET\", requireRequest: true },\n async (ctx) => ctx.json({ url: ctx.request.url }),\n ),\n probeIp: createAuthEndpoint(\n \"/probe/ip\",\n { method: \"GET\", requireRequest: true },\n async (ctx) =>\n ctx.json({\n ip: getIP(ctx.request, ctx.context.options),\n resolved: resolvedIp(ctx.request, ctx.context.options),\n }),\n ),\n probeThrowApiError: createAuthEndpoint(\n \"/probe/throw-api-error\",\n { method: \"GET\" },\n async () => {\n throw new APIError(\"BAD_REQUEST\", {\n code: \"PROBE_API_ERROR\",\n message: \"Probe API error\",\n });\n },\n ),\n probeThrowError: createAuthEndpoint(\n \"/probe/throw-error\",\n { method: \"GET\" },\n async () => {\n throw new Error(\"probe infrastructure failure\");\n },\n ),\n },\n hooks: {\n before: [\n {\n matcher: () => true,\n handler: createAuthMiddleware(async (ctx) => {\n state.calls.push(ctx.path);\n const wait = state.delay?.(ctx.path);\n if (wait) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n const fault = state.fault?.(ctx.path);\n if (fault !== undefined) {\n throw fault;\n }\n const response = state.respond?.(ctx.path, ctx.headers);\n if (response !== undefined) {\n return response;\n }\n }),\n },\n ],\n after: [\n {\n matcher: () => true,\n handler: createAuthMiddleware(async (ctx) => {\n state.refresh.push({\n path: ctx.path,\n skip: (await getShouldSkipSessionRefresh()) === true,\n });\n const header = state.responseHeader?.(ctx.path);\n if (header) {\n ctx.setHeader(header[0], header[1]);\n }\n const setCookies =\n ctx.context.responseHeaders?.getSetCookie() ?? [];\n if (setCookies.length) {\n state.produced.push({\n path: ctx.path,\n setCookies,\n headers: ctx.headers ? new Headers(ctx.headers) : undefined,\n sessionCookie: ctx.context.authCookies.sessionToken.name,\n });\n }\n }),\n },\n ],\n },\n } satisfies BetterAuthPlugin;\n Object.defineProperty(plugin, PROBE_STATE, { value: state });\n return plugin;\n}\n\n/** A TEST-NET-2 address that no kit request sends and no kit configuration trusts. */\nconst IP_SENTINEL = \"198.51.100.254\";\nconst IP_SENTINEL_HEADER = \"x-conformance-ip-sentinel\";\n\n/**\n * The client IP Better Auth resolves from the request's IP headers, without the localhost fallback getIP() returns\n * under NODE_ENV=development/test or a truthy TEST (vitest sets it): the sentinel header is read last, so getIP()\n * returns the sentinel exactly when the configured headers yield no trusted address.\n */\nfunction resolvedIp(request: Request, options: BetterAuthOptions) {\n const ipAddress = options.advanced?.ipAddress;\n const headers = new Headers(request.headers);\n headers.set(IP_SENTINEL_HEADER, IP_SENTINEL);\n const ip = getIP(headers, {\n ...options,\n advanced: {\n ...options.advanced,\n ipAddress: {\n ...ipAddress,\n ipAddressHeaders: [\n ...(ipAddress?.ipAddressHeaders ?? [\"x-forwarded-for\"]),\n IP_SENTINEL_HEADER,\n ],\n },\n },\n });\n return ip === IP_SENTINEL ? null : ip;\n}\n\n/** The probe state of an instance that includes conformanceProbePlugin(). */\nexport async function probeOf(auth: AuthLike): Promise<ProbeState> {\n const context = (await auth.$context) as { getPlugin(id: string): unknown };\n const plugin = context.getPlugin(PROBE_PLUGIN_ID);\n const state =\n plugin && typeof plugin === \"object\"\n ? (Reflect.get(plugin, PROBE_STATE) as ProbeState | undefined)\n : undefined;\n if (!state) {\n throw new BetterAuthConfigurationError(\n \"CONFORMANCE_PROBE_MISSING\",\n \"The conformance kits need conformanceProbePlugin() on the Better Auth instance.\",\n \"Create the instance with createConformanceAuth() or add conformanceProbePlugin() before nestjs().\",\n );\n }\n return state;\n}\n\n/**\n * Better Auth's origin-check flags of a conformance instance. Both default to false, so every origin check is on; a\n * caller's `options.advanced` cannot change them, only this argument can.\n */\nexport interface ConformanceAuthSettings {\n /**\n * Better Auth's advanced.disableOriginCheck. true skips Better Auth's own origin validation of its routes; with\n * disableCSRFCheck false the library's application-route checks stay on (BA-r6-01, T-csrf-http-unsafe).\n */\n readonly disableOriginCheck?: boolean;\n /** Better Auth's advanced.disableCSRFCheck. true switches every origin check off, the library's included. */\n readonly disableCSRFCheck?: boolean;\n}\n\n/**\n * A memory-adapter Better Auth instance with the settings the kits assume: origin checks explicitly on\n * (advanced.disableOriginCheck: false, which vitest's TEST=true would otherwise switch off, and\n * advanced.disableCSRFCheck: false, which would otherwise switch every origin check off), session.updateAge 0 so\n * every session read refreshes, testUtils(), bearer(), conformanceProbePlugin() and nestjs() last. The kit settings\n * win over the same options in `options`; `settings` switches the origin checks off explicitly.\n */\nexport function createConformanceAuth(\n options: Omit<BetterAuthOptions, \"database\"> = {},\n settings: ConformanceAuthSettings = {},\n): AuthLike {\n // The probe creates a table for every model of the resolved schema when Better Auth initializes it.\n const tables: Record<string, unknown[]> = {};\n const resolved = {\n secret: globalThis.crypto.randomUUID() + globalThis.crypto.randomUUID(),\n baseURL: KIT_BASE_URL,\n emailAndPassword: { enabled: true },\n logger: { disabled: true },\n ...options,\n session: { ...options.session, updateAge: 0 },\n advanced: {\n ...options.advanced,\n disableOriginCheck: settings.disableOriginCheck === true,\n disableCSRFCheck: settings.disableCSRFCheck === true,\n },\n plugins: [\n testUtils(),\n bearer(),\n probePlugin({ memoryTables: tables }),\n ...(options.plugins ?? []),\n nestjs(),\n ],\n } satisfies BetterAuthOptions;\n return betterAuth<BetterAuthOptions>({\n ...resolved,\n database: memoryAdapter(tables),\n }) as unknown as AuthLike;\n}\n\ninterface TestHelpers {\n createUser(overrides?: Record<string, unknown>): { id: string };\n saveUser(user: { id: string }): Promise<{ id: string }>;\n login(options: { userId: string }): Promise<{\n headers: Headers;\n token: string;\n session: { token: string; expiresAt: Date };\n }>;\n}\n\nexport interface KitIdentity {\n readonly userId: string;\n readonly email: string;\n readonly password?: string;\n /** Cookie header value of a fresh session. */\n readonly cookie: string;\n /** Raw session token for the bearer() plugin. */\n readonly token: string;\n}\n\nexport async function testHelpers(auth: AuthLike): Promise<TestHelpers> {\n const context = (await auth.$context) as { test?: TestHelpers };\n if (!context.test) {\n throw new BetterAuthConfigurationError(\n \"TEST_UTILS_MISSING\",\n \"The conformance kits need Better Auth's testUtils() plugin on the instance.\",\n \"Create the instance with createConformanceAuth() or add testUtils().\",\n );\n }\n return context.test;\n}\n\n/** A stored user with a fresh session; `password` signs the user up through Better Auth instead. */\nexport async function kitIdentity(\n auth: AuthLike,\n options: { password?: boolean; role?: string } = {},\n): Promise<KitIdentity> {\n const helpers = await testHelpers(auth);\n const email = `${globalThis.crypto.randomUUID()}@conformance.example`;\n let userId: string;\n let password: string | undefined;\n if (options.password) {\n password = `pw-${globalThis.crypto.randomUUID()}`;\n const result = (await (\n auth.api as unknown as {\n signUpEmail(input: {\n body: { email: string; password: string; name: string };\n }): Promise<{ user: { id: string } }>;\n }\n ).signUpEmail({ body: { email, password, name: \"Conformance\" } })) as {\n user: { id: string };\n };\n userId = result.user.id;\n } else {\n userId = (\n await helpers.saveUser(\n helpers.createUser({\n email,\n name: \"Conformance\",\n ...(options.role ? { role: options.role } : {}),\n }),\n )\n ).id;\n }\n const login = await helpers.login({ userId });\n return {\n userId,\n email,\n password,\n cookie: login.headers.get(\"cookie\") ?? \"\",\n token: login.token,\n };\n}\n\n/** Build the cases that one kit returns. */\nexport function conformanceCase(\n id: string,\n title: string,\n run: () => Promise<ConformanceOutcome>,\n skip?: string,\n): ConformanceCase {\n return skip === undefined ? { id, title, run } : { id, title, skip, run };\n}\n\n/**\n * Register cases with a runner that has describe/it (vitest, jest, node:test). Cases are grouped by id. A case with\n * `skip` registers a passing test whose name states the reason, so every unsupported capability stays visible. A case\n * that skips at run time calls the runner's context.skip(reason) when the runner passes a context (Vitest, node:test);\n * under Jest it passes.\n */\nexport function runConformance(\n cases: readonly ConformanceCase[],\n runner: ConformanceRunner,\n): void {\n const groups = new Map<string, ConformanceCase[]>();\n for (const item of cases) {\n groups.set(item.id, [...(groups.get(item.id) ?? []), item]);\n }\n for (const [id, items] of groups) {\n runner.describe(id, () => {\n for (const item of items) {\n if (item.skip !== undefined) {\n runner.it(`${item.title} (skipped: ${item.skip})`, async () => {});\n } else {\n // No declared parameters: Jest would treat one as a done callback, and Vitest parses it for fixtures.\n runner.it(item.title, async function () {\n // biome-ignore lint/complexity/noArguments: see above; the runner's test context is the first argument.\n const context = arguments[0] as\n | { skip?: (note?: string) => void }\n | undefined;\n const result = await item.run();\n if (result && typeof result.skipped === \"string\") {\n context?.skip?.(result.skipped);\n }\n });\n }\n }\n });\n }\n}\n\nexport interface LogEntry {\n readonly level: \"log\" | \"error\" | \"warn\" | \"debug\" | \"verbose\" | \"fatal\";\n readonly text: string;\n}\n\nfunction render(value: unknown): string {\n if (value instanceof Error) {\n return inspect(value, { depth: 4 });\n }\n if (typeof value === \"string\") {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/** A Nest logger that records every entry for log assertions. */\nexport class CapturingLogger implements LoggerService {\n readonly entries: LogEntry[] = [];\n\n private record(level: LogEntry[\"level\"], values: unknown[]): void {\n this.entries.push({ level, text: values.map(render).join(\" \") });\n }\n\n log(...values: unknown[]): void {\n this.record(\"log\", values);\n }\n\n error(...values: unknown[]): void {\n this.record(\"error\", values);\n }\n\n warn(...values: unknown[]): void {\n this.record(\"warn\", values);\n }\n\n debug(...values: unknown[]): void {\n this.record(\"debug\", values);\n }\n\n verbose(...values: unknown[]): void {\n this.record(\"verbose\", values);\n }\n\n fatal(...values: unknown[]): void {\n this.record(\"fatal\", values);\n }\n\n errors(): LogEntry[] {\n return this.entries.filter(\n (entry) => entry.level === \"error\" || entry.level === \"fatal\",\n );\n }\n\n text(): string {\n return this.entries.map((entry) => entry.text).join(\"\\n\");\n }\n}\n\nexport interface RawResponse {\n readonly status: number;\n readonly headers: IncomingHttpHeaders;\n readonly body: Buffer;\n}\n\n/**\n * An HTTP/1.1 request through node:http, which adds no fetch metadata (Sec-Fetch-*) and keeps every Set-Cookie line.\n * `chunks` sends a chunked body; `abortAfterFirstChunk` destroys the response after its first data event.\n */\nexport function sendRaw(\n url: string,\n options: {\n method?: string;\n headers?: OutgoingHttpHeaders;\n body?: Uint8Array | string;\n chunks?: readonly (Uint8Array | string)[];\n timeoutMs?: number;\n abortAfterFirstChunk?: boolean;\n } = {},\n): Promise<RawResponse> {\n return new Promise((resolve, reject) => {\n const request = nodeRequest(\n url,\n {\n method: options.method ?? \"GET\",\n headers: options.headers,\n agent: false,\n },\n (response) => {\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer) => {\n chunks.push(chunk);\n if (options.abortAfterFirstChunk) {\n response.destroy();\n resolve({\n status: response.statusCode ?? 0,\n headers: response.headers,\n body: Buffer.concat(chunks),\n });\n }\n });\n response.once(\"error\", reject);\n response.once(\"end\", () =>\n resolve({\n status: response.statusCode ?? 0,\n headers: response.headers,\n body: Buffer.concat(chunks),\n }),\n );\n },\n );\n request.setTimeout(options.timeoutMs ?? 5_000, () => {\n request.destroy(new Error(`Request to ${url} timed out`));\n });\n request.once(\"error\", reject);\n if (options.chunks) {\n for (const chunk of options.chunks) {\n request.write(chunk);\n }\n } else if (options.body !== undefined) {\n request.write(options.body);\n }\n request.end();\n });\n}\n\nexport function setCookieLines(headers: IncomingHttpHeaders): string[] {\n const value = headers[\"set-cookie\"];\n return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\nexport async function settle<T>(\n fn: () => Promise<T>,\n): Promise<{ ok: true; value: T } | { ok: false; error: unknown }> {\n try {\n return { ok: true, value: await fn() };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/** Collect issue codes from an AUTH_BOOT_FAILED error (or the codes of a single configuration error). */\nexport function bootIssueCodes(error: unknown): string[] {\n const codes: string[] = [];\n const visit = (value: unknown) => {\n if (!value || typeof value !== \"object\") {\n return;\n }\n const code = Reflect.get(value, \"code\");\n if (typeof code === \"string\") {\n codes.push(code);\n }\n const issues = Reflect.get(value, \"issues\");\n if (Array.isArray(issues)) {\n issues.forEach(visit);\n }\n };\n visit(error);\n return codes;\n}\n","import assert from \"node:assert/strict\";\nimport { IncomingMessage } from \"node:http\";\nimport { connect } from \"node:http2\";\nimport { Socket } from \"node:net\";\nimport {\n Body,\n Catch,\n Controller,\n Get,\n Injectable,\n Module,\n Post,\n Req,\n RequestMethod,\n Res,\n UseGuards,\n UseInterceptors,\n VersioningType,\n type ArgumentsHost,\n type CallHandler,\n type CanActivate,\n type DynamicModule,\n type ExecutionContext,\n type INestApplication,\n type INestMicroservice,\n type MiddlewareConsumer,\n type NestInterceptor,\n type NestModule,\n type OnApplicationShutdown,\n type Type,\n} from \"@nestjs/common\";\nimport {\n APP_FILTER,\n BaseExceptionFilter,\n NestFactory,\n type AbstractHttpAdapter,\n} from \"@nestjs/core\";\nimport { Test } from \"@nestjs/testing\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport { APIError, isAPIError } from \"better-auth/api\";\nimport type { Observable } from \"rxjs\";\nimport type {\n AuthHandlerInterceptor,\n BetterAuthRuntimeOptions,\n ExtensionRef,\n HttpPlatform,\n HttpRequestAccessor,\n} from \"./auth-contracts.js\";\nimport {\n BeforeAuth,\n CurrentPrincipal,\n Public,\n RequireAuth,\n} from \"./auth-decorators.js\";\nimport { isInfrastructureError } from \"./auth-errors.js\";\nimport { BetterAuthModule } from \"./auth-module.js\";\nimport { MOUNT_COORDINATOR } from \"./auth-tokens.js\";\nimport type { AuthHookContext, AuthLike, AuthPrincipal } from \"./auth-types.js\";\nimport {\n BRIDGE_HANDLE,\n type BridgeHandle,\n EXTENSION_DEFINITION,\n} from \"./bridge-protocol.js\";\nimport {\n bootIssueCodes,\n CapturingLogger,\n type ConformanceCase,\n conformanceCase,\n conformanceSkip,\n type ConformanceOutcome,\n type ConformanceSkip,\n createConformanceAuth,\n KIT_BASE_URL,\n kitIdentity,\n probeOf,\n type ProbeState,\n type RawResponse,\n sendRaw,\n setCookieLines,\n settle,\n} from \"./conformance-fixtures.js\";\nimport type { MountCoordinator } from \"./mount-coordinator.js\";\n\nexport interface HttpConformanceOptions {\n platform: ExtensionRef<HttpPlatform>;\n /** Fresh Nest HTTP adapter per app, e.g. () => new ExpressAdapter(). */\n createHttpAdapter(): AbstractHttpAdapter;\n /** Bootstraps to exercise. Default both. */\n bootstrap?: readonly (\"factory\" | \"testing\")[];\n /** Enable host CORS the platform's usual way. Default: app.enableCors({ origin, credentials: true }). */\n enableHostCors?(app: INestApplication, origin: string): void | Promise<void>;\n /**\n * Configure trust in one forwarding hop on a created application the platform's usual way, e.g. app.set('trust proxy',\n * 1). The trusted-hop rows (H-ip-platform, H-proxy-trust, H-url-trust-proxy, H-proxy-untrusted-warning) need this or\n * createTrustingHttpAdapter; without either they are skipped with the reason.\n */\n trustOneProxy?(app: INestApplication): void | Promise<void>;\n /**\n * A fresh adapter that already trusts one forwarding hop, for platforms whose proxy trust is fixed when the adapter is\n * constructed, e.g. () => new FastifyAdapter({ trustProxy: 'loopback' }). The kit's requests come from loopback, so\n * trusting loopback is trusting one hop. Trusted-hop boots use it when given, instead of createHttpAdapter plus\n * trustOneProxy.\n */\n createTrustingHttpAdapter?(): AbstractHttpAdapter;\n /**\n * HTTP/2 variant, required when the platform declares capabilities.http2. Its createTrustingHttpAdapter serves the\n * HTTP/2 trusted-hop rows as createTrustingHttpAdapter serves the HTTP/1.1 ones.\n */\n http2?: {\n createHttpAdapter(): AbstractHttpAdapter;\n createTrustingHttpAdapter?(): AbstractHttpAdapter;\n };\n /** How to obtain a base URL. Default: app.listen(0) + getUrl(). */\n listen?(app: INestApplication): Promise<string>;\n /**\n * Transport options for the H-no-adapter microservice rows, e.g. () => ({ transport: Transport.TCP, options: { host:\n * '127.0.0.1', port: 0 } }). The kit does not load the optional @nestjs/microservices peer itself; without this option\n * those rows are skipped with the reason.\n */\n microservice?(): MicroserviceOptions;\n}\n\n/** The options NestFactory.createMicroservice() and TestingModule.createNestMicroservice() accept. */\ntype MicroserviceOptions = NonNullable<\n Parameters<typeof NestFactory.createMicroservice>[1]\n>;\n\ntype Bootstrap = \"factory\" | \"testing\";\nconst AUTH = \"/api/auth\";\nconst DYNAMIC_AUTH = \"/tenant/auth\";\n/** The client IP of the kit's requests: baseUrl() always connects over IPv4 loopback. */\nconst LOOPBACK = \"127.0.0.1\";\nconst CORS_ORIGIN = \"https://app.example\";\n/** Makes the kit's `around` interceptor throw, so auth.handler rejects with a non-APIError. */\nconst THROW_HEADER = \"x-conformance-throw\";\nconst SDK_HEADERS = Symbol.for(\"better-call:api-error-headers\");\nconst CANONICAL_413 = JSON.stringify({\n code: \"PAYLOAD_TOO_LARGE\",\n message: \"Request body exceeds the configured limit\",\n});\n\ninterface BootConfig {\n auth?: Omit<BetterAuthOptions, \"database\">;\n module?: Partial<BetterAuthRuntimeOptions<AuthLike>>;\n async?: boolean;\n duplicateForRoot?: boolean;\n cors?: boolean;\n prefix?: string;\n versioning?: boolean;\n middleware?: boolean;\n http2?: boolean;\n trustProxy?: boolean;\n /** Boot on this instance instead of a fresh createConformanceAuth(config.auth). */\n instance?: AuthLike;\n /** Receives the paths the kit's @BeforeAuth() hook provider sees. */\n hooks?: string[];\n /** Runs in the kit root module's onApplicationShutdown hook. */\n onShutdown?(): Promise<void>;\n}\n\ninterface AccessorObservation {\n guardKey?: object;\n interceptorKey?: object;\n handlerKey?: object;\n isRequest?: boolean;\n rejectsPlain?: boolean;\n rejectsUpgrade?: boolean;\n liveInHandler?: boolean;\n request?: unknown;\n sinkAppended?: boolean;\n}\n\ninterface HttpBoot {\n readonly app: INestApplication;\n readonly url: string;\n /** Whether the app serves h2c (config.http2). */\n readonly http2: boolean;\n readonly auth: AuthLike;\n readonly probe: ProbeState;\n readonly logger: CapturingLogger;\n readonly filtered: unknown[];\n readonly around: string[];\n readonly accessor: AccessorObservation;\n requests(): HttpRequestAccessor;\n close(): Promise<void>;\n}\n\nfunction resolvedPlatform(app: INestApplication): HttpPlatform {\n const coordinator = app.get<MountCoordinator>(MOUNT_COORDINATOR, {\n strict: false,\n });\n const platform = coordinator.platform;\n assert.ok(platform, \"the application selected no HTTP platform\");\n return platform;\n}\n\n/**\n * The capabilities a platform reference declares, when that is known without booting: a platform object without\n * `capabilities` declares none. Undefined means unknown (a class whose instances may set it, or a definition).\n */\nfunction declaredCapabilities(\n ref: ExtensionRef<HttpPlatform>,\n): HttpPlatform[\"capabilities\"] | undefined {\n if (typeof ref === \"function\") {\n try {\n return (ref as unknown as { prototype: HttpPlatform }).prototype\n ?.capabilities;\n } catch {\n return undefined;\n }\n }\n if (ref && typeof ref === \"object\" && !(EXTENSION_DEFINITION in ref)) {\n return (ref as Partial<HttpPlatform>).capabilities ?? {};\n }\n return undefined;\n}\n\n/** true/false when a platform member is statically known, undefined for definitions. */\nfunction staticMember(\n ref: ExtensionRef<HttpPlatform>,\n name: keyof HttpPlatform,\n): boolean | undefined {\n if (typeof ref === \"function\") {\n return typeof Reflect.get(ref.prototype as object, name) === \"function\"\n ? true\n : undefined;\n }\n if (ref && typeof ref === \"object\" && !(EXTENSION_DEFINITION in ref)) {\n return typeof Reflect.get(ref, name) === \"function\";\n }\n return undefined;\n}\n\nasync function capabilitiesOf(\n options: HttpConformanceOptions,\n): Promise<HttpPlatform[\"capabilities\"]> {\n const declared = declaredCapabilities(options.platform);\n if (declared) {\n return declared;\n }\n const boot = await bootHttp(options, \"testing\", {});\n try {\n return resolvedPlatform(boot.app).capabilities;\n } finally {\n await boot.close();\n }\n}\n\nfunction kitModule(\n options: HttpConformanceOptions,\n auth: AuthLike,\n probe: ProbeState,\n config: BootConfig,\n state: {\n filtered: unknown[];\n around: string[];\n accessor: AccessorObservation;\n requests(): HttpRequestAccessor;\n adapter(): AbstractHttpAdapter;\n /** Paths the kit's @BeforeAuth() hook provider saw. */\n hooks?: string[];\n },\n): Type {\n const hooks = state.hooks ?? config.hooks;\n const record: AuthHandlerInterceptor = async (call, next) => {\n state.around.push(\n `${call.request.method.toUpperCase()} ${new URL(call.request.url).pathname}`,\n );\n const failure = call.request.headers.get(THROW_HEADER);\n if (failure === \"api-error\") {\n const error = new APIError(\"BAD_REQUEST\", {\n code: \"CONFORMANCE_API_ERROR\",\n message: \"Conformance API error\",\n });\n Object.defineProperty(error, SDK_HEADERS, {\n value: new Headers({ \"set-cookie\": \"conformance_cleared=; Max-Age=0\" }),\n });\n throw error;\n }\n if (failure) {\n throw new Error(\"conformance exchange failure\");\n }\n return next();\n };\n const { http, ...runtime } = config.module ?? {};\n const moduleOptions = {\n logSummary: false,\n ...runtime,\n http: { ...http, around: [record, ...(http?.around ?? [])] },\n };\n const imports: DynamicModule[] = [];\n if (config.async) {\n const DEPENDENCY = Symbol(\"conformance-async-dependency\");\n @Module({\n providers: [\n {\n provide: DEPENDENCY,\n useFactory: async () => {\n await new Promise((resolve) => setTimeout(resolve, 20));\n return { auth };\n },\n },\n ],\n exports: [DEPENDENCY],\n })\n class AsyncDependencyModule {}\n imports.push(\n BetterAuthModule.forRootAsync({\n platforms: [options.platform],\n imports: [AsyncDependencyModule],\n inject: [DEPENDENCY],\n useFactory: async (dependency: { auth: AuthLike }) => ({\n ...moduleOptions,\n auth: dependency.auth,\n }),\n }),\n );\n } else {\n imports.push(\n BetterAuthModule.forRoot({\n ...moduleOptions,\n auth,\n platforms: [options.platform],\n } as never),\n );\n }\n if (config.duplicateForRoot) {\n imports.push(\n BetterAuthModule.forRoot({ auth, logSummary: false } as never),\n );\n }\n const guard: CanActivate = {\n canActivate(context: ExecutionContext) {\n state.accessor.guardKey = state\n .requests()\n .key(context.switchToHttp().getRequest());\n return true;\n },\n };\n const interceptor: NestInterceptor = {\n intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable<unknown> {\n state.accessor.interceptorKey = state\n .requests()\n .key(context.switchToHttp().getRequest());\n return next.handle();\n },\n };\n\n @Controller()\n class ConformanceAppController {\n @Public()\n @Post(\"app/echo\")\n echo(@Body() body: unknown, @Req() request: { rawBody?: Buffer }) {\n return {\n body,\n rawBody: request.rawBody\n ? Buffer.from(request.rawBody).toString(\"utf8\")\n : null,\n };\n }\n\n @Public()\n @Get(\"app/ping\")\n ping() {\n return { pong: true };\n }\n\n @Public()\n @Get(\"api/auth/app-owned\")\n owned() {\n return { owner: \"app\" };\n }\n\n @Get(\"app/me\")\n me(@CurrentPrincipal() principal: AuthPrincipal | null) {\n return { userId: principal?.userId ?? null };\n }\n\n @RequireAuth({ authoritative: true })\n @Get(\"app/authoritative\")\n authoritative(@CurrentPrincipal() principal: AuthPrincipal | null) {\n return { userId: principal?.userId ?? null };\n }\n\n @Public()\n @UseGuards(guard)\n @UseInterceptors(interceptor)\n @Get(\"app/accessor\")\n accessor(\n @Req() request: unknown,\n @Res({ passthrough: true }) response: unknown,\n ) {\n const requests = state.requests();\n const observed = state.accessor;\n observed.handlerKey = requests.key(request);\n observed.isRequest = requests.isRequest(request);\n observed.rejectsPlain = !requests.isRequest({\n headers: { host: \"localhost\" },\n url: \"/app/accessor\",\n method: \"GET\",\n });\n observed.rejectsUpgrade = !requests.isRequest(\n new IncomingMessage(new Socket()),\n );\n observed.liveInHandler = requests.isLive(request);\n observed.request = request;\n observed.sinkAppended =\n requests\n .cookieSink(request, response)\n ?.append([\"kit_sink=1; Path=/\"]) ?? false;\n state\n .adapter()\n .appendHeader(response, \"Set-Cookie\", \"kit_handler=1; Path=/\");\n return { ok: true };\n }\n }\n\n @Injectable()\n class ConformanceHookProvider {\n @BeforeAuth(\"/probe/html\")\n record(_context: AuthHookContext<\"/probe/html\">): void {\n hooks?.push(\"/probe/html\");\n }\n }\n\n @Catch()\n class ConformanceRecordingFilter extends BaseExceptionFilter {\n override catch(exception: unknown, host: ArgumentsHost): void {\n state.filtered.push(exception);\n super.catch(exception, host);\n }\n }\n\n @Module({\n imports,\n controllers: [ConformanceAppController],\n providers: [\n ConformanceHookProvider,\n { provide: APP_FILTER, useClass: ConformanceRecordingFilter },\n ],\n })\n class ConformanceHttpModule implements NestModule, OnApplicationShutdown {\n configure(consumer: MiddlewareConsumer): void {\n if (config.middleware) {\n consumer\n .apply((_request: unknown, _response: unknown, next: () => void) => {\n probe.order.push(\"middleware\");\n next();\n })\n .forRoutes({ path: \"*path\", method: RequestMethod.ALL });\n }\n }\n\n async onApplicationShutdown(): Promise<void> {\n await config.onShutdown?.();\n }\n }\n return ConformanceHttpModule;\n}\n\n/** The factory of an adapter that trusts one forwarding hop, for HTTP/1.1 or HTTP/2, when the options give one. */\nfunction trustingAdapterOf(\n options: HttpConformanceOptions,\n http2: boolean | undefined,\n): (() => AbstractHttpAdapter) | undefined {\n const source = http2 ? options.http2 : options;\n return source?.createTrustingHttpAdapter\n ? () => source.createTrustingHttpAdapter!()\n : undefined;\n}\n\n/** A fresh adapter for a boot: the trusting adapter for a trusted-hop boot when given, else the default one. */\nfunction createAdapter(\n options: HttpConformanceOptions,\n config: BootConfig,\n): AbstractHttpAdapter {\n const trusting = config.trustProxy\n ? trustingAdapterOf(options, config.http2)\n : undefined;\n if (trusting) {\n return trusting();\n }\n return config.http2\n ? options.http2!.createHttpAdapter()\n : options.createHttpAdapter();\n}\n\nasync function bootHttp(\n options: HttpConformanceOptions,\n bootstrap: Bootstrap,\n config: BootConfig,\n): Promise<HttpBoot> {\n const auth = config.instance ?? createConformanceAuth(config.auth);\n const probe = await probeOf(auth);\n const logger = new CapturingLogger();\n const filtered: unknown[] = [];\n const around: string[] = [];\n const accessor: AccessorObservation = {};\n let application: INestApplication | undefined;\n const adapter = createAdapter(options, config);\n const requests = () => resolvedPlatform(application!).requests;\n const module = kitModule(options, auth, probe, config, {\n filtered,\n around,\n accessor,\n requests,\n adapter: () => adapter,\n });\n const appOptions = { logger, rawBody: true, abortOnError: false };\n let app: INestApplication;\n if (bootstrap === \"factory\") {\n app = await NestFactory.create(module, adapter, appOptions);\n } else {\n const moduleRef = await Test.createTestingModule({\n imports: [module],\n }).compile();\n app = moduleRef.createNestApplication(adapter, appOptions);\n }\n application = app;\n try {\n if (config.cors) {\n if (options.enableHostCors) {\n await options.enableHostCors(app, CORS_ORIGIN);\n } else {\n app.enableCors({ origin: CORS_ORIGIN, credentials: true });\n }\n }\n if (config.prefix) {\n app.setGlobalPrefix(config.prefix);\n }\n if (config.versioning) {\n app.enableVersioning({ type: VersioningType.URI });\n }\n if (config.trustProxy && !trustingAdapterOf(options, config.http2)) {\n assert.ok(\n options.trustOneProxy,\n \"trustOneProxy or createTrustingHttpAdapter is required here\",\n );\n await options.trustOneProxy(app);\n }\n await app.init();\n const url = await baseUrl(options, app);\n return {\n app,\n url,\n http2: config.http2 === true,\n auth,\n probe,\n logger,\n filtered,\n around,\n accessor,\n requests,\n close: () => app.close(),\n };\n } catch (error) {\n await app.close().catch(() => undefined);\n throw error;\n }\n}\n\n/** The base URL of an initialized app: the `listen` option, or listen(0) and getUrl(), normalized. */\nasync function baseUrl(\n options: HttpConformanceOptions,\n app: INestApplication,\n): Promise<string> {\n let url: string;\n if (options.listen) {\n url = await options.listen(app);\n } else {\n await app.listen(0, \"127.0.0.1\");\n url = await app.getUrl();\n }\n return url.replace(\"[::1]\", \"127.0.0.1\").replace(/\\/$/, \"\");\n}\n\nasync function withBoot(\n options: HttpConformanceOptions,\n bootstrap: Bootstrap,\n config: BootConfig,\n fn: (boot: HttpBoot) => Promise<ConformanceOutcome>,\n): Promise<ConformanceOutcome> {\n const boot = await bootHttp(options, bootstrap, config);\n try {\n return await fn(boot);\n } finally {\n await boot.close();\n }\n}\n\nfunction json(response: RawResponse): Record<string, unknown> {\n return JSON.parse(response.body.toString(\"utf8\")) as Record<string, unknown>;\n}\n\nasync function echo(\n boot: HttpBoot,\n body: Uint8Array | string | undefined,\n headers: Record<string, string>,\n chunks?: readonly (Uint8Array | string)[],\n): Promise<{ bytes: Buffer; headers: Map<string, string>; status: number }> {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/echo-raw`, {\n method: \"POST\",\n headers: { origin: KIT_BASE_URL, ...headers },\n body,\n chunks,\n });\n assert.equal(\n response.status,\n 200,\n `echo-raw answered ${response.status}: ${response.body.toString(\"utf8\")}`,\n );\n const value = json(response) as {\n body: string;\n headers: [string, string][];\n };\n return {\n status: response.status,\n bytes: Buffer.from(value.body, \"base64\"),\n headers: new Map(value.headers),\n };\n}\n\nfunction bodyCase(\n id: string,\n title: string,\n body: () => {\n bytes?: Uint8Array | string;\n chunks?: readonly (Uint8Array | string)[];\n contentType?: string;\n headers?: Record<string, string>;\n },\n) {\n return async (options: HttpConformanceOptions, bootstrap: Bootstrap) =>\n withBoot(options, bootstrap, {}, async (boot) => {\n const input = body();\n const expected = Buffer.concat(\n (input.chunks ?? (input.bytes === undefined ? [] : [input.bytes])).map(\n (chunk) => Buffer.from(chunk),\n ),\n );\n const headers: Record<string, string> = { ...input.headers };\n if (input.contentType) {\n headers[\"content-type\"] = input.contentType;\n }\n if (!input.chunks) {\n headers[\"content-length\"] = String(expected.length);\n }\n const result = await echo(boot, input.bytes, headers, input.chunks);\n assert.deepEqual(\n [...result.bytes],\n [...expected],\n `${id}: ${title} bytes changed`,\n );\n assert.equal(\n result.headers.get(\"content-type\") ?? null,\n input.contentType ?? null,\n `${id}: content-type changed`,\n );\n });\n}\n\nasync function waitFor(\n predicate: () => boolean,\n message: string,\n timeoutMs = 2_000,\n): Promise<void> {\n const started = Date.now();\n while (!predicate()) {\n if (Date.now() - started > timeoutMs) {\n assert.fail(message);\n }\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n}\n\n/**\n * Runs `fn` with process.env.NODE_ENV set to `value`, then restores it. The kit's production-mode rows use it: the\n * library treats every NODE_ENV except development, dev and test as production (§5.4). Run kit cases sequentially.\n */\nasync function withNodeEnv<T>(value: string, fn: () => Promise<T>): Promise<T> {\n const previous = process.env.NODE_ENV;\n process.env.NODE_ENV = value;\n try {\n return await fn();\n } finally {\n if (previous === undefined) {\n Reflect.deleteProperty(process.env, \"NODE_ENV\");\n } else {\n process.env.NODE_ENV = previous;\n }\n }\n}\n\nconst inProduction = <T>(fn: () => Promise<T>) => withNodeEnv(\"production\", fn);\n\n/** The per-IP rule the rate-limit rows apply to /probe/ip, counted in a per-boot store that records every key. */\nconst IP_RULE = { window: 60, max: 2 } as const;\n\nfunction rateLimited(keys: string[]): BootConfig {\n const counts = new Map<string, number>();\n return {\n auth: {\n rateLimit: {\n enabled: true,\n customRules: { \"/probe/ip\": IP_RULE },\n customStorage: {\n async consume(key, rule) {\n keys.push(key);\n const count = (counts.get(key) ?? 0) + 1;\n counts.set(key, count);\n return count > rule.max\n ? { allowed: false, retryAfter: rule.window }\n : { allowed: true, retryAfter: null };\n },\n },\n },\n },\n };\n}\n\n/** Better Auth trustedProxies covering every loopback address the kit's requests come from. */\nconst loopbackProxies: BootConfig = {\n auth: {\n advanced: { ipAddress: { trustedProxies: [\"127.0.0.0/8\", \"::1/128\"] } },\n },\n};\n\nfunction warningsWith(boot: HttpBoot, ...parts: string[]): string[] {\n return boot.logger.entries\n .filter(\n (entry) =>\n entry.level === \"warn\" &&\n parts.every((part) => entry.text.includes(part)),\n )\n .map((entry) => entry.text);\n}\n\nfunction http2Origin(boot: HttpBoot): string {\n return boot.url.replace(/^https?:/, \"http:\");\n}\n\nfunction http2Request(\n origin: string,\n headers: Record<string, string>,\n body?: string,\n): Promise<{ status: number; body: Buffer }> {\n return new Promise((resolve, reject) => {\n const session = connect(origin);\n const chunks: Buffer[] = [];\n let status = 0;\n const fail = (error: Error) => {\n session.close();\n reject(error);\n };\n session.once(\"error\", fail);\n const stream = session.request(headers);\n stream.once(\"error\", fail);\n stream.once(\"response\", (received) => {\n status = Number(received[\":status\"] ?? 0);\n });\n stream.on(\"data\", (chunk: Buffer) => chunks.push(Buffer.from(chunk)));\n stream.once(\"end\", () => {\n session.close();\n resolve({ status, body: Buffer.concat(chunks) });\n });\n stream.end(body);\n });\n}\n\nconst multipartBoundary = \"----conformance-boundary\";\nconst multipartBody = [\n `--${multipartBoundary}\\r\\n`,\n 'Content-Disposition: form-data; name=\"field\"\\r\\n\\r\\n',\n \"value with spaces\\r\\n\",\n `--${multipartBoundary}\\r\\n`,\n 'Content-Disposition: form-data; name=\"file\"; filename=\"a.bin\"\\r\\n',\n \"Content-Type: application/octet-stream\\r\\n\\r\\n\",\n \"\\u0000\\u0001\\u0002\\r\\n\",\n `--${multipartBoundary}--\\r\\n`,\n].join(\"\");\n\ntype PerBootstrap = (\n options: HttpConformanceOptions,\n bootstrap: Bootstrap,\n) => Promise<ConformanceOutcome>;\n\n/**\n * The HTTP platform kit (invariants H1–H14). Each case boots a real Nest application per bootstrap with a real Better\n * Auth instance that includes conformanceProbePlugin(), an app controller, a @BeforeAuth() hook provider, a recording\n * global filter and an `around` recorder. HTTP/2 is required when the platform declares capabilities.http2. A platform\n * without the capability or the optional proxyTrust(), and a harness with neither trustOneProxy nor\n * createTrustingHttpAdapter for the trusted-hop rows, get a skip with the reason: before the run for platform objects,\n * at run time for classes and definitions. The microservice rows of H-no-adapter need the\n * `microservice` option. Production-mode rows set process.env.NODE_ENV to 'production' while they run and restore it,\n * so run the cases sequentially.\n */\nexport function httpPlatformConformance(\n options: HttpConformanceOptions,\n): ConformanceCase[] {\n const bootstraps = options.bootstrap ?? [\"factory\", \"testing\"];\n const cases: ConformanceCase[] = [];\n const add = (\n id: string,\n title: string,\n run: PerBootstrap,\n only?: (bootstrap: Bootstrap) => string | undefined,\n ) => {\n for (const bootstrap of bootstraps) {\n cases.push(\n conformanceCase(\n id,\n `${title} [${bootstrap}]`,\n () => run(options, bootstrap),\n only?.(bootstrap),\n ),\n );\n }\n };\n const noHttp2 = () =>\n declaredCapabilities(options.platform) !== undefined &&\n !declaredCapabilities(options.platform)?.http2\n ? \"the platform declares no http2 capability\"\n : undefined;\n /** A skip when the resolved platform declares no http2 capability; requires the http2 option when it does. */\n const http2Ready = async (\n o: HttpConformanceOptions,\n ): Promise<ConformanceSkip | undefined> => {\n const capabilities = await capabilitiesOf(o);\n if (!capabilities?.http2) {\n return conformanceSkip(\"the platform declares no http2 capability\");\n }\n assert.ok(\n o.http2,\n \"the platform declares capabilities.http2, so the kit requires the http2 option\",\n );\n return undefined;\n };\n const noProxyTrust = () =>\n staticMember(options.platform, \"proxyTrust\") === false\n ? \"the platform does not implement the optional proxyTrust()\"\n : undefined;\n /** A skip when neither trustOneProxy nor the protocol's createTrustingHttpAdapter can make a trusted-hop boot. */\n const noTrustHook = (http2 = false) =>\n options.trustOneProxy || trustingAdapterOf(options, http2)\n ? undefined\n : http2\n ? \"neither trustOneProxy nor http2.createTrustingHttpAdapter was given\"\n : \"neither trustOneProxy nor createTrustingHttpAdapter was given\";\n /** The static skip of a trusted-hop row: the HTTP/2 row also needs the http2 capability. */\n const trustedHop = (http2: boolean) => () =>\n (http2 ? noHttp2() : undefined) ?? noTrustHook(http2);\n /** The run-time skip of a trusted-hop row, decided from the resolved platform for HTTP/2. */\n const trustedHopReady = async (\n o: HttpConformanceOptions,\n http2: boolean,\n ): Promise<ConformanceSkip | undefined> =>\n http2 ? http2Ready(o) : undefined;\n const overHttp2 = (http2: boolean, title: string) =>\n http2 ? `over HTTP/2, ${title}` : title;\n\n add(\n \"H-mount-methods\",\n \"every method under the base path reaches Better Auth\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n for (const method of [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"HEAD\",\n \"OPTIONS\",\n ]) {\n await sendRaw(`${boot.url}${AUTH}/probe/echo-raw`, {\n method,\n headers: { origin: KIT_BASE_URL, \"content-length\": \"0\" },\n });\n assert.ok(\n boot.around.includes(`${method} ${AUTH}/probe/echo-raw`),\n `${method} did not reach the auth exchange (saw ${boot.around.join(\", \")})`,\n );\n }\n }),\n );\n add(\n \"H-mount-boundary\",\n \"the bare base path is mounted, /api/authx falls through, and other controllers work\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n await sendRaw(`${boot.url}${AUTH}`);\n assert.ok(\n boot.around.includes(`GET ${AUTH}`),\n \"the bare base path did not reach Better Auth\",\n );\n const adjacent = await sendRaw(`${boot.url}/api/authx`);\n assert.equal(adjacent.status, 404);\n assert.ok(\n !boot.around.some((entry) => entry.includes(\"/api/authx\")),\n \"/api/authx reached Better Auth\",\n );\n const ping = await sendRaw(`${boot.url}/app/ping`);\n assert.equal(ping.status, 200);\n assert.deepEqual(json(ping), { pong: true });\n }),\n );\n add(\n \"H-mount-custom-path\",\n \"basePath and baseURL paths mount there, unaffected by a global prefix and URI versioning\",\n async (o, b) => {\n await withBoot(\n o,\n b,\n {\n auth: { basePath: \"/custom/auth\" },\n prefix: \"v1\",\n versioning: true,\n },\n async (boot) => {\n const response = await sendRaw(`${boot.url}/custom/auth/probe/html`);\n assert.equal(response.status, 200);\n assert.equal(response.body.toString(\"utf8\"), \"<p>probe</p>\");\n const ping = await sendRaw(`${boot.url}/v1/app/ping`);\n assert.equal(ping.status, 200);\n const prefixed = await sendRaw(\n `${boot.url}/v1/custom/auth/probe/html`,\n );\n assert.notEqual(prefixed.status, 200);\n },\n );\n await withBoot(\n o,\n b,\n { auth: { baseURL: `${KIT_BASE_URL}/base/auth` } },\n async (boot) => {\n const response = await sendRaw(`${boot.url}/base/auth/probe/html`);\n assert.equal(response.status, 200);\n },\n );\n },\n );\n const dynamicHosts = [new URL(KIT_BASE_URL).host, \"tenant.example\"];\n const dynamicMount: BootConfig = {\n auth: {\n baseURL: { allowedHosts: dynamicHosts, fallback: KIT_BASE_URL },\n basePath: DYNAMIC_AUTH,\n },\n prefix: \"v1\",\n versioning: true,\n };\n const assertDynamicUrl = (value: unknown, host: string) => {\n const url = new URL(String(value));\n assert.equal(\n url.host,\n host,\n `the request URL lost the allowed host ${host}`,\n );\n assert.equal(url.pathname, `${DYNAMIC_AUTH}/probe/url`);\n };\n add(\n \"H-mount-custom-path\",\n \"a dynamic allowedHosts baseURL mounts at basePath for every allowed host, unaffected by a global prefix and URI versioning\",\n (o, b) =>\n withBoot(o, b, dynamicMount, async (boot) => {\n for (const host of dynamicHosts) {\n const response = await sendRaw(\n `${boot.url}${DYNAMIC_AUTH}/probe/url`,\n {\n headers: { host },\n },\n );\n assert.equal(\n response.status,\n 200,\n `${host}: ${response.body.toString(\"utf8\").slice(0, 200)}`,\n );\n assertDynamicUrl(json(response).url, host);\n }\n const ping = await sendRaw(`${boot.url}/v1/app/ping`);\n assert.equal(ping.status, 200);\n const prefixed = await sendRaw(\n `${boot.url}/v1${DYNAMIC_AUTH}/probe/html`,\n );\n assert.notEqual(prefixed.status, 200);\n const fallthrough = await sendRaw(`${boot.url}${AUTH}/probe/html`);\n assert.equal(fallthrough.status, 404);\n assert.ok(\n !boot.around.some((entry) => entry.includes(AUTH)),\n `the default base path reached Better Auth: ${boot.around.join(\", \")}`,\n );\n }),\n );\n add(\n \"H-mount-custom-path\",\n \"over HTTP/2, a dynamic allowedHosts baseURL serves the :authority host at basePath\",\n async (o, b) => {\n const skip = await http2Ready(o);\n if (skip) {\n return skip;\n }\n await withBoot(o, b, { ...dynamicMount, http2: true }, async (boot) => {\n const response = await http2Request(http2Origin(boot), {\n \":method\": \"GET\",\n \":path\": `${DYNAMIC_AUTH}/probe/url`,\n \":authority\": \"tenant.example\",\n });\n assert.equal(response.status, 200, response.body.toString(\"utf8\"));\n assertDynamicUrl(\n (JSON.parse(response.body.toString(\"utf8\")) as { url: string }).url,\n \"tenant.example\",\n );\n });\n },\n noHttp2,\n );\n add(\n \"H-app-route-precedence\",\n \"a controller route under the base path is served by Nest\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/app-owned`);\n assert.equal(response.status, 200);\n assert.deepEqual(json(response), { owner: \"app\" });\n assert.ok(\n !boot.around.some((entry) => entry.endsWith(\"/app-owned\")),\n \"Better Auth also saw the controller route\",\n );\n }),\n );\n\n const bodies: [string, string, Parameters<typeof bodyCase>[2]][] = [\n [\n \"H-body-json\",\n \"JSON with odd whitespace and key order\",\n () => ({\n bytes: '{ \"b\" :1,\\n\\t\"a\": [ 2 ,1 ] } ',\n contentType: \"application/json\",\n }),\n ],\n [\n \"H-body-utf8\",\n \"UTF-8 text\",\n () => ({\n bytes: '{\"name\":\"Zoë ✓ 認証 🔐\"}',\n contentType: \"application/json; charset=utf-8\",\n }),\n ],\n [\n \"H-body-urlencoded\",\n \"urlencoded b=%20x&c=1\",\n () => ({\n bytes: \"b=%20x&c=1\",\n contentType: \"application/x-www-form-urlencoded\",\n }),\n ],\n [\n \"H-body-text\",\n \"text/plain\",\n () => ({ bytes: \"plain text\\r\\n\", contentType: \"text/plain\" }),\n ],\n [\n \"H-body-scim\",\n \"application/scim+json\",\n () => ({\n bytes: '{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"]}',\n contentType: \"application/scim+json\",\n }),\n ],\n [\n \"H-body-multipart\",\n \"multipart/form-data\",\n () => ({\n bytes: multipartBody,\n contentType: `multipart/form-data; boundary=${multipartBoundary}`,\n }),\n ],\n [\n \"H-body-binary\",\n \"binary bytes 0x00-0xff\",\n () => ({\n bytes: Uint8Array.from({ length: 256 }, (_, index) => index),\n contentType: \"application/octet-stream\",\n }),\n ],\n [\n \"H-body-chunked\",\n \"a chunked transfer\",\n () => ({\n chunks: ['{\"part\":', '\"one\",', '\"two\":2}'],\n contentType: \"application/json\",\n }),\n ],\n [\n \"H-body-empty\",\n \"an empty body\",\n () => ({ bytes: \"\", contentType: \"application/json\" }),\n ],\n [\n \"H-body-no-content-type\",\n \"a body without content-type\",\n () => ({ bytes: \"raw-bytes\" }),\n ],\n ];\n for (const [id, title, input] of bodies) {\n add(id, `${title} arrives byte-exact`, bodyCase(id, title, input));\n }\n add(\"H-body-form-sign-in\", \"a urlencoded sign-in succeeds\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const identity = await kitIdentity(boot.auth, { password: true });\n const response = await sendRaw(`${boot.url}${AUTH}/sign-in/email`, {\n method: \"POST\",\n headers: {\n origin: KIT_BASE_URL,\n \"content-type\": \"application/x-www-form-urlencoded\",\n },\n body: new URLSearchParams({\n email: identity.email,\n password: identity.password!,\n }).toString(),\n });\n assert.equal(\n response.status,\n 200,\n response.body.toString(\"utf8\").slice(0, 200),\n );\n assert.ok(\n setCookieLines(response.headers).some((line) =>\n line.includes(\"session_token=\"),\n ),\n \"the sign-in set no session cookie\",\n );\n }),\n );\n\n const limited: BootConfig = {\n module: { http: { bodyLimit: 32 } },\n cors: true,\n };\n add(\n \"H-limit-declared\",\n \"a declared over-limit body answers 413 with host CORS headers\",\n (o, b) =>\n withBoot(o, b, limited, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/echo-raw`, {\n method: \"POST\",\n headers: {\n origin: CORS_ORIGIN,\n \"content-type\": \"application/json\",\n \"content-length\": \"40\",\n },\n body: \"x\".repeat(40),\n });\n assert.equal(response.status, 413);\n assert.equal(\n response.headers[\"access-control-allow-origin\"],\n CORS_ORIGIN,\n );\n assert.equal(response.body.toString(\"utf8\"), CANONICAL_413);\n assert.equal(boot.probe.order.length, 0, \"Better Auth was called\");\n }),\n );\n add(\n \"H-limit-chunked\",\n \"a chunked over-limit body answers 413 with host CORS headers\",\n (o, b) =>\n withBoot(o, b, limited, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/echo-raw`, {\n method: \"POST\",\n headers: { origin: CORS_ORIGIN, \"content-type\": \"text/plain\" },\n chunks: [\"x\".repeat(20), \"y\".repeat(20)],\n });\n assert.equal(response.status, 413);\n assert.equal(\n response.headers[\"access-control-allow-origin\"],\n CORS_ORIGIN,\n );\n assert.equal(response.body.toString(\"utf8\"), CANONICAL_413);\n assert.equal(boot.probe.order.length, 0, \"Better Auth was called\");\n }),\n );\n add(\n \"H-limit-canonical-body\",\n \"the limit is exact and the 413 body is canonical\",\n (o, b) =>\n withBoot(o, b, limited, async (boot) => {\n const exact = await sendRaw(`${boot.url}${AUTH}/probe/echo-raw`, {\n method: \"POST\",\n headers: {\n origin: KIT_BASE_URL,\n \"content-type\": \"text/plain\",\n \"content-length\": \"32\",\n },\n body: \"z\".repeat(32),\n });\n assert.equal(exact.status, 200, \"a body at the limit was rejected\");\n const over = await sendRaw(`${boot.url}${AUTH}/probe/echo-raw`, {\n method: \"POST\",\n headers: {\n origin: KIT_BASE_URL,\n \"content-type\": \"text/plain\",\n \"content-length\": \"33\",\n },\n body: \"z\".repeat(33),\n });\n assert.equal(over.status, 413);\n assert.equal(over.body.toString(\"utf8\"), CANONICAL_413);\n }),\n );\n add(\"H-app-parsing\", \"app routes keep Nest body parsing\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}/app/echo`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: '{\"value\":1}',\n });\n assert.equal(response.status, 201);\n assert.deepEqual(json(response).body, { value: 1 });\n }),\n );\n add(\"H-app-rawbody\", \"app routes keep rawBody\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const raw = '{ \"value\" : 2 }';\n const response = await sendRaw(`${boot.url}/app/echo`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: raw,\n });\n assert.equal(json(response).rawBody, raw);\n }),\n );\n add(\"H-url-query\", \"the query string reaches Better Auth unchanged\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const path = `${AUTH}/probe/url?code=abc123&state=xyz%3D`;\n const response = await sendRaw(`${boot.url}${path}`);\n assert.equal(json(response).url, `${KIT_BASE_URL}${path}`);\n }),\n );\n add(\"H-url-encoded\", \"percent-encoding is preserved\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const path = `${AUTH}/probe/url?next=%2Fa%20b%2Bc&mark=%E2%9C%93`;\n const response = await sendRaw(`${boot.url}${path}`);\n assert.equal(json(response).url, `${KIT_BASE_URL}${path}`);\n }),\n );\n add(\n \"H-headers-passthrough\",\n \"browser, credential and content headers arrive unmodified\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const headers = {\n origin: KIT_BASE_URL,\n referer: `${KIT_BASE_URL}/page?x=1`,\n \"sec-fetch-site\": \"same-origin\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-dest\": \"empty\",\n cookie: \"a=1; b=2\",\n authorization: \"Bearer conformance.token\",\n \"content-type\": \"application/json; charset=utf-8\",\n };\n const result = await echo(boot, \"{}\", {\n ...headers,\n \"content-length\": \"2\",\n });\n for (const [name, value] of Object.entries(headers)) {\n assert.equal(result.headers.get(name), value, `${name} changed`);\n }\n }),\n );\n /** GET /probe/ip over the boot's protocol. */\n const probeIp = async (\n boot: HttpBoot,\n headers: Record<string, string> = {},\n ): Promise<{ status: number; ip?: unknown; resolved?: unknown }> => {\n const response = boot.http2\n ? await http2Request(http2Origin(boot), {\n \":method\": \"GET\",\n \":path\": `${AUTH}/probe/ip`,\n ...headers,\n })\n : await sendRaw(`${boot.url}${AUTH}/probe/ip`, { headers });\n return response.status === 200\n ? {\n status: response.status,\n ...(JSON.parse(response.body.toString(\"utf8\")) as object),\n }\n : { status: response.status };\n };\n add(\n \"H-ip-platform\",\n \"Better Auth's getIP sees the platform client IP\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const value = await probeIp(boot);\n assert.equal(\n value.resolved,\n LOOPBACK,\n \"Better Auth resolved no client IP from the request headers the platform set\",\n );\n assert.equal(value.ip, LOOPBACK);\n }),\n );\n add(\n \"H-ip-platform\",\n \"over HTTP/2, Better Auth's getIP sees the platform client IP\",\n async (o, b) => {\n const skip = await http2Ready(o);\n if (skip) {\n return skip;\n }\n await withBoot(o, b, { http2: true }, async (boot) => {\n const response = await http2Request(http2Origin(boot), {\n \":method\": \"GET\",\n \":path\": `${AUTH}/probe/ip`,\n });\n assert.equal(response.status, 200, response.body.toString(\"utf8\"));\n const value = JSON.parse(response.body.toString(\"utf8\")) as {\n resolved: unknown;\n };\n assert.equal(\n value.resolved,\n LOOPBACK,\n \"Better Auth resolved no client IP over HTTP/2\",\n );\n });\n },\n noHttp2,\n );\n const spoofedIp = {\n \"x-forwarded-for\": \"203.0.113.20\",\n \"x-real-ip\": \"203.0.113.21\",\n [`x-nestjs-kit-better-auth-ip-${\"0\".repeat(32)}`]: \"203.0.113.22\",\n };\n add(\n \"H-ip-platform\",\n \"in production mode, the platform IP keys a per-IP rate-limit bucket that client-sent IP headers cannot leave\",\n (o, b) => {\n const keys: string[] = [];\n return inProduction(() =>\n withBoot(o, b, rateLimited(keys), async (boot) => {\n const first = await probeIp(boot);\n assert.equal(first.resolved, LOOPBACK);\n const statuses = [first.status];\n for (let index = 1; index <= IP_RULE.max; index++) {\n statuses.push((await probeIp(boot)).status);\n }\n assert.deepEqual(\n statuses,\n [200, 200, 429],\n `the per-IP rule (max ${IP_RULE.max}) answered ${statuses.join(\", \")}`,\n );\n assert.equal(\n (await probeIp(boot, spoofedIp)).status,\n 429,\n \"client-sent IP headers moved the request out of the platform IP's bucket\",\n );\n assert.deepEqual(\n [...new Set(keys)],\n [`${LOOPBACK}|/probe/ip`],\n \"the rate limiter was not keyed by the platform IP\",\n );\n }),\n );\n },\n );\n for (const http2 of [false, true]) {\n add(\n \"H-ip-platform\",\n overHttp2(\n http2,\n \"in production mode behind a trusted hop, every forwarded client gets its own rate-limit bucket\",\n ),\n async (o, b) => {\n const skip = await trustedHopReady(o, http2);\n if (skip) {\n return skip;\n }\n const keys: string[] = [];\n const [left, right] = [\"203.0.113.30\", \"203.0.113.31\"];\n return inProduction(() =>\n withBoot(\n o,\n b,\n { ...rateLimited(keys), trustProxy: true, http2 },\n async (boot) => {\n const statuses: number[] = [];\n for (let index = 0; index <= IP_RULE.max; index++) {\n statuses.push(\n (await probeIp(boot, { \"x-forwarded-for\": left })).status,\n );\n }\n assert.deepEqual(statuses, [200, 200, 429]);\n const other = await probeIp(boot, { \"x-forwarded-for\": right });\n assert.equal(\n other.status,\n 200,\n \"a second client shared the first client's bucket\",\n );\n assert.equal(other.resolved, right);\n assert.deepEqual([...new Set(keys)].sort(), [\n `${left}|/probe/ip`,\n `${right}|/probe/ip`,\n ]);\n },\n ),\n );\n },\n trustedHop(http2),\n );\n }\n add(\n \"H-ip-platform\",\n \"with trustedProxies covering the platform IP and trust off, Better Auth resolves no IP and B18 warns where proxyTrust() reports 'none'\",\n (o, b) =>\n inProduction(() =>\n withBoot(o, b, loopbackProxies, async (boot) => {\n const value = await probeIp(boot, {\n \"x-forwarded-for\": \"203.0.113.40\",\n });\n assert.equal(\n value.resolved,\n null,\n `Better Auth resolved ${String(value.resolved)} although trustedProxies covers the socket IP`,\n );\n const platform = resolvedPlatform(boot.app);\n const trust = platform.proxyTrust?.(\n boot.app.getHttpAdapter() as AbstractHttpAdapter,\n );\n const b18 = warningsWith(boot, \"W_CLIENT_IP\", \"trustedProxies\");\n if (trust?.mode === \"none\") {\n assert.equal(b18.length, 1, boot.logger.text());\n }\n }),\n ),\n );\n for (const http2 of [false, true]) {\n add(\n \"H-ip-platform\",\n overHttp2(\n http2,\n \"with trustedProxies covering the proxy and trust on, Better Auth resolves the client IP without a B18 warning\",\n ),\n async (o, b) => {\n const skip = await trustedHopReady(o, http2);\n if (skip) {\n return skip;\n }\n return inProduction(() =>\n withBoot(\n o,\n b,\n { ...loopbackProxies, trustProxy: true, http2 },\n async (boot) => {\n const value = await probeIp(boot, {\n \"x-forwarded-for\": \"203.0.113.41\",\n });\n assert.equal(\n value.resolved,\n \"203.0.113.41\",\n \"Better Auth did not resolve the client IP behind the trusted hop\",\n );\n assert.deepEqual(\n warningsWith(boot, \"W_CLIENT_IP\", \"trustedProxies\"),\n [],\n );\n },\n ),\n );\n },\n trustedHop(http2),\n );\n }\n add(\"H-ip-spoof\", \"client-sent client-IP headers are ignored\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/ip`, {\n headers: {\n \"x-forwarded-for\": \"203.0.113.7\",\n \"x-real-ip\": \"203.0.113.8\",\n [`x-nestjs-kit-better-auth-ip-${\"0\".repeat(32)}`]: \"203.0.113.9\",\n },\n });\n const ip = json(response).ip;\n assert.ok(\n ![\"203.0.113.7\", \"203.0.113.8\", \"203.0.113.9\"].includes(String(ip)),\n `a spoofed IP reached Better Auth: ${String(ip)}`,\n );\n }),\n );\n add(\n \"H-proxy-trust\",\n \"proxyTrust() reports the effective setting before and after trusting one hop\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const platform = resolvedPlatform(boot.app);\n if (typeof platform.proxyTrust !== \"function\") {\n return conformanceSkip(\n \"the platform does not implement the optional proxyTrust()\",\n );\n }\n const adapter = boot.app.getHttpAdapter() as AbstractHttpAdapter;\n const before = platform.proxyTrust(adapter);\n let after: ReturnType<typeof platform.proxyTrust>;\n if (o.trustOneProxy) {\n await o.trustOneProxy(boot.app);\n after = platform.proxyTrust(adapter);\n } else {\n // Trust fixed at construction: compare with an app on the trusting adapter.\n const trusted = await bootHttp(o, b, { trustProxy: true });\n try {\n after = resolvedPlatform(trusted.app).proxyTrust!(\n trusted.app.getHttpAdapter() as AbstractHttpAdapter,\n );\n } finally {\n await trusted.close();\n }\n }\n if (before.mode === \"unknown\" || after.mode === \"unknown\") {\n assert.equal(\n before.mode,\n after.mode,\n \"a platform that cannot inspect proxy trust must report unknown consistently\",\n );\n return;\n }\n assert.notDeepEqual(\n after,\n before,\n \"proxyTrust() did not reflect the trusted hop\",\n );\n assert.notEqual(after.mode, \"none\");\n }),\n () => noProxyTrust() ?? noTrustHook(),\n );\n const forwarded = {\n \"x-forwarded-proto\": \"https\",\n \"x-forwarded-host\": \"proxy.example\",\n };\n const derivedBaseUrl: BootConfig = {\n auth: { baseURL: undefined },\n module: { http: { allowRequestDerivedBaseURL: true } },\n };\n const probedUrl = async (boot: HttpBoot) =>\n new URL(\n String(\n json(\n await sendRaw(`${boot.url}${AUTH}/probe/url`, {\n headers: forwarded,\n }),\n ).url,\n ),\n );\n add(\n \"H-url-trust-proxy\",\n \"untrusted forwarding headers leave the request URL unchanged\",\n (o, b) =>\n withBoot(o, b, derivedBaseUrl, async (boot) => {\n const url = await probedUrl(boot);\n assert.notEqual(url.host, \"proxy.example\", \"untrusted forwarding\");\n assert.notEqual(url.protocol, \"https:\", \"untrusted forwarding\");\n }),\n );\n add(\n \"H-url-trust-proxy\",\n \"a trusted forwarding hop sets the request URL's protocol and host\",\n (o, b) =>\n withBoot(o, b, { ...derivedBaseUrl, trustProxy: true }, async (boot) => {\n assert.equal((await probedUrl(boot)).origin, \"https://proxy.example\");\n }),\n () => noTrustHook(),\n );\n add(\n \"H-h2-pseudo\",\n \"HTTP/2 pseudo-headers never reach Better Auth\",\n async (o, b) => {\n const skip = await http2Ready(o);\n if (skip) {\n return skip;\n }\n await withBoot(o, b, { http2: true }, async (boot) => {\n const response = await http2Request(\n http2Origin(boot),\n {\n \":method\": \"POST\",\n \":path\": `${AUTH}/probe/echo-raw`,\n origin: KIT_BASE_URL,\n \"content-type\": \"text/plain\",\n },\n \"h2 body\",\n );\n assert.equal(response.status, 200);\n const value = JSON.parse(response.body.toString(\"utf8\")) as {\n headers: [string, string][];\n body: string;\n };\n assert.equal(Buffer.from(value.body, \"base64\").toString(), \"h2 body\");\n assert.ok(\n value.headers.every(([name]) => !name.startsWith(\":\")),\n \"pseudo-headers reached Better Auth\",\n );\n });\n },\n noHttp2,\n );\n add(\n \"H-resp-multicookie\",\n \"three Set-Cookie values arrive on separate lines\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/multi-cookie`);\n const lines = setCookieLines(response.headers);\n assert.equal(lines.length, 3, `Set-Cookie lines: ${lines.join(\" | \")}`);\n assert.deepEqual(lines.map((line) => line.split(\"=\", 1)[0]).sort(), [\n \"probe_a\",\n \"probe_b\",\n \"probe_c\",\n ]);\n }),\n );\n add(\n \"H-resp-redirect\",\n \"a 302 with Location and a cookie is not followed\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/redirect`);\n assert.equal(response.status, 302);\n assert.equal(\n response.headers.location,\n \"https://probe-plugin.example/next\",\n );\n assert.ok(\n setCookieLines(response.headers).some((line) =>\n line.startsWith(\"probe_redirect=1\"),\n ),\n );\n }),\n );\n add(\n \"H-resp-stream\",\n \"a three-chunk stream arrives in order and a client abort cancels it\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/stream`);\n assert.equal(\n response.body.toString(\"utf8\"),\n \"chunk-0;chunk-1;chunk-2;\",\n );\n boot.probe.streamCancelled = false;\n await sendRaw(`${boot.url}${AUTH}/probe/stream`, {\n abortAfterFirstChunk: true,\n });\n await waitFor(\n () => boot.probe.streamCancelled,\n \"a client abort did not cancel the response stream\",\n );\n }),\n );\n add(\"H-resp-head\", \"HEAD writes no body and never answers 500\", (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n method: \"HEAD\",\n });\n assert.ok(response.status < 500, `HEAD answered ${response.status}`);\n assert.equal(response.body.length, 0);\n }),\n );\n add(\n \"H-resp-status\",\n \"status, HTML and merged Vary pass through; a before-hook APIError becomes its response\",\n (o, b) =>\n withBoot(o, b, { cors: true }, async (boot) => {\n const html = await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers: { origin: CORS_ORIGIN },\n });\n assert.equal(html.status, 200);\n assert.match(String(html.headers[\"content-type\"]), /^text\\/html/);\n assert.equal(html.body.toString(\"utf8\"), \"<p>probe</p>\");\n const tokens = (value: unknown) =>\n String(value ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((token) => token.trim())\n .filter(Boolean);\n const host = tokens(\n (\n await sendRaw(`${boot.url}/app/ping`, {\n headers: { origin: CORS_ORIGIN },\n })\n ).headers.vary,\n );\n const vary = tokens(html.headers.vary);\n for (const token of [...host, \"accept\"]) {\n assert.ok(\n vary.includes(token),\n `Vary lost ${token}: ${vary.join(\", \")}`,\n );\n }\n const apiError = await sendRaw(\n `${boot.url}${AUTH}/probe/throw-api-error`,\n );\n assert.equal(apiError.status, 400);\n assert.equal(json(apiError).code, \"PROBE_API_ERROR\");\n boot.probe.fault = (path) =>\n path === \"/probe/html\"\n ? new APIError(\"FORBIDDEN\", {\n code: \"PROBE_DENIED\",\n message: \"denied\",\n })\n : undefined;\n const denied = await sendRaw(`${boot.url}${AUTH}/probe/html`);\n assert.equal(denied.status, 403);\n assert.equal(json(denied).code, \"PROBE_DENIED\");\n }),\n );\n add(\n \"H-cors-preflight\",\n \"host CORS answers the preflight before Better Auth\",\n (o, b) =>\n withBoot(o, b, { cors: true }, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/put`, {\n method: \"OPTIONS\",\n headers: {\n origin: CORS_ORIGIN,\n \"access-control-request-method\": \"PUT\",\n },\n });\n assert.ok(response.status >= 200 && response.status < 300);\n assert.equal(\n response.headers[\"access-control-allow-origin\"],\n CORS_ORIGIN,\n );\n assert.ok(\n !boot.around.some((entry) => entry.startsWith(\"OPTIONS\")),\n \"the preflight reached Better Auth\",\n );\n }),\n );\n add(\"H-cors-actual\", \"host CORS adds its headers to auth responses\", (o, b) =>\n withBoot(o, b, { cors: true }, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers: { origin: CORS_ORIGIN },\n });\n assert.equal(\n response.headers[\"access-control-allow-origin\"],\n CORS_ORIGIN,\n );\n assert.equal(\n response.headers[\"access-control-allow-credentials\"],\n \"true\",\n );\n }),\n );\n add(\n \"H-accessor-key\",\n \"requests.key() is one object for guards, interceptors and handlers\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}/app/accessor`);\n assert.equal(response.status, 200);\n const { guardKey, interceptorKey, handlerKey } = boot.accessor;\n assert.ok(guardKey && typeof guardKey === \"object\");\n assert.equal(guardKey, interceptorKey);\n assert.equal(guardKey, handlerKey);\n }),\n );\n add(\n \"H-accessor-is-request\",\n \"isRequest() recognizes only platform requests and isLive() turns false after the response\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n await sendRaw(`${boot.url}/app/accessor`);\n const observed = boot.accessor;\n assert.equal(observed.isRequest, true);\n assert.equal(\n observed.rejectsPlain,\n true,\n \"a plain object was accepted\",\n );\n assert.equal(\n observed.rejectsUpgrade,\n true,\n \"a bare IncomingMessage (upgrade request) was accepted\",\n );\n assert.equal(observed.liveInHandler, true);\n await waitFor(\n () => !boot.requests().isLive(observed.request),\n \"isLive() stayed true after the response was sent\",\n );\n }),\n );\n add(\n \"H-accessor-cookie-merge\",\n \"cookieSink() cookies arrive with the handler's own, and session reads leak no cache headers\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}/app/accessor`);\n assert.equal(boot.accessor.sinkAppended, true);\n const names = setCookieLines(response.headers).map(\n (line) => line.split(\"=\", 1)[0],\n );\n assert.ok(names.includes(\"kit_sink\"), `cookies: ${names.join(\",\")}`);\n assert.ok(names.includes(\"kit_handler\"), `cookies: ${names.join(\",\")}`);\n const identity = await kitIdentity(boot.auth);\n const me = await sendRaw(`${boot.url}/app/me`, {\n headers: { cookie: identity.cookie },\n });\n assert.equal(me.status, 200);\n assert.equal(json(me).userId, identity.userId);\n assert.equal(me.headers.pragma, undefined);\n assert.ok(\n !String(me.headers[\"cache-control\"] ?? \"\").includes(\"no-store\"),\n \"getSession cache headers leaked onto an app route\",\n );\n }),\n );\n add(\n \"H-errors-infra\",\n \"a non-APIError from the exchange reaches the host pipeline as a 5xx\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers: { [THROW_HEADER]: \"1\" },\n });\n assert.ok(response.status >= 500, `status ${response.status}`);\n assert.ok(\n boot.filtered.some(isInfrastructureError),\n \"the global filter saw no infrastructure error\",\n );\n assert.ok(boot.logger.errors().length > 0, \"Nest logged no error\");\n }),\n );\n add(\n \"H-errors-filter-sees\",\n \"the global filter sees exchange failures with a global prefix set\",\n (o, b) =>\n withBoot(o, b, { prefix: \"v1\" }, async (boot) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers: { [THROW_HEADER]: \"1\" },\n });\n assert.ok(response.status >= 500);\n assert.ok(boot.filtered.some(isInfrastructureError));\n }),\n );\n add(\n \"H-errors-apierror-throw\",\n \"with onAPIError.throw the filter receives the original APIError\",\n (o, b) =>\n withBoot(\n o,\n b,\n { auth: { onAPIError: { throw: true } } },\n async (boot) => {\n await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers: { [THROW_HEADER]: \"api-error\" },\n });\n const error = boot.filtered.find((value) => isAPIError(value)) as\n | { body?: { code?: string } }\n | undefined;\n assert.ok(error, \"the filter did not receive the APIError\");\n assert.equal(error.body?.code, \"CONFORMANCE_API_ERROR\");\n const hidden = Reflect.get(error, SDK_HEADERS) as Headers | undefined;\n assert.deepEqual(hidden?.getSetCookie(), [\n \"conformance_cleared=; Max-Age=0\",\n ]);\n },\n ),\n );\n add(\n \"H-errors-no-hang\",\n \"failing endpoints, exchanges and interceptors complete within a timeout\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const results = await Promise.all([\n sendRaw(`${boot.url}${AUTH}/probe/throw-error`, { timeoutMs: 3_000 }),\n sendRaw(`${boot.url}${AUTH}/probe/throw-api-error`, {\n timeoutMs: 3_000,\n }),\n sendRaw(`${boot.url}${AUTH}/probe/html`, {\n timeoutMs: 3_000,\n headers: { [THROW_HEADER]: \"1\" },\n }),\n ]);\n assert.ok(results.every((response) => response.status >= 400));\n }),\n );\n add(\n \"H-middleware-order\",\n \"MiddlewareConsumer middleware runs before the auth handler\",\n (o, b) =>\n withBoot(o, b, { middleware: true }, async (boot) => {\n await echo(boot, \"{}\", {\n \"content-type\": \"application/json\",\n \"content-length\": \"2\",\n });\n assert.deepEqual(boot.probe.order, [\"middleware\", \"auth\"]);\n }),\n );\n add(\n \"H-async-options-factory\",\n \"a forRootAsync factory behind an async dependency still captures exact bytes\",\n (o, b) =>\n withBoot(o, b, { async: true }, async (boot) => {\n const raw = '{ \"spaced\" : true }';\n const result = await echo(boot, raw, {\n \"content-type\": \"application/json\",\n \"content-length\": String(raw.length),\n });\n assert.equal(result.bytes.toString(\"utf8\"), raw);\n }),\n );\n add(\n \"H-no-adapter\",\n \"application contexts and module init boot without an HTTP adapter\",\n async (o) => {\n const auth = createConformanceAuth();\n const bridge = await bridgeOf(auth);\n const module = kitModule(\n o,\n auth,\n await probeOf(auth),\n {},\n {\n filtered: [],\n around: [],\n accessor: {},\n requests: () => assert.fail(\"no HTTP platform expected\"),\n adapter: () => assert.fail(\"no HTTP adapter expected\"),\n },\n );\n const context = await NestFactory.createApplicationContext(module, {\n logger: false,\n abortOnError: false,\n });\n await context.init();\n assert.equal(bridge.state, \"bound\");\n await context.close();\n assert.equal(bridge.state, \"closed\");\n const moduleRef = await Test.createTestingModule({\n imports: [module],\n }).compile();\n moduleRef.useLogger(false);\n await moduleRef.init();\n assert.equal(bridge.state, \"bound\");\n await moduleRef.close();\n assert.equal(bridge.state, \"closed\");\n },\n );\n add(\n \"H-no-adapter\",\n \"a microservice boots once without an HTTP adapter, with listen() and with init() then listen()\",\n async (o, b) => {\n for (const initFirst of [false, true]) {\n const label = `${b === \"factory\" ? \"NestFactory.createMicroservice()\" : \"Test.createNestMicroservice()\"} with ${initFirst ? \"init() then listen()\" : \"listen()\"}`;\n const auth = createConformanceAuth();\n const bridge = await bridgeOf(auth);\n const logger = new CapturingLogger();\n const module = kitModule(\n o,\n auth,\n await probeOf(auth),\n { module: { logSummary: true } },\n {\n filtered: [],\n around: [],\n accessor: {},\n requests: () => assert.fail(\"no HTTP platform expected\"),\n adapter: () => assert.fail(\"no HTTP adapter expected\"),\n },\n );\n const microserviceOptions = {\n ...o.microservice!(),\n logger,\n abortOnError: false,\n };\n const microservice: INestMicroservice =\n b === \"factory\"\n ? await NestFactory.createMicroservice(module, microserviceOptions)\n : (\n await Test.createTestingModule({ imports: [module] }).compile()\n ).createNestMicroservice(microserviceOptions);\n try {\n if (initFirst) {\n await microservice.init();\n }\n await microservice.listen();\n assert.equal(\n bridge.state,\n \"bound\",\n `${label}: the instance is not bound`,\n );\n const summaries = logger.entries.filter((entry) =>\n entry.text.startsWith(\"'default': \"),\n );\n assert.equal(\n summaries.length,\n 1,\n `${label}: the lifecycle ran ${summaries.length} times\\n${logger.text()}`,\n );\n assert.match(summaries[0]!.text, /not mounted/, label);\n assert.deepEqual(logger.errors(), [], `${label}: ${logger.text()}`);\n } finally {\n await microservice.close();\n }\n assert.equal(\n bridge.state,\n \"closed\",\n `${label}: close() left the binding ${bridge.state}`,\n );\n }\n },\n () =>\n options.microservice ? undefined : \"no microservice option was given\",\n );\n add(\n \"H-late-adapter\",\n \"module init followed by an application init fails with LATE_HTTP_ADAPTER\",\n async (o) => {\n const auth = createConformanceAuth();\n const module = kitModule(\n o,\n auth,\n await probeOf(auth),\n {},\n {\n filtered: [],\n around: [],\n accessor: {},\n requests: () => assert.fail(\"unused\"),\n adapter: () => assert.fail(\"unused\"),\n },\n );\n const moduleRef = await Test.createTestingModule({\n imports: [module],\n }).compile();\n moduleRef.useLogger(false);\n try {\n await moduleRef.init();\n const app = moduleRef.createNestApplication(o.createHttpAdapter(), {\n logger: false,\n });\n const result = await settle(() => app.init());\n assert.equal(result.ok, false, \"the late adapter was accepted\");\n assert.ok(\n bootIssueCodes(!result.ok && result.error).includes(\n \"LATE_HTTP_ADAPTER\",\n ) || String(!result.ok && result.error).includes(\"LATE_HTTP_ADAPTER\"),\n String(!result.ok && result.error),\n );\n } finally {\n await moduleRef.close();\n }\n },\n );\n add(\n \"H-reused-testing-module\",\n \"a second application from one compiled TestingModule follows capabilities.prepareAtInit\",\n async (o) => {\n const capabilities = await capabilitiesOf(o);\n const auth = createConformanceAuth();\n const around: string[] = [];\n const hooks: string[] = [];\n let current: INestApplication | undefined;\n const module = kitModule(\n o,\n auth,\n await probeOf(auth),\n {},\n {\n filtered: [],\n around,\n accessor: {},\n requests: () => resolvedPlatform(current!).requests,\n adapter: () => current!.getHttpAdapter() as AbstractHttpAdapter,\n hooks,\n },\n );\n const moduleRef = await Test.createTestingModule({\n imports: [module],\n }).compile();\n const first = moduleRef.createNestApplication(o.createHttpAdapter(), {\n logger: false,\n });\n current = first;\n await first.init();\n await first.close();\n const second = moduleRef.createNestApplication(o.createHttpAdapter(), {\n logger: false,\n });\n current = second;\n try {\n const result = await settle(() => second.init());\n if (!capabilities?.prepareAtInit) {\n assert.equal(result.ok, false, \"the second application booted\");\n assert.match(\n String(!result.ok && result.error),\n /APP_ADAPTER_CHANGED/,\n );\n return;\n }\n assert.equal(\n result.ok,\n true,\n `prepareAtInit platform failed: ${String(!result.ok && result.error)}`,\n );\n const url = await baseUrl(o, second);\n const before = hooks.length;\n const response = await sendRaw(`${url}${AUTH}/probe/html`);\n assert.equal(response.status, 200);\n assert.equal(\n hooks.length - before,\n 1,\n \"the second application did not run the @BeforeAuth() hook once\",\n );\n const ping = await sendRaw(`${url}/app/ping`);\n assert.equal(ping.status, 200);\n const identity = await kitIdentity(auth);\n const authoritative = await sendRaw(`${url}/app/authoritative`, {\n headers: { cookie: identity.cookie },\n });\n assert.equal(\n authoritative.status,\n 200,\n `the second application denied an authoritative route: ${authoritative.body.toString(\"utf8\")}`,\n );\n assert.equal(json(authoritative).userId, identity.userId);\n } finally {\n await second.close().catch(() => undefined);\n }\n },\n );\n add(\n \"H-double-forroot\",\n \"a second forRoot for the same instance fails boot\",\n async (o, b) => {\n const result = await settle(() =>\n bootHttp(o, b, { duplicateForRoot: true }),\n );\n if (result.ok) {\n await result.value.close();\n assert.fail(\"a duplicate forRoot booted\");\n }\n assert.ok(\n bootIssueCodes(result.error).includes(\"DUPLICATE_INSTANCE\"),\n String(result.error),\n );\n },\n );\n add(\n \"H-close-keeps-hooks\",\n \"app.close() closes the binding without unbinding its hooks, and the next application takes it over silently\",\n async (o, b) => {\n const auth = createConformanceAuth();\n const bridge = await bridgeOf(auth);\n const direct = async () =>\n (await auth.handler(new Request(`${KIT_BASE_URL}${AUTH}/probe/html`)))\n .status;\n const closedHooks: string[] = [];\n let duringShutdown: number | undefined;\n const first = await bootHttp(o, b, {\n instance: auth,\n hooks: closedHooks,\n onShutdown: async () => {\n duringShutdown = await direct();\n },\n });\n try {\n const served = await sendRaw(`${first.url}${AUTH}/probe/html`);\n assert.equal(served.status, 200);\n assert.equal(\n closedHooks.length,\n 1,\n \"the @BeforeAuth() hook did not run\",\n );\n } finally {\n await first.close();\n }\n const warns = (boot: HttpBoot) =>\n boot.logger.entries\n .filter((entry) => entry.level === \"warn\")\n .map((entry) => entry.text);\n const expected = new Set(warns(first));\n assert.equal(duringShutdown, 200);\n assert.equal(\n closedHooks.length,\n 2,\n \"a Better Auth call from another module's shutdown hook skipped the application's @BeforeAuth() hook\",\n );\n assert.equal(\n bridge.state,\n \"closed\",\n `app.close() left the binding ${bridge.state}`,\n );\n assert.equal(await direct(), 200);\n assert.equal(\n closedHooks.length,\n 3,\n \"a Better Auth call after app.close() skipped the closed application's @BeforeAuth() hook\",\n );\n const nextHooks: string[] = [];\n await withBoot(\n o,\n b,\n { instance: auth, hooks: nextHooks },\n async (next) => {\n assert.equal(bridge.state, \"bound\");\n assert.deepEqual(\n warns(next).filter((text) => !expected.has(text)),\n [],\n \"the next application warned while taking over the closed binding\",\n );\n const served = await sendRaw(`${next.url}${AUTH}/probe/html`);\n assert.equal(served.status, 200);\n assert.equal(\n nextHooks.length,\n 1,\n \"the next application's hook did not run\",\n );\n assert.equal(\n closedHooks.length,\n 3,\n \"the closed application's hook still ran after the next application bound\",\n );\n },\n );\n },\n );\n add(\n \"H-diagnostics-404\",\n \"an unknown auth path logs one WARN with a suggestion and keeps the 404\",\n (o, b) =>\n withBoot(\n o,\n b,\n { module: { http: { diagnostics: true } } },\n async (boot) => {\n for (let index = 0; index < 2; index++) {\n const response = await sendRaw(\n `${boot.url}${AUTH}/sign-inn/email`,\n {\n method: \"POST\",\n headers: {\n origin: KIT_BASE_URL,\n \"content-type\": \"application/json\",\n },\n body: \"{}\",\n },\n );\n assert.equal(response.status, 404);\n }\n const warnings = boot.logger.entries.filter(\n (entry) =>\n entry.level === \"warn\" &&\n entry.text.includes(`${AUTH}/sign-inn/email`),\n );\n assert.equal(warnings.length, 1, boot.logger.text());\n assert.match(warnings[0]!.text, /Did you mean/);\n },\n ),\n );\n const proxyWarnings = (boot: HttpBoot) =>\n warningsWith(boot, \"W_PROXY_UNTRUSTED\");\n add(\n \"H-proxy-untrusted-warning\",\n \"in production with proxy trust off, the first forwarded auth request logs W_PROXY_UNTRUSTED once and changes no response\",\n (o, b) =>\n inProduction(() =>\n withBoot(o, b, {}, async (boot) => {\n const platform = resolvedPlatform(boot.app);\n if (typeof platform.proxyTrust !== \"function\") {\n return conformanceSkip(\n \"the platform does not implement the optional proxyTrust()\",\n );\n }\n const trust = platform.proxyTrust(\n boot.app.getHttpAdapter() as AbstractHttpAdapter,\n );\n if (trust.mode !== \"none\") {\n return conformanceSkip(\n `a fresh adapter reports proxy trust '${trust.mode}', not 'none'`,\n );\n }\n const html = async (headers: Record<string, string> = {}) => {\n const response = await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers,\n });\n assert.equal(response.status, 200);\n assert.equal(response.body.toString(\"utf8\"), \"<p>probe</p>\");\n };\n await html();\n assert.deepEqual(\n proxyWarnings(boot),\n [],\n \"a request without forwarding headers logged\",\n );\n const ping = await sendRaw(`${boot.url}/app/ping`, {\n headers: { \"x-forwarded-for\": \"203.0.113.50\" },\n });\n assert.equal(ping.status, 200);\n assert.deepEqual(proxyWarnings(boot), [], \"an app route logged\");\n await html({ \"x-forwarded-for\": \"203.0.113.51\" });\n const [warning, ...repeated] = proxyWarnings(boot);\n assert.ok(\n warning,\n \"a forwarded auth request logged no W_PROXY_UNTRUSTED\",\n );\n assert.ok(\n warning.includes(`socket IP ${LOOPBACK}.`),\n `the warning did not name the platform's socket IP: ${warning}`,\n );\n assert.ok(\n !warning.includes(\"203.0.113.51\"),\n \"the warning named a client-sent address as the socket IP\",\n );\n assert.deepEqual(repeated, []);\n await html({ forwarded: \"for=203.0.113.52\" });\n await html({ \"x-real-ip\": \"203.0.113.53\" });\n assert.equal(\n proxyWarnings(boot).length,\n 1,\n \"W_PROXY_UNTRUSTED was logged more than once per application\",\n );\n }),\n ),\n noProxyTrust,\n );\n add(\n \"H-proxy-untrusted-warning\",\n \"outside production, forwarded auth requests log no W_PROXY_UNTRUSTED\",\n (o, b) =>\n withNodeEnv(\"test\", () =>\n withBoot(o, b, {}, async (boot) => {\n await sendRaw(`${boot.url}${AUTH}/probe/html`, {\n headers: { \"x-forwarded-for\": \"203.0.113.54\" },\n });\n assert.deepEqual(proxyWarnings(boot), []);\n }),\n ),\n noProxyTrust,\n );\n // Behind a trusted hop no platform may cause the warning: one without proxyTrust() must not be taken for 'none'.\n for (const http2 of [false, true]) {\n add(\n \"H-proxy-untrusted-warning\",\n overHttp2(\n http2,\n \"in production behind a trusted hop, forwarded auth requests log no W_PROXY_UNTRUSTED\",\n ),\n async (o, b) => {\n const skip = await trustedHopReady(o, http2);\n if (skip) {\n return skip;\n }\n return inProduction(() =>\n withBoot(o, b, { trustProxy: true, http2 }, async (boot) => {\n const headers = { \"x-forwarded-for\": \"203.0.113.55\" };\n const response = boot.http2\n ? await http2Request(http2Origin(boot), {\n \":method\": \"GET\",\n \":path\": `${AUTH}/probe/html`,\n ...headers,\n })\n : await sendRaw(`${boot.url}${AUTH}/probe/html`, { headers });\n assert.equal(response.status, 200);\n assert.deepEqual(proxyWarnings(boot), []);\n }),\n );\n },\n trustedHop(http2),\n );\n }\n add(\n \"H-log-hygiene\",\n \"session and probe cookies never appear in captured logs\",\n (o, b) =>\n withBoot(o, b, {}, async (boot) => {\n const identity = await kitIdentity(boot.auth);\n const token = identity.cookie.split(\"=\")[1]!.split(\".\")[0]!;\n await sendRaw(`${boot.url}${AUTH}/probe/multi-cookie`);\n await sendRaw(`${boot.url}${AUTH}/probe/throw-error`, {\n headers: { cookie: identity.cookie },\n });\n boot.probe.fault = () => new Error(`storage failed for ${token}`);\n await sendRaw(`${boot.url}/app/me`, {\n headers: { cookie: identity.cookie },\n });\n const text = boot.logger.text();\n assert.ok(!text.includes(token), \"a session token reached the logs\");\n assert.ok(!text.includes(\"gamma\"), \"a probe cookie reached the logs\");\n }),\n );\n return cases;\n}\n\nasync function bridgeOf(auth: AuthLike): Promise<BridgeHandle> {\n const context = (await auth.$context) as { getPlugin(id: string): unknown };\n const plugin = context.getPlugin(\"@nestjs-kit/better-auth\") as object;\n return Reflect.get(plugin, BRIDGE_HANDLE) as BridgeHandle;\n}\n","import {\n Controller,\n Get,\n type ExecutionContext,\n type INestApplication,\n type LoggerService,\n type Provider,\n} from \"@nestjs/common\";\nimport { Test, type TestingModule } from \"@nestjs/testing\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport type {\n AuthorizationDecision,\n AuthorizationPolicy,\n AuthPrincipalBase,\n AuthTransport,\n CookieSink,\n ExtensionRef,\n PolicyInvoker,\n PrincipalResolver,\n PrincipalSource,\n Requirement,\n RequirementExpr,\n RoutePlan,\n SessionPrincipalOptions,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport { Require } from \"./auth-decorators.js\";\nimport {\n type AuthFailure,\n AuthFailures,\n BetterAuthConfigurationError,\n} from \"./auth-errors.js\";\nimport { BetterAuthGuard } from \"./auth-guard.js\";\nimport { BetterAuthModule } from \"./auth-module.js\";\nimport {\n INSTANCE_REGISTRY,\n POLICY_INVOKER,\n POLICY_RESOLVER,\n PRINCIPAL_RESOLVER,\n REQUEST_SCOPE,\n ROUTE_PLANNER,\n} from \"./auth-tokens.js\";\nimport type { AuthLike, AuthPrincipal, PrincipalKind } from \"./auth-types.js\";\nimport { AuthorizationEvaluator } from \"./authorization-evaluator.js\";\nimport {\n CapturingLogger,\n type ConformanceOutcome,\n probeOf,\n type ProbeState,\n createConformanceAuth,\n PROBE_TRUSTED_ORIGIN,\n testHelpers,\n} from \"./conformance-fixtures.js\";\nimport type {\n FixtureHandler,\n TransportInvocationResult,\n} from \"./conformance-transport.js\";\nimport type { InstanceRegistry } from \"./instance-registry.js\";\nimport type { PolicyResolver } from \"./policy-resolver.js\";\nimport { absent, authenticated, rejected } from \"./principal-resolver.js\";\nimport type { RequestScope } from \"./request-scope.js\";\nimport type { RoutePlanner } from \"./route-planner.js\";\nimport { authHeadersFor } from \"./testing.js\";\n\nexport interface PolicyConformanceOptions {\n /**\n * The requirement to judge. Its policies must be policy objects: the kit boots no application providers, so a class\n * or token reference cannot resolve. For a DI policy, pass an instance built with its dependencies (new MyPolicy(deps)).\n */\n requirement: RequirementExpr;\n /**\n * The Better Auth instance the principals belong to. It must include conformanceProbePlugin(), testUtils(), the\n * policy's plugins and nestjs(): createConformanceAuth({ plugins }) builds one. Session principals are judged with\n * real session headers for their user (testUtils().getAuthHeaders). Unit-specific cases use the instance's plugins\n * when present: session.cookieCache for the warm-cache variants, apiKey({ enableSessionForAPIKeys: true }) for the\n * API-key session and quota cases; each states the reason when it skips.\n */\n auth: AuthLike;\n allowingPrincipal(): Promise<AuthPrincipal>;\n denyingPrincipal(): Promise<AuthPrincipal>;\n delegatedPrincipal?(): Promise<AuthPrincipal>;\n /**\n * Principal sources the kit registers besides the built-in session source, for the requirement's other principal kinds\n * (e.g. apiKeyPrincipal()). Cases that send a request through the guard resolve those kinds with them; without them\n * the kit registers placeholder sources that resolve nothing.\n */\n sources?: readonly ExtensionRef<PrincipalSource>[];\n /**\n * Transports to deliver the transport-specific rows through, besides the kit's in-process request: each delivery adds\n * its own variants of Z-admin-banned (connection deliveries with a principal TTL), Z-admin-rejects-api-key-session,\n * Z-apikey-quota-per-request and Z-org-ref-types, titled with its name.\n */\n deliveries?: readonly PolicyDelivery[];\n /**\n * Builds the instances the kit needs in another configuration (adminUserIds, customSession shapes, a dynamic baseURL,\n * an instance without apiKey()) with exactly the given overrides, on the storage under test. It must add what\n * createConformanceAuth() adds (testUtils(), bearer(), conformanceProbePlugin(), nestjs(), an explicit\n * advanced.disableOriginCheck: false and session.updateAge 0) and have its schema migrated. Default:\n * createConformanceAuth(overrides), on the memory adapter.\n */\n variant?(\n overrides: Omit<BetterAuthOptions, \"database\">,\n ): AuthLike | Promise<AuthLike>;\n}\n\n/**\n * A transport the policy kit delivers its transport-specific rows through (design v7 §14.1). Build it from the harness\n * of a transportConformance run: it exposes the kit's handlers the way that harness exposes the transport kit's fixtures.\n */\nexport interface PolicyDelivery {\n /** The transport's name in case titles, e.g. 'Socket.IO'. */\n readonly name: string;\n /**\n * Boots an app with BetterAuthModule's globalGuard that exposes each handler under its name in the transport's shape:\n * a gateway message with explicit coverage, a message pattern or a GraphQL query field, plus the subscription field\n * that connect()'s operations select on a GraphQL socket. Apply the handler's decorators like transportConformance's\n * createApp does. The kit's only named input is `orgId`: pass its value through with its JSON type (a GraphQL\n * harness declares a JSON scalar argument), so ctx.param('orgId') reads it unchanged. Pass `principals` to\n * BetterAuthModule and use `logger` from boot on. The kit closes the app.\n */\n createApp(\n handlers: Readonly<Record<string, FixtureHandler>>,\n auth: AuthLike,\n options: {\n readonly principals: readonly ExtensionRef<PrincipalSource>[];\n readonly logger: LoggerService;\n },\n ): Promise<INestApplication>;\n /**\n * One logical request to a handler with the given headers: a message on its own connection, an RPC request, an\n * operation. The kit's headers carry the probe plugin's trusted Origin, as a browser on a trusted page sends it.\n */\n invoke(\n app: INestApplication,\n handler: string,\n headers: HeadersInit,\n input?: Record<string, unknown>,\n ): Promise<TransportInvocationResult>;\n /**\n * Connection deliveries (WebSocket gateways, graphql-ws): opens one connection whose handshake carries `headers`.\n * Its invoke() sends one message, or one subscription operation for GraphQL, after the previous one answered.\n */\n connect?(\n app: INestApplication,\n headers: HeadersInit,\n ): Promise<PolicyDeliveryConnection>;\n /**\n * The principal TTL of connect()'s connections: the transport's principalTtlMs or subscriptionPrincipalTtlMs. The\n * connection variant of Z-admin-banned runs when it is positive, and checks that the connection reuses its principal.\n */\n readonly connectionPrincipalTtlMs?: number;\n}\n\n/** One connection of a PolicyDelivery. */\nexport interface PolicyDeliveryConnection {\n invoke(\n handler: string,\n input?: Record<string, unknown>,\n ): Promise<TransportInvocationResult>;\n close(): Promise<void>;\n}\n\n/** An instance with the given overrides, built by options.variant() or createConformanceAuth(). */\nexport async function variantOf(\n options: Pick<PolicyConformanceOptions, \"variant\">,\n overrides: Omit<BetterAuthOptions, \"database\">,\n): Promise<AuthLike> {\n return options.variant\n ? await options.variant(overrides)\n : createConformanceAuth(overrides);\n}\n\nexport function requirementsOf(expression: RequirementExpr): Requirement[] {\n return \"anyOf\" in expression\n ? expression.anyOf.flatMap(requirementsOf)\n : \"allOf\" in expression\n ? expression.allOf.flatMap(requirementsOf)\n : [expression];\n}\n\nfunction isPolicyObject(value: unknown): value is AuthorizationPolicy<unknown> {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as AuthorizationPolicy<unknown>).evaluate === \"function\"\n );\n}\n\n/** The policy objects of a requirement; the kit rejects class and token references up front. */\nexport function staticPolicies(\n expression: RequirementExpr,\n): AuthorizationPolicy<unknown>[] {\n return requirementsOf(expression).map((item) => {\n if (!isPolicyObject(item.policy)) {\n throw new BetterAuthConfigurationError(\n \"CONFORMANCE_POLICY_OBJECT_REQUIRED\",\n `policyConformance received a requirement whose policy is a class or injection token (${String((item.policy as { name?: unknown })?.name ?? item.policy)}); the kit registers no application providers to resolve it.`,\n \"Pass the policy object, e.g. requirement(new MyPolicy(dependencies), params).\",\n );\n }\n return item.policy;\n });\n}\n\nexport const KIT_ROUTE = \"handle\";\n\n/** A controller with one method per route, each carrying the given method decorators. */\nfunction controllerFor(\n routes: Readonly<Record<string, readonly MethodDecorator[]>>,\n) {\n @Controller(\"nestjs-kit-better-auth-policy-conformance\")\n class PolicyConformanceController {}\n for (const [name, decorators] of Object.entries(routes)) {\n const method = function handle(): void {};\n Object.defineProperty(method, \"name\", { value: name });\n Object.defineProperty(PolicyConformanceController.prototype, name, {\n value: method,\n writable: true,\n configurable: true,\n });\n const descriptor = Object.getOwnPropertyDescriptor(\n PolicyConformanceController.prototype,\n name,\n )!;\n for (const decorator of [Get(name), ...decorators].reverse()) {\n decorator(PolicyConformanceController.prototype, name, descriptor);\n }\n }\n return PolicyConformanceController;\n}\n\nexport const CONFORMANCE_KIND_SOURCE =\n \"@nestjs-kit/better-auth:conformance-kind\";\n\n/**\n * Placeholder sources for the non-session kinds a requirement names that no given source produces, so boot validation\n * (B15) sees producers of every judged kind. They never resolve anything: the evaluator-level cases hand principals to\n * the evaluator directly.\n */\nfunction kindSources(\n expressions: readonly RequirementExpr[],\n produced: ReadonlySet<string>,\n): PrincipalSource[] {\n const kinds = new Set<string>();\n for (const item of expressions.flatMap(requirementsOf)) {\n const policy = isPolicyObject(item.policy) ? item.policy : undefined;\n for (const kind of item.principals ?? policy?.requires?.principals ?? []) {\n kinds.add(kind);\n }\n }\n kinds.delete(\"session\");\n return [...kinds]\n .filter((kind) => !produced.has(kind))\n .map((kind) => ({\n id: `${CONFORMANCE_KIND_SOURCE}:${kind}`,\n kinds: [kind] as PrincipalSource[\"kinds\"],\n acceptance: \"explicit\",\n delegates: true,\n resolve: async () => ({ outcome: \"absent\" }) as const,\n }));\n}\n\nfunction kindsOf(source: ExtensionRef<PrincipalSource>): readonly string[] {\n return typeof source === \"object\" &&\n source !== null &&\n Array.isArray((source as PrincipalSource).kinds)\n ? (source as PrincipalSource).kinds\n : [];\n}\n\nexport interface BootOptions {\n /**\n * Routes by method name, each with its method decorators. Default: one route requiring `expression`; with routes,\n * `expression` only names the kinds that need placeholder sources.\n */\n routes?: Readonly<Record<string, readonly MethodDecorator[]>>;\n sources?: readonly ExtensionRef<PrincipalSource>[];\n providers?: readonly Provider[];\n session?: SessionPrincipalOptions<unknown> | false;\n transports?: readonly ExtensionRef<AuthTransport>[];\n logger?: CapturingLogger;\n}\n\nexport interface Booted {\n readonly moduleRef: TestingModule;\n readonly controller: ReturnType<typeof controllerFor>;\n readonly logger: CapturingLogger;\n}\n\n/** Boot a TestingModule with the kit's controller and the given requirement; failures close the module. */\nexport async function boot(\n auth: AuthLike,\n expression: RequirementExpr | undefined,\n options: BootOptions = {},\n): Promise<Booted> {\n const routes = options.routes ?? {\n [KIT_ROUTE]: expression ? [Require(expression)] : [],\n };\n const expressions = expression ? [expression] : [];\n const produced = new Set(\n (options.sources ?? []).flatMap((source) => [...kindsOf(source)]),\n );\n const sources = [\n ...(options.sources ?? []),\n ...kindSources(expressions, produced),\n ];\n const controller = controllerFor(routes);\n const logger = options.logger ?? new CapturingLogger();\n const moduleRef = await Test.createTestingModule({\n imports: [\n BetterAuthModule.forRoot({\n auth,\n principals: sources,\n http: { mount: false },\n logSummary: false,\n ...(options.transports ? { transports: options.transports } : {}),\n ...(options.session === undefined ? {} : { session: options.session }),\n } as never),\n ],\n controllers: [controller],\n providers: [...(options.providers ?? [])],\n }).compile();\n moduleRef.useLogger(logger);\n try {\n await moduleRef.init();\n } catch (error) {\n await moduleRef.close().catch(() => undefined);\n throw error;\n }\n return { moduleRef, controller, logger };\n}\n\nexport interface DecideCall {\n key?: object;\n invocation?: object;\n /** The request's headers; default: fresh session headers for a non-delegated principal's user, none otherwise. */\n headers?: Headers;\n /** Runs after the principal's session headers exist, right before evaluation. */\n beforeEvaluate?: () => void | Promise<void>;\n}\n\n/** The evaluator-level harness: principals go straight to the real AuthorizationEvaluator. */\nexport interface Harness {\n readonly auth: AuthLike;\n readonly probe: ProbeState;\n readonly invocations: { count: number };\n readonly policies: PolicyResolver;\n readonly logger: CapturingLogger;\n decide(\n principal: AuthPrincipal,\n call?: DecideCall,\n ): Promise<AuthorizationDecision>;\n close(): Promise<void>;\n}\n\nexport async function harness(\n options: Pick<PolicyConformanceOptions, \"auth\" | \"requirement\" | \"sources\">,\n): Promise<Harness> {\n const probe = await probeOf(options.auth);\n const { moduleRef, controller, logger } = await boot(\n options.auth,\n options.requirement,\n { sources: options.sources },\n );\n const real = moduleRef.get<PolicyInvoker>(POLICY_INVOKER);\n const invocations = { count: 0 };\n const counting: PolicyInvoker = {\n invoke(policy, params, context) {\n invocations.count++;\n return real.invoke(policy, params, context);\n },\n };\n const policies = moduleRef.get<PolicyResolver>(POLICY_RESOLVER);\n const evaluator = new AuthorizationEvaluator(\n policies,\n counting,\n moduleRef.get<PrincipalResolver>(PRINCIPAL_RESOLVER),\n moduleRef.get<RequestScope>(REQUEST_SCOPE),\n );\n const plan: RoutePlan = moduleRef\n .get<RoutePlanner>(ROUTE_PLANNER)\n .plan(controller, KIT_ROUTE);\n const entry = moduleRef\n .get<InstanceRegistry>(INSTANCE_REGISTRY)\n .get(\"default\");\n const execution = {\n getClass: () => controller,\n getHandler: () => Reflect.get(controller.prototype, KIT_ROUTE),\n getArgs: () => [],\n getArgByIndex: () => undefined,\n getType: () => \"@nestjs-kit/better-auth:conformance\",\n } as unknown as ExecutionContext;\n return {\n auth: options.auth,\n probe,\n invocations,\n policies,\n logger,\n async decide(principal, ids = {}) {\n const headers =\n ids.headers ??\n (principal.userId && !principal.delegation\n ? await authHeadersFor(options.auth, principal.userId)\n : new Headers());\n const key = ids.key ?? {};\n const call: TransportCall = {\n key,\n invocation: ids.invocation ?? key,\n headers: () => new Headers(headers),\n clientIp: null,\n cookies: null,\n param: () => undefined,\n };\n await ids.beforeEvaluate?.();\n return evaluator.evaluate(\n plan,\n principal,\n call,\n entry,\n execution,\n \"conformance\",\n );\n },\n close: () => moduleRef.close(),\n };\n}\n\nfunction resetFaults(probe: ProbeState): void {\n probe.fault = undefined;\n probe.storageFault = undefined;\n probe.respond = undefined;\n}\n\nexport async function withHarness(\n options: Pick<PolicyConformanceOptions, \"auth\" | \"requirement\" | \"sources\">,\n fn: (harness: Harness) => Promise<ConformanceOutcome>,\n): Promise<ConformanceOutcome> {\n const value = await harness(options);\n try {\n return await fn(value);\n } finally {\n resetFaults(value.probe);\n await value.close();\n }\n}\n\n/** Better Auth endpoints dispatched since `from`, without the session reads. */\nexport function betterAuthCalls(probe: ProbeState, from: number): string[] {\n return probe.calls.slice(from).filter((path) => path !== \"/get-session\");\n}\n\nexport function sessionReads(probe: ProbeState, from: number): number {\n return probe.calls.slice(from).filter((path) => path === \"/get-session\")\n .length;\n}\n\n// ── Request harness: calls through the real BetterAuthGuard ─────────────────\n\nconst KIT_CONTEXT = \"@nestjs-kit/better-auth:policy-conformance\";\n\ninterface KitMessage {\n readonly headers: Headers;\n readonly input: Record<string, unknown>;\n readonly key: object;\n readonly invocation: object;\n readonly sink: CookieSink;\n}\n\nclass KitDenial extends Error {\n constructor(readonly failure: AuthFailure) {\n super(failure.message);\n }\n}\n\n/**\n * The kit's in-process transport: one message is one logical request with one invocation. It is cookie-capable\n * (a recording sink), carries no browser leg and reads `param(name)` from the message input.\n */\nclass PolicyKitTransport implements AuthTransport {\n readonly id = \"@nestjs-kit/better-auth:conformance/policy-request\";\n\n handles(context: ExecutionContext): boolean {\n return context.getType<string>() === KIT_CONTEXT;\n }\n\n describe(context: ExecutionContext): TransportCall {\n const [message] = context.getArgs() as [KitMessage];\n return {\n key: message.key,\n invocation: message.invocation,\n headers: () => new Headers(message.headers),\n clientIp: null,\n cookies: message.sink,\n param: (name) => message.input[name],\n };\n }\n\n toException(failure: AuthFailure): unknown {\n return new KitDenial(failure);\n }\n}\n\n/** What one request through the guard answered: allowed, a denial with its status, or a 5xx. */\nexport type RequestOutcome =\n | { readonly ok: true; readonly status: 200 }\n | {\n readonly ok: false;\n readonly status: number;\n readonly code?: string;\n readonly reason?: string;\n readonly error?: unknown;\n };\n\n/** One connection of a connection delivery: each request is one message or operation on it. */\nexport interface RequestConnection {\n request(\n route: string,\n input?: Record<string, unknown>,\n ): Promise<RequestOutcome>;\n close(): Promise<void>;\n}\n\nexport interface RequestHarness {\n readonly probe: ProbeState;\n readonly logger: CapturingLogger;\n request(\n route: string,\n headers: HeadersInit,\n input?: Record<string, unknown>,\n ): Promise<RequestOutcome>;\n /** Connection deliveries only. */\n connect?(headers: HeadersInit): Promise<RequestConnection>;\n close(): Promise<void>;\n}\n\nexport type RequestOptions = Omit<BootOptions, \"transports\"> & {\n routes: Readonly<Record<string, readonly MethodDecorator[]>>;\n};\n\nexport async function requestHarness(\n auth: AuthLike,\n options: RequestOptions,\n): Promise<RequestHarness> {\n const probe = await probeOf(auth);\n const { moduleRef, controller, logger } = await boot(auth, undefined, {\n ...options,\n transports: [new PolicyKitTransport()],\n });\n const guard = moduleRef.get(BetterAuthGuard, { strict: false });\n return {\n probe,\n logger,\n async request(route, headers, input = {}) {\n const key = {};\n const message: KitMessage = {\n headers: new Headers(headers),\n input,\n key,\n invocation: key,\n sink: { append: () => true },\n };\n const args = [message];\n const context = {\n getClass: () => controller,\n getHandler: () => Reflect.get(controller.prototype, route),\n getArgs: () => args,\n getArgByIndex: (index: number) => args[index],\n getType: () => KIT_CONTEXT,\n } as unknown as ExecutionContext;\n try {\n await guard.canActivate(context);\n return { ok: true, status: 200 };\n } catch (error) {\n if (error instanceof KitDenial) {\n return {\n ok: false,\n status: error.failure.status,\n code: error.failure.code,\n reason: error.failure.reason,\n };\n }\n return { ok: false, status: 500, error };\n }\n },\n close: () => moduleRef.close(),\n };\n}\n\n/** A delivery's answer as a request outcome: its status code (500 when it carries none), code and reason. */\nfunction deliveredOutcome(result: TransportInvocationResult): RequestOutcome {\n if (result.ok) {\n return { ok: true, status: 200 };\n }\n return {\n ok: false,\n status: result.error?.statusCode ?? 500,\n code: result.error?.code,\n reason: result.error?.reason,\n ...(result.error?.statusCode === undefined\n ? { error: result.error?.message }\n : {}),\n };\n}\n\n/** The kit's routes as the delivery's handlers: no parameters, a safe operation, answering `{ ok: true }`. */\nfunction deliveryHandlers(\n routes: Readonly<Record<string, readonly MethodDecorator[]>>,\n): Record<string, FixtureHandler> {\n return Object.fromEntries(\n Object.entries(routes).map(([name, decorators]) => [\n name,\n {\n decorators,\n params: [],\n operation: \"read\",\n handle: () => ({ ok: true }),\n } satisfies FixtureHandler,\n ]),\n );\n}\n\n/** The request harness over a PolicyDelivery's real transport. */\nexport async function deliveryHarness(\n delivery: PolicyDelivery,\n auth: AuthLike,\n options: RequestOptions,\n): Promise<RequestHarness> {\n if (options.providers?.length || options.session !== undefined) {\n throw new BetterAuthConfigurationError(\n \"CONFORMANCE_DELIVERY_OPTIONS\",\n \"A policy delivery boots its own application: it takes routes and principal sources only.\",\n );\n }\n const probe = await probeOf(auth);\n const logger = options.logger ?? new CapturingLogger();\n const app = await delivery.createApp(deliveryHandlers(options.routes), auth, {\n principals: options.sources ?? [],\n logger,\n });\n const connect = delivery.connect?.bind(delivery);\n // A browser on a trusted page: the probe plugin's origin is trusted on every kit instance.\n const browser = (headers: HeadersInit) => {\n const values = new Headers(headers);\n if (!values.has(\"origin\")) {\n values.set(\"origin\", PROBE_TRUSTED_ORIGIN);\n }\n return values;\n };\n return {\n probe,\n logger,\n request: async (route, headers, input = {}) =>\n deliveredOutcome(\n await delivery.invoke(app, route, browser(headers), input),\n ),\n ...(connect\n ? {\n async connect(headers: HeadersInit): Promise<RequestConnection> {\n const connection = await connect(app, browser(headers));\n return {\n request: async (route, input = {}) =>\n deliveredOutcome(await connection.invoke(route, input)),\n close: () => connection.close(),\n };\n },\n }\n : {}),\n close: () => app.close(),\n };\n}\n\n/** Runs `fn` with requests through the in-process guard, or through `delivery`'s transport when given. */\nexport async function withRequests(\n auth: AuthLike,\n options: RequestOptions,\n fn: (harness: RequestHarness) => Promise<ConformanceOutcome>,\n delivery?: PolicyDelivery,\n): Promise<ConformanceOutcome> {\n const value = delivery\n ? await deliveryHarness(delivery, auth, options)\n : await requestHarness(auth, options);\n try {\n return await fn(value);\n } finally {\n resetFaults(value.probe);\n await value.close();\n }\n}\n\nexport function describeOutcome(outcome: RequestOutcome): string {\n return outcome.ok\n ? \"allowed\"\n : `${outcome.status} ${outcome.code ?? \"\"} ${outcome.reason ?? \"\"} ${outcome.error ? String(outcome.error) : \"\"}`.trim();\n}\n\n// ── Kit identities and credentials ─────────────────────────────────────────\n\nconst API_KEY_KIND = \"api-key\" as PrincipalKind;\nexport const KIT_KEY_HEADER = \"x-conformance-key\";\nexport const KIT_KEY_SOURCE = \"@nestjs-kit/better-auth:conformance-policy-key\";\n\nexport interface KitKeys {\n /** Key value → the user it acts for and its grant. */\n readonly keys: Map<string, { userId: string; grant: GrantMap }>;\n verifications: number;\n}\n\ntype GrantMap = Readonly<Record<string, readonly string[]>>;\n\nfunction grants(grant: GrantMap, requested: GrantMap): boolean {\n return Object.entries(requested).every(([resource, actions]) =>\n actions.every((action) => grant[resource]?.includes(action)),\n );\n}\n\n/** A delegated principal of the kind 'api-key' for a user, whose own grant is `grant`. */\nexport function kitKeyPrincipal(\n userId: string,\n grant: GrantMap,\n): AuthPrincipal {\n return {\n kind: API_KEY_KIND,\n source: KIT_KEY_SOURCE,\n userId,\n delegation: {\n description: \"conformance key grant\",\n allows: (requested: GrantMap) => grants(grant, requested),\n },\n } as unknown as AuthPrincipal;\n}\n\n/** The kit's API-key source: header x-conformance-key, explicit acceptance, delegated principals, counted verifications. */\nexport function kitKeySource(keys: KitKeys): PrincipalSource {\n const source: PrincipalSource<AuthPrincipalBase> = {\n id: KIT_KEY_SOURCE,\n kinds: [API_KEY_KIND],\n acceptance: \"explicit\",\n delegates: true,\n credentialHeaders: [KIT_KEY_HEADER],\n appliesTo: (request) => request.headers.has(KIT_KEY_HEADER),\n async resolve(request) {\n const value = request.headers.get(KIT_KEY_HEADER);\n if (!value) {\n return absent();\n }\n keys.verifications++;\n const key = keys.keys.get(value);\n if (!key) {\n return rejected(\n AuthFailures.rejected({ status: 401, reason: \"INVALID_API_KEY\" }),\n );\n }\n return authenticated(\n kitKeyPrincipal(key.userId, key.grant) as unknown as AuthPrincipalBase,\n );\n },\n };\n return source as unknown as PrincipalSource;\n}\n\ninterface SdkContext {\n options: {\n plugins?: readonly { id: string }[];\n session?: { cookieCache?: { enabled?: boolean } };\n };\n internalAdapter: {\n deleteUserSessions(userId: string): Promise<void>;\n deleteUser(userId: string): Promise<void>;\n updateUser(userId: string, data: Record<string, unknown>): Promise<unknown>;\n };\n adapter: {\n update(input: {\n model: string;\n where: { field: string; value: unknown }[];\n update: Record<string, unknown>;\n }): Promise<unknown>;\n findOne<T>(input: {\n model: string;\n where: { field: string; value: unknown }[];\n }): Promise<T | null>;\n };\n}\n\nexport async function sdkContext(auth: AuthLike): Promise<SdkContext> {\n return (await auth.$context) as unknown as SdkContext;\n}\n\nexport async function hasPlugin(auth: AuthLike, id: string): Promise<boolean> {\n return !!(await sdkContext(auth)).options.plugins?.some(\n (plugin) => plugin.id === id,\n );\n}\n\nexport async function cookieCacheEnabled(auth: AuthLike): Promise<boolean> {\n return (\n (await sdkContext(auth)).options.session?.cookieCache?.enabled === true\n );\n}\n\n/** A stored user with the given fields; `id` pins the user id. */\nexport async function kitUser(\n auth: AuthLike,\n fields: Record<string, unknown> = {},\n): Promise<string> {\n const helpers = await testHelpers(auth);\n return (\n await helpers.saveUser(\n helpers.createUser({\n email: `${globalThis.crypto.randomUUID()}@conformance.example`,\n name: \"Conformance\",\n ...fields,\n }),\n )\n ).id;\n}\n\nfunction mergeCookies(header: string, setCookies: readonly string[]): string {\n const cookies = new Map<string, string>();\n for (const part of header.split(\";\")) {\n const trimmed = part.trim();\n if (trimmed) {\n cookies.set(trimmed.split(\"=\", 1)[0]!, trimmed);\n }\n }\n for (const line of setCookies) {\n const pair = line.split(\";\", 1)[0]!.trim();\n cookies.set(pair.split(\"=\", 1)[0]!, pair);\n }\n return [...cookies.values()].join(\"; \");\n}\n\n/**\n * Fresh session headers for a user. `warmCache` adds the signed cookie-cache cookie a session read issues, or returns\n * null when the instance issued none (its session.cookieCache is off).\n */\nexport async function sessionHeaders(\n auth: AuthLike,\n userId: string,\n options: { warmCache?: boolean } = {},\n): Promise<Headers | null> {\n const headers = await authHeadersFor(auth, userId);\n if (!options.warmCache) {\n return headers;\n }\n const result = (await (\n auth.api as unknown as {\n getSession(input: {\n headers: Headers;\n returnHeaders: true;\n }): Promise<{ headers: Headers }>;\n }\n ).getSession({ headers, returnHeaders: true })) as { headers: Headers };\n const setCookies = result.headers.getSetCookie();\n if (!setCookies.some((line) => /session_data=[^;]/.test(line))) {\n return null;\n }\n headers.set(\"cookie\", mergeCookies(headers.get(\"cookie\") ?? \"\", setCookies));\n return headers;\n}\n\n/** A session principal read through Better Auth's getSession for the given headers, as the session source builds it. */\nexport async function sessionPrincipalOf(\n auth: AuthLike,\n headers: Headers,\n): Promise<AuthPrincipal> {\n const session = (await (\n auth.api as unknown as {\n getSession(input: { headers: Headers }): Promise<{\n user: { id: string };\n } | null>;\n }\n ).getSession({ headers })) as { user: { id: string } } | null;\n if (!session) {\n throw new BetterAuthConfigurationError(\n \"CONFORMANCE_SESSION_MISSING\",\n \"The kit could not read the session it created.\",\n );\n }\n return {\n kind: \"session\",\n source: \"better-auth:session\",\n userId: session.user.id,\n session,\n } as unknown as AuthPrincipal;\n}\n","import assert from \"node:assert/strict\";\nimport { isAPIError } from \"better-auth/api\";\nimport { admin, customSession, organization } from \"better-auth/plugins\";\nimport type {\n AuthorizationPolicy,\n Requirement,\n RequirementExpr,\n} from \"./auth-contracts.js\";\nimport { Require, RequireAuth } from \"./auth-decorators.js\";\nimport { INVOCATION_VALUES } from \"./auth-tokens.js\";\nimport type { AuthLike, PrincipalKind } from \"./auth-types.js\";\nimport { allow } from \"./authorization-evaluator.js\";\nimport {\n bootIssueCodes,\n type ConformanceCase,\n conformanceCase,\n conformanceSkip,\n type ConformanceOutcome,\n KIT_BASE_URL,\n settle,\n} from \"./conformance-fixtures.js\";\nimport {\n betterAuthCalls,\n boot,\n cookieCacheEnabled,\n describeOutcome,\n hasPlugin,\n KIT_KEY_HEADER,\n type KitKeys,\n kitKeyPrincipal,\n kitKeySource,\n kitUser,\n type PolicyConformanceOptions,\n type PolicyDelivery,\n type RequestOutcome,\n requirementsOf,\n sdkContext,\n sessionHeaders,\n sessionPrincipalOf,\n variantOf,\n withHarness,\n withRequests,\n} from \"./conformance-policy-harness.js\";\nimport {\n ACTIVE_ORGANIZATION_ID,\n activeOrganization,\n fromParam,\n orgMember,\n type OrganizationRef,\n organizationRef,\n orgPermission,\n} from \"./organization.js\";\n\nconst ADMIN_POLICY = \"better-auth:admin/permission\";\nconst ORG_POLICIES = new Set([\n \"better-auth:organization/permission\", // gitleaks:allow: public policy identifier\n \"better-auth:organization/member\",\n]);\nconst API_KEY_POLICY = \"better-auth:api-key/permission\";\nconst SDK_KEY_HEADER = \"x-api-key\";\nconst MOCK_SESSION_HEADER = \"x-conformance-mock-session\";\nconst SESSION_KIND = \"session\" as PrincipalKind;\nconst API_KEY_KIND = \"api-key\" as PrincipalKind;\nconst BOTH_KINDS = [SESSION_KIND, API_KEY_KIND] as const;\nconst UNAUTHENTICATED = \"UNAUTHENTICATED\";\n\ntype Permissions = Readonly<Record<string, readonly string[]>>;\n\ninterface SdkApi {\n getSession(input: { headers: Headers }): Promise<unknown>;\n listUsers(input: { headers: Headers; query: object }): Promise<unknown>;\n banUser(input: {\n headers: Headers;\n body: { userId: string };\n }): Promise<unknown>;\n createApiKey(input: {\n body: {\n userId: string;\n permissions?: Permissions;\n remaining?: number;\n rateLimitEnabled?: boolean;\n };\n }): Promise<{ id: string; key: string }>;\n createOrganization(input: {\n headers: Headers;\n body: { name: string; slug: string };\n }): Promise<{ id: string }>;\n setActiveOrganization(input: {\n headers: Headers;\n body: { organizationId: string };\n }): Promise<unknown>;\n}\n\nfunction api(auth: AuthLike): SdkApi {\n return auth.api as unknown as SdkApi;\n}\n\n/** Better Auth's own answer for a server call: 200, or the APIError status (500 for any other throw). */\nasync function sdkStatus(call: () => Promise<unknown>): Promise<number> {\n const result = await settle(call);\n if (result.ok) {\n return 200;\n }\n return isAPIError(result.error) ? result.error.statusCode : 500;\n}\n\nfunction statusOf(outcome: RequestOutcome): number {\n return outcome.ok ? 200 : outcome.status;\n}\n\nfunction leafWith(\n expression: RequirementExpr,\n match: (policy: AuthorizationPolicy<unknown>) => boolean,\n): Requirement | undefined {\n return requirementsOf(expression).find((item) =>\n match(item.policy as AuthorizationPolicy<unknown>),\n );\n}\n\nfunction adminRequirement(\n policy: AuthorizationPolicy<unknown>,\n permissions: Permissions,\n principals?: readonly PrincipalKind[],\n): Requirement {\n return {\n policy,\n params: { permissions },\n ...(principals ? { principals } : {}),\n };\n}\n\nfunction withOrganization(\n leaf: Requirement,\n organization: OrganizationRef,\n): Requirement {\n return {\n ...leaf,\n params: { ...(leaf.params as object), organization },\n };\n}\n\nasync function createKey(\n auth: AuthLike,\n userId: string,\n body: { permissions?: Permissions; remaining?: number } = {},\n): Promise<{ id: string; key: string }> {\n return api(auth).createApiKey({\n body: { userId, rateLimitEnabled: false, ...body },\n });\n}\n\n/** Whether Better Auth turns the key into a session (apiKey({ enableSessionForAPIKeys: true })). */\nasync function keySessions(auth: AuthLike, key: string): Promise<boolean> {\n const session = await settle(() =>\n api(auth).getSession({ headers: new Headers({ [SDK_KEY_HEADER]: key }) }),\n );\n return session.ok && !!session.value;\n}\n\nasync function remainingOf(auth: AuthLike, keyId: string): Promise<number> {\n const row = await (await sdkContext(auth)).adapter.findOne<{\n remaining: number | null;\n }>({ model: \"apikey\", where: [{ field: \"id\", value: keyId }] });\n return row?.remaining ?? Number.NaN;\n}\n\nasync function createOrganizationFor(\n auth: AuthLike,\n headers: Headers,\n): Promise<string> {\n return (\n await api(auth).createOrganization({\n headers,\n body: {\n name: \"Conformance\",\n slug: `conformance-${globalThis.crypto.randomUUID()}`,\n },\n })\n ).id;\n}\n\nasync function setRole(\n auth: AuthLike,\n userId: string,\n role: string | null,\n): Promise<void> {\n await (await sdkContext(auth)).adapter.update({\n model: \"user\",\n where: [{ field: \"id\", value: userId }],\n update: { role },\n });\n}\n\nfunction assertDenied(\n outcome: RequestOutcome,\n status: number,\n reason: string | undefined,\n message: string,\n): void {\n assert.equal(outcome.ok, false, `${message}: allowed`);\n assert.equal(\n statusOf(outcome),\n status,\n `${message}: ${describeOutcome(outcome)}`,\n );\n if (reason !== undefined && !outcome.ok) {\n assert.equal(\n outcome.reason ?? outcome.code,\n reason,\n `${message}: ${describeOutcome(outcome)}`,\n );\n }\n}\n\n/**\n * The unit-specific rows of design §14.1 and the core class-policy row. Each unit's cases run when the requirement\n * contains that built-in policy, and skip with the reason otherwise; instances the case needs in another configuration\n * (customSession shapes, adminUserIds, a dynamic baseURL) are built by options.variant(), createConformanceAuth() by default.\n */\nexport function unitPolicyCases(\n options: PolicyConformanceOptions,\n known: readonly AuthorizationPolicy<unknown>[],\n): ConformanceCase[] {\n const { auth } = options;\n const adminPolicy = known.find((policy) => policy.id === ADMIN_POLICY);\n const orgLeaf = leafWith(options.requirement, (policy) =>\n ORG_POLICIES.has(policy.id),\n );\n const keyLeaf = leafWith(\n options.requirement,\n (policy) => policy.id === API_KEY_POLICY,\n );\n const noAdmin = adminPolicy\n ? undefined\n : `the requirement contains no built-in admin permission policy (${ADMIN_POLICY})`;\n const noOrg = orgLeaf\n ? undefined\n : \"the requirement contains no built-in organization policy\";\n const admin_ = adminPolicy!;\n const adminCase = (\n id: string,\n title: string,\n run: () => Promise<ConformanceOutcome>,\n skip = noAdmin,\n ) => conformanceCase(id, title, run, skip);\n\n /** Z-admin-rejects-api-key-session through the in-process guard, or through `delivery`'s transport. */\n const rejectsApiKeySession = async (\n delivery?: PolicyDelivery,\n ): Promise<ConformanceOutcome> => {\n if (!(await hasPlugin(auth, \"api-key\"))) {\n return conformanceSkip(\"the instance has no apiKey() plugin\");\n }\n const adminId = await kitUser(auth, { role: \"admin\" });\n const otherId = await kitUser(auth, { role: \"user\" });\n const key = await createKey(auth, adminId, {\n permissions: { project: [\"read\"] },\n });\n if (!(await keySessions(auth, key.key))) {\n return conformanceSkip(\n \"the instance's apiKey() plugin does not set enableSessionForAPIKeys (or reads no x-api-key header)\",\n );\n }\n const keyHeaders = new Headers({ [SDK_KEY_HEADER]: key.key });\n assert.equal(\n await sdkStatus(() =>\n api(auth).listUsers({ headers: keyHeaders, query: {} }),\n ),\n 401,\n \"Better Auth's listUsers accepted an API-key session\",\n );\n assert.equal(\n await sdkStatus(() =>\n api(auth).banUser({\n headers: keyHeaders,\n body: { userId: otherId },\n }),\n ),\n 401,\n \"Better Auth's banUser accepted an API-key session\",\n );\n const cookie = (await sessionHeaders(auth, adminId))!.get(\"cookie\")!;\n return withRequests(\n auth,\n {\n routes: {\n ban: [Require(adminRequirement(admin_, { user: [\"ban\"] }))],\n authoritative: [RequireAuth({ authoritative: true })],\n ordinary: [RequireAuth()],\n },\n },\n async ({ request }) => {\n assertDenied(\n await request(\"ban\", keyHeaders),\n 401,\n undefined,\n \"x-api-key alone on @RequirePermission({ user: ['ban'] })\",\n );\n assertDenied(\n await request(\"authoritative\", keyHeaders),\n 401,\n undefined,\n \"x-api-key alone on @RequireAuth({ authoritative: true })\",\n );\n const ordinary = await request(\"ordinary\", keyHeaders);\n assert.equal(\n ordinary.ok,\n true,\n `a default-freshness route rejected the key session: ${describeOutcome(ordinary)}`,\n );\n assertDenied(\n await request(\"authoritative\", {\n cookie,\n [SDK_KEY_HEADER]: key.key,\n }),\n 401,\n undefined,\n \"the admin's cookie with the key on an authoritative route (RK27)\",\n );\n },\n delivery,\n );\n };\n\n /**\n * Z-org-ref-types' input rows through the in-process guard, or through `delivery`'s transport: junk `orgId` values are\n * denied ORGANIZATION_REQUIRED without a Better Auth call and without an error log, the owner's ID is allowed.\n */\n const orgRefInputs = async (\n leaf: Requirement,\n delivery?: PolicyDelivery,\n ): Promise<{ headers: Headers; organizationId: string }> => {\n const ownerId = await kitUser(auth);\n const headers = (await sessionHeaders(auth, ownerId))!;\n const organizationId = await createOrganizationFor(auth, headers);\n await withRequests(\n auth,\n {\n routes: {\n org: [Require(withOrganization(leaf, fromParam(\"orgId\")))],\n },\n },\n async ({ request, probe, logger }) => {\n for (const value of [{ $ne: null }, 123, [\"a\"], \"\"]) {\n const from = probe.calls.length;\n assertDenied(\n await request(\"org\", headers, { orgId: value }),\n 403,\n \"ORGANIZATION_REQUIRED\",\n `orgId ${JSON.stringify(value)}`,\n );\n assert.deepEqual(\n betterAuthCalls(probe, from),\n [],\n `orgId ${JSON.stringify(value)} reached Better Auth`,\n );\n }\n const valid = await request(\"org\", headers, {\n orgId: organizationId,\n });\n assert.equal(\n valid.ok,\n true,\n `the owner's organization ID was denied: ${describeOutcome(valid)}`,\n );\n assert.deepEqual(\n logger.errors().map((entry) => entry.text),\n [],\n \"a rejected organization input was logged as an error\",\n );\n },\n delivery,\n );\n return { headers, organizationId };\n };\n\n const quotaRoutes = () => {\n const permission = orgPermission(\n { organization: [\"update\"] },\n { organization: fromParam(\"orgId\") },\n );\n const member = orgMember({ organization: fromParam(\"orgId\") });\n return {\n routes: { quota: [Require(permission, member)] },\n permission,\n member,\n };\n };\n\n /**\n * Z-apikey-quota-per-request's first setup through the in-process guard, or through `delivery`'s transport: an API-key\n * session on two org policies spends the key's quota 3 times per request. Returns the skip when the instance cannot.\n */\n const quotaSpend = async (\n delivery?: PolicyDelivery,\n ): Promise<ConformanceOutcome> => {\n if (!(await hasPlugin(auth, \"api-key\"))) {\n return conformanceSkip(\"the instance has no apiKey() plugin\");\n }\n const ownerId = await kitUser(auth);\n const headers = (await sessionHeaders(auth, ownerId))!;\n const organizationId = await createOrganizationFor(auth, headers);\n const key = await createKey(auth, ownerId, { remaining: 100 });\n if (!(await keySessions(auth, key.key))) {\n return conformanceSkip(\n \"the instance's apiKey() plugin does not set enableSessionForAPIKeys (or reads no x-api-key header)\",\n );\n }\n return withRequests(\n auth,\n { routes: quotaRoutes().routes },\n async ({ request }) => {\n const before = await remainingOf(auth, key.id);\n const outcome = await request(\n \"quota\",\n { [SDK_KEY_HEADER]: key.key },\n { orgId: organizationId },\n );\n assert.equal(\n outcome.ok,\n true,\n `the key owner's organization route was denied: ${describeOutcome(outcome)}`,\n );\n assert.equal(\n before - (await remainingOf(auth, key.id)),\n 3,\n \"one request with two credential-presenting org policies must spend 3\",\n );\n },\n delivery,\n );\n };\n\n /**\n * Z-admin-banned on one connection of `delivery`, whose connections reuse their principal for its declared TTL: the\n * connection keeps a signed-out user's principal for a default-freshness handler, while the authoritative admin handler\n * denies a banned or signed-out admin with a warm cookie cache on the connection's next message.\n */\n const bannedOnConnection = async (\n delivery: PolicyDelivery,\n ): Promise<ConformanceOutcome> => {\n if (!(await cookieCacheEnabled(auth))) {\n return conformanceSkip(\n \"the instance's session.cookieCache is off; run the kit on an instance with session.cookieCache.enabled\",\n );\n }\n const sdk = await sdkContext(auth);\n const banning = (await sessionHeaders(\n auth,\n await kitUser(auth, { role: \"admin\" }),\n ))!;\n const ttl = delivery.connectionPrincipalTtlMs;\n return withRequests(\n auth,\n {\n routes: {\n list: [Require(adminRequirement(admin_, { user: [\"list\"] }))],\n ordinary: [RequireAuth()],\n },\n },\n async ({ connect }) => {\n // The case runs only for deliveries with connect().\n const open = connect!;\n const reusing = await kitUser(auth, { role: \"admin\" });\n const connection = await open((await sessionHeaders(auth, reusing))!);\n try {\n const first = await connection.request(\"ordinary\");\n assert.equal(\n first.ok,\n true,\n `the connection's first message was denied: ${describeOutcome(first)}`,\n );\n await sdk.internalAdapter.deleteUserSessions(reusing);\n const reused = await connection.request(\"ordinary\");\n assert.equal(\n reused.ok,\n true,\n `the connection did not reuse its principal within its declared ${ttl} ms TTL: ${describeOutcome(reused)}`,\n );\n assertDenied(\n await connection.request(\"list\"),\n 401,\n undefined,\n \"an authoritative handler reused the connection's principal after sign-out\",\n );\n } finally {\n await connection.close();\n }\n for (const variant of [\"banned\", \"signed out everywhere\"]) {\n const userId = await kitUser(auth, { role: \"admin\" });\n const headers = (await sessionHeaders(auth, userId, {\n warmCache: true,\n }))!;\n const socket = await open(headers);\n try {\n for (const route of [\"list\", \"ordinary\"]) {\n const before = await socket.request(route);\n assert.equal(\n before.ok,\n true,\n `${variant}: ${route} denied the admin before: ${describeOutcome(before)}`,\n );\n }\n if (variant === \"banned\") {\n await api(auth).banUser({ headers: banning, body: { userId } });\n } else {\n await sdk.internalAdapter.deleteUserSessions(userId);\n }\n assertDenied(\n await socket.request(\"list\"),\n 401,\n undefined,\n `${variant}: the connection's next message still admitted the admin`,\n );\n } finally {\n await socket.close();\n }\n }\n },\n delivery,\n );\n };\n\n /** The delivery variants of the transport-specific rows, titled with the delivery's name. */\n const deliveryCases = (delivery: PolicyDelivery): ConformanceCase[] => {\n const title = (text: string) => `${delivery.name}: ${text}`;\n return [\n adminCase(\n \"Z-admin-rejects-api-key-session\",\n title(\n \"an admin's API-key session is rejected on admin and authoritative handlers and accepted on default-freshness handlers\",\n ),\n () => rejectsApiKeySession(delivery),\n ),\n adminCase(\n \"Z-admin-banned\",\n title(\n \"a banned or signed-out admin with a warm cookie cache is denied on the connection's next message despite its principal TTL\",\n ),\n () => bannedOnConnection(delivery),\n noAdmin ??\n (!delivery.connect\n ? \"the delivery opens no connections (connect())\"\n : !(delivery.connectionPrincipalTtlMs! > 0)\n ? \"the delivery's connections reuse no principal (connectionPrincipalTtlMs); the row applies to a principal TTL\"\n : undefined),\n ),\n conformanceCase(\n \"Z-org-ref-types\",\n title(\n \"fromParam rejects non-string organization inputs without a Better Auth call\",\n ),\n async () => {\n await orgRefInputs(orgLeaf!, delivery);\n },\n noOrg,\n ),\n conformanceCase(\n \"Z-apikey-quota-per-request\",\n title(\"an API-key session on org policies spends 3 per request\"),\n () => quotaSpend(delivery),\n noOrg,\n ),\n ];\n };\n\n return [\n adminCase(\n \"Z-admin-rejects-api-key\",\n \"an admin-owned API-key principal is denied PRINCIPAL_NOT_SUPPORTED without a Better Auth call, and 401 on a request\",\n async () => {\n const principal = await options.delegatedPrincipal!();\n const requirement = adminRequirement(admin_, { user: [\"ban\"] });\n await withHarness({ auth, requirement }, async ({ decide, probe }) => {\n const calls = probe.calls.length;\n const storage = probe.storage.length;\n const decision = await decide(principal);\n assert.equal(decision.effect, \"deny\", JSON.stringify(decision));\n assert.equal(\n (decision as { reason?: string }).reason,\n \"PRINCIPAL_NOT_SUPPORTED\",\n JSON.stringify(decision),\n );\n assert.deepEqual(\n probe.calls.slice(calls),\n [],\n \"the evaluator called Better Auth for an unsupported principal\",\n );\n assert.equal(\n probe.storage.length,\n storage,\n \"the evaluator read storage for an unsupported principal\",\n );\n });\n const keys: KitKeys = {\n keys: new Map([\n [\n \"conformance-admin-key\",\n { userId: principal.userId ?? \"\", grant: { user: [\"ban\"] } },\n ],\n ]),\n verifications: 0,\n };\n return withRequests(\n auth,\n {\n routes: { ban: [Require(requirement)] },\n sources: [kitKeySource(keys)],\n },\n async ({ request }) => {\n const outcome = await request(\"ban\", {\n [KIT_KEY_HEADER]: \"conformance-admin-key\",\n });\n assertDenied(\n outcome,\n 401,\n UNAUTHENTICATED,\n \"an API key on a session-only admin route\",\n );\n assert.equal(\n keys.verifications,\n 0,\n \"the route verified an API key it does not accept\",\n );\n },\n );\n },\n noAdmin ??\n (options.delegatedPrincipal\n ? undefined\n : \"the options give no delegatedPrincipal()\"),\n ),\n adminCase(\n \"Z-admin-rejects-api-key-session\",\n \"an admin's API-key session is rejected on admin and authoritative routes and accepted on default-freshness routes\",\n () => rejectsApiKeySession(),\n ),\n adminCase(\n \"Z-admin-banned\",\n \"a banned or signed-out admin with a warm cookie cache is denied on the next request; a banned key owner until banExpires\",\n async () => {\n if (!(await cookieCacheEnabled(auth))) {\n return conformanceSkip(\n \"the instance's session.cookieCache is off; run the kit on an instance with session.cookieCache.enabled\",\n );\n }\n const sdk = await sdkContext(auth);\n const banning = await sessionHeaders(\n auth,\n await kitUser(auth, { role: \"admin\" }),\n );\n await withRequests(\n auth,\n {\n routes: {\n list: [Require(adminRequirement(admin_, { user: [\"list\"] }))],\n },\n },\n async ({ request }) => {\n for (const variant of [\"banned\", \"signed out everywhere\"]) {\n const userId = await kitUser(auth, { role: \"admin\" });\n const headers = (await sessionHeaders(auth, userId, {\n warmCache: true,\n }))!;\n const before = await request(\"list\", headers);\n assert.equal(\n before.ok,\n true,\n `${variant}: the admin was denied before: ${describeOutcome(before)}`,\n );\n if (variant === \"banned\") {\n await api(auth).banUser({\n headers: banning!,\n body: { userId },\n });\n } else {\n await sdk.internalAdapter.deleteUserSessions(userId);\n }\n assertDenied(\n await request(\"list\", headers),\n 401,\n undefined,\n `${variant}: the warm cookie cache still admitted the admin`,\n );\n }\n },\n );\n return withHarness(\n {\n auth,\n requirement: adminRequirement(\n admin_,\n { user: [\"set-role\"] },\n BOTH_KINDS,\n ),\n },\n async ({ decide }) => {\n const ownerId = await kitUser(auth, { role: \"admin\" });\n const principal = kitKeyPrincipal(ownerId, { user: [\"set-role\"] });\n assert.equal(\n (await decide(principal)).effect,\n \"allow\",\n \"the admin's key was denied before the ban\",\n );\n await sdk.internalAdapter.updateUser(ownerId, {\n banned: true,\n banExpires: new Date(Date.now() + 3_600_000),\n });\n assert.deepEqual(\n await decide(principal),\n { effect: \"deny\", status: 401, reason: \"USER_BANNED\" },\n \"a banned owner's key was not denied USER_BANNED\",\n );\n await sdk.internalAdapter.updateUser(ownerId, {\n banExpires: new Date(Date.now() - 1_000),\n });\n assert.equal(\n (await decide(principal)).effect,\n \"allow\",\n \"the key stayed denied after banExpires passed\",\n );\n },\n );\n },\n ),\n adminCase(\n \"Z-admin-custom-session-role\",\n \"with customSession role shapes, @RequirePermission answers as Better Auth's listUsers, never a 500\",\n async () => {\n const computed = new Map<string, string>();\n const shapes: [\n string,\n (user: { id: string; role?: unknown }) => unknown,\n ][] = [\n [\"an array role\", (user) => [user.role]],\n [\n \"a display label\",\n (user) => (user.role === \"admin\" ? \"Administrator\" : \"Member\"),\n ],\n [\n \"a role computed from app data\",\n (user) => computed.get(user.id) ?? \"viewer\",\n ],\n ];\n for (const [shape, roleOf] of shapes) {\n const kitAuth = await variantOf(options, {\n plugins: [\n admin(),\n customSession(async ({ user, session }) => ({\n user: {\n ...user,\n role: roleOf(user as { id: string; role?: unknown }),\n },\n session,\n })),\n ],\n });\n const adminId = await kitUser(kitAuth, { role: \"admin\" });\n const plainId = await kitUser(kitAuth, { role: \"user\" });\n computed.set(adminId, \"user\");\n computed.set(plainId, \"admin\");\n await withRequests(\n kitAuth,\n {\n routes: {\n list: [Require(adminRequirement(admin_, { user: [\"list\"] }))],\n },\n },\n async ({ request }) => {\n for (const [name, userId] of [\n [\"admin\", adminId],\n [\"plain user\", plainId],\n ] as const) {\n const headers = (await sessionHeaders(kitAuth, userId))!;\n const expected = await sdkStatus(() =>\n api(kitAuth).listUsers({ headers, query: {} }),\n );\n const outcome = await request(\"list\", headers);\n assert.notEqual(\n statusOf(outcome),\n 500,\n `${shape}, ${name}: ${describeOutcome(outcome)}`,\n );\n assert.equal(\n statusOf(outcome),\n expected,\n `${shape}, ${name}: the route answered ${describeOutcome(outcome)}, listUsers ${expected}`,\n );\n }\n },\n );\n }\n },\n ),\n adminCase(\n \"Z-admin-deleted-user\",\n \"a deleted key owner and a user deleted after the guard's read are denied 401 USER_NOT_FOUND, never 5xx\",\n () =>\n withHarness(\n {\n auth,\n requirement: adminRequirement(\n admin_,\n { user: [\"list\"] },\n BOTH_KINDS,\n ),\n },\n async ({ decide, logger }) => {\n const sdk = await sdkContext(auth);\n const ownerId = await kitUser(auth, { role: \"admin\" });\n await sdk.internalAdapter.deleteUser(ownerId);\n const delegated = await settle(() =>\n decide(kitKeyPrincipal(ownerId, { user: [\"list\"] })),\n );\n assert.deepEqual(\n delegated.ok && delegated.value,\n { effect: \"deny\", status: 401, reason: \"USER_NOT_FOUND\" },\n `a key whose owner was deleted: ${String(!delegated.ok && delegated.error)}`,\n );\n const userId = await kitUser(auth, { role: \"admin\" });\n const headers = (await sessionHeaders(auth, userId))!;\n const principal = await sessionPrincipalOf(auth, headers);\n const session = await settle(() =>\n decide(principal, {\n headers,\n beforeEvaluate: () => sdk.internalAdapter.deleteUser(userId),\n }),\n );\n assert.deepEqual(\n session.ok && session.value,\n { effect: \"deny\", status: 401, reason: \"USER_NOT_FOUND\" },\n `a user deleted between the guard's read and the policy's call: ${String(!session.ok && session.error)}`,\n );\n assert.deepEqual(\n logger.errors(),\n [],\n \"a deleted user was logged as an error\",\n );\n },\n ),\n ),\n adminCase(\n \"Z-admin-null-role\",\n \"a NULL or empty stored role answers 403 MISSING_PERMISSION as listUsers does, adminUserIds allows, never a 500\",\n async () => {\n const listedId = `conformance-listed-${globalThis.crypto.randomUUID()}`;\n const kitAuth = await variantOf(options, {\n plugins: [admin({ adminUserIds: [listedId] })],\n });\n const nullId = await kitUser(kitAuth, { role: \"user\" });\n await kitUser(kitAuth, { id: listedId, role: \"user\" });\n const emptyId = await kitUser(kitAuth, { role: \"user\" });\n await setRole(kitAuth, nullId, null);\n await setRole(kitAuth, listedId, null);\n await setRole(kitAuth, emptyId, \"\");\n const rows = [\n [\"a NULL role\", nullId, 403],\n [\"a NULL role listed in adminUserIds\", listedId, 200],\n [\"an empty-string role\", emptyId, 403],\n ] as const;\n await withRequests(\n kitAuth,\n {\n routes: {\n list: [Require(adminRequirement(admin_, { user: [\"list\"] }))],\n },\n },\n async ({ request }) => {\n for (const [name, userId, status] of rows) {\n const headers = (await sessionHeaders(kitAuth, userId))!;\n assert.equal(\n await sdkStatus(() =>\n api(kitAuth).listUsers({ headers, query: {} }),\n ),\n status,\n `${name}: Better Auth's listUsers answered otherwise`,\n );\n const outcome = await request(\"list\", headers);\n if (status === 200) {\n assert.equal(\n outcome.ok,\n true,\n `${name}, session: ${describeOutcome(outcome)}`,\n );\n } else {\n assertDenied(\n outcome,\n 403,\n \"MISSING_PERMISSION\",\n `${name}, session`,\n );\n }\n }\n },\n );\n return withHarness(\n {\n auth: kitAuth,\n requirement: adminRequirement(\n admin_,\n { user: [\"list\"] },\n BOTH_KINDS,\n ),\n },\n async ({ decide }) => {\n for (const [name, userId, status] of rows) {\n const result = await settle(() =>\n decide(kitKeyPrincipal(userId, { user: [\"list\"] })),\n );\n assert.ok(\n result.ok,\n `${name}, API key: the policy threw ${String(!result.ok && result.error)}`,\n );\n assert.deepEqual(\n result.value,\n status === 200\n ? { effect: \"allow\" }\n : { effect: \"deny\", reason: \"MISSING_PERMISSION\" },\n `${name}, API key`,\n );\n }\n },\n );\n },\n ),\n adminCase(\n \"Z-admin-dynamic-base-url\",\n \"a dynamic baseURL without fallback fails boot (B20); with fallback the admin route is decided\",\n async () => {\n const allowedHosts = [new URL(KIT_BASE_URL).host];\n const requirement = adminRequirement(admin_, { user: [\"list\"] });\n const without = await settle(async () =>\n boot(\n await variantOf(options, {\n baseURL: { allowedHosts },\n plugins: [admin()],\n }),\n requirement,\n ),\n );\n if (without.ok) {\n await without.value.moduleRef.close();\n assert.fail(\"a dynamic baseURL without fallback booted\");\n }\n assert.ok(\n bootIssueCodes(without.error).includes(\n \"DYNAMIC_BASE_URL_WITHOUT_FALLBACK\",\n ),\n String(without.error),\n );\n const kitAuth = await variantOf(options, {\n baseURL: { allowedHosts, fallback: KIT_BASE_URL },\n plugins: [admin()],\n });\n const adminId = await kitUser(kitAuth, { role: \"admin\" });\n const plainId = await kitUser(kitAuth, { role: \"user\" });\n return withRequests(\n kitAuth,\n { routes: { list: [Require(requirement)] } },\n async ({ request }) => {\n const allowed = await request(\n \"list\",\n (await sessionHeaders(kitAuth, adminId))!,\n );\n assert.equal(\n allowed.ok,\n true,\n `the admin was not allowed: ${describeOutcome(allowed)}`,\n );\n assertDenied(\n await request(\"list\", (await sessionHeaders(kitAuth, plainId))!),\n 403,\n \"MISSING_PERMISSION\",\n \"a plain user\",\n );\n },\n );\n },\n ),\n conformanceCase(\n \"Z-org-ref-types\",\n \"fromParam rejects non-string organization inputs without a call; a literal 'active' is an ID; customSession shapes use getActiveMember\",\n async () => {\n const leaf = orgLeaf!;\n const { headers, organizationId } = await orgRefInputs(leaf);\n await api(auth).setActiveOrganization({\n headers,\n body: { organizationId },\n });\n const principal = await sessionPrincipalOf(auth, headers);\n await withHarness(\n {\n auth,\n requirement: {\n anyOf: [\n withOrganization(\n leaf,\n organizationRef(() => \"active\"),\n ),\n withOrganization(leaf, activeOrganization()),\n ],\n },\n },\n async ({ decide, probe }) => {\n const from = probe.calls.length;\n const decision = await decide(principal, { headers });\n assert.equal(\n decision.effect,\n \"allow\",\n `the default ref denied the active organization: ${JSON.stringify(decision)}`,\n );\n assert.equal(\n betterAuthCalls(probe, from).length,\n 2,\n `a literal 'active' and the default ref made ${betterAuthCalls(probe, from).length} calls`,\n );\n },\n );\n const shaped = await variantOf(options, {\n plugins: [\n organization(),\n customSession(async ({ user, session }) => ({\n user,\n session: {\n id: session.id,\n userId: session.userId,\n token: session.token,\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n expiresAt: session.expiresAt,\n },\n })),\n ],\n });\n const shapedOwner = await kitUser(shaped);\n const shapedHeaders = (await sessionHeaders(shaped, shapedOwner))!;\n const shapedOrganization = await createOrganizationFor(\n shaped,\n shapedHeaders,\n );\n await api(shaped).setActiveOrganization({\n headers: shapedHeaders,\n body: { organizationId: shapedOrganization },\n });\n const shapedPrincipal = await sessionPrincipalOf(shaped, shapedHeaders);\n return withHarness(\n {\n auth: shaped,\n requirement: withOrganization(leaf, activeOrganization()),\n },\n async ({ decide, probe }) => {\n const from = probe.calls.length;\n const invocation = {};\n const decision = await decide(shapedPrincipal, {\n headers: shapedHeaders,\n invocation,\n });\n assert.equal(decision.effect, \"allow\", JSON.stringify(decision));\n assert.ok(\n betterAuthCalls(probe, from).includes(\n \"/organization/get-active-member\",\n ),\n `the default ref did not call getActiveMember: ${betterAuthCalls(probe, from).join(\", \")}`,\n );\n const published = (\n Reflect.get(invocation, INVOCATION_VALUES) as\n | Map<string, Map<symbol, unknown>>\n | undefined\n )\n ?.get(\"default\")\n ?.get(ACTIVE_ORGANIZATION_ID);\n assert.equal(\n published,\n shapedOrganization,\n \"the policy did not publish the active organization ID\",\n );\n },\n );\n },\n noOrg,\n ),\n conformanceCase(\n \"Z-apikey-quota-per-request\",\n \"an API-key session on org policies spends 3 per request, with W_API_KEY_SESSION_MULTIPLIER naming them\",\n async () => {\n const spent = await quotaSpend();\n if (spent) {\n return spent;\n }\n const { routes, permission, member } = quotaRoutes();\n const advice = async (\n target: AuthLike,\n session?: { apiKeySessions: boolean },\n ) => {\n const booted = await boot(target, undefined, {\n routes,\n ...(session ? { session } : {}),\n });\n await booted.moduleRef.close();\n return booted.logger.entries\n .filter((entry) => entry.level === \"warn\")\n .map((entry) => entry.text);\n };\n const line = (lines: readonly string[], code: string) =>\n lines.find((text) => text.startsWith(`${code}:`));\n const conditional = \"If enableSessionForAPIKeys is enabled\";\n for (const [label, lines, factual] of [\n [\"by default\", await advice(auth), false],\n [\n \"with session.apiKeySessions: true\",\n await advice(auth, { apiKeySessions: true }),\n true,\n ],\n ] as const) {\n const full = line(lines, \"W_API_KEY_FULL_SESSION\");\n const multiplier = line(lines, \"W_API_KEY_SESSION_MULTIPLIER\");\n assert.ok(full, `${label}: no W_API_KEY_FULL_SESSION`);\n assert.ok(multiplier, `${label}: no W_API_KEY_SESSION_MULTIPLIER`);\n for (const id of [permission.policy, member.policy].map(\n (policy) => (policy as AuthorizationPolicy<unknown>).id,\n )) {\n assert.ok(\n multiplier.includes(id),\n `${label}: W_API_KEY_SESSION_MULTIPLIER does not name ${id}: ${multiplier}`,\n );\n }\n for (const text of [full, multiplier]) {\n assert.equal(\n text.includes(conditional),\n !factual,\n `${label}: ${text}`,\n );\n }\n }\n for (const [label, lines] of [\n [\n \"with session.apiKeySessions: false\",\n await advice(auth, { apiKeySessions: false }),\n ],\n [\n \"without the api-key plugin\",\n await advice(\n await variantOf(options, { plugins: [organization()] }),\n ),\n ],\n ] as const) {\n assert.deepEqual(\n lines.filter((text) => text.startsWith(\"W_API_KEY_\")),\n [],\n `${label}: API-key session advice was emitted`,\n );\n }\n },\n noOrg,\n ),\n conformanceCase(\n \"Z-apikey-quota-per-request\",\n \"a key resolved by an API-key source on @RequireApiKeyPermission spends 1 per request\",\n async () => {\n const leaf = keyLeaf!;\n if (!(await hasPlugin(auth, \"api-key\"))) {\n return conformanceSkip(\"the instance has no apiKey() plugin\");\n }\n const sources = options.sources ?? [];\n if (\n !sources.some(\n (source) =>\n typeof source === \"object\" &&\n source !== null &&\n \"kinds\" in source &&\n (source.kinds as readonly string[]).includes(API_KEY_KIND),\n )\n ) {\n return conformanceSkip(\n \"the options give no source of the 'api-key' kind (sources: [apiKeyPrincipal()])\",\n );\n }\n const ownerId = await kitUser(auth);\n const key = await createKey(auth, ownerId, {\n remaining: 100,\n permissions: leaf.params as Permissions,\n });\n return withRequests(\n auth,\n { routes: { quota: [Require(options.requirement)] }, sources },\n async ({ request }) => {\n const before = await remainingOf(auth, key.id);\n const outcome = await request(\"quota\", {\n [SDK_KEY_HEADER]: key.key,\n });\n assert.equal(\n outcome.ok,\n true,\n `a key granting the requirement was denied: ${describeOutcome(outcome)}`,\n );\n assert.equal(\n before - (await remainingOf(auth, key.id)),\n 1,\n \"one request on @RequireApiKeyPermission must spend 1\",\n );\n },\n );\n },\n keyLeaf\n ? undefined\n : `the requirement contains no built-in API-key permission policy (${API_KEY_POLICY})`,\n ),\n conformanceCase(\n \"Z-class-policy-requires\",\n \"a class policy's instance requires field sets accepted kinds and freshness, by class and by string token\",\n async () => {\n const evaluations = { principals: 0, fresh: 0 };\n class PrincipalsPolicy implements AuthorizationPolicy<object> {\n readonly id = \"@nestjs-kit/better-auth:conformance/class-principals\";\n readonly requires = { principals: BOTH_KINDS };\n\n evaluate() {\n evaluations.principals++;\n return allow();\n }\n }\n class FreshPolicy implements AuthorizationPolicy<object> {\n readonly id = \"@nestjs-kit/better-auth:conformance/class-fresh\";\n readonly requires = { freshIdentity: true };\n\n evaluate() {\n evaluations.fresh++;\n return allow();\n }\n }\n const principalsToken =\n \"@nestjs-kit/better-auth:conformance/class-principals-token\";\n const freshToken =\n \"@nestjs-kit/better-auth:conformance/class-fresh-token\";\n const userId = await kitUser(auth);\n const user = await (await sdkContext(auth)).adapter.findOne<\n Record<string, unknown>\n >({ model: \"user\", where: [{ field: \"id\", value: userId }] });\n const keys: KitKeys = {\n keys: new Map([[\"conformance-class-key\", { userId, grant: {} }]]),\n verifications: 0,\n };\n return withRequests(\n auth,\n {\n routes: {\n principalsClass: [\n Require({ policy: PrincipalsPolicy as never, params: {} }),\n ],\n principalsToken: [\n Require({ policy: principalsToken, params: {} }),\n ],\n freshClass: [\n Require({ policy: FreshPolicy as never, params: {} }),\n ],\n freshToken: [Require({ policy: freshToken, params: {} })],\n ordinary: [RequireAuth()],\n },\n sources: [kitKeySource(keys)],\n providers: [\n PrincipalsPolicy,\n FreshPolicy,\n { provide: principalsToken, useClass: PrincipalsPolicy },\n { provide: freshToken, useClass: FreshPolicy },\n ],\n },\n async ({ request, probe }) => {\n for (const route of [\"principalsClass\", \"principalsToken\"]) {\n const verifications = keys.verifications;\n const count = evaluations.principals;\n const outcome = await request(route, {\n [KIT_KEY_HEADER]: \"conformance-class-key\",\n });\n assert.equal(\n outcome.ok,\n true,\n `${route}: an API key was not admitted: ${describeOutcome(outcome)}`,\n );\n assert.equal(\n keys.verifications,\n verifications + 1,\n `${route}: the key source did not run`,\n );\n assert.equal(evaluations.principals, count + 1);\n }\n // A session a plugin's before hook places for /get-session, as apiKey's enableSessionForAPIKeys does.\n probe.respond = (path, headers) =>\n path === \"/get-session\" && headers?.has(MOCK_SESSION_HEADER)\n ? {\n user,\n session: {\n id: `conformance-mock-${userId}`,\n token: \"conformance-mock\",\n userId,\n createdAt: new Date(),\n updatedAt: new Date(),\n expiresAt: new Date(Date.now() + 3_600_000),\n },\n }\n : undefined;\n const mocked = { [MOCK_SESSION_HEADER]: \"1\" };\n const ordinary = await request(\"ordinary\", mocked);\n assert.equal(\n ordinary.ok,\n true,\n `a default-freshness route rejected the hook-placed session: ${describeOutcome(ordinary)}`,\n );\n for (const route of [\"freshClass\", \"freshToken\"]) {\n assertDenied(\n await request(route, mocked),\n 401,\n undefined,\n `${route}: a hook-placed session on a freshIdentity route`,\n );\n }\n assert.equal(\n evaluations.fresh,\n 0,\n \"a freshIdentity class policy was evaluated for a hook-placed session\",\n );\n },\n );\n },\n ),\n ...(options.deliveries ?? []).flatMap(deliveryCases),\n ];\n}\n","import assert from \"node:assert/strict\";\nimport { Inject, Injectable, Scope } from \"@nestjs/common\";\nimport { APIError } from \"better-auth/api\";\nimport type {\n AuthorizationContext,\n AuthorizationDecision,\n AuthorizationPolicy,\n Requirement,\n} from \"./auth-contracts.js\";\nimport { Require } from \"./auth-decorators.js\";\nimport {\n isAuthFailure,\n isConfigurationError,\n isInfrastructureError,\n} from \"./auth-errors.js\";\nimport type { AuthPrincipal } from \"./auth-types.js\";\nimport {\n bootIssueCodes,\n type ConformanceCase,\n conformanceCase,\n conformanceSkip,\n type ConformanceOutcome,\n settle,\n} from \"./conformance-fixtures.js\";\nimport {\n betterAuthCalls,\n boot,\n type Harness,\n hasPlugin,\n KIT_ROUTE,\n type PolicyConformanceOptions,\n requirementsOf,\n sdkContext,\n sessionHeaders,\n sessionReads,\n staticPolicies,\n variantOf,\n withHarness,\n} from \"./conformance-policy-harness.js\";\nimport { unitPolicyCases } from \"./conformance-policy-units.js\";\n\nexport type {\n PolicyConformanceOptions,\n PolicyDelivery,\n PolicyDeliveryConnection,\n} from \"./conformance-policy-harness.js\";\n\nconst noGrant = {\n description: \"conformance: no grant\",\n allows: () => false,\n};\n\n/**\n * The evaluator's answer to a session that ended between the guard's read and the policy's call: 401 (the guard's\n * UNAUTHENTICATED) with Better Auth's generic code as `reason`, or UNAUTHENTICATED when the 401 carried no code.\n */\nfunction isSessionLoss(decision: AuthorizationDecision): boolean {\n return (\n decision.effect === \"deny\" &&\n decision.status === 401 &&\n (decision.reason === \"UNAUTHORIZED\" ||\n decision.reason === \"UNAUTHENTICATED\")\n );\n}\n\n/** Storage operations on the session model since `from` (database reads and writes of sessions). */\nfunction sessionStorage(storage: readonly string[], from: number): number {\n return storage.slice(from).filter((entry) => entry.endsWith(\":session\"))\n .length;\n}\n\nconst SCOPED_DEPENDENCY =\n \"@nestjs-kit/better-auth:conformance/request-scoped-dependency\";\n\n/**\n * The unit's first policy as a DI class policy with one injected dependency, whose provider scope the case chooses:\n * the same requirement then boots with a singleton dependency and fails B11 with a request-scoped one.\n */\nfunction classPolicyFor(policy: AuthorizationPolicy<unknown>) {\n @Injectable()\n class ConformanceClassPolicy implements AuthorizationPolicy<unknown> {\n readonly id = `${policy.id}#conformance-class`;\n readonly requires = policy.requires;\n\n constructor(\n @Inject(SCOPED_DEPENDENCY)\n readonly dependency: { readonly scope: string },\n ) {}\n\n evaluate(\n params: unknown,\n context: AuthorizationContext,\n ): AuthorizationDecision | Promise<AuthorizationDecision> {\n return policy.evaluate(params, context as never);\n }\n }\n return ConformanceClassPolicy;\n}\n\n/**\n * The authorization-policy kit (invariants Z1–Z6 and the unit-specific rows of design §14.1). Each principal is judged\n * through the real AuthorizationEvaluator, so the delegation gate, error normalization and the per-invocation\n * decision memo apply exactly as in the guard; an infrastructure error thrown here is the guard's 5xx. Cases that\n * need route planning, acceptance or principal resolution send an in-process request through the real\n * BetterAuthGuard. Storage outages are injected into the instance's database adapter, so an endpoint that swallows a\n * storage error into a 401 is exercised; APIError mapping uses the probe plugin's before hook. Requirements must name\n * policy objects (see PolicyConformanceOptions.requirement). Unit-specific cases run when the requirement contains\n * the built-in admin, organization or API-key policy and skip with the reason otherwise.\n */\nexport function policyConformance(\n options: PolicyConformanceOptions,\n): ConformanceCase[] {\n const add = (\n id: string,\n title: string,\n run: (harness: Harness) => Promise<ConformanceOutcome>,\n skip?: string,\n ) => conformanceCase(id, title, () => withHarness(options, run), skip);\n const known = staticPolicies(options.requirement);\n // Z5 is about leaves that name no kinds; a leaf that names the delegated kind may allow it, so any naming leaf skips.\n const kindsNamed = requirementsOf(options.requirement).some(\n (item, index) =>\n item.principals !== undefined ||\n known[index]?.requires?.principals !== undefined,\n );\n const plugins = [\n ...new Set(known.flatMap((policy) => policy.requires?.plugins ?? [])),\n ];\n const infraThrows =\n (warmCache: boolean) =>\n async ({ decide, probe, auth }: Harness): Promise<ConformanceOutcome> => {\n const principal = await options.allowingPrincipal();\n if (warmCache && (!principal.userId || principal.delegation)) {\n return conformanceSkip(\n \"the allowing principal carries no session cookie for a cookie cache\",\n );\n }\n const headers = warmCache\n ? await sessionHeaders(auth, principal.userId!, { warmCache: true })\n : undefined;\n if (headers === null) {\n return conformanceSkip(\n \"the instance's session.cookieCache is off; run the kit on an instance with session.cookieCache.enabled for this variant\",\n );\n }\n const customSession = await hasPlugin(auth, \"custom-session\");\n let calls = probe.calls.length;\n let storage = probe.storage.length;\n const result = await settle(() =>\n decide(principal, {\n ...(headers ? { headers } : {}),\n beforeEvaluate: () => {\n calls = probe.calls.length;\n storage = probe.storage.length;\n probe.storageFault = () => new Error(\"conformance storage outage\");\n },\n }),\n );\n probe.storageFault = undefined;\n if (\n betterAuthCalls(probe, calls).length === 0 &&\n probe.storage.length === storage\n ) {\n return conformanceSkip(\n \"the policy read no storage and called no Better Auth endpoint for the allowing principal\",\n );\n }\n if (customSession && result.ok && isSessionLoss(result.value)) {\n // RK2: customSession swallows the failure of its inner session read, the re-classification read included.\n return;\n }\n assert.equal(\n result.ok,\n false,\n `a storage outage was decided: ${JSON.stringify(result.ok && result.value)}`,\n );\n assert.ok(\n isInfrastructureError(!result.ok && result.error),\n String(!result.ok && result.error),\n );\n };\n return [\n add(\n \"Z-deny-decision\",\n \"the allowing principal is allowed and the denying principal gets a deny value, never a throw\",\n async ({ decide }) => {\n const allowed = await decide(await options.allowingPrincipal());\n assert.equal(\n allowed.effect,\n \"allow\",\n `the allowing principal was denied: ${JSON.stringify(allowed)}`,\n );\n const result = await settle(async () =>\n decide(await options.denyingPrincipal()),\n );\n assert.equal(\n result.ok,\n true,\n `the policy threw for a denial: ${String(!result.ok && result.error)}`,\n );\n const decision = result.ok ? result.value : undefined;\n assert.equal(decision?.effect, \"deny\");\n assert.equal(\n typeof (decision as { reason?: unknown }).reason,\n \"string\",\n );\n },\n ),\n add(\n \"Z-infra-throws\",\n \"a storage outage after the session read is infrastructure, never a denial (cookie cache off)\",\n infraThrows(false),\n ),\n add(\n \"Z-infra-throws\",\n \"a storage outage after the session read is infrastructure, never a denial (warm cookie cache)\",\n infraThrows(true),\n ),\n add(\n \"Z-apierror-mapping\",\n \"APIErrors escaping the policy map to re-classification, denials, 429, configuration and infrastructure errors\",\n async ({ decide, probe }) => {\n const principal = await options.allowingPrincipal();\n const sessionBacked = principal.source === \"better-auth:session\";\n const variants: {\n error: () => unknown;\n expect: (\n result: Awaited<ReturnType<typeof settle<AuthorizationDecision>>>,\n ) => void;\n }[] = [\n ...[\n () => new APIError(\"UNAUTHORIZED\"),\n () =>\n new APIError(\"UNAUTHORIZED\", {\n code: \"UNAUTHORIZED\",\n message: \"Unauthorized\",\n }),\n ].map((error) => ({\n error,\n expect: (\n result: Awaited<ReturnType<typeof settle<AuthorizationDecision>>>,\n ) => {\n if (sessionBacked) {\n assert.ok(\n !result.ok && isInfrastructureError(result.error),\n `a generic 401 with a live session must be infrastructure: ${JSON.stringify(result.ok && result.value)}`,\n );\n } else {\n assert.deepEqual(result.ok && result.value, {\n effect: \"deny\",\n status: 401,\n reason: \"UNAUTHENTICATED\",\n });\n }\n },\n })),\n {\n error: () =>\n new APIError(\"UNAUTHORIZED\", {\n code: \"CONFORMANCE_CODED\",\n message: \"coded\",\n }),\n expect: (result) => {\n assert.equal(result.ok && result.value.effect, \"deny\");\n assert.equal(\n result.ok && (result.value as { reason?: string }).reason,\n \"CONFORMANCE_CODED\",\n );\n assert.equal(\n result.ok && (result.value as { status?: number }).status,\n 403,\n );\n },\n },\n {\n error: () =>\n new APIError(\"FORBIDDEN\", {\n code: \"CONFORMANCE_FORBIDDEN\",\n message: \"forbidden\",\n }),\n expect: (result) => {\n assert.equal(\n result.ok && (result.value as { reason?: string }).reason,\n \"CONFORMANCE_FORBIDDEN\",\n );\n },\n },\n {\n error: () => new APIError(\"TOO_MANY_REQUESTS\"),\n expect: (result) => {\n assert.ok(\n !result.ok &&\n isAuthFailure(result.error) &&\n result.error.status === 429,\n \"a 429 must propagate as a rate-limit failure\",\n );\n },\n },\n {\n error: () => new APIError(\"BAD_REQUEST\", { code: \"CONFORMANCE\" }),\n expect: (result) => {\n assert.ok(\n !result.ok && isConfigurationError(result.error),\n \"another 4xx must be a configuration error\",\n );\n },\n },\n {\n error: () => new APIError(\"INTERNAL_SERVER_ERROR\"),\n expect: (result) => {\n assert.ok(\n !result.ok && isInfrastructureError(result.error),\n \"a 5xx must be infrastructure\",\n );\n },\n },\n ];\n for (const variant of variants) {\n const from = probe.calls.length;\n probe.fault = (path) =>\n path === \"/get-session\" ? undefined : variant.error();\n const result = await settle(() => decide(principal));\n probe.fault = undefined;\n if (betterAuthCalls(probe, from).length === 0) {\n return conformanceSkip(\n \"the policy calls no Better Auth endpoint for the allowing principal\",\n );\n }\n variant.expect(result);\n }\n },\n ),\n add(\n \"Z-policy-session-lost\",\n \"a session lost before the policy's call is 401, a storage failure there is 5xx, each with one re-read per request\",\n async ({ decide, probe, auth }) => {\n const principal = await options.allowingPrincipal();\n if (principal.source !== \"better-auth:session\" || !principal.userId) {\n return conformanceSkip(\n \"the allowing principal is not a session principal of the built-in session source\",\n );\n }\n const userId = principal.userId;\n const sdk = await sdkContext(auth);\n const customSession = await hasPlugin(auth, \"custom-session\");\n // Revoked: both invocations of one request answer 401 and share one re-classification read.\n const revoked = {\n key: {},\n headers: await sessionHeaders(auth, userId),\n };\n let reads = probe.calls.length;\n let storage = probe.storage.length;\n const first = await decide(principal, {\n key: revoked.key,\n invocation: {},\n headers: revoked.headers!,\n beforeEvaluate: async () => {\n await sdk.internalAdapter.deleteUserSessions(userId);\n reads = probe.calls.length;\n storage = probe.storage.length;\n },\n });\n if (\n first.effect === \"allow\" &&\n sessionStorage(probe.storage, storage) === 0\n ) {\n return conformanceSkip(\n \"the policy's Better Auth calls do not read the principal's session\",\n );\n }\n const second = await decide(principal, {\n key: revoked.key,\n invocation: {},\n headers: revoked.headers!,\n });\n for (const decision of [first, second]) {\n assert.ok(\n isSessionLoss(decision),\n `a session revoked before the policy's call must deny 401 UNAUTHENTICATED: ${JSON.stringify(decision)}`,\n );\n }\n assert.equal(\n sessionReads(probe, reads),\n 1,\n `two invocations of one request re-read the session ${sessionReads(probe, reads)} times`,\n );\n // Storage failure at the same point: infrastructure (customSession: the documented 401, RK2).\n const failing = {\n key: {},\n headers: await sessionHeaders(auth, userId),\n };\n const outcomes = [];\n for (const index of [0, 1]) {\n outcomes.push(\n await settle(() =>\n decide(principal, {\n key: failing.key,\n invocation: {},\n headers: failing.headers!,\n beforeEvaluate: () => {\n if (index === 0) {\n reads = probe.calls.length;\n }\n probe.storageFault = () =>\n new Error(\"conformance storage outage\");\n },\n }),\n ),\n );\n }\n probe.storageFault = undefined;\n for (const outcome of outcomes) {\n if (customSession) {\n assert.ok(\n outcome.ok && isSessionLoss(outcome.value),\n `with customSession a storage failure must answer the documented 401: ${outcome.ok ? JSON.stringify(outcome.value) : String(outcome.error)}`,\n );\n } else {\n assert.ok(\n !outcome.ok && isInfrastructureError(outcome.error),\n `a storage failure at the policy's call must be infrastructure: ${JSON.stringify(outcome.ok && outcome.value)}`,\n );\n }\n }\n assert.equal(\n sessionReads(probe, reads),\n 1,\n `two invocations of one request re-read the session ${sessionReads(probe, reads)} times during the outage`,\n );\n },\n ),\n add(\n \"Z-delegation-scope\",\n \"a delegated principal is never allowed beyond its own grant\",\n async ({ decide }) => {\n const principal = await options.delegatedPrincipal!();\n assert.ok(\n principal.delegation,\n \"delegatedPrincipal() must carry delegation\",\n );\n const narrowed = { ...principal, delegation: noGrant } as AuthPrincipal;\n const decision = await decide(narrowed);\n assert.equal(\n decision.effect,\n \"deny\",\n \"the policy widened a delegated principal beyond its grant\",\n );\n },\n options.delegatedPrincipal\n ? undefined\n : \"the options give no delegatedPrincipal()\",\n ),\n add(\n \"Z-delegation-unnamed-denied\",\n \"a requirement that names no kinds never judges a delegated principal\",\n async ({ decide }) => {\n const principal = options.delegatedPrincipal\n ? await options.delegatedPrincipal()\n : ({\n ...(await options.allowingPrincipal()),\n delegation: { description: \"conformance\", allows: () => true },\n } as AuthPrincipal);\n const decision = await decide(principal);\n // anyOf denials add a status and a joined message; the effect and reason are the invariant.\n assert.equal(decision.effect, \"deny\", JSON.stringify(decision));\n assert.equal(\n (decision as { reason?: string }).reason,\n \"PRINCIPAL_NOT_SUPPORTED\",\n JSON.stringify(decision),\n );\n },\n kindsNamed\n ? \"a requirement leaf names the principal kinds it judges\"\n : undefined,\n ),\n add(\n \"Z-per-invocation\",\n \"decisions are per invocation while identical inputs share one Better Auth call\",\n async ({ decide, probe, invocations }) => {\n const principal = await options.allowingPrincipal();\n const key = {};\n const first = {};\n const from = probe.calls.length;\n await decide(principal, { key, invocation: first });\n const afterFirst = betterAuthCalls(probe, from).length;\n const count = invocations.count;\n await decide(principal, { key, invocation: {} });\n assert.ok(\n invocations.count > count,\n \"a decision was reused for another invocation\",\n );\n assert.equal(\n betterAuthCalls(probe, from).length,\n afterFirst,\n \"identical inputs in one request called Better Auth again\",\n );\n const reused = invocations.count;\n await decide(principal, { key, invocation: first });\n assert.equal(\n invocations.count,\n reused,\n \"one invocation evaluated the same requirement twice\",\n );\n },\n ),\n conformanceCase(\n \"Z-singleton\",\n \"the policy as a class with a request-scoped dependency fails boot; with a singleton dependency it boots\",\n async () => {\n const leaf = requirementsOf(options.requirement)[0]!;\n const policy = known[0]!;\n const bootWith = (scope: Scope) => {\n const ClassPolicy = classPolicyFor(policy);\n const requirement: Requirement = {\n ...leaf,\n policy: ClassPolicy as never,\n };\n return settle(() =>\n boot(options.auth, leaf, {\n routes: { [KIT_ROUTE]: [Require(requirement)] },\n sources: options.sources,\n providers: [\n ClassPolicy,\n {\n provide: SCOPED_DEPENDENCY,\n useFactory: () => ({ scope: String(scope) }),\n scope,\n },\n ],\n }),\n );\n };\n const singleton = await bootWith(Scope.DEFAULT);\n if (!singleton.ok) {\n assert.fail(\n `the class policy with a singleton dependency failed boot: ${String(singleton.error)}`,\n );\n }\n await singleton.value.moduleRef.close();\n const scoped = await bootWith(Scope.REQUEST);\n if (scoped.ok) {\n await scoped.value.moduleRef.close();\n assert.fail(\"a class policy with a request-scoped dependency booted\");\n }\n assert.ok(\n bootIssueCodes(scoped.error).includes(\"NON_SINGLETON_EXTENSION\"),\n `boot did not report NON_SINGLETON_EXTENSION (B11): ${String(scoped.error)}`,\n );\n },\n ),\n conformanceCase(\n \"Z-boot-prerequisite\",\n \"an instance without the policy's plugin prerequisites fails boot\",\n async () => {\n const result = await settle(async () =>\n boot(await variantOf(options, {}), options.requirement),\n );\n if (result.ok) {\n await result.value.moduleRef.close();\n assert.fail(\"an instance without the policy's plugins booted\");\n }\n assert.ok(\n bootIssueCodes(result.error).includes(\"PLUGIN_PREREQUISITE\"),\n String(result.error),\n );\n },\n plugins.length\n ? undefined\n : \"the policy declares no plugin prerequisites\",\n ),\n ...unitPolicyCases(options, known),\n ];\n}\n","import assert from \"node:assert/strict\";\nimport { inspect } from \"node:util\";\nimport {\n Body,\n ConsoleLogger,\n Controller,\n Inject,\n type INestApplication,\n Module,\n Post,\n Req,\n type Type,\n} from \"@nestjs/common\";\nimport { type AbstractHttpAdapter, NestFactory } from \"@nestjs/core\";\nimport { Test, type TestingModule } from \"@nestjs/testing\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport { permission } from \"./admin.js\";\nimport type {\n AuthHandle,\n AuthorizationDecision,\n CookieSink,\n ExtensionRef,\n HttpPlatform,\n PrincipalRequest,\n PrincipalResolver,\n PrincipalResult,\n PrincipalSource,\n RequirementExpr,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport {\n AcceptPrincipals,\n ForwardAuthCookies,\n RequireAuth,\n} from \"./auth-decorators.js\";\nimport {\n BetterAuthConfigurationError,\n getRawCause,\n isAuthFailure,\n isInfrastructureError,\n} from \"./auth-errors.js\";\nimport { BetterAuthModule } from \"./auth-module.js\";\nimport { BetterAuthService } from \"./auth-service.js\";\nimport {\n getBetterAuthHandleToken,\n getExtensionToken,\n PRINCIPAL_RESOLVER,\n} from \"./auth-tokens.js\";\nimport type {\n AdminPermissions,\n AuthLike,\n AuthPrincipal,\n PrincipalKind,\n} from \"./auth-types.js\";\nimport {\n bootIssueCodes,\n type ConformanceCase,\n conformanceCase,\n conformanceSkip,\n type ConformanceOutcome,\n createConformanceAuth,\n KIT_BASE_URL,\n kitIdentity,\n PROBE_PLUGIN_ID,\n probeOf,\n type ProbeState,\n type RawResponse,\n sendRaw,\n setCookieLines,\n settle,\n} from \"./conformance-fixtures.js\";\nimport { harness as policyHarness } from \"./conformance-policy-harness.js\";\n\n/** An API key the kit's S-apikey-* cases created, and the request headers that present it. */\nexport interface ConformanceApiKey {\n /** The key's record id, which the kit uses to disable or expire the key through the database adapter. */\n readonly id: string;\n readonly headers: Headers;\n}\n\n/** Real HTTP delivery for the HTTP-route rows of S-cookie-forwarded and S-infra-throws and the cookie-bridge cases (S-bridge-*). */\nexport interface PrincipalHttpConformanceOptions {\n platform: ExtensionRef<HttpPlatform>;\n /** Fresh Nest HTTP adapter per app, e.g. () => new ExpressAdapter(). */\n createHttpAdapter(): AbstractHttpAdapter;\n /** How to obtain a base URL. Default: app.listen(0, '127.0.0.1') + getUrl(). */\n listen?(app: INestApplication): Promise<string>;\n}\n\nexport interface PrincipalSourceConformanceOptions {\n /**\n * The source under test. Pass a factory reference (defineExtension({ use: { useFactory } })) when the source keeps\n * per-instance state across requests, such as the API-key outage probe or a JWT key cache: every case boots its\n * own module, and a factory gives each case a fresh source.\n */\n source: ExtensionRef<PrincipalSource>;\n /**\n * The Better Auth instance the credentials belong to. It must include conformanceProbePlugin(), testUtils() and\n * nestjs(), with session.updateAge 0 and session refresh enabled, so every session read produces a refresh\n * Set-Cookie: createConformanceAuth({ plugins }) builds one. The kit fails with CONFORMANCE_SESSION_REFRESH otherwise.\n */\n auth: AuthLike;\n credentials: {\n /**\n * A fresh valid credential of `auth`: the options' instance, or a variant() instance (S-dynamic-base-url). Variant\n * instances have a dynamic baseURL without fallback that allows localhost:3000 (the kit base URL's host) and\n * public.example, so an auth.api call that creates the credential must pass headers with one of those hosts.\n */\n valid(auth: AuthLike): Promise<Headers>;\n invalid(): Headers;\n rateLimited?(auth: AuthLike): Promise<Headers>;\n /**\n * S-apikey-*: creates a key with these extra createApiKey body fields (remaining, rateLimitEnabled, ...).\n * Default: a key of a new kit user through auth.api.createApiKey, presented in the source's first credential header.\n */\n apiKey?(\n auth: AuthLike,\n fields: Readonly<Record<string, unknown>>,\n ): Promise<ConformanceApiKey>;\n /** S-apikey-org-key: an organization-owned key (references: 'organization'). The case skips without it. */\n organizationKey?(auth: AuthLike): Promise<Headers>;\n };\n /**\n * S-dynamic-base-url: another instance of the same configuration with the kit's overrides (a dynamic baseURL,\n * trusted proxy headers). Default: createConformanceAuth({ ...overrides, plugins }) with the plugins of `auth`\n * other than the kit's own; pass variant() when those plugin objects keep per-instance state.\n */\n variant?(overrides: Omit<BetterAuthOptions, \"database\">): AuthLike;\n /**\n * Boots a guarded route and the cookie-bridge routes on this HTTP platform for the HTTP-route rows of\n * S-cookie-forwarded and S-infra-throws and for S-bridge-*. Those cases skip without it.\n */\n http?: PrincipalHttpConformanceOptions;\n}\n\ninterface ResolveInit {\n freshness?: \"default\" | \"authoritative\";\n /** Shared by the calls of one logical request, as the resolver's per-request memo is. */\n memo?: Map<unknown, Promise<unknown>>;\n}\n\ninterface Harness {\n readonly auth: AuthLike;\n readonly source: PrincipalSource;\n readonly handle: AuthHandle;\n readonly probe: ProbeState;\n /** The source alone, inside the resolver's chain scope. */\n resolve(\n headers: Headers,\n cookies: CookieSink | null,\n init?: ResolveInit,\n ): Promise<PrincipalResult>;\n /** The real principal resolver, with its error normalization and redaction. */\n resolveChain(\n headers: Headers,\n cookies: CookieSink | null,\n ): Promise<PrincipalResult>;\n close(): Promise<void>;\n}\n\ninterface HarnessInit {\n /** Another instance than options.auth (a variant). */\n auth?: AuthLike;\n /** Extra BetterAuthModule.forRoot options. */\n module?: Record<string, unknown>;\n}\n\nclass RecordingSink implements CookieSink {\n readonly values: string[] = [];\n\n append(setCookies: readonly string[]): boolean {\n this.values.push(...setCookies);\n return true;\n }\n}\n\nasync function assertKitInstance(auth: AuthLike): Promise<ProbeState> {\n const probe = await probeOf(auth);\n const session = (\n (await auth.$context) as {\n options: {\n session?: { updateAge?: number; disableSessionRefresh?: boolean };\n };\n }\n ).options.session;\n if (session?.updateAge !== 0 || session.disableSessionRefresh) {\n throw new BetterAuthConfigurationError(\n \"CONFORMANCE_SESSION_REFRESH\",\n \"The principal-source kit needs session.updateAge 0 with session refresh enabled, so that every session read produces a refresh Set-Cookie.\",\n \"Create the instance with createConformanceAuth() or set session: { updateAge: 0 }.\",\n );\n }\n return probe;\n}\n\nfunction kitModule(\n auth: AuthLike,\n source: ExtensionRef<PrincipalSource>,\n module: Record<string, unknown> = {},\n) {\n return BetterAuthModule.forRoot({\n auth,\n principals: [source],\n session: false,\n http: { mount: false },\n logSummary: false,\n ...module,\n } as never);\n}\n\nasync function harness(\n options: PrincipalSourceConformanceOptions,\n init: HarnessInit = {},\n): Promise<Harness> {\n const auth = init.auth ?? options.auth;\n const probe = await assertKitInstance(auth);\n const moduleRef: TestingModule = await Test.createTestingModule({\n imports: [kitModule(auth, options.source, init.module)],\n }).compile();\n moduleRef.useLogger(false);\n try {\n await moduleRef.init();\n } catch (error) {\n await moduleRef.close().catch(() => undefined);\n throw error;\n }\n const handle = moduleRef.get<AuthHandle>(getBetterAuthHandleToken());\n const source = moduleRef.get<PrincipalSource>(\n getExtensionToken(\"principals\", \"default\", 0),\n );\n const resolver = moduleRef.get<PrincipalResolver>(PRINCIPAL_RESOLVER);\n return {\n auth,\n source,\n handle,\n probe,\n resolve(headers, cookies, resolveInit = {}) {\n const memo = resolveInit.memo ?? new Map<unknown, Promise<unknown>>();\n const request: PrincipalRequest = {\n headers,\n cookies,\n transport: \"conformance\",\n freshness: resolveInit.freshness ?? \"default\",\n auth: handle,\n memo<T>(key: unknown, compute: () => Promise<T>): Promise<T> {\n if (!memo.has(key)) {\n memo.set(key, compute());\n }\n return memo.get(key) as Promise<T>;\n },\n };\n // The same chain scope the resolver establishes: same-credential forwarding, library-internal calls.\n return handle.run(\n {\n cookies,\n forward: \"same-credential\",\n inbound: () => headers,\n internal: true,\n },\n async () => {\n if (source.appliesTo && !source.appliesTo(request)) {\n return { outcome: \"absent\" } as const;\n }\n return source.resolve(request);\n },\n );\n },\n resolveChain(headers, cookies) {\n const key = {};\n const call: TransportCall = {\n key,\n invocation: key,\n headers: () => new Headers(headers),\n clientIp: null,\n cookies,\n param: () => undefined,\n };\n return resolver.resolve(call, {\n auth: handle,\n freshness: \"default\",\n accepts: new Set<string>(source.kinds),\n sourceSet: \"@nestjs-kit/better-auth:principal-conformance\",\n });\n },\n close: () => moduleRef.close(),\n };\n}\n\nasync function withHarness(\n options: PrincipalSourceConformanceOptions,\n fn: (harness: Harness) => Promise<ConformanceOutcome>,\n init: HarnessInit = {},\n): Promise<ConformanceOutcome> {\n const value = await harness(options, init);\n try {\n return await fn(value);\n } finally {\n value.probe.fault = undefined;\n value.probe.storageFault = undefined;\n value.probe.storageDelay = undefined;\n value.probe.respond = undefined;\n await value.close();\n }\n}\n\nfunction names(cookies: readonly string[]): string[] {\n return cookies.map((line) => line.split(\"=\", 1)[0]!);\n}\n\nfunction cookieValue(header: string | null | undefined, name: string): string {\n for (const part of (header ?? \"\").split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index > 0 && part.slice(0, index).trim() === name) {\n return part.slice(index + 1).trim();\n }\n }\n return \"\";\n}\n\n/** The request's credential as the cookie bridge compares it: session cookie, Authorization and declared headers. */\nfunction credentialOf(\n headers: Headers | undefined,\n sessionCookie: string,\n extra: readonly string[],\n): string {\n return [\n cookieValue(headers?.get(\"cookie\"), sessionCookie),\n headers?.get(\"authorization\") ?? \"\",\n ...extra.map((name) => headers?.get(name) ?? \"\"),\n ].join(\"\\u0000\");\n}\n\n/** Set-Cookie lines that calls with the request's own credential, or with none, produced since `from`. */\nfunction ownCookies(\n probe: ProbeState,\n from: number,\n request: Headers,\n extra: readonly string[],\n): string[] {\n return probe.produced.slice(from).flatMap((entry) => {\n const call = credentialOf(entry.headers, entry.sessionCookie, extra);\n return call === credentialOf(request, entry.sessionCookie, extra) ||\n call === credentialOf(undefined, entry.sessionCookie, extra)\n ? entry.setCookies\n : [];\n });\n}\n\nfunction occurrences(lines: readonly string[], line: string): number {\n return lines.filter((value) => value === line).length;\n}\n\nconst KIT_HOST = new URL(KIT_BASE_URL).host;\nconst PUBLIC_HOST = \"public.example\";\n/** Hosts a variant instance's dynamic baseURL allows. */\nconst DYNAMIC_HOSTS = [KIT_HOST, PUBLIC_HOST];\n/** How long S-apikey-outage stalls the key's usage update, above apiKeyPrincipal()'s default slowMs of 500. */\nconst STALL_MS = 750;\nconst READ_ONLY = \"cannot execute UPDATE in a read-only transaction\";\nconst WRITES = new Set([\n \"create\",\n \"update\",\n \"updateMany\",\n \"delete\",\n \"deleteMany\",\n]);\n/** The kit's own plugins, which createConformanceAuth() adds to every instance it builds. */\nconst KIT_PLUGINS = new Set([\n \"test-utils\",\n \"bearer\",\n PROBE_PLUGIN_ID,\n \"@nestjs-kit/better-auth\",\n]);\n\nfunction variantOf(\n options: PrincipalSourceConformanceOptions,\n overrides: Omit<BetterAuthOptions, \"database\">,\n): Promise<AuthLike> {\n if (options.variant) {\n return Promise.resolve(options.variant(overrides));\n }\n return (async () => {\n const context = (await options.auth.$context) as {\n options: { plugins?: { id: string }[] };\n };\n const plugins = (context.options.plugins ?? []).filter(\n (plugin) => !KIT_PLUGINS.has(plugin.id),\n );\n return createConformanceAuth({\n ...overrides,\n plugins: plugins as never,\n });\n })();\n}\n\n/** Judges one principal against a requirement through the policy kit's real-evaluator harness. */\nasync function judgePrincipal(\n auth: AuthLike,\n requirement: RequirementExpr,\n principal: AuthPrincipal,\n): Promise<{ decision: AuthorizationDecision; evaluations: number }> {\n const value = await policyHarness({ auth, requirement });\n try {\n const decision = await value.decide(principal);\n return { decision, evaluations: value.invocations.count };\n } finally {\n await value.close();\n }\n}\n\n/** A source that verifies keys of the Better Auth api-key plugin (the S-apikey-* cases). */\nfunction verifiesApiKeys(source: PrincipalSource): boolean {\n return (\n (source.kinds as readonly string[]).includes(\"api-key\") &&\n (source.requires?.plugins ?? []).includes(\"api-key\")\n );\n}\n\nconst NOT_API_KEY = \"the source does not verify keys of the api-key plugin\";\n\ninterface KeyApi {\n createApiKey(input: {\n body: Record<string, unknown>;\n }): Promise<{ id: string; key: string }>;\n verifyApiKey(input: unknown): Promise<unknown>;\n}\n\nasync function createKey(\n options: PrincipalSourceConformanceOptions,\n harness: Harness,\n fields: Readonly<Record<string, unknown>> = {},\n): Promise<ConformanceApiKey> {\n if (options.credentials.apiKey) {\n return options.credentials.apiKey(harness.auth, fields);\n }\n const owner = await kitIdentity(harness.auth);\n const created = await (harness.auth.api as unknown as KeyApi).createApiKey({\n body: { userId: owner.userId, ...fields },\n });\n return {\n id: created.id,\n headers: new Headers({\n [harness.source.credentialHeaders?.[0] ?? \"x-api-key\"]: created.key,\n }),\n };\n}\n\nasync function updateKey(\n harness: Harness,\n id: string,\n update: Record<string, unknown>,\n): Promise<void> {\n const context = (await harness.auth.$context) as {\n adapter: {\n update(input: {\n model: string;\n where: { field: string; value: unknown }[];\n update: Record<string, unknown>;\n }): Promise<unknown>;\n };\n };\n await context.adapter.update({\n model: \"apikey\",\n where: [{ field: \"id\", value: id }],\n update,\n });\n}\n\n/** An unknown key in the source's credential header, unique per call so no cache answers it. */\nfunction unknownKey(source: PrincipalSource): Headers {\n return new Headers({\n [source.credentialHeaders?.[0] ?? \"x-api-key\"]:\n `conformance-unknown-${globalThis.crypto.randomUUID()}`,\n });\n}\n\nfunction assertRejected(\n result: PrincipalResult,\n status: number,\n reason: string,\n label: string,\n): void {\n assert.equal(\n result.outcome,\n \"rejected\",\n `${label} resolved ${JSON.stringify(result)}`,\n );\n const failure = result.outcome === \"rejected\" ? result.failure : undefined;\n assert.equal(failure?.status, status, `${label}: ${JSON.stringify(failure)}`);\n assert.equal(failure?.reason, reason, `${label}: ${JSON.stringify(failure)}`);\n}\n\nasync function assertInfrastructure(\n run: () => Promise<PrincipalResult>,\n label: string,\n): Promise<void> {\n const result = await settle(run);\n assert.equal(\n result.ok,\n false,\n `${label} resolved ${JSON.stringify(result.ok && result.value)} instead of an infrastructure error`,\n );\n assert.ok(\n !isAuthFailure(!result.ok && result.error),\n `${label} was thrown as a denial: ${String(!result.ok && result.error)}`,\n );\n}\n\n/** Every form of the credentials a request presents: cookie values (signed, decoded, raw token), bearer, headers. */\nfunction credentialForms(\n headers: Headers,\n credentialHeaders: readonly string[],\n): string[] {\n const forms = new Set<string>();\n const add = (value: string | null | undefined) => {\n if (value && value.length >= 8) {\n forms.add(value);\n }\n };\n for (const part of (headers.get(\"cookie\") ?? \"\").split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index < 0) {\n continue;\n }\n const value = part.slice(index + 1).trim();\n add(value);\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n // Keep the raw form.\n }\n add(decoded);\n const dot = decoded.lastIndexOf(\".\");\n if (dot > 0) {\n add(decoded.slice(0, dot));\n }\n }\n const authorization = headers.get(\"authorization\");\n add(authorization);\n add(/^\\S+\\s+(.+)$/.exec(authorization ?? \"\")?.[1]);\n for (const name of credentialHeaders) {\n if (name !== \"cookie\" && name !== \"authorization\") {\n add(headers.get(name));\n }\n }\n return [...forms];\n}\n\n/** Raw session token of the instance's session cookie in a request, or undefined. */\nasync function sessionToken(\n auth: AuthLike,\n headers: Headers,\n): Promise<{ name: string; token: string } | undefined> {\n const context = (await auth.$context) as {\n authCookies: { sessionToken: { name: string } };\n };\n const name = context.authCookies.sessionToken.name;\n const value = decodeURIComponent(cookieValue(headers.get(\"cookie\"), name));\n const dot = value.lastIndexOf(\".\");\n return dot > 0 ? { name, token: value.slice(0, dot) } : undefined;\n}\n\n/** A plain-object rendering of an error, as JSON loggers serialize one: own properties, message, stack and causes. */\nfunction serializeError(value: unknown, depth = 0): unknown {\n if (!(value instanceof Error) || depth > 8) {\n return value;\n }\n const output: Record<string, unknown> = {\n ...Object.fromEntries(Object.entries(value)),\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n if (value.cause !== undefined) {\n output.cause = serializeError(value.cause, depth + 1);\n }\n return output;\n}\n\n/** What Nest's ConsoleLogger writes for an error, in text and JSON mode. */\nfunction consoleLogged(error: Error): string {\n const chunks: string[] = [];\n const stdout = process.stdout.write;\n const stderr = process.stderr.write;\n const record = (chunk: unknown) => {\n chunks.push(String(chunk));\n return true;\n };\n process.stdout.write = record as typeof process.stdout.write;\n process.stderr.write = record as typeof process.stderr.write;\n try {\n const text = new ConsoleLogger(\"S-log-redaction\", { colors: false });\n text.error(error);\n text.error(error.message, error.stack);\n new ConsoleLogger(\"S-log-redaction\", { json: true }).error(error);\n } finally {\n process.stdout.write = stdout;\n process.stderr.write = stderr;\n }\n return chunks.join(\"\");\n}\n\nconst BRIDGE_PATH = \"nestjs-kit-better-auth-principal-conformance\";\n\ninterface BridgeBoot {\n readonly url: string;\n readonly origin: string;\n post(\n path: string,\n headers: Headers,\n body?: Record<string, unknown>,\n ): Promise<RawResponse>;\n close(): Promise<void>;\n}\n\nfunction bridgeController(kinds: readonly string[]): Type {\n @Controller(BRIDGE_PATH)\n class PrincipalBridgeController {\n constructor(\n @Inject(BetterAuthService) private readonly service: BetterAuthService,\n ) {}\n\n @Post(\"principal\")\n principal() {\n return { ok: true };\n }\n\n @Post(\"sign-up\")\n signUp() {\n return this.signUpAnother();\n }\n\n @ForwardAuthCookies()\n @Post(\"sign-up-forwarded\")\n signUpForwarded() {\n return this.signUpAnother();\n }\n\n @ForwardAuthCookies()\n @Post(\"foreign-session\")\n async foreignSession(@Body() body: { token: string }) {\n await this.foreignRead(body.token);\n return { ok: true };\n }\n\n @ForwardAuthCookies()\n @Post(\"foreign-forwarded\")\n async foreignForwarded(@Body() body: { token: string }) {\n await this.service.forwardForeignCookies(() =>\n this.foreignRead(body.token),\n );\n return { ok: true };\n }\n\n @Post(\"foreign-undeclared\")\n async foreignUndeclared(@Body() body: { token: string }) {\n try {\n await this.service.forwardForeignCookies(() =>\n this.foreignRead(body.token),\n );\n return { code: null };\n } catch (error) {\n return { code: (error as { code?: unknown }).code ?? null };\n }\n }\n\n @ForwardAuthCookies()\n @Post(\"sign-out\")\n async signOut(@Req() request: unknown) {\n await (\n this.service.api as unknown as {\n signOut(input: { headers: Headers }): Promise<unknown>;\n }\n ).signOut({ headers: this.service.headersFrom(request) });\n return { ok: true };\n }\n\n private async signUpAnother() {\n const result = await (\n this.service.api as unknown as {\n signUpEmail(input: {\n body: { email: string; password: string; name: string };\n }): Promise<{ token: string | null }>;\n }\n ).signUpEmail({\n body: {\n email: `${globalThis.crypto.randomUUID()}@conformance.example`,\n password: `pw-${globalThis.crypto.randomUUID()}`,\n name: \"Conformance third party\",\n },\n });\n return { token: result.token };\n }\n\n private foreignRead(token: string) {\n return (\n this.service.api as unknown as {\n getSession(input: { headers: Headers }): Promise<unknown>;\n }\n ).getSession({\n headers: new Headers({ authorization: `Bearer ${token}` }),\n });\n }\n }\n RequireAuth()(PrincipalBridgeController);\n AcceptPrincipals(\n ...(kinds as readonly string[] as [PrincipalKind, ...PrincipalKind[]]),\n )(PrincipalBridgeController);\n return PrincipalBridgeController;\n}\n\nasync function bootBridge(\n options: PrincipalSourceConformanceOptions,\n http: PrincipalHttpConformanceOptions,\n kinds: readonly string[],\n): Promise<BridgeBoot> {\n const controller = bridgeController(kinds);\n const auth = options.auth;\n const imports = [\n BetterAuthModule.forRoot({\n auth,\n principals: [options.source],\n session: false,\n platforms: [http.platform],\n http: { mount: false },\n logSummary: false,\n } as never),\n ];\n @Module({\n imports,\n controllers: [controller],\n })\n class PrincipalBridgeModule {}\n const app = await NestFactory.create(\n PrincipalBridgeModule,\n http.createHttpAdapter(),\n { logger: false, abortOnError: false },\n );\n try {\n await app.init();\n let url: string;\n if (http.listen) {\n url = await http.listen(app);\n } else {\n await app.listen(0, \"127.0.0.1\");\n url = await app.getUrl();\n }\n url = url.replace(\"[::1]\", \"127.0.0.1\").replace(/\\/$/, \"\");\n const context = (await auth.$context) as { baseURL: string };\n const origin = new URL(context.baseURL || KIT_BASE_URL).origin;\n return {\n url,\n origin,\n post(path, headers, body = {}) {\n const outgoing: Record<string, string> = {};\n headers.forEach((value, name) => {\n outgoing[name] = value;\n });\n return sendRaw(`${url}/${BRIDGE_PATH}/${path}`, {\n method: \"POST\",\n headers: {\n ...outgoing,\n origin,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n },\n close: () => app.close(),\n };\n } catch (error) {\n await app.close().catch(() => undefined);\n throw error;\n }\n}\n\nfunction json(response: RawResponse): Record<string, unknown> {\n return JSON.parse(response.body.toString(\"utf8\") || \"{}\") as Record<\n string,\n unknown\n >;\n}\n\n/** Set-Cookie lines of a response that carry this raw session token. */\nfunction linesWithToken(response: RawResponse, token: string): string[] {\n return setCookieLines(response.headers).filter((line) =>\n decodeURIComponent(line.split(\";\", 1)[0]!).includes(`=${token}.`),\n );\n}\n\n/**\n * The principal-source kit (invariants P1–P7 and the unit-specific rows of design v7 §14.1). It resolves the source\n * directly inside the resolver's chain scope, so a source that throws for invalid credentials fails\n * S-rejected-not-thrown although core would normalize the throw at runtime; S-log-redaction resolves through the real\n * principal resolver. Storage faults are injected into the instance's database adapter, below every endpoint and\n * every direct adapter read, so endpoints that swallow storage errors are exercised too. A case that does not apply to\n * the source (an API-key row for a session source, say) skips with the reason.\n */\nexport function principalSourceConformance(\n options: PrincipalSourceConformanceOptions,\n): ConformanceCase[] {\n const add = (\n id: string,\n title: string,\n run: (harness: Harness) => Promise<ConformanceOutcome>,\n skip?: string,\n ) => conformanceCase(id, title, () => withHarness(options, run), skip);\n const valid = (harness: Harness) => options.credentials.valid(harness.auth);\n return [\n add(\n \"S-rejected-not-thrown\",\n \"invalid credentials resolve rejected with 401, 403 or 429 and never throw\",\n async ({ resolve, source }) => {\n const result = await settle(() =>\n resolve(options.credentials.invalid(), new RecordingSink()),\n );\n assert.equal(\n result.ok,\n true,\n `resolve threw for an invalid credential: ${String(!result.ok && result.error)}`,\n );\n const value = result.ok ? result.value : undefined;\n // Better Auth answers an unreadable session cookie as \"no session\"; session-backed sources mirror it.\n if (value?.outcome === \"absent\" && source.sessionBacked) {\n return;\n }\n assert.equal(value?.outcome, \"rejected\");\n const failure =\n value?.outcome === \"rejected\" ? value.failure : undefined;\n assert.ok(\n isAuthFailure(failure),\n \"the rejection is not an AuthFailure\",\n );\n assert.ok([401, 403, 429].includes(failure.status));\n },\n ),\n add(\n \"S-infra-throws\",\n \"a storage outage makes resolve throw instead of denying\",\n async (harness) => {\n const { resolve, probe } = harness;\n const headers = await valid(harness);\n const storage = probe.storage.length;\n probe.storageFault = () => new Error(\"conformance storage outage\");\n const result = await settle(() =>\n resolve(headers, new RecordingSink()),\n );\n probe.storageFault = undefined;\n // The fault fires only inside a storage operation; an endpoint served without storage sees no outage.\n if (probe.storage.length === storage) {\n return conformanceSkip(\n \"the source ran no storage operation for a valid credential\",\n );\n }\n assert.equal(\n result.ok,\n false,\n `a storage outage resolved ${JSON.stringify(result.ok && result.value)}`,\n );\n assert.ok(\n !isAuthFailure(!result.ok && result.error),\n `a storage outage was thrown as a denial: ${String(!result.ok && result.error)}`,\n );\n },\n ),\n add(\n \"S-cookie-forwarded\",\n \"Set-Cookie lines of the source's own-credential calls reach the sink exactly once\",\n async (harness) => {\n const { resolve, probe, source } = harness;\n const sink = new RecordingSink();\n const headers = await valid(harness);\n const from = probe.produced.length;\n const result = await resolve(new Headers(headers), sink);\n assert.equal(result.outcome, \"authenticated\");\n const produced = ownCookies(\n probe,\n from,\n headers,\n source.credentialHeaders ?? [],\n );\n for (const line of new Set(produced)) {\n assert.equal(\n occurrences(sink.values, line),\n occurrences(produced, line),\n `the source's Better Auth calls produced ${occurrences(produced, line)} × ${names([line])[0]}, the sink received ${occurrences(sink.values, line)} (sink: ${names(sink.values).join(\", \") || \"nothing\"})`,\n );\n }\n const seen = names(sink.values);\n assert.deepEqual(\n seen,\n [...new Set(seen)],\n `a cookie was delivered twice: ${seen.join(\", \")}`,\n );\n },\n ),\n add(\n \"S-refresh-suppressed\",\n \"resolving without a cookie sink refreshes nothing\",\n async (harness) => {\n const { resolve, probe } = harness;\n const headers = await valid(harness);\n const writes = probe.writes.length;\n const refresh = probe.refresh.length;\n const result = await resolve(headers, null);\n assert.equal(result.outcome, \"authenticated\");\n assert.ok(\n !probe.writes.slice(writes).includes(\"session.update\"),\n \"a session row was refreshed\",\n );\n assert.ok(\n probe.refresh.slice(refresh).every((entry) => entry.skip),\n \"a Better Auth call ran without refresh suppression\",\n );\n },\n ),\n add(\n \"S-absent-clean\",\n \"no credential resolves absent without cookies or writes\",\n async ({ resolve, probe }) => {\n const sink = new RecordingSink();\n const writes = probe.writes.length;\n const result = await resolve(new Headers(), sink);\n assert.equal(result.outcome, \"absent\");\n assert.deepEqual(sink.values, []);\n assert.deepEqual(probe.writes.slice(writes), []);\n },\n ),\n add(\n \"S-shape\",\n \"an authenticated principal names its kind, source and user\",\n async (harness) => {\n const { resolve, source } = harness;\n const result = await resolve(await valid(harness), new RecordingSink());\n assert.equal(result.outcome, \"authenticated\");\n const principal =\n result.outcome === \"authenticated\" ? result.principal : undefined;\n assert.ok(principal);\n assert.ok((source.kinds as readonly string[]).includes(principal.kind));\n assert.equal(principal.source, source.id);\n assert.ok(\n principal.userId === null || typeof principal.userId === \"string\",\n );\n },\n ),\n add(\n \"S-credential-headers\",\n \"a valid credential without its declared headers resolves absent\",\n async (harness) => {\n const { resolve, source } = harness;\n const headers = await valid(harness);\n for (const name of source.credentialHeaders ?? []) {\n headers.delete(name);\n }\n const result = await resolve(headers, new RecordingSink());\n assert.equal(\n result.outcome,\n \"absent\",\n \"the source read a credential from an undeclared header\",\n );\n },\n ),\n add(\n \"S-session-backed\",\n \"sessionBacked is declared exactly when the principal is Better Auth's session read\",\n async (harness) => {\n const { resolve, source, handle } = harness;\n const getSession = (headers: Headers) =>\n (\n handle.api as {\n getSession(input: { headers: Headers }): Promise<unknown>;\n }\n ).getSession({ headers });\n for (const headers of [\n await valid(harness),\n options.credentials.invalid(),\n ]) {\n const session = await getSession(new Headers(headers)).catch(\n () => null,\n );\n const result = await resolve(new Headers(headers), null);\n if (source.sessionBacked) {\n assert.equal(\n result.outcome === \"authenticated\",\n session !== null,\n \"a sessionBacked source disagrees with getSession\",\n );\n } else if (result.outcome === \"authenticated\") {\n assert.equal(\n session,\n null,\n \"the credential is a Better Auth session; declare sessionBacked\",\n );\n }\n }\n },\n ),\n add(\n \"S-delegation\",\n \"delegation is present exactly when the source declares delegates\",\n async (harness) => {\n const { resolve, source } = harness;\n const result = await resolve(await valid(harness), new RecordingSink());\n assert.equal(result.outcome, \"authenticated\");\n const principal =\n result.outcome === \"authenticated\" ? result.principal : undefined;\n assert.equal(\n Boolean(principal?.delegation),\n Boolean(source.delegates),\n \"delegates does not match the produced principals\",\n );\n if (principal?.delegation) {\n assert.equal(typeof principal.delegation.allows, \"function\");\n assert.equal(typeof principal.delegation.description, \"string\");\n assert.equal(\n typeof principal.delegation.allows({ conformance: [\"probe\"] }),\n \"boolean\",\n );\n }\n },\n ),\n add(\n \"S-rate-limited\",\n \"a rate-limited credential resolves rejected 429\",\n async (harness) => {\n const result = await harness.resolve(\n await options.credentials.rateLimited!(harness.auth),\n new RecordingSink(),\n );\n assert.equal(result.outcome, \"rejected\");\n const failure =\n result.outcome === \"rejected\" ? result.failure : undefined;\n assert.equal(failure?.status, 429);\n },\n options.credentials.rateLimited\n ? undefined\n : \"the options give no rateLimited() credential\",\n ),\n ...dynamicBaseUrlCases(options),\n ...apiKeyCases(options, add),\n add(\n \"S-short-circuit-session\",\n \"a before hook's short-circuited session is a default-freshness principal and never authoritative\",\n async (harness) => {\n const { resolve, probe, source } = harness;\n if (!source.sessionBacked) {\n return conformanceSkip(\"the source is not session-backed\");\n }\n const headers = await valid(harness);\n const userId = `conformance-short-circuit-${globalThis.crypto.randomUUID()}`;\n const now = new Date();\n probe.respond = (path) =>\n path === \"/get-session\"\n ? {\n user: {\n id: userId,\n email: `${userId}@conformance.example`,\n emailVerified: false,\n name: \"Conformance short-circuit\",\n createdAt: now,\n updatedAt: now,\n },\n session: {\n id: `${userId}-session`,\n userId,\n token: `${userId}-token`,\n expiresAt: new Date(now.getTime() + 3_600_000),\n createdAt: now,\n updatedAt: now,\n },\n }\n : undefined;\n const calls = probe.calls.length;\n // A cookie sink: the transport is cookie-capable, as HTTP is.\n const fresh = await settle(() =>\n resolve(new Headers(headers), new RecordingSink()),\n );\n assert.ok(\n probe.calls.slice(calls).includes(\"/get-session\"),\n \"the source did not read the session through /get-session\",\n );\n assert.equal(\n fresh.ok,\n true,\n `a short-circuited session read threw: ${String(!fresh.ok && fresh.error)}`,\n );\n const value = fresh.ok ? fresh.value : undefined;\n assert.equal(\n value?.outcome,\n \"authenticated\",\n `a default-freshness read of a short-circuited session resolved ${JSON.stringify(value)}`,\n );\n assert.equal(\n value?.outcome === \"authenticated\" ? value.principal.userId : null,\n userId,\n \"the principal is not the short-circuited session's user\",\n );\n const authoritative = await settle(() =>\n resolve(new Headers(headers), new RecordingSink(), {\n freshness: \"authoritative\",\n }),\n );\n assert.equal(\n authoritative.ok,\n true,\n `an authoritative read threw: ${String(!authoritative.ok && authoritative.error)}`,\n );\n const decided = authoritative.ok ? authoritative.value : undefined;\n assert.notEqual(\n decided?.outcome,\n \"authenticated\",\n \"an authoritative route accepted a session no endpoint produced\",\n );\n if (decided?.outcome === \"rejected\") {\n assert.equal(decided.failure.status, 401);\n }\n },\n ),\n ...bridgeCases(options),\n ...httpRouteCases(options),\n ...logRedactionCases(options),\n ...jwtCases(options),\n ];\n}\n\nfunction logRedactionCases(\n options: PrincipalSourceConformanceOptions,\n): ConformanceCase[] {\n /** One run: every credential form of the requests in the outage error, resolved through the real resolver. */\n const run = (exposeRawCause: boolean) =>\n withHarness(\n options,\n async (value) => {\n const headers = await options.credentials.valid(value.auth);\n const requests = [headers];\n const session = await sessionToken(value.auth, headers);\n if (value.source.sessionBacked && session) {\n requests.push(\n new Headers({ authorization: `Bearer ${session.token}` }),\n );\n }\n let observed = false;\n // Better Auth endpoints may swallow an adapter error into a generic one, so the error also comes from a\n // before hook, which rethrows it unchanged: both reach the library's error path.\n const modes = [\"storage\", \"endpoint\"] as const;\n for (const request of requests) {\n const secrets = credentialForms(\n request,\n value.source.credentialHeaders ?? [],\n );\n const outage = () => {\n const error = new Error(\n `conformance outage for ${secrets.join(\" \")}`,\n );\n Object.assign(error, { detail: secrets.join(\" \") });\n error.cause = new Error(`nested ${secrets.join(\" \")}`);\n return error;\n };\n for (const mode of modes) {\n const inject = () => {\n if (mode === \"storage\") {\n value.probe.storageFault = outage;\n } else {\n value.probe.fault = outage;\n }\n };\n inject();\n const chained = await settle(() =>\n value.resolveChain(new Headers(request), new RecordingSink()),\n );\n inject();\n const direct = await settle(() =>\n value.resolve(new Headers(request), new RecordingSink()),\n );\n value.probe.storageFault = undefined;\n value.probe.fault = undefined;\n if (chained.ok) {\n continue;\n }\n observed = true;\n const error = chained.error;\n assert.ok(\n isInfrastructureError(error),\n `a ${mode} outage surfaced as ${String(error)}`,\n );\n const logs = [\n consoleLogged(error),\n JSON.stringify(serializeError(error)),\n // The raw cause is a hidden property by design when the instance opts in.\n inspect(error, { depth: 8, showHidden: !exposeRawCause }),\n ].join(\"\\n\");\n for (const secret of secrets) {\n assert.ok(\n !logs.includes(secret),\n `a credential reached the logs after a ${mode} outage (exposeRawCause: ${exposeRawCause}): ${secret.slice(0, 6)}…`,\n );\n }\n const raw = getRawCause(error);\n if (!exposeRawCause) {\n assert.equal(\n raw,\n undefined,\n \"getRawCause exposed a cause without errors.exposeRawCause\",\n );\n } else if (!direct.ok && !isInfrastructureError(direct.error)) {\n // The source let the error escape; the resolver wraps it and keeps it for the opt-in.\n assert.ok(\n raw instanceof Error &&\n raw.message === (direct.error as Error | undefined)?.message,\n `errors.exposeRawCause did not keep the escaped raw cause: ${String(raw)}`,\n );\n }\n }\n }\n return observed\n ? undefined\n : conformanceSkip(\n \"the source read no storage and called no Better Auth endpoint for a valid credential, so no error reached it\",\n );\n },\n { module: { errors: { exposeRawCause } } },\n );\n return [\n conformanceCase(\n \"S-log-redaction\",\n \"a storage error carrying the request's credentials leaves none in Nest ConsoleLogger or JSON logs\",\n () => run(false),\n ),\n conformanceCase(\n \"S-log-redaction\",\n \"with errors.exposeRawCause the logs stay redacted and getRawCause keeps an escaped raw cause\",\n () => run(true),\n ),\n ];\n}\n\nfunction dynamicBaseUrlCases(\n options: PrincipalSourceConformanceOptions,\n): ConformanceCase[] {\n const dynamic = { baseURL: { allowedHosts: DYNAMIC_HOSTS } };\n return [\n conformanceCase(\n \"S-dynamic-base-url\",\n \"a dynamic baseURL without fallback fails boot for hostless sources and never answers 500 for the others\",\n async () => {\n const auth = await variantOf(options, dynamic as never);\n // A misconfigured variant fails the case; only the source's boot errors skip it.\n await assertKitInstance(auth);\n const booted = await settle(() => harness(options, { auth }));\n if (!booted.ok) {\n const codes = bootIssueCodes(booted.error);\n if (codes.includes(\"DYNAMIC_BASE_URL_WITHOUT_FALLBACK\")) {\n return;\n }\n if (!codes.length) {\n throw booted.error;\n }\n return conformanceSkip(\n `the source rejects a dynamic baseURL without fallback at boot (${codes.filter((code) => code !== \"AUTH_BOOT_FAILED\").join(\", \")})`,\n );\n }\n const value = booted.value;\n try {\n assert.ok(\n !value.source.requires?.hostlessCalls,\n \"a source that declares requires.hostlessCalls booted with a dynamic baseURL and no fallback\",\n );\n const host = { host: KIT_HOST };\n const requests: [string, Headers][] = [\n [\"valid\", await options.credentials.valid(auth)],\n [\"invalid\", options.credentials.invalid()],\n ];\n for (const [label, credential] of requests) {\n const headers = new Headers(credential);\n headers.set(\"host\", host.host);\n const result = await settle(() =>\n value.resolve(headers, new RecordingSink()),\n );\n assert.equal(\n result.ok,\n true,\n `the ${label} credential threw with a dynamic baseURL (a hostless call?): ${String(!result.ok && result.error)}`,\n );\n }\n } finally {\n await value.close();\n }\n },\n ),\n conformanceCase(\n \"S-dynamic-base-url\",\n \"behind a trusted proxy, the forwarded public host resolves the dynamic baseURL\",\n async () => {\n const auth = await variantOf(options, {\n ...dynamic,\n advanced: { trustedProxyHeaders: true },\n } as never);\n // A misconfigured variant fails the case; only the source's boot errors skip it.\n await assertKitInstance(auth);\n const booted = await settle(() => harness(options, { auth }));\n if (!booted.ok) {\n const codes = bootIssueCodes(booted.error);\n if (!codes.length) {\n throw booted.error;\n }\n return conformanceSkip(\n `the source rejects a dynamic baseURL without fallback at boot (${codes.filter((code) => code !== \"AUTH_BOOT_FAILED\").join(\", \")})`,\n );\n }\n const value = booted.value;\n try {\n const headers = new Headers(await options.credentials.valid(auth));\n // The app's own host is not allowed; only the forwarded public host is.\n headers.set(\"host\", \"nest-app:3000\");\n headers.set(\"x-forwarded-host\", PUBLIC_HOST);\n headers.set(\"x-forwarded-proto\", \"https\");\n const result = await settle(() =>\n value.resolve(headers, new RecordingSink()),\n );\n assert.equal(\n result.ok,\n true,\n `a forwarded request threw with a dynamic baseURL: ${String(!result.ok && result.error)}`,\n );\n } finally {\n await value.close();\n }\n },\n ),\n ];\n}\n\nfunction apiKeyCases(\n options: PrincipalSourceConformanceOptions,\n add: (\n id: string,\n title: string,\n run: (harness: Harness) => Promise<ConformanceOutcome>,\n ) => ConformanceCase,\n): ConformanceCase[] {\n const apiKeyCase = (\n id: string,\n title: string,\n run: (harness: Harness) => Promise<ConformanceOutcome>,\n ) =>\n add(id, title, (harness) =>\n verifiesApiKeys(harness.source)\n ? run(harness)\n : Promise.resolve(conformanceSkip(NOT_API_KEY)),\n );\n return [\n apiKeyCase(\n \"S-apikey-results\",\n \"rate-limited, exhausted, disabled, expired and unknown keys map to their statuses, one verification per request\",\n async (harness) => {\n const { resolve, source } = harness;\n const limited = await createKey(options, harness, {\n rateLimitEnabled: true,\n rateLimitMax: 1,\n rateLimitTimeWindow: 60_000,\n });\n assert.equal(\n (await resolve(new Headers(limited.headers), null)).outcome,\n \"authenticated\",\n \"the rate-limited key's first request did not authenticate\",\n );\n const throttled = await resolve(new Headers(limited.headers), null);\n assertRejected(throttled, 429, \"RATE_LIMITED\", \"a rate-limited key\");\n const retryAfter = Number(\n throttled.outcome === \"rejected\"\n ? throttled.failure.headers?.get(\"retry-after\")\n : undefined,\n );\n assert.ok(\n retryAfter >= 50 && retryAfter <= 60,\n `Retry-After ${retryAfter} does not come from the 60 s window's tryAgainIn`,\n );\n const exhausted = await createKey(options, harness, { remaining: 0 });\n assertRejected(\n await resolve(exhausted.headers, null),\n 429,\n \"USAGE_EXCEEDED\",\n \"an exhausted key\",\n );\n const disabled = await createKey(options, harness);\n await updateKey(harness, disabled.id, { enabled: false });\n assertRejected(\n await resolve(disabled.headers, null),\n 401,\n \"KEY_DISABLED\",\n \"a disabled key\",\n );\n const expired = await createKey(options, harness);\n await updateKey(harness, expired.id, {\n expiresAt: new Date(Date.now() - 60_000),\n });\n assertRejected(\n await resolve(expired.headers, null),\n 401,\n \"KEY_EXPIRED\",\n \"an expired key\",\n );\n assertRejected(\n await resolve(unknownKey(source), null),\n 401,\n \"INVALID_API_KEY\",\n \"an unknown key\",\n );\n const api = harness.auth.api as unknown as KeyApi;\n const verify = api.verifyApiKey;\n let verifications = 0;\n api.verifyApiKey = (input) => {\n verifications++;\n return verify.call(api, input);\n };\n try {\n const key = await createKey(options, harness);\n const memo = new Map<unknown, Promise<unknown>>();\n for (const freshness of [\n \"default\",\n \"default\",\n \"authoritative\",\n ] as const) {\n assert.equal(\n (\n await resolve(new Headers(key.headers), null, {\n freshness,\n memo,\n })\n ).outcome,\n \"authenticated\",\n );\n }\n } finally {\n api.verifyApiKey = verify;\n }\n assert.equal(\n verifications,\n 1,\n `one request verified its key ${verifications} times`,\n );\n },\n ),\n apiKeyCase(\n \"S-apikey-outage\",\n \"a flood of invalid keys runs at most one outage probe\",\n async ({ resolve, probe, source }) => {\n const from = probe.storage.length;\n const results = await Promise.all(\n Array.from({ length: 12 }, () => resolve(unknownKey(source), null)),\n );\n for (const result of results) {\n assertRejected(result, 401, \"INVALID_API_KEY\", \"an unknown key\");\n }\n const writes = probe.storage\n .slice(from)\n .filter((entry) => WRITES.has(entry.split(\":\", 1)[0]!));\n assert.ok(\n writes.length <= 1,\n `a flood of 12 invalid keys wrote ${writes.length} times (${writes.join(\", \")}); the outage probe runs at most once per second`,\n );\n },\n ),\n apiKeyCase(\n \"S-apikey-outage\",\n \"with key reads failing, an API-key request answers 5xx instead of 401\",\n async (harness) => {\n const { resolve, probe, source } = harness;\n const key = await createKey(options, harness);\n probe.storageFault = (call) =>\n call.method === \"findOne\"\n ? new Error(\"conformance read outage\")\n : undefined;\n await assertInfrastructure(\n () => resolve(unknownKey(source), null),\n \"an unknown key during a read outage\",\n );\n await assertInfrastructure(\n () => resolve(new Headers(key.headers), null),\n \"a valid key during a read outage\",\n );\n },\n ),\n apiKeyCase(\n \"S-apikey-outage\",\n \"a stalled, failing usage update answers 5xx while an unknown key still answers a fast 401\",\n async (harness) => {\n const { resolve, probe, source } = harness;\n const key = await createKey(options, harness);\n const usage = (call: { method: string; model: string | undefined }) =>\n call.method === \"update\" && call.model === \"apikey\";\n probe.storageDelay = (call) => (usage(call) ? STALL_MS : undefined);\n probe.storageFault = (call) =>\n usage(call) ? new Error(\"conformance stalled update\") : undefined;\n await assertInfrastructure(\n () => resolve(new Headers(key.headers), null),\n \"a valid key whose usage update stalled and failed\",\n );\n const started = performance.now();\n const unknown = await resolve(unknownKey(source), null);\n const elapsed = performance.now() - started;\n assertRejected(unknown, 401, \"INVALID_API_KEY\", \"an unknown key\");\n assert.ok(\n elapsed < STALL_MS,\n `an unknown key took ${Math.round(elapsed)} ms, no faster than the stalled update`,\n );\n },\n ),\n apiKeyCase(\n \"S-apikey-write-outage\",\n \"with reads succeeding and every write failing, a valid key answers 5xx, not 401\",\n async (harness) => {\n const { resolve, probe } = harness;\n const key = await createKey(options, harness);\n probe.storageFault = (call) =>\n WRITES.has(call.method) ? new Error(READ_ONLY) : undefined;\n await assertInfrastructure(\n () => resolve(new Headers(key.headers), null),\n \"a valid key during a write outage\",\n );\n },\n ),\n apiKeyCase(\n \"S-apikey-write-outage\",\n \"the outage probe's write changes no key row\",\n async (harness) => {\n const { resolve, source } = harness;\n await createKey(options, harness);\n const context = (await harness.auth.$context) as {\n adapter: { findMany(input: { model: string }): Promise<unknown[]> };\n };\n const before = JSON.stringify(\n await context.adapter.findMany({ model: \"apikey\" }),\n );\n assertRejected(\n await resolve(unknownKey(source), null),\n 401,\n \"INVALID_API_KEY\",\n \"an unknown key\",\n );\n assert.equal(\n JSON.stringify(await context.adapter.findMany({ model: \"apikey\" })),\n before,\n \"an invalid key changed a stored key\",\n );\n },\n ),\n conformanceCase(\n \"S-apikey-org-key\",\n \"an organization-owned key has no user and is denied by user-scoped admin permissions\",\n async () => {\n let principal: AuthPrincipal | undefined;\n const outcome = await withHarness(options, async (harness) => {\n if (!verifiesApiKeys(harness.source)) {\n return conformanceSkip(NOT_API_KEY);\n }\n if (!(await harness.handle.hasPlugin(\"admin\"))) {\n return conformanceSkip(\"the instance has no admin() plugin\");\n }\n const result = await harness.resolve(\n await options.credentials.organizationKey!(harness.auth),\n null,\n );\n assert.equal(\n result.outcome,\n \"authenticated\",\n `the organization key resolved ${JSON.stringify(result)}`,\n );\n principal =\n result.outcome === \"authenticated\" ? result.principal : undefined;\n const key = principal as\n | (AuthPrincipal & { organizationId?: unknown })\n | undefined;\n assert.equal(\n key?.userId,\n null,\n \"an organization-owned key produced a user principal\",\n );\n assert.ok(\n typeof key?.organizationId === \"string\" &&\n key.organizationId.length > 0,\n \"an organization-owned key carries no organizationId\",\n );\n });\n if (outcome && typeof outcome.skipped === \"string\") {\n return outcome;\n }\n // The kit judges the instance under test, not the program's registered instance, whose\n // admin() statements type permission() and may name other resources.\n const permissions = { user: [\"list\"] } as Readonly<\n Record<string, readonly string[]>\n > as AdminPermissions;\n const optedIn = await judgePrincipal(\n options.auth,\n permission(permissions, { principals: [\"session\", \"api-key\"] }),\n principal!,\n );\n assert.equal(optedIn.decision.effect, \"deny\");\n assert.equal(\n (optedIn.decision as { reason?: string }).reason,\n \"USER_REQUIRED\",\n JSON.stringify(optedIn.decision),\n );\n assert.equal(\n (optedIn.decision as { status?: number }).status ?? 403,\n 403,\n );\n const gated = await judgePrincipal(\n options.auth,\n permission(permissions),\n principal!,\n );\n assert.equal(gated.decision.effect, \"deny\");\n assert.equal(\n (gated.decision as { reason?: string }).reason,\n \"PRINCIPAL_NOT_SUPPORTED\",\n JSON.stringify(gated.decision),\n );\n assert.equal(\n gated.evaluations,\n 0,\n \"the default permission() ran its policy for an API-key principal\",\n );\n },\n options.credentials.organizationKey\n ? undefined\n : \"the options give no organizationKey() credential\",\n ),\n ];\n}\n\nfunction bridgeCases(\n options: PrincipalSourceConformanceOptions,\n): ConformanceCase[] {\n const skip = options.http ? undefined : \"the options give no http harness\";\n /** Boots the bridge app for a session-backed source whose credential carries the session cookie. */\n const withBridge = async (\n fn: (boot: BridgeBoot, caller: () => Promise<Headers>) => Promise<void>,\n ): Promise<ConformanceOutcome> => {\n const inspected = await harness(options);\n const { source } = inspected;\n let credential: Headers;\n try {\n credential = await options.credentials.valid(options.auth);\n } finally {\n await inspected.close();\n }\n if (!source.sessionBacked) {\n return conformanceSkip(\"the source is not session-backed\");\n }\n if (!(await sessionToken(options.auth, credential))) {\n return conformanceSkip(\n \"the valid credential carries no session cookie of the instance\",\n );\n }\n const boot = await bootBridge(options, options.http!, source.kinds);\n try {\n await fn(boot, () => options.credentials.valid(options.auth));\n } finally {\n await boot.close();\n }\n };\n return [\n conformanceCase(\n \"S-bridge-third-party-signup\",\n \"a direct sign-up for another user leaves the caller's cookies untouched unless the handler forwards\",\n () =>\n withBridge(async (boot, caller) => {\n const headers = await caller();\n const own = (await sessionToken(options.auth, headers))!;\n const plain = await boot.post(\"sign-up\", headers);\n assert.equal(plain.status, 201, plain.body.toString(\"utf8\"));\n const token = String(json(plain).token);\n assert.deepEqual(\n linesWithToken(plain, token),\n [],\n \"a guarded handler's direct sign-up set the new user's session cookie on the caller\",\n );\n for (const line of setCookieLines(plain.headers)) {\n if (line.startsWith(`${own.name}=`)) {\n assert.ok(\n decodeURIComponent(line).startsWith(\n `${own.name}=${own.token}.`,\n ),\n \"the caller's session cookie was replaced\",\n );\n }\n }\n const forwarded = await boot.post(\n \"sign-up-forwarded\",\n await caller(),\n );\n assert.equal(forwarded.status, 201, forwarded.body.toString(\"utf8\"));\n const forwardedToken = String(json(forwarded).token);\n assert.equal(\n linesWithToken(forwarded, forwardedToken).length,\n 1,\n \"@ForwardAuthCookies() did not forward the direct sign-up's session cookie\",\n );\n }),\n skip,\n ),\n conformanceCase(\n \"S-bridge-foreign-credentials\",\n \"foreign-credential cookies are forwarded only through forwardForeignCookies in a forwarding handler\",\n () =>\n withBridge(async (boot, caller) => {\n const foreign = await kitIdentity(options.auth);\n const dropped = await boot.post(\"foreign-session\", await caller(), {\n token: foreign.token,\n });\n assert.equal(dropped.status, 201, dropped.body.toString(\"utf8\"));\n assert.deepEqual(\n linesWithToken(dropped, foreign.token),\n [],\n \"a direct getSession with a foreign bearer token forwarded its refresh cookie\",\n );\n const headers = await caller();\n const own = (await sessionToken(options.auth, headers))!;\n const signOut = await boot.post(\"sign-out\", headers);\n assert.equal(signOut.status, 201, signOut.body.toString(\"utf8\"));\n assert.ok(\n setCookieLines(signOut.headers).some(\n (line) =>\n line.startsWith(`${own.name}=`) &&\n (line.startsWith(`${own.name}=;`) || /max-age=0/i.test(line)),\n ),\n `the caller's own sign-out did not forward its cookie deletion: ${setCookieLines(signOut.headers).join(\" | \")}`,\n );\n const explicit = await boot.post(\n \"foreign-forwarded\",\n await caller(),\n {\n token: foreign.token,\n },\n );\n assert.equal(explicit.status, 201, explicit.body.toString(\"utf8\"));\n assert.equal(\n linesWithToken(explicit, foreign.token).length,\n 1,\n \"forwardForeignCookies() in a forwarding handler did not forward the foreign refresh cookie\",\n );\n const undeclared = await boot.post(\n \"foreign-undeclared\",\n await caller(),\n { token: foreign.token },\n );\n assert.equal(\n json(undeclared).code,\n \"FORWARDING_NOT_DECLARED\",\n \"forwardForeignCookies() ran outside a forwarding handler\",\n );\n assert.deepEqual(linesWithToken(undeclared, foreign.token), []);\n }),\n skip,\n ),\n ];\n}\n\n/** A response header the probe sets on the source's own calls; it must never reach the client (S-cookie-forwarded). */\nconst CALL_HEADER = \"x-conformance-call-header\";\n\n/** S-cookie-forwarded and S-infra-throws through a guarded route of the http harness. */\nfunction httpRouteCases(\n options: PrincipalSourceConformanceOptions,\n): ConformanceCase[] {\n const skip = options.http ? undefined : \"the options give no http harness\";\n const withRoute = async (\n fn: (\n boot: BridgeBoot,\n source: PrincipalSource,\n probe: ProbeState,\n ) => Promise<ConformanceOutcome>,\n ): Promise<ConformanceOutcome> => {\n const inspected = await harness(options);\n const { source, probe } = inspected;\n await inspected.close();\n const boot = await bootBridge(options, options.http!, source.kinds);\n try {\n return await fn(boot, source, probe);\n } finally {\n probe.storageFault = undefined;\n probe.responseHeader = undefined;\n await boot.close();\n }\n };\n return [\n conformanceCase(\n \"S-infra-throws\",\n \"through an HTTP route: a storage outage answers 5xx, never 401 or 403\",\n () =>\n withRoute(async (boot, _source, probe) => {\n const headers = await options.credentials.valid(options.auth);\n const storage = probe.storage.length;\n probe.storageFault = () => new Error(\"conformance storage outage\");\n const response = await boot.post(\"principal\", headers);\n probe.storageFault = undefined;\n // The fault fires only inside a storage operation; an endpoint served without storage sees no outage.\n if (probe.storage.length === storage) {\n return conformanceSkip(\n \"the source ran no storage operation for a valid credential\",\n );\n }\n assert.ok(\n response.status >= 500 && response.status < 600,\n `a guarded route answered ${response.status} for a storage outage instead of 5xx: ${response.body.toString(\"utf8\")}`,\n );\n }),\n skip,\n ),\n conformanceCase(\n \"S-cookie-forwarded\",\n \"through an HTTP route: each Set-Cookie line of the source's own-credential calls reaches the client exactly once, and no other header of those calls does\",\n () =>\n withRoute(async (boot, source, probe) => {\n const headers = await options.credentials.valid(options.auth);\n const from = probe.produced.length;\n const calls = probe.calls.length;\n probe.responseHeader = () => [CALL_HEADER, \"leaked\"];\n const response = await boot.post(\"principal\", headers);\n probe.responseHeader = undefined;\n assert.equal(\n response.status,\n 201,\n `the guarded route answered ${response.status}: ${response.body.toString(\"utf8\")}`,\n );\n const produced = ownCookies(\n probe,\n from,\n headers,\n source.credentialHeaders ?? [],\n );\n const delivered = setCookieLines(response.headers);\n for (const line of new Set(produced)) {\n assert.equal(\n occurrences(delivered, line),\n 1,\n `the source's Better Auth calls produced ${names([line])[0]}, the client received it ${occurrences(delivered, line)} times (received: ${names(delivered).join(\", \") || \"nothing\"})`,\n );\n }\n for (const line of delivered) {\n assert.ok(\n produced.includes(line),\n `the client received ${names([line])[0]}, which no call with the request's own credential produced`,\n );\n }\n if (probe.calls.length > calls) {\n assert.equal(\n response.headers[CALL_HEADER],\n undefined,\n \"a header other than Set-Cookie that the source's Better Auth calls set reached the client\",\n );\n }\n }),\n skip,\n ),\n ];\n}\n\ninterface JwtApi {\n signJWT(input: {\n body: {\n payload: Record<string, unknown>;\n overrideOptions?: Record<string, unknown>;\n };\n }): Promise<{ token: string }>;\n}\n\nfunction jwtCases(\n options: PrincipalSourceConformanceOptions,\n): ConformanceCase[] {\n const NOT_JWT = \"the source does not require the jwt plugin\";\n const jwtCase = (\n title: string,\n run: (\n harness: Harness,\n mint: JwtApi[\"signJWT\"],\n ) => Promise<ConformanceOutcome>,\n ) =>\n conformanceCase(\"S-jwt-claims\", title, () =>\n withHarness(options, async (harness) => {\n if (!(harness.source.requires?.plugins ?? []).includes(\"jwt\")) {\n return conformanceSkip(NOT_JWT);\n }\n const api = harness.auth.api as unknown as JwtApi;\n return run(harness, (input) => api.signJWT(input));\n }),\n );\n const bearer = (token: string) =>\n new Headers({ authorization: `Bearer ${token}` });\n return [\n jwtCase(\n \"a token signJWT minted verifies, and one minted under another issuer is rejected 401 INVALID_JWT\",\n async ({ resolve }, mint) => {\n const subject = `conformance-${globalThis.crypto.randomUUID()}`;\n const { token } = await mint({ body: { payload: { sub: subject } } });\n const verified = await resolve(bearer(token), null);\n assert.equal(\n verified.outcome,\n \"authenticated\",\n `a token signJWT minted did not verify (iss/aud must be the baseURL origin): ${JSON.stringify(verified)}`,\n );\n const foreign = await mint({\n body: {\n payload: { sub: subject },\n overrideOptions: {\n jwt: { issuer: \"https://conformance-foreign-issuer.example\" },\n },\n },\n });\n const result = await settle(() => resolve(bearer(foreign.token), null));\n assert.equal(\n result.ok,\n true,\n `a foreign-issuer token threw: ${String(!result.ok && result.error)}`,\n );\n assertRejected(\n result.ok ? result.value : { outcome: \"absent\" },\n 401,\n \"INVALID_JWT\",\n \"a foreign-issuer token\",\n );\n },\n ),\n jwtCase(\n \"with the key-set read failing, a valid token answers 5xx\",\n async ({ resolve, probe }, mint) => {\n const { token } = await mint({\n body: { payload: { sub: \"conformance\" } },\n });\n const from = probe.storage.length;\n probe.storageFault = (call) =>\n call.model === \"jwks\"\n ? new Error(\"conformance key-set outage\")\n : undefined;\n const result = await settle(() => resolve(bearer(token), null));\n probe.storageFault = undefined;\n if (\n !probe.storage.slice(from).some((entry) => entry.endsWith(\":jwks\"))\n ) {\n return conformanceSkip(\n \"the source served the key set from a cache; pass it as a factory reference so each case starts cold\",\n );\n }\n assert.equal(\n result.ok,\n false,\n `a key-set outage resolved ${JSON.stringify(result.ok && result.value)}`,\n );\n assert.ok(\n !isAuthFailure(!result.ok && result.error),\n `a key-set outage was thrown as a denial: ${String(!result.ok && result.error)}`,\n );\n },\n ),\n ];\n}\n","import assert from \"node:assert/strict\";\nimport {\n type ExecutionContext,\n type INestApplication,\n type LoggerService,\n SetMetadata,\n type Type,\n UseGuards,\n} from \"@nestjs/common\";\nimport {\n DiscoveryService,\n ExternalContextCreator,\n MetadataScanner,\n ModuleRef,\n Reflector,\n} from \"@nestjs/core\";\nimport type { TestingModuleBuilder } from \"@nestjs/testing\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport { organization } from \"better-auth/plugins\";\nimport type {\n AuthorizationPolicy,\n AuthPrincipalBase,\n AuthTransport,\n ClaimOptions,\n ExtensionRef,\n GuardReach,\n PrincipalSource,\n RequirementExpr,\n RoutePlan,\n TransportCall,\n} from \"./auth-contracts.js\";\nimport {\n AcceptPrincipals,\n CurrentPrincipal,\n ForwardAuthCookies,\n OptionalAuth,\n Public,\n Require,\n RequireAuth,\n requirement,\n SkipDefaultRequirements,\n SkipOriginCheck,\n UseBetterAuth,\n} from \"./auth-decorators.js\";\nimport { AuthFailures, BetterAuthConfigurationError } from \"./auth-errors.js\";\nimport { BetterAuthGuard } from \"./auth-guard.js\";\nimport type { BetterAuthService } from \"./auth-service.js\";\nimport {\n MOUNT_COORDINATOR,\n ROUTE_PLANNER,\n TRANSPORT_REGISTRY,\n WS_CONNECTION_AUTH,\n} from \"./auth-tokens.js\";\nimport type { AuthLike, AuthPrincipal, PrincipalKind } from \"./auth-types.js\";\nimport { allow, deny } from \"./authorization-evaluator.js\";\nimport { EXTENSION_DEFINITION } from \"./bridge-protocol.js\";\nimport {\n bootIssueCodes,\n CapturingLogger,\n type ConformanceCase,\n conformanceCase,\n conformanceSkip,\n type ConformanceOutcome,\n type ConformanceSkip,\n type ConformanceAuthSettings,\n createConformanceAuth,\n kitIdentity,\n type KitIdentity,\n PROBE_TRUSTED_ORIGIN,\n KIT_BASE_URL,\n probeOf,\n type ProbeState,\n settle,\n UNTRUSTED_ORIGIN,\n} from \"./conformance-fixtures.js\";\nimport {\n ACTIVE_ORGANIZATION_ID,\n ActiveOrganizationId,\n fromParam,\n orgPermission,\n} from \"./organization.js\";\nimport { absent, authenticated, rejected } from \"./principal-resolver.js\";\nimport { CurrentSession } from \"./session-principal.js\";\nimport type { MountCoordinator } from \"./mount-coordinator.js\";\nimport type { RoutePlanner } from \"./route-planner.js\";\nimport { overrideAuthGuard } from \"./testing.js\";\nimport type { TransportRegistry } from \"./transport-registry.js\";\n\nexport type InvocationShape =\n | \"aliases\"\n | \"batched\"\n | \"messages\"\n | \"subscriptions\";\n\n/** One fixture handler the kit supplies; the harness exposes it as a controller route, resolver field, gateway message or message pattern. */\nexport interface FixtureHandler {\n /** Method decorators to apply, in order (access, acceptance, requirements). */\n readonly decorators: readonly MethodDecorator[];\n /** Parameter decorators by parameter index, e.g. [CurrentSession()]. */\n readonly params: readonly ParameterDecorator[];\n /** 'read': HTTP GET, GraphQL query, RPC request. 'unsafe': HTTP POST, GraphQL mutation. WS messages are always enforced. */\n readonly operation: \"read\" | \"unsafe\";\n /** Handler body: receives the decorated parameter values, the invocation input and the harness context; its result is the response. */\n handle(\n params: readonly unknown[],\n input: Record<string, unknown>,\n context: FixtureContext,\n ): unknown;\n}\n\n/** What the harness hands every fixture handler. */\nexport interface FixtureContext {\n /** The default instance's service (BETTER_AUTH_SERVICE). */\n readonly service: BetterAuthService;\n}\n\n/**\n * One method of an abstract base class, exposed through two subclasses that carry `subclasses.public` and\n * `subclasses.denied` as class decorators (T-inherited-handler). A harness without invokeInherited exposes it as a\n * plain handler.\n */\nexport interface InheritedFixture extends FixtureHandler {\n readonly subclasses: {\n readonly public: readonly ClassDecorator[];\n readonly denied: readonly ClassDecorator[];\n };\n}\n\n/**\n * GraphQL shapes only: one object type FixtureNode, returned by the root fields and carrying the field resolvers\n * below. invokeGraph selects `publicNested` as `publicNested { id reader }` and `guarded` as\n * `guarded { id principal nestedReader }`, so `reader` and `nestedReader` read the reading of their enclosing field.\n */\nexport interface GraphFixtures {\n readonly roots: {\n readonly public: FixtureHandler;\n readonly sessionOnly: FixtureHandler;\n readonly mixed: FixtureHandler;\n /**\n * A list root: its handler returns 20 FixtureNode items, so serve it as a list of FixtureNode (`[FixtureNode]`).\n * Given only to the reader rows of T-internal-error-logged-once.\n */\n readonly items?: FixtureHandler;\n };\n readonly fields: {\n readonly plain: FixtureHandler;\n readonly publicNested: FixtureHandler;\n readonly reader: FixtureHandler;\n readonly guarded?: FixtureHandler;\n readonly nestedReader?: FixtureHandler;\n readonly sessionReader: FixtureHandler;\n /** @ForwardAuthCookies() without access metadata: an inheriting form-mode field that signs a kit user in (T-csrf-login-proxy). */\n readonly forwarding?: FixtureHandler;\n /** A String field reading @ActiveOrganizationId() without a requirement that provides it (T-internal-error-logged-once). */\n readonly organizationReader?: FixtureHandler;\n /** A String field returning the user id of the zero-argument service.getSession() (T-internal-error-logged-once). */\n readonly serviceSession?: FixtureHandler;\n };\n /** Federation shapes only: @ResolveReference() of FixtureNode, with the kit's per-representation requirement on `orgId`. */\n readonly reference?: FixtureHandler;\n /** Class decorators of the resolver class that serves the roots, the fields and the reference resolver. */\n readonly classDecorators?: readonly ClassDecorator[];\n}\n\nexport interface GraphSelection {\n readonly root: keyof GraphFixtures[\"roots\"];\n readonly fields: readonly (keyof GraphFixtures[\"fields\"])[];\n}\n\n/**\n * The fixture handlers of transportConformance, by name (the `handler` argument of invoke()). Harnesses expose each\n * input field as the transport's named input, so ctx.param(name) reads input[name] (HTTP: route param or query).\n * `triple` and `tripleMixed` are three distinct handler methods; invoke() runs all three in one logical request when\n * the transport can, otherwise the first one.\n */\nexport interface TransportFixtures {\n readonly required: FixtureHandler;\n readonly optional: FixtureHandler;\n readonly public: FixtureHandler;\n readonly forbidden: FixtureHandler;\n readonly triple: readonly [FixtureHandler, FixtureHandler, FixtureHandler];\n readonly tripleMixed: readonly [\n FixtureHandler,\n FixtureHandler,\n FixtureHandler,\n ];\n readonly readsSession: FixtureHandler;\n /** @AcceptPrincipals('session', 'api-key'), returns service.getSession() (T-reads-session). */\n readonly readsSessionService: FixtureHandler;\n readonly unsafe: FixtureHandler;\n readonly loginProxy: FixtureHandler;\n /** @Public() @ForwardAuthCookies(), operation 'read' (HTTP GET), calls service.api.signInEmail (T-csrf-login-proxy, T-csrf-safe-methods). */\n readonly loginProxyRead: FixtureHandler;\n readonly loginProxyService: FixtureHandler;\n readonly publicService: FixtureHandler;\n readonly acceptsApiKey: FixtureHandler;\n readonly org: FixtureHandler;\n readonly inherited: InheritedFixture;\n readonly unguarded: FixtureHandler;\n /**\n * Default access, operation 'read': a direct auth.api.getSession() call presenting the invocation's `cookie` input,\n * the caller's own session cookie (T-csrf-safe-methods).\n */\n readonly callerSession: FixtureHandler;\n /** Like callerSession, with @Public(). */\n readonly publicCallerSession: FixtureHandler;\n /** GraphQL shapes only; other harnesses ignore it. */\n readonly graph: GraphFixtures;\n}\n\nexport interface TransportInvocationResult {\n ok: boolean;\n body?: unknown;\n error?: {\n code?: string;\n statusCode?: number;\n reason?: string;\n message?: string;\n };\n setCookies: string[];\n}\n\nexport interface GraphResult {\n /** The operation's data, keyed like the selection: data[root][field]. */\n data: unknown;\n errors: readonly {\n path: readonly (string | number)[];\n code?: string;\n reason?: string;\n message?: string;\n }[];\n}\n\nexport interface TransportConformanceOptions {\n transport: ExtensionRef<AuthTransport>;\n /**\n * Boots an app exposing the kit's fixture handlers in the transport's shape, with BetterAuthModule's globalGuard as\n * given. Pass `principals` to BetterAuthModule (the kit's API-key source), and `defaultRequirements` and\n * `globalScope` when set. With `override`, boot through Test.createTestingModule() and pass the builder through it\n * before compile(). Apply every fixture decorator the kit supplies, including its SetMetadata() marker. The app is\n * closed by the kit.\n */\n createApp(\n fixtures: TransportFixtures,\n auth: AuthLike,\n options: {\n globalGuard: boolean;\n override?: (builder: TestingModuleBuilder) => TestingModuleBuilder;\n defaultRequirements?: readonly RequirementExpr[];\n /**\n * GraphQL shapes: the fieldResolverEnhancers to serve 'graph' with. The kit boots GraphQL cases with [] and\n * ['guards', 'interceptors'], and the reader rows of T-internal-error-logged-once with ['guards', 'interceptors',\n * 'filters'] and ['guards', 'filters'].\n */\n fieldResolverEnhancers?: readonly (\n | \"guards\"\n | \"interceptors\"\n | \"filters\"\n )[];\n /** GraphQL shapes: serve 'graph' from a federation subgraph (FixtureNode an entity keyed by id, with GraphFixtures.reference when given). */\n federation?: boolean;\n /** Principal sources for BetterAuthModule's `principals`: the kit's API-key source. */\n principals?: readonly ExtensionRef<PrincipalSource>[];\n /** BetterAuthModule's globalScope; unset keeps the module default (T-coverage-claims). */\n globalScope?: boolean;\n /** Register BetterAuthGuard as APP_GUARD and BetterAuthScopeInterceptor as APP_INTERCEPTOR yourself (with globalGuard: false; T-coverage-claims). */\n appEnhancers?: boolean;\n /** The logger the app uses from boot on (e.g. createNestApplication(adapter, { logger }) or moduleRef.useLogger(logger)): cases assert boot warnings. */\n logger?: LoggerService;\n /** BetterAuthModule's cookies.forwardDirectCalls (T-stamp-per-plan). */\n forwardDirectCalls?: boolean;\n /**\n * BetterAuthModule's logSummary. The kit passes true where it asserts the boot summary (T-coverage-claims); unset\n * leaves the harness's choice, such as false to keep other boots quiet.\n */\n logSummary?: boolean;\n /** GraphQL shapes: the fieldResolverCoverage of the transport this boot registers (T-stamp-per-plan). */\n fieldResolverCoverage?: \"warn\";\n /** GraphQL shapes: the GraphQL module's `context` option, one of `graphqlContexts` (T-stale-context, T-subscription-origin). */\n graphqlContext?: GraphqlContextShape;\n },\n ): Promise<INestApplication>;\n /** Invokes a fixture handler with given credentials and browser headers; returns the transport-native outcome. */\n invoke(\n app: INestApplication,\n handler: Exclude<keyof TransportFixtures, \"graph\">,\n headers: HeadersInit,\n input?: Record<string, unknown>,\n ): Promise<TransportInvocationResult>;\n /**\n * Two invocations of the 'org' fixture in ONE logical request or connection, with different inputs. Required when\n * the transport has a lineage: the multiple-invocation cases then fail without it, and are skipped with a reason\n * for other transports.\n */\n invokeTwice?(\n app: INestApplication,\n shape: InvocationShape,\n inputs: [Record<string, unknown>, Record<string, unknown>],\n headers: HeadersInit,\n ): Promise<\n [\n { ok: boolean; error?: { reason?: string } },\n { ok: boolean; error?: { reason?: string } },\n ]\n >;\n /** Shapes invokeTwice can produce; required with it. */\n invocationShapes?: readonly InvocationShape[];\n /**\n * GraphQL shapes: one operation over HTTP selecting the given root fields of fixtures.graph, each with the given\n * FixtureNode fields. `delays` states the order in which the kit's session and API-key sources settle; the kit\n * applies it to its own sources, so a harness may ignore it. Required when the transport nests handlers\n * (defaultAccessFor): the GraphQL cases then fail without it, and are skipped with a reason for other transports.\n */\n invokeGraph?(\n app: INestApplication,\n selection: readonly GraphSelection[],\n headers: HeadersInit,\n options?: {\n delays?: { readonly session: number; readonly apiKey: number };\n },\n ): Promise<GraphResult>;\n /**\n * Federation shapes only: one `_entities` query for the given representations of FixtureNode. Required when the\n * transport claims the kit's reference resolver in a federation boot: T-reference-resolver then fails without it,\n * and is skipped with a reason for other transports.\n */\n invokeEntities?(\n app: INestApplication,\n representations: readonly Record<string, unknown>[],\n fields: readonly (keyof GraphFixtures[\"fields\"])[],\n headers: HeadersInit,\n ): Promise<GraphResult>;\n /**\n * Connection shapes (WebSocket gateways): opens ONE connection whose handshake carries `headers`, sends one message to\n * each given fixture handler on it in order, each after the previous one answered, closes the connection and returns\n * every outcome once the server has observed the close (T-stale-context runs a later caller after it). Required when\n * the transport's browser leg is its connection's handshake: the T-ws-origin-* cases then fail without it, and are\n * skipped with a reason for other transports.\n */\n invokeConnection?(\n app: INestApplication,\n handlers: readonly Exclude<keyof TransportFixtures, \"graph\">[],\n headers: HeadersInit,\n options?: {\n /**\n * Values the connection sends in its init payload (graphql-ws connection_init) instead of the handshake's credential\n * headers; given only when `invocationShapes` includes 'subscriptions'.\n */\n readonly connectionParams?: Readonly<Record<string, string>>;\n },\n ): Promise<TransportInvocationResult[]>;\n /**\n * Invokes `fixtures.inherited` through the subclass that carries `subclasses[subclass]`. Without it T-inherited-handler\n * is skipped with a reason: a transport that addresses handlers by a name that one inherited method shares across\n * subclasses (an RPC pattern, a GraphQL root field) cannot expose it twice.\n */\n invokeInherited?(\n app: INestApplication,\n subclass: \"public\" | \"denied\",\n headers: HeadersInit,\n ): Promise<TransportInvocationResult>;\n /**\n * GraphQL shapes: the `graphqlContext` values createApp honours. T-stale-context needs 'static' and 'cached' and fails\n * without them when the transport nests handlers; the custom-context rows of T-subscription-origin run for 'fresh' and\n * 'plain-request' when listed.\n */\n graphqlContexts?: readonly GraphqlContextShape[];\n /**\n * Connection shapes: authenticates one connection whose handshake carries `headers` through the app's connection-time\n * authentication (WS_CONNECTION_AUTH), requiring a principal: `ok` when one authenticates, otherwise the failure\n * (401 without credentials). Required when the app provides WS_CONNECTION_AUTH: the T-ws-origin-* cases then fail\n * without it.\n */\n authenticateConnection?(\n app: INestApplication,\n headers: HeadersInit,\n ): Promise<ConnectionAuthenticationResult>;\n expectCookieCapable: boolean;\n /**\n * Whether the transport describes a browser leg (false for RPC; T-selection fails a false claim). A leg that follows each\n * operation enables the T-csrf-* cases; a leg that is the connection's handshake, shared by the connection's messages and\n * enforced on every one, enables the T-ws-origin-* cases instead. The kit reads which from the transport.\n */\n expectBrowserLeg: boolean;\n}\n\n/**\n * The GraphQL module's `context` option of a boot: 'fresh' is a function returning a new object that keeps what the driver\n * passes it (the native request, the graphql-ws context); 'plain-request' a function returning a new object whose `req` is a\n * plain object holding only the native request's cookie header; 'cached' a function returning the object it built on its\n * first call; 'static' an object.\n */\nexport type GraphqlContextShape =\n | \"fresh\"\n | \"plain-request\"\n | \"cached\"\n | \"static\";\n\n/** The outcome of connection-time authentication (authenticateConnection). */\nexport interface ConnectionAuthenticationResult {\n ok: boolean;\n error?: TransportInvocationResult[\"error\"];\n}\n\nconst KEY_SOURCE_ID = \"@nestjs-kit/better-auth:conformance-api-key\";\n/** An origin only a function-valued trustedOrigins returns (T-ws-origin-*). */\nconst FUNCTION_TRUSTED_ORIGIN = \"https://function-trusted.example\";\nconst ALLOWED_ORGS = new Set([\"org-a\", \"org-a2\"]);\nconst SESSION_KIND = \"session\" as PrincipalKind;\nconst API_KEY_KIND = \"api-key\" as PrincipalKind;\n\ninterface KitKeys {\n readonly valid: string;\n readonly limited: string;\n verifications: number;\n /** The user the valid key acts for. */\n owner: string;\n /** Milliseconds the source waits before answering (T-stamp-per-plan settle order). */\n delayMs: number;\n}\n\nfunction keySource(keys: KitKeys): PrincipalSource<AuthPrincipalBase> {\n return {\n id: KEY_SOURCE_ID,\n kinds: [API_KEY_KIND],\n acceptance: \"explicit\",\n delegates: true,\n credentialHeaders: [\"x-api-key\"],\n appliesTo: (request) => request.headers.has(\"x-api-key\"),\n async resolve(request) {\n const value = request.headers.get(\"x-api-key\");\n if (!value) {\n return absent();\n }\n keys.verifications++;\n if (keys.delayMs) {\n await new Promise((resolve) => setTimeout(resolve, keys.delayMs));\n }\n if (value === keys.limited) {\n return rejected(\n AuthFailures.rejected({\n status: 429,\n reason: \"RATE_LIMITED\",\n retryAfterSeconds: 7,\n }),\n );\n }\n if (value !== keys.valid) {\n return rejected(\n AuthFailures.rejected({ status: 401, reason: \"INVALID_API_KEY\" }),\n );\n }\n return authenticated({\n kind: API_KEY_KIND,\n source: KEY_SOURCE_ID,\n userId: keys.owner,\n delegation: {\n description: \"conformance key grant\",\n allows: () => false,\n },\n });\n },\n };\n}\n\nconst denyPolicy: AuthorizationPolicy<Record<string, never>> = {\n id: \"@nestjs-kit/better-auth:conformance/deny\",\n evaluate: () => deny({ reason: \"CONFORMANCE_DENIED\" }),\n};\n/**\n * The 'org' fixture's requirement: the organization unit's permission check on the invocation's orgId input. The kit\n * seeds org-a and org-a2, which the kit identity owns, and org-b, where it is a member without that permission.\n */\nconst orgFixturePermission = orgPermission(\n { organization: [\"update\"] },\n { organization: fromParam(\"orgId\") },\n);\n// The kit's per-representation policy for federation reference resolvers: it decides from the representation's orgId\n// alone, so reference boots need no organization data per representation.\nconst orgPolicy: AuthorizationPolicy<Record<string, never>> = {\n id: \"@nestjs-kit/better-auth:conformance/organization\",\n requires: { principals: [SESSION_KIND] },\n async evaluate(_params, context) {\n const organization = context.param(\"orgId\");\n if (typeof organization !== \"string\" || !organization) {\n return deny({ reason: \"ORGANIZATION_REQUIRED\" });\n }\n if (!ALLOWED_ORGS.has(organization)) {\n return deny({ reason: \"MISSING_PERMISSION\" });\n }\n context.provide(ACTIVE_ORGANIZATION_ID, organization);\n return allow();\n },\n};\nconst kindsPolicy = (\n id: string,\n principals: readonly PrincipalKind[] | undefined,\n): AuthorizationPolicy<Record<string, never>> => ({\n id: `@nestjs-kit/better-auth:conformance/${id}`,\n ...(principals ? { requires: { principals } } : {}),\n evaluate: () => allow(),\n});\nconst sessionOnly = requirement(\n kindsPolicy(\"session-only\", [SESSION_KIND]),\n {},\n);\nconst apiKeyOnly = requirement(kindsPolicy(\"api-key-only\", [API_KEY_KIND]), {});\nconst sessionOrKey = requirement(\n kindsPolicy(\"session-or-key\", [SESSION_KIND, API_KEY_KIND]),\n {},\n);\nconst unnamedKinds = requirement(kindsPolicy(\"unnamed-kinds\", undefined), {});\n\nfunction view(principal: unknown): unknown {\n const value = principal as AuthPrincipal | null | undefined;\n return value ? { kind: value.kind, userId: value.userId } : null;\n}\n\nfunction handler(\n decorators: readonly MethodDecorator[],\n params: readonly ParameterDecorator[],\n operation: \"read\" | \"unsafe\",\n handle: FixtureHandler[\"handle\"],\n): FixtureHandler {\n return { decorators, params, operation, handle };\n}\n\nasync function signIn(\n service: BetterAuthService,\n input: Record<string, unknown>,\n): Promise<void> {\n await (\n service.api as unknown as {\n signInEmail(input: {\n body: { email: string; password: string };\n }): Promise<unknown>;\n }\n ).signInEmail({\n body: { email: String(input.email), password: String(input.password) },\n });\n}\n\nfunction principalHandler(\n decorators: readonly MethodDecorator[] = [],\n operation: \"read\" | \"unsafe\" = \"read\",\n): FixtureHandler {\n return handler(\n decorators,\n [CurrentPrincipal()],\n operation,\n ([principal]) => ({\n principal: view(principal),\n }),\n );\n}\n\n/** Marks each fixture handler with its fixture name, so the kit can map claims and boot reports to fixtures. */\nconst FIXTURE_METADATA = \"@nestjs-kit/better-auth:conformance-fixture\";\n\ntype FixtureName = Exclude<keyof TransportFixtures, \"graph\">;\n\ninterface GraphBoot {\n /** Include `guarded` and `nestedReader` (the ['guards', 'interceptors'] boots only). */\n readonly guarded?: boolean;\n /** Include the federation `reference` fixture; 'bare' leaves out its method-level requirement. */\n readonly reference?: boolean | \"bare\";\n /** Include the `forwarding` field, signing in with these credentials. */\n readonly forwarding?: { readonly email: string; readonly password: string };\n /** Class decorators of the graph resolver class. */\n readonly classDecorators?: readonly ClassDecorator[];\n /** Include the `items` root and the `organizationReader` and `serviceSession` fields (T-internal-error-logged-once). */\n readonly readerErrors?: boolean;\n}\n\n/** How many FixtureNode items the `items` root returns. */\nconst ITEM_COUNT = 20;\n\n/** The fixture marker of a graph handler, for claims and plans of GraphQL boots. */\nconst graphMarker = (name: string) => `graph.${name}`;\n\n/**\n * The kit's fixture handlers; `extra` appends decorators to named handlers and `everyHandler` to all of them for boot\n * variants. `graph` selects the GraphQL fixtures a boot may serve: `guarded` fails a [] boot (FIELD_RESOLVER_UNGUARDED)\n * and `reference` belongs to federation boots, so both are left out unless asked for.\n */\nfunction kitFixtures(\n extra: Partial<Record<FixtureName, MethodDecorator[]>> = {},\n everyHandler: MethodDecorator[] = [],\n graph: GraphBoot = {},\n): TransportFixtures {\n const withExtra = <F extends FixtureHandler>(\n name: FixtureName,\n fixture: F,\n marker: string = name,\n ): F => ({\n ...fixture,\n decorators: [\n SetMetadata(FIXTURE_METADATA, marker),\n ...fixture.decorators,\n ...(extra[name] ?? []),\n ...everyHandler,\n ],\n });\n const plain = () => handler([], [], \"read\", () => ({ ok: true }));\n const marked = (name: string, fixture: FixtureHandler): FixtureHandler => ({\n ...fixture,\n decorators: [\n SetMetadata(FIXTURE_METADATA, graphMarker(name)),\n ...fixture.decorators,\n ],\n });\n const reader = () =>\n handler([], [CurrentPrincipal()], \"read\", ([principal]) => ({\n principal: view(principal),\n }));\n // A direct call presenting the caller's own session cookie, which the invocation passes as its `cookie` input.\n const callerSession = (decorators: MethodDecorator[]) =>\n handler(decorators, [], \"read\", async (_params, input, { service }) => {\n const session = (await (\n service.api as unknown as {\n getSession(input: { headers: Headers }): Promise<unknown>;\n }\n ).getSession({\n headers: new Headers({ cookie: String(input.cookie ?? \"\") }),\n })) as { user?: { id?: string } } | null;\n return { userId: session?.user?.id ?? null };\n });\n const forwarding = graph.forwarding;\n const loginProxy = (operation: \"read\" | \"unsafe\") =>\n handler(\n [Public(), ForwardAuthCookies()],\n [],\n operation,\n async (_params, input, { service }) => {\n await signIn(service, input);\n return { signedIn: true };\n },\n );\n return {\n required: withExtra(\"required\", principalHandler()),\n optional: withExtra(\"optional\", principalHandler([OptionalAuth()])),\n public: withExtra(\n \"public\",\n handler([Public()], [], \"read\", () => ({ public: true })),\n ),\n forbidden: withExtra(\n \"forbidden\",\n handler([Require(requirement(denyPolicy, {}))], [], \"read\", () => ({\n reached: true,\n })),\n ),\n triple: [\n withExtra(\"triple\", plain(), \"triple0\"),\n withExtra(\"triple\", plain(), \"triple1\"),\n withExtra(\"triple\", plain(), \"triple2\"),\n ],\n tripleMixed: [\n withExtra(\"tripleMixed\", plain(), \"tripleMixed0\"),\n withExtra(\n \"tripleMixed\",\n handler(\n [AcceptPrincipals(SESSION_KIND, API_KEY_KIND)],\n [],\n \"read\",\n () => ({\n ok: true,\n }),\n ),\n \"tripleMixed1\",\n ),\n withExtra(\"tripleMixed\", plain(), \"tripleMixed2\"),\n ],\n readsSession: withExtra(\n \"readsSession\",\n handler(\n [],\n [CurrentSession()],\n \"read\",\n async ([session], _input, { service }) => ({\n userId:\n (session as { user?: { id?: string } } | null)?.user?.id ?? null,\n service: (await service.getPrincipal())?.userId ?? null,\n }),\n ),\n ),\n readsSessionService: withExtra(\n \"readsSessionService\",\n handler(\n [AcceptPrincipals(SESSION_KIND, API_KEY_KIND)],\n [],\n \"read\",\n async (_params, _input, { service }) => ({\n userId:\n (\n (await service.getSession()) as {\n user?: { id?: string };\n } | null\n )?.user?.id ?? null,\n }),\n ),\n ),\n unsafe: withExtra(\"unsafe\", principalHandler([], \"unsafe\")),\n loginProxy: withExtra(\"loginProxy\", loginProxy(\"unsafe\")),\n loginProxyRead: withExtra(\"loginProxyRead\", loginProxy(\"read\")),\n loginProxyService: withExtra(\n \"loginProxyService\",\n handler([Public()], [], \"unsafe\", async (_params, input, { service }) => {\n await service.forwardForeignCookies(() => signIn(service, input));\n return { signedIn: true };\n }),\n ),\n publicService: withExtra(\n \"publicService\",\n handler(\n [Public()],\n [],\n \"unsafe\",\n async (_params, _input, { service }) => ({\n session: await service.getSession(),\n }),\n ),\n ),\n acceptsApiKey: withExtra(\n \"acceptsApiKey\",\n principalHandler([AcceptPrincipals(SESSION_KIND, API_KEY_KIND)]),\n ),\n org: withExtra(\n \"org\",\n handler(\n [Require(orgFixturePermission)],\n [ActiveOrganizationId()],\n \"read\",\n ([organization], input) => {\n if (organization !== input.orgId) {\n throw new Error(\n `ActiveOrganizationId answered ${String(organization)} for ${String(input.orgId)}`,\n );\n }\n return { organization };\n },\n ),\n ),\n inherited: withExtra(\"inherited\", {\n ...plain(),\n subclasses: {\n public: [Public()],\n denied: [Require(requirement(denyPolicy, {}))],\n },\n }),\n callerSession: withExtra(\"callerSession\", callerSession([])),\n publicCallerSession: withExtra(\n \"publicCallerSession\",\n callerSession([Public()]),\n ),\n unguarded: withExtra(\n \"unguarded\",\n handler([], [CurrentSession(), ActiveOrganizationId()], \"read\", () => ({\n reached: true,\n })),\n ),\n graph: {\n roots: {\n public: marked(\n \"public\",\n handler([Public()], [], \"read\", () => ({ id: \"public\" })),\n ),\n sessionOnly: marked(\n \"sessionOnly\",\n handler([], [CurrentPrincipal()], \"read\", ([p]) => ({\n id: \"session\",\n principal: view(p),\n })),\n ),\n mixed: marked(\n \"mixed\",\n handler(\n [AcceptPrincipals(SESSION_KIND, API_KEY_KIND)],\n [CurrentPrincipal()],\n \"read\",\n ([p]) => ({ id: \"mixed\", principal: view(p) }),\n ),\n ),\n ...(graph.readerErrors\n ? {\n items: marked(\n \"items\",\n handler(\n [AcceptPrincipals(SESSION_KIND, API_KEY_KIND)],\n [],\n \"read\",\n () =>\n Array.from({ length: ITEM_COUNT }, (_, index) => ({\n id: `item-${index}`,\n })),\n ),\n ),\n }\n : {}),\n },\n fields: {\n plain: marked(\n \"plain\",\n handler([], [], \"read\", () => \"plain\"),\n ),\n publicNested: marked(\n \"publicNested\",\n handler([Public()], [], \"read\", () => ({ id: \"nested\" })),\n ),\n reader: marked(\"reader\", reader()),\n ...(graph.guarded\n ? {\n guarded: marked(\n \"guarded\",\n handler(\n [RequireAuth()],\n [CurrentPrincipal()],\n \"read\",\n ([p]) => ({ id: \"guarded\", principal: view(p) }),\n ),\n ),\n nestedReader: marked(\"nestedReader\", reader()),\n }\n : {}),\n sessionReader: marked(\n \"sessionReader\",\n handler(\n [],\n [CurrentSession()],\n \"read\",\n ([session]) =>\n (session as { user?: { id?: string } } | null)?.user?.id ?? null,\n ),\n ),\n ...(graph.readerErrors\n ? {\n organizationReader: marked(\n \"organizationReader\",\n handler(\n [],\n [ActiveOrganizationId()],\n \"read\",\n ([organization]) =>\n typeof organization === \"string\" ? organization : null,\n ),\n ),\n serviceSession: marked(\n \"serviceSession\",\n handler(\n [],\n [],\n \"read\",\n async (_params, _input, { service }) =>\n (\n (await service.getSession()) as {\n user?: { id?: string };\n } | null\n )?.user?.id ?? null,\n ),\n ),\n }\n : {}),\n ...(forwarding\n ? {\n forwarding: marked(\n \"forwarding\",\n handler(\n [ForwardAuthCookies()],\n [],\n \"read\",\n async (_params, _input, { service }) => {\n await signIn(service, forwarding);\n return \"forwarded\";\n },\n ),\n ),\n }\n : {}),\n },\n ...(graph.reference\n ? {\n reference: handler(\n [\n SetMetadata(FIXTURE_METADATA, \"reference\"),\n ...(graph.reference === \"bare\"\n ? []\n : [Require(requirement(orgPolicy, {}))]),\n ],\n [],\n \"read\",\n (_params, input) => ({ id: input.id, orgId: input.orgId }),\n ),\n }\n : {}),\n ...(graph.classDecorators\n ? { classDecorators: graph.classDecorators }\n : {}),\n },\n };\n}\n\n/** How a described call exposes its browser leg: none, one per operation, or its connection's handshake. */\ntype LegShape = \"none\" | \"operation\" | \"connection\";\n\ninterface Instrumentation {\n readonly consumed: string[];\n readonly contexts: ExecutionContext[];\n /** The leg shape of each call described while `recordLegs` is set. */\n readonly legs: LegShape[];\n unavailable: boolean;\n /**\n * Read each described call's browser leg while its invocation runs. A transport may fail closed once the logical\n * request has completed (GraphQL rejects a completed request), so the kit never reads a leg afterwards.\n */\n recordLegs: boolean;\n}\n\n/** Wraps the registry's describe() so request-dependent getters are counted and can be made unavailable. */\nfunction instrument(app: INestApplication): Instrumentation {\n const registry = app.get<TransportRegistry>(TRANSPORT_REGISTRY, {\n strict: false,\n });\n const state: Instrumentation = {\n consumed: [],\n contexts: [],\n legs: [],\n unavailable: false,\n recordLegs: false,\n };\n const original = registry.describe.bind(registry);\n registry.describe = (context, transport) => {\n const call = original(context, transport);\n state.contexts.push(context);\n if (state.recordLegs) {\n const browser = call.browser;\n state.legs.push(\n browser === undefined\n ? \"none\"\n : browser.key === call.key\n ? \"operation\"\n : \"connection\",\n );\n }\n const read = <T>(name: string, get: () => T): T => {\n state.consumed.push(name);\n if (state.unavailable) {\n throw BetterAuthConfigurationError.atRequest(\n \"CONFORMANCE_EXTRACTION_UNAVAILABLE\",\n \"The conformance kit made request extraction unavailable\",\n );\n }\n return get();\n };\n const wrapped: TransportCall = {\n key: call.key,\n invocation: call.invocation,\n connection: call.connection,\n principalTtlMs: call.principalTtlMs,\n lineage: call.lineage,\n param: (name) => call.param(name),\n headers: () => read(\"headers\", () => call.headers()),\n get clientIp() {\n return read(\"clientIp\", () => call.clientIp);\n },\n get cookies() {\n return read(\"cookies\", () => call.cookies);\n },\n get request() {\n return read(\"request\", () => call.request);\n },\n get browser() {\n return read(\"browser\", () => call.browser);\n },\n };\n return wrapped;\n };\n return state;\n}\n\nfunction resolvedTransport(\n app: INestApplication,\n ref: ExtensionRef<AuthTransport>,\n): AuthTransport {\n const list = app\n .get<TransportRegistry>(TRANSPORT_REGISTRY, { strict: false })\n .list();\n const id =\n ref && typeof ref === \"object\" && !(EXTENSION_DEFINITION in ref)\n ? (ref as AuthTransport).id\n : undefined;\n // Harnesses register the transport first; core appends the HTTP transport.\n const found =\n list.find((transport) => transport === ref) ??\n (typeof ref === \"function\"\n ? list.find((transport) => transport instanceof ref)\n : undefined) ??\n (id === undefined\n ? undefined\n : list.find((transport) => transport.id === id)) ??\n list[0];\n assert.ok(found, \"no transport is registered\");\n return found;\n}\n\n/**\n * Whether a transport member is known without booting: a transport object answers for itself, a class only when its\n * prototype defines the member (instance fields are unknown), and a definition never. Undefined means unknown.\n */\nfunction staticMember(\n ref: ExtensionRef<AuthTransport>,\n name: keyof AuthTransport,\n): boolean | undefined {\n if (typeof ref === \"function\") {\n return typeof Reflect.get(ref.prototype as object, name) === \"function\"\n ? true\n : undefined;\n }\n if (ref && typeof ref === \"object\" && !(EXTENSION_DEFINITION in ref)) {\n return typeof Reflect.get(ref, name) === \"function\";\n }\n return undefined;\n}\n\ninterface KitEnv {\n readonly auth: AuthLike;\n readonly probe: ProbeState;\n readonly keys: KitKeys;\n readonly identity: KitIdentity;\n readonly source: PrincipalSource<AuthPrincipalBase>;\n /**\n * The transport's browser leg is its connection's handshake: a browser always sends Origin there, so the kit's cookie\n * credential carries the trusted base URL as Origin, as a page of that origin does.\n */\n readonly connectionLeg: boolean;\n sessionCookieName(): Promise<string>;\n}\n\n/** The organizations the 'org' fixture names: the identity owns org-a and org-a2 and is a plain member of org-b. */\nasync function seedOrganizations(\n auth: AuthLike,\n userId: string,\n): Promise<void> {\n const context = (await auth.$context) as {\n adapter: {\n create(input: {\n model: string;\n data: Record<string, unknown>;\n forceAllowId?: boolean;\n }): Promise<unknown>;\n };\n };\n for (const [id, role] of [\n [\"org-a\", \"owner\"],\n [\"org-a2\", \"owner\"],\n [\"org-b\", \"member\"],\n ] as const) {\n await context.adapter.create({\n model: \"organization\",\n data: {\n id,\n name: id,\n slug: `${id}-${globalThis.crypto.randomUUID()}`,\n createdAt: new Date(),\n },\n forceAllowId: true,\n });\n await context.adapter.create({\n model: \"member\",\n data: { organizationId: id, userId, role, createdAt: new Date() },\n });\n }\n}\n\nasync function environment(\n authOptions: Omit<BetterAuthOptions, \"database\"> = {},\n connectionLeg = false,\n settings: ConformanceAuthSettings = {},\n): Promise<KitEnv> {\n const plugins = authOptions.plugins ?? [];\n const auth = createConformanceAuth(\n {\n ...authOptions,\n plugins: plugins.some((plugin) => plugin.id === \"organization\")\n ? plugins\n : [...plugins, organization()],\n },\n // Only the T-csrf-http-unsafe rows pass origin-check settings.\n settings,\n );\n const probe = await probeOf(auth);\n const identity = await kitIdentity(auth);\n await seedOrganizations(auth, identity.userId);\n const keys: KitKeys = {\n valid: `key-${globalThis.crypto.randomUUID()}`,\n limited: `limited-${globalThis.crypto.randomUUID()}`,\n verifications: 0,\n owner: identity.userId,\n delayMs: 0,\n };\n return {\n auth,\n probe,\n keys,\n identity,\n source: keySource(keys),\n connectionLeg,\n async sessionCookieName() {\n const context = (await auth.$context) as {\n authCookies: { sessionToken: { name: string } };\n };\n return context.authCookies.sessionToken.name;\n },\n };\n}\n\n/** An organization the kit identity of `env` owns (instances with the organization plugin); returns its id. */\nasync function createKitOrganization(env: KitEnv): Promise<string> {\n const created = (await (\n env.auth.api as unknown as {\n createOrganization(input: {\n headers: Headers;\n body: { name: string; slug: string };\n }): Promise<{ id: string }>;\n }\n ).createOrganization({\n headers: new Headers({ cookie: env.identity.cookie }),\n body: {\n name: \"Conformance\",\n slug: `conformance-${globalThis.crypto.randomUUID()}`,\n },\n })) as { id: string };\n return created.id;\n}\n\ninterface Booted {\n readonly app: INestApplication;\n /** Everything the app logged, from boot on when the harness applies the `logger` option. */\n readonly logger: CapturingLogger;\n readonly instrumentation: Instrumentation;\n}\n\ntype GraphEnhancers = readonly (\"guards\" | \"interceptors\" | \"filters\")[];\n\ninterface BootOptions {\n fixtures?: TransportFixtures;\n forwardDirectCalls?: boolean;\n fieldResolverCoverage?: \"warn\";\n graphqlContext?: GraphqlContextShape;\n globalGuard?: boolean;\n override?: (builder: TestingModuleBuilder) => TestingModuleBuilder;\n defaultRequirements?: readonly RequirementExpr[];\n fieldResolverEnhancers?: GraphEnhancers;\n federation?: boolean;\n globalScope?: boolean;\n appEnhancers?: boolean;\n logSummary?: boolean;\n}\n\nasync function withApp(\n options: TransportConformanceOptions,\n env: KitEnv,\n fn: (booted: Booted) => Promise<void>,\n boot: BootOptions = {},\n logger = new CapturingLogger(),\n): Promise<void> {\n const app = await options.createApp(\n boot.fixtures ?? kitFixtures(),\n env.auth,\n {\n globalGuard: boot.globalGuard ?? true,\n principals: [env.source as unknown as PrincipalSource],\n logger,\n ...(boot.override ? { override: boot.override } : {}),\n ...(boot.defaultRequirements\n ? { defaultRequirements: boot.defaultRequirements }\n : {}),\n ...(boot.fieldResolverEnhancers\n ? { fieldResolverEnhancers: boot.fieldResolverEnhancers }\n : {}),\n ...(boot.federation ? { federation: true } : {}),\n ...(boot.globalScope === undefined\n ? {}\n : { globalScope: boot.globalScope }),\n ...(boot.appEnhancers ? { appEnhancers: true } : {}),\n ...(boot.forwardDirectCalls ? { forwardDirectCalls: true } : {}),\n ...(boot.fieldResolverCoverage\n ? { fieldResolverCoverage: boot.fieldResolverCoverage }\n : {}),\n ...(boot.graphqlContext ? { graphqlContext: boot.graphqlContext } : {}),\n ...(boot.logSummary ? { logSummary: true } : {}),\n },\n );\n app.useLogger(logger);\n try {\n await fn({ app, logger, instrumentation: instrument(app) });\n } finally {\n await app.close();\n }\n}\n\nasync function bootFailure(\n options: TransportConformanceOptions,\n env: KitEnv,\n boot: BootOptions,\n): Promise<unknown> {\n const result = await settle(() =>\n withApp(options, env, async () => undefined, boot),\n );\n assert.equal(result.ok, false, \"the boot variant booted\");\n return !result.ok && result.error;\n}\n\nasync function expectBootFailure(\n options: TransportConformanceOptions,\n env: KitEnv,\n boot: BootOptions,\n code: string | readonly string[],\n): Promise<void> {\n const expected = typeof code === \"string\" ? [code] : code;\n const error = await bootFailure(options, env, boot);\n const codes = bootIssueCodes(error);\n assert.ok(\n expected.some(\n (value) => codes.includes(value) || String(error).includes(value),\n ),\n `expected ${expected.join(\" or \")}, got ${codes.join(\", \")}: ${String(error)}`,\n );\n}\n\n/** The default instance's boot summary line (BetterAuthModule's logSummary). */\nfunction summaryLine(logger: CapturingLogger): string {\n const line = logger.entries.find(\n (entry) =>\n entry.level === \"log\" &&\n entry.text.startsWith(\"'default': \") &&\n entry.text.includes(\"; scope: \"),\n )?.text;\n assert.ok(\n line,\n `boot logged no summary (pass the logSummary and logger options to the app): ${logger.text().slice(0, 500)}`,\n );\n return line;\n}\n\n/** Stable codes of the WARN entries a logger captured (`CODE: message`). */\nfunction warningCodes(logger: CapturingLogger): Set<string> {\n return new Set(\n logger.entries\n .filter((entry) => entry.level === \"warn\")\n .map((entry) => /^([A-Z][A-Z0-9_]+):/.exec(entry.text)?.[1])\n .filter((code): code is string => code !== undefined),\n );\n}\n\ninterface RecordedClaim {\n // biome-ignore lint/complexity/noBannedTypes: Nest metadata accepts class and function targets.\n readonly target: Function;\n readonly method: string | undefined;\n readonly reach: GuardReach;\n readonly options: ClaimOptions;\n /** The kit fixture the claimed handler serves, from its SetMetadata() marker. */\n readonly fixture: string | undefined;\n}\n\n/** Suffix the kit gives every Nest metadata key written while it runs validate() with renamed metadata (T-metadata-canary). */\nconst RENAMED_METADATA = \":nestjs-kit-better-auth-conformance-renamed\";\n\ninterface ClaimRecording {\n /** Classes the validation context's discovery lists besides the app's controllers and providers. */\n // biome-ignore lint/complexity/noBannedTypes: Nest metadata accepts class and function targets.\n readonly classes?: readonly Function[];\n /**\n * Write every string metadata key under another name while validate() runs, as if the installed Nest wrote its\n * decorators' metadata under keys the transport does not read.\n */\n readonly renameMetadata?: boolean;\n}\n\n/** The claims the transport makes for a booted app, recorded by running its validate() once more. */\nasync function recordClaims(\n app: INestApplication,\n ref: ExtensionRef<AuthTransport>,\n recording: ClaimRecording = {},\n): Promise<RecordedClaim[]> {\n const transport = resolvedTransport(app, ref);\n const claims: RecordedClaim[] = [];\n const planner = app.get<RoutePlanner>(ROUTE_PLANNER, { strict: false });\n const discovery = app.get(DiscoveryService, { strict: false });\n const extra = (recording.classes ?? []).map(\n (metatype) =>\n ({\n metatype,\n isAlias: false,\n name: metatype.name,\n }) as unknown as ReturnType<DiscoveryService[\"getProviders\"]>[number],\n );\n const define = Reflect.defineMetadata;\n if (recording.renameMetadata) {\n Reflect.defineMetadata = (\n key: unknown,\n value: unknown,\n target: object,\n property?: string | symbol,\n ) =>\n define(\n typeof key === \"string\" && !key.startsWith(\"design:\")\n ? `${key}${RENAMED_METADATA}`\n : key,\n value,\n target,\n property as string | symbol,\n );\n }\n try {\n await transport.validate?.({\n discovery: {\n getControllers: () => [...discovery.getControllers(), ...extra],\n getProviders: () => [...discovery.getProviders(), ...extra],\n } as unknown as DiscoveryService,\n reflector: app.get(Reflector, { strict: false }),\n moduleRef: app.get(ModuleRef, { strict: false }),\n hasHttpAdapter:\n app.get<MountCoordinator>(MOUNT_COORDINATOR, { strict: false })\n .adapter !== null,\n planOf: (target, method) => planner.plan(target as Type, method),\n claim: (target, method, reach, options) => {\n const handler: unknown =\n method === undefined\n ? undefined\n : Reflect.get(target.prototype as object, method);\n const fixture =\n typeof handler === \"function\"\n ? (Reflect.getMetadata(FIXTURE_METADATA, handler) as\n | string\n | undefined)\n : undefined;\n claims.push({ target, method, reach, options, fixture });\n },\n logger: new CapturingLogger(),\n });\n } finally {\n Reflect.defineMetadata = define;\n }\n return claims;\n}\n\n/** A class with the own class-level metadata of `target` and no methods: a push-only gateway, a controller without routes. */\n// biome-ignore lint/complexity/noBannedTypes: Nest metadata accepts class and function targets.\nfunction withoutHandlers(target: Function): Function {\n const clone = { [`${target.name}WithoutHandlers`]: class {} }[\n `${target.name}WithoutHandlers`\n ]!;\n for (const key of Reflect.getOwnMetadataKeys(target)) {\n Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, target), clone);\n }\n return clone;\n}\n\n/** The booted instance and method name that serve a kit fixture, found by its SetMetadata() marker. */\nfunction fixtureInstance(\n app: INestApplication,\n fixture: string,\n): { instance: object; method: string } {\n const discovery = app.get(DiscoveryService, { strict: false });\n const scanner = new MetadataScanner();\n for (const wrapper of [\n ...discovery.getControllers(),\n ...discovery.getProviders(),\n ]) {\n const instance: unknown = wrapper.instance;\n if (!instance || typeof instance !== \"object\") {\n continue;\n }\n for (const method of scanner.getAllMethodNames(\n Object.getPrototypeOf(instance) as object,\n )) {\n const handler: unknown = Reflect.get(instance, method);\n if (\n typeof handler === \"function\" &&\n Reflect.getMetadata(FIXTURE_METADATA, handler) === fixture\n ) {\n return { instance, method };\n }\n }\n }\n assert.fail(`no booted controller or provider serves the ${fixture} fixture`);\n}\n\n/**\n * Whether the transport has a member, resolved through one boot when a class or definition leaves it unknown. The\n * kit's multiple-invocation and GraphQL cases apply to transports with `lineage` and `defaultAccessFor`.\n */\nasync function transportHas(\n options: TransportConformanceOptions,\n env: KitEnv,\n member: \"lineage\" | \"defaultAccessFor\",\n): Promise<boolean> {\n const known = staticMember(options.transport, member);\n if (known !== undefined) {\n return known;\n }\n let found = false;\n await withApp(options, env, async ({ app }) => {\n found =\n typeof resolvedTransport(app, options.transport)[member] === \"function\";\n });\n return found;\n}\n\n/**\n * Whether the transport's browser leg is its connection's handshake: the leg of an anonymous `optional` (read) invocation\n * outlives the invocation's logical request, as a WebSocket's handshake does. A cross-site page reads every reply on such\n * a connection, so the T-ws-origin-* cases expect every message enforced. Other legs follow each operation (HTTP\n * requests, GraphQL over HTTP).\n */\nasync function connectionShaped(\n options: TransportConformanceOptions,\n): Promise<boolean> {\n let shaped = false;\n await withApp(\n options,\n await environment(),\n async ({ app, instrumentation }) => {\n instrumentation.recordLegs = true;\n succeeded(\n await options.invoke(app, \"optional\", {}),\n \"an anonymous optional invocation\",\n );\n const [leg] = instrumentation.legs;\n assert.ok(leg, \"the guard described no invocation\");\n shaped = leg === \"connection\";\n },\n );\n return shaped;\n}\n\nfunction sessionReads(probe: ProbeState, from: number): number {\n return probe.calls.slice(from).filter((path) => path === \"/get-session\")\n .length;\n}\n\nfunction denied(\n result: Pick<TransportInvocationResult, \"ok\" | \"body\" | \"error\">,\n status: number,\n reason?: string,\n label = \"\",\n): void {\n const prefix = label ? `${label}: ` : \"\";\n assert.equal(\n result.ok,\n false,\n `${prefix}expected a ${status} denial, got success: ${JSON.stringify(result.body)}`,\n );\n assert.equal(\n result.error?.statusCode,\n status,\n `${prefix}expected ${status}, got ${JSON.stringify(result.error)}`,\n );\n if (reason !== undefined) {\n assert.equal(\n result.error?.reason,\n reason,\n `${prefix}${JSON.stringify(result.error)}`,\n );\n }\n}\n\nfunction internal(\n result: Pick<TransportInvocationResult, \"ok\" | \"error\">,\n label = \"\",\n): void {\n const prefix = label ? `${label}: ` : \"\";\n assert.equal(result.ok, false, `${prefix}expected a generic internal error`);\n const status = result.error?.statusCode;\n assert.ok(\n status === undefined || status >= 500,\n `${prefix}expected a 5xx, got ${JSON.stringify(result.error)}`,\n );\n}\n\nfunction succeeded(result: TransportInvocationResult, label = \"\"): void {\n assert.equal(\n result.ok,\n true,\n `${label ? `${label}: ` : \"\"}expected success, got ${JSON.stringify(result.error)}`,\n );\n}\n\nfunction principalOf(result: TransportInvocationResult) {\n return (result.body as { principal?: { kind?: string; userId?: string } })\n ?.principal;\n}\n\n/** A context type no built-in transport handles (T-public-unclaimed-context). */\nconst UNCLAIMED_CONTEXT = \"@nestjs-kit/better-auth:conformance-unclaimed\";\n\nconst foreignContext = {\n getType: () => \"@nestjs-kit/better-auth:conformance-foreign\",\n getArgs: () => [{}],\n getArgByIndex: () => ({}),\n getClass: () => Object,\n getHandler: () => function foreign() {},\n switchToHttp: () => ({\n getRequest: () => ({}),\n getResponse: () => ({}),\n getNext: () => undefined,\n }),\n switchToRpc: () => ({ getData: () => ({}), getContext: () => ({}) }),\n switchToWs: () => ({\n getData: () => ({}),\n getClient: () => ({}),\n getPattern: () => \"\",\n }),\n} as unknown as ExecutionContext;\n\n/**\n * The transport kit (invariants T1–T11 and the core behavior every transport exposes). The kit owns the Better Auth\n * instance, a kit API-key source (passed as `principals`), kit policies and the fixture handlers; the harness exposes\n * the fixtures in its transport's shape. Applicability comes from the transport, not from the helpers a harness\n * passes: a transport with a lineage needs invokeTwice, one that nests handlers (defaultAccessFor) needs invokeGraph,\n * and one that claims the kit's federation reference resolver needs invokeEntities. The kit reads those members from\n * a transport object directly and boots once for a class or a definition.\n */\nexport function transportConformance(\n options: TransportConformanceOptions,\n): ConformanceCase[] {\n const cases: ConformanceCase[] = [];\n let legShape: Promise<boolean> | undefined;\n /** Whether the browser leg is the connection's handshake, read once per kit from the transport. */\n const connectionLeg = async (): Promise<boolean> => {\n if (!options.expectBrowserLeg) {\n return false;\n }\n legShape ??= connectionShaped(options);\n return legShape;\n };\n const kitEnvironment = async (\n authOptions?: Omit<BetterAuthOptions, \"database\">,\n settings?: ConformanceAuthSettings,\n ): Promise<KitEnv> =>\n environment(authOptions, await connectionLeg(), settings);\n const addRun = (\n id: string,\n title: string,\n run: () => Promise<ConformanceOutcome>,\n skip?: string,\n ) => cases.push(conformanceCase(id, title, run, skip));\n const add = (\n id: string,\n title: string,\n run: (env: KitEnv) => Promise<ConformanceOutcome>,\n skip?: string,\n ) => addRun(id, title, async () => run(await kitEnvironment()), skip);\n const noBrowser = options.expectBrowserLeg\n ? undefined\n : \"the transport declares no browser leg\";\n /** Undefined when the browser leg follows each operation; a skip when it is the connection's handshake. */\n const operationLeg = async (): Promise<ConformanceSkip | undefined> =>\n (await connectionLeg())\n ? conformanceSkip(\n \"the browser leg is the connection's handshake, enforced on every message (T-ws-origin-* cover it)\",\n )\n : undefined;\n const noLineage = \"the transport has no lineage and gives no invokeTwice\";\n const noNesting = \"the transport nests no handlers and gives no invokeGraph\";\n const twiceSkip =\n !options.invokeTwice && staticMember(options.transport, \"lineage\") === false\n ? noLineage\n : undefined;\n const graphSkip =\n !options.invokeGraph &&\n staticMember(options.transport, \"defaultAccessFor\") === false\n ? noNesting\n : undefined;\n /** Undefined when invokeTwice is given; fails when the transport has a lineage without it. */\n const twiceReady = async (\n env: KitEnv,\n ): Promise<ConformanceSkip | undefined> => {\n if (options.invokeTwice) {\n assert.ok(\n options.invocationShapes?.length,\n \"invokeTwice requires invocationShapes\",\n );\n return undefined;\n }\n assert.equal(\n await transportHas(options, env, \"lineage\"),\n false,\n \"the transport has a lineage, so invokeTwice and invocationShapes are required\",\n );\n return conformanceSkip(noLineage);\n };\n /** Undefined when invokeGraph is given; fails when the transport nests handlers without it. */\n const graphReady = async (\n env: KitEnv,\n ): Promise<ConformanceSkip | undefined> => {\n if (options.invokeGraph) {\n return undefined;\n }\n assert.equal(\n await transportHas(options, env, \"defaultAccessFor\"),\n false,\n \"the transport nests handlers (defaultAccessFor), so invokeGraph is required\",\n );\n return conformanceSkip(noNesting);\n };\n const enhancerBoots: readonly GraphEnhancers[] = [\n [],\n [\"guards\", \"interceptors\"],\n ];\n const graphOf = (result: GraphResult, root: string, field?: string) => {\n const node = (result.data as Record<string, unknown> | null | undefined)?.[\n root\n ] as Record<string, unknown> | null | undefined;\n return field === undefined ? node : node?.[field];\n };\n const userOf = (value: unknown) =>\n (value as { principal?: { userId?: string } | null } | null | undefined)\n ?.principal?.userId ?? null;\n const host = new URL(KIT_BASE_URL).host;\n const dynamicBaseURL = { allowedHosts: [host], fallback: KIT_BASE_URL };\n const cookie = (env: KitEnv) => ({\n cookie: env.identity.cookie,\n ...(env.connectionLeg ? { origin: KIT_BASE_URL } : {}),\n });\n\n add(\n \"T-selection\",\n \"handles() accepts its contexts with and without credentials and rejects foreign ones\",\n (env) =>\n withApp(options, env, async ({ app, instrumentation }) => {\n const transport = resolvedTransport(app, options.transport);\n const registry = app.get<TransportRegistry>(TRANSPORT_REGISTRY, {\n strict: false,\n });\n instrumentation.recordLegs = !options.expectBrowserLeg;\n succeeded(await options.invoke(app, \"optional\", {}));\n instrumentation.recordLegs = false;\n for (const leg of instrumentation.legs) {\n assert.equal(\n leg,\n \"none\",\n \"the transport describes a browser leg, so expectBrowserLeg must be true\",\n );\n }\n succeeded(await options.invoke(app, \"optional\", cookie(env)));\n assert.ok(\n instrumentation.contexts.length >= 2,\n \"the guard described no invocation\",\n );\n for (const context of instrumentation.contexts) {\n assert.equal(transport.handles(context), true);\n assert.equal(\n registry.find(context),\n transport,\n \"another registered transport claimed the context first\",\n );\n }\n assert.equal(transport.handles(foreignContext), false);\n }),\n );\n add(\n \"T-public-unclaimed-context\",\n \"in a context type no registered transport handles, a public handler runs without auth work and a required one answers NO_TRANSPORT\",\n (env) =>\n withApp(options, env, async ({ app, instrumentation }) => {\n const creator = app.get(ExternalContextCreator, { strict: false });\n const run = (fixture: FixtureName) => {\n const { instance, method } = fixtureInstance(app, fixture);\n const callback = Reflect.get(instance, method) as (\n ...args: unknown[]\n ) => unknown;\n const handler = creator.create(\n instance as Record<string, (...args: unknown[]) => unknown>,\n callback,\n method,\n undefined,\n undefined,\n undefined,\n undefined,\n { guards: true, interceptors: true, filters: false },\n UNCLAIMED_CONTEXT,\n );\n return settle(async () => handler({}));\n };\n const from = env.probe.calls.length;\n const described = instrumentation.contexts.length;\n const reached = await run(\"public\");\n assert.ok(\n reached.ok,\n `the public handler did not run: ${String(!reached.ok && reached.error)}`,\n );\n assert.equal(\n instrumentation.contexts.length,\n described,\n \"the guard described a context no transport handles\",\n );\n assert.equal(sessionReads(env.probe, from), 0, \"the session was read\");\n const required = await run(\"required\");\n assert.equal(required.ok, false, \"the required handler ran\");\n assert.deepEqual(\n bootIssueCodes(!required.ok && required.error),\n [\"NO_TRANSPORT\"],\n `expected NO_TRANSPORT, got ${String(!required.ok && required.error)}`,\n );\n assert.equal(sessionReads(env.probe, from), 0, \"the session was read\");\n }),\n );\n add(\n \"T-no-credentials\",\n \"missing credentials answer 401 UNAUTHENTICATED without throwing from headers()\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const result = await options.invoke(app, \"required\", {});\n denied(result, 401);\n assert.equal(result.error?.code, \"UNAUTHENTICATED\");\n succeeded(await options.invoke(app, \"public\", {}));\n }),\n );\n add(\n \"T-credentials\",\n \"cookie, bearer and x-api-key credentials are extracted\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const byCookie = await options.invoke(app, \"required\", cookie(env));\n succeeded(byCookie);\n assert.deepEqual(principalOf(byCookie), {\n kind: \"session\",\n userId: env.identity.userId,\n });\n const byBearer = await options.invoke(app, \"required\", {\n authorization: `Bearer ${env.identity.token}`,\n });\n succeeded(byBearer);\n assert.equal(principalOf(byBearer)?.userId, env.identity.userId);\n const byKey = await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": env.keys.valid,\n });\n succeeded(byKey);\n assert.equal(principalOf(byKey)?.kind, \"api-key\");\n }),\n );\n add(\n \"T-memo-once\",\n \"one logical request resolves each accepted-kind set at most once\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n let from = env.probe.calls.length;\n succeeded(await options.invoke(app, \"triple\", cookie(env)));\n assert.ok(\n sessionReads(env.probe, from) <= 1,\n `triple read the session ${sessionReads(env.probe, from)} times`,\n );\n from = env.probe.calls.length;\n succeeded(await options.invoke(app, \"tripleMixed\", cookie(env)));\n assert.ok(sessionReads(env.probe, from) <= 2);\n for (const shape of options.invocationShapes ?? []) {\n if (shape !== \"aliases\" && shape !== \"batched\") {\n continue;\n }\n from = env.probe.calls.length;\n await options.invokeTwice!(\n app,\n shape,\n [{ orgId: \"org-a\" }, { orgId: \"org-a2\" }],\n cookie(env),\n );\n assert.equal(\n sessionReads(env.probe, from),\n 1,\n `two ${shape} invocations of one request resolved the principal ${sessionReads(env.probe, from)} times`,\n );\n }\n }),\n );\n add(\n \"T-invocation-decisions\",\n \"two invocations in one request or connection are decided and valued independently\",\n async (env) =>\n (await twiceReady(env)) ??\n withApp(options, env, async ({ app }) => {\n for (const shape of options.invocationShapes!) {\n const [first, second] = await options.invokeTwice!(\n app,\n shape,\n [{ orgId: \"org-a\" }, { orgId: \"org-b\" }],\n cookie(env),\n );\n assert.equal(first.ok, true, `${shape}: the allowed org was denied`);\n assert.equal(\n second.error?.reason,\n \"MISSING_PERMISSION\",\n `${shape}: the second invocation was not decided independently (${JSON.stringify(second)})`,\n );\n const [deniedFirst, allowedSecond] = await options.invokeTwice!(\n app,\n shape,\n [{ orgId: \"org-b\" }, { orgId: \"org-a\" }],\n cookie(env),\n );\n assert.equal(deniedFirst.error?.reason, \"MISSING_PERMISSION\");\n assert.equal(\n allowedSecond.ok,\n true,\n `${shape}: the second invocation was not decided independently (${JSON.stringify(allowedSecond)})`,\n );\n const values = await options.invokeTwice!(\n app,\n shape,\n [{ orgId: \"org-a\" }, { orgId: \"org-a2\" }],\n cookie(env),\n );\n assert.deepEqual(\n values.map((value) => value.ok),\n [true, true],\n `${shape}: @ActiveOrganizationId() did not return each invocation's own organization`,\n );\n }\n }),\n twiceSkip,\n );\n add(\n \"T-acceptance\",\n \"an x-api-key on a route that does not accept api keys is never verified\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const withCookie = await options.invoke(app, \"required\", {\n ...cookie(env),\n \"x-api-key\": env.keys.valid,\n });\n succeeded(withCookie);\n assert.equal(principalOf(withCookie)?.kind, \"session\");\n denied(\n await options.invoke(app, \"required\", {\n \"x-api-key\": env.keys.valid,\n }),\n 401,\n );\n assert.equal(env.keys.verifications, 0, \"the key was verified\");\n succeeded(\n await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": env.keys.valid,\n }),\n );\n assert.equal(env.keys.verifications, 1);\n }),\n );\n add(\n \"T-cookie-forwarded\",\n \"a refreshed session cookie is forwarded exactly once\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const name = await env.sessionCookieName();\n const result = await options.invoke(app, \"required\", cookie(env));\n succeeded(result);\n const lines = result.setCookies.filter((line) =>\n line.startsWith(`${name}=`),\n );\n assert.equal(\n lines.length,\n 1,\n `refresh cookies: ${result.setCookies.join(\" | \")}`,\n );\n }),\n options.expectCookieCapable\n ? undefined\n : \"the transport cannot deliver Set-Cookie (see T-refresh-suppressed)\",\n );\n add(\n \"T-refresh-suppressed\",\n \"a cookie-less transport moves no session expiry and writes no cookie\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const context = (await env.auth.$context) as {\n internalAdapter: {\n findSession(token: string): Promise<{\n session: { expiresAt: Date };\n } | null>;\n };\n };\n const before = await context.internalAdapter.findSession(\n env.identity.token,\n );\n const writes = env.probe.writes.length;\n const result = await options.invoke(app, \"required\", cookie(env));\n succeeded(result);\n const after = await context.internalAdapter.findSession(\n env.identity.token,\n );\n assert.deepEqual(result.setCookies, []);\n assert.equal(\n new Date(after!.session.expiresAt).getTime(),\n new Date(before!.session.expiresAt).getTime(),\n \"the session expiry moved\",\n );\n assert.ok(\n !env.probe.writes.slice(writes).includes(\"session.update\"),\n \"the session row was refreshed\",\n );\n assert.ok(\n env.probe.refresh\n .filter((entry) => entry.path === \"/get-session\")\n .slice(-1)\n .every((entry) => entry.skip),\n \"getShouldSkipSessionRefresh() was not true inside the scope\",\n );\n }),\n options.expectCookieCapable\n ? \"the transport delivers Set-Cookie (see T-cookie-forwarded)\"\n : undefined,\n );\n add(\n \"T-csrf-http-unsafe\",\n \"an unsafe cookie operation needs a trusted origin, checked before any session read, unless an explicit opt-out applies; Better Auth's boolean origin skip is not one\",\n async (env) => {\n const skip = await operationLeg();\n if (skip) {\n return skip;\n }\n await withApp(options, env, async ({ app }) => {\n const from = env.probe.calls.length;\n denied(\n await options.invoke(app, \"unsafe\", {\n ...cookie(env),\n origin: UNTRUSTED_ORIGIN,\n }),\n 403,\n \"INVALID_ORIGIN\",\n );\n assert.equal(sessionReads(env.probe, from), 0, \"the session was read\");\n denied(\n await options.invoke(app, \"unsafe\", cookie(env)),\n 403,\n \"MISSING_OR_NULL_ORIGIN\",\n );\n for (const origin of [PROBE_TRUSTED_ORIGIN, KIT_BASE_URL]) {\n succeeded(\n await options.invoke(app, \"unsafe\", { ...cookie(env), origin }),\n `trusted origin ${origin}`,\n );\n }\n succeeded(\n await options.invoke(app, \"unsafe\", {\n ...cookie(env),\n // A same-origin page of the trusted base URL: the leg's own host is that origin.\n host: new URL(KIT_BASE_URL).host,\n origin: \"null\",\n \"sec-fetch-site\": \"same-origin\",\n }),\n \"Origin: null with Sec-Fetch-Site: same-origin\",\n );\n succeeded(\n await options.invoke(app, \"unsafe\", {\n authorization: `Bearer ${env.identity.token}`,\n origin: UNTRUSTED_ORIGIN,\n }),\n \"a bearer token without a cookie\",\n );\n });\n // Explicit opt-outs: @SkipOriginCheck() on the handler, and Better Auth's own advanced.disableCSRFCheck.\n const untrusted = async (\n app: INestApplication,\n kit: KitEnv,\n label: string,\n ) => {\n const result = await options.invoke(app, \"unsafe\", {\n ...cookie(kit),\n origin: UNTRUSTED_ORIGIN,\n });\n succeeded(result, `${label}: a cookie from an untrusted Origin`);\n assert.equal(principalOf(result)?.userId, kit.identity.userId, label);\n };\n await withApp(\n options,\n env,\n ({ app }) => untrusted(app, env, \"@SkipOriginCheck()\"),\n { fixtures: kitFixtures({ unsafe: [SkipOriginCheck()] }) },\n );\n const disabled = await kitEnvironment({}, { disableCSRFCheck: true });\n await withApp(options, disabled, ({ app }) =>\n untrusted(app, disabled, \"advanced.disableCSRFCheck\"),\n );\n // Better Auth's boolean origin skip with an explicit disableCSRFCheck: false opens only Better Auth's own\n // routes; application operations stay checked, a deliberate divergence that B19 names. [R6:BA-r6-01]\n const sdkSkip = await kitEnvironment(\n {},\n { disableOriginCheck: true, disableCSRFCheck: false },\n );\n const skipLogger = new CapturingLogger();\n await withApp(\n options,\n sdkSkip,\n async ({ app }) => {\n const from = sdkSkip.probe.calls.length;\n denied(\n await options.invoke(app, \"unsafe\", {\n ...cookie(sdkSkip),\n origin: UNTRUSTED_ORIGIN,\n }),\n 403,\n \"INVALID_ORIGIN\",\n );\n assert.equal(\n sessionReads(sdkSkip.probe, from),\n 0,\n \"disableOriginCheck: true with disableCSRFCheck: false: the session was read\",\n );\n succeeded(\n await options.invoke(app, \"unsafe\", {\n ...cookie(sdkSkip),\n origin: KIT_BASE_URL,\n }),\n \"disableOriginCheck: true with disableCSRFCheck: false: the trusted base URL\",\n );\n },\n {},\n skipLogger,\n );\n assert.ok(\n skipLogger.entries.some(\n (entry) =>\n entry.level === \"warn\" &&\n entry.text.startsWith(\"W_ORIGIN_CHECK:\") &&\n entry.text.includes(\"app-route checks remain on\"),\n ),\n `boot did not warn W_ORIGIN_CHECK that app-route checks remain on (pass the logger option to the app): ${skipLogger.text().slice(0, 500)}`,\n );\n },\n noBrowser,\n );\n add(\n \"T-csrf-http-cookie-plus-token\",\n \"a cookie plus a bearer token from an untrusted origin is still denied\",\n async (env) =>\n (await operationLeg()) ??\n withApp(options, env, async ({ app }) => {\n for (const token of [\"a.b\", env.identity.token]) {\n denied(\n await options.invoke(app, \"unsafe\", {\n ...cookie(env),\n authorization: `Bearer ${token}`,\n origin: UNTRUSTED_ORIGIN,\n }),\n 403,\n \"INVALID_ORIGIN\",\n );\n }\n }),\n noBrowser,\n );\n add(\n \"T-csrf-login-proxy\",\n \"a forwarding login proxy follows Better Auth's form rule, and service forwarding needs a declaration\",\n async (env) => {\n const skip = await operationLeg();\n if (skip) {\n return skip;\n }\n const user = await kitIdentity(env.auth, { password: true });\n const credentials = { email: user.email, password: user.password! };\n await withApp(options, env, async ({ app }) => {\n const name = await env.sessionCookieName();\n let signIns = env.probe.calls.filter(\n (path) => path === \"/sign-in/email\",\n ).length;\n const navigation = await options.invoke(\n app,\n \"loginProxy\",\n {\n \"sec-fetch-site\": \"cross-site\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-dest\": \"document\",\n },\n credentials,\n );\n denied(navigation, 403, \"CROSS_SITE_NAVIGATION_LOGIN_BLOCKED\");\n assert.deepEqual(navigation.setCookies, []);\n assert.equal(\n env.probe.calls.filter((path) => path === \"/sign-in/email\").length,\n signIns,\n \"the proxy called Better Auth before the form check\",\n );\n denied(\n await options.invoke(\n app,\n \"loginProxy\",\n {\n origin: UNTRUSTED_ORIGIN,\n \"sec-fetch-site\": \"cross-site\",\n \"sec-fetch-mode\": \"cors\",\n },\n credentials,\n ),\n 403,\n \"INVALID_ORIGIN\",\n );\n const trusted = await options.invoke(\n app,\n \"loginProxy\",\n { origin: KIT_BASE_URL },\n credentials,\n );\n succeeded(trusted);\n assert.ok(\n trusted.setCookies.some((line) => line.startsWith(`${name}=`)),\n \"the trusted sign-in forwarded no session cookie\",\n );\n succeeded(await options.invoke(app, \"loginProxy\", {}, credentials));\n // A public forwarding proxy on a safe operation (HTTP GET) is in form mode too: cross-site input causes no\n // Better Auth call, no session write and no cookie. [R7:SEC-r7-01]\n signIns = env.probe.calls.filter(\n (path) => path === \"/sign-in/email\",\n ).length;\n const writes = env.probe.writes.length;\n const readNavigation = await options.invoke(\n app,\n \"loginProxyRead\",\n {\n \"sec-fetch-site\": \"cross-site\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-dest\": \"document\",\n },\n credentials,\n );\n denied(readNavigation, 403, \"CROSS_SITE_NAVIGATION_LOGIN_BLOCKED\");\n assert.deepEqual(readNavigation.setCookies, []);\n assert.equal(\n env.probe.calls.filter((path) => path === \"/sign-in/email\").length,\n signIns,\n \"a cross-site navigation reached Better Auth through the safe forwarding proxy\",\n );\n assert.deepEqual(\n env.probe.writes.slice(writes),\n [],\n \"a cross-site navigation wrote a session through the safe forwarding proxy\",\n );\n const trustedRead = await options.invoke(\n app,\n \"loginProxyRead\",\n { origin: KIT_BASE_URL },\n credentials,\n );\n succeeded(trustedRead, \"a trusted fetch of the safe forwarding proxy\");\n assert.ok(\n trustedRead.setCookies.some((line) => line.startsWith(`${name}=`)),\n \"the trusted safe forwarding proxy forwarded no session cookie\",\n );\n succeeded(\n await options.invoke(app, \"loginProxyRead\", {}, credentials),\n \"a headerless non-browser call of the safe forwarding proxy\",\n );\n signIns = env.probe.calls.filter(\n (path) => path === \"/sign-in/email\",\n ).length;\n const attempts: Record<string, string>[] = [\n { origin: KIT_BASE_URL },\n { origin: UNTRUSTED_ORIGIN, \"sec-fetch-site\": \"cross-site\" },\n ];\n for (const headers of attempts) {\n const result = await options.invoke(\n app,\n \"loginProxyService\",\n headers,\n credentials,\n );\n internal(result);\n assert.deepEqual(result.setCookies, []);\n }\n assert.equal(\n env.probe.calls.filter((path) => path === \"/sign-in/email\").length,\n signIns,\n \"forwardForeignCookies ran its callback without a declaration\",\n );\n });\n // An inheriting forwarding field under a safe query is in form mode: boot needs field guards to reach it, and a\n // cross-site request is denied before the field calls Better Auth. [R7:SEC-r7-01]\n if (await graphReady(env)) {\n return;\n }\n const forwarding = (guarded: boolean) =>\n kitFixtures({}, [], { guarded, forwarding: credentials });\n await expectBootFailure(\n options,\n env,\n { fieldResolverEnhancers: [], fixtures: forwarding(false) },\n \"FIELD_RESOLVER_UNGUARDED\",\n );\n await withApp(\n options,\n env,\n async ({ app }) => {\n const signIns = env.probe.calls.filter(\n (path) => path === \"/sign-in/email\",\n ).length;\n const writes = env.probe.writes.length;\n const selection: GraphSelection[] = [\n { root: \"public\", fields: [\"forwarding\", \"reader\"] },\n ];\n const navigation = await options.invokeGraph!(app, selection, {\n \"sec-fetch-site\": \"cross-site\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-dest\": \"document\",\n });\n assert.ok(\n navigation.errors.some(\n (error) =>\n error.path.includes(\"forwarding\") &&\n error.reason === \"CROSS_SITE_NAVIGATION_LOGIN_BLOCKED\",\n ),\n `a cross-site navigation reached the inherited forwarding field: ${JSON.stringify(navigation)}`,\n );\n assert.equal(\n env.probe.calls.filter((path) => path === \"/sign-in/email\").length,\n signIns,\n \"a cross-site navigation reached Better Auth through the inherited forwarding field\",\n );\n assert.deepEqual(\n env.probe.writes.slice(writes),\n [],\n \"a cross-site navigation wrote a session through the inherited forwarding field\",\n );\n for (const [headers, label] of [\n [{ origin: KIT_BASE_URL }, \"a trusted fetch\"],\n [{}, \"a headerless non-browser request\"],\n ] as const) {\n const result = await options.invokeGraph!(app, selection, headers);\n assert.deepEqual(\n result.errors,\n [],\n `${label} of the inherited forwarding field: ${JSON.stringify(result.errors)}`,\n );\n assert.equal(graphOf(result, \"public\", \"forwarding\"), \"forwarded\");\n assert.equal(\n userOf(graphOf(result, \"public\", \"reader\")),\n null,\n `${label}: the forwarding field changed the inherited reading`,\n );\n }\n },\n {\n fieldResolverEnhancers: [\"guards\", \"interceptors\"],\n fixtures: forwarding(true),\n },\n );\n },\n noBrowser,\n );\n add(\n \"T-csrf-safe-methods\",\n \"safe cookie reads are not denied by origin validation, while forwarding enforces form mode without cookies\",\n async (env) => {\n const skip = await operationLeg();\n if (skip) {\n return skip;\n }\n const user = await kitIdentity(env.auth, { password: true });\n await withApp(options, env, async ({ app, logger }) => {\n for (const headers of [\n { ...cookie(env), origin: UNTRUSTED_ORIGIN },\n cookie(env),\n ]) {\n const result = await options.invoke(app, \"readsSession\", headers);\n succeeded(result);\n assert.equal(\n (result.body as { userId?: string }).userId,\n env.identity.userId,\n );\n }\n const signIns = env.probe.calls.filter(\n (path) => path === \"/sign-in/email\",\n ).length;\n const result = await options.invoke(\n app,\n \"loginProxyRead\",\n {\n origin: UNTRUSTED_ORIGIN,\n \"sec-fetch-site\": \"cross-site\",\n \"sec-fetch-mode\": \"cors\",\n },\n { email: user.email, password: user.password },\n );\n denied(result, 403, \"INVALID_ORIGIN\");\n assert.deepEqual(result.setCookies, []);\n assert.equal(\n env.probe.calls.filter((path) => path === \"/sign-in/email\").length,\n signIns,\n \"a cross-site safe operation of a forwarding handler reached Better Auth\",\n );\n // A direct call presenting the caller's session needs a passing verdict for this leg: the guarded safe\n // operation computes an advisory one, a public handler none. [R5:SEC-r5-01]\n const direct = { cookie: env.identity.cookie };\n const callerSession = async (\n handler: \"callerSession\" | \"publicCallerSession\",\n origin: string | undefined,\n ) =>\n options.invoke(\n app,\n handler,\n { ...cookie(env), ...(origin === undefined ? {} : { origin }) },\n direct,\n );\n for (const origin of [UNTRUSTED_ORIGIN, undefined]) {\n const label = `a guarded safe operation's direct caller-session call ${origin ? \"from an untrusted Origin\" : \"without Origin\"}`;\n const errors = logger.errors().length;\n internal(await callerSession(\"callerSession\", origin), label);\n assert.match(\n logger\n .errors()\n .slice(errors)\n .map((entry) => entry.text)\n .join(\"\\n\"),\n /PUBLIC_HANDLER_USED_CALLER_SESSION/,\n label,\n );\n }\n const trusted = await callerSession(\"callerSession\", KIT_BASE_URL);\n succeeded(\n trusted,\n \"a guarded safe operation's direct caller-session call from a trusted Origin\",\n );\n assert.equal(\n (trusted.body as { userId?: string }).userId,\n env.identity.userId,\n );\n for (const origin of [KIT_BASE_URL, UNTRUSTED_ORIGIN]) {\n internal(\n await callerSession(\"publicCallerSession\", origin),\n `a public handler's direct caller-session call from ${origin}`,\n );\n }\n });\n },\n noBrowser,\n );\n /** Guarded fixtures a connection case sends, one message each, on one connection. */\n const guardedMessages: readonly FixtureName[] = [\n \"required\",\n \"optional\",\n \"acceptsApiKey\",\n ];\n /** Undefined when the browser leg is the connection's handshake and invokeConnection is given; fails without it. */\n const connectionReady = async (): Promise<ConformanceSkip | undefined> => {\n if (!(await connectionLeg())) {\n return conformanceSkip(\n \"the browser leg follows each operation (T-csrf-* cover it)\",\n );\n }\n assert.ok(\n options.invokeConnection,\n \"the transport's browser leg is its connection's handshake, so invokeConnection is required\",\n );\n return undefined;\n };\n /** Whether the kit checks connection-time authentication: required when the app provides WS_CONNECTION_AUTH. */\n const authenticatesConnections = (app: INestApplication): boolean => {\n let provided: boolean;\n try {\n app.get(WS_CONNECTION_AUTH, { strict: false });\n provided = true;\n } catch {\n provided = false;\n }\n assert.ok(\n !provided || options.authenticateConnection,\n \"the app provides WS_CONNECTION_AUTH, so authenticateConnection is required\",\n );\n return options.authenticateConnection !== undefined;\n };\n /** Every guarded message of one connection, and connection-time authentication, answer the denial. */\n const deniedOnConnection = async (\n app: INestApplication,\n headers: Record<string, string>,\n status: number,\n reason: string,\n label: string,\n ) => {\n const results = await options.invokeConnection!(\n app,\n guardedMessages,\n headers,\n );\n assert.equal(results.length, guardedMessages.length, label);\n for (const [index, result] of results.entries()) {\n denied(result, status, reason, `${label}, ${guardedMessages[index]}`);\n }\n if (authenticatesConnections(app)) {\n denied(\n await options.authenticateConnection!(app, headers),\n status,\n reason,\n `${label}, connection-time authentication`,\n );\n }\n };\n /** Every guarded message of one connection reads the user, and connection-time authentication succeeds. */\n const allowedOnConnection = async (\n app: INestApplication,\n headers: Record<string, string>,\n userId: string,\n label: string,\n ) => {\n const results = await options.invokeConnection!(\n app,\n guardedMessages,\n headers,\n );\n assert.equal(results.length, guardedMessages.length, label);\n for (const [index, result] of results.entries()) {\n succeeded(result, `${label}, ${guardedMessages[index]}`);\n assert.equal(principalOf(result)?.userId, userId, label);\n }\n if (authenticatesConnections(app)) {\n const connection = await options.authenticateConnection!(app, headers);\n assert.equal(\n connection.ok,\n true,\n `${label}, connection-time authentication: ${JSON.stringify(connection.error)}`,\n );\n }\n };\n addRun(\n \"T-ws-origin-untrusted\",\n \"a handshake with a cookie and an untrusted or missing Origin is denied on every message and at connection time, a token-only handshake is allowed, and a function-valued trustedOrigins runs once per connection\",\n async () => {\n const skip = await connectionReady();\n if (skip) {\n return skip;\n }\n const requests: (Request | undefined)[] = [];\n const env = await kitEnvironment({\n trustedOrigins: (request?: Request) => {\n requests.push(request);\n return [FUNCTION_TRUSTED_ORIGIN];\n },\n });\n await withApp(options, env, async ({ app }) => {\n const session = env.identity.cookie;\n await deniedOnConnection(\n app,\n { cookie: session, origin: UNTRUSTED_ORIGIN },\n 403,\n \"INVALID_ORIGIN\",\n \"a cookie handshake from an untrusted Origin\",\n );\n await deniedOnConnection(\n app,\n { cookie: session },\n 403,\n \"MISSING_OR_NULL_ORIGIN\",\n \"a cookie handshake without Origin\",\n );\n for (const origin of [KIT_BASE_URL, UNTRUSTED_ORIGIN]) {\n await allowedOnConnection(\n app,\n { authorization: `Bearer ${env.identity.token}`, origin },\n env.identity.userId,\n `a token-only handshake from ${origin}`,\n );\n }\n const from = requests.length;\n const results = await options.invokeConnection!(app, guardedMessages, {\n cookie: session,\n origin: FUNCTION_TRUSTED_ORIGIN,\n });\n for (const result of results) {\n succeeded(\n result,\n \"a cookie handshake from a function-trusted Origin\",\n );\n }\n assert.equal(\n requests.length - from,\n 1,\n `trustedOrigins() ran ${requests.length - from} times for one connection of ${guardedMessages.length} messages`,\n );\n });\n },\n noBrowser,\n );\n add(\n \"T-ws-origin-junk-token\",\n \"a cookie plus a junk or valid bearer token from an untrusted Origin is denied on every message and at connection time\",\n async (env) =>\n (await connectionReady()) ??\n withApp(options, env, async ({ app }) => {\n for (const [token, kind] of [\n [\"a.b\", \"junk\"],\n [env.identity.token, \"valid\"],\n ] as const) {\n await deniedOnConnection(\n app,\n {\n cookie: env.identity.cookie,\n authorization: `Bearer ${token}`,\n origin: UNTRUSTED_ORIGIN,\n },\n 403,\n \"INVALID_ORIGIN\",\n `a cookie plus a ${kind} bearer token from an untrusted Origin`,\n );\n }\n }),\n noBrowser,\n );\n addRun(\n \"T-ws-origin-dynamic-baseurl\",\n \"with a dynamic baseURL, a same-origin cookie handshake is allowed without a 500 and a cross-site one is denied\",\n async () => {\n const skip = await connectionReady();\n if (skip) {\n return skip;\n }\n const env = await kitEnvironment({ baseURL: dynamicBaseURL });\n await withApp(options, env, async ({ app }) => {\n await allowedOnConnection(\n app,\n { cookie: env.identity.cookie, host, origin: KIT_BASE_URL },\n env.identity.userId,\n \"a same-origin cookie handshake\",\n );\n await deniedOnConnection(\n app,\n { cookie: env.identity.cookie, host, origin: UNTRUSTED_ORIGIN },\n 403,\n \"INVALID_ORIGIN\",\n \"a cross-site cookie handshake\",\n );\n });\n },\n noBrowser,\n );\n addRun(\n \"T-ws-origin-forwarded-host\",\n \"forwarded host and protocol headers never make an untrusted Origin the handshake's own, with a dynamic or unset baseURL and either trustedProxyHeaders\",\n async () => {\n const skip = await connectionReady();\n if (skip) {\n return skip;\n }\n const spoof = {\n host,\n origin: UNTRUSTED_ORIGIN,\n \"x-forwarded-host\": new URL(UNTRUSTED_ORIGIN).host,\n \"x-forwarded-proto\": \"https\",\n };\n for (const baseURL of [dynamicBaseURL, undefined]) {\n for (const trustedProxyHeaders of [false, true]) {\n const env = await kitEnvironment({\n baseURL,\n advanced: { trustedProxyHeaders },\n });\n const label = `${baseURL ? \"dynamic\" : \"unset\"} baseURL, trustedProxyHeaders ${trustedProxyHeaders}`;\n await withApp(options, env, async ({ app }) => {\n await deniedOnConnection(\n app,\n { cookie: env.identity.cookie, ...spoof },\n 403,\n \"INVALID_ORIGIN\",\n `${label}: a forwarded-host spoof`,\n );\n await allowedOnConnection(\n app,\n { cookie: env.identity.cookie, host, origin: KIT_BASE_URL },\n env.identity.userId,\n `${label}: a same-origin handshake`,\n );\n });\n }\n }\n },\n noBrowser,\n );\n addRun(\n \"T-ws-origin-function-trusted-origins\",\n \"a function-valued trustedOrigins receives the handshake's absolute URL, and a throwing one answers the generic internal error\",\n async () => {\n const skip = await connectionReady();\n if (skip) {\n return skip;\n }\n const requests: (Request | undefined)[] = [];\n let outage: Error | undefined;\n const env = await kitEnvironment({\n trustedOrigins: (request?: Request) => {\n requests.push(request);\n if (outage) {\n throw outage;\n }\n return [FUNCTION_TRUSTED_ORIGIN];\n },\n });\n await withApp(options, env, async ({ app }) => {\n const headers = {\n cookie: env.identity.cookie,\n host,\n origin: FUNCTION_TRUSTED_ORIGIN,\n };\n const from = requests.length;\n await allowedOnConnection(\n app,\n headers,\n env.identity.userId,\n \"a cookie handshake from a function-trusted Origin\",\n );\n const received = requests.slice(from);\n assert.ok(received.length > 0, \"trustedOrigins() was not called\");\n for (const request of received) {\n assert.ok(\n request instanceof Request,\n \"trustedOrigins() received no Request\",\n );\n assert.equal(\n new URL(request.url).origin,\n KIT_BASE_URL,\n `trustedOrigins() received ${request.url}, not the handshake's absolute URL`,\n );\n }\n const secret = `trusted-origins-outage-${globalThis.crypto.randomUUID()}`;\n outage = new Error(secret);\n try {\n const results = await options.invokeConnection!(\n app,\n guardedMessages,\n headers,\n );\n for (const [index, result] of results.entries()) {\n internal(\n result,\n `a throwing trustedOrigins(), ${guardedMessages[index]}`,\n );\n assert.ok(\n !JSON.stringify(result.error ?? {}).includes(secret),\n \"the client saw the trustedOrigins() error\",\n );\n }\n if (authenticatesConnections(app)) {\n const connection = await options.authenticateConnection!(\n app,\n headers,\n );\n internal(\n connection,\n \"a throwing trustedOrigins(), connection-time authentication\",\n );\n assert.ok(\n !JSON.stringify(connection.error ?? {}).includes(secret),\n \"the client saw the trustedOrigins() error at connection time\",\n );\n }\n } finally {\n outage = undefined;\n }\n });\n },\n noBrowser,\n );\n const subscriptions = options.invocationShapes?.includes(\"subscriptions\")\n ? undefined\n : \"the harness serves no subscriptions (invocationShapes lacks 'subscriptions')\";\n const subscribe = (app: INestApplication, headers: HeadersInit) =>\n options.invokeTwice!(\n app,\n \"subscriptions\",\n [{ orgId: \"org-a\" }, { orgId: \"org-a2\" }],\n headers,\n );\n const subscriptionDenied = async (\n app: INestApplication,\n headers: Record<string, string>,\n label: string,\n connectionParams?: Record<string, string>,\n ) => {\n for (const [index, result] of (await subscribe(app, headers)).entries()) {\n assert.equal(result.ok, false, `${label}, subscription ${index + 1}`);\n assert.equal(\n result.error?.reason,\n \"INVALID_ORIGIN\",\n `${label}, subscription ${index + 1}: ${JSON.stringify(result.error)}`,\n );\n }\n const messages: FixtureName[] = [\"required\", \"unsafe\"];\n const results = await options.invokeConnection!(\n app,\n messages,\n headers,\n connectionParams ? { connectionParams } : undefined,\n );\n for (const [index, result] of results.entries()) {\n denied(result, 403, \"INVALID_ORIGIN\", `${label}, ${messages[index]}`);\n }\n };\n add(\n \"T-subscription-credentials\",\n \"subscriptions extract credentials from the upgrade cookie and from connectionParams, and deny anonymous connections\",\n async (env) => {\n assert.ok(\n options.invokeConnection,\n \"the harness serves subscriptions, so invokeConnection is required\",\n );\n const other = await kitIdentity(env.auth);\n await withApp(options, env, async ({ app }) => {\n for (const [headers, label] of [\n [cookie(env), \"an upgrade cookie\"],\n [\n { authorization: `Bearer ${env.identity.token}` },\n \"a connectionParams bearer token\",\n ],\n ] as const) {\n assert.deepEqual(\n (await subscribe(app, headers)).map((result) => result.ok),\n [true, true],\n `${label} did not authenticate its subscriptions`,\n );\n }\n assert.deepEqual(\n (await subscribe(app, {})).map((result) => result.ok),\n [false, false],\n \"an anonymous connection's subscriptions were allowed\",\n );\n // A connectionParams cookie replaces the upgrade cookie in the credentials.\n const [replaced] = await options.invokeConnection!(\n app,\n [\"required\"],\n cookie(env),\n { connectionParams: { cookie: other.cookie } },\n );\n succeeded(replaced!, \"a connectionParams cookie\");\n assert.equal(\n principalOf(replaced!)?.userId,\n other.userId,\n \"the connectionParams cookie did not replace the upgrade cookie in the credentials\",\n );\n });\n },\n subscriptions,\n );\n add(\n \"T-subscription-origin\",\n \"subscriptions, queries and mutations on a socket whose upgrade carries a cookie and an untrusted Origin are denied, whatever connectionParams carry\",\n async (env) => {\n assert.ok(\n options.invokeConnection,\n \"the harness serves subscriptions, so invokeConnection is required\",\n );\n const other = await kitIdentity(env.auth);\n const hostile = { cookie: env.identity.cookie, origin: UNTRUSTED_ORIGIN };\n const contexts = options.graphqlContexts ?? [];\n for (const graphqlContext of [\n undefined,\n ...(contexts.includes(\"fresh\") ? ([\"fresh\"] as const) : []),\n ]) {\n const label = graphqlContext\n ? `a ${graphqlContext} GraphQL context`\n : \"the driver's context\";\n await withApp(\n options,\n env,\n async ({ app }) => {\n await subscriptionDenied(\n app,\n hostile,\n `${label}: an untrusted Origin`,\n );\n // The browser leg keeps the upgrade cookie when connectionParams replace it in the credentials.\n await subscriptionDenied(\n app,\n hostile,\n `${label}: an untrusted Origin with a connectionParams cookie`,\n { cookie: other.cookie },\n );\n await allowedOnConnection(\n app,\n cookie(env),\n env.identity.userId,\n `${label}: a trusted Origin`,\n );\n },\n graphqlContext ? { graphqlContext } : {},\n );\n }\n if (contexts.includes(\"plain-request\")) {\n await withApp(\n options,\n env,\n async ({ app, logger }) => {\n const results = await options.invokeConnection!(\n app,\n [\"required\", \"unsafe\"],\n cookie(env),\n );\n for (const result of results) {\n internal(\n result,\n \"a context holding only the cookie in a plain req\",\n );\n }\n assert.match(logger.text(), /GRAPHQL_CONTEXT_UNRECOGNIZED/);\n },\n { graphqlContext: \"plain-request\" },\n );\n }\n },\n subscriptions,\n );\n add(\n \"T-subscription-origin-junk-connection-params\",\n \"a junk connectionParams bearer token beside the victim's upgrade cookie from an untrusted Origin is denied for subscriptions and queries\",\n async (env) => {\n assert.ok(\n options.invokeConnection,\n \"the harness serves subscriptions, so invokeConnection is required\",\n );\n await withApp(options, env, async ({ app }) => {\n // The harness carries a bearer token of a connection in connectionParams, where graphql-ws clients put it.\n await subscriptionDenied(\n app,\n {\n cookie: env.identity.cookie,\n origin: UNTRUSTED_ORIGIN,\n authorization: \"Bearer a.b\",\n },\n \"a junk connectionParams bearer token\",\n { authorization: \"Bearer a.b\" },\n );\n });\n },\n subscriptions,\n );\n add(\"T-error-shape\", \"401, 403 and 429 carry code and reason\", (env) =>\n withApp(options, env, async ({ app }) => {\n const unauthenticated = await options.invoke(app, \"required\", {});\n denied(unauthenticated, 401);\n assert.equal(unauthenticated.error?.code, \"UNAUTHENTICATED\");\n const forbidden = await options.invoke(app, \"forbidden\", cookie(env));\n denied(forbidden, 403, \"CONFORMANCE_DENIED\");\n assert.equal(forbidden.error?.code, \"FORBIDDEN\");\n const limited = await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": env.keys.limited,\n });\n denied(limited, 429, \"RATE_LIMITED\");\n assert.equal(limited.error?.code, \"RATE_LIMITED\");\n const invalid = await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": \"unknown\",\n });\n denied(invalid, 401, \"INVALID_API_KEY\");\n }),\n );\n add(\"T-no-error-log\", \"denials are not logged at ERROR\", (env) =>\n withApp(options, env, async ({ app, logger }) => {\n await options.invoke(app, \"required\", {});\n await options.invoke(app, \"forbidden\", cookie(env));\n await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": env.keys.limited,\n });\n assert.deepEqual(\n logger.errors().map((entry) => entry.text.slice(0, 200)),\n [],\n );\n }),\n );\n add(\n \"T-infra-5xx\",\n \"a failing session store answers 5xx on protected handlers\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n env.probe.storageFault = () => new Error(\"conformance outage\");\n const result = await options.invoke(app, \"required\", cookie(env));\n env.probe.storageFault = undefined;\n internal(result);\n assert.notEqual(result.error?.statusCode, 401);\n assert.notEqual(result.error?.statusCode, 403);\n }),\n );\n add(\n \"T-internal-error-generic\",\n \"infrastructure and reader misconfiguration reach the client without detail\",\n async (env) => {\n await withApp(options, env, async ({ app, logger }) => {\n const secret = `outage-${globalThis.crypto.randomUUID()}`;\n env.probe.fault = (path) =>\n path === \"/get-session\" ? new Error(secret) : undefined;\n const result = await options.invoke(app, \"required\", cookie(env));\n internal(result);\n assert.ok(\n !JSON.stringify(result.error).includes(secret),\n \"the client saw the infrastructure detail\",\n );\n assert.ok(logger.errors().length > 0, \"nothing was logged at ERROR\");\n });\n env.probe.fault = undefined;\n await withApp(\n options,\n env,\n async ({ app, logger }) => {\n const result = await options.invoke(app, \"unguarded\", cookie(env));\n internal(result);\n const client = JSON.stringify(result.error ?? {});\n assert.ok(!client.includes(\"unguarded\"), `client saw ${client}`);\n assert.ok(!client.includes(\"stampPrincipal\"), `client saw ${client}`);\n assert.match(logger.text(), /NO_AUTH_RESULT/);\n },\n {\n override: (builder) =>\n overrideAuthGuard(builder, { canActivate: () => true }),\n },\n );\n },\n );\n add(\n \"T-internal-error-logged-once\",\n \"one failing logical request logs one ERROR entry for all its invocations\",\n async (env) =>\n (await twiceReady(env)) ??\n withApp(options, env, async ({ app, logger }) => {\n const shapes = (options.invocationShapes ?? []).filter(\n (shape) => shape === \"aliases\" || shape === \"batched\",\n );\n for (const shape of shapes) {\n const errors = logger.errors().length;\n env.probe.fault = (path) =>\n path === \"/get-session\"\n ? new Error(\"conformance outage\")\n : undefined;\n const results = await options.invokeTwice!(\n app,\n shape,\n [{ orgId: \"org-a\" }, { orgId: \"org-a2\" }],\n cookie(env),\n );\n env.probe.fault = undefined;\n assert.deepEqual(\n results.map((value) => value.ok),\n [false, false],\n );\n assert.equal(\n logger.errors().length - errors,\n 1,\n `${shape}: ${logger.errors().length - errors} ERROR entries for one request`,\n );\n }\n }),\n twiceSkip &&\n \"the transport has no lineage, so each error is logged once by construction\",\n );\n add(\n \"T-internal-error-logged-once\",\n \"reader configuration errors under 20 list items log one ERROR entry per request and distinct error, with field interceptors and with lineage alone\",\n async (env) => {\n const skip = await graphReady(env);\n if (skip) {\n return skip;\n }\n const apiKey = { \"x-api-key\": env.keys.valid };\n /** One `items` operation: asserts 20 failed `field` values and returns the ERROR entries it logged. */\n const items = async (\n app: INestApplication,\n logger: CapturingLogger,\n fields: readonly (keyof GraphFixtures[\"fields\"])[],\n headers: HeadersInit,\n label: string,\n ): Promise<string[]> => {\n const from = logger.errors().length;\n const result = await options.invokeGraph!(\n app,\n [{ root: \"items\", fields }],\n headers,\n );\n const list = (result.data as Record<string, unknown> | null)?.items as\n | readonly Record<string, unknown>[]\n | null\n | undefined;\n assert.equal(\n list?.length,\n ITEM_COUNT,\n `${label}: the items root did not return ${ITEM_COUNT} items: ${JSON.stringify(result).slice(0, 500)}`,\n );\n for (const field of fields) {\n const failed = result.errors.filter(\n (error) => error.path.at(-1) === field,\n );\n assert.equal(\n failed.length,\n ITEM_COUNT,\n `${label}: ${failed.length} ${field} errors instead of one per item: ${JSON.stringify(result.errors).slice(0, 500)}`,\n );\n assert.ok(\n list!.every((item) => item[field] === null),\n `${label}: a ${field} value resolved`,\n );\n for (const error of failed) {\n assert.ok(\n !/[A-Z]+_[A-Z_]+/.test(error.message ?? \"\"),\n `${label}: the client saw the configuration detail ${error.message}`,\n );\n }\n }\n assert.equal(\n result.errors.length,\n ITEM_COUNT * fields.length,\n `${label}: ${JSON.stringify(result.errors).slice(0, 500)}`,\n );\n return logger\n .errors()\n .slice(from)\n .map((entry) => entry.text);\n };\n const once = (entries: readonly string[], code: string, label: string) =>\n assert.ok(\n entries.length === 1 && entries[0]!.includes(code),\n `${label}: expected one ERROR entry with ${code}, got ${entries.length}: ${entries.join(\" | \").slice(0, 500)}`,\n );\n // Readers throw configuration errors that share the guard's surfaced-error record. [R6:NEST-r6-02] [R7:NEST-r7-02]\n for (const enhancers of [\n [\"guards\", \"interceptors\", \"filters\"],\n [\"guards\", \"filters\"],\n ] as const) {\n const scoped = enhancers.includes(\"interceptors\" as never);\n const boot = `[${enhancers.join(\", \")}]`;\n await withApp(\n options,\n env,\n async ({ app, logger }) => {\n // A second request logs again: the bound is per request, not per process.\n for (const round of [1, 2]) {\n const label = `${boot}, request ${round}`;\n once(\n await items(\n app,\n logger,\n [\"sessionReader\"],\n apiKey,\n `${label}: an API key's session readers`,\n ),\n \"SESSION_REQUIRED\",\n `${label}: an API key's session readers`,\n );\n once(\n await items(\n app,\n logger,\n [\"organizationReader\"],\n cookie(env),\n `${label}: organization readers without a providing requirement`,\n ),\n \"NO_INVOCATION_VALUE\",\n `${label}: organization readers without a providing requirement`,\n );\n const service = await items(\n app,\n logger,\n [\"serviceSession\"],\n apiKey,\n `${label}: service getSession() for an API key`,\n );\n // A field scope bounds service reads by the request; without one each fresh NO_AUTH_SCOPE is logged.\n const code = scoped ? \"SESSION_REQUIRED\" : \"NO_AUTH_SCOPE\";\n assert.equal(\n service.length,\n scoped ? 1 : ITEM_COUNT,\n `${label}: service getSession() logged ${service.length} ERROR entries`,\n );\n assert.ok(\n service.every((entry) => entry.includes(code)),\n `${label}: service getSession() did not log ${code}: ${service.join(\" | \").slice(0, 500)}`,\n );\n }\n // Distinct reasons of one request are not suppressed.\n const distinct = await items(\n app,\n logger,\n [\"sessionReader\", \"organizationReader\"],\n apiKey,\n `${boot}: session and organization readers together`,\n );\n assert.equal(\n distinct.length,\n 2,\n `${boot}: two reasons logged ${distinct.length} ERROR entries: ${distinct.join(\" | \").slice(0, 500)}`,\n );\n for (const code of [\"SESSION_REQUIRED\", \"NO_INVOCATION_VALUE\"]) {\n assert.ok(\n distinct.some((entry) => entry.includes(code)),\n `${boot}: ${code} was suppressed by another reason`,\n );\n }\n },\n {\n fieldResolverEnhancers: enhancers,\n fixtures: kitFixtures({}, [], { readerErrors: true }),\n },\n );\n // A guard that records no result leaves every nested reader without one. Without field interceptors such a\n // guard also records no lineage, so a reader has no request key to share and each fresh error is logged.\n if (!scoped) {\n continue;\n }\n await withApp(\n options,\n env,\n async ({ app, logger }) => {\n once(\n await items(\n app,\n logger,\n [\"reader\"],\n cookie(env),\n `${boot}: readers without an authentication result`,\n ),\n \"NO_AUTH_RESULT\",\n `${boot}: readers without an authentication result`,\n );\n },\n {\n fieldResolverEnhancers: enhancers,\n fixtures: kitFixtures({}, [], { readerErrors: true }),\n override: (builder) =>\n overrideAuthGuard(builder, { canActivate: () => true }),\n },\n );\n }\n },\n graphSkip,\n );\n add(\"T-public-no-lookup\", \"public handlers never read the session\", (env) =>\n withApp(options, env, async ({ app }) => {\n const from = env.probe.calls.length;\n succeeded(await options.invoke(app, \"public\", cookie(env)));\n assert.equal(sessionReads(env.probe, from), 0);\n }),\n );\n add(\n \"T-reads-session\",\n \"session readers return the session, mixed-kind service reads throw SESSION_REQUIRED, and mixed-kind boots fail PRINCIPAL_PARAM_CONFLICT\",\n async (env) => {\n await withApp(options, env, async ({ app, logger }) => {\n const result = await options.invoke(app, \"readsSession\", cookie(env));\n succeeded(result);\n assert.equal(\n (result.body as { userId?: string }).userId,\n env.identity.userId,\n );\n // Boot cannot see a service getSession() call in a mixed-kind handler: it warns, and the read throws.\n assert.ok(\n warningCodes(logger).has(\"W_MIXED_KIND_SESSION_READER\"),\n `boot did not warn W_MIXED_KIND_SESSION_READER: ${logger.text().slice(0, 500)}`,\n );\n const session = await options.invoke(\n app,\n \"readsSessionService\",\n cookie(env),\n );\n succeeded(session, \"a session caller of a mixed-kind getSession()\");\n assert.equal(\n (session.body as { userId?: string }).userId,\n env.identity.userId,\n );\n const key = await options.invoke(app, \"readsSessionService\", {\n \"x-api-key\": env.keys.valid,\n });\n internal(key);\n assert.match(logger.text(), /SESSION_REQUIRED/);\n });\n await expectBootFailure(\n options,\n env,\n {\n fixtures: kitFixtures({\n readsSession: [AcceptPrincipals(SESSION_KIND, API_KEY_KIND)],\n }),\n },\n \"PRINCIPAL_PARAM_CONFLICT\",\n );\n await expectBootFailure(\n options,\n env,\n { defaultRequirements: [sessionOrKey] },\n \"PRINCIPAL_PARAM_CONFLICT\",\n );\n },\n );\n add(\n \"T-scope\",\n \"param decorators and the service see the same reading\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const result = await options.invoke(app, \"readsSession\", cookie(env));\n succeeded(result);\n assert.deepEqual(result.body, {\n userId: env.identity.userId,\n service: env.identity.userId,\n });\n }),\n );\n add(\n \"T-carrier\",\n \"param decorators read the guard's reading with and without the scope interceptor, one value per invocation\",\n async (env) => {\n for (const globalScope of [true, false]) {\n const label = globalScope\n ? \"with the scope interceptor\"\n : \"with globalScope: false\";\n await withApp(\n options,\n env,\n async ({ app }) => {\n const byCookie = await options.invoke(app, \"required\", cookie(env));\n succeeded(byCookie, `${label}: a cookie`);\n assert.deepEqual(principalOf(byCookie), {\n kind: \"session\",\n userId: env.identity.userId,\n });\n const byKey = await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": env.keys.valid,\n });\n succeeded(byKey, `${label}: an API key`);\n assert.equal(principalOf(byKey)?.kind, \"api-key\", label);\n const org = await options.invoke(app, \"org\", cookie(env), {\n orgId: \"org-a\",\n });\n succeeded(org, `${label}: @ActiveOrganizationId()`);\n assert.deepEqual(org.body, { organization: \"org-a\" }, label);\n // The org fixture fails when @ActiveOrganizationId() answers another invocation's organization.\n for (const shape of options.invocationShapes ?? []) {\n const values = await options.invokeTwice!(\n app,\n shape,\n [{ orgId: \"org-a\" }, { orgId: \"org-a2\" }],\n cookie(env),\n );\n assert.deepEqual(\n values.map((value) => value.ok),\n [true, true],\n `${label}, ${shape}: ${JSON.stringify(values)}`,\n );\n }\n },\n globalScope ? {} : { globalScope: false },\n );\n }\n },\n );\n add(\n \"T-coverage-claims\",\n \"unguarded boots report exactly the claimed fixtures, and explicit enhancers, app enhancers, global stand-ins and globalScope: false boot\",\n async (env) => {\n let claims: RecordedClaim[] = [];\n const expected = new Map<string, string>();\n const defaults = new CapturingLogger();\n await withApp(\n options,\n env,\n async ({ app }) => {\n claims = await recordClaims(app, options.transport);\n const planner = app.get<RoutePlanner>(ROUTE_PLANNER, {\n strict: false,\n });\n for (const claim of claims) {\n if (\n !claim.fixture ||\n claim.method === undefined ||\n (claim.options.coverage ?? \"error\") !== \"error\"\n ) {\n continue;\n }\n const plan: RoutePlan = planner.plan(\n claim.target as Type,\n claim.method,\n );\n const accessCovered =\n (plan.access === \"public\" || plan.access === \"inherit\") &&\n plan.originCheck !== \"form\";\n if (\n !accessCovered &&\n (claim.options.everyHandler || plan.declares)\n ) {\n expected.set(claim.fixture, claim.options.code);\n }\n }\n },\n { logSummary: true },\n defaults,\n );\n assert.ok(\n claims.some((claim) => claim.fixture),\n \"the transport claimed none of the kit's fixture handlers\",\n );\n assert.match(\n summaryLine(defaults),\n /; scope: global;/,\n \"the default boot's summary does not report the global scope interceptor\",\n );\n // Boot 3: the bare fixtures fail with exactly the handlers B16 reports, each with its claim's code, and boot\n // when no claim calls for a report.\n const bare = await settle(() =>\n withApp(options, env, async () => undefined, { globalGuard: false }),\n );\n assert.equal(\n bare.ok,\n expected.size === 0,\n bare.ok\n ? `the bare fixtures booted, but the claims call for reports of ${JSON.stringify([...expected])}`\n : `no claim calls for a coverage report, but boot failed: ${String(bare.error)}`,\n );\n const issues = ((!bare.ok &&\n (bare.error as { issues?: unknown } | undefined)?.issues) ||\n []) as readonly { code?: string; detail?: string }[];\n const reported = new Map<string, string>();\n for (const claim of claims) {\n if (!claim.fixture || claim.method === undefined) {\n continue;\n }\n const site = `${claim.target.name}.${claim.method} `;\n const issue = issues.find((value) =>\n String(value.detail ?? \"\").startsWith(site),\n );\n if (issue?.code) {\n reported.set(claim.fixture, issue.code);\n }\n }\n assert.deepEqual(\n [...reported].sort(),\n [...expected].sort(),\n `B16 reported ${JSON.stringify([...reported])}, the claims call for ${JSON.stringify([...expected])}`,\n );\n if (\n claims.some(\n (claim) =>\n claim.fixture === \"loginProxy\" &&\n (claim.options.coverage ?? \"error\") === \"error\",\n )\n ) {\n assert.ok(\n reported.has(\"loginProxy\"),\n \"@Public() must not cover a form-mode forwarding handler\",\n );\n }\n for (const name of [\"public\", \"publicService\"]) {\n assert.ok(!reported.has(name), `${name} was reported`);\n }\n if (claims.some((claim) => claim.fixture && claim.reach === \"explicit\")) {\n await expectBootFailure(\n options,\n env,\n {\n globalGuard: false,\n fixtures: kitFixtures({}, [UseGuards(BetterAuthGuard)]),\n },\n \"AUTH_BOOT_FAILED\",\n );\n }\n await withApp(options, env, async () => undefined, {\n globalGuard: false,\n fixtures: kitFixtures({}, [UseBetterAuth()]),\n });\n const global = claims.some(\n (claim) => claim.fixture && claim.reach === \"global\",\n );\n if (global) {\n await withApp(options, env, async () => undefined, {\n globalGuard: false,\n appEnhancers: true,\n });\n }\n // Boot 4: a replaced global guard is still the global guard.\n const standIn = { canActivate: async () => true };\n await withApp(options, env, async () => undefined, {\n override: (builder) =>\n builder.overrideProvider(BetterAuthGuard).useValue(standIn),\n });\n class StandInGuard {\n canActivate(): boolean {\n return true;\n }\n }\n await withApp(options, env, async () => undefined, {\n override: (builder) =>\n builder.overrideProvider(BetterAuthGuard).useClass(StandInGuard),\n });\n if (global) {\n const unscoped = new CapturingLogger();\n await withApp(\n options,\n env,\n async () => undefined,\n { globalScope: false, logSummary: true },\n unscoped,\n );\n const added = [...warningCodes(unscoped)].filter(\n (code) => !warningCodes(defaults).has(code),\n );\n assert.deepEqual(\n added,\n [\"W_NO_GLOBAL_SCOPE\"],\n `globalScope: false must boot global claims with W_NO_GLOBAL_SCOPE only (pass the logger option to the app): ${unscoped.text().slice(0, 500)}`,\n );\n // The summary reports the missing interceptor too. [R6:SEC-r6-03]\n assert.match(\n summaryLine(unscoped),\n /; scope: off — see W_NO_GLOBAL_SCOPE;/,\n \"globalScope: false: the boot summary does not report scope: off\",\n );\n }\n },\n );\n add(\n \"T-metadata-canary\",\n \"validate() fails NEST_METADATA_KEY_CHANGED when Nest writes its metadata under other keys, and claims no class without handlers\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n // The boot ran the transport's canaries against the installed Nest.\n const claims = await recordClaims(app, options.transport);\n assert.ok(\n claims.some((claim) => claim.fixture),\n \"the transport claimed none of the kit's fixture handlers\",\n );\n const clones = [...new Set(claims.map((claim) => claim.target))].map(\n withoutHandlers,\n );\n const extra = await recordClaims(app, options.transport, {\n classes: clones,\n });\n assert.deepEqual(\n extra\n .filter((claim) => clones.includes(claim.target))\n .map((claim) => `${claim.target.name}.${String(claim.method)}`),\n [],\n \"the transport claimed a class without handlers\",\n );\n const renamed = await settle(() =>\n recordClaims(app, options.transport, { renameMetadata: true }),\n );\n assert.equal(\n renamed.ok,\n false,\n \"validate() passed while Nest wrote its metadata under other keys: the transport runs no metadata canary\",\n );\n assert.ok(\n bootIssueCodes(!renamed.ok && renamed.error).includes(\n \"NEST_METADATA_KEY_CHANGED\",\n ),\n `expected NEST_METADATA_KEY_CHANGED, got ${String(!renamed.ok && renamed.error)}`,\n );\n }),\n );\n add(\n \"T-unsatisfiable-kinds\",\n \"default requirements that admit no common kind fail boot unless skipped\",\n async (env) => {\n await expectBootFailure(\n options,\n env,\n {\n defaultRequirements: [sessionOnly],\n fixtures: kitFixtures({ acceptsApiKey: [Require(apiKeyOnly)] }),\n },\n \"UNSATISFIABLE_PRINCIPAL_KINDS\",\n );\n await expectBootFailure(\n options,\n env,\n {\n defaultRequirements: [unnamedKinds],\n fixtures: kitFixtures({ acceptsApiKey: [Require(apiKeyOnly)] }),\n },\n \"UNSATISFIABLE_PRINCIPAL_KINDS\",\n );\n await withApp(\n options,\n env,\n async ({ app }) => {\n const result = await options.invoke(app, \"acceptsApiKey\", {\n \"x-api-key\": env.keys.valid,\n });\n succeeded(result);\n assert.equal(principalOf(result)?.kind, \"api-key\");\n },\n {\n defaultRequirements: [sessionOnly],\n fixtures: kitFixtures({\n acceptsApiKey: [Require(apiKeyOnly), SkipDefaultRequirements()],\n }),\n },\n );\n },\n );\n add(\n \"T-public-service-null\",\n \"a public unsafe handler's service reads null without a session read\",\n (env) =>\n withApp(options, env, async ({ app }) => {\n const from = env.probe.calls.length;\n const result = await options.invoke(app, \"publicService\", {\n ...cookie(env),\n origin: UNTRUSTED_ORIGIN,\n });\n succeeded(result);\n assert.deepEqual(result.body, { session: null });\n assert.equal(sessionReads(env.probe, from), 0);\n }),\n );\n addRun(\n \"T-dynamic-base-url\",\n \"with a dynamic baseURL without fallback, a transport with hostless calls fails boot and any other resolves every credential shape\",\n async () => {\n let hostless = false;\n await withApp(\n options,\n await kitEnvironment({ baseURL: dynamicBaseURL }),\n async ({ app }) => {\n hostless =\n resolvedTransport(app, options.transport).requires\n ?.hostlessCalls === true;\n },\n );\n const env = await kitEnvironment({ baseURL: { allowedHosts: [host] } });\n if (hostless) {\n await expectBootFailure(\n options,\n env,\n {},\n \"DYNAMIC_BASE_URL_WITHOUT_FALLBACK\",\n );\n return;\n }\n await withApp(options, env, async ({ app }) => {\n for (const [handler, headers, kind] of [\n [\"required\", cookie(env), \"session\"],\n [\n \"required\",\n { authorization: `Bearer ${env.identity.token}` },\n \"session\",\n ],\n [\"acceptsApiKey\", { \"x-api-key\": env.keys.valid }, \"api-key\"],\n ] as const) {\n const result = await options.invoke(app, handler, {\n ...headers,\n host,\n });\n succeeded(result, `a ${kind} credential (${Object.keys(headers)})`);\n assert.deepEqual(principalOf(result), {\n kind,\n userId: env.identity.userId,\n });\n }\n });\n },\n );\n add(\n \"T-public-direct-invalid-context\",\n \"public work runs without extraction; guarded and forwarding work fails closed before side effects\",\n async (env) => {\n const user = await kitIdentity(env.auth, { password: true });\n await withApp(options, env, async ({ app, instrumentation }) => {\n instrumentation.consumed.length = 0;\n succeeded(await options.invoke(app, \"public\", cookie(env)));\n succeeded(await options.invoke(app, \"publicService\", cookie(env)));\n assert.deepEqual(\n instrumentation.consumed,\n [],\n \"public scope construction consumed request-dependent capabilities\",\n );\n instrumentation.unavailable = true;\n succeeded(await options.invoke(app, \"public\", cookie(env)));\n const guarded = await options.invoke(app, \"required\", cookie(env));\n internal(guarded);\n const signIns = env.probe.calls.filter(\n (path) => path === \"/sign-in/email\",\n ).length;\n const proxy = await options.invoke(\n app,\n \"loginProxy\",\n { origin: KIT_BASE_URL },\n { email: user.email, password: user.password },\n );\n internal(proxy);\n assert.deepEqual(proxy.setCookies, []);\n assert.equal(\n env.probe.calls.filter((path) => path === \"/sign-in/email\").length,\n signIns,\n \"a forwarding handler reached Better Auth without extraction\",\n );\n });\n },\n );\n const noInherited =\n \"the harness exposes no inherited handler through two subclasses (invokeInherited)\";\n addRun(\n \"T-inherited-handler\",\n \"one inherited method answers per subclass, public then protected and the other way round\",\n async () => {\n for (const order of [\n [\"public\", \"denied\"],\n [\"denied\", \"public\"],\n ] as const) {\n // A fresh boot per order: the first request of a boot fills the plan cache.\n const env = await kitEnvironment();\n await withApp(options, env, async ({ app }) => {\n for (let round = 0; round < 2; round++) {\n for (const subclass of order) {\n const label = `${order.join(\" first, then \")}, round ${round + 1}: the ${subclass} subclass`;\n const result = await options.invokeInherited!(\n app,\n subclass,\n cookie(env),\n );\n if (subclass === \"public\") {\n succeeded(result, label);\n } else {\n denied(result, 403, \"CONFORMANCE_DENIED\", label);\n }\n }\n }\n });\n }\n },\n options.invokeInherited ? undefined : noInherited,\n );\n addRun(\n \"T-stale-context\",\n \"a static GraphQL context fails boot, and a cached one never answers a later caller with an earlier caller's principal\",\n async () => {\n const env = await kitEnvironment();\n if (!(await transportHas(options, env, \"defaultAccessFor\"))) {\n return conformanceSkip(\n \"the transport nests no handlers, so it serves no GraphQL context\",\n );\n }\n const contexts = options.graphqlContexts ?? [];\n assert.ok(\n contexts.includes(\"static\") && contexts.includes(\"cached\"),\n \"the transport nests handlers, so graphqlContexts must include 'static' and 'cached'\",\n );\n await expectBootFailure(\n options,\n env,\n { graphqlContext: \"static\" },\n \"GRAPHQL_STATIC_CONTEXT\",\n );\n // The first caller finishes before a later caller runs: its request completes, or, where the browser leg is the\n // connection's handshake, its connection closes; invokeConnection resolves after the server observed the close.\n const connection = await connectionLeg();\n assert.ok(\n !connection || options.invokeConnection,\n \"the transport's browser leg is its connection's handshake, so invokeConnection is required\",\n );\n const invokeAlone = async (\n app: INestApplication,\n handler: \"required\" | \"optional\" | \"public\" | \"publicService\",\n headers: HeadersInit,\n ): Promise<TransportInvocationResult> =>\n connection\n ? (await options.invokeConnection!(app, [handler], headers))[0]!\n : options.invoke(app, handler, headers);\n const later = await kitIdentity(env.auth);\n const laterCookie = { ...cookie(env), cookie: later.cookie };\n await withApp(\n options,\n env,\n async ({ app, logger }) => {\n const first = await invokeAlone(app, \"required\", cookie(env));\n succeeded(first, \"the first caller of a cached context\");\n assert.equal(principalOf(first)?.userId, env.identity.userId);\n for (const handler of [\"required\", \"optional\"] as const) {\n const result = await invokeAlone(app, handler, laterCookie);\n const label = `a later caller of ${handler}`;\n if (connection) {\n // A connection that is closed when an operation starts lends it no credential: the operation runs\n // anonymously, or with the later caller's own principal where the driver rebuilds its context.\n assert.notEqual(\n principalOf(result)?.userId,\n env.identity.userId,\n `${label} read the first caller's principal`,\n );\n if (result.ok) {\n const principal = principalOf(result);\n assert.ok(\n principal === null || principal?.userId === later.userId,\n `${label} read neither its own principal nor none: ${JSON.stringify(result.body)}`,\n );\n } else {\n denied(result, 401, undefined, label);\n }\n continue;\n }\n // A driver that rebuilds its context around the cached object answers with the later caller's own principal.\n if (result.ok) {\n assert.equal(\n principalOf(result)?.userId,\n later.userId,\n `${label} did not read its own principal`,\n );\n } else {\n internal(result, label);\n assert.match(logger.text(), /GRAPHQL_CONTEXT_STALE_REQUEST/);\n }\n }\n // Public work reads no credential of the completed request or closed connection.\n succeeded(\n await invokeAlone(app, \"public\", laterCookie),\n \"a later caller of a public handler\",\n );\n const service = await invokeAlone(app, \"publicService\", laterCookie);\n succeeded(service, \"a later caller of a public service read\");\n assert.deepEqual(service.body, { session: null });\n if (connection) {\n // A closed connection is an ordinary client outcome, not a configuration error.\n assert.deepEqual(\n logger.errors().map((entry) => entry.text.slice(0, 200)),\n [],\n \"a later caller of a closed connection's context logged at ERROR\",\n );\n assert.doesNotMatch(\n logger.text(),\n /AUTH_MISCONFIGURED|GRAPHQL_CONTEXT_STALE_REQUEST/,\n );\n }\n },\n { graphqlContext: \"cached\" },\n );\n },\n );\n /** The claimed site of each graph fixture handler of a booted app, by fixture name. */\n const graphSites = async (app: INestApplication) => {\n const sites = new Map<string, { target: Type; method: string }>();\n for (const claim of await recordClaims(app, options.transport)) {\n if (claim.fixture?.startsWith(\"graph.\") && claim.method !== undefined) {\n sites.set(claim.fixture.slice(\"graph.\".length), {\n target: claim.target as Type,\n method: claim.method,\n });\n }\n }\n return sites;\n };\n const graphSite = (\n sites: Map<string, { target: Type; method: string }>,\n name: string,\n ) => {\n const site = sites.get(name);\n assert.ok(site, `the transport claimed no ${name} graph handler`);\n return site;\n };\n const planAt = (\n app: INestApplication,\n site: { target: Type; method: string },\n ): RoutePlan =>\n app\n .get<RoutePlanner>(ROUTE_PLANNER, { strict: false })\n .plan(site.target, site.method);\n /** The boot advice lines a logger captured for one code. */\n const adviceLines = (logger: CapturingLogger, code: string) =>\n logger.entries\n .map((entry) => entry.text)\n .filter((text) => text.startsWith(`${code}:`));\n add(\n \"T-inherit-no-lookup\",\n \"an anonymous public operation with an inheriting field reads no session, a guarded field is still enforced, and class-level metadata reaches operations only\",\n async (env) => {\n const skip = await graphReady(env);\n if (skip) {\n return skip;\n }\n for (const enhancers of enhancerBoots) {\n const guarded = enhancers.length > 0;\n const logger = new CapturingLogger();\n await withApp(\n options,\n env,\n async ({ app }) => {\n const from = env.probe.calls.length;\n const result = await options.invokeGraph!(\n app,\n [{ root: \"public\", fields: [\"plain\"] }],\n {},\n );\n assert.deepEqual(\n result.errors,\n [],\n `[${enhancers.join(\", \")}]: ${JSON.stringify(result.errors)}`,\n );\n assert.equal(\n sessionReads(env.probe, from),\n 0,\n `[${enhancers.join(\", \")}]: an inheriting field read the session`,\n );\n if (guarded) {\n const field = await options.invokeGraph!(\n app,\n [{ root: \"public\", fields: [\"guarded\"] }],\n {},\n );\n assert.ok(\n field.errors.length > 0 &&\n field.errors.every(\n (error) => error.code === \"UNAUTHENTICATED\",\n ),\n `a guarded field under a public root was not denied: ${JSON.stringify(field.errors)}`,\n );\n }\n const sites = await graphSites(app);\n const [warning] = adviceLines(logger, \"W_FIELD_RESOLVER_INHERITS\");\n assert.ok(\n warning,\n `[${enhancers.join(\", \")}]: boot did not warn W_FIELD_RESOLVER_INHERITS`,\n );\n const inheriting = warning.slice(\n 0,\n warning.indexOf(\" inherit readings\"),\n );\n for (const field of [\"plain\", \"reader\"]) {\n const site = graphSite(sites, field);\n assert.ok(\n inheriting.includes(`${site.target.name}.${site.method}`),\n `W_FIELD_RESOLVER_INHERITS does not list ${field}: ${warning}`,\n );\n }\n },\n {\n fieldResolverEnhancers: enhancers,\n fixtures: kitFixtures({}, [], { guarded }),\n },\n logger,\n );\n }\n // Class-level acceptance reaches the operations of the resolver class, never its field resolvers. [R3:NEST-r3-05]\n for (const enhancers of enhancerBoots) {\n const logger = new CapturingLogger();\n const label = `class-level @AcceptPrincipals, [${enhancers.join(\", \")}]`;\n await withApp(\n options,\n env,\n async ({ app }) => {\n const sites = await graphSites(app);\n for (const field of [\"plain\", \"reader\", \"sessionReader\"]) {\n assert.equal(\n planAt(app, graphSite(sites, field)).access,\n \"inherit\",\n `${label}: the ${field} field resolver lost its inherit plan`,\n );\n }\n const root = graphSite(sites, \"sessionOnly\");\n assert.deepEqual(\n [...planAt(app, root).accepts].sort(),\n [API_KEY_KIND, SESSION_KIND],\n `${label}: the class-level acceptance did not reach the root field`,\n );\n const from = env.probe.calls.length;\n const result = await options.invokeGraph!(\n app,\n [{ root: \"public\", fields: [\"plain\", \"reader\"] }],\n {},\n );\n assert.deepEqual(\n result.errors,\n [],\n `${label}: ${JSON.stringify(result.errors)}`,\n );\n assert.equal(sessionReads(env.probe, from), 0, label);\n const [info] = adviceLines(\n logger,\n \"I_CLASS_METADATA_OPERATIONS_ONLY\",\n );\n assert.ok(\n info?.includes(root.target.name),\n `${label}: I_CLASS_METADATA_OPERATIONS_ONLY does not name ${root.target.name}: ${info}`,\n );\n for (const field of [\"plain\", \"reader\"]) {\n assert.ok(\n info.includes(graphSite(sites, field).method),\n `${label}: I_CLASS_METADATA_OPERATIONS_ONLY does not name the ${field} field: ${info}`,\n );\n }\n },\n {\n fieldResolverEnhancers: enhancers,\n fixtures: kitFixtures({}, [], {\n guarded: enhancers.length > 0,\n classDecorators: [AcceptPrincipals(SESSION_KIND, API_KEY_KIND)],\n }),\n },\n logger,\n );\n }\n },\n graphSkip,\n );\n add(\n \"T-stamp-per-plan\",\n \"a nested reader reads its own enclosing field's reading, whichever source settles first\",\n async (env) => {\n const skip = await graphReady(env);\n if (skip) {\n return skip;\n }\n // User Y's cookie and user X's key in one operation.\n env.keys.owner = (await kitIdentity(env.auth)).userId;\n const userY = env.identity.userId;\n const headers = { ...cookie(env), \"x-api-key\": env.keys.valid };\n for (const enhancers of enhancerBoots) {\n const guarded = enhancers.length > 0;\n const logger = new CapturingLogger();\n await withApp(\n options,\n env,\n async ({ app }) => {\n for (const delays of [\n { session: 0, apiKey: 30 },\n { session: 30, apiKey: 0 },\n ]) {\n env.probe.delay = (path) =>\n path === \"/get-session\" ? delays.session : undefined;\n env.keys.delayMs = delays.apiKey;\n const label = `[${enhancers.join(\", \")}] session ${delays.session} ms, key ${delays.apiKey} ms`;\n try {\n const result = await options.invokeGraph!(\n app,\n [\n { root: \"sessionOnly\", fields: [\"reader\", \"publicNested\"] },\n {\n root: \"mixed\",\n fields: guarded ? [\"reader\", \"guarded\"] : [\"reader\"],\n },\n { root: \"public\", fields: [\"reader\"] },\n ],\n headers,\n { delays },\n );\n assert.ok(\n result.errors.every(\n (error) => error.reason !== \"NO_AUTH_RESULT\",\n ),\n `${label}: ${JSON.stringify(result.errors)}`,\n );\n assert.deepEqual(\n result.errors,\n [],\n `${label}: ${JSON.stringify(result.errors)}`,\n );\n assert.equal(\n userOf(graphOf(result, \"sessionOnly\", \"reader\")),\n userY,\n `${label}: reader under sessionOnly`,\n );\n assert.equal(\n userOf(\n (\n graphOf(result, \"sessionOnly\", \"publicNested\") as {\n reader?: unknown;\n } | null\n )?.reader,\n ),\n userY,\n `${label}: reader under publicNested under sessionOnly`,\n );\n assert.equal(\n userOf(graphOf(result, \"mixed\", \"reader\")),\n userOf(graphOf(result, \"mixed\")),\n `${label}: reader under mixed must read mixed's own principal`,\n );\n assert.equal(\n userOf(graphOf(result, \"public\", \"reader\")),\n null,\n `${label}: reader under public`,\n );\n if (guarded) {\n const node = graphOf(result, \"mixed\", \"guarded\") as {\n principal?: { userId?: string };\n nestedReader?: unknown;\n } | null;\n assert.equal(\n node?.principal?.userId,\n userY,\n `${label}: guarded under mixed accepts sessions only`,\n );\n assert.equal(\n userOf(node?.nestedReader),\n userY,\n `${label}: nestedReader under guarded must read guarded's own principal`,\n );\n }\n } finally {\n env.probe.delay = undefined;\n env.keys.delayMs = 0;\n }\n }\n const alone = await options.invokeGraph!(\n app,\n [{ root: \"public\", fields: [\"reader\"] }],\n headers,\n );\n assert.deepEqual(alone.errors, [], JSON.stringify(alone.errors));\n assert.equal(\n userOf(graphOf(alone, \"public\", \"reader\")),\n null,\n \"reader under a public root without a guarded sibling\",\n );\n // A nested session reader under a root that accepts API keys. [R5:NEST-r5-03]\n const sessionReader: GraphSelection[] = [\n { root: \"mixed\", fields: [\"sessionReader\"] },\n ];\n const bySession = await options.invokeGraph!(\n app,\n sessionReader,\n cookie(env),\n );\n assert.deepEqual(\n bySession.errors,\n [],\n JSON.stringify(bySession.errors),\n );\n assert.equal(graphOf(bySession, \"mixed\", \"sessionReader\"), userY);\n const byKey = await options.invokeGraph!(app, sessionReader, {\n \"x-api-key\": env.keys.valid,\n });\n assert.ok(\n byKey.errors.length === 1 &&\n byKey.errors[0]!.path.includes(\"sessionReader\"),\n `an API key's nested session read did not fail at the field: ${JSON.stringify(byKey)}`,\n );\n assert.equal(graphOf(byKey, \"mixed\", \"sessionReader\"), null);\n assert.match(logger.text(), /SESSION_REQUIRED/);\n const sessionSite = graphSite(\n await graphSites(app),\n \"sessionReader\",\n );\n assert.ok(\n adviceLines(logger, \"W_NESTED_PRINCIPAL_PARAM\").some((line) =>\n line.includes(\n `${sessionSite.target.name}.${sessionSite.method}`,\n ),\n ),\n \"boot did not list sessionReader in W_NESTED_PRINCIPAL_PARAM\",\n );\n },\n {\n fieldResolverEnhancers: enhancers,\n fixtures: kitFixtures({}, [], { guarded }),\n },\n logger,\n );\n }\n // Instance-wide forwarding puts publicNested in form mode; the reading below it stays the root's. [R5:NEST-r5-05]\n for (const enhancers of enhancerBoots) {\n await withApp(\n options,\n env,\n async ({ app }) => {\n const result = await options.invokeGraph!(\n app,\n [{ root: \"sessionOnly\", fields: [\"publicNested\"] }],\n { ...cookie(env), origin: KIT_BASE_URL },\n );\n const label = `cookies.forwardDirectCalls, [${enhancers.join(\", \")}]`;\n assert.deepEqual(\n result.errors,\n [],\n `${label}: ${JSON.stringify(result.errors)}`,\n );\n assert.equal(\n userOf(\n (\n graphOf(result, \"sessionOnly\", \"publicNested\") as {\n reader?: unknown;\n } | null\n )?.reader,\n ),\n userY,\n `${label}: reader under publicNested under sessionOnly`,\n );\n },\n {\n fieldResolverEnhancers: enhancers,\n forwardDirectCalls: true,\n fieldResolverCoverage: \"warn\",\n fixtures: kitFixtures(),\n },\n );\n }\n },\n graphSkip,\n );\n const federation = (graph: GraphBoot = {}): BootOptions => ({\n federation: true,\n fieldResolverEnhancers: [\"guards\", \"interceptors\"],\n fixtures: kitFixtures({}, [], { guarded: true, reference: true, ...graph }),\n });\n add(\n \"T-reference-resolver\",\n \"federation reference resolvers need field guards and decide each entity, and inheriting entity fields need one\",\n async (env) => {\n if (!options.invokeEntities) {\n if (!(await transportHas(options, env, \"defaultAccessFor\"))) {\n return conformanceSkip(\n \"the transport nests no handlers, so it serves no federation reference resolvers\",\n );\n }\n let claimed = false;\n await withApp(\n options,\n env,\n async ({ app }) => {\n claimed = (await recordClaims(app, options.transport)).some(\n (claim) => claim.fixture === \"reference\",\n );\n },\n federation(),\n );\n assert.equal(\n claimed,\n false,\n \"the transport claims the federation reference resolver, so invokeEntities is required\",\n );\n return conformanceSkip(\n \"the transport claims no reference resolver and gives no invokeEntities\",\n );\n }\n await expectBootFailure(\n options,\n env,\n { ...federation(), fieldResolverEnhancers: undefined },\n [\"REFERENCE_RESOLVER_UNGUARDED\", \"FEDERATION_FIELD_GUARDS_REQUIRED\"],\n );\n const representations = [\n { __typename: \"FixtureNode\", id: \"1\", orgId: \"org-a\" },\n { __typename: \"FixtureNode\", id: \"2\", orgId: \"org-b\" },\n ];\n await withApp(\n options,\n env,\n async ({ app }) => {\n const anonymous = await options.invokeEntities!(\n app,\n representations,\n [\"plain\"],\n {},\n );\n assert.ok(\n anonymous.errors.length >= 2 &&\n anonymous.errors.every(\n (error) => error.code === \"UNAUTHENTICATED\",\n ),\n JSON.stringify(anonymous.errors),\n );\n const decided = await options.invokeEntities!(\n app,\n representations,\n [\"plain\", \"reader\"],\n cookie(env),\n );\n assert.equal(\n decided.errors.length,\n 1,\n `two representations were not decided independently: ${JSON.stringify(decided.errors)}`,\n );\n assert.equal(decided.errors[0]!.reason, \"MISSING_PERMISSION\");\n assert.ok(\n decided.errors[0]!.path.includes(1),\n JSON.stringify(decided.errors),\n );\n const [entity] =\n (decided.data as { _entities?: unknown[] } | null)?._entities ?? [];\n assert.equal(\n userOf((entity as { reader?: unknown } | undefined)?.reader),\n env.identity.userId,\n `reader under _entities.0 must read the reference resolver's reading: ${JSON.stringify(decided.data)}`,\n );\n },\n federation(),\n );\n // Without a reference resolver no guard decides the entity, so its inheriting fields answer the generic 500 of\n // NO_ENCLOSING_DECISION.\n await withApp(\n options,\n env,\n async ({ app }) => {\n const result = await options.invokeEntities!(\n app,\n representations.slice(0, 1),\n [\"plain\", \"reader\"],\n cookie(env),\n );\n const [entity] = ((result.data as { _entities?: unknown[] } | null)\n ?._entities ?? []) as ({\n plain?: unknown;\n reader?: unknown;\n } | null)[];\n assert.ok(\n entity?.plain == null && entity?.reader == null,\n `an entity without a reference resolver answered data: ${JSON.stringify(result.data)}`,\n );\n for (const field of [\"plain\", \"reader\"]) {\n assert.ok(\n result.errors.some(\n (error) =>\n error.path.includes(field) &&\n error.code !== \"UNAUTHENTICATED\" &&\n error.code !== \"FORBIDDEN\",\n ),\n `${field} did not answer the generic internal error: ${JSON.stringify(result.errors)}`,\n );\n }\n },\n federation({ reference: false }),\n );\n // A class-level organization requirement reaches the reference resolver, whose representation carries orgId.\n // [R5:NEST-r5-02]\n const orgEnv = await kitEnvironment({ plugins: [organization()] });\n const member = await createKitOrganization(orgEnv);\n await withApp(\n options,\n orgEnv,\n async ({ app, logger }) => {\n const reference = (await recordClaims(app, options.transport)).find(\n (claim) => claim.fixture === \"reference\",\n );\n assert.ok(reference, \"the transport claimed no reference resolver\");\n const site = `${reference.target.name}.${String(reference.method)}`;\n assert.ok(\n adviceLines(logger, \"W_ORG_PARAM_MISSING\").some((line) =>\n line.includes(site),\n ),\n `boot did not name ${site} in W_ORG_PARAM_MISSING: ${logger.text().slice(0, 800)}`,\n );\n const [info] = adviceLines(\n logger,\n \"I_CLASS_METADATA_OPERATIONS_ONLY\",\n );\n assert.ok(\n info?.includes(reference.target.name) &&\n info.includes(String(reference.method)),\n `I_CLASS_METADATA_OPERATIONS_ONLY does not name ${site} as reached: ${info}`,\n );\n const decided = await options.invokeEntities!(\n app,\n [\n { __typename: \"FixtureNode\", id: \"1\", orgId: member },\n { __typename: \"FixtureNode\", id: \"2\", orgId: \"org-b\" },\n ],\n [\"plain\"],\n cookie(orgEnv),\n );\n assert.equal(\n decided.errors.length,\n 1,\n `the class-level requirement did not decide each representation: ${JSON.stringify(decided.errors)}`,\n );\n assert.equal(decided.errors[0]!.code, \"FORBIDDEN\");\n assert.ok(\n decided.errors[0]!.path.includes(1),\n JSON.stringify(decided.errors),\n );\n const own = await options.invokeGraph!(\n app,\n [{ root: \"public\", fields: [\"plain\"] }],\n {},\n );\n assert.deepEqual(\n own.errors,\n [],\n `the class's own public query failed: ${JSON.stringify(own.errors)}`,\n );\n },\n federation({\n reference: \"bare\",\n classDecorators: [\n Require(\n orgPermission(\n { member: [\"create\"] },\n { organization: fromParam(\"orgId\") },\n ),\n ),\n ],\n }),\n );\n },\n staticMember(options.transport, \"defaultAccessFor\") === false &&\n !options.invokeEntities\n ? \"the transport nests no handlers, so it serves no federation reference resolvers\"\n : undefined,\n );\n return cases;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,0BACd,YACA,cACiD;CACjD,SAAS,UAAwC,QAAW;EAC1D,MAAM,SAAS,OACb,GAAG,CAAC,MAAM,SACmC;GAC7C,MAAM,UAAU,WAAW;GAC3B,IAAI,CAAC,SAAS;IACZ,aAAa;IACb;GACF;GACA,MAAM,QAAQ,QAAQ,SAAS,OAAO,CAAC;GACvC,IAAI,cAAuC,CAAC;GAC5C,IAAI,UAAU;GACd,KAAK,MAAM,QAAQ,OAAO;IACxB,MAAM,SAAS,MAAM,KAClB,OAAO,SAAS,SAAS,IACtB;KAAE,GAAG;KAAM,GAAG;IAAY,IAC1B,MACJ,GACF;IACA,IAAI,WAAW,OACb,OAAO;IAET,IACE,CAAC,OAAO,SAAS,SAAS,KAC1B,UACA,OAAO,WAAW,YAClB,UAAU,QACV;KACA,cAAc;MAAE,GAAG;MAAa,GAAG,OAAO;KAAK;KAC/C,UAAU;IACZ;GACF;GAGA,OACE,UAAU,EAAE,MAAM,YAAY,IAAI,KAAA;EAEtC;EACA,MAAM,QAAQ,OACZ,GAAG,CAAC,MAAM,SACQ;GAClB,MAAM,UAAU,WAAW;GAC3B,IAAI,CAAC,SAAS;IACZ,aAAa;I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