@classytic/arc 2.45.1 → 2.46.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 (321) hide show
  1. package/README.md +1 -1
  2. package/dist/{EventTransport-CiicKz2Z.d.mts → EventTransport-CYEoCJGe.d.mts} +0 -2
  3. package/dist/{EventTransport-4b0noGwa.mjs → EventTransport-DNgD9NP4.mjs} +3 -4
  4. package/dist/{HookSystem-4pABQnGn.mjs → HookSystem-DRbPzEcP.mjs} +3 -4
  5. package/dist/{QueryCache--5uAuYPW.d.mts → QueryCache-DdvrGG8Q.d.mts} +1 -3
  6. package/dist/{ResourceRegistry-BBaN_Ne-.mjs → ResourceRegistry-Douk51fa.mjs} +15 -4
  7. package/dist/{acquire-kiZzy5bX.mjs → acquire-RbtvDg9s.mjs} +2 -3
  8. package/dist/{actionPermissions-BLnbDA6g.mjs → actionPermissions-De0AJ7hm.mjs} +37 -42
  9. package/dist/audit/index.d.mts +2 -10
  10. package/dist/audit/index.mjs +8 -12
  11. package/dist/auth/audit.d.mts +0 -2
  12. package/dist/auth/audit.mjs +2 -3
  13. package/dist/auth/index.d.mts +9 -17
  14. package/dist/auth/index.mjs +26 -29
  15. package/dist/auth/redis-session.d.mts +2 -4
  16. package/dist/auth/redis-session.mjs +2 -3
  17. package/dist/{authorizationDecision-CVlaTjAX.mjs → authorizationDecision-DeZMrHcm.mjs} +5 -6
  18. package/dist/{base-CZyixEQR.d.mts → base-HXNgPQww.d.mts} +1 -7
  19. package/dist/{boundedMap-DSy7KkeX.mjs → boundedMap-2WBh3gM9.mjs} +2 -3
  20. package/dist/{buildHandler-B4IhILv9.mjs → buildHandler-DxVOOBpw.mjs} +5 -6
  21. package/dist/cache/index.d.mts +4 -10
  22. package/dist/cache/index.mjs +5 -6
  23. package/dist/{caching-DqakP2vY.mjs → caching-BYRwYrUo.mjs} +3 -4
  24. package/dist/{claimed-XoiVrWZ2.mjs → claimed-DYlELdnm.mjs} +2 -3
  25. package/dist/cleanup/index.d.mts +9 -18
  26. package/dist/cleanup/index.mjs +12 -20
  27. package/dist/cli/commands/describe.d.mts +1 -3
  28. package/dist/cli/commands/describe.mjs +4 -5
  29. package/dist/cli/commands/docs.d.mts +1 -3
  30. package/dist/cli/commands/docs.mjs +4 -5
  31. package/dist/cli/commands/doctor.d.mts +1 -3
  32. package/dist/cli/commands/doctor.mjs +2 -3
  33. package/dist/cli/commands/generate.d.mts +1 -1
  34. package/dist/cli/commands/generate.mjs +2 -2
  35. package/dist/cli/commands/init.d.mts +1 -1
  36. package/dist/cli/commands/init.mjs +2 -2
  37. package/dist/cli/commands/introspect.d.mts +1 -3
  38. package/dist/cli/commands/introspect.mjs +3 -4
  39. package/dist/cli/index.d.mts +2 -2
  40. package/dist/cli/index.mjs +3 -3
  41. package/dist/{constants-CtWkmWn3.mjs → constants-CHZMUwBW.mjs} +2 -3
  42. package/dist/context/index.d.mts +0 -8
  43. package/dist/context/index.mjs +6 -7
  44. package/dist/core/index.d.mts +3 -3
  45. package/dist/core/index.mjs +8 -8
  46. package/dist/{core-Cro2v5a7.mjs → core-D9rS2BxO.mjs} +9 -12
  47. package/dist/{createActionRouter-k-gwiPv6.mjs → createActionRouter-0qkCRzTL.mjs} +7 -8
  48. package/dist/{createAggregationRouter-BqWqhAPG.mjs → createAggregationRouter-CUf5Esd9.mjs} +9 -10
  49. package/dist/{createApp-Dw7L72Hz.mjs → createApp-DZIXfDKD.mjs} +49 -62
  50. package/dist/{createMcpServer-DSztofa9.d.mts → createMcpServer-DeVpqQF-.d.mts} +1 -3
  51. package/dist/{defineAggregation-pxbd7BBK.mjs → defineAggregation-bmKQ4NmC.mjs} +2 -3
  52. package/dist/{defineResource-DwgEjLCO.mjs → defineResource-CGmdmGwh.mjs} +78 -29
  53. package/dist/discovery/index.d.mts +1 -3
  54. package/dist/discovery/index.mjs +2 -3
  55. package/dist/docs/index.d.mts +8 -8
  56. package/dist/docs/index.mjs +4 -5
  57. package/dist/{elevation-B9wF2Z1F.mjs → elevation-CzhqAyVN.mjs} +9 -10
  58. package/dist/{elevation-BW2J3tNj.d.mts → elevation-DPD0hcU-.d.mts} +0 -2
  59. package/dist/encryption/index.d.mts +1 -7
  60. package/dist/encryption/index.mjs +8 -13
  61. package/dist/{errorHandler--4rSMMvq.d.mts → errorHandler-B9r88jZV.d.mts} +8 -3
  62. package/dist/{errorHandler-Dr2nG0Ui.mjs → errorHandler-dFyGOEoB.mjs} +16 -6
  63. package/dist/{errors-BtHzrSA6.mjs → errors-BY8vzlP4.mjs} +2 -3
  64. package/dist/{errors-JYc9vwqE.d.mts → errors-DTo0me1o.d.mts} +0 -2
  65. package/dist/{eventPlugin-BtmA4-3P.d.mts → eventPlugin-BY38F6yK.d.mts} +1 -7
  66. package/dist/{eventPlugin-Dvs7OBw8.mjs → eventPlugin-eMhAPtQA.mjs} +10 -12
  67. package/dist/{eventTypes-BVoCTG5c.mjs → eventTypes-Do2KYeJx.mjs} +5 -8
  68. package/dist/events/index.d.mts +4 -16
  69. package/dist/events/index.mjs +8 -9
  70. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  71. package/dist/events/transports/redis-stream-entry.mjs +5 -6
  72. package/dist/events/transports/redis.d.mts +2 -4
  73. package/dist/events/transports/redis.mjs +3 -4
  74. package/dist/{externalPaths-CmGOxOtD.d.mts → externalPaths-BOqdq5wr.d.mts} +0 -2
  75. package/dist/factory/index.d.mts +4 -14
  76. package/dist/factory/index.mjs +12 -18
  77. package/dist/{fastify-augmentation-DRlCIWE9.d.mts → fastify-augmentation-Dtn0IIRn.d.mts} +4 -10
  78. package/dist/{fields-BBSpf8pS.d.mts → fields-JTkrtO-r.d.mts} +0 -2
  79. package/dist/{fields-C1e_7Fwi.mjs → fields-LnbCcvsw.mjs} +2 -3
  80. package/dist/{filter-merge-xaiEKtz8.mjs → filter-merge-BAWi019Q.mjs} +2 -3
  81. package/dist/{generate-DCGuEbqI.d.mts → generate-C-g_KOkV.d.mts} +0 -4
  82. package/dist/{generate-DJiJMaXN.mjs → generate-oXoDnpJf.mjs} +7 -12
  83. package/dist/{headers-Dr-wt6Tr.mjs → headers-DBd3Qheo.mjs} +3 -4
  84. package/dist/{health-DkkWbJtQ.mjs → health-BlJu9GXS.mjs} +2 -3
  85. package/dist/{health-BLYn_Hds.mjs → health-Dp-3EC9o.mjs} +4 -7
  86. package/dist/hooks/index.d.mts +1 -1
  87. package/dist/hooks/index.mjs +2 -2
  88. package/dist/idempotency/index.d.mts +3 -9
  89. package/dist/idempotency/index.mjs +10 -13
  90. package/dist/idempotency/redis.d.mts +1 -1
  91. package/dist/idempotency/redis.mjs +3 -4
  92. package/dist/{index-Bxriq3so.d.mts → index-B5i9-vuP.d.mts} +4 -26
  93. package/dist/{index-Chgz3d0i.d.mts → index-BAXDo5eE.d.mts} +1 -7
  94. package/dist/{index-Beg3aNnK.d.mts → index-BTxzJ_MN.d.mts} +67 -25
  95. package/dist/{index-CUJvoyw3.d.mts → index-Bqfo8hLz.d.mts} +2 -24
  96. package/dist/{index-uhkUA5-U.d.mts → index-CUdaoCYt.d.mts} +13 -23
  97. package/dist/{index-WH7xgvxS.d.mts → index-DyJFTJLA.d.mts} +31 -92
  98. package/dist/index.d.mts +7 -9
  99. package/dist/index.mjs +12 -13
  100. package/dist/{init-CW3kJqNW.mjs → init-BOaNkLYb.mjs} +18 -35
  101. package/dist/{init-Cscs4lab.d.mts → init-CV2_Fw3H.d.mts} +0 -4
  102. package/dist/integrations/event-gateway.d.mts +3 -5
  103. package/dist/integrations/event-gateway.mjs +3 -4
  104. package/dist/integrations/index.d.mts +3 -3
  105. package/dist/integrations/index.mjs +1 -1
  106. package/dist/integrations/jobs/index.d.mts +1 -1
  107. package/dist/integrations/jobs/index.mjs +7 -11
  108. package/dist/integrations/mcp/index.d.mts +7 -39
  109. package/dist/integrations/mcp/index.mjs +8 -14
  110. package/dist/integrations/mcp/testing.d.mts +3 -5
  111. package/dist/integrations/mcp/testing.mjs +3 -4
  112. package/dist/integrations/streamline.d.mts +1 -3
  113. package/dist/integrations/streamline.mjs +4 -5
  114. package/dist/integrations/webhooks.d.mts +2 -4
  115. package/dist/integrations/webhooks.mjs +4 -5
  116. package/dist/integrations/websocket-pushref-redis.d.mts +2 -4
  117. package/dist/integrations/websocket-pushref-redis.mjs +2 -3
  118. package/dist/integrations/websocket-redis.d.mts +2 -4
  119. package/dist/integrations/websocket-redis.mjs +2 -3
  120. package/dist/integrations/websocket.d.mts +2 -2
  121. package/dist/integrations/websocket.mjs +13 -24
  122. package/dist/{interface-JJzwH4Ro.d.mts → interface-BmExzQRD.d.mts} +0 -2
  123. package/dist/{interface-BOk3YnTz.d.mts → interface-WR1U0K7t.d.mts} +0 -2
  124. package/dist/{jsonBody-DPU8yYwA.mjs → jsonBody-DpRpKR_K.mjs} +3 -4
  125. package/dist/{keys-Dgn6OYhl.mjs → keys-FBz6Ull-.mjs} +2 -3
  126. package/dist/{loadResources-BtKj6P1P.mjs → loadResources-Bx1sKPnF.mjs} +4 -5
  127. package/dist/{loadResourcesFromEntry-Bmq6TnB7.mjs → loadResourcesFromEntry-b_jcqbxh.mjs} +3 -4
  128. package/dist/logger/index.d.mts +1 -3
  129. package/dist/logger/index.mjs +2 -2
  130. package/dist/{logger-qQNLlOAU.mjs → logger-CbFcIEBZ.mjs} +3 -5
  131. package/dist/{mcpPlugin-DDfe8jAP.mjs → mcpPlugin-yix548XX.mjs} +41 -60
  132. package/dist/{memory-C0Blueoh.mjs → memory-Bgw5dn8N.mjs} +4 -5
  133. package/dist/{metrics-DYka72iN.mjs → metrics-CZDQWVjS.mjs} +4 -5
  134. package/dist/middleware/index.d.mts +1 -5
  135. package/dist/middleware/index.mjs +4 -5
  136. package/dist/migrations/index.d.mts +0 -2
  137. package/dist/migrations/index.mjs +3 -4
  138. package/dist/{module-BszSyWbd.mjs → module-Dsc_nKL5.mjs} +2 -3
  139. package/dist/{multiTenant-CAtYlW6H.d.mts → multiTenant-XCxAUlru.d.mts} +1 -5
  140. package/dist/{multipartBody-RHvIkNmc.mjs → multipartBody-B85ek8Kj.mjs} +2 -3
  141. package/dist/observeSend-BK-JN1jK.mjs +20 -0
  142. package/dist/{openapi-BrFPc3Ny.mjs → openapi-Co7hl073.mjs} +18 -28
  143. package/dist/outbox-admin/index.d.mts +2 -4
  144. package/dist/outbox-admin/index.mjs +6 -7
  145. package/dist/{outbox-module-gZCHoE4H.d.mts → outbox-module-XvUThpqn.d.mts} +2 -8
  146. package/dist/{outbox-module-DF4Bu_Qa.mjs → outbox-module-mg9kDYkd.mjs} +13 -17
  147. package/dist/permissions/index.d.mts +4 -4
  148. package/dist/permissions/index.mjs +7 -7
  149. package/dist/{permissions-DN1CWH56.mjs → permissions-A1oKtpiC.mjs} +19 -29
  150. package/dist/{pipe-B8uq865o.mjs → pipe-Czpw9U2n.mjs} +3 -4
  151. package/dist/pipeline/index.d.mts +1 -9
  152. package/dist/pipeline/index.mjs +5 -8
  153. package/dist/{plan-DUGfynNg.mjs → plan-KVseuBCL.mjs} +5 -9
  154. package/dist/{plugin-ByU3h-bR.mjs → plugin-DTWt_8C3.mjs} +130 -62
  155. package/dist/plugins/index.d.mts +8 -16
  156. package/dist/plugins/index.mjs +22 -26
  157. package/dist/plugins/response-cache.d.mts +2 -4
  158. package/dist/plugins/response-cache.mjs +10 -10
  159. package/dist/plugins/tracing-entry.d.mts +1 -1
  160. package/dist/plugins/tracing-entry.mjs +3 -4
  161. package/dist/{pluralize-Cdya8zYt.mjs → pluralize-msB9X3yw.mjs} +2 -3
  162. package/dist/presets/filesUpload.d.mts +4 -6
  163. package/dist/presets/filesUpload.mjs +6 -7
  164. package/dist/presets/index.d.mts +3 -19
  165. package/dist/presets/index.mjs +2 -2
  166. package/dist/presets/multiTenant.d.mts +1 -1
  167. package/dist/presets/multiTenant.mjs +7 -7
  168. package/dist/presets/search.d.mts +3 -5
  169. package/dist/presets/search.mjs +3 -4
  170. package/dist/{presets-CCOlKTZw.mjs → presets-qKCehiJM.mjs} +11 -18
  171. package/dist/{projection-BGty6ie4.mjs → projection-ClBqtsIw.mjs} +3 -4
  172. package/dist/{pushref-registry-UxCkoA4C.d.mts → pushref-registry-d86QUaSq.d.mts} +0 -6
  173. package/dist/{queryCachePlugin-B7itTkWu.mjs → queryCachePlugin-3gJj5Rbz.mjs} +8 -10
  174. package/dist/{queryCachePlugin-C2lZjTxk.d.mts → queryCachePlugin-DYQUyeJ9.d.mts} +2 -4
  175. package/dist/{rateLimitKey-DBWO59H9.mjs → rateLimitKey-Kro---xl.mjs} +2 -3
  176. package/dist/{realtime-_59Rlje8.mjs → realtime-Ber8uJN2.mjs} +17 -19
  177. package/dist/{redis-BDgv9Glw.d.mts → redis-RpDMemdm.d.mts} +2 -4
  178. package/dist/{redis-stream-BMk-bpQS.d.mts → redis-stream-CS1N9dwM.d.mts} +1 -3
  179. package/dist/{redisShapes-CQksY67q.d.mts → redisShapes-CqBXTn_s.d.mts} +0 -2
  180. package/dist/registry/index.d.mts +2 -12
  181. package/dist/registry/index.mjs +3 -3
  182. package/dist/{registry-uG4wr541.mjs → registry-BA-_vFYk.mjs} +7 -12
  183. package/dist/{renewingLease-CiU3ZynH.mjs → renewingLease-CMY8YOcc.mjs} +2 -3
  184. package/dist/{replyHelpers-Dr2pnXZg.mjs → replyHelpers-DK9P_XSz.mjs} +3 -4
  185. package/dist/{requestContext-DBKIdmDi.mjs → requestContext-GYO_0gEw.mjs} +2 -3
  186. package/dist/{requirement-CbiLdQ1n.d.mts → requirement-CTRQjjQx.d.mts} +0 -2
  187. package/dist/{requirement-DxOaghWD.mjs → requirement-DeNjZIH3.mjs} +2 -3
  188. package/dist/{resourceRateLimit-Wf6d6FL9.d.mts → resourceRateLimit-DCWglD7V.d.mts} +1 -3
  189. package/dist/{resourceRateLimit-BBdj5yRq.mjs → resourceRateLimit-tHLbrtWc.mjs} +3 -4
  190. package/dist/{rolldown-runtime-DpVPUeXF.mjs → rolldown-runtime-Kv1fZdLg.mjs} +2 -3
  191. package/dist/{routeValidator-BNTqM1Eh.mjs → routeValidator-C_H5NanI.mjs} +2 -3
  192. package/dist/{runtimeCapabilities-D_3eUO6V.mjs → runtimeCapabilities-DWqbxkyw.mjs} +2 -3
  193. package/dist/{schedules-CVS7c1nv.mjs → schedules-eO_RzhCU.mjs} +132 -9
  194. package/dist/{schemaConverter-BQbg7loK.mjs → schemaConverter-DBJrPZN4.mjs} +3 -4
  195. package/dist/{schemaIR-CUI3hPQR.mjs → schemaIR-CEScKT2v.mjs} +3 -4
  196. package/dist/schemas/index.d.mts +0 -2
  197. package/dist/schemas/index.mjs +2 -3
  198. package/dist/scim/index.d.mts +0 -12
  199. package/dist/scim/index.mjs +10 -18
  200. package/dist/scope/index.d.mts +2 -6
  201. package/dist/scope/index.mjs +5 -5
  202. package/dist/{scope-DFXngazv.mjs → scope-B-Sm9m_E.mjs} +5 -6
  203. package/dist/{sessionManager-qimlKV0P.d.mts → sessionManager-CdvDF04x.d.mts} +2 -4
  204. package/dist/{shutdown-BCXCwghd.mjs → shutdown-DzLFbe27.mjs} +2 -3
  205. package/dist/{simpleEqualityMatcher-5jOzYQ_L.mjs → simpleEqualityMatcher-DOJhwQ8g.mjs} +2 -3
  206. package/dist/{sse-BilBz766.mjs → sse-2972pVwV.mjs} +8 -9
  207. package/dist/{sseStream-BG_uJL6J.mjs → sseStream-AWLEeNV-.mjs} +3 -4
  208. package/dist/{storage-Cx9Sz3Ou.d.mts → storage-odC5MNKN.d.mts} +0 -2
  209. package/dist/{store-helpers-CzLZdVa1.mjs → store-helpers-VzjgVTkM.mjs} +2 -3
  210. package/dist/{streaming-DgUvMWlv.mjs → streaming-DvraWW6x.mjs} +2 -3
  211. package/dist/{subscriberIdentity-EWnIZ-U8.mjs → subscriberIdentity-Bya56jsg.mjs} +2 -3
  212. package/dist/{tenancy-CVMvO5DH.mjs → tenancy-DSa_0hhw.mjs} +3 -4
  213. package/dist/{tenantPreparation-DIH-GX4g.mjs → tenantPreparation-BrpkQre3.mjs} +5 -6
  214. package/dist/testing/cleanupStoreContract.d.mts +2 -4
  215. package/dist/testing/cleanupStoreContract.mjs +2 -3
  216. package/dist/testing/index.d.mts +6 -32
  217. package/dist/testing/index.mjs +24 -37
  218. package/dist/testing/outboxStoreContract.d.mts +1 -3
  219. package/dist/testing/outboxStoreContract.mjs +3 -4
  220. package/dist/testing/requiredPorts.d.mts +2 -4
  221. package/dist/testing/requiredPorts.mjs +3 -4
  222. package/dist/testing/storageContract.d.mts +2 -4
  223. package/dist/testing/storageContract.mjs +2 -3
  224. package/dist/{timing-q9NITK04.mjs → timing-6rQTuCwg.mjs} +3 -5
  225. package/dist/{tracing-Dro5eH6j.d.mts → tracing-JSFiBl5r.d.mts} +0 -2
  226. package/dist/{transactionContext-NHmhDIOF.mjs → transactionContext-DaxYUEgH.mjs} +2 -3
  227. package/dist/{typeGuards-CPYR9RCg.mjs → typeGuards-UKnX8wPX.mjs} +2 -3
  228. package/dist/types/index.d.mts +4 -4
  229. package/dist/types/index.mjs +1 -1
  230. package/dist/types/storage.d.mts +1 -1
  231. package/dist/types/storage.mjs +1 -1
  232. package/dist/{types-ByHn9rEO.d.mts → types-0Dqlbgn8.d.mts} +0 -2
  233. package/dist/{types-D3Ixsh00.d.mts → types-BYEb_dLW.d.mts} +2 -4
  234. package/dist/{types-BJ-2XqVF.d.mts → types-BeEJm-DV.d.mts} +114 -14
  235. package/dist/{types-DVLddu2q.d.mts → types-C0YJAiL0.d.mts} +0 -2
  236. package/dist/{types-BI4sbUJ3.mjs → types-CuGjhn83.mjs} +5 -6
  237. package/dist/{types-Ddl9OjmE.d.mts → types-DnkIALZ8.d.mts} +0 -4
  238. package/dist/usage/index.d.mts +2 -10
  239. package/dist/usage/index.mjs +8 -12
  240. package/dist/{userHelpers-oBTU3a_k.mjs → userHelpers-oX5_mOVs.mjs} +2 -3
  241. package/dist/utils/index.d.mts +5 -39
  242. package/dist/utils/index.mjs +12 -12
  243. package/dist/{utils-BmE8zRrh.mjs → utils-CjjGOT4E.mjs} +20 -30
  244. package/dist/{validate-Dby08LhR.mjs → validate-4RlTKOJb.mjs} +5 -7
  245. package/dist/{versioning-P6JMNcJr.mjs → versioning-Dk2-19La.mjs} +4 -5
  246. package/dist/{versioning-Bqm_57Qt.d.mts → versioning-S18y2-0C.d.mts} +1 -15
  247. package/dist/{websocket-Cs4awVyD.d.mts → websocket-BGuc-WVZ.d.mts} +1 -15
  248. package/dist/{workScope-BcMLKa3G.mjs → workScope-DoBsoVo4.mjs} +3 -4
  249. package/llms.txt +37 -30
  250. package/package.json +9 -8
  251. package/skills/arc/SKILL.md +65 -844
  252. package/skills/arc/references/agent-auth.md +82 -193
  253. package/skills/arc/references/api-reference.md +41 -245
  254. package/skills/arc/references/auth-api-keys.md +99 -0
  255. package/skills/arc/references/auth-better-auth-overlay.md +87 -0
  256. package/skills/arc/references/auth-better-auth.md +78 -0
  257. package/skills/arc/references/auth-permissions.md +100 -0
  258. package/skills/arc/references/auth-strategies.md +122 -0
  259. package/skills/arc/references/boot.md +80 -0
  260. package/skills/arc/references/enterprise-auth.md +65 -81
  261. package/skills/arc/references/events-outbox.md +90 -0
  262. package/skills/arc/references/events.md +75 -440
  263. package/skills/arc/references/integrations-jobs.md +74 -0
  264. package/skills/arc/references/integrations-realtime.md +84 -0
  265. package/skills/arc/references/integrations-webhooks.md +71 -0
  266. package/skills/arc/references/integrations-workflows.md +47 -0
  267. package/skills/arc/references/mcp-auth.md +83 -0
  268. package/skills/arc/references/mcp-custom-tools.md +125 -0
  269. package/skills/arc/references/mcp-setup.md +115 -0
  270. package/skills/arc/references/mcp-testing.md +63 -0
  271. package/skills/arc/references/multi-tenancy.md +56 -230
  272. package/skills/arc/references/permissions-scope.md +81 -0
  273. package/skills/arc/references/production-api.md +119 -0
  274. package/skills/arc/references/production-audit.md +101 -0
  275. package/skills/arc/references/production-boot.md +91 -0
  276. package/skills/arc/references/production-caching.md +63 -0
  277. package/skills/arc/references/production-distributed.md +75 -0
  278. package/skills/arc/references/production-idempotency.md +83 -0
  279. package/skills/arc/references/production-observability.md +83 -0
  280. package/skills/arc/references/production-realtime.md +70 -0
  281. package/skills/arc/references/production-reliability.md +100 -0
  282. package/skills/arc/references/production-shutdown.md +43 -0
  283. package/skills/arc/references/querying.md +76 -0
  284. package/skills/arc/references/resources.md +97 -0
  285. package/skills/arc/references/schedules.md +79 -0
  286. package/skills/arc/references/scim.md +61 -208
  287. package/skills/arc/references/tenancy-scope-install.md +82 -0
  288. package/skills/arc/references/testing.md +101 -144
  289. package/skills/arc/references/usage-cleanup-capabilities.md +45 -0
  290. package/skills/arc/references/validation.md +91 -0
  291. package/skills/arc/references/writes-hooks-errors.md +80 -0
  292. package/skills/arc-code-review/SKILL.md +67 -114
  293. package/skills/arc-code-review/references/arc-cheatsheet.md +68 -167
  294. package/skills/arc-code-review/references/mongokit-repositories.md +104 -0
  295. package/skills/arc-code-review/references/recipe-events-cache-jobs.md +112 -0
  296. package/skills/arc-code-review/references/recipe-resource.md +100 -0
  297. package/skills/arc-code-review/references/recipe-schemas-fields.md +93 -0
  298. package/skills/arc-code-review/references/recipe-scope-permissions.md +82 -0
  299. package/skills/arc-code-review/references/scaffolding.md +61 -198
  300. package/skills/arc-code-review/references/severity.md +49 -102
  301. package/skills/arc-code-review/references/smells-auth-scope.md +80 -0
  302. package/skills/arc-code-review/references/smells-data-events.md +66 -0
  303. package/skills/arc-code-review/references/smells-imports-style.md +59 -0
  304. package/skills/arc-code-review/references/smells-platform.md +89 -0
  305. package/skills/arc-code-review/references/smells-routes-schemas.md +66 -0
  306. package/skills/arc-module-publishing/SKILL.md +82 -208
  307. package/skills/arc-module-publishing/references/action-presets-and-plugins.md +87 -0
  308. package/skills/arc-module-publishing/references/build-and-types.md +73 -0
  309. package/skills/arc-module-publishing/references/module-lifecycle.md +101 -0
  310. package/skills/arc-module-publishing/references/package-manifest.md +34 -122
  311. package/skills/arc-module-publishing/references/publishing-workflow.md +44 -140
  312. package/skills/arc-module-publishing/references/resource-assembly.md +102 -0
  313. package/skills/arc-module-publishing/references/testing-packages.md +82 -0
  314. package/skills/arc/references/auth.md +0 -729
  315. package/skills/arc/references/integrations.md +0 -452
  316. package/skills/arc/references/mcp.md +0 -691
  317. package/skills/arc/references/production.md +0 -835
  318. package/skills/arc-code-review/references/anti-patterns.md +0 -1008
  319. package/skills/arc-code-review/references/migration-recipes.md +0 -649
  320. package/skills/arc-code-review/references/mongokit-migration.md +0 -360
  321. package/skills/arc-module-publishing/references/authoring-modules.md +0 -327
@@ -1,729 +0,0 @@
1
- # Arc Authentication & Authorization
2
-
3
- ## Decision tree — which pattern fits your auth provider
4
-
5
- Arc deliberately ships **zero per-provider code**. The contract is `request.scope`. Three shapes cover every realistic provider:
6
-
7
- | Where does user data live? | Who writes it? | Pattern |
8
- |---|---|---|
9
- | Your DB | You | **arc JWT / authenticator** — define your User model normally; no overlay |
10
- | The provider's cloud | Provider (Clerk, Auth0, Supabase Auth...) | **authenticate callback** — verify provider JWT, map claims to `request.scope`. Optionally webhook-sync to a local user table for joins |
11
- | Your DB | A library writes it via its own driver (Better Auth) | **kit overlay** — `@classytic/mongokit/better-auth`, sqlite hand-rolled — gives you arc CRUD + queryparser over the library's tables |
12
-
13
- **Better Auth is the recommended path** when you want both "users live in my DB" AND "I don't want to hand-roll signup / OAuth / 2FA / orgs". It's the only provider that needs the overlay because it's the only one writing your tables.
14
-
15
- For everything else, the canonical primitive is the `authenticate` callback — verify the token, populate `request.scope`. Arc doesn't care which library produced the token.
16
-
17
- ## Auth Strategies (Discriminated Union)
18
-
19
- Auth config uses `type` field to select strategy:
20
-
21
- ### JWT (`type: 'jwt'`)
22
-
23
- ```typescript
24
- const app = await createApp({
25
- auth: {
26
- type: 'jwt',
27
- jwt: {
28
- secret: process.env.JWT_SECRET, // Required, 32+ chars
29
- expiresIn: '15m', // Access token TTL
30
- refreshSecret: process.env.JWT_REFRESH_SECRET,
31
- refreshExpiresIn: '7d',
32
- },
33
- // Optional: custom authenticator with JWT helpers
34
- authenticate: async (request, { jwt }) => {
35
- const token = request.headers.authorization?.split(' ')[1];
36
- if (!token) return null;
37
- const decoded = jwt.verify(token);
38
- return await User.findById(decoded._id);
39
- },
40
- },
41
- });
42
- // Decorates: app.authenticate, app.optionalAuthenticate, app.authorize, app.auth
43
- ```
44
-
45
- **Token lifecycle:**
46
-
47
- ```typescript
48
- // Issue tokens
49
- const tokens = app.auth.issueTokens({ _id: user._id, email, role });
50
- // Returns: { accessToken, refreshToken?, expiresIn, tokenType: 'Bearer' }
51
-
52
- // Verify refresh token (rejects access tokens)
53
- const decoded = app.auth.verifyRefreshToken(refreshToken);
54
- ```
55
-
56
- ### Better Auth (`type: 'betterAuth'`)
57
-
58
- Two pieces — the **request-side bridge** (catch-all `/api/auth/*` route + scope adapter) and the **table-side overlay** (so arc resources can read BA's collections with full pagination / queryparser / OpenAPI).
59
-
60
- #### Request-side bridge
61
-
62
- ```typescript
63
- import { createBetterAuthAdapter } from '@classytic/arc/auth';
64
-
65
- const adapter = createBetterAuthAdapter({
66
- auth, // Your betterAuth() instance
67
- basePath: '/api/auth',
68
- orgContext: true, // Extract org membership into request.scope
69
- });
70
-
71
- const app = await createApp({
72
- auth: { type: 'betterAuth', betterAuth: adapter },
73
- });
74
-
75
- // BA-on-Mongo + `beforeBoot` (2.22): BA's mongodbAdapter needs an OPEN
76
- // connection (`mongoose.connection.getClient()` throws pre-connect), so pass
77
- // a THUNK — resolved during auth registration, after beforeBoot connects:
78
- const app2 = await createApp({
79
- beforeBoot: () => connectDatabase(),
80
- auth: { type: 'betterAuth', betterAuth: () => createBetterAuthAdapter({ auth: getAuth(), orgContext: true }) },
81
- });
82
- ```
83
-
84
- **Org context flow** (when `orgContext: true`):
85
- 1. Gets session via `auth.api.getSession()` (in-process, no HTTP round-trip)
86
- 2. Reads `session.activeOrganizationId`, or falls back to `x-organization-id` header (needed for API key auth where synthetic sessions have no org context)
87
- 3. Looks up org membership via `auth.api.getActiveMember` (or `getActiveMemberRole` with explicit `organizationId` for header-based resolution)
88
- 4. Splits roles: `"admin,recruiter"` → `['admin', 'recruiter']`
89
- 5. Resolves `session.activeTeamId` (if set) against `auth.api.listUserTeams` scoped to the ACTIVE org, and binds it only if the team is one the user belongs to AND carries that `organizationId`. Stale or cross-org team state is dropped, not trusted. Requires **better-auth >=1.7.0** — the `organizationId` query param landed in 1.7.0, and without it a self-query returns teams across every org the user belongs to.
90
- 6. Sets `request.scope`: `{ kind: 'member', organizationId, orgRoles: string[], teamId? }`
91
-
92
- Both `authenticate` and `optionalAuthenticate` run this same flow — an optional-auth route sees the identical scope when a session exists (arc 2.37.1; before that `teamId` was never set on the optional path).
93
-
94
- **Sessions at scale (BA-native knobs — know these before reaching for arc's):**
95
- - **Redis sessions**: use BA's `secondaryStorage` (sessions land there INSTEAD of the DB unless `session.storeSessionInDatabase: true`). Arc's `@classytic/arc/auth/redis` (`SessionStore`) is the JWT-strategy store — different layer, don't mix them.
96
- - **Cookie cache gotcha that keeps orgContext correct**: BA's `session.cookieCache` never caches CUSTOM session fields (e.g. `activeOrganizationId`) — they're re-fetched per request, so arc's org scope can't go stale via the cookie. Cost: enabling cookieCache does NOT skip the org lookup.
97
- - **Rate limiting**: BA ships its own (`rateLimit.storage: 'secondary-storage'`) for auth endpoints; arc's `rateLimit.skipPaths: ['/api/auth/*']` guidance composes — exempt BA routes from arc's bucket, let BA's limiter own its own surface.
98
-
99
- > **Arc 2.13+ requires `auth.api.*`** — pass a real `betterAuth()` instance. The pre-2.13 HTTP fallback for org/team lookups was retired.
100
-
101
- #### Table-side overlay — read BA's tables as arc resources
102
-
103
- Better Auth writes its own tables (`user`, `organization`, `member`, `invitation`, ...) via its own driver. To expose them as arc resources with pagination, queryparser, OpenAPI, audit, permissions, and multi-tenant scope, use the kit-side overlay:
104
-
105
- ##### Mongoose / mongokit (Tier 2 — convenience factory)
106
-
107
- ```typescript
108
- import { betterAuth } from 'better-auth';
109
- import { mongodbAdapter } from '@better-auth/mongo-adapter';
110
- import { organization } from 'better-auth/plugins/organization'; // dedicated path — tree-shaking (BA best practice)
111
- import mongoose from 'mongoose';
112
- import {
113
- createBetterAuthOverlay,
114
- registerBetterAuthStubs,
115
- } from '@classytic/mongokit/better-auth';
116
-
117
- const auth = betterAuth({
118
- database: mongodbAdapter(mongoose.connection.getClient().db()),
119
- plugins: [organization()],
120
- // ...
121
- });
122
-
123
- // Bulk-register stubs so `populate('user')` works app-wide.
124
- registerBetterAuthStubs(mongoose, { plugins: ['organization'] });
125
-
126
- // Per-resource overlay — ready to plug into defineResource.
127
- const orgAdapter = createBetterAuthOverlay({
128
- mongoose,
129
- collection: 'organization',
130
- });
131
-
132
- defineResource({
133
- name: 'organization',
134
- adapter: orgAdapter,
135
- tenantField: false, // platform-wide, not tenant-scoped
136
- permissions: { list: requireAuth(), get: requireAuth() },
137
- });
138
- ```
139
-
140
- ##### Mongoose / mongokit (Tier 1 — hand-rolled, full control)
141
-
142
- When you need custom validators, `toJSON` transforms (e.g., strip `password`), domain methods on the Repository, or special indexes — drop the factory and hand-roll:
143
-
144
- ```typescript
145
- const userSchema = new mongoose.Schema(
146
- {
147
- name: String,
148
- email: String,
149
- role: { type: [String], enum: SYSTEM_ROLES, default: ['user'] },
150
- isActive: { type: Boolean, default: true },
151
- // BA owns these via strict:false overlay; only declare what you need typed
152
- },
153
- { strict: false, timestamps: false, collection: 'user' },
154
- );
155
- userSchema.set('toJSON', { transform: (_, ret) => { delete ret.password; return ret; } });
156
- const User = mongoose.model('User', userSchema);
157
-
158
- class UserRepository extends Repository<IUser> {
159
- async getByRole(role: string) { return this.getAll({ filters: { role, isActive: true } }); }
160
- }
161
-
162
- defineResource({
163
- name: 'user',
164
- adapter: createMongooseAdapter(User, new UserRepository(User)),
165
- tenantField: false,
166
- fields: { password: fields.hidden() }, // belt-and-braces
167
- permissions: { list: requireRoles(['admin']) },
168
- });
169
- ```
170
-
171
- ##### sqlite / sqlitekit (Tier 2 — convenience factory)
172
-
173
- Same parallel structure as mongokit. The factory derives the Drizzle table dynamically from BA's resolved schema (`auth.$context.tables`) — `additionalFields`, `modelName` overrides, and plugin schema additions all flow through automatically.
174
-
175
- ```typescript
176
- import Database from 'better-sqlite3';
177
- import { drizzle } from 'drizzle-orm/better-sqlite3';
178
- import { betterAuth } from 'better-auth';
179
- import { organization } from 'better-auth/plugins/organization'; // dedicated path — tree-shaking (BA best practice)
180
- import { createBetterAuthOverlay } from '@classytic/sqlitekit/better-auth';
181
-
182
- const sqlite = new Database('app.db');
183
- const auth = betterAuth({ database: sqlite, plugins: [organization()] });
184
- const db = drizzle(sqlite);
185
-
186
- // Async because we await BA's resolved schema. Resolves once at boot.
187
- const orgAdapter = await createBetterAuthOverlay({ auth, db, collection: 'organization' });
188
-
189
- defineResource({ name: 'organization', adapter: orgAdapter, idField: 'id', tenantField: false });
190
- ```
191
-
192
- Need a column BA doesn't declare (host-side audit, custom JSON column, etc.)? Pass `additionalColumns`:
193
-
194
- ```typescript
195
- import { integer, text } from 'drizzle-orm/sqlite-core';
196
-
197
- const orgAdapter = await createBetterAuthOverlay({
198
- auth, db, collection: 'organization',
199
- additionalColumns: {
200
- syncedAt: integer('syncedAt'),
201
- branchType: text('branchType'), // matches your BA additionalFields entry
202
- },
203
- });
204
- ```
205
-
206
- ##### sqlite / sqlitekit (Tier 1 — hand-roll for full control)
207
-
208
- When you need a custom `SqliteRepository` subclass with domain methods, custom Drizzle column modes (`integer({ mode: 'timestamp_ms' })` for typed Date), or table-level extensions the factory can't express — drop the factory:
209
-
210
- ```typescript
211
- import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
212
- import { drizzle } from 'drizzle-orm/better-sqlite3';
213
- import { SqliteRepository } from '@classytic/sqlitekit/repository';
214
- import { createDrizzleAdapter } from '@classytic/sqlitekit/adapter';
215
-
216
- export const organizationTable = sqliteTable('organization', {
217
- id: text('id').primaryKey().notNull(),
218
- name: text('name').notNull(),
219
- slug: text('slug'),
220
- logo: text('logo'),
221
- createdAt: integer('createdAt', { mode: 'timestamp_ms' }).notNull(), // typed Date
222
- metadata: text('metadata'),
223
- });
224
-
225
- class OrgRepository extends SqliteRepository<{ id: string; name: string }> {
226
- async getActive() { return this.getAll({ filters: { /* ... */ } }); }
227
- }
228
-
229
- const db = drizzle(sqliteDatabase);
230
- const repo = new OrgRepository({ db, table: organizationTable, idField: 'id' });
231
- const orgAdapter = createDrizzleAdapter({ table: organizationTable, repository: repo });
232
- ```
233
-
234
- Reference playgrounds: [`playground/better-auth/mongo/`](../../../playground/better-auth/mongo/) · [`playground/better-auth/sqlite/`](../../../playground/better-auth/sqlite/). Both pass identical 17-scenario smoke suites — same `defineResource` host code, only the kit import differs.
235
-
236
- > **Removed in arc 2.13** — `@classytic/arc/auth/mongoose` (the old `registerBetterAuthMongooseModels`). The helper moved to `@classytic/mongokit/better-auth` as `registerBetterAuthStubs`. Same behavior, kit-owned location.
237
-
238
- ### Better Auth plugin integration matrix
239
-
240
- The `auth.api.*` direct in-process API map and `auth.$context.tables` schema introspection let arc and the kit overlays be **plugin-agnostic** — wire any combination of BA plugins, the overlay reads what's there. No per-plugin code in arc/mongokit/sqlitekit.
241
-
242
- | BA plugin | Adds tables | Tested in | What you need on the arc side |
243
- |---|---|---|---|
244
- | (core) — `emailAndPassword`, OAuth providers | `user`, `session`, `account`, `verification` | both kits + playground | Nothing extra. Optionally overlay `user` as a resource. |
245
- | `organization()` (built-in) | `organization`, `member`, `invitation` | both kits + playground | `createBetterAuthAdapter({ orgContext: true })`; overlay `organization` / `member` as resources. |
246
- | `organization({ teams: true })` | + `team`, `teamMember` | mongokit | `requireTeamMembership()` works on `scope.teamId`. Needs **better-auth >=1.7.0** (see step 5 of the org-context flow). |
247
- | `twoFactor()` (built-in) | `twoFactor` | both kits | Picked up automatically by overlay; expose `twoFactor` as a resource if needed. |
248
- | `admin()` (built-in) | (field-only, augments `user`) | both kits | `requireRoles(['admin'])` reads the platform role; no extra plumbing. |
249
- | `bearer()` (built-in) | (none — header strategy) | CLI scaffold | Token comes via `Authorization: Bearer <session>` instead of cookie — same `auth.api.getSession()` path. Use for SPA / mobile clients. |
250
- | `apiKey()` from **`@better-auth/api-key`** (separate npm package) | `apikey` | both kits | Arc auto-resolves API key sessions via `enableSessionForAPIKeys: true`; falls back to `x-organization-id` header for org context. See "API Key Auth" below. |
251
- | `magicLink()`, `username()`, `passkey()`, `oidcProvider()`, `mcp()`, `deviceAuthorization()` | varies (passkey: `passkey`; oidc: `oauthApplication`/`oauthAccessToken`; deviceAuth: `deviceCode`) | not in kit tests | Overlay reads them automatically — pass plugin name to `registerBetterAuthStubs` or list under `extraCollections`. |
252
-
253
- #### Multi-plugin recipe — combine without overlay code changes
254
-
255
- ```typescript
256
- import { betterAuth } from 'better-auth';
257
- import { mongodbAdapter } from '@better-auth/mongo-adapter';
258
- // Dedicated paths per plugin — tree-shaking (BA best practice; never the barrel)
259
- import { admin } from 'better-auth/plugins/admin';
260
- import { organization } from 'better-auth/plugins/organization';
261
- import { twoFactor } from 'better-auth/plugins/two-factor';
262
- import { bearer } from 'better-auth/plugins/bearer';
263
- import { apiKey } from '@better-auth/api-key';
264
- import { createBetterAuthOverlay, registerBetterAuthStubs } from '@classytic/mongokit/better-auth';
265
-
266
- const auth = betterAuth({
267
- database: mongodbAdapter(mongoose.connection.getClient().db()),
268
- emailAndPassword: { enabled: true },
269
- plugins: [
270
- organization(), // adds organization, member, invitation
271
- twoFactor(), // adds twoFactor
272
- admin(), // augments user with role/banned/banReason
273
- bearer(), // header-based session for SPA/mobile
274
- apiKey({ enableSessionForAPIKeys: true }), // adds apikey
275
- ],
276
- });
277
-
278
- // One stub-registration call covers the populate('user') / ref:'organization' surface
279
- // for every plugin you've enabled. apikey isn't ref'd by populate so it goes into extras.
280
- registerBetterAuthStubs(mongoose, {
281
- plugins: ['organization'],
282
- extraCollections: ['apikey'],
283
- });
284
-
285
- // Overlay any of the resulting tables — picks modelName + additionalFields up
286
- // automatically from auth.$context.tables. Tested combinations: organization,
287
- // member, invitation, apikey, twoFactor, user.
288
- const orgAdapter = await createBetterAuthOverlay({ auth, mongoose, collection: 'organization' });
289
- const memberAdapter = await createBetterAuthOverlay({ auth, mongoose, collection: 'member' });
290
- const apiKeyAdapter = await createBetterAuthOverlay({ auth, mongoose, collection: 'apikey' });
291
- ```
292
-
293
- Sqlitekit is symmetric — replace `{ mongoose }` with `{ db }` (a Drizzle binding), use `additionalColumns` instead of `additionalFields`, and skip the stub registration step (no `populate()` in Drizzle).
294
-
295
- #### Multi-role members — `role: "admin,recruiter,viewer"`
296
-
297
- BA's organization plugin stores multiple roles in a single comma-separated `member.role` string (be-prod canonical). The overlay round-trips this unchanged; arc's `requireRoles()` and `requireOrgRole()` split on comma when reading `scope.orgRoles`:
298
-
299
- ```typescript
300
- // BA writes: arc reads:
301
- // member.role = "admin,recruiter,viewer" → scope.orgRoles = ['admin', 'recruiter', 'viewer']
302
-
303
- defineResource({
304
- name: 'invoice',
305
- permissions: {
306
- create: requireOrgRole('admin'), // matches — admin is in the list
307
- delete: requireOrgRole('owner'), // does NOT match — string-equality on each role
308
- },
309
- });
310
- ```
311
-
312
- Filtering `member` by exact role string with `?role=admin` will NOT match a multi-role member — the column is opaque text, not an array. Filter with `role[like]=admin` (case-sensitive substring) or model membership server-side.
313
-
314
- #### `registerBetterAuthStubs(mongoose, opts?)` — full options (mongokit only)
315
-
316
- Bulk-registers `strict: false` Mongoose stubs so `populate('user')` / `ref: 'organization'` work app-wide without per-collection schemas. Idempotent — calling twice returns `[]` the second time.
317
-
318
- ```typescript
319
- registerBetterAuthStubs(mongoose, {
320
- plugins: ['organization', 'organization-teams', 'mcp', 'oidcProvider', 'deviceAuthorization'],
321
- extraCollections: ['passkey', 'ssoProvider', 'apikey'], // anything not in the plugin map
322
- modelOverrides: { organization: 'OrgRoot' }, // BA modelName → Mongoose model name
323
- usePlural: true, // register 'organizations' alongside 'organization'
324
- });
325
- ```
326
-
327
- Plugin keys recognized by the registry: `organization`, `organization-teams`, `twoFactor`, `jwt`, `oidcProvider`, `mcp`, `deviceAuthorization`. Field-only plugins (`admin`, `username`, `magicLink`, `bearer`, `apiKey` field augmentations) need no entry.
328
-
329
- **Gotcha — stub already registered + `additionalFields` requested:** `createBetterAuthOverlay` throws when the host called `registerBetterAuthStubs` for the same collection AND now passes `additionalFields` to the overlay. The stub model is already locked to `strict: false` with no extra paths; adding fields after the fact would silently no-op. Call order: register stubs OR overlay-with-additional-fields, not both for the same collection.
330
-
331
- ### API Key Auth (Better Auth `apiKey()` plugin)
332
-
333
- `apiKey` ships as a **separate npm package**: `@better-auth/api-key`. It is NOT exported from `better-auth/plugins` like `organization` / `twoFactor` / `bearer`. Common mistake.
334
-
335
- ```typescript
336
- import { apiKey } from '@better-auth/api-key'; // ✓ separate package
337
- // import { apiKey } from 'better-auth/plugins'; // ✗ does not exist
338
-
339
- const auth = betterAuth({
340
- // ...
341
- plugins: [apiKey({ enableSessionForAPIKeys: true })],
342
- });
343
- ```
344
-
345
- When enabled, Arc's adapter automatically:
346
- - Resolves API key sessions via `enableSessionForAPIKeys: true` (the plugin's option, not arc's).
347
- - Falls back to `x-organization-id` header for org context — API key sessions have no `activeOrganizationId`, so without the header `scope.kind` is `'authenticated'`, not `'member'`.
348
- - Generates OpenAPI security schemes dynamically — `apiKeyAuth` only appears in the spec when the plugin is active.
349
-
350
- ```
351
- x-api-key: ak_live_... # Authentication
352
- x-organization-id: org_abc123 # Org context (required for org-scoped resources)
353
- ```
354
-
355
- **OpenAPI security semantics** (auto-derived; no manual schema):
356
- - Resource paths: `security: [{ bearerAuth: [] }, { apiKeyAuth: [], orgHeader: [] }]`
357
- - Meaning: bearer token alone **OR** (API key **AND** org header together)
358
- - Auth endpoints: `security: [{ cookieAuth: [] }, { bearerAuth: [] }, { apiKeyAuth: [] }]`
359
- - No org header required for auth management endpoints
360
-
361
- **Overlay the `apikey` table as an arc resource** (admin-only, for issuing/revoking keys via REST):
362
-
363
- ```typescript
364
- const apiKeyAdapter = await createBetterAuthOverlay({ auth, mongoose, collection: 'apikey' });
365
- // or sqlitekit: { auth, db, collection: 'apikey' }
366
-
367
- defineResource({
368
- name: 'apikey',
369
- adapter: apiKeyAdapter,
370
- tenantField: false, // platform-managed, not tenant-scoped
371
- permissions: {
372
- list: requireRoles(['admin']),
373
- get: requireRoles(['admin']),
374
- create: denyAll('use POST /api/auth/api-key/create'), // BA owns the issuance path
375
- delete: requireRoles(['admin']),
376
- },
377
- fields: {
378
- key: fields.hidden(), // never expose the raw key after creation
379
- },
380
- });
381
- ```
382
-
383
- The plugin also adds a required `configId` field on `apikey` rows and uses `referenceId` (not `userId`) — note when seeding test fixtures.
384
-
385
- ### Bearer plugin — SPA / mobile clients
386
-
387
- For non-cookie clients (React Native, native mobile, headless SPA), enable `bearer()` so sessions travel as `Authorization: Bearer <session-token>` instead of cookies. Same `auth.api.getSession()` path, just a different transport.
388
-
389
- ```typescript
390
- import { bearer } from 'better-auth/plugins/bearer'; // dedicated path — tree-shaking
391
- const auth = betterAuth({ plugins: [bearer(), organization()] });
392
- ```
393
-
394
- Arc's adapter handles both transports identically — you don't switch arc config based on which is enabled. Enable both `cookie` (default) + `bearer` for hybrid web + mobile apps.
395
-
396
- ### CLI scaffolding for Better Auth
397
-
398
- `arc init my-api --better-auth --mongokit --ts` prompts for session strategy and api-key:
399
-
400
- ```
401
- Session strategy [1=Cookie (web app, default), 2=Bearer token (mobile/SPA), 3=Both]: 3
402
- Enable API key plugin (machine-to-machine auth via @better-auth/api-key)? [y/N]: y
403
- ```
404
-
405
- The scaffold wires `registerBetterAuthStubs(mongoose, { plugins: [...], extraCollections: ['apikey'] })`, conditional plugin imports, and the matching peer dep entries (`@better-auth/api-key` only if you opted in).
406
-
407
- ### Custom Plugin (`type: 'custom'`)
408
-
409
- ```typescript
410
- auth: { type: 'custom', plugin: myAuthPlugin }
411
- // Plugin must decorate fastify.authenticate
412
- ```
413
-
414
- ### Custom Function (`type: 'authenticator'`)
415
-
416
- ```typescript
417
- auth: {
418
- type: 'authenticator',
419
- authenticate: async (req, reply) => {
420
- const session = await validateSession(req);
421
- if (!session) reply.code(401).send({ error: 'Unauthorized' });
422
- req.user = session.user;
423
- },
424
- }
425
- ```
426
-
427
- ### Clerk / Auth0 / Supabase Auth / any cloud SaaS
428
-
429
- User data lives in the provider's cloud, not your DB. No tables to overlay — just verify the provider's JWT and map claims to `request.scope`. The same shape works for any cloud auth provider; only the verifier function differs.
430
-
431
- ```typescript
432
- import { verifyToken } from '@clerk/backend';
433
-
434
- await createApp({
435
- auth: {
436
- type: 'jwt', // arc's plugin handles plumbing
437
- jwt: { secret: 'unused' }, // overridden by authenticate
438
- authenticate: async (request) => {
439
- const token = request.headers.authorization?.slice(7);
440
- if (!token) return null;
441
- const claims = await verifyToken(token, { secretKey: process.env.CLERK_SECRET_KEY! });
442
-
443
- // Map provider claims → arc scope (same shape BA produces)
444
- if (claims.org_id) {
445
- request.scope = {
446
- kind: 'member',
447
- userId: claims.sub,
448
- organizationId: claims.org_id,
449
- orgRoles: [claims.org_role],
450
- userRoles: claims.org_role ? [claims.org_role] : [],
451
- };
452
- }
453
- return { id: claims.sub, email: claims.email };
454
- },
455
- },
456
- });
457
- ```
458
-
459
- **Optional: local user table for joins.** If your resources reference users (`Order.userId → populate`), webhook-sync from Clerk into a local `users` collection and treat it as a normal arc resource — no overlay needed because *you* write it.
460
-
461
- ```typescript
462
- // POST /webhooks/clerk
463
- fastify.post('/webhooks/clerk', { config: { rawBody: true } }, async (req, reply) => {
464
- // Verify Clerk webhook signature, then upsert into your User collection.
465
- await User.findOneAndUpdate({ _id: payload.data.id }, payload.data, { upsert: true });
466
- return { ok: true };
467
- });
468
- ```
469
-
470
- ### Disabled
471
-
472
- ```typescript
473
- auth: false
474
- ```
475
-
476
- ## Fastify Decorators
477
-
478
- | Decorator | Description | JWT | Better Auth |
479
- |-----------|-------------|-----|-------------|
480
- | `fastify.authenticate` | Verify JWT/session, set `request.user` | Yes | Yes |
481
- | `fastify.optionalAuthenticate` | Parse token if present, skip if absent | Yes | Yes |
482
- | `fastify.authorize(...roles)` | Check `user.role`. `authorize('*')` = any auth user | Yes | No |
483
-
484
- ## Permission Functions
485
-
486
- ```typescript
487
- import {
488
- allowPublic, requireAuth, requireRoles, requireOwnership,
489
- requireOrgMembership, requireOrgRole, requireTeamMembership,
490
- // Platform-only role gate — an ORG role can never satisfy it. Required by
491
- // globally-scoped surfaces (jobsPlugin managementRoutes) that cannot filter by tenant.
492
- requirePlatformRole,
493
- allOf, anyOf, when, denyAll,
494
- } from '@classytic/arc';
495
- ```
496
-
497
- | Function | Description |
498
- |----------|-------------|
499
- | `allowPublic()` | No authentication |
500
- | `allowPublic({ policy })` | No authentication, rows narrowed by a filter (or a per-caller resolver; `{}` = unrestricted) |
501
- | `requireAuth()` | Any authenticated user |
502
- | `requireRoles(['admin'])` | At least one role matches |
503
- | `requireOwnership('userId')` | Resource owner only (elevated bypasses) |
504
- | `requireOrgMembership()` | Must be org member |
505
- | `requireOrgRole('admin', 'owner')` | Must have org-level role |
506
- | `requireTeamMembership()` | Must have active team |
507
- | `allOf(p1, p2)` | AND — all must pass |
508
- | `anyOf(p1, p2)` | OR — any can pass |
509
- | `denyAll(reason?)` | Always deny |
510
-
511
- **Custom permission:**
512
-
513
- ```typescript
514
- import { allow, deny, type PermissionCheck } from '@classytic/arc/permissions';
515
-
516
- const requirePro = (): PermissionCheck => async (ctx) => {
517
- if (!ctx.user) return deny('Auth required');
518
- return ctx.user.plan === 'pro' ? allow() : deny('Pro plan required');
519
- };
520
- ```
521
-
522
- ## Dynamic ACL (DB-managed)
523
-
524
- ```typescript
525
- import { createDynamicPermissionMatrix } from '@classytic/arc/permissions';
526
-
527
- const acl = createDynamicPermissionMatrix({
528
- resolveRolePermissions: async ({ request }) => aclService.getRoleMatrix(orgId),
529
- cacheStore: new RedisCacheStore({ client: redis, prefix: 'acl:' }),
530
- });
531
-
532
- permissions: { list: acl.canAction('product', 'read') }
533
- ```
534
-
535
- - Reads org roles from `request.scope.orgRoles`
536
- - Elevated scope bypasses all checks
537
- - Supports `*` wildcard for resource/action
538
- - Cache failures fail open to resolver
539
-
540
- ## Org-Scoped Permission Checks
541
-
542
- ```typescript
543
- import { allowPublic, requireAuth, requireOrgRole } from '@classytic/arc/permissions';
544
-
545
- // Resource-level permission check on the active org's member.role
546
- defineResource({
547
- name: 'invoice',
548
- permissions: {
549
- list: requireAuth(),
550
- create: requireOrgRole('admin', 'owner'),
551
- },
552
- });
553
- ```
554
-
555
- The 2.16 release removed the legacy `@classytic/arc/org` REST plugin
556
- and its `orgGuard` / `requireOrg` middleware (zero verified consumers).
557
- The PermissionCheck variant — `requireOrgRole` from
558
- `@classytic/arc/permissions` — is the canonical path: it composes with
559
- `anyOf` / `allOf`, integrates with the resource pipeline, and reads
560
- `request.scope.orgRoles` (set by auth adapters). For preHandler-style
561
- org enforcement on custom routes outside a resource, build a one-line
562
- preHandler that throws if `getOrgId(request.scope)` is missing.
563
-
564
- ## Request Scope
565
-
566
- ```typescript
567
- import type { RequestScope } from '@classytic/arc/scope';
568
- import { getUserId, getUserRoles, getOrgId, getOrgRoles, getTeamId } from '@classytic/arc/scope';
569
-
570
- // Variants (userId/userRoles on all authenticated variants):
571
- // { kind: 'public' }
572
- // { kind: 'authenticated', userId?, userRoles? }
573
- // { kind: 'member', userId?, userRoles, organizationId, orgRoles: string[], teamId? }
574
- // { kind: 'elevated', userId?, organizationId?, elevatedBy }
575
-
576
- const userId = getUserId(request.scope); // string | undefined
577
- const globalRoles = getUserRoles(request.scope); // string[]
578
- const orgId = getOrgId(request.scope); // string | undefined
579
- const orgRoles = getOrgRoles(request.scope); // string[]
580
- ```
581
-
582
- ## Two Role Layers
583
-
584
- | Layer | Source | Scope Field | Checked By |
585
- |-------|--------|-------------|------------|
586
- | Global roles | `user.role` | `scope.userRoles` | `requireRoles()`, `authorize()` |
587
- | Org roles | Org membership | `scope.orgRoles` | `requireOrgRole()`, `requireOrgMembership()` |
588
-
589
- ## Role Hierarchy
590
-
591
- ```typescript
592
- import { createRoleHierarchy } from '@classytic/arc/permissions';
593
-
594
- const hierarchy = createRoleHierarchy({
595
- superadmin: ['admin'],
596
- admin: ['branch_manager'],
597
- });
598
-
599
- hierarchy.expand(['superadmin']); // → ['superadmin', 'admin', 'branch_manager']
600
- hierarchy.includes(['admin'], 'branch_manager'); // → true
601
- ```
602
-
603
- ## Token Extraction & Revocation
604
-
605
- ```typescript
606
- auth: {
607
- type: 'jwt', jwt: { secret },
608
- tokenExtractor: (req) => req.cookies?.['auth-token'] ?? null,
609
- isRevoked: async (decoded) => redis.sismember('revoked', decoded.jti),
610
- }
611
- ```
612
-
613
- ## Service Identity (Machine Principals)
614
-
615
- Arc distinguishes **machine callers** (API clients, spawned agents, cron workers) from **human users** via `RequestScope.service` — a first-class scope kind with `clientId` + OAuth-style `scopes`. Any auth mechanism (arc JWT, API keys, Better Auth client credentials, mTLS, gateway headers) can install it; arc does not ship a "service token" issuer — the app picks its credential flow and maps the result to scope.
616
-
617
- Install service scope from your `authenticate` callback — arc's default JWT verify installs `member` scope by design, so custom authenticators are the extension point:
618
-
619
- ```typescript
620
- await createApp({
621
- auth: {
622
- type: 'jwt',
623
- jwt: { secret: process.env.JWT_SECRET! },
624
- authenticate: async (request, { jwt }) => {
625
- const token = request.headers.authorization?.slice(7);
626
- if (!token) return null;
627
- const decoded = jwt.verify(token) as {
628
- clientId?: string; userId?: string;
629
- organizationId?: string; scopes?: string[];
630
- };
631
- // Machine principal — clientId present, no human user record.
632
- if (decoded.clientId) {
633
- request.scope = {
634
- kind: 'service',
635
- clientId: decoded.clientId,
636
- organizationId: decoded.organizationId ?? '',
637
- scopes: decoded.scopes ?? [],
638
- };
639
- return { clientId: decoded.clientId }; // returned value → request.user
640
- }
641
- // Human principal — fall through to user lookup.
642
- return await User.findById(decoded.userId);
643
- },
644
- },
645
- });
646
- ```
647
-
648
- Gate routes on service identity using the scope helpers + a permission builder:
649
-
650
- ```typescript
651
- import { isService, getClientId, getServiceScopes } from '@classytic/arc/scope';
652
- import { allow, deny, type PermissionCheck } from '@classytic/arc/permissions';
653
-
654
- const requireScope = (scope: string): PermissionCheck => (ctx) => {
655
- if (!isService(ctx.request.scope)) return deny('service only');
656
- const has = getServiceScopes(ctx.request.scope).includes(scope);
657
- return has ? allow() : deny(`missing scope: ${scope}`);
658
- };
659
-
660
- defineResource({
661
- name: 'order',
662
- permissions: { create: requireScope('orders:write') },
663
- });
664
- ```
665
-
666
- **Mixing humans and services on the same route** — compose arc's builders:
667
-
668
- ```typescript
669
- // Humans with 'editor' role OR services with 'orders:write' scope
670
- permissions: {
671
- create: anyOf(requireOrgRole('editor'), requireScope('orders:write')),
672
- }
673
- ```
674
-
675
- **Audit differentiation** — because `scope.kind === 'service'` carries `clientId` instead of `userId`, your audit plugin's `actor` resolver can tag machine actions distinctly:
676
-
677
- ```typescript
678
- auditPlugin({
679
- actor: (request) =>
680
- isService(request.scope)
681
- ? { kind: 'service', clientId: getClientId(request.scope) }
682
- : { kind: 'user', userId: getUserId(request.scope) },
683
- });
684
- ```
685
-
686
- **Rate-limit separation** — gate a separate bucket per `clientId` so one noisy agent can't starve humans in the same org:
687
-
688
- ```typescript
689
- rateLimit: {
690
- keyGenerator: (req) =>
691
- isService(req.scope) ? `svc:${getClientId(req.scope)}` : `org:${getOrgId(req.scope)}`,
692
- }
693
- ```
694
-
695
- **Credential-flow choice is the app's** — arc does not pick for you:
696
-
697
- | Flow | Wire via `authenticate` callback |
698
- |---|---|
699
- | Arc JWT with `clientId` claim | example above |
700
- | API key in header (DB lookup) | read `x-api-key`, look up client, set `scope` to service |
701
- | Better Auth client credentials | `auth.api.getSession({ headers })`, detect client-credential grant |
702
- | mTLS cert DN → client | read cert from terminator header, map DN → `clientId` |
703
- | OAuth2 client-credentials | verify token via introspection endpoint |
704
-
705
- All five produce the same downstream primitive: `RequestScope.service`. Permission builders, audit hooks, and rate-limit keys compose the same way regardless.
706
-
707
- ## Microservice Gateway Pattern
708
-
709
- ```
710
- Frontend → API Gateway (Arc + Better Auth) → Downstream Services
711
- ↓
712
- Forwards: X-User-Id, X-Org-Id, X-User-Roles
713
- ```
714
-
715
- Gateway verifies session, downstream services trust headers:
716
-
717
- ```typescript
718
- // Downstream — no Better Auth needed
719
- const app = await createApp({
720
- auth: {
721
- type: 'authenticator',
722
- authenticate: async (req, reply) => {
723
- const userId = req.headers['x-user-id'];
724
- if (!userId) return reply.code(401).send({ error: 'Unauthorized' });
725
- req.user = { id: userId, role: JSON.parse(req.headers['x-user-roles'] || '[]') };
726
- },
727
- },
728
- });
729
- ```