@getstrata/core 2.2.60 → 3.0.4

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 (330) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/core/audit/exportAuditLogs.d.ts +12 -3
  3. package/dist/core/audit/exportStore.d.ts +6 -2
  4. package/dist/core/audit/siemFormatter.d.ts +2 -2
  5. package/dist/core/auth/abilityCatalog.d.ts +1 -9
  6. package/dist/core/auth/authContext.d.ts +2 -0
  7. package/dist/core/auth/authOutcome.d.ts +32 -0
  8. package/dist/core/auth/authReader.d.ts +22 -0
  9. package/dist/core/auth/basicAuthGuard.d.ts +19 -3
  10. package/dist/core/auth/emailVerification.d.ts +1 -1
  11. package/dist/core/auth/guard.d.ts +27 -6
  12. package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
  13. package/dist/core/auth/jwt.d.ts +5 -4
  14. package/dist/core/auth/jwtGuard.d.ts +7 -6
  15. package/dist/core/auth/membershipContext.d.ts +10 -7
  16. package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
  17. package/dist/core/auth/membershipMiddleware.d.ts +1 -2
  18. package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
  19. package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
  20. package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
  21. package/dist/core/auth/oauth/providers.d.ts +3 -1
  22. package/dist/core/auth/oneTimeToken.d.ts +2 -3
  23. package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
  24. package/dist/core/auth/passwordLogin.d.ts +5 -5
  25. package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
  26. package/dist/core/auth/policy.d.ts +23 -10
  27. package/dist/core/auth/requireAuthCapability.d.ts +3 -0
  28. package/dist/core/auth/resolveMembershipService.d.ts +3 -2
  29. package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
  30. package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
  31. package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
  32. package/dist/core/auth/sessionCookie.d.ts +20 -9
  33. package/dist/core/auth/sessionGuard.d.ts +14 -3
  34. package/dist/core/cache/createCacheStore.d.ts +6 -3
  35. package/dist/core/cache/redisCacheStore.d.ts +5 -1
  36. package/dist/core/cache/repository.d.ts +5 -1
  37. package/dist/core/cache/simpleCache.d.ts +2 -1
  38. package/dist/core/cache/tokens.d.ts +8 -0
  39. package/dist/core/config/applicationConfig.d.ts +21 -0
  40. package/dist/core/config/configSnapshot.d.ts +3 -0
  41. package/dist/core/config/envSchema.d.ts +3 -2
  42. package/dist/core/contracts/application.d.ts +153 -0
  43. package/dist/core/contracts/authUserDirectory.d.ts +24 -7
  44. package/dist/core/contracts/container.d.ts +20 -23
  45. package/dist/core/contracts/di.d.ts +4 -2
  46. package/dist/core/contracts/executionContext.d.ts +5 -0
  47. package/dist/core/contracts/executionOperations.d.ts +10 -0
  48. package/dist/core/contracts/executionOwnership.d.ts +38 -0
  49. package/dist/core/contracts/persistence.d.ts +20 -0
  50. package/dist/core/contracts/serviceTokens.d.ts +32 -18
  51. package/dist/core/contracts/services.d.ts +63 -0
  52. package/dist/core/contracts/token.d.ts +19 -0
  53. package/dist/core/crypto/fieldEncryption.d.ts +19 -7
  54. package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
  55. package/dist/core/crypto/mfaSecret.d.ts +10 -3
  56. package/dist/core/database/baseRepository.d.ts +14 -10
  57. package/dist/core/database/bindings.d.ts +6 -0
  58. package/dist/core/database/bunSql.d.ts +3 -12
  59. package/dist/core/database/definitions.d.ts +209 -0
  60. package/dist/core/database/dialect.d.ts +5 -24
  61. package/dist/core/database/driverPorts.d.ts +116 -0
  62. package/dist/core/database/errors.d.ts +47 -7
  63. package/dist/core/database/factory.d.ts +51 -31
  64. package/dist/core/database/index.d.ts +9 -10
  65. package/dist/core/database/keyset.d.ts +2 -1
  66. package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
  67. package/dist/core/database/manager.d.ts +12 -0
  68. package/dist/core/database/model.d.ts +91 -97
  69. package/dist/core/database/modelQuery.d.ts +9 -5
  70. package/dist/core/database/modelRegistry.d.ts +52 -33
  71. package/dist/core/database/mysqlConnection.d.ts +1 -19
  72. package/dist/core/database/mysqlNative.d.ts +38 -0
  73. package/dist/core/database/nativeTransactions.d.ts +16 -0
  74. package/dist/core/database/ormInternal.d.ts +85 -0
  75. package/dist/core/database/ormRuntime.d.ts +4 -0
  76. package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
  77. package/dist/core/database/postgresNative.d.ts +11 -0
  78. package/dist/core/database/query.d.ts +24 -23
  79. package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
  80. package/dist/core/database/rawMysql.d.ts +7 -0
  81. package/dist/core/database/rawPostgres.d.ts +23 -0
  82. package/dist/core/database/rawSqlite.d.ts +6 -0
  83. package/dist/core/database/relationQueries.d.ts +3 -2
  84. package/dist/core/database/relationQuery.d.ts +24 -6
  85. package/dist/core/database/repositoryQuery.d.ts +6 -1
  86. package/dist/core/database/schema/driver.d.ts +1 -1
  87. package/dist/core/database/seeders/types.d.ts +1 -1
  88. package/dist/core/database/session.d.ts +13 -0
  89. package/dist/core/database/sessionFactory.d.ts +9 -0
  90. package/dist/core/database/sqlDialects.d.ts +22 -0
  91. package/dist/core/database/tokens.d.ts +7 -0
  92. package/dist/core/database/transactionSession.d.ts +43 -0
  93. package/dist/core/errors/http.d.ts +4 -1
  94. package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
  95. package/dist/core/events/index.d.ts +2 -3
  96. package/dist/core/events/outbox/index.d.ts +44 -13
  97. package/dist/core/events/outbox/metrics.d.ts +4 -4
  98. package/dist/core/events/outbox/workerTransport.d.ts +17 -0
  99. package/dist/core/http/authMiddleware.d.ts +2 -2
  100. package/dist/core/http/authorizeMiddleware.d.ts +2 -2
  101. package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
  102. package/dist/core/http/conditionalResponse.d.ts +7 -2
  103. package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
  104. package/dist/core/http/corsMiddleware.d.ts +2 -1
  105. package/dist/core/http/csrfMiddleware.d.ts +6 -1
  106. package/dist/core/http/csrfToken.d.ts +17 -7
  107. package/dist/core/http/databaseError.d.ts +4 -0
  108. package/dist/core/http/etag.d.ts +5 -2
  109. package/dist/core/http/flashMiddleware.d.ts +1 -1
  110. package/dist/core/http/flashSession.d.ts +13 -7
  111. package/dist/core/http/index.d.ts +1 -1
  112. package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
  113. package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
  114. package/dist/core/http/parseMultipartUpload.d.ts +3 -2
  115. package/dist/core/http/requestMetaContext.d.ts +5 -0
  116. package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
  117. package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
  118. package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
  119. package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
  120. package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
  121. package/dist/core/http/response.d.ts +4 -3
  122. package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
  123. package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
  124. package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
  125. package/dist/core/http/signedUrl.d.ts +8 -6
  126. package/dist/core/http/throttleMiddleware.d.ts +9 -5
  127. package/dist/core/http/uploads.d.ts +9 -3
  128. package/dist/core/http/webErrorResponse.d.ts +8 -2
  129. package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
  130. package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
  131. package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
  132. package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
  133. package/dist/core/mail/mailer.d.ts +7 -5
  134. package/dist/core/openapi/generator.d.ts +12 -4
  135. package/dist/core/openapi/registeredRoute.d.ts +4 -4
  136. package/dist/core/queue/createAppQueue.d.ts +9 -4
  137. package/dist/core/queue/failedJobMetrics.d.ts +11 -2
  138. package/dist/core/queue/failedJobRepository.d.ts +6 -3
  139. package/dist/core/queue/failedJobService.d.ts +1 -0
  140. package/dist/core/queue/index.d.ts +16 -6
  141. package/dist/core/queue/jobRegistry.d.ts +3 -2
  142. package/dist/core/queue/jobRunner.d.ts +10 -4
  143. package/dist/core/queue/publicQueue.d.ts +18 -9
  144. package/dist/core/queue/queueConfig.d.ts +20 -10
  145. package/dist/core/queue/queueHandoff.d.ts +31 -0
  146. package/dist/core/queue/queueMetrics.d.ts +10 -3
  147. package/dist/core/queue/queueServices.d.ts +28 -0
  148. package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
  149. package/dist/core/queue/redisQueue.d.ts +19 -10
  150. package/dist/core/queue/redisQueueKeys.d.ts +5 -5
  151. package/dist/core/queue/redisStreams.d.ts +17 -10
  152. package/dist/core/queue/resilientQueue.d.ts +10 -4
  153. package/dist/core/queue/types.d.ts +1 -0
  154. package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
  155. package/dist/core/runtime/application.d.ts +7 -0
  156. package/dist/core/runtime/executionContext.d.ts +9 -0
  157. package/dist/core/runtime/executionTasks.d.ts +49 -0
  158. package/dist/core/runtime/resourceJournal.d.ts +67 -0
  159. package/dist/core/runtime/serviceGraph.d.ts +14 -0
  160. package/dist/core/security/oauthState.d.ts +13 -9
  161. package/dist/core/security/publicReads.d.ts +2 -2
  162. package/dist/core/security/safeFetch.d.ts +1 -0
  163. package/dist/core/security/safeUrl.d.ts +3 -0
  164. package/dist/core/security/scimTenantTokens.d.ts +1 -1
  165. package/dist/core/security/tokenExpiry.d.ts +1 -1
  166. package/dist/core/security/webhookSignature.d.ts +1 -1
  167. package/dist/core/storage/storage.d.ts +24 -16
  168. package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
  169. package/dist/core/tenant/resolveTenant.d.ts +2 -2
  170. package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
  171. package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
  172. package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
  173. package/dist/core/tracing/otel.d.ts +4 -6
  174. package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
  175. package/dist/core/view/etaViewEngine.d.ts +1 -1
  176. package/dist/core/view/index.d.ts +5 -4
  177. package/dist/core/view/tokens.d.ts +8 -0
  178. package/dist/core/view/viewRenderer.d.ts +2 -2
  179. package/dist/core/view/webErrorView.d.ts +8 -7
  180. package/dist/core/view/webLayoutData.d.ts +6 -4
  181. package/dist/entries/audit/exportAuditLogs.js +87 -1024
  182. package/dist/entries/audit/siemFormatter.js +4 -90
  183. package/dist/entries/auth/abilityCatalog.js +28 -0
  184. package/dist/entries/auth/accessControl.js +5 -16
  185. package/dist/entries/auth/accountStateMigration.js +216 -236
  186. package/dist/entries/auth/authOutcome.js +80 -0
  187. package/dist/entries/auth/authReader.js +68 -0
  188. package/dist/entries/auth/basicAuthGuard.js +144 -1249
  189. package/dist/entries/auth/emailVerification.js +2 -2
  190. package/dist/entries/auth/intendedUrlCookie.js +35 -59
  191. package/dist/entries/auth/jwt.js +22 -47
  192. package/dist/entries/auth/jwtGuard.js +99 -231
  193. package/dist/entries/auth/membershipMiddleware.js +71 -10
  194. package/dist/entries/auth/membershipScope.js +16 -22
  195. package/dist/entries/auth/membershipService.js +11 -28
  196. package/dist/entries/auth/oauth/oidcProvider.js +59 -64
  197. package/dist/entries/auth/oauth/providers.js +12 -95
  198. package/dist/entries/auth/oauth/samlProvider.js +53 -1080
  199. package/dist/entries/auth/oneTimeToken.js +27 -289
  200. package/dist/entries/auth/passwordConfirmCookie.js +40 -63
  201. package/dist/entries/auth/passwordLogin.js +94 -399
  202. package/dist/entries/auth/pendingMfaCookie.js +6 -6
  203. package/dist/entries/auth/policy.js +22 -56
  204. package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
  205. package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
  206. package/dist/entries/auth/sessionCookie.js +58 -73
  207. package/dist/entries/auth/sessionGuard.js +95 -248
  208. package/dist/entries/auth/tokenHash.js +11 -43
  209. package/dist/entries/cache/createCacheStore.js +126 -117
  210. package/dist/entries/cache/repository.js +25 -0
  211. package/dist/entries/cache/simpleCache.js +12 -7
  212. package/dist/entries/cache/tokens.js +9 -0
  213. package/dist/entries/config/applicationConfig.js +163 -0
  214. package/dist/entries/config/envSchema.js +21 -4
  215. package/dist/entries/contracts/application.js +1 -0
  216. package/dist/entries/contracts/authUserDirectory.js +10 -0
  217. package/dist/entries/contracts/container.js +99 -26
  218. package/dist/entries/contracts/di.js +3 -0
  219. package/dist/entries/contracts/executionContext.js +7 -0
  220. package/dist/entries/contracts/executionOperations.js +7 -0
  221. package/dist/entries/contracts/executionOwnership.js +7 -0
  222. package/dist/entries/contracts/membership.js +1 -0
  223. package/dist/entries/contracts/persistence.js +1 -0
  224. package/dist/entries/contracts/serviceTokens.js +26 -116
  225. package/dist/entries/contracts/services.js +98 -0
  226. package/dist/entries/contracts/token.js +41 -0
  227. package/dist/entries/crypto/fieldEncryption.js +49 -50
  228. package/dist/entries/crypto/mfaSecret.js +86 -82
  229. package/dist/entries/database/acquisitionMetrics.js +107 -0
  230. package/dist/entries/database/baseRepository.d.ts +2 -0
  231. package/dist/entries/database/bindings.js +2082 -0
  232. package/dist/entries/database/definitions.js +175 -0
  233. package/dist/entries/database/errors.js +114 -89
  234. package/dist/entries/database/factory.js +67 -28
  235. package/dist/entries/database/migrations.js +172 -224
  236. package/dist/entries/database/model.d.ts +1 -0
  237. package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
  238. package/dist/entries/database/query.js +159 -161
  239. package/dist/entries/database/repositoryQuery.d.ts +1 -0
  240. package/dist/entries/database/repositoryQuery.js +1 -1373
  241. package/dist/entries/database/schema.js +216 -236
  242. package/dist/entries/database/session.js +1 -0
  243. package/dist/entries/database/sqliteConnection.js +525 -83
  244. package/dist/entries/database/tokens.js +9 -0
  245. package/dist/entries/errors/http.js +118 -1
  246. package/dist/entries/http/authMiddleware.js +8 -5
  247. package/dist/entries/http/authorizeMiddleware.js +1 -1
  248. package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
  249. package/dist/entries/http/clientIp.js +2 -2
  250. package/dist/entries/http/conditionalResponse.js +19 -7
  251. package/dist/entries/http/corsMiddleware.js +6 -101
  252. package/dist/entries/http/csrfMiddleware.js +92 -106
  253. package/dist/entries/http/csrfToken.js +58 -94
  254. package/dist/entries/http/etag.js +7 -4
  255. package/dist/entries/http/flashMiddleware.js +57 -99
  256. package/dist/entries/http/flashSession.js +41 -68
  257. package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
  258. package/dist/entries/http/metricsMiddleware.js +2 -16
  259. package/dist/entries/http/parseMultipartUpload.js +15 -29
  260. package/dist/entries/http/requireAbilityMiddleware.js +2 -2
  261. package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
  262. package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
  263. package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
  264. package/dist/entries/http/response.js +67 -233
  265. package/dist/entries/http/routeMiddleware.js +0 -14
  266. package/dist/entries/http/scimThrottleMiddleware.js +43 -237
  267. package/dist/entries/http/securedRouteModelBinding.js +37 -25
  268. package/dist/entries/http/securityHeadersMiddleware.js +8 -25
  269. package/dist/entries/http/signedUrl.js +20 -110
  270. package/dist/entries/http/throttleMiddleware.js +41 -185
  271. package/dist/entries/http/uploads.js +9 -24
  272. package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
  273. package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
  274. package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
  275. package/dist/entries/mail/mailer.js +68 -78
  276. package/dist/entries/openapi/generator.js +33 -100
  277. package/dist/entries/queue/createAppQueue.js +416 -256
  278. package/dist/entries/queue/failedJobRepository.js +17 -8
  279. package/dist/entries/queue/failedJobService.js +1 -0
  280. package/dist/entries/queue/jobRunner.js +141 -66
  281. package/dist/entries/queue/publicQueue.js +411 -257
  282. package/dist/entries/queue/queueConfig.js +61 -0
  283. package/dist/entries/queue/queueHandoff.js +318 -0
  284. package/dist/entries/queue/queueMetrics.js +989 -1386
  285. package/dist/entries/queue/queueServices.js +133 -0
  286. package/dist/entries/queue/queueWorkerTransport.js +1703 -0
  287. package/dist/entries/queue/redisQueue.js +282 -180
  288. package/dist/entries/queue.js +6 -45
  289. package/dist/entries/runtime/application.js +1585 -0
  290. package/dist/entries/runtime/asyncContextStore.js +0 -16
  291. package/dist/entries/security/oauthState.js +35 -67
  292. package/dist/entries/security/publicReads.js +4 -4
  293. package/dist/entries/security/safeFetch.js +1 -0
  294. package/dist/entries/security/scimTenantTokens.js +3 -3
  295. package/dist/entries/security/tokenExpiry.js +2 -2
  296. package/dist/entries/security/totp.js +1 -87
  297. package/dist/entries/security/webhookSignature.js +2 -90
  298. package/dist/entries/storage/storage.js +120 -45
  299. package/dist/entries/tenant/databaseTenantContext.js +6 -907
  300. package/dist/entries/tenant/publicTenantHost.js +78 -0
  301. package/dist/entries/tenant/resolveTenant.js +14 -0
  302. package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
  303. package/dist/entries/tenant/tenancyConfig.js +1 -19
  304. package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
  305. package/dist/entries/tracing/tracingMiddleware.js +104 -173
  306. package/dist/entries/view/tokens.js +11 -0
  307. package/dist/framework/public-api.d.ts +62 -44
  308. package/dist/index.js +10435 -11351
  309. package/dist/internal/ormInternal.js +117 -0
  310. package/dist/internal/ormRuntime.js +5000 -0
  311. package/package.json +158 -46
  312. package/dist/core/database/bindConnection.d.ts +0 -1
  313. package/dist/core/database/boundConnection.d.ts +0 -5
  314. package/dist/core/database/defaultConnection.d.ts +0 -7
  315. package/dist/core/database/namedConnections.d.ts +0 -15
  316. package/dist/core/database/readOnlyCollector.d.ts +0 -7
  317. package/dist/core/database/repositoryConnection.d.ts +0 -4
  318. package/dist/core/database/transaction.d.ts +0 -23
  319. package/dist/core/database/transactionControl.d.ts +0 -6
  320. package/dist/core/events/deferredModelEvents.d.ts +0 -7
  321. package/dist/core/facades/index.d.ts +0 -10
  322. package/dist/core/runtime/applicationRegistry.d.ts +0 -18
  323. package/dist/entries/database/bindConnection.js +0 -1
  324. package/dist/entries/database/boundConnection.js +0 -1
  325. package/dist/entries/database/defaultConnection.js +0 -1
  326. package/dist/entries/database/namedConnections.js +0 -1
  327. package/dist/entries/database/repositoryConnection.js +0 -1
  328. package/dist/entries/database/transaction.js +0 -1
  329. package/dist/entries/facades.js +0 -711
  330. package/dist/entries/runtime/applicationRegistry.js +0 -1
@@ -1,141 +1,9 @@
1
1
  // @bun
2
- // ../../src/core/contracts/container.ts
3
- function createServiceToken(key) {
4
- if (!key.trim())
5
- throw new Error("Service token key must not be empty.");
6
- return key;
7
- }
8
-
9
- class ServiceContainer {
10
- services = new Map;
11
- singletonFactories = new Map;
12
- bindings = new Map;
13
- resolutionPath = [];
14
- set(key, value) {
15
- this.singletonFactories.delete(key);
16
- this.bindings.delete(key);
17
- this.services.set(key, value);
18
- return value;
19
- }
20
- singleton(key, factory) {
21
- this.bindings.delete(key);
22
- this.services.delete(key);
23
- this.singletonFactories.set(key, factory);
24
- }
25
- bind(key, factory) {
26
- this.singletonFactories.delete(key);
27
- this.services.delete(key);
28
- this.bindings.set(key, factory);
29
- }
30
- get(key) {
31
- if (this.services.has(key)) {
32
- return this.services.get(key);
33
- }
34
- const singletonFactory = this.singletonFactories.get(key);
35
- if (singletonFactory) {
36
- const value = this.resolveFactory(key, singletonFactory);
37
- this.services.set(key, value);
38
- return value;
39
- }
40
- const binding = this.bindings.get(key);
41
- if (binding) {
42
- return this.resolveFactory(key, binding);
43
- }
44
- throw new Error(`Service "${key}" is not registered.`);
45
- }
46
- resolveFactory(key, factory) {
47
- if (this.resolutionPath.includes(key)) {
48
- throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
49
- }
50
- this.resolutionPath.push(key);
51
- try {
52
- return factory(this);
53
- } finally {
54
- this.resolutionPath.pop();
55
- }
56
- }
57
- resolve(key) {
58
- return this.get(key);
59
- }
60
- make(key) {
61
- return this.resolve(key);
62
- }
63
- instance(key, value) {
64
- return this.set(key, value);
65
- }
66
- has(key) {
67
- return this.services.has(key) || this.singletonFactories.has(key) || this.bindings.has(key);
68
- }
69
- }
70
-
71
- class ConfigStore {
72
- values = new Map;
73
- set(key, value) {
74
- this.values.set(key, value);
75
- return value;
76
- }
77
- get(key) {
78
- return this.values.get(key);
79
- }
80
- require(key) {
81
- if (!this.values.has(key)) {
82
- throw new Error(`Config key "${key}" is not defined.`);
83
- }
84
- return this.values.get(key);
85
- }
86
- has(key) {
87
- return this.values.has(key);
88
- }
89
- }
90
-
91
- // ../../src/core/contracts/serviceTokens.ts
92
- var CORE_THROTTLE_QUOTA_POLICY_TOKEN = createServiceToken("core.throttleQuotaPolicy");
93
- var CORE_PUBLIC_TENANCY_TOKEN = createServiceToken("core.publicTenancy");
94
- var CORE_TENANT_RESOLVER_TOKEN = createServiceToken("core.tenantResolver");
95
- var CORE_HTTP_CLEANUP_TOKEN = createServiceToken("core.httpCleanup");
96
- var CORE_CONFIG_TOKEN = "core.config";
97
- var CORE_CACHE_TOKEN = "core.cache";
98
- var CORE_QUEUE_TOKEN = "core.queue";
99
- var CORE_EVENT_BUS_TOKEN = "core.eventBus";
100
- var CORE_POLICY_GATE_TOKEN = "core.policyGate";
101
- var CORE_AUTH_TOKEN = "core.auth";
102
- var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
103
- var CORE_ABILITY_CHECKER_TOKEN = "core.abilityChecker";
104
- var CORE_AUTH_USER_DIRECTORY_TOKEN = "core.authUserDirectory";
105
- function isAbilityChecker(value) {
106
- if (!value || typeof value !== "object") {
107
- return false;
108
- }
109
- const candidate = value;
110
- return typeof candidate.tokenCan === "function" && typeof candidate.requireAbility === "function";
111
- }
112
- function isAuthUserDirectory(value) {
113
- if (!value || typeof value !== "object") {
114
- return false;
115
- }
116
- return typeof value.findByIdOrThrow === "function";
117
- }
118
- function resolveAbilityChecker(container) {
119
- if (container.has(CORE_ABILITY_CHECKER_TOKEN)) {
120
- return container.resolve(CORE_ABILITY_CHECKER_TOKEN);
121
- }
122
- return container.resolve(CORE_TOKEN_SERVICE_TOKEN);
123
- }
124
- function resolveAuthUserDirectory(container) {
125
- if (container.has(CORE_AUTH_USER_DIRECTORY_TOKEN)) {
126
- const directory = container.resolve(CORE_AUTH_USER_DIRECTORY_TOKEN);
127
- if (isAuthUserDirectory(directory)) {
128
- return directory;
129
- }
130
- }
131
- if (container.has(CORE_TOKEN_SERVICE_TOKEN)) {
132
- const tokenService = container.resolve(CORE_TOKEN_SERVICE_TOKEN);
133
- if (isAuthUserDirectory(tokenService)) {
134
- return tokenService;
135
- }
136
- }
137
- return null;
138
- }
2
+ // ../../src/core/auth/jwtGuard.ts
3
+ import {
4
+ authenticateProof,
5
+ authUserFromOutcome
6
+ } from "@getstrata/core/auth/authOutcome";
139
7
 
140
8
  // ../../src/core/http/statelessAuth.ts
141
9
  function authorizationScheme(request) {
@@ -216,14 +84,14 @@ function envFlagEnabled(value) {
216
84
  }
217
85
 
218
86
  // ../../src/core/runtime/appKeyPrefix.ts
219
- function appKeyPrefix() {
220
- return process.env.APP_KEY_PREFIX?.trim() || "strata";
87
+ function appKeyPrefix(env = process.env) {
88
+ return env.APP_KEY_PREFIX?.trim() || "strata";
221
89
  }
222
- function appCookieName(kind) {
223
- return `${appKeyPrefix()}_${kind}`;
90
+ function appCookieName(kind, env = process.env) {
91
+ return `${appKeyPrefix(env)}_${kind}`;
224
92
  }
225
- function appDevSecret(kind) {
226
- return `${appKeyPrefix()}-dev-${kind}`;
93
+ function appDevSecret(kind, env = process.env) {
94
+ return `${appKeyPrefix(env)}-dev-${kind}`;
227
95
  }
228
96
  function requireConfiguredSecret(names, devKind, env = process.env) {
229
97
  for (const name of names) {
@@ -235,65 +103,39 @@ function requireConfiguredSecret(names, devKind, env = process.env) {
235
103
  if (isProductionEnv(env)) {
236
104
  throw new Error(`${names[0]} must be set outside development. Do not derive secrets from the app name.`);
237
105
  }
238
- return appDevSecret(devKind);
106
+ return appDevSecret(devKind, env);
239
107
  }
240
108
  function namespacedRedisKey(kind) {
241
109
  return `${appKeyPrefix()}:${kind}`;
242
110
  }
243
- function smtpEhloHost() {
244
- const raw = process.env.MAIL_EHLO?.trim() || `${appKeyPrefix()}.local`;
111
+ function smtpEhloHost(env = process.env) {
112
+ const raw = env.MAIL_EHLO?.trim() || `${appKeyPrefix(env)}.local`;
245
113
  const safe = raw.replace(/[^a-zA-Z0-9.-]/g, "");
246
114
  return safe || "strata.local";
247
115
  }
248
- function siemEventType() {
249
- return process.env.SIEM_EVENT_TYPE?.trim() || `${appKeyPrefix()}.audit`;
250
- }
251
- function appUserAgent() {
252
- return process.env.APP_USER_AGENT?.trim() || appKeyPrefix();
253
- }
254
- function otelServiceName() {
255
- return process.env.OTEL_SERVICE_NAME?.trim() || `${appKeyPrefix()}-api`;
256
- }
257
- function webhookSignatureHeader() {
258
- return process.env.WEBHOOK_SIGNATURE_HEADER?.trim() || `x-${appKeyPrefix()}-signature`;
259
- }
260
- function appDisplayName() {
261
- return process.env.APP_NAME?.trim() || "Strata";
262
- }
263
- function appEnv() {
264
- return process.env.APP_ENV?.trim() || "local";
265
- }
266
- function appUrl() {
267
- return (process.env.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "");
268
- }
269
- function apiPrefix() {
270
- const raw = process.env.API_PREFIX?.trim() || "/api/v1";
271
- const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
272
- const trimmed = withSlash.replace(/\/+$/, "");
273
- return trimmed || "/api/v1";
274
- }
275
- function sdkClientClassName() {
276
- const override = process.env.APP_SDK_CLASS?.trim();
277
- if (override && /^[A-Za-z_][A-Za-z0-9_]*$/.test(override)) {
278
- return override;
279
- }
280
- const fromName = appDisplayName().replace(/[^A-Za-z0-9]/g, "");
281
- return fromName ? `${fromName}Client` : "AppClient";
116
+ function otelServiceName(env = process.env) {
117
+ return env.OTEL_SERVICE_NAME?.trim() || `${appKeyPrefix(env)}-api`;
282
118
  }
283
119
 
284
120
  // ../../src/core/auth/jwt.ts
121
+ function jwtOptionsFromEnvironment(env) {
122
+ const parsed = Number.parseInt(env.JWT_TTL_SECONDS ?? "", 10);
123
+ return Object.freeze({
124
+ secret: requireConfiguredSecret(["JWT_SECRET", "SESSION_SECRET"], "jwt-secret", env),
125
+ ttlSeconds: Number.isInteger(parsed) && parsed > 0 ? parsed : 3600
126
+ });
127
+ }
285
128
  function resolveJwtSecret(secret) {
286
129
  if (secret?.trim()) {
287
130
  return secret.trim();
288
131
  }
289
- return requireConfiguredSecret(["JWT_SECRET", "SESSION_SECRET"], "jwt-secret");
132
+ throw new TypeError("Explicit JWT secret is required.");
290
133
  }
291
134
  function jwtTtlSeconds(override) {
292
135
  if (typeof override === "number" && Number.isInteger(override) && override > 0) {
293
136
  return override;
294
137
  }
295
- const parsed = Number.parseInt(process.env.JWT_TTL_SECONDS ?? "", 10);
296
- return Number.isInteger(parsed) && parsed > 0 ? parsed : 3600;
138
+ return 3600;
297
139
  }
298
140
  function encodeJson(value) {
299
141
  return Buffer.from(JSON.stringify(value)).toString("base64url");
@@ -316,7 +158,7 @@ function signaturesMatch(left, right) {
316
158
  }
317
159
  return timingSafeEqual(leftBuffer, rightBuffer);
318
160
  }
319
- function signJwt(payload, options = {}) {
161
+ function signJwt(payload, options) {
320
162
  const issuedAt = Date.now() / 1000;
321
163
  const body = {
322
164
  ...payload,
@@ -356,6 +198,14 @@ function verifyJwt(token, secret) {
356
198
  return payload;
357
199
  }
358
200
 
201
+ // ../../src/core/auth/requireAuthCapability.ts
202
+ function requireAuthCapability(value, methods, mechanism) {
203
+ if (!value || typeof value !== "object" || methods.some((method) => typeof Reflect.get(value, method) !== "function")) {
204
+ throw new TypeError(`Missing ${mechanism} authentication capability: ${methods.join(", ")}.`);
205
+ }
206
+ return value;
207
+ }
208
+
359
209
  // ../../src/core/auth/sessionCookie.ts
360
210
  import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual2 } from "crypto";
361
211
 
@@ -392,31 +242,46 @@ function readBunRequestCookie(request, name) {
392
242
  }
393
243
 
394
244
  // ../../src/core/auth/sessionCookie.ts
395
- var SESSION_COOKIE = appCookieName("session");
245
+ var SESSION_COOKIE = "strata_session";
396
246
  var SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
397
247
  var SESSION_REMEMBER_TTL_SECONDS = 60 * 60 * 24 * 30;
398
- function sessionCookieName() {
399
- return process.env.SESSION_COOKIE_NAME?.trim() || appCookieName("session");
248
+ function sessionCookieOptionsFromEnvironment(env) {
249
+ return Object.freeze({
250
+ cookieName: sessionCookieName(env),
251
+ secret: requireConfiguredSecret(["SESSION_SECRET"], "session-secret", env),
252
+ ttlSeconds: sessionTtlSeconds(env),
253
+ rememberTtlSeconds: sessionRememberTtlSeconds(env),
254
+ production: isProductionEnv(env)
255
+ });
256
+ }
257
+ function createSessionReader(options) {
258
+ const snapshot = Object.freeze({ ...options });
259
+ if (!snapshot.cookieName || !snapshot.secret || !Number.isSafeInteger(snapshot.ttlSeconds) || snapshot.ttlSeconds <= 0)
260
+ throw new TypeError("Invalid session reader configuration.");
261
+ return (request) => readSession(request, snapshot);
262
+ }
263
+ function sessionCookieName(env) {
264
+ return env.SESSION_COOKIE_NAME?.trim() || appCookieName("session", env);
400
265
  }
401
266
  function parsePositiveSeconds(raw, fallback) {
402
267
  const parsed = Number.parseInt(raw ?? "", 10);
403
268
  return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
404
269
  }
405
- function sessionTtlSeconds() {
406
- return parsePositiveSeconds(process.env.SESSION_TTL_SECONDS, SESSION_TTL_SECONDS);
270
+ function sessionTtlSeconds(env) {
271
+ return parsePositiveSeconds(env.SESSION_TTL_SECONDS, SESSION_TTL_SECONDS);
407
272
  }
408
- function sessionRememberTtlSeconds() {
409
- return parsePositiveSeconds(process.env.SESSION_REMEMBER_TTL_SECONDS, SESSION_REMEMBER_TTL_SECONDS);
273
+ function sessionRememberTtlSeconds(env) {
274
+ return parsePositiveSeconds(env.SESSION_REMEMBER_TTL_SECONDS, SESSION_REMEMBER_TTL_SECONDS);
410
275
  }
411
- function resolveSessionSecret() {
412
- return requireConfiguredSecret(["SESSION_SECRET"], "session-secret");
276
+ function missingSessionSecret() {
277
+ throw new TypeError("Explicit session secret is required.");
413
278
  }
414
- function signSession(userId, issuedAt, ttlSeconds, authVersion) {
279
+ function signSession(userId, issuedAt, ttlSeconds, authVersion, secret) {
415
280
  const payload = authVersion !== undefined ? `v2.${userId}.${issuedAt}.${ttlSeconds}.${authVersion}` : ttlSeconds === undefined ? `${userId}.${issuedAt}` : `${userId}.${issuedAt}.${ttlSeconds}`;
416
- const signature = createHmac2("sha256", resolveSessionSecret()).update(payload).digest("hex");
281
+ const signature = createHmac2("sha256", secret ?? missingSessionSecret()).update(payload).digest("hex");
417
282
  return `${payload}.${signature}`;
418
283
  }
419
- function readSignedSession(userIdRaw, issuedAtRaw, cookieSignature, ttlSeconds, remember, authVersion) {
284
+ function readSignedSession(userIdRaw, issuedAtRaw, cookieSignature, ttlSeconds, remember, authVersion, options) {
420
285
  const userId = Number.parseInt(userIdRaw, 10);
421
286
  const issuedAt = Number.parseInt(issuedAtRaw, 10);
422
287
  if (!Number.isInteger(userId) || userId <= 0 || !Number.isFinite(issuedAt)) {
@@ -428,7 +293,7 @@ function readSignedSession(userIdRaw, issuedAtRaw, cookieSignature, ttlSeconds,
428
293
  if (Date.now() - issuedAt > ttlSeconds * 1000) {
429
294
  return null;
430
295
  }
431
- const expectedSignature = (authVersion !== undefined ? signSession(userId, issuedAt, ttlSeconds, authVersion) : remember ? signSession(userId, issuedAt, ttlSeconds) : signSession(userId, issuedAt)).split(".").pop();
296
+ const expectedSignature = (authVersion !== undefined ? signSession(userId, issuedAt, ttlSeconds, authVersion, options.secret) : remember ? signSession(userId, issuedAt, ttlSeconds, undefined, options.secret) : signSession(userId, issuedAt, undefined, undefined, options.secret)).split(".").pop();
432
297
  if (!expectedSignature || !cookieSignature) {
433
298
  return null;
434
299
  }
@@ -442,8 +307,8 @@ function readSignedSession(userIdRaw, issuedAtRaw, cookieSignature, ttlSeconds,
442
307
  }
443
308
  return { userId, issuedAt, ...authVersion !== undefined ? { authVersion } : {} };
444
309
  }
445
- function readSession(request) {
446
- const cookieValue = readRequestCookie(request, sessionCookieName());
310
+ function readSession(request, options) {
311
+ const cookieValue = readRequestCookie(request, options.cookieName);
447
312
  if (!cookieValue) {
448
313
  return null;
449
314
  }
@@ -452,20 +317,20 @@ function readSession(request) {
452
317
  const fields = parts.slice(1, 5);
453
318
  if (fields.some((value) => !/^(0|[1-9][0-9]*)$/.test(value) || !Number.isSafeInteger(Number(value))))
454
319
  return null;
455
- return readSignedSession(String(parts[1]), String(parts[2]), parts[5], Number(parts[3]), true, Number(parts[4]));
320
+ return readSignedSession(String(parts[1]), String(parts[2]), parts[5], Number(parts[3]), true, Number(parts[4]), options);
456
321
  }
457
322
  if (parts.length === 4) {
458
323
  const [userIdRaw, issuedAtRaw, ttlRaw, cookieSignature] = parts;
459
- return readSignedSession(String(userIdRaw), String(issuedAtRaw), cookieSignature, Number.parseInt(String(ttlRaw), 10), true);
324
+ return readSignedSession(String(userIdRaw), String(issuedAtRaw), cookieSignature, Number.parseInt(String(ttlRaw), 10), true, undefined, options);
460
325
  }
461
326
  if (parts.length !== 3) {
462
327
  return null;
463
328
  }
464
329
  const [userIdRaw, issuedAtRaw, cookieSignature] = parts;
465
- return readSignedSession(String(userIdRaw), String(issuedAtRaw), cookieSignature, sessionTtlSeconds(), false);
330
+ return readSignedSession(String(userIdRaw), String(issuedAtRaw), cookieSignature, options.ttlSeconds, false, undefined, options);
466
331
  }
467
- function readSessionUserId(request) {
468
- return readSession(request)?.userId ?? null;
332
+ function readSessionUserId(request, options) {
333
+ return readSession(request, options)?.userId ?? null;
469
334
  }
470
335
  function isSessionInvalidated(issuedAt, validAfter) {
471
336
  if (!validAfter) {
@@ -477,33 +342,30 @@ function isSessionInvalidated(issuedAt, validAfter) {
477
342
  }
478
343
  return issuedAt < timestamp;
479
344
  }
480
- function createSessionCookieDetails(userId, options = {}) {
345
+ function createSessionCookieDetails(userId, options = {}, config) {
481
346
  if (options.authVersion !== undefined && (!Number.isSafeInteger(options.authVersion) || options.authVersion < 0))
482
347
  throw new RangeError("authVersion must be a non-negative safe integer.");
483
348
  const issuedAt = Date.now();
484
- const ttlSeconds = options.remember ? sessionRememberTtlSeconds() : sessionTtlSeconds();
485
- const value = options.authVersion !== undefined ? signSession(userId, issuedAt, ttlSeconds, options.authVersion) : options.remember ? signSession(userId, issuedAt, ttlSeconds) : signSession(userId, issuedAt);
486
- const secure = isProductionEnv() ? "; Secure" : "";
349
+ const ttlSeconds = options.remember ? config.rememberTtlSeconds : config.ttlSeconds;
350
+ const value = options.authVersion !== undefined ? signSession(userId, issuedAt, ttlSeconds, options.authVersion, config.secret) : options.remember ? signSession(userId, issuedAt, ttlSeconds, undefined, config.secret) : signSession(userId, issuedAt, undefined, undefined, config.secret);
351
+ const secure = config.production ? "; Secure" : "";
487
352
  return {
488
- header: `${sessionCookieName()}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ttlSeconds}${secure}`,
353
+ header: `${config.cookieName}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ttlSeconds}${secure}`,
489
354
  userId,
490
355
  issuedAt,
491
356
  ttlSeconds,
492
357
  ...options.authVersion !== undefined ? { authVersion: options.authVersion } : {}
493
358
  };
494
359
  }
495
- function createSessionCookie(userId, options = {}) {
496
- return createSessionCookieDetails(userId, options).header;
360
+ function createSessionCookie(userId, options = {}, config) {
361
+ return createSessionCookieDetails(userId, options, config).header;
497
362
  }
498
- function clearSessionCookie() {
499
- const secure = isProductionEnv() ? "; Secure" : "";
500
- return `${sessionCookieName()}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`;
363
+ function clearSessionCookie(config) {
364
+ const secure = config.production ? "; Secure" : "";
365
+ return `${config.cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`;
501
366
  }
502
367
 
503
368
  // ../../src/core/auth/jwtGuard.ts
504
- function isServiceContainer(value) {
505
- return "has" in value && "resolve" in value && typeof value.has === "function";
506
- }
507
369
  function authUserFromJwt(payload) {
508
370
  return {
509
371
  id: payload.sub,
@@ -513,19 +375,30 @@ function authUserFromJwt(payload) {
513
375
  };
514
376
  }
515
377
  function jwtSubjectId(payload) {
516
- const userId = typeof payload.sub === "number" ? payload.sub : Number.parseInt(String(payload.sub), 10);
517
- if (!Number.isInteger(userId) || userId <= 0) {
378
+ if (typeof payload.sub === "string" && !/^[1-9]\d*$/.test(payload.sub))
379
+ return null;
380
+ const userId = typeof payload.sub === "number" ? payload.sub : Number(payload.sub);
381
+ if (!Number.isSafeInteger(userId) || userId <= 0)
518
382
  return null;
519
- }
520
383
  return userId;
521
384
  }
522
385
 
523
386
  class JwtGuard {
524
387
  options;
525
- constructor(options = {}) {
526
- this.options = isServiceContainer(options) ? { container: options } : options;
388
+ constructor(options) {
389
+ requireAuthCapability(options.directory, ["findByIdOrThrow"], "JWT");
390
+ if (typeof options.secret !== "string" || !options.secret) {
391
+ throw new TypeError("Explicit JWT secret is required.");
392
+ }
393
+ this.options = options;
394
+ }
395
+ authenticate(request) {
396
+ return authenticateProof("bearer", authorizationScheme(request) === "bearer" && (readBearerToken(request) === null || readBearerToken(request)?.split(".").length === 3), () => this.resolveUser(request));
527
397
  }
528
398
  async resolve(request) {
399
+ return authUserFromOutcome(await this.authenticate(request));
400
+ }
401
+ async resolveUser(request) {
529
402
  const token = readBearerToken(request);
530
403
  if (token?.split(".").length !== 3) {
531
404
  return null;
@@ -537,20 +410,14 @@ class JwtGuard {
537
410
  if (typeof payload.iat !== "number" || !Number.isFinite(payload.iat)) {
538
411
  return null;
539
412
  }
540
- const directory = this.options.directory ?? (this.options.container ? resolveAuthUserDirectory(this.options.container) : null);
541
- if (!directory) {
542
- return null;
543
- }
413
+ const directory = this.options.directory;
544
414
  const userId = jwtSubjectId(payload);
545
415
  if (userId === null) {
546
416
  return null;
547
417
  }
548
- let record;
549
- try {
550
- record = await directory.findByIdOrThrow(userId);
551
- } catch {
418
+ const record = await directory.findByIdOrThrow(userId);
419
+ if (record.id !== userId)
552
420
  return null;
553
- }
554
421
  if (!isAccountActive(record) || !matchesAuthVersion(payload.authVersion, record.auth_version))
555
422
  return null;
556
423
  if (record.auth_version === undefined && isSessionInvalidated(payload.iat * 1000, record.session_valid_after)) {
@@ -558,6 +425,7 @@ class JwtGuard {
558
425
  }
559
426
  return {
560
427
  ...authUserFromJwt(payload),
428
+ id: record.id,
561
429
  ...record.auth_version !== undefined ? { authVersion: record.auth_version } : {}
562
430
  };
563
431
  }
@@ -1,16 +1,77 @@
1
1
  // @bun
2
- // ../../src/core/auth/membershipContextMiddleware.ts
3
- import { runWithMembershipContext } from "@getstrata/core/auth/membershipContext";
4
- function createMembershipContextMiddleware() {
5
- return async (_request, next) => {
6
- return await runWithMembershipContext(async () => await next());
7
- };
2
+ // ../../src/core/runtime/asyncContextStore.ts
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ function createAsyncContextStore(key) {
5
+ const symbol = Symbol.for(key);
6
+ const globalRecord = globalThis;
7
+ const existing = globalRecord[symbol];
8
+ if (existing) {
9
+ return existing;
10
+ }
11
+ const store = new AsyncLocalStorage;
12
+ globalRecord[symbol] = store;
13
+ return store;
14
+ }
15
+
16
+ // ../../src/core/auth/accessControl.ts
17
+ import { ForbiddenError } from "@getstrata/core/errors/http";
18
+
19
+ // ../../src/core/auth/authContext.ts
20
+ var authContext = createAsyncContextStore("@getstrata/authContext");
21
+ var credentialSourceContext = createAsyncContextStore("@getstrata/credentialSource");
22
+ function runWithAuthContext(user, credentialSource, callback) {
23
+ return authContext.run(user, () => credentialSourceContext.run(credentialSource, callback));
24
+ }
25
+ function currentAuthUser() {
26
+ return authContext.getStore() ?? null;
8
27
  }
9
28
 
10
- // ../../src/core/auth/membershipMiddleware.ts
11
- function createMembershipMiddleware() {
12
- return createMembershipContextMiddleware();
29
+ // ../../src/core/auth/accessControl.ts
30
+ var ROLE_RANK = {
31
+ member: 1,
32
+ admin: 2,
33
+ owner: 3
34
+ };
35
+ function isGlobalAdmin(user) {
36
+ return user?.role === "admin";
37
+ }
38
+ function hasMinimumOrgRole(role, minimum) {
39
+ if (!role) {
40
+ return false;
41
+ }
42
+ return ROLE_RANK[role] >= ROLE_RANK[minimum];
43
+ }
44
+ function requireAuthenticatedUser() {
45
+ const user = currentAuthUser();
46
+ if (!user) {
47
+ throw new ForbiddenError("Authentication required.");
48
+ }
49
+ return user;
50
+ }
51
+ function resolveUserId(user) {
52
+ const userId = typeof user.id === "number" ? user.id : Number(user.id);
53
+ if (!Number.isInteger(userId) || userId <= 0) {
54
+ throw new ForbiddenError("Invalid authenticated user.");
55
+ }
56
+ return userId;
57
+ }
58
+
59
+ // ../../src/core/auth/membershipContext.ts
60
+ var membershipContext = createAsyncContextStore("@getstrata/membershipContext");
61
+ function runWithMembershipSnapshot(snapshot, callback) {
62
+ return membershipContext.run({
63
+ organizationIds: snapshot.map((row) => row.organization_id),
64
+ rolesByOrganizationId: new Map(snapshot.map((row) => [row.organization_id, row.role]))
65
+ }, callback);
66
+ }
67
+ function currentOrganizationIds() {
68
+ return [...membershipContext.getStore()?.organizationIds ?? []];
69
+ }
70
+
71
+ // ../../src/core/auth/membershipContextMiddleware.ts
72
+ function createMembershipContextMiddleware(snapshot) {
73
+ return async (_request, next) => await runWithMembershipSnapshot(snapshot, next);
13
74
  }
14
75
  export {
15
- createMembershipMiddleware
76
+ createMembershipContextMiddleware as createMembershipMiddleware
16
77
  };
@@ -1,15 +1,10 @@
1
1
  // @bun
2
- var __esm = (fn, res, err) => () => {
3
- if (fn)
4
- try {
5
- res = fn(fn = 0);
6
- } catch (e) {
7
- err = [e];
8
- }
9
- if (err)
10
- throw err[0];
11
- return res;
12
- };
2
+ // ../../src/core/auth/membershipScope.ts
3
+ import { NotFoundError } from "@getstrata/core/errors/http";
4
+ import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
5
+
6
+ // ../../src/core/auth/accessControl.ts
7
+ import { ForbiddenError } from "@getstrata/core/errors/http";
13
8
 
14
9
  // ../../src/core/runtime/asyncContextStore.ts
15
10
  import { AsyncLocalStorage } from "async_hooks";
@@ -24,19 +19,13 @@ function createAsyncContextStore(key) {
24
19
  globalRecord[symbol] = store;
25
20
  return store;
26
21
  }
27
- var init_asyncContextStore = () => {};
28
-
29
- // ../../src/core/auth/membershipScope.ts
30
- import { NotFoundError } from "@getstrata/core/errors/http";
31
- import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
32
-
33
- // ../../src/core/auth/accessControl.ts
34
- import { ForbiddenError } from "@getstrata/core/errors/http";
35
22
 
36
23
  // ../../src/core/auth/authContext.ts
37
- init_asyncContextStore();
38
24
  var authContext = createAsyncContextStore("@getstrata/authContext");
39
25
  var credentialSourceContext = createAsyncContextStore("@getstrata/credentialSource");
26
+ function runWithAuthContext(user, credentialSource, callback) {
27
+ return authContext.run(user, () => credentialSourceContext.run(credentialSource, callback));
28
+ }
40
29
  function currentAuthUser() {
41
30
  return authContext.getStore() ?? null;
42
31
  }
@@ -72,10 +61,15 @@ function resolveUserId(user) {
72
61
  }
73
62
 
74
63
  // ../../src/core/auth/membershipContext.ts
75
- init_asyncContextStore();
76
64
  var membershipContext = createAsyncContextStore("@getstrata/membershipContext");
65
+ function runWithMembershipSnapshot(snapshot, callback) {
66
+ return membershipContext.run({
67
+ organizationIds: snapshot.map((row) => row.organization_id),
68
+ rolesByOrganizationId: new Map(snapshot.map((row) => [row.organization_id, row.role]))
69
+ }, callback);
70
+ }
77
71
  function currentOrganizationIds() {
78
- return membershipContext.getStore()?.organizationIds ?? [];
72
+ return [...membershipContext.getStore()?.organizationIds ?? []];
79
73
  }
80
74
 
81
75
  // ../../src/core/auth/membershipScope.ts