@classytic/arc 2.49.0 → 2.51.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 (159) hide show
  1. package/dist/{EventTransport-DbHZK230.mjs → EventTransport-K7Q9WPjm.mjs} +2 -2
  2. package/dist/{HookSystem-DMoeJ6Do.mjs → HookSystem-DBAu9uNT.mjs} +2 -2
  3. package/dist/{ResourceRegistry-CP-iTcKy.mjs → ResourceRegistry-BelzCRMy.mjs} +2 -2
  4. package/dist/{acquire-CB0va87C.mjs → acquire-B0zhfGSm.mjs} +1 -1
  5. package/dist/audit/index.mjs +4 -4
  6. package/dist/auth/audit.mjs +1 -1
  7. package/dist/auth/index.d.mts +30 -0
  8. package/dist/auth/index.mjs +172 -32
  9. package/dist/auth/redis-session.mjs +1 -1
  10. package/dist/auth/social/index.d.mts +42 -0
  11. package/dist/auth/social/index.mjs +311 -0
  12. package/dist/{authorizationDecision-DHO94aV2.mjs → authorizationDecision-Dxj_cy6N.mjs} +4 -4
  13. package/dist/{boundedMap-C51EUUOm.mjs → boundedMap-DOBai-H3.mjs} +1 -1
  14. package/dist/{buildHandler-9DuwEKvr.mjs → buildHandler-Dyl8P9j0.mjs} +5 -5
  15. package/dist/cache/index.mjs +4 -4
  16. package/dist/{caching-COTX3sDa.mjs → caching-CUmaNL8Y.mjs} +2 -2
  17. package/dist/{claimed-C7T1nHlo.mjs → claimed-DJPk4VZr.mjs} +1 -1
  18. package/dist/cleanup/index.mjs +4 -4
  19. package/dist/cli/commands/describe.mjs +3 -3
  20. package/dist/cli/commands/docs.mjs +3 -3
  21. package/dist/cli/commands/doctor.mjs +1 -1
  22. package/dist/cli/commands/generate.mjs +2 -2
  23. package/dist/cli/commands/init.mjs +2 -2
  24. package/dist/cli/commands/introspect.mjs +2 -2
  25. package/dist/cli/index.mjs +3 -3
  26. package/dist/{constants-DOnfMd7i.mjs → constants-DH41jnNT.mjs} +1 -1
  27. package/dist/context/index.mjs +5 -5
  28. package/dist/core/index.mjs +7 -7
  29. package/dist/{core-BoEdFDDw.mjs → core-DPmRWlpx.mjs} +3 -3
  30. package/dist/{createActionRouter-CpTn15dm.mjs → createActionRouter-B1xhER6i.mjs} +5 -5
  31. package/dist/{createAggregationRouter-CD_Hydp0.mjs → createAggregationRouter-CNntJL-z.mjs} +7 -7
  32. package/dist/{createApp-Be6XTGD9.mjs → createApp-DpG26bCu.mjs} +29 -29
  33. package/dist/{defineAggregation-BI5pRb8c.mjs → defineAggregation-rI3EbZUg.mjs} +1 -1
  34. package/dist/{defineResource-BAzNu5Um.mjs → defineResource-5DcG_wlI.mjs} +8 -8
  35. package/dist/discovery/index.mjs +1 -1
  36. package/dist/docs/index.mjs +3 -3
  37. package/dist/{elevation-DupGuM41.mjs → elevation-XFu7J3aj.mjs} +5 -5
  38. package/dist/encryption/index.mjs +3 -3
  39. package/dist/{errorHandler-DA03vRqp.mjs → errorHandler-xDVUWOMu.mjs} +3 -3
  40. package/dist/{errors-BpYV859Y.mjs → errors-KBZ3tQk5.mjs} +1 -1
  41. package/dist/{eventPlugin-D7LYtYzL.mjs → eventPlugin-C4lNj2Dw.mjs} +8 -8
  42. package/dist/{eventTypes-BqA-N-Uz.mjs → eventTypes-DZRoUAdk.mjs} +2 -2
  43. package/dist/events/index.mjs +8 -8
  44. package/dist/events/transports/redis-stream-entry.mjs +4 -4
  45. package/dist/events/transports/redis.mjs +2 -2
  46. package/dist/factory/index.mjs +6 -6
  47. package/dist/{fieldTypes-EFWxCkZ5.mjs → fieldTypes-DrXUW1jc.mjs} +2 -2
  48. package/dist/{fields-CT1Erg7o.mjs → fields-C5J8WTd2.mjs} +1 -1
  49. package/dist/{filter-merge-B1eJ1pMx.mjs → filter-merge-DTjYoDrj.mjs} +1 -1
  50. package/dist/{generate-Cr0ULavs.mjs → generate-SA8oMlLB.mjs} +2 -2
  51. package/dist/{headers-D4bncIOf.mjs → headers-D5wrBLOk.mjs} +2 -2
  52. package/dist/{health-DN_pUVMX.mjs → health-BLal039H.mjs} +1 -1
  53. package/dist/{health-BoFxrkJE.mjs → health-vEo3fni4.mjs} +1 -1
  54. package/dist/hooks/index.mjs +2 -2
  55. package/dist/http-cache/index.mjs +4 -4
  56. package/dist/http-cache/purgers/cloudflare.mjs +2 -2
  57. package/dist/http-cache/purgers/fastly.mjs +2 -2
  58. package/dist/http-cache/testing/index.mjs +1 -1
  59. package/dist/idempotency/index.mjs +7 -7
  60. package/dist/idempotency/redis.mjs +2 -2
  61. package/dist/index.mjs +11 -11
  62. package/dist/{init-C4a24wD2.mjs → init-DeKHaNZn.mjs} +22 -22
  63. package/dist/integrations/event-gateway.mjs +2 -2
  64. package/dist/integrations/index.mjs +1 -1
  65. package/dist/integrations/jobs/index.mjs +3 -3
  66. package/dist/integrations/mcp/index.mjs +2 -2
  67. package/dist/integrations/mcp/testing.mjs +2 -2
  68. package/dist/integrations/streamline.mjs +3 -3
  69. package/dist/integrations/webhooks.mjs +4 -4
  70. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  71. package/dist/integrations/websocket-redis.mjs +1 -1
  72. package/dist/integrations/websocket.mjs +2 -2
  73. package/dist/{jsonBody-DoTt5BS6.mjs → jsonBody-rDPGT5A9.mjs} +2 -2
  74. package/dist/{keys--l9n7aOC.mjs → keys-t7i-lJ2r.mjs} +1 -1
  75. package/dist/{loadResources-rygByIQA.mjs → loadResources-CcupAVJH.mjs} +3 -3
  76. package/dist/{loadResourcesFromEntry-ItNBIQ5w.mjs → loadResourcesFromEntry-BpjYlaoj.mjs} +2 -2
  77. package/dist/logger/index.mjs +2 -2
  78. package/dist/{logger-UbknHqHy.mjs → logger-IL7Btm-N.mjs} +1 -1
  79. package/dist/{mcpPlugin-CTkk4RP8.mjs → mcpPlugin-BsdH7Vot.mjs} +21 -21
  80. package/dist/{memory-C47xVsjX.mjs → memory-Dkp6ZD3F.mjs} +3 -3
  81. package/dist/{metrics-TJyAb1Xk.mjs → metrics-CDPqgdKr.mjs} +3 -3
  82. package/dist/middleware/index.mjs +3 -3
  83. package/dist/migrations/index.mjs +2 -2
  84. package/dist/{module-CWiqsXnh.mjs → module-KFxT1Iuk.mjs} +1 -1
  85. package/dist/{multipartBody-BdG1qbn1.mjs → multipartBody-BHktuarE.mjs} +1 -1
  86. package/dist/{observeSend-DrA3ADFN.mjs → observeSend-CY-sLanc.mjs} +1 -1
  87. package/dist/{openapi-D6MAbYpv.mjs → openapi-DbeXiy2v.mjs} +6 -6
  88. package/dist/outbox-admin/index.mjs +5 -5
  89. package/dist/{outbox-module-D5QABFQW.mjs → outbox-module-BWqkTE8-.mjs} +7 -7
  90. package/dist/permissions/index.mjs +7 -7
  91. package/dist/{permissions-CFsmdYUt.mjs → permissions-e5YMrFbm.mjs} +9 -9
  92. package/dist/{pipe-B_05AgGt.mjs → pipe-CMnKfdF4.mjs} +2 -2
  93. package/dist/pipeline/index.mjs +2 -2
  94. package/dist/{plan-BnlNJhrj.mjs → plan-BvLJGm3U.mjs} +1 -1
  95. package/dist/{plugin-CrMPYbdj.mjs → plugin-DYmu8uT4.mjs} +24 -24
  96. package/dist/plugins/index.mjs +18 -18
  97. package/dist/plugins/response-cache.mjs +4 -4
  98. package/dist/plugins/tracing-entry.mjs +2 -2
  99. package/dist/{pluralize-oVIxJ4CY.mjs → pluralize-ClwfBdIx.mjs} +1 -1
  100. package/dist/presets/filesUpload.mjs +5 -5
  101. package/dist/presets/index.mjs +2 -2
  102. package/dist/presets/multiTenant.mjs +5 -5
  103. package/dist/presets/search.mjs +2 -2
  104. package/dist/{presets-CUd3L7v6.mjs → presets-DX_lPabi.mjs} +4 -4
  105. package/dist/{projection-DowJlIto.mjs → projection-DnZiFPPE.mjs} +2 -2
  106. package/dist/{purger.types-BjKy8869.mjs → purger.types-BEzTVDOU.mjs} +1 -1
  107. package/dist/{queryCachePlugin-BvB3k_Fh.mjs → queryCachePlugin-C57-Nj-g.mjs} +6 -6
  108. package/dist/{rateLimitKey-56nH1cWN.mjs → rateLimitKey-B1RxyGt3.mjs} +1 -1
  109. package/dist/{realtime-DXGBPtYK.mjs → realtime-C-VIoXMg.mjs} +67 -11
  110. package/dist/registry/index.mjs +3 -3
  111. package/dist/{registry-Biz-6sEZ.mjs → registry-DbQvODPH.mjs} +2 -2
  112. package/dist/{relay-DEIoMntZ.mjs → relay-B61seKq1.mjs} +5 -5
  113. package/dist/{renewingLease-BCJpW9-u.mjs → renewingLease-Dp7wmzNN.mjs} +1 -1
  114. package/dist/{replyHelpers-DliJNb0-.mjs → replyHelpers-CHii_jIO.mjs} +2 -2
  115. package/dist/{requestContext-tUgLt9Ky.mjs → requestContext-C_mbAm8o.mjs} +1 -1
  116. package/dist/{requirement-0l2DApiQ.mjs → requirement-C8OsWLYp.mjs} +1 -1
  117. package/dist/{resourceRateLimit-iSXF8rLH.mjs → resourceRateLimit-DhbQZjE2.mjs} +2 -2
  118. package/dist/{rolldown-runtime-gKJR3o-6.mjs → rolldown-runtime-HTi8KV7V.mjs} +1 -1
  119. package/dist/{routeValidator-xNYA4rr1.mjs → routeValidator-DnQ2BGnH.mjs} +1 -1
  120. package/dist/{runtimeCapabilities-BQK-GrYe.mjs → runtimeCapabilities-G9QXHov1.mjs} +1 -1
  121. package/dist/{schedules-D9iMVFhF.mjs → schedules-DAthT5O3.mjs} +5 -5
  122. package/dist/{schemaConverter-cIh4oX9a.mjs → schemaConverter-BOt_ed78.mjs} +2 -2
  123. package/dist/{schemaIR-BsY4y9VP.mjs → schemaIR-MZVVj6Cw.mjs} +14 -14
  124. package/dist/schemas/index.mjs +1 -1
  125. package/dist/scim/index.mjs +2 -2
  126. package/dist/scope/index.mjs +5 -5
  127. package/dist/{scope-QyhM9w8z.mjs → scope-btg-225w.mjs} +4 -4
  128. package/dist/{shutdown-BM7Q0h4B.mjs → shutdown-Dfy8La90.mjs} +1 -1
  129. package/dist/{streamFrames-B3ZJfI02.mjs → simpleEqualityMatcher-D5dOqbbj.mjs} +2 -19
  130. package/dist/{sse-ofvlcTQQ.mjs → sse-DivxX1m6.mjs} +7 -7
  131. package/dist/{sseStream-BxQW7hPq.mjs → sseStream-hQxQjvre.mjs} +2 -2
  132. package/dist/{store-helpers-_FRhHDyv.mjs → store-helpers-DfqfssAw.mjs} +1 -1
  133. package/dist/{streaming-HZr63UiM.mjs → streaming-CQiOktsh.mjs} +1 -1
  134. package/dist/{subscriberIdentity-DSgnoT_D.mjs → subscriberIdentity-Bf8VLqA7.mjs} +1 -1
  135. package/dist/{tenancy-_ukT0oBt.mjs → tenancy-Btmaf1MB.mjs} +2 -2
  136. package/dist/{tenantPreparation-DSlQI53c.mjs → tenantPreparation-4e3qyb6q.mjs} +4 -4
  137. package/dist/testing/cleanupStoreContract.mjs +1 -1
  138. package/dist/testing/index.mjs +11 -11
  139. package/dist/testing/outboxStoreContract.mjs +2 -2
  140. package/dist/testing/requiredPorts.mjs +2 -2
  141. package/dist/testing/storageContract.mjs +1 -1
  142. package/dist/{timing-Z8p-Zlw1.mjs → timing-DXx0IWyi.mjs} +1 -1
  143. package/dist/{transactionContext-DBbSTfY3.mjs → transactionContext-DperjON1.mjs} +1 -1
  144. package/dist/{typeGuards-_6nNQqgq.mjs → typeGuards-eoQLIOh6.mjs} +1 -1
  145. package/dist/types/index.mjs +1 -1
  146. package/dist/types/storage.mjs +1 -1
  147. package/dist/{types-CrOlZ4rY.mjs → types-CcpISJe8.mjs} +4 -4
  148. package/dist/usage/index.mjs +4 -4
  149. package/dist/{userHelpers-CBKx3XJN.mjs → userHelpers-Cp5zqlEN.mjs} +1 -1
  150. package/dist/utils/index.d.mts +2 -48
  151. package/dist/utils/index.mjs +13 -13
  152. package/dist/{utils--HE8R8sH.mjs → utils-dKN-_315.mjs} +7 -7
  153. package/dist/{validate-BUeE2MLR.mjs → validate-BZHaAdgy.mjs} +3 -3
  154. package/dist/{versioning-qYgqwOhL.mjs → versioning-CPLP0VbB.mjs} +3 -3
  155. package/dist/{workScope-C-1QHNmV.mjs → workScope-BI72KXsI.mjs} +2 -2
  156. package/package.json +19 -14
  157. package/skills/arc/references/api-reference.md +1 -1
  158. package/skills/arc/references/auth-better-auth.md +27 -1
  159. package/skills/arc/references/production-realtime.md +1 -1
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
- import { r as workSeedFromEvent, t as runWorkScope } from "./workScope-C-1QHNmV.mjs";
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
+ import { r as workSeedFromEvent, t as runWorkScope } from "./workScope-BI72KXsI.mjs";
3
3
  import { createEvent as createEvent$1, createEventRouter } from "@classytic/primitives/events";
4
4
  // src/events/EventTransport.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
- import { t as buildRequestScopeProjection } from "./projection-DowJlIto.mjs";
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
+ import { t as buildRequestScopeProjection } from "./projection-DnZiFPPE.mjs";
3
3
  // src/hooks/HookSystem.ts
4
4
  /**
5
5
  * Hook System
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
- import "./constants-DOnfMd7i.mjs";
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
+ import "./constants-DH41jnNT.mjs";
3
3
  // src/registry/ResourceRegistry.ts
4
4
  /**
5
5
  * Resource Registry
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
2
  // src/idempotency/acquire.ts
3
3
  async function acquireIdempotencyKey(store, key, requestId, lockTtlMs) {
4
4
  if (typeof store.acquire === "function") return store.acquire(key, requestId, lockTtlMs);
@@ -1,7 +1,7 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
- import { t as transactionContext } from "../transactionContext-DBbSTfY3.mjs";
3
- import { g as getUserId, i as getClientId } from "../types-CrOlZ4rY.mjs";
4
- import { n as declareRuntimeCapability } from "../runtimeCapabilities-BQK-GrYe.mjs";
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
+ import { t as transactionContext } from "../transactionContext-DperjON1.mjs";
3
+ import { g as getUserId, i as getClientId } from "../types-CcpISJe8.mjs";
4
+ import { n as declareRuntimeCapability } from "../runtimeCapabilities-G9QXHov1.mjs";
5
5
  import { and, anyOf, eq, gte, lt, lte } from "@classytic/repo-core/filter";
6
6
  import fp from "fastify-plugin";
7
7
  // src/audit/repository-audit-adapter.ts
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
2
  // src/auth/audit.ts
3
3
  function compileGlobs(patterns) {
4
4
  if (patterns.length === 0) return () => false;
@@ -138,6 +138,14 @@ interface BetterAuthAdapterOptions {
138
138
  max: number;
139
139
  timeWindow: string | number;
140
140
  } | false;
141
+ /**
142
+ * Route prefixes (`'/admin'`, `'/api/account'`) whose requests re-read the session from Better
143
+ * Auth's session store, bypassing the cookie cache, as Better Auth's `sensitiveSessionMiddleware`
144
+ * does: a revoked or expired session is a 401, a banned user a 403. Matched against the registered
145
+ * route URL on `/` boundaries. Costs one session-store read per matching request. Per route:
146
+ * `requireSensitiveSession`. See wiki/auth.md.
147
+ */
148
+ sensitivePaths?: readonly string[];
141
149
  }
142
150
  interface BetterAuthAdapterResult {
143
151
  /** Fastify plugin that registers catch-all auth routes */
@@ -146,6 +154,21 @@ interface BetterAuthAdapterResult {
146
154
  authenticate: (request: FastifyRequest, reply: FastifyReply$1) => Promise<void | FastifyReply$1>;
147
155
  /** Optional authenticate -- resolves session silently, continues as unauthenticated on failure */
148
156
  optionalAuthenticate: (request: FastifyRequest, reply: FastifyReply$1) => Promise<void>;
157
+ /**
158
+ * PreHandler for a sensitive route (account, security settings, admin, money): after
159
+ * `authenticate`, re-reads the session from storage, bypassing the cookie cache; revoked or
160
+ * expired → 401, banned → 403. One extra session-store read, skipped on a `sensitivePaths` route.
161
+ * Per resource: `routeGuards: [requireSensitiveSession]`.
162
+ */
163
+ requireSensitiveSession: (request: FastifyRequest, reply: FastifyReply$1) => Promise<void | FastifyReply$1>;
164
+ /**
165
+ * PreHandler for a route that needs a RECENT sign-in (change password, add a passkey, delete the
166
+ * account), as Better Auth's `freshSessionMiddleware`: after `authenticate`, a session older than
167
+ * Better Auth's `session.freshAge` (default one day; `0` disables the check) is a 403
168
+ * "Session is not fresh", and the client re-authenticates. No session (a credential verifier, or
169
+ * no `authenticate` before it) is a 401. Per resource: `routeGuards: [requireFreshSession]`.
170
+ */
171
+ requireFreshSession: (request: FastifyRequest, reply: FastifyReply$1) => Promise<void | FastifyReply$1>;
149
172
  /** Permission helpers bound to this auth adapter (available when orgContext is enabled) */
150
173
  permissions: {
151
174
  requireOrgRole: (...roles: string[]) => PermissionCheck;
@@ -173,6 +196,13 @@ declare module "fastify" {
173
196
  optionalAuthenticate: (request: FastifyRequest, reply: FastifyReply$1) => Promise<void>;
174
197
  }
175
198
  }
199
+ /**
200
+ * Header arc sets on every request it hands Better Auth: Fastify's `request.ip` (so it honors
201
+ * arc's `trustProxy`), replacing any client-sent value. Better Auth keys rate limits on
202
+ * `X-Forwarded-For` by default, which a directly-connected client can forge; opt in with
203
+ * `advanced: { ipAddress: { ipAddressHeaders: [BETTER_AUTH_CLIENT_IP_HEADER] } }`.
204
+ */
205
+ export declare const BETTER_AUTH_CLIENT_IP_HEADER = "x-arc-client-ip";
176
206
  /**
177
207
  * Create a Better Auth adapter for Arc/Fastify.
178
208
  *
@@ -1,10 +1,10 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
- import { n as getUserRoles, r as normalizeRoles } from "../userHelpers-CBKx3XJN.mjs";
3
- import { d as createDomainError, l as UnauthorizedError, p as isArcError, t as ArcError } from "../errors-BpYV859Y.mjs";
4
- import { E as requireOrgRole, T as requireOrgMembership, k as requireTeamMembership } from "../permissions-CFsmdYUt.mjs";
5
- import { n as requireSingleHeaderValue } from "../headers-D4bncIOf.mjs";
6
- import { o as toJsonSchema } from "../schemaConverter-cIh4oX9a.mjs";
7
- import { n as declareRuntimeCapability } from "../runtimeCapabilities-BQK-GrYe.mjs";
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
+ import { n as getUserRoles, r as normalizeRoles } from "../userHelpers-Cp5zqlEN.mjs";
3
+ import { d as createDomainError, l as UnauthorizedError, p as isArcError, t as ArcError } from "../errors-KBZ3tQk5.mjs";
4
+ import { E as requireOrgRole, T as requireOrgMembership, k as requireTeamMembership } from "../permissions-e5YMrFbm.mjs";
5
+ import { n as requireSingleHeaderValue } from "../headers-D5wrBLOk.mjs";
6
+ import { o as toJsonSchema } from "../schemaConverter-BOt_ed78.mjs";
7
+ import { n as declareRuntimeCapability } from "../runtimeCapabilities-G9QXHov1.mjs";
8
8
  import { ARC_ERROR_CODES } from "@classytic/repo-core/errors";
9
9
  import { isProductionEnv } from "@classytic/primitives/environment";
10
10
  import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
@@ -562,19 +562,52 @@ function mergeUserFieldsIntoRequestBody(requestBody, userFields, endpointPath) {
562
562
  * });
563
563
  */
564
564
  /**
565
+ * Header arc sets on every request it hands Better Auth: Fastify's `request.ip` (so it honors
566
+ * arc's `trustProxy`), replacing any client-sent value. Better Auth keys rate limits on
567
+ * `X-Forwarded-For` by default, which a directly-connected client can forge; opt in with
568
+ * `advanced: { ipAddress: { ipAddressHeaders: [BETTER_AUTH_CLIENT_IP_HEADER] } }`.
569
+ */
570
+ const BETTER_AUTH_CLIENT_IP_HEADER = "x-arc-client-ip";
571
+ /** Verbs Better Auth endpoints may declare that the catch-all will register. */
572
+ const ROUTABLE_METHODS = /* @__PURE__ */ new Set([
573
+ "GET",
574
+ "POST",
575
+ "PUT",
576
+ "PATCH",
577
+ "DELETE"
578
+ ]);
579
+ /**
580
+ * The verbs Better Auth's router answers: GET and POST (core, and the official Fastify guide),
581
+ * plus any a plugin endpoint declares — `@better-auth/scim` uses PUT/PATCH/DELETE,
582
+ * `@better-auth/oauth-provider` PATCH/DELETE. Mirrors better-call's `createRouter`, which skips
583
+ * endpoints without a path or marked `metadata.SERVER_ONLY`. Never `all()`: that adds TRACE and
584
+ * QUERY to the auth surface.
585
+ */
586
+ function betterAuthRouteMethods(api) {
587
+ const methods = /* @__PURE__ */ new Set(["GET", "POST"]);
588
+ for (const endpoint of Object.values(api ?? {})) {
589
+ if (!endpoint || typeof endpoint !== "function" && typeof endpoint !== "object") continue;
590
+ const { path, options } = endpoint;
591
+ if (typeof path !== "string" || !options || options.metadata?.SERVER_ONLY) continue;
592
+ for (const method of [options.method].flat()) {
593
+ if (typeof method !== "string") continue;
594
+ const verb = method.toUpperCase();
595
+ if (ROUTABLE_METHODS.has(verb)) methods.add(verb);
596
+ }
597
+ }
598
+ return [...methods];
599
+ }
600
+ /**
565
601
  * Convert a Fastify request into a Fetch API Request.
566
602
  *
567
603
  * Better Auth expects standard Web API Request objects.
568
604
  * We reconstruct one from Fastify's request properties.
569
605
  */
570
606
  function toFetchRequest(request) {
571
- const url = `${request.protocol ?? "http"}://${request.hostname ?? "localhost"}${request.url}`;
572
- const headers = new Headers();
573
- for (const [key, value] of Object.entries(request.headers)) {
574
- if (value === void 0) continue;
575
- if (Array.isArray(value)) for (const v of value) headers.append(key, v);
576
- else headers.set(key, value);
577
- }
607
+ const url = `${request.protocol ?? "http"}://${request.host || "localhost"}${request.url}`;
608
+ const headers = buildHeaders(request);
609
+ headers.delete(BETTER_AUTH_CLIENT_IP_HEADER);
610
+ if (request.ip) headers.set(BETTER_AUTH_CLIENT_IP_HEADER, request.ip);
578
611
  const hasBody = request.method !== "GET" && request.method !== "HEAD";
579
612
  let body;
580
613
  if (hasBody && request.body != null) {
@@ -661,17 +694,39 @@ function withErrorEnvelope(text, status, contentType, correlationId) {
661
694
  });
662
695
  }
663
696
  /**
697
+ * Whether sessions live in a server-side store (Better Auth's `isStateful`: `database` or
698
+ * `secondaryStorage`). Without one the signed cookie IS the session, so an authoritative read
699
+ * keeps the cookie cache. An instance without `options` (a stub) counts as stateful.
700
+ */
701
+ function hasSessionStore(auth) {
702
+ const options = auth.options;
703
+ return !options || !!options.database || !!options.secondaryStorage;
704
+ }
705
+ /**
706
+ * Better Auth admin plugin's ban rule, as its session-create hook applies it: `banned`, unless
707
+ * `banExpires` has passed. Checked only on an authoritative read (a cached user is stale).
708
+ */
709
+ function isBannedUser(user) {
710
+ if (user.banned !== true) return false;
711
+ if (!user.banExpires) return true;
712
+ return !(new Date(user.banExpires).getTime() < Date.now());
713
+ }
714
+ /**
664
715
  * Resolve the current session via `auth.api.getSession`. Throws
665
716
  * `ArcError(BETTER_AUTH_API_MISSING)` when it is absent (a stub, not a real
666
- * `betterAuth()` instance).
717
+ * `betterAuth()` instance). `authoritative` bypasses the cookie cache
718
+ * (`disableCookieCache`), so the session is read from storage.
667
719
  */
668
- async function getSessionDirect(auth, headers) {
720
+ async function getSessionDirect(auth, headers, authoritative = false) {
669
721
  const api = auth.api;
670
722
  if (!api || typeof api.getSession !== "function") throw new ArcError("Better Auth instance is missing `api.getSession` — arc requires the in-process API map. Pass a real `betterAuth()` instance or supply an `api: { getSession }` stub.", {
671
723
  code: ARC_ERROR_CODES.AUTH_MISCONFIGURED,
672
724
  statusCode: 500
673
725
  });
674
- const result = await api.getSession({ headers });
726
+ const result = await api.getSession(authoritative ? {
727
+ headers,
728
+ query: { disableCookieCache: true }
729
+ } : { headers });
675
730
  return result?.user ? result : null;
676
731
  }
677
732
  /**
@@ -778,7 +833,25 @@ async function resolveActiveTeamId(input) {
778
833
  }
779
834
  const AUTH_SCHEME = /^[A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*$/;
780
835
  function createBetterAuthAdapter(options) {
781
- const { auth, basePath = "/api/auth", orgContext: orgContextOpt = false, openapi: openapiOpt = true, userFields, exposeAuthErrors = false, resolveOrgRoles, memberLookup = "better-auth", credentials = {} } = options;
836
+ const { auth, basePath = "/api/auth", orgContext: orgContextOpt = false, openapi: openapiOpt = true, userFields, exposeAuthErrors = false, resolveOrgRoles, memberLookup = "better-auth", credentials = {}, sensitivePaths = [] } = options;
837
+ const sensitivePrefixes = sensitivePaths.map((prefix) => {
838
+ if (typeof prefix !== "string" || !prefix.startsWith("/")) throw new Error(`createBetterAuthAdapter: sensitivePaths entry ${JSON.stringify(prefix)} must start with "/".`);
839
+ return prefix.replace(/\/+$/, "");
840
+ });
841
+ /** The registered route URL (not the raw URL, which percent-encoding could disguise). */
842
+ const isSensitiveRoute = (request) => {
843
+ if (sensitivePrefixes.length === 0) return false;
844
+ const url = request.routeOptions?.url ?? request.url.split("?")[0] ?? "";
845
+ return sensitivePrefixes.some((prefix) => url === prefix || url.startsWith(`${prefix}/`));
846
+ };
847
+ const authoritativeRead = hasSessionStore(auth);
848
+ /** Requests whose principal was read authoritatively this request (store read, or a verifier). */
849
+ const verifiedFresh = /* @__PURE__ */ new WeakSet();
850
+ const bannedReply = (reply) => reply.code(403).send({
851
+ code: ARC_ERROR_CODES.FORBIDDEN,
852
+ message: "Account is banned",
853
+ status: 403
854
+ });
782
855
  const verifiers = /* @__PURE__ */ new Map();
783
856
  for (const [scheme, verify] of Object.entries(credentials)) {
784
857
  if (!AUTH_SCHEME.test(scheme)) throw new Error(`createBetterAuthAdapter: "${scheme}" is not an auth scheme name.`);
@@ -861,11 +934,13 @@ function createBetterAuthAdapter(options) {
861
934
  return reply;
862
935
  }
863
936
  request.scope = scope;
937
+ verifiedFresh.add(request);
864
938
  return;
865
939
  }
866
940
  try {
867
941
  const headers = buildHeaders(request);
868
- const sessionData = await getSessionDirect(auth, headers);
942
+ const sensitive = isSensitiveRoute(request);
943
+ const sessionData = await getSessionDirect(auth, headers, sensitive && authoritativeRead);
869
944
  if (!sessionData?.user) {
870
945
  reply.code(401).send({
871
946
  code: ARC_ERROR_CODES.UNAUTHORIZED,
@@ -874,6 +949,10 @@ function createBetterAuthAdapter(options) {
874
949
  });
875
950
  return reply;
876
951
  }
952
+ if (sensitive) {
953
+ if (isBannedUser(sessionData.user)) return bannedReply(reply);
954
+ verifiedFresh.add(request);
955
+ }
877
956
  const req = request;
878
957
  req.user = sessionData.user;
879
958
  req.session = sessionData.session;
@@ -912,13 +991,21 @@ function createBetterAuthAdapter(options) {
912
991
  const presented = presentedCredential(request);
913
992
  if (presented) {
914
993
  const scope = await presented.verify(presented.value, request);
915
- if (scope) request.scope = scope;
994
+ if (scope) {
995
+ request.scope = scope;
996
+ verifiedFresh.add(request);
997
+ }
916
998
  return;
917
999
  }
918
1000
  try {
919
1001
  const headers = buildHeaders(request);
920
- const sessionData = await getSessionDirect(auth, headers);
1002
+ const sensitive = isSensitiveRoute(request);
1003
+ const sessionData = await getSessionDirect(auth, headers, sensitive && authoritativeRead);
921
1004
  if (!sessionData?.user) return;
1005
+ if (sensitive) {
1006
+ if (isBannedUser(sessionData.user)) return;
1007
+ verifiedFresh.add(request);
1008
+ }
922
1009
  const req = request;
923
1010
  req.user = sessionData.user;
924
1011
  req.session = sessionData.session;
@@ -938,6 +1025,52 @@ function createBetterAuthAdapter(options) {
938
1025
  if (err instanceof ArcError) throw err;
939
1026
  }
940
1027
  };
1028
+ /**
1029
+ * Runs after `authenticate`: the session `request.user` came from must still exist in storage
1030
+ * for the same user. Skipped when this request already read authoritatively (a `sensitivePaths`
1031
+ * route, or a registered credential verifier, which arc never caches).
1032
+ */
1033
+ const requireSensitiveSession = async (request, reply) => {
1034
+ if (verifiedFresh.has(request)) return;
1035
+ const unauthorized = (message) => reply.code(401).send({
1036
+ code: ARC_ERROR_CODES.UNAUTHORIZED,
1037
+ message,
1038
+ status: 401
1039
+ });
1040
+ const current = request.user;
1041
+ if (!current || presentedCredential(request)) return unauthorized("Authentication required");
1042
+ try {
1043
+ const sessionData = await getSessionDirect(auth, buildHeaders(request), authoritativeRead);
1044
+ const freshId = sessionData ? String(sessionData.user.id ?? sessionData.user._id ?? "") : "";
1045
+ if (!freshId || freshId !== String(current.id ?? current._id ?? "")) return unauthorized("Invalid or expired session");
1046
+ if (isBannedUser(sessionData?.user ?? {})) return bannedReply(reply);
1047
+ verifiedFresh.add(request);
1048
+ } catch (err) {
1049
+ if (err instanceof ArcError) throw err;
1050
+ return unauthorized(exposeAuthErrors && err instanceof Error ? err.message : "Authentication required");
1051
+ }
1052
+ };
1053
+ /** Better Auth's default `session.freshAge` (seconds): one day. `0` turns the check off. */
1054
+ const DEFAULT_FRESH_AGE_S = 86400;
1055
+ const freshAgeSeconds = () => {
1056
+ const configured = auth.options?.session?.freshAge;
1057
+ return typeof configured === "number" && Number.isFinite(configured) && configured >= 0 ? configured : DEFAULT_FRESH_AGE_S;
1058
+ };
1059
+ const requireFreshSession = async (request, reply) => {
1060
+ const session = request.session;
1061
+ const createdAt = session ? new Date(session.createdAt).getTime() : NaN;
1062
+ if (!session || presentedCredential(request) || Number.isNaN(createdAt)) return reply.code(401).send({
1063
+ code: ARC_ERROR_CODES.UNAUTHORIZED,
1064
+ message: "Authentication required",
1065
+ status: 401
1066
+ });
1067
+ const freshAge = freshAgeSeconds();
1068
+ if (freshAge !== 0 && Date.now() - createdAt >= freshAge * 1e3) return reply.code(403).send({
1069
+ code: ARC_ERROR_CODES.FORBIDDEN,
1070
+ message: "Session is not fresh",
1071
+ status: 403
1072
+ });
1073
+ };
941
1074
  let extractedOpenApi;
942
1075
  if (openapiOpt === false) extractedOpenApi = void 0;
943
1076
  else if (typeof openapiOpt === "object") extractedOpenApi = openapiOpt;
@@ -949,16 +1082,21 @@ function createBetterAuthAdapter(options) {
949
1082
  });
950
1083
  }
951
1084
  const routeOpts = options.rateLimit && typeof options.rateLimit === "object" ? { config: { rateLimit: options.rateLimit } } : {};
952
- fastify.all(`${normalizedBase}/*`, routeOpts, async (request, reply) => {
953
- try {
954
- const fetchRequest = toFetchRequest(request);
955
- await sendFetchResponse(await auth.handler(fetchRequest), reply, request);
956
- } catch (err) {
957
- throw new ArcError("Authentication service error", {
958
- code: ARC_ERROR_CODES.AUTH_SERVICE_ERROR,
959
- statusCode: 500,
960
- cause: err instanceof Error ? err : new Error(String(err))
961
- });
1085
+ fastify.route({
1086
+ method: betterAuthRouteMethods(auth.api),
1087
+ url: `${normalizedBase}/*`,
1088
+ ...routeOpts,
1089
+ handler: async (request, reply) => {
1090
+ try {
1091
+ const fetchRequest = toFetchRequest(request);
1092
+ await sendFetchResponse(await auth.handler(fetchRequest), reply, request);
1093
+ } catch (err) {
1094
+ throw new ArcError("Authentication service error", {
1095
+ code: ARC_ERROR_CODES.AUTH_SERVICE_ERROR,
1096
+ statusCode: 500,
1097
+ cause: err instanceof Error ? err : new Error(String(err))
1098
+ });
1099
+ }
962
1100
  }
963
1101
  });
964
1102
  if (!fastify.hasDecorator("authenticate")) fastify.decorate("authenticate", authenticate);
@@ -982,6 +1120,8 @@ function createBetterAuthAdapter(options) {
982
1120
  }),
983
1121
  authenticate,
984
1122
  optionalAuthenticate,
1123
+ requireSensitiveSession,
1124
+ requireFreshSession,
985
1125
  permissions: {
986
1126
  requireOrgRole: (...roles) => requireOrgRole(roles),
987
1127
  requireOrgMembership: () => requireOrgMembership(),
@@ -1415,4 +1555,4 @@ function mirrorTrustedOriginsFromCors(options) {
1415
1555
  if (!corsOrigins) return [canonicalUrl];
1416
1556
  return Array.from(/* @__PURE__ */ new Set([canonicalUrl, ...corsOrigins]));
1417
1557
  }
1418
- export { MemorySessionStore, authPlugin_default as authPlugin, createBetterAuthAdapter, createSessionManager, extractBetterAuthOpenApi, mirrorTrustedOriginsFromCors };
1558
+ export { BETTER_AUTH_CLIENT_IP_HEADER, MemorySessionStore, authPlugin_default as authPlugin, createBetterAuthAdapter, createSessionManager, extractBetterAuthOpenApi, mirrorTrustedOriginsFromCors };
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.51.0 | MIT | https://classytic.com */
2
2
  import sjson from "secure-json-parse";
3
3
  // src/auth/redis-session.ts
4
4
  /**
@@ -0,0 +1,42 @@
1
+
2
+ import { SocialProviders } from "better-auth/social-providers";
3
+ import { BetterAuthPlugin } from "better-auth";
4
+ /** Provider ids with a preset. */
5
+ type SocialProviderId = "google" | "github" | "apple" | "facebook";
6
+ /** A provider as listed to clients: id plus display name. */
7
+ interface SocialProviderInfo {
8
+ id: string;
9
+ name: string;
10
+ }
11
+ interface DefineSocialProvidersOptions {
12
+ /** Providers to enable: an array or a comma list (`"google,github"`). Empty enables none. */
13
+ enabled: readonly string[] | string;
14
+ /** Where credentials are read. Default `process.env`. */
15
+ env?: Readonly<Record<string, string | undefined>>;
16
+ /** Better Auth provider options merged over each preset (shallow). */
17
+ overrides?: Partial<Record<SocialProviderId, Record<string, unknown>>>;
18
+ }
19
+ interface DefinedSocialProviders {
20
+ /** Pass to `betterAuth({ socialProviders })`. */
21
+ socialProviders: SocialProviders;
22
+ /** Enabled providers in `enabled` order; pass to `socialAuth({ providers })`. */
23
+ providers: SocialProviderInfo[];
24
+ /** Origins the enabled providers post back from (Apple's form_post). Add to `trustedOrigins`. */
25
+ trustedOrigins: string[];
26
+ }
27
+ /**
28
+ * Better Auth `socialProviders`, the client-facing provider list and the extra trusted origins,
29
+ * for the providers `enabled` names. Throws on an unknown id, and on an enabled provider whose
30
+ * credentials are missing (the message names each missing variable).
31
+ *
32
+ * @example
33
+ * const social = defineSocialProviders({ enabled: process.env.SOCIAL_PROVIDERS ?? "" });
34
+ * betterAuth({ socialProviders: social.socialProviders, plugins: [socialAuth({ providers: social.providers })] });
35
+ */
36
+ export declare function defineSocialProviders(options: DefineSocialProvidersOptions): DefinedSocialProviders;
37
+ interface SocialAuthOptions {
38
+ /** Display names for `/social/providers` (`defineSocialProviders().providers`). */
39
+ providers?: readonly SocialProviderInfo[];
40
+ }
41
+ export declare function socialAuth(options?: SocialAuthOptions): BetterAuthPlugin;
42
+ export type { DefineSocialProvidersOptions, DefinedSocialProviders, SocialAuthOptions, SocialProviderId, SocialProviderInfo };