@classytic/arc 2.45.2 → 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-DHb1tpu-.mjs → EventTransport-DNgD9NP4.mjs} +3 -4
  4. package/dist/{HookSystem-C1u0EUnt.mjs → HookSystem-DRbPzEcP.mjs} +3 -4
  5. package/dist/{QueryCache--5uAuYPW.d.mts → QueryCache-DdvrGG8Q.d.mts} +1 -3
  6. package/dist/{ResourceRegistry-D2jXWVN_.mjs → ResourceRegistry-Douk51fa.mjs} +15 -4
  7. package/dist/{acquire-DTkA8Lme.mjs → acquire-RbtvDg9s.mjs} +2 -3
  8. package/dist/{actionPermissions-DRVk6m7x.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-D48fUJv1.mjs → authorizationDecision-DeZMrHcm.mjs} +5 -6
  18. package/dist/{base-CZyixEQR.d.mts → base-HXNgPQww.d.mts} +1 -7
  19. package/dist/{boundedMap-DkKiPifd.mjs → boundedMap-2WBh3gM9.mjs} +2 -3
  20. package/dist/{buildHandler-BiZ4VATS.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-Cj0as-P1.mjs → caching-BYRwYrUo.mjs} +3 -4
  24. package/dist/{claimed-ChI13rUR.mjs → claimed-DYlELdnm.mjs} +2 -3
  25. package/dist/cleanup/index.d.mts +4 -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-D_aiew34.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-QIZ2560Y.mjs → core-D9rS2BxO.mjs} +9 -12
  47. package/dist/{createActionRouter-CvH84dyx.mjs → createActionRouter-0qkCRzTL.mjs} +7 -8
  48. package/dist/{createAggregationRouter-DGyK2Hp6.mjs → createAggregationRouter-CUf5Esd9.mjs} +9 -10
  49. package/dist/{createApp-CKjZpmq9.mjs → createApp-DZIXfDKD.mjs} +49 -62
  50. package/dist/{createMcpServer-DSztofa9.d.mts → createMcpServer-DeVpqQF-.d.mts} +1 -3
  51. package/dist/{defineAggregation-BLza7Ca4.mjs → defineAggregation-bmKQ4NmC.mjs} +2 -3
  52. package/dist/{defineResource-CEo0gDCb.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-BJTsSnke.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-2p4SL5zm.mjs → errorHandler-dFyGOEoB.mjs} +16 -6
  63. package/dist/{errors-grZkIA8N.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-ItcYBGUs.mjs → eventPlugin-eMhAPtQA.mjs} +10 -12
  67. package/dist/{eventTypes-Ck6fD3ne.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-BRX0Krcj.mjs → fields-LnbCcvsw.mjs} +2 -3
  80. package/dist/{filter-merge-CDc7YMwX.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-hvg7V2g1.mjs → generate-oXoDnpJf.mjs} +7 -12
  83. package/dist/{headers-Cqkg4LzI.mjs → headers-DBd3Qheo.mjs} +3 -4
  84. package/dist/{health-PVt0VjOx.mjs → health-BlJu9GXS.mjs} +2 -3
  85. package/dist/{health-DyeP3mTW.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-jC3rMPzb.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-ptwyzZQ-.mjs → jsonBody-DpRpKR_K.mjs} +3 -4
  125. package/dist/{keys-C1vFuSbv.mjs → keys-FBz6Ull-.mjs} +2 -3
  126. package/dist/{loadResources-CHPDyIPn.mjs → loadResources-Bx1sKPnF.mjs} +4 -5
  127. package/dist/{loadResourcesFromEntry-BkHHTu_B.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-C5bvCiAK.mjs → logger-CbFcIEBZ.mjs} +3 -5
  131. package/dist/{mcpPlugin-C9qohJCF.mjs → mcpPlugin-yix548XX.mjs} +41 -60
  132. package/dist/{memory-CxiTwT0j.mjs → memory-Bgw5dn8N.mjs} +4 -5
  133. package/dist/{metrics-Ckp2zRy-.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-CfnKuIuH.mjs → module-Dsc_nKL5.mjs} +2 -3
  139. package/dist/{multiTenant-CAtYlW6H.d.mts → multiTenant-XCxAUlru.d.mts} +1 -5
  140. package/dist/{multipartBody-BFasGtP9.mjs → multipartBody-B85ek8Kj.mjs} +2 -3
  141. package/dist/observeSend-BK-JN1jK.mjs +20 -0
  142. package/dist/{openapi-DAPxjYHX.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-B4FAkx3A.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-B14c3OMp.mjs → permissions-A1oKtpiC.mjs} +19 -29
  150. package/dist/{pipe-CQv7PsAK.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-CpnTykjb.mjs → plan-KVseuBCL.mjs} +5 -9
  154. package/dist/{plugin-DXTjVg_Q.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-C3VJKRGp.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-CquqYJPy.mjs → presets-qKCehiJM.mjs} +11 -18
  171. package/dist/{projection-CgfSLOSM.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-D0HUISHJ.mjs → queryCachePlugin-3gJj5Rbz.mjs} +8 -10
  174. package/dist/{queryCachePlugin-C2lZjTxk.d.mts → queryCachePlugin-DYQUyeJ9.d.mts} +2 -4
  175. package/dist/{rateLimitKey-AvkBOMkl.mjs → rateLimitKey-Kro---xl.mjs} +2 -3
  176. package/dist/{realtime-CbWtVbqK.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-BVwpAuFI.mjs → registry-BA-_vFYk.mjs} +7 -12
  183. package/dist/{renewingLease-CykpeNcQ.mjs → renewingLease-CMY8YOcc.mjs} +2 -3
  184. package/dist/{replyHelpers-DA51IZio.mjs → replyHelpers-DK9P_XSz.mjs} +3 -4
  185. package/dist/{requestContext-DIWHKDtQ.mjs → requestContext-GYO_0gEw.mjs} +2 -3
  186. package/dist/{requirement-CbiLdQ1n.d.mts → requirement-CTRQjjQx.d.mts} +0 -2
  187. package/dist/{requirement-Cp_fsMDL.mjs → requirement-DeNjZIH3.mjs} +2 -3
  188. package/dist/{resourceRateLimit-Wf6d6FL9.d.mts → resourceRateLimit-DCWglD7V.d.mts} +1 -3
  189. package/dist/{resourceRateLimit-BFuluodF.mjs → resourceRateLimit-tHLbrtWc.mjs} +3 -4
  190. package/dist/{rolldown-runtime-D_lMdYOd.mjs → rolldown-runtime-Kv1fZdLg.mjs} +2 -3
  191. package/dist/{routeValidator-DuLonYwr.mjs → routeValidator-C_H5NanI.mjs} +2 -3
  192. package/dist/{runtimeCapabilities-CydRfm0i.mjs → runtimeCapabilities-DWqbxkyw.mjs} +2 -3
  193. package/dist/{schedules-B693KXxa.mjs → schedules-eO_RzhCU.mjs} +132 -9
  194. package/dist/{schemaConverter-DNvZWTV6.mjs → schemaConverter-DBJrPZN4.mjs} +3 -4
  195. package/dist/{schemaIR-REV2y7Wd.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-Bevxy_ST.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-CfrqPR7A.mjs → shutdown-DzLFbe27.mjs} +2 -3
  205. package/dist/{simpleEqualityMatcher-BJwfuRKP.mjs → simpleEqualityMatcher-DOJhwQ8g.mjs} +2 -3
  206. package/dist/{sse-CuNNWr2z.mjs → sse-2972pVwV.mjs} +8 -9
  207. package/dist/{sseStream-C_2ujAVY.mjs → sseStream-AWLEeNV-.mjs} +3 -4
  208. package/dist/{storage-Cx9Sz3Ou.d.mts → storage-odC5MNKN.d.mts} +0 -2
  209. package/dist/{store-helpers-C8uBGCbb.mjs → store-helpers-VzjgVTkM.mjs} +2 -3
  210. package/dist/{streaming-Bdq_M4d5.mjs → streaming-DvraWW6x.mjs} +2 -3
  211. package/dist/{subscriberIdentity-B-KpZkdl.mjs → subscriberIdentity-Bya56jsg.mjs} +2 -3
  212. package/dist/{tenancy-C5PCvm1h.mjs → tenancy-DSa_0hhw.mjs} +3 -4
  213. package/dist/{tenantPreparation-dYvWrgNa.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-DCqsezX8.mjs → timing-6rQTuCwg.mjs} +3 -5
  225. package/dist/{tracing-Dro5eH6j.d.mts → tracing-JSFiBl5r.d.mts} +0 -2
  226. package/dist/{transactionContext-DrcNyjpv.mjs → transactionContext-DaxYUEgH.mjs} +2 -3
  227. package/dist/{typeGuards-CEl10KPy.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-D9NWjpYc.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-BHig1kHq.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-BG5P7_Vb.mjs → utils-CjjGOT4E.mjs} +20 -30
  244. package/dist/{validate-D_mdOCir.mjs → validate-4RlTKOJb.mjs} +5 -7
  245. package/dist/{versioning-DBGHjPh7.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-DPPfM4m6.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
@@ -0,0 +1,99 @@
1
+ # API keys and machine identity
2
+
3
+ Two routes to machine callers: Better Auth `apiKey()` (keys stored by BA), or your own `authenticate` / permission check mapping any credential to a `service` scope. Both end in `RequestScope.service`.
4
+
5
+ ## Better Auth `apiKey()`
6
+
7
+ `apiKey` is a SEPARATE package. It is not in `better-auth/plugins`.
8
+
9
+ ```typescript
10
+ import { apiKey } from '@better-auth/api-key';
11
+
12
+ const auth = betterAuth({
13
+ plugins: [organization(), apiKey({ enableSessionForAPIKeys: true })], // option belongs to the plugin
14
+ });
15
+ ```
16
+
17
+ ```
18
+ x-api-key: ak_live_... # authentication
19
+ x-organization-id: org_abc123 # org context for org-scoped resources
20
+ ```
21
+
22
+ - API-key sessions have no `activeOrganizationId`. Without the header, `scope.kind` is `authenticated`, not `member`.
23
+ - OpenAPI security is derived automatically: resource paths `[{ bearerAuth }, { apiKeyAuth, orgHeader }]` (bearer alone OR key AND org header); auth endpoints `[{ cookieAuth }, { bearerAuth }, { apiKeyAuth }]`. `apiKeyAuth` appears only when the plugin is active.
24
+ - `apikey` rows use `referenceId` (not `userId`) and a required `configId`: remember in fixtures.
25
+
26
+ Admin read view of keys (the overlay is read-only; issue and revoke through BA `/api/auth/api-key/*`):
27
+
28
+ ```typescript
29
+ const apiKeyAdapter = await createBetterAuthOverlay({ auth, mongoose, collection: 'apikey' });
30
+
31
+ defineResource({
32
+ name: 'apikey',
33
+ adapter: apiKeyAdapter,
34
+ tenantField: false,
35
+ permissions: { list: requireRoles(['admin']), get: requireRoles(['admin']) },
36
+ fields: { key: fields.hidden() }, // never expose the raw key
37
+ });
38
+ ```
39
+
40
+ ## Service scope from `authenticate`
41
+
42
+ Arc's default JWT verify installs `member` scope. Custom authenticators are the extension point.
43
+
44
+ ```typescript
45
+ auth: {
46
+ type: 'jwt',
47
+ jwt: { secret: process.env.JWT_SECRET! },
48
+ authenticate: async (request, { jwt }) => {
49
+ const token = request.headers.authorization?.slice(7);
50
+ if (!token || !jwt) return null;
51
+ const d = jwt.verify<{ clientId?: string; userId?: string; organizationId?: string; scopes?: string[] }>(token);
52
+ if (d.clientId) {
53
+ request.scope = { kind: 'service', clientId: d.clientId, organizationId: d.organizationId ?? '', scopes: d.scopes ?? [] };
54
+ return { clientId: d.clientId }; // becomes request.user
55
+ }
56
+ return userRepo.getById(String(d.userId));
57
+ },
58
+ }
59
+ ```
60
+
61
+ | Credential | Wire via |
62
+ |---|---|
63
+ | JWT with `clientId` claim | example above |
64
+ | API key in header (DB lookup) | read `x-api-key`, look up client, set service scope |
65
+ | Better Auth client credentials | `auth.api.getSession({ headers })`, detect the grant |
66
+ | mTLS | map certificate DN (terminator header) to `clientId` |
67
+ | OAuth2 client credentials | verify via introspection |
68
+ | Non-session scheme with BA | `createBetterAuthAdapter({ credentials })` |
69
+
70
+ An API-key permission check can also return the scope (`allow({ scope })`): see multi-tenancy.md.
71
+
72
+ ## Gating services
73
+
74
+ ```typescript
75
+ import { anyOf, requireOrgRole, requireServiceScope } from '@classytic/arc/permissions';
76
+
77
+ permissions: {
78
+ create: requireServiceScope('orders:write'), // any listed scope; elevated passes
79
+ update: anyOf(requireOrgRole('editor'), requireServiceScope('orders:write')), // humans or services
80
+ }
81
+ ```
82
+
83
+ - `requireOrgRole` DENIES service scopes. Compose with `anyOf` to accept both.
84
+ - `requireServiceScope` denies `member` scopes.
85
+
86
+ ## Audit and rate limits
87
+
88
+ Audit rows use `userId`, else `clientId`, as actor (from the validated scope). Key rate limits per client so one agent cannot starve humans:
89
+
90
+ ```typescript
91
+ import { createTenantKeyGenerator, getClientId, getOrgId, isService } from '@classytic/arc/scope';
92
+
93
+ rateLimit: {
94
+ keyGenerator: createTenantKeyGenerator({
95
+ strategy: ({ scope, ip }) =>
96
+ scope && isService(scope) ? `svc:${getClientId(scope)}` : `org:${(scope && getOrgId(scope)) ?? ip}`,
97
+ }),
98
+ }
99
+ ```
@@ -0,0 +1,87 @@
1
+ # Better Auth tables as arc resources
2
+
3
+ BA writes its own tables (`user`, `organization`, `member`, ...). A kit overlay exposes them as READ resources (pagination, queryparser, OpenAPI, permissions). Overlays are plugin-agnostic: they read `auth.$context.tables`.
4
+
5
+ The overlay repository is sealed read-only by default. Mutate identities through `auth.api`, never through generic CRUD. `unsafeWritable: true` lifts the seal for admin repair paths only.
6
+
7
+ ## mongokit
8
+
9
+ ```typescript
10
+ import { betterAuth } from 'better-auth';
11
+ import { mongodbAdapter } from '@better-auth/mongo-adapter';
12
+ import { organization } from 'better-auth/plugins/organization';
13
+ import mongoose from 'mongoose';
14
+ import { createBetterAuthOverlay, registerBetterAuthStubs } from '@classytic/mongokit/better-auth';
15
+ import { defineResource } from '@classytic/arc';
16
+ import { requireAuth } from '@classytic/arc/permissions';
17
+
18
+ const auth = betterAuth({
19
+ database: mongodbAdapter(mongoose.connection.getClient().db()),
20
+ plugins: [organization()],
21
+ });
22
+
23
+ // strict:false stubs so populate('user') / ref:'organization' work app-wide
24
+ registerBetterAuthStubs(mongoose, { plugins: ['organization'] });
25
+
26
+ const orgAdapter = await createBetterAuthOverlay({ auth, mongoose, collection: 'organization' });
27
+
28
+ defineResource({
29
+ name: 'organization',
30
+ adapter: orgAdapter,
31
+ tenantField: false, // platform-wide, not tenant-scoped
32
+ permissions: { list: requireAuth(), get: requireAuth() },
33
+ });
34
+ ```
35
+
36
+ `registerBetterAuthStubs(mongoose, opts)`:
37
+
38
+ | Option | Purpose |
39
+ |---|---|
40
+ | `plugins` | `organization`, `organization-teams`, `twoFactor`, `jwt`, `oidcProvider`, `mcp`, `deviceAuthorization` |
41
+ | `extraCollections` | Any collection not in the plugin map, e.g. `['apikey', 'passkey']` |
42
+ | `modelOverrides` | BA modelName => Mongoose model name |
43
+ | `usePlural` | Also register the plural name |
44
+ | `idType` | `'objectid'` (default) or `'string'` |
45
+
46
+ Field-only plugins (`admin`, `username`, `magicLink`, `bearer`) need no entry.
47
+
48
+ Gotchas:
49
+ - `idType` must match the stored `_id` (`typeof doc._id`). A wrong value makes `getById` 404 and `populate` return null with no error. Use `'string'` when `advanced.database.generateId` is overridden.
50
+ - `createBetterAuthOverlay` throws when a model for that collection already exists (stub registered, or a second call) and `additionalFields` is passed. Choose stub OR overlay-with-fields per collection.
51
+ - Call `ensureBetterAuthSessionTtl(connection)` once at boot: BA creates no TTL index for expired sessions.
52
+ - Need `toJSON` stripping or domain repository methods? Hand-roll a `strict: false` Mongoose model on `collection: 'user'`, wrap it with a mongokit `Repository` and `createMongooseAdapter`, and hide secrets with `fields: { password: fields.hidden() }`.
53
+
54
+ ## sqlitekit
55
+
56
+ ```typescript
57
+ import Database from 'better-sqlite3';
58
+ import { drizzle } from 'drizzle-orm/better-sqlite3';
59
+ import { createBetterAuthOverlay } from '@classytic/sqlitekit/better-auth';
60
+
61
+ const sqlite = new Database('app.db');
62
+ const auth = betterAuth({ database: sqlite, plugins: [organization()] });
63
+ const orgAdapter = await createBetterAuthOverlay({ auth, db: drizzle(sqlite), collection: 'organization' });
64
+
65
+ defineResource({ name: 'organization', adapter: orgAdapter, idField: 'id', tenantField: false });
66
+ ```
67
+
68
+ Same shape as mongokit: replace `{ mongoose }` with `{ db }`, `additionalFields` with `additionalColumns` (Drizzle column builders), and skip stubs.
69
+
70
+ ## Plugin matrix
71
+
72
+ | BA plugin | Tables | Arc side |
73
+ |---|---|---|
74
+ | core (emailAndPassword, OAuth) | `user`, `session`, `account`, `verification` | Optionally overlay `user` |
75
+ | `organization()` | `organization`, `member`, `invitation` | `orgContext: true`; overlay as needed |
76
+ | `organization({ teams: { enabled: true } })` | + `team`, `teamMember` | `requireTeamMembership()` on `scope.teamId` |
77
+ | `twoFactor()` | `twoFactor` | Overlay if exposed |
78
+ | `admin()` | fields on `user` | `requireRoles(['admin'])` reads the platform role |
79
+ | `bearer()` | none | Header transport; see auth-better-auth.md |
80
+ | `apiKey()` from `@better-auth/api-key` | `apikey` | auth-api-keys.md |
81
+ | `passkey`, `oidcProvider`, `mcp`, `deviceAuthorization`, `magicLink`, `username` | varies | List in `plugins` or `extraCollections` |
82
+
83
+ Import plugins from dedicated paths (`better-auth/plugins/organization`, `.../admin`, `.../two-factor`, `.../bearer`) for tree-shaking.
84
+
85
+ Multi-plugin example: one `registerBetterAuthStubs(mongoose, { plugins: ['organization'], extraCollections: ['apikey'] })`, then one overlay call per table (`organization`, `member`, `apikey`, `twoFactor`, `user`).
86
+
87
+ Runnable references: `playground/better-auth/mongo/` and `playground/better-auth/sqlite/`.
@@ -0,0 +1,78 @@
1
+ # Better Auth adapter
2
+
3
+ Bridge Better Auth (BA) sessions into `request.scope`. Pass a real `betterAuth()` instance: arc calls `auth.api.*` in-process.
4
+
5
+ ```typescript
6
+ import { createApp } from '@classytic/arc/factory';
7
+ import { createBetterAuthAdapter } from '@classytic/arc/auth';
8
+
9
+ const adapter = createBetterAuthAdapter({
10
+ auth, // betterAuth() instance
11
+ basePath: '/api/auth', // default
12
+ orgContext: true, // resolve org membership into scope
13
+ });
14
+
15
+ const app = await createApp({ auth: { type: 'betterAuth', betterAuth: adapter } });
16
+ ```
17
+
18
+ BA's Mongo adapter needs an open connection. Pass a thunk, resolved after `beforeBoot`:
19
+
20
+ ```typescript
21
+ const app = await createApp({
22
+ beforeBoot: () => connectDatabase(),
23
+ auth: { type: 'betterAuth', betterAuth: () => createBetterAuthAdapter({ auth: getAuth(), orgContext: true }) },
24
+ });
25
+ ```
26
+
27
+ Result also exposes `plugin`, `authenticate`, `optionalAuthenticate`, `permissions` (`requireOrgRole`, `requireOrgMembership`, `requireTeamMembership`), `openapi`.
28
+
29
+ ## Options
30
+
31
+ | Option | Purpose |
32
+ |---|---|
33
+ | `orgContext` | Resolve org membership into scope (default false) |
34
+ | `resolveOrgRoles({ userId, organizationId, memberRoles })` | Org hierarchy seam: return the effective roles (e.g. parent-org roles) or `null` to stay non-member. Needs `orgContext` |
35
+ | `memberLookup: 'better-auth' \| 'resolver'` | `'resolver'` skips BA's membership read; use only if the resolver never reads `memberRoles` |
36
+ | `credentials: { Scheme: verify }` | Non-session credentials by `Authorization` scheme; verifier returns a `RequestScope` (usually `service`) or `null` (401). `Bearer` is reserved |
37
+ | `rateLimit: { max, timeWindow } \| false` | Per-route limit on the auth catch-all (no default) |
38
+ | `openapi` | `true` (default) extracts from `auth.api`; `false`; or a manual spec |
39
+ | `userFields` | Extra user fields merged into OpenAPI schemas |
40
+ | `exposeAuthErrors` | Show detail in 401 (debug only) |
41
+
42
+ ```typescript
43
+ createBetterAuthAdapter({
44
+ auth, orgContext: true,
45
+ credentials: { Device: async (value, request) => verifyDevice(value) }, // Authorization: Device <token>
46
+ });
47
+ ```
48
+
49
+ Gate `credentials` routes with `requireServiceScope(...)`.
50
+
51
+ ## Org context flow (`orgContext: true`)
52
+
53
+ 1. `auth.api.getSession()` in-process.
54
+ 2. Org id = `session.activeOrganizationId`, else the `x-organization-id` header (API-key sessions carry no org).
55
+ 3. Membership via `auth.api.getActiveMember` (or `getActiveMemberRole` for header orgs).
56
+ 4. Roles split on comma: `"admin,recruiter"` => `['admin', 'recruiter']`.
57
+ 5. `session.activeTeamId` is bound only if it appears in `auth.api.listUserTeams` for the ACTIVE org. Stale or cross-org teams are dropped. Needs better-auth >=1.7.0.
58
+ 6. Scope: `{ kind: 'member', organizationId, orgRoles, teamId? }`.
59
+
60
+ `authenticate` and `optionalAuthenticate` run the same flow. Without an org the scope is `authenticated`.
61
+
62
+ ## Multi-role members
63
+
64
+ BA stores several roles in one `member.role` string. Arc reads `scope.orgRoles` as an array and `requireOrgRole('admin')` matches any element. Querying `?role=admin` does NOT match a multi-role row (opaque text); use `role[like]=admin`.
65
+
66
+ ## Sessions at scale
67
+
68
+ - Redis sessions: BA `secondaryStorage` (sessions skip the DB unless `session.storeSessionInDatabase: true`). Arc's `RedisSessionStore` (`@classytic/arc/auth/redis`) belongs to `createSessionManager`, a different layer. Do not mix.
69
+ - BA `session.cookieCache` never caches custom session fields such as `activeOrganizationId`, so scope cannot go stale, but the org lookup still runs.
70
+ - BA has its own limiter (`rateLimit.storage: 'secondary-storage'`). Exempt it from arc's bucket: `rateLimit: { skipPaths: ['/api/auth/*'] }`.
71
+
72
+ ## Bearer transport (SPA, mobile)
73
+
74
+ Add BA `bearer()` (import from `better-auth/plugins/bearer`) so sessions travel as `Authorization: Bearer <session-token>`. Same `getSession()` path; no arc config change. Cookie and bearer can both be enabled.
75
+
76
+ ## Scaffold
77
+
78
+ `arc init my-api --better-auth --mongokit --ts` prompts for session strategy (cookie, bearer, both) and the API key plugin, then wires plugins, `registerBetterAuthStubs`, and peer deps.
@@ -0,0 +1,100 @@
1
+ # Permission checks, roles and scope helpers
2
+
3
+ ```typescript
4
+ import {
5
+ allowPublic, requireAuth, requireRoles, requireOwnership,
6
+ requireOrgMembership, requireOrgRole, requireTeamMembership,
7
+ requirePlatformRole, requireServiceScope,
8
+ allOf, anyOf, not, when, denyAll, allow, deny, type PermissionCheck,
9
+ } from '@classytic/arc/permissions';
10
+ ```
11
+
12
+ | Check | Passes when |
13
+ |---|---|
14
+ | `allowPublic()` | Always, no auth |
15
+ | `allowPublic({ policy })` | Always; rows narrowed by a filter or `(ctx) => filter` (`{}` = unrestricted; static `{}` throws; resolver returning non-object => 403) |
16
+ | `requireAuth()` | Any authenticated caller |
17
+ | `requireRoles(['admin'])` | A role matches. Checks global roles AND `scope.orgRoles` by default; options `{ bypassRoles, includeOrgRoles: false }` |
18
+ | `requirePlatformRole('ops')` | Global role only; an org role never satisfies it. Use for global surfaces (e.g. jobs management routes) |
19
+ | `requireOwnership('userId', { bypassRoles })` | Authenticated; adds policy `{ userId: <caller> }` |
20
+ | `requireOrgMembership()` | `member` scope |
21
+ | `requireOrgRole('admin', 'owner')` | Any listed role in `scope.orgRoles`; denies service scopes |
22
+ | `requireTeamMembership()` | `scope.teamId` set |
23
+ | `requireServiceScope('a:read')` | Service holds ANY listed scope |
24
+ | `allOf(a, b)` / `anyOf(a, b)` / `not(a)` | AND / OR (first granting branch wins) / negation |
25
+ | `denyAll(reason?)` | Never |
26
+
27
+ Elevated scope passes the scope-based checks.
28
+
29
+ `anyOf(allowPublic({ policy }), requireRoles('admin'))` filters admins too (a public branch grants everyone). Put the privileged branch first, or return `{}` for staff from a policy resolver.
30
+
31
+ ## Custom check
32
+
33
+ ```typescript
34
+ const requirePro = (): PermissionCheck => async (ctx) => {
35
+ if (!ctx.user) return deny('Auth required');
36
+ return ctx.user.plan === 'pro' ? allow() : deny('Pro plan required');
37
+ };
38
+ ```
39
+
40
+ `allow({ policy, scope })` can add a row filter and install a scope (multi-tenancy.md). A custom public check must set `_isPublic` or anonymous callers get 401; prefer `allowPublic({ policy })`.
41
+
42
+ ## Static and dynamic role matrices
43
+
44
+ ```typescript
45
+ import { createOrgPermissions, createDynamicPermissionMatrix } from '@classytic/arc/permissions';
46
+
47
+ const perms = createOrgPermissions({
48
+ statements: { product: ['create', 'update', 'delete'] },
49
+ roles: { owner: { product: ['create', 'update', 'delete'] }, member: { product: [] } },
50
+ });
51
+ permissions: { create: perms.can({ product: ['create'] }) }
52
+
53
+ const acl = createDynamicPermissionMatrix({
54
+ resolveRolePermissions: async (ctx) => aclService.getRoleMatrix(ctx), // role -> resource -> actions[]
55
+ cache: { ttlSeconds: 60 }, // or cacheStore: <CacheStore>
56
+ });
57
+ permissions: { list: acl.canAction('product', 'read') }
58
+ ```
59
+
60
+ - Reads `scope.orgRoles`; elevated bypasses; `*` wildcards for resource/action; cache failures fall through to the resolver.
61
+ - `acl.invalidateByOrg(orgId)`, `acl.clearCache()`. Multi-node: `await acl.connectEvents(eventBus)` (after the events plugin is registered) so invalidations propagate; pass `fastify` in the config so the memory cache shows in the distributed-runtime audit.
62
+ - Also on the matrix: `requireRole(...)`, `requireMembership()`, `requireTeamMembership()`.
63
+
64
+ ## Role hierarchy
65
+
66
+ ```typescript
67
+ import { createRoleHierarchy } from '@classytic/arc/permissions';
68
+
69
+ const h = createRoleHierarchy({ superadmin: ['admin'], admin: ['branch_manager'] });
70
+ h.expand(['superadmin']); // ['superadmin', 'admin', 'branch_manager']
71
+ h.includes(['admin'], 'branch_manager'); // true
72
+ ```
73
+
74
+ ## Request scope
75
+
76
+ ```typescript
77
+ import { getUserId, getUserRoles, getOrgId, getOrgRoles, getTeamId, requireOrgId, isMember } from '@classytic/arc/scope';
78
+ ```
79
+
80
+ | Kind | Fields |
81
+ |---|---|
82
+ | `public` | none |
83
+ | `authenticated` | `userId?`, `userRoles?` |
84
+ | `member` | `userId?`, `userRoles`, `organizationId`, `orgRoles`, `teamId?`, `context?`, `ancestorOrgIds?` |
85
+ | `service` | `clientId`, `organizationId`, `scopes?`, `mandate?`, `dpopJkt?`, `context?`, `ancestorOrgIds?` |
86
+ | `elevated` | `userId?`, `organizationId?`, `elevatedBy`, `context?`, `ancestorOrgIds?` |
87
+
88
+ Two role layers: global roles (`scope.userRoles`, from `user.role`) and org roles (`scope.orgRoles`, from membership). `requireOrgRole` checks only the second.
89
+
90
+ ## Elevation (platform admin)
91
+
92
+ ```typescript
93
+ createApp({ elevation: { platformRoles: ['superadmin'], onElevation: (e) => audit.write(e) } });
94
+ ```
95
+
96
+ A platform-role user sends `x-arc-scope: platform` (optionally `x-organization-id`) to get `kind: 'elevated'`. Header names are configurable (`scopeHeader`, `orgHeader`).
97
+
98
+ ## Custom routes outside a resource
99
+
100
+ No org middleware ships. Write a one-line `preHandler` that throws when `getOrgId(request.scope)` is undefined, or call `requireOrgId(request.scope)` (throws 403).
@@ -0,0 +1,122 @@
1
+ # Auth strategies
2
+
3
+ Pick how requests are authenticated. Every strategy ends the same way: `request.scope` is set (see multi-tenancy.md).
4
+
5
+ ## Decision table
6
+
7
+ | User data lives | Written by | Use |
8
+ |---|---|---|
9
+ | Your DB | You | `type: 'jwt'` (arc issues/verifies) or `type: 'authenticator'` |
10
+ | Provider cloud (Clerk, Auth0, Supabase) | Provider | `authenticate` callback: verify provider token, set `request.scope` |
11
+ | Your DB | Better Auth | `type: 'betterAuth'` (auth-better-auth.md) |
12
+ | Upstream gateway | Gateway | `type: 'authenticator'` trusting forwarded headers |
13
+
14
+ Arc ships no per-provider code. The contract is `request.scope`.
15
+
16
+ ## `type: 'jwt'`
17
+
18
+ ```typescript
19
+ import { createApp } from '@classytic/arc/factory';
20
+
21
+ const app = await createApp({
22
+ auth: {
23
+ type: 'jwt',
24
+ jwt: {
25
+ secret: process.env.JWT_SECRET!, // 32+ chars
26
+ expiresIn: '15m',
27
+ refreshSecret: process.env.JWT_REFRESH_SECRET,
28
+ refreshExpiresIn: '7d',
29
+ },
30
+ // Optional: replaces the default Bearer verify
31
+ authenticate: async (request, { jwt }) => {
32
+ const token = request.headers.authorization?.split(' ')[1];
33
+ if (!token || !jwt) return null; // null = 401
34
+ const decoded = jwt.verify<{ _id: string }>(token);
35
+ return userRepo.getById(decoded._id);
36
+ },
37
+ tokenExtractor: (req) => req.cookies?.['auth-token'] ?? null,
38
+ isRevoked: async (decoded) => Boolean(await redis.sismember('revoked', String(decoded.jti))),
39
+ },
40
+ });
41
+ ```
42
+
43
+ Decorates `app.authenticate`, `app.optionalAuthenticate`, `app.authorize(...roles)` (`'*'` = any authenticated user), `app.auth`.
44
+
45
+ ```typescript
46
+ const tokens = app.auth.issueTokens({ _id: user._id, email, role });
47
+ // { accessToken, refreshToken?, expiresIn, tokenType: 'Bearer' }
48
+ const decoded = app.auth.verifyRefreshToken(refreshToken); // rejects access tokens
49
+ ```
50
+
51
+ Gotchas:
52
+ - Default verify requires `type: 'access'` in the token (`issueTokens` sets it). Tokens without it are 401 unless `strictTokenType: false`. Refresh tokens are always rejected.
53
+ - `isRevoked` fails closed: a throw means revoked.
54
+ - Default scope from the returned user: has `organizationId` => `member`, else `authenticated`. A scope your `authenticate` already set is kept.
55
+ - 401 body is generic; `exposeAuthErrors: true` shows the message (debug only).
56
+
57
+ ## `type: 'authenticator'`
58
+
59
+ ```typescript
60
+ auth: {
61
+ type: 'authenticator',
62
+ authenticate: async (req, reply) => {
63
+ const session = await validateSession(req);
64
+ if (!session) return reply.code(401).send({ code: 'arc.unauthorized', message: 'Unauthorized', status: 401 });
65
+ req.user = session.user;
66
+ },
67
+ // optionalAuthenticate: optional; derived from authenticate when omitted
68
+ }
69
+ ```
70
+
71
+ ## `type: 'custom'` and `auth: false`
72
+
73
+ ```typescript
74
+ auth: { type: 'custom', plugin: myAuthPlugin } // plugin must decorate fastify.authenticate
75
+ auth: false // no auth
76
+ ```
77
+
78
+ ## Cloud provider (Clerk, Auth0, Supabase)
79
+
80
+ No tables to overlay. Verify the provider token, map claims to scope.
81
+
82
+ ```typescript
83
+ import { verifyToken } from '@clerk/backend';
84
+
85
+ auth: {
86
+ type: 'jwt',
87
+ jwt: { secret: process.env.JWT_SECRET! }, // required by the type, unused by authenticate
88
+ authenticate: async (request) => {
89
+ const token = request.headers.authorization?.slice(7);
90
+ if (!token) return null;
91
+ const claims = await verifyToken(token, { secretKey: process.env.CLERK_SECRET_KEY! });
92
+ if (claims.org_id) {
93
+ request.scope = {
94
+ kind: 'member', userId: claims.sub, userRoles: [],
95
+ organizationId: claims.org_id, orgRoles: claims.org_role ? [claims.org_role] : [],
96
+ };
97
+ }
98
+ return { id: claims.sub, email: claims.email };
99
+ },
100
+ }
101
+ ```
102
+
103
+ Need joins on users? Webhook-sync the provider's users into a local collection and expose it as a normal resource.
104
+
105
+ ## Gateway headers
106
+
107
+ ```typescript
108
+ auth: {
109
+ type: 'authenticator',
110
+ authenticate: async (req, reply) => {
111
+ const userId = req.headers['x-user-id'];
112
+ if (typeof userId !== 'string') return reply.code(401).send({ code: 'arc.unauthorized', message: 'Unauthorized', status: 401 });
113
+ req.user = { id: userId, role: JSON.parse(String(req.headers['x-user-roles'] ?? '[]')) };
114
+ },
115
+ }
116
+ ```
117
+
118
+ Trust these headers only when the service is unreachable except through the gateway.
119
+
120
+ ## Header-selected org (JWT/custom auth)
121
+
122
+ `resolveOrgFromHeader` from `@classytic/arc/scope` is a `preHandler` that upgrades the scope to `member` from `x-organization-id` after your `resolveMembership(userId, orgId)` returns `{ roles }` (or null). Register it after authentication.
@@ -0,0 +1,80 @@
1
+ # Boot: createApp, loadResources, roles, controllers, DX
2
+
3
+ ## createApp
4
+
5
+ ```typescript
6
+ import { createApp, loadResources } from '@classytic/arc/factory';
7
+
8
+ const app = await createApp({
9
+ preset: 'production', // production | development | testing | edge
10
+ runtime: 'memory', // memory | distributed
11
+ role: process.env.ARC_ROLE as 'api' | 'worker' | 'relay' | 'scheduler' | 'all',
12
+ beforeBoot: async () => { await mongoose.connect(uri); return () => mongoose.disconnect(); },
13
+ resourcePrefix: '/api/v1',
14
+ auth: { type: 'jwt', jwt: { secret: process.env.JWT_SECRET } },
15
+ cors: { origin: process.env.ALLOWED_ORIGINS!.split(','), credentials: true },
16
+ resources: await loadResources(import.meta.url),
17
+ arcPlugins: { events: true, queryCache: false, sse: false, caching: true },
18
+ stores: { events: new RedisEventTransport({ client: redis }) }, // required when runtime: 'distributed'
19
+ });
20
+ await app.listen({ port: 8040, host: '0.0.0.0' });
21
+ ```
22
+
23
+ Boot order is fixed: `beforeBoot` -> module graph -> arc core -> `plugins` -> `bootstrap[]` -> `resources` -> `afterResources` -> `onReady`.
24
+
25
+ | Option | Use |
26
+ |---|---|
27
+ | `beforeBoot` | connect the DB here (runs before Fastify and before resource files import); returned disposer runs on close and on failed boot |
28
+ | `resources` | array, or `async (fastify) => [...]` that runs after `bootstrap[]` (repository inside an async-booted engine) |
29
+ | `loadResources(import.meta.url, { context, filter })` | auto-discovers `*.resource.ts` (src in dev, dist in prod); `context` threads handles into `(ctx) => defineResource(...)` exports; `filter(absPath)` gates files before import |
30
+ | `role` | `api`/`worker` arm no module schedules; `relay` arms only `kind: 'relay'` arms; `scheduler` arms all; `relay`/`scheduler` with `resources` is boot-fatal; default `all` |
31
+ | `modules` | `defineModule` units (resources, events, scheduledJobs, healthChecks, errorMappers, workflows) |
32
+ | `errorHandler` | `{ errorMappers, includeStack, exposeInternalMessages, notFound }`; `false` registers none |
33
+ | `logger.redact` | REPLACES arc's defaults: spread `DEFAULT_LOGGER_REDACT_PATHS` from `@classytic/arc/factory` |
34
+ | `stores` | event transport, query cache, idempotency, etc.; arc closes only stores it built |
35
+ | `rateLimit.plan` | per-plan ceilings: `{ resolve, limits: { free: { max: 60 }, enterprise: false }, default }` |
36
+
37
+ `createWorker(sameOptions)` (`@classytic/arc/factory`) boots the headless process: no HTTP, runs events, schedules and relays. Error disclosure (`includeStack`, `exposeInternalMessages`) derives from `preset`, else the environment; host keys merge over the derived pair.
38
+
39
+ Unknown routes answer `404 { code: 'arc.not_found', message, status, correlationId }` by default. A host that calls `setNotFoundHandler` itself passes `errorHandler: { notFound: false }` (Fastify allows one per scope); `notFound: (request, reply) => ...` replaces arc's.
40
+
41
+ ## Controllers
42
+
43
+ The auto-built `BaseController` covers every preset. Write one only for domain methods:
44
+
45
+ ```typescript
46
+ import { BaseController, type IControllerResponse, type IRequestContext } from '@classytic/arc';
47
+
48
+ class ProductController extends BaseController<Product> {
49
+ constructor(opts: { tenantField?: string | false; idField?: string } = {}) {
50
+ super(productRepo, { resourceName: 'product', ...opts });
51
+ }
52
+ async getFeatured(req: IRequestContext): Promise<IControllerResponse<Product[]>> {
53
+ return { data: await this.repository.getAll({ filters: { isFeatured: true } }) };
54
+ }
55
+ }
56
+ ```
57
+
58
+ Slim mixins: `class OrderController extends SoftDeleteMixin(BulkMixin(BaseCrudController)) {}`.
59
+
60
+ ## DX helpers
61
+
62
+ ```typescript
63
+ import { multipartBody } from '@classytic/arc/middleware';
64
+ import { defineGuard } from '@classytic/arc/utils';
65
+
66
+ middlewares: { create: [multipartBody({ allowedMimeTypes: ['image/png'], maxFileSize: 5_000_000 })] } // no-op for JSON
67
+ routeGuards: [tenantGuard.preHandler] // every route; order: auth, permissions, cache/idempotency, routeGuards, route preHandler
68
+ routes: [{ method: 'POST', path: '/export', handler: 'export', permissions: requireAuth(),
69
+ rateLimit: { max: 5, timeWindow: '1 minute' } }] // false = never throttle
70
+ routes: [{ preAuth: [(req) => { req.headers.authorization = `Bearer ${req.query.token}`; }] }] // EventSource token
71
+ ```
72
+
73
+ - `req: ArcRequest` types `user`, `scope`, `signal`. `request.user` is undefined on public routes: guard it.
74
+ - Reply helpers (opt in with `createApp({ replyHelpers: true })`): `reply.sendList(...)`, `reply.stream(readable, { contentType, filename })`.
75
+ - `streamResponse: true` routes returning a Web `ReadableStream` (AI SDK UI message stream) are piped for you; manual: `pipeUIMessageStreamToReply` from `@classytic/arc/utils`.
76
+ - `verifySignature(body, ...)` needs `req.rawBody`, not the parsed body.
77
+
78
+ ## CLI
79
+
80
+ `arc init my-api --mongokit --better-auth --ts` scaffolds; `arc generate resource product [--mcp]`; `arc docs ./openapi.json --entry ./dist/index.js`; `arc introspect`; `arc describe <file> --json`; `arc doctor`.