@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,1455 +1,4 @@
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
- };
13
-
14
- // ../../src/core/runtime/asyncContextStore.ts
15
- import { AsyncLocalStorage } from "async_hooks";
16
- function createAsyncContextStore(key) {
17
- const symbol = Symbol.for(key);
18
- const globalRecord = globalThis;
19
- const existing = globalRecord[symbol];
20
- if (existing) {
21
- return existing;
22
- }
23
- const store = new AsyncLocalStorage;
24
- globalRecord[symbol] = store;
25
- return store;
26
- }
27
- var init_asyncContextStore = () => {};
28
-
29
- // ../../src/core/database/connectionContext.ts
30
- function runWithDatabaseConnection(connection, callback) {
31
- return activeConnection.run(connection, callback);
32
- }
33
- function getActiveDatabaseConnection(fallback) {
34
- return activeConnection.getStore() ?? fallback;
35
- }
36
- function hasActiveDatabaseConnection() {
37
- return activeConnection.getStore() !== undefined;
38
- }
39
- var activeConnection;
40
- var init_connectionContext = __esm(() => {
41
- init_asyncContextStore();
42
- activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
43
- });
44
-
45
- // ../../src/core/tenant/tenantContext.ts
46
- function runWithTenant(tenant, callback) {
47
- return tenantContext.run(tenant, callback);
48
- }
49
- function currentTenant() {
50
- return tenantContext.getStore() ?? null;
51
- }
52
- var tenantContext;
53
- var init_tenantContext = __esm(() => {
54
- init_asyncContextStore();
55
- tenantContext = createAsyncContextStore("@getstrata/tenantContext");
56
- });
57
-
58
- // ../../src/core/events/eventBus.ts
59
- class EventBus {
60
- constructor() {}
61
- transactionalListeners = new Map;
62
- listenTransactional(event, listener) {
63
- const handlers = this.transactionalListeners.get(event) ?? new Set;
64
- handlers.add(listener);
65
- this.transactionalListeners.set(event, handlers);
66
- return () => {
67
- handlers.delete(listener);
68
- if (!handlers.size)
69
- this.transactionalListeners.delete(event);
70
- };
71
- }
72
- hasTransactionalListeners(event) {
73
- return (this.transactionalListeners.get(event)?.size ?? 0) > 0;
74
- }
75
- async dispatchTransactional(event, payload) {
76
- for (const listener of this.transactionalListeners.get(event) ?? [])
77
- await listener(payload);
78
- }
79
- listeners = new Map;
80
- on(event, listener) {
81
- return this.listen(event, listener);
82
- }
83
- listen(event, listener) {
84
- const handlers = this.listeners.get(event) ?? new Set;
85
- handlers.add(listener);
86
- this.listeners.set(event, handlers);
87
- return () => {
88
- handlers.delete(listener);
89
- if (handlers.size === 0) {
90
- this.listeners.delete(event);
91
- }
92
- };
93
- }
94
- async emit(event, payload) {
95
- await this.dispatch(event, payload);
96
- }
97
- async dispatch(event, payload) {
98
- const handlers = this.listeners.get(event);
99
- if (!handlers || handlers.size === 0) {
100
- return;
101
- }
102
- for (const handler of handlers) {
103
- await handler(payload);
104
- }
105
- }
106
- }
107
- function readSharedEventBus() {
108
- const globalBus = globalThis[EVENT_BUS_KEY];
109
- if (globalBus) {
110
- return globalBus;
111
- }
112
- const bus = new EventBus;
113
- globalThis[EVENT_BUS_KEY] = bus;
114
- return bus;
115
- }
116
- var EVENT_BUS_KEY, eventBus;
117
- var init_eventBus = __esm(() => {
118
- EVENT_BUS_KEY = Symbol.for("@getstrata/eventBus");
119
- eventBus = readSharedEventBus();
120
- });
121
-
122
- // ../../src/core/database/transactionControl.ts
123
- function unwrapTransactionRollback(error, depth = 0) {
124
- if (error instanceof TransactionRollback) {
125
- return error;
126
- }
127
- if (depth >= 5 || !(error instanceof Error) || error.cause === undefined) {
128
- return null;
129
- }
130
- return unwrapTransactionRollback(error.cause, depth + 1);
131
- }
132
- function hasActiveTransaction() {
133
- return hasActiveDatabaseConnection() && (transactionScopes.getStore()?.rollback.length ?? 0) > 0;
134
- }
135
- function requestTransactionRollback() {
136
- const state = transactionScopes.getStore();
137
- const index = state ? state.rollback.length - 1 : -1;
138
- if (!state || index < 0) {
139
- return;
140
- }
141
- state.rollback[index] = true;
142
- }
143
- function scopeRequestsRollback() {
144
- const state = transactionScopes.getStore();
145
- if (!state || state.rollback.length === 0) {
146
- return false;
147
- }
148
- return state.rollback[state.rollback.length - 1] === true;
149
- }
150
- async function commitOrRollbackScope(result) {
151
- if (scopeRequestsRollback()) {
152
- throw new TransactionRollback(result);
153
- }
154
- return result;
155
- }
156
- async function settleTransaction(work) {
157
- try {
158
- return await work();
159
- } catch (error) {
160
- const rollback = unwrapTransactionRollback(error);
161
- if (rollback) {
162
- return rollback.result;
163
- }
164
- throw error;
165
- }
166
- }
167
- async function runWithTransactionScope(callback) {
168
- const existing = transactionScopes.getStore();
169
- if (existing) {
170
- existing.rollback.push(false);
171
- try {
172
- return await callback();
173
- } finally {
174
- existing.rollback.pop();
175
- }
176
- }
177
- const state = { rollback: [false] };
178
- return await transactionScopes.run(state, callback);
179
- }
180
- var TransactionRollback, transactionScopes;
181
- var init_transactionControl = __esm(() => {
182
- init_asyncContextStore();
183
- init_connectionContext();
184
- TransactionRollback = class TransactionRollback extends Error {
185
- result;
186
- constructor(result) {
187
- super("Transaction rolled back");
188
- this.name = "TransactionRollback";
189
- this.result = result;
190
- }
191
- };
192
- transactionScopes = createAsyncContextStore("@getstrata/transactionScopes");
193
- });
194
-
195
- // ../../src/core/tenant/tenancyConfig.ts
196
- function readTenancyDriver(env = process.env) {
197
- const raw = env.TENANCY_DRIVER?.trim();
198
- if (raw === undefined || raw === "") {
199
- return "rls";
200
- }
201
- if (TENANCY_DRIVERS.includes(raw)) {
202
- return raw;
203
- }
204
- throw new Error(`TENANCY_DRIVER must be one of ${TENANCY_DRIVERS.join(", ")}; received "${raw}".`);
205
- }
206
- function isTenancyEnabled(env = process.env) {
207
- return readTenancyDriver(env) !== "none";
208
- }
209
- function isRlsTenancy(env = process.env) {
210
- return readTenancyDriver(env) === "rls";
211
- }
212
- var TENANCY_DRIVERS;
213
- var init_tenancyConfig = __esm(() => {
214
- TENANCY_DRIVERS = ["rls", "column", "none"];
215
- });
216
-
217
- // ../../src/core/tenant/tenantDatabaseScope.ts
218
- import { getDefaultDatabasePool } from "@getstrata/core/database/defaultConnection";
219
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
220
- async function applyTenantContextToTransaction(transaction, tenantId) {
221
- await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
222
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
223
- }
224
- async function runWithTenantDatabase(tenant, callback) {
225
- const outerTenant = currentTenant();
226
- if (hasActiveDatabaseConnection() && outerTenant && outerTenant.id !== tenant.id) {
227
- throw new Error("Cannot switch tenants inside an active database transaction.");
228
- }
229
- if (!isTenancyEnabled() || !isRlsTenancy()) {
230
- return await runWithTenant(tenant, callback);
231
- }
232
- if (hasActiveDatabaseConnection()) {
233
- const activeConnection = getActiveDatabaseConnection(getDefaultDatabasePool());
234
- return await runWithScopedTenantTransaction(() => applyTenantContextToTransaction(activeConnection, tenant.id), () => runWithTenant(tenant, callback));
235
- }
236
- const pool = getDefaultDatabasePool();
237
- const begin = pool.begin;
238
- if (typeof begin !== "function") {
239
- throw new Error("RLS tenant scope requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
240
- }
241
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
242
- return await begin.bind(pool)(AsyncLocalStorage2.bind(async (transaction) => {
243
- await applyTenantContextToTransaction(transaction, tenant.id);
244
- return await runWithDatabaseConnection(transaction, async () => {
245
- return await runWithTransactionScope(async () => commitOrRollbackScope(await runWithTenant(tenant, callback)));
246
- });
247
- }));
248
- }));
249
- }
250
- function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
251
- return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
252
- }
253
- var init_tenantDatabaseScope = __esm(() => {
254
- init_connectionContext();
255
- init_transactionControl();
256
- init_deferredModelEvents();
257
- init_databaseTenantContext();
258
- init_tenancyConfig();
259
- init_tenantContext();
260
- });
261
-
262
- // ../../src/core/events/deferredModelEvents.ts
263
- function sameTenant(left, right) {
264
- if (left === null && right === null) {
265
- return true;
266
- }
267
- if (left === null || right === null) {
268
- return false;
269
- }
270
- return left.id === right.id;
271
- }
272
- function groupQueuedModelEvents(queued) {
273
- const groups = [];
274
- for (const item of queued) {
275
- const lastGroup = groups[groups.length - 1];
276
- const last = lastGroup?.[lastGroup.length - 1];
277
- if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant) || "callback" in last !== "callback" in item) {
278
- groups.push([item]);
279
- } else {
280
- lastGroup.push(item);
281
- }
282
- }
283
- return groups;
284
- }
285
- async function dispatchEventBatch(batch) {
286
- for (const item of batch) {
287
- if ("callback" in item)
288
- await item.callback();
289
- else
290
- await eventBus.dispatch(item.event, item.payload);
291
- }
292
- }
293
- async function dispatchQueuedModelEvents(queued) {
294
- if (queued.length === 0) {
295
- return;
296
- }
297
- await Promise.resolve().then(() => init_tenantDatabaseScope());
298
- for (const batch of groupQueuedModelEvents(queued)) {
299
- const tenant = batch[0]?.tenant ?? null;
300
- if (tenant) {
301
- if (batch.some((item) => ("callback" in item))) {
302
- await runWithTenant(tenant, () => dispatchEventBatch(batch));
303
- } else {
304
- await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
305
- }
306
- } else {
307
- await dispatchEventBatch(batch);
308
- }
309
- }
310
- }
311
- async function dispatchModelEvent(event, payload) {
312
- await eventBus.dispatchTransactional(event, payload);
313
- const state = deferredModelEvents.getStore();
314
- const frame = state?.frames[state.frames.length - 1];
315
- if (frame) {
316
- frame.push({
317
- event,
318
- payload,
319
- tenant: currentTenant()
320
- });
321
- return;
322
- }
323
- await eventBus.dispatch(event, payload);
324
- }
325
- async function runWithDeferredModelEvents(callback) {
326
- const existing = deferredModelEvents.getStore();
327
- if (existing) {
328
- existing.frames.push([]);
329
- existing.rollbackFrames.push([]);
330
- try {
331
- const result = await callback();
332
- const nested = existing.frames.pop() ?? [];
333
- const rollback = existing.rollbackFrames.pop() ?? [];
334
- existing.rollbackFrames.at(-1)?.push(...rollback);
335
- const parent = existing.frames[existing.frames.length - 1];
336
- if (parent) {
337
- parent.push(...nested);
338
- }
339
- return result;
340
- } catch (error) {
341
- existing.frames.pop();
342
- for (const rollback of (existing.rollbackFrames.pop() ?? []).reverse())
343
- rollback();
344
- throw error;
345
- }
346
- }
347
- const state = { frames: [[]], rollbackFrames: [[]] };
348
- let result;
349
- try {
350
- result = await deferredModelEvents.run(state, callback);
351
- } catch (error) {
352
- for (const rollback of (state.rollbackFrames[0] ?? []).reverse())
353
- rollback();
354
- throw error;
355
- }
356
- await dispatchQueuedModelEvents(state.frames[0] ?? []);
357
- return result;
358
- }
359
- var deferredModelEvents;
360
- var init_deferredModelEvents = __esm(() => {
361
- init_asyncContextStore();
362
- init_tenantContext();
363
- init_eventBus();
364
- deferredModelEvents = createAsyncContextStore("@getstrata/deferredModelEvents");
365
- });
366
-
367
- // ../../src/core/database/acquisitionMetrics.ts
368
- async function observeTransactionAcquisition(metrics, acquire, signal) {
369
- const state = states.get(metrics);
370
- if (!state)
371
- throw new TypeError("Transaction acquisition metrics must be created by the framework factory.");
372
- const started = performance.now();
373
- state.inflight++;
374
- let outcome = "acquired";
375
- try {
376
- return await acquire();
377
- } catch (error) {
378
- outcome = signal?.aborted ? "aborted" : "failed";
379
- throw error;
380
- } finally {
381
- state.inflight--;
382
- const elapsed = Math.max(0, performance.now() - started) / 1000;
383
- const histogram = state.outcomes[outcomes.indexOf(outcome)];
384
- if (histogram) {
385
- histogram.count++;
386
- histogram.sumSeconds += elapsed;
387
- for (let index = 0;index < ACQUISITION_BUCKETS_SECONDS.length; index++) {
388
- const bound = ACQUISITION_BUCKETS_SECONDS[index];
389
- if (bound !== undefined && elapsed <= bound)
390
- histogram.buckets[index] = (histogram.buckets[index] ?? 0) + 1;
391
- }
392
- }
393
- }
394
- }
395
- var ACQUISITION_BUCKETS_SECONDS, outcomes, metricsBrand, states;
396
- var init_acquisitionMetrics = __esm(() => {
397
- ACQUISITION_BUCKETS_SECONDS = [
398
- 0.001,
399
- 0.005,
400
- 0.01,
401
- 0.025,
402
- 0.05,
403
- 0.1,
404
- 0.25,
405
- 0.5,
406
- 1,
407
- 2.5,
408
- 5,
409
- 10
410
- ];
411
- outcomes = ["acquired", "failed", "aborted"];
412
- metricsBrand = Symbol("transaction acquisition metrics");
413
- states = new WeakMap;
414
- });
415
-
416
- // ../../src/core/database/connection.ts
417
- function createDatabaseConnection(source) {
418
- return {
419
- async unsafe(query, params = []) {
420
- return await source.unsafe(query, params);
421
- }
422
- };
423
- }
424
- var init_connection = () => {};
425
-
426
- // ../../src/core/database/boundConnection.ts
427
- function boundConnectionState() {
428
- const globalRecord = globalThis;
429
- const existing = globalRecord[BOUND_CONNECTION_KEY];
430
- if (existing) {
431
- return existing;
432
- }
433
- const created = { connection: null };
434
- globalRecord[BOUND_CONNECTION_KEY] = created;
435
- return created;
436
- }
437
- function getBoundDatabaseConnection() {
438
- return boundConnectionState().connection;
439
- }
440
- var BOUND_CONNECTION_KEY;
441
- var init_boundConnection = __esm(() => {
442
- BOUND_CONNECTION_KEY = Symbol.for("@getstrata/boundDatabaseConnection");
443
- });
444
-
445
- // ../../src/core/database/queryProxy.ts
446
- var POOL_CONNECTION_METHODS;
447
- var init_queryProxy = __esm(() => {
448
- init_connectionContext();
449
- POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
450
- });
451
-
452
- // ../../src/core/database/defaultConnection.ts
453
- function defaultConnectionState() {
454
- const globalRecord = globalThis;
455
- const existing = globalRecord[DEFAULT_CONNECTION_KEY];
456
- if (existing) {
457
- return existing;
458
- }
459
- const created = { pool: null, query: null };
460
- globalRecord[DEFAULT_CONNECTION_KEY] = created;
461
- return created;
462
- }
463
- function getDefaultDatabasePool2() {
464
- const pool = defaultConnectionState().pool;
465
- if (!pool) {
466
- throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
467
- }
468
- return pool;
469
- }
470
- function getDefaultDatabaseQuery() {
471
- const query = defaultConnectionState().query;
472
- if (!query) {
473
- throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
474
- }
475
- return query;
476
- }
477
- var DEFAULT_CONNECTION_KEY;
478
- var init_defaultConnection = __esm(() => {
479
- init_queryProxy();
480
- DEFAULT_CONNECTION_KEY = Symbol.for("@getstrata/defaultDatabaseConnection");
481
- });
482
-
483
- // ../../src/core/database/schema/driver.ts
484
- function normalizeConnectionName(connection) {
485
- const normalized = connection.trim().toLowerCase();
486
- if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
487
- return "pgsql";
488
- }
489
- if (normalized === "mysql" || normalized === "mariadb") {
490
- return "mysql";
491
- }
492
- if (normalized === "sqlite") {
493
- return "sqlite";
494
- }
495
- throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
496
- }
497
- function resolveDriverFromUrl(url) {
498
- const normalized = url.trim().toLowerCase();
499
- if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
500
- return "pgsql";
501
- }
502
- if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
503
- return "mysql";
504
- }
505
- if (normalized.startsWith("sqlite:")) {
506
- return "sqlite";
507
- }
508
- return null;
509
- }
510
- function resolveDatabaseDriver(options = {}) {
511
- const connection = options.connection ?? process.env.DB_CONNECTION;
512
- if (connection) {
513
- return normalizeConnectionName(connection);
514
- }
515
- const url = options.url ?? process.env.DATABASE_URL ?? "";
516
- const fromUrl = resolveDriverFromUrl(url);
517
- if (fromUrl) {
518
- return fromUrl;
519
- }
520
- return "pgsql";
521
- }
522
- var init_driver = () => {};
523
-
524
- // ../../src/core/database/dialect.ts
525
- function assertSafeIdentifier(identifier) {
526
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
527
- throw new Error(`Invalid SQL identifier: ${identifier}`);
528
- }
529
- return identifier;
530
- }
531
- function quoteIdentifierFor(dialect, column) {
532
- return dialect.quoteIdentifier(column);
533
- }
534
- function dialectFor(driver) {
535
- return dialects[driver];
536
- }
537
- function currentSqlDialect() {
538
- return dialectContext.getStore() ?? dialectOverride ?? dialectFor(resolveDatabaseDriver());
539
- }
540
- var postgresDialect, mysqlDialect, sqliteDialect, dialects, dialectContext, dialectOverride = null;
541
- var init_dialect = __esm(() => {
542
- init_asyncContextStore();
543
- init_driver();
544
- postgresDialect = {
545
- driver: "pgsql",
546
- placeholder(index) {
547
- return `$${index}`;
548
- },
549
- quoteIdentifier(identifier) {
550
- return `"${assertSafeIdentifier(identifier)}"`;
551
- },
552
- nowExpression() {
553
- return "NOW()";
554
- },
555
- epochMillisecondsExpression() {
556
- return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)";
557
- },
558
- rowLockClause(skipLocked = false) {
559
- return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
560
- },
561
- timestampValue(value) {
562
- return value.toISOString();
563
- },
564
- returningClause(columns) {
565
- return ` RETURNING ${columns}`;
566
- },
567
- ilikeOperator() {
568
- return "ILIKE";
569
- },
570
- nullsLastSuffix() {
571
- return " NULLS LAST";
572
- },
573
- castToText(expression) {
574
- return `${expression}::text`;
575
- },
576
- upsertSuffix(conflictColumns, updateColumns) {
577
- const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
578
- if (updateColumns.length === 0) {
579
- return ` ON CONFLICT (${target}) DO NOTHING`;
580
- }
581
- const assignments = updateColumns.map((column) => {
582
- const quoted = quoteIdentifierFor(this, column);
583
- return `${quoted} = excluded.${quoted}`;
584
- }).join(", ");
585
- return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
586
- }
587
- };
588
- mysqlDialect = {
589
- driver: "mysql",
590
- placeholder() {
591
- return "?";
592
- },
593
- quoteIdentifier(identifier) {
594
- return `\`${assertSafeIdentifier(identifier)}\``;
595
- },
596
- nowExpression() {
597
- return "CURRENT_TIMESTAMP";
598
- },
599
- epochMillisecondsExpression() {
600
- return "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS UNSIGNED)";
601
- },
602
- rowLockClause(skipLocked = false) {
603
- return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
604
- },
605
- timestampValue(value) {
606
- return value.toISOString().slice(0, 19).replace("T", " ");
607
- },
608
- returningClause() {
609
- return "";
610
- },
611
- ilikeOperator() {
612
- return "LIKE";
613
- },
614
- nullsLastSuffix() {
615
- return "";
616
- },
617
- castToText(expression) {
618
- return `CAST(${expression} AS CHAR)`;
619
- },
620
- upsertSuffix(conflictColumns, updateColumns) {
621
- if (updateColumns.length === 0) {
622
- const anchor = quoteIdentifierFor(this, conflictColumns[0] ?? "");
623
- return ` ON DUPLICATE KEY UPDATE ${anchor} = ${anchor}`;
624
- }
625
- const assignments = updateColumns.map((column) => {
626
- const quoted = quoteIdentifierFor(this, column);
627
- return `${quoted} = VALUES(${quoted})`;
628
- }).join(", ");
629
- return ` ON DUPLICATE KEY UPDATE ${assignments}`;
630
- }
631
- };
632
- sqliteDialect = {
633
- driver: "sqlite",
634
- placeholder() {
635
- return "?";
636
- },
637
- quoteIdentifier(identifier) {
638
- return `"${assertSafeIdentifier(identifier)}"`;
639
- },
640
- nowExpression() {
641
- return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
642
- },
643
- epochMillisecondsExpression() {
644
- return "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
645
- },
646
- rowLockClause() {
647
- return "";
648
- },
649
- timestampValue(value) {
650
- return value.toISOString();
651
- },
652
- returningClause(columns) {
653
- return ` RETURNING ${columns}`;
654
- },
655
- ilikeOperator() {
656
- return "LIKE";
657
- },
658
- nullsLastSuffix() {
659
- return "";
660
- },
661
- castToText(expression) {
662
- return `CAST(${expression} AS TEXT)`;
663
- },
664
- upsertSuffix(conflictColumns, updateColumns) {
665
- const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
666
- if (updateColumns.length === 0) {
667
- return ` ON CONFLICT (${target}) DO NOTHING`;
668
- }
669
- const assignments = updateColumns.map((column) => {
670
- const quoted = quoteIdentifierFor(this, column);
671
- return `${quoted} = excluded.${quoted}`;
672
- }).join(", ");
673
- return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
674
- }
675
- };
676
- dialects = {
677
- pgsql: postgresDialect,
678
- mysql: mysqlDialect,
679
- sqlite: sqliteDialect
680
- };
681
- dialectContext = createAsyncContextStore("@getstrata/sqlDialect");
682
- });
683
-
684
- // ../../src/core/database/repositoryConnection.ts
685
- function resolveRepositoryConnection() {
686
- return getActiveDatabaseConnection(getBoundDatabaseConnection() ?? getDefaultDatabaseQuery());
687
- }
688
- function compileTaggedSql(strings, values) {
689
- const dialect = currentSqlDialect();
690
- let query = strings[0] ?? "";
691
- const params = [];
692
- for (let index = 0;index < values.length; index += 1) {
693
- params.push(values[index]);
694
- query += `${dialect.placeholder(params.length)}${strings[index + 1] ?? ""}`;
695
- }
696
- return { query, params };
697
- }
698
- function isTaggedStrings(value) {
699
- if (!Array.isArray(value) || typeof value[0] !== "string") {
700
- return false;
701
- }
702
- return typeof value.raw !== "undefined";
703
- }
704
- function runOnConnection(connection, args) {
705
- if (typeof connection === "function") {
706
- return connection(...args);
707
- }
708
- if (typeof connection.unsafe !== "function") {
709
- throw new Error("Database connection cannot run SQL.");
710
- }
711
- const strings = args[0];
712
- if (!isTaggedStrings(strings)) {
713
- throw new Error("Database connection cannot run tagged SQL.");
714
- }
715
- const compiled = compileTaggedSql(strings, args.slice(1));
716
- return connection.unsafe(compiled.query, compiled.params);
717
- }
718
- var repositoryConnection;
719
- var init_repositoryConnection = __esm(() => {
720
- init_boundConnection();
721
- init_connectionContext();
722
- init_defaultConnection();
723
- init_dialect();
724
- repositoryConnection = new Proxy(function repositoryConnection() {}, {
725
- apply(_target, _thisArg, args) {
726
- return runOnConnection(resolveRepositoryConnection(), args);
727
- },
728
- get(_target, property) {
729
- const connection = resolveRepositoryConnection();
730
- const value = connection[property];
731
- return typeof value === "function" ? value.bind(connection) : value;
732
- }
733
- });
734
- });
735
-
736
- // ../../src/core/database/transaction.ts
737
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
738
- function scopedConnection(source) {
739
- const connection = createDatabaseConnection(source);
740
- transactionAliases.set(connection, source);
741
- return connection;
742
- }
743
- function isActiveTransactionConnection(connection) {
744
- if (!hasActiveTransaction() || !hasActiveDatabaseConnection())
745
- return false;
746
- const active = getActiveDatabaseConnection(connection);
747
- return connection === active || transactionAliases.get(connection) === active;
748
- }
749
- async function runInSavepoint(connection, operation) {
750
- const inherited = transactionFrame.getStore();
751
- let parent = inherited?.connection === connection ? inherited : outerFrames.get(connection);
752
- if (!parent) {
753
- parent = { connection, childActive: false };
754
- outerFrames.set(connection, parent);
755
- }
756
- if (parent.childActive) {
757
- throw new Error("Concurrent nested transactions on one connection are not supported. Await each transaction before starting the next.");
758
- }
759
- parent.childActive = true;
760
- const name = `strata_${crypto.randomUUID().replaceAll("-", "")}`;
761
- try {
762
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
763
- await connection.unsafe(`SAVEPOINT ${name}`);
764
- try {
765
- const result = await transactionFrame.run({ connection, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await operation(scopedConnection(connection)))));
766
- await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
767
- return result;
768
- } catch (error) {
769
- await connection.unsafe(`ROLLBACK TO SAVEPOINT ${name}`);
770
- await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
771
- throw error;
772
- }
773
- }));
774
- } finally {
775
- parent.childActive = false;
776
- }
777
- }
778
- function supportsTransactions(connection) {
779
- return typeof connection.begin === "function";
780
- }
781
- async function runInTransaction(operation, options = {}) {
782
- const signal = options.acquisitionSignal;
783
- signal?.throwIfAborted();
784
- const admittedOperation = (connection) => {
785
- signal?.throwIfAborted();
786
- return operation(connection);
787
- };
788
- const pool = options.connection ?? resolveRepositoryConnection();
789
- if (hasActiveDatabaseConnection()) {
790
- const active = getActiveDatabaseConnection(pool);
791
- if (options.connection && options.connection !== active && options.connection !== transactionRoots.get(active) && transactionAliases.get(options.connection) !== active)
792
- throw new Error("Cannot switch database connections within an active transaction.");
793
- return await runInSavepoint(active, admittedOperation);
794
- }
795
- if (!supportsTransactions(pool)) {
796
- throw new Error("Active database connection does not support transactions. Bind a client with begin() via bindDatabaseConnection.");
797
- }
798
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
799
- let reserved;
800
- if (signal || options.acquisitionMetrics) {
801
- if (!pool.reserve)
802
- throw new Error(signal ? "Active database connection does not support cancellable transaction acquisition." : "Active database connection does not support observable transaction acquisition.");
803
- const reserve = pool.reserve.bind(pool);
804
- reserved = options.acquisitionMetrics ? await observeTransactionAcquisition(options.acquisitionMetrics, () => reserve({ signal }), signal) : await reserve({ signal });
805
- }
806
- const connection = reserved ?? pool;
807
- try {
808
- signal?.throwIfAborted();
809
- if (!supportsTransactions(connection))
810
- throw new Error("Reserved database connection does not support transactions.");
811
- return await connection.begin(AsyncLocalStorage3.bind(async (transaction) => {
812
- transactionRoots.set(transaction, pool);
813
- return await runWithDatabaseConnection(transaction, () => transactionFrame.run({ connection: transaction, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await admittedOperation(scopedConnection(transaction))))));
814
- }));
815
- } finally {
816
- await reserved?.release();
817
- }
818
- }));
819
- }
820
- var transactionFrame, outerFrames, transactionRoots, transactionAliases;
821
- var init_transaction = __esm(() => {
822
- init_deferredModelEvents();
823
- init_asyncContextStore();
824
- init_acquisitionMetrics();
825
- init_connection();
826
- init_connectionContext();
827
- init_repositoryConnection();
828
- init_transactionControl();
829
- init_acquisitionMetrics();
830
- transactionFrame = createAsyncContextStore("@getstrata/transactionFrame");
831
- outerFrames = new WeakMap;
832
- transactionRoots = new WeakMap;
833
- transactionAliases = new WeakMap;
834
- });
835
-
836
- // ../../src/core/tenant/databaseTenantContext.ts
837
- import { getDefaultDatabasePool as getDefaultDatabasePool3 } from "@getstrata/core/database/defaultConnection";
838
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
839
- async function applyBypassToTransaction(transaction, bypass) {
840
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, [
841
- bypass ? "true" : "false"
842
- ]);
843
- }
844
- function stringifyBypassIdentifier(identifier) {
845
- if (typeof identifier === "number") {
846
- return String(identifier);
847
- }
848
- return identifier.trim();
849
- }
850
- async function applyIdentifierToTransaction(transaction, identifier) {
851
- await transaction.unsafe(`SELECT set_config('app.bypass_identifier', $1, true)`, [
852
- stringifyBypassIdentifier(identifier)
853
- ]);
854
- }
855
- function assertBypassIdentifier(identifier) {
856
- if (typeof identifier === "number") {
857
- if (!Number.isInteger(identifier) || identifier <= 0) {
858
- throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
859
- }
860
- return;
861
- }
862
- if (typeof identifier === "string" && identifier.trim() !== "") {
863
- return;
864
- }
865
- throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
866
- }
867
- async function runWithScopedTenantTransaction(apply, callback) {
868
- if (!isRlsTenancy()) {
869
- return await callback();
870
- }
871
- if (hasActiveDatabaseConnection()) {
872
- const connection = getActiveDatabaseConnection(getDefaultDatabasePool3());
873
- return await runInTransaction(async () => {
874
- const [previous] = await connection.unsafe(`SELECT current_setting('app.tenant_id', true) AS tenant_id,
875
- current_setting('app.bypass_rls', true) AS bypass_rls,
876
- current_setting('app.bypass_identifier', true) AS bypass_identifier`);
877
- await apply(connection);
878
- const result = await callback();
879
- await connection.unsafe(`SELECT set_config('app.tenant_id', $1, true),
880
- set_config('app.bypass_rls', $2, true), set_config('app.bypass_identifier', $3, true)`, [previous?.tenant_id ?? "", previous?.bypass_rls ?? "", previous?.bypass_identifier ?? ""]);
881
- return result;
882
- });
883
- }
884
- const pool = getDefaultDatabasePool3();
885
- const begin = pool.begin;
886
- if (typeof begin !== "function") {
887
- throw new Error("RLS migration bypass requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
888
- }
889
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
890
- return await begin.bind(pool)(AsyncLocalStorage4.bind(async (transaction) => {
891
- await apply(transaction);
892
- return await runWithDatabaseConnection(transaction, () => runWithTransactionScope(async () => commitOrRollbackScope(await callback())));
893
- }));
894
- }));
895
- }
896
- async function runWithMigrationBypass(callback) {
897
- return await runWithScopedTenantTransaction((transaction) => applyBypassToTransaction(transaction, true), callback);
898
- }
899
- async function runWithMigrationBypassForIdentifier(identifier, callback) {
900
- assertBypassIdentifier(identifier);
901
- return await runWithScopedTenantTransaction((transaction) => applyIdentifierToTransaction(transaction, identifier), callback);
902
- }
903
- var init_databaseTenantContext = __esm(() => {
904
- init_connectionContext();
905
- init_transaction();
906
- init_transactionControl();
907
- init_deferredModelEvents();
908
- init_tenancyConfig();
909
- });
910
-
911
- // ../../src/core/runtime/appEnv.ts
912
- var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
913
- function normalizeEnvValue(value) {
914
- return (value ?? "").trim().toLowerCase();
915
- }
916
- function isProductionEnv(env = process.env) {
917
- const appEnv = normalizeEnvValue(env.APP_ENV);
918
- const nodeEnv = normalizeEnvValue(env.NODE_ENV);
919
- if (appEnv === "production" || nodeEnv === "production") {
920
- return true;
921
- }
922
- if (appEnv === "") {
923
- return false;
924
- }
925
- return !NON_PRODUCTION_APP_ENVS.has(appEnv);
926
- }
927
- function envFlagEnabled(value) {
928
- return value === "true";
929
- }
930
-
931
- // ../../src/core/runtime/appKeyPrefix.ts
932
- function appKeyPrefix() {
933
- return process.env.APP_KEY_PREFIX?.trim() || "strata";
934
- }
935
- function appCookieName(kind) {
936
- return `${appKeyPrefix()}_${kind}`;
937
- }
938
- function appDevSecret(kind) {
939
- return `${appKeyPrefix()}-dev-${kind}`;
940
- }
941
- function requireConfiguredSecret(names, devKind, env = process.env) {
942
- for (const name of names) {
943
- const value = env[name]?.trim();
944
- if (value) {
945
- return value;
946
- }
947
- }
948
- if (isProductionEnv(env)) {
949
- throw new Error(`${names[0]} must be set outside development. Do not derive secrets from the app name.`);
950
- }
951
- return appDevSecret(devKind);
952
- }
953
- function namespacedRedisKey(kind) {
954
- return `${appKeyPrefix()}:${kind}`;
955
- }
956
- function smtpEhloHost() {
957
- const raw = process.env.MAIL_EHLO?.trim() || `${appKeyPrefix()}.local`;
958
- const safe = raw.replace(/[^a-zA-Z0-9.-]/g, "");
959
- return safe || "strata.local";
960
- }
961
- function siemEventType() {
962
- return process.env.SIEM_EVENT_TYPE?.trim() || `${appKeyPrefix()}.audit`;
963
- }
964
- function appUserAgent() {
965
- return process.env.APP_USER_AGENT?.trim() || appKeyPrefix();
966
- }
967
- function otelServiceName() {
968
- return process.env.OTEL_SERVICE_NAME?.trim() || `${appKeyPrefix()}-api`;
969
- }
970
- function webhookSignatureHeader() {
971
- return process.env.WEBHOOK_SIGNATURE_HEADER?.trim() || `x-${appKeyPrefix()}-signature`;
972
- }
973
- function appDisplayName() {
974
- return process.env.APP_NAME?.trim() || "Strata";
975
- }
976
- function appEnv() {
977
- return process.env.APP_ENV?.trim() || "local";
978
- }
979
- function appUrl() {
980
- return (process.env.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "");
981
- }
982
- function apiPrefix() {
983
- const raw = process.env.API_PREFIX?.trim() || "/api/v1";
984
- const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
985
- const trimmed = withSlash.replace(/\/+$/, "");
986
- return trimmed || "/api/v1";
987
- }
988
- function sdkClientClassName() {
989
- const override = process.env.APP_SDK_CLASS?.trim();
990
- if (override && /^[A-Za-z_][A-Za-z0-9_]*$/.test(override)) {
991
- return override;
992
- }
993
- const fromName = appDisplayName().replace(/[^A-Za-z0-9]/g, "");
994
- return fromName ? `${fromName}Client` : "AppClient";
995
- }
996
-
997
- // ../../src/core/security/safeFetch.ts
998
- import { pinUrlToAddress, resolveSafeOutboundTarget } from "@getstrata/core/security/safeUrl";
999
- var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
1000
- function untilAborted(work, signal) {
1001
- signal.throwIfAborted();
1002
- return new Promise((resolve, reject) => {
1003
- const onAbort = () => reject(signal.reason);
1004
- signal.addEventListener("abort", onAbort, { once: true });
1005
- work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
1006
- });
1007
- }
1008
- function preserveResponseMetadata(response, original) {
1009
- Object.defineProperties(response, {
1010
- url: { value: original.url },
1011
- redirected: { value: original.redirected },
1012
- type: { value: original.type }
1013
- });
1014
- const clone = response.clone.bind(response);
1015
- response.clone = () => preserveResponseMetadata(clone(), original);
1016
- return response;
1017
- }
1018
- function withBodyDeadline(response, signal, release) {
1019
- if (!response.body) {
1020
- release();
1021
- return response;
1022
- }
1023
- const reader = response.body.getReader();
1024
- let stopped = false;
1025
- let bodyController;
1026
- const stop = (reason, errorBody) => {
1027
- if (stopped)
1028
- return;
1029
- stopped = true;
1030
- release();
1031
- signal.removeEventListener("abort", onAbort);
1032
- if (errorBody)
1033
- bodyController.error(reason);
1034
- reader.cancel(reason).catch(() => {}).finally(() => reader.releaseLock());
1035
- };
1036
- const onAbort = () => stop(signal.reason, true);
1037
- const body = new ReadableStream({
1038
- start(controller) {
1039
- bodyController = controller;
1040
- signal.addEventListener("abort", onAbort, { once: true });
1041
- if (signal.aborted)
1042
- onAbort();
1043
- },
1044
- async pull(controller) {
1045
- try {
1046
- const result = await untilAborted(reader.read(), signal);
1047
- if (stopped)
1048
- return;
1049
- if (result.done) {
1050
- stopped = true;
1051
- release();
1052
- signal.removeEventListener("abort", onAbort);
1053
- reader.releaseLock();
1054
- controller.close();
1055
- } else {
1056
- controller.enqueue(result.value);
1057
- }
1058
- } catch (error) {
1059
- stop(error, true);
1060
- }
1061
- },
1062
- cancel(reason) {
1063
- stop(reason, false);
1064
- }
1065
- }, { highWaterMark: 0 });
1066
- return preserveResponseMetadata(new Response(body, {
1067
- status: response.status,
1068
- statusText: response.statusText,
1069
- headers: response.headers
1070
- }), response);
1071
- }
1072
- async function safeFetch(input, init = {}, options = {}) {
1073
- init.signal?.throwIfAborted();
1074
- const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
1075
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
1076
- throw new RangeError("safeFetch timeoutMs must be a positive finite number.");
1077
- }
1078
- const maxRedirects = options.maxRedirects ?? 0;
1079
- const urlOptions = {
1080
- allowHttp: options.allowHttp,
1081
- resolveDns: options.resolveDns ?? true,
1082
- allowPrivate: options.allowPrivate
1083
- };
1084
- const controller = new AbortController;
1085
- const forwardAbort = () => controller.abort(init.signal?.reason);
1086
- init.signal?.addEventListener("abort", forwardAbort, { once: true });
1087
- const timeout = setTimeout(() => controller.abort(new DOMException("The operation timed out.", "TimeoutError")), timeoutMs);
1088
- const release = () => {
1089
- clearTimeout(timeout);
1090
- init.signal?.removeEventListener("abort", forwardAbort);
1091
- };
1092
- try {
1093
- let current = await untilAborted(resolveSafeOutboundTarget(input, urlOptions), controller.signal);
1094
- let redirectCount = 0;
1095
- while (true) {
1096
- controller.signal.throwIfAborted();
1097
- const address = current.addresses[0];
1098
- const fetchUrl = address ? pinUrlToAddress(current.url, address).toString() : current.url.toString();
1099
- const headers = new Headers(init.headers);
1100
- if (address && !headers.has("host"))
1101
- headers.set("Host", current.url.host);
1102
- const fetchInit = {
1103
- ...init,
1104
- headers,
1105
- signal: controller.signal,
1106
- redirect: "manual"
1107
- };
1108
- if (address)
1109
- fetchInit.tls = { serverName: current.url.hostname };
1110
- const response = await untilAborted(fetch(fetchUrl, fetchInit), controller.signal);
1111
- if (response.status >= 300 && response.status < 400) {
1112
- const location = response.headers.get("location");
1113
- if (location && redirectCount < maxRedirects) {
1114
- if (response.body)
1115
- await untilAborted(response.body.cancel(), controller.signal);
1116
- current = await untilAborted(resolveSafeOutboundTarget(new URL(location, current.url).toString(), urlOptions), controller.signal);
1117
- redirectCount++;
1118
- continue;
1119
- }
1120
- }
1121
- return withBodyDeadline(response, controller.signal, release);
1122
- }
1123
- } catch (error) {
1124
- controller.abort(error);
1125
- release();
1126
- throw error;
1127
- }
1128
- }
1129
-
1130
- // ../../src/core/security/safeUrl.ts
1131
- import { BadRequestError } from "@getstrata/core/errors/http";
1132
- var BLOCKED_HOSTNAMES = new Set([
1133
- "localhost",
1134
- "127.0.0.1",
1135
- "0.0.0.0",
1136
- "::1",
1137
- "metadata.google.internal"
1138
- ]);
1139
- function parseCanonicalDottedDecimal(hostname) {
1140
- const parts = hostname.split(".");
1141
- if (parts.length !== 4) {
1142
- return null;
1143
- }
1144
- const octets = [];
1145
- for (const part of parts) {
1146
- if (!/^(0|[1-9]\d{0,2})$/u.test(part)) {
1147
- return null;
1148
- }
1149
- const value = Number.parseInt(part, 10);
1150
- if (!Number.isInteger(value) || value < 0 || value > 255) {
1151
- return null;
1152
- }
1153
- octets.push(value);
1154
- }
1155
- return octets;
1156
- }
1157
- function parseDottedIpv4(hostname) {
1158
- return parseCanonicalDottedDecimal(hostname);
1159
- }
1160
- function isBlockedIpv4Octets(octets) {
1161
- const [a = 0, b = 0] = octets;
1162
- if (a === 10 || a === 127 || a === 0) {
1163
- return true;
1164
- }
1165
- if (a === 169 && b === 254) {
1166
- return true;
1167
- }
1168
- if (a === 172 && b >= 16 && b <= 31) {
1169
- return true;
1170
- }
1171
- if (a === 192 && b === 168) {
1172
- return true;
1173
- }
1174
- if (a === 100 && b >= 64 && b <= 127) {
1175
- return true;
1176
- }
1177
- if (a === 198 && (b === 18 || b === 19)) {
1178
- return true;
1179
- }
1180
- return false;
1181
- }
1182
- function expandIpv6(hostname) {
1183
- const trimmed = hostname.trim().toLowerCase();
1184
- const unbracketed = trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
1185
- if (unbracketed.includes("%")) {
1186
- return null;
1187
- }
1188
- const mapped = unbracketed.match(/^::ffff:([0-9a-fx.]+)$/iu);
1189
- if (mapped?.[1]) {
1190
- const octets = parseDottedIpv4(mapped[1]);
1191
- if (!octets) {
1192
- return null;
1193
- }
1194
- return [
1195
- 0,
1196
- 0,
1197
- 0,
1198
- 0,
1199
- 0,
1200
- 65535,
1201
- octets[0] << 8 | octets[1],
1202
- octets[2] << 8 | octets[3]
1203
- ];
1204
- }
1205
- const halves = unbracketed.split("::");
1206
- if (halves.length > 2) {
1207
- return null;
1208
- }
1209
- const parseGroup = (part) => {
1210
- if (!/^[0-9a-f]{1,4}$/u.test(part)) {
1211
- return null;
1212
- }
1213
- return Number.parseInt(part, 16);
1214
- };
1215
- if (halves.length === 1) {
1216
- const groups = unbracketed.split(":");
1217
- if (groups.length !== 8) {
1218
- return null;
1219
- }
1220
- const values = groups.map(parseGroup);
1221
- return values.every((value) => value !== null) ? values : null;
1222
- }
1223
- const head = halves[0] ? halves[0].split(":").filter(Boolean) : [];
1224
- const tail = halves[1] ? halves[1].split(":").filter(Boolean) : [];
1225
- if (head.length + tail.length > 8) {
1226
- return null;
1227
- }
1228
- const values = [];
1229
- for (const part of head) {
1230
- const value = parseGroup(part);
1231
- if (value === null) {
1232
- return null;
1233
- }
1234
- values.push(value);
1235
- }
1236
- while (values.length < 8 - tail.length) {
1237
- values.push(0);
1238
- }
1239
- for (const part of tail) {
1240
- const value = parseGroup(part);
1241
- if (value === null) {
1242
- return null;
1243
- }
1244
- values.push(value);
1245
- }
1246
- return values.length === 8 ? values : null;
1247
- }
1248
- function isBlockedIpv6(hostname) {
1249
- const groups = expandIpv6(hostname);
1250
- if (!groups) {
1251
- return hostname.includes(":");
1252
- }
1253
- const first = groups[0] ?? 0;
1254
- const second = groups[1] ?? 0;
1255
- if (groups.every((group) => group === 0)) {
1256
- return true;
1257
- }
1258
- if (groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1) {
1259
- return true;
1260
- }
1261
- if ((first & 65472) === 65152) {
1262
- return true;
1263
- }
1264
- if ((first & 65024) === 64512) {
1265
- return true;
1266
- }
1267
- if ((first & 65280) === 65280) {
1268
- return true;
1269
- }
1270
- if (first === 0 && second === 0 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 65535) {
1271
- const a = (groups[6] ?? 0) >> 8;
1272
- const b = (groups[6] ?? 0) & 255;
1273
- const c = (groups[7] ?? 0) >> 8;
1274
- const d = (groups[7] ?? 0) & 255;
1275
- return isBlockedIpv4Octets([a, b, c, d]);
1276
- }
1277
- return false;
1278
- }
1279
- function isBlockedHostname(hostname) {
1280
- const normalized = hostname.trim().toLowerCase();
1281
- if (normalized.length === 0) {
1282
- return true;
1283
- }
1284
- if (BLOCKED_HOSTNAMES.has(normalized)) {
1285
- return true;
1286
- }
1287
- if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
1288
- return true;
1289
- }
1290
- if (normalized.includes(":")) {
1291
- return isBlockedIpv6(normalized);
1292
- }
1293
- if (/^\d+$/u.test(normalized)) {
1294
- return true;
1295
- }
1296
- if (normalized.includes(".")) {
1297
- const canonical = parseCanonicalDottedDecimal(normalized);
1298
- if (canonical) {
1299
- return isBlockedIpv4Octets(canonical);
1300
- }
1301
- if (/^[0-9a-fx.]+$/iu.test(normalized)) {
1302
- return true;
1303
- }
1304
- }
1305
- return false;
1306
- }
1307
- function productionSafeOutboundOptions(options) {
1308
- if (!isProductionEnv()) {
1309
- return options;
1310
- }
1311
- return { ...options, allowPrivate: false, resolveDns: true };
1312
- }
1313
- function assertSafeOutboundUrl(rawUrl, options = {}) {
1314
- const resolved = productionSafeOutboundOptions(options);
1315
- let parsed;
1316
- try {
1317
- parsed = new URL(rawUrl);
1318
- } catch {
1319
- throw new BadRequestError("Webhook URL is invalid.");
1320
- }
1321
- if (parsed.protocol !== "https:" && !(resolved.allowHttp && parsed.protocol === "http:")) {
1322
- throw new BadRequestError("Webhook URL must use HTTPS.");
1323
- }
1324
- if (parsed.username || parsed.password) {
1325
- throw new BadRequestError("Webhook URL must not include credentials.");
1326
- }
1327
- if (!resolved.allowPrivate && isBlockedHostname(parsed.hostname)) {
1328
- throw new BadRequestError("Webhook URL targets a blocked host.");
1329
- }
1330
- return parsed;
1331
- }
1332
-
1333
- // ../../src/core/audit/exportStore.ts
1334
- init_databaseTenantContext();
1335
- import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
1336
- async function readPendingAuditLogs(batchSize) {
1337
- return await runWithMigrationBypass(async () => {
1338
- return await db`
1339
- SELECT
1340
- id,
1341
- user_id,
1342
- action,
1343
- subject_type,
1344
- subject_id,
1345
- payload,
1346
- ip_address,
1347
- user_agent,
1348
- checksum,
1349
- tenant_id,
1350
- trace_id,
1351
- created_at
1352
- FROM audit_log
1353
- WHERE exported_at IS NULL
1354
- ORDER BY id
1355
- LIMIT ${batchSize}
1356
- `;
1357
- });
1358
- }
1359
- async function acknowledgeAuditLogs(ids) {
1360
- await runWithMigrationBypass(async () => {
1361
- for (const id of ids) {
1362
- await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1363
- }
1364
- });
1365
- }
1366
-
1367
- // ../../src/core/audit/siemFormatter.ts
1368
- function formatSiemAuditEvent(input) {
1369
- return {
1370
- timestamp: input.created_at.toISOString(),
1371
- event_type: siemEventType(),
1372
- actor_user_id: input.user_id,
1373
- tenant_id: input.tenant_id ?? null,
1374
- trace_id: input.trace_id ?? null,
1375
- action: input.action,
1376
- subject_type: input.subject_type,
1377
- subject_id: input.subject_id,
1378
- ip_address: input.ip_address ?? null,
1379
- user_agent: input.user_agent ?? null,
1380
- checksum: input.checksum ?? null,
1381
- payload: input.payload ?? {}
1382
- };
1383
- }
1384
- function formatCefLine(event) {
1385
- const extension = [
1386
- `rt=${event.timestamp}`,
1387
- `suid=${event.actor_user_id ?? "unknown"}`,
1388
- `cs1=${event.action}`,
1389
- `cs1Label=Action`,
1390
- `cs2=${event.subject_type}`,
1391
- `cs2Label=SubjectType`,
1392
- `cs3=${event.subject_id ?? ""}`,
1393
- `cs3Label=SubjectId`,
1394
- `src=${event.ip_address ?? ""}`,
1395
- `request=${event.trace_id ?? ""}`
1396
- ].join(" ");
1397
- return `CEF:0|${appDisplayName()}|API|1.0|${event.action}|${event.subject_type}|5|${extension}`;
1398
- }
1399
-
1400
- // ../../src/core/audit/exportAuditLogs.ts
1401
- function resolveAuditExportConfig() {
1402
- const endpoint = process.env.SIEM_EXPORT_URL?.trim();
1403
- if (!endpoint) {
1404
- return null;
1405
- }
1406
- assertSafeOutboundUrl(endpoint, { allowHttp: appEnv() !== "production" });
1407
- const batchSize = Number(process.env.SIEM_EXPORT_BATCH_SIZE ?? "100");
1408
- return {
1409
- endpoint,
1410
- format: process.env.SIEM_EXPORT_FORMAT === "cef" ? "cef" : "json",
1411
- batchSize: Number.isFinite(batchSize) ? batchSize : 100
1412
- };
1413
- }
1414
- async function exportPendingAuditLogs() {
1415
- const config = resolveAuditExportConfig();
1416
- if (!config) {
1417
- return 0;
1418
- }
1419
- const rows = await readPendingAuditLogs(config.batchSize);
1420
- if (rows.length === 0) {
1421
- return 0;
1422
- }
1423
- const events = rows.map((row) => formatSiemAuditEvent({
1424
- action: row.action,
1425
- subject_type: row.subject_type,
1426
- subject_id: row.subject_id,
1427
- user_id: row.user_id,
1428
- tenant_id: row.tenant_id,
1429
- trace_id: row.trace_id,
1430
- ip_address: row.ip_address,
1431
- user_agent: row.user_agent,
1432
- checksum: row.checksum,
1433
- payload: row.payload,
1434
- created_at: row.created_at
1435
- }));
1436
- const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1437
- `) : JSON.stringify({ events });
1438
- const response = await safeFetch(config.endpoint, {
1439
- method: "POST",
1440
- headers: {
1441
- "content-type": config.format === "cef" ? "text/plain" : "application/json",
1442
- ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1443
- },
1444
- body
1445
- }, { allowHttp: appEnv() !== "production" });
1446
- if (!response.ok) {
1447
- throw new Error(`SIEM export failed with status ${response.status}.`);
1448
- }
1449
- await acknowledgeAuditLogs(rows.map((row) => row.id));
1450
- return rows.length;
1451
- }
1452
-
1453
2
  // ../../src/core/logging/logger.ts
1454
3
  class Logger {
1455
4
  channel;
@@ -1486,59 +35,18 @@ class Logger {
1486
35
  }
1487
36
  var appLogger = new Logger("app");
1488
37
 
1489
- // ../../src/core/queue/jobRegistry.ts
1490
- class JobRegistry {
1491
- factories = new Map;
1492
- instances = new WeakMap;
1493
- register(name, factory) {
1494
- this.factories.set(name, factory);
1495
- }
1496
- resolveName(job) {
1497
- return this.instances.get(job);
1498
- }
1499
- track(name, job) {
1500
- this.instances.set(job, name);
1501
- return job;
1502
- }
1503
- create(name) {
1504
- const factory = this.factories.get(name);
1505
- if (!factory) {
1506
- return;
1507
- }
1508
- return factory();
1509
- }
1510
- names() {
1511
- return [...this.factories.keys()];
1512
- }
1513
- }
1514
- var JOB_REGISTRY_KEY = Symbol.for("@getstrata/jobRegistry");
1515
- function readSharedJobRegistry() {
1516
- const globalRegistry = globalThis[JOB_REGISTRY_KEY];
1517
- if (globalRegistry) {
1518
- return globalRegistry;
1519
- }
1520
- const registry = new JobRegistry;
1521
- globalThis[JOB_REGISTRY_KEY] = registry;
1522
- return registry;
1523
- }
1524
- var jobRegistry = readSharedJobRegistry();
1525
-
1526
38
  // ../../src/core/queue/index.ts
1527
39
  class Job {
1528
40
  static jobName;
1529
41
  maxAttempts;
1530
42
  backoffMs;
1531
43
  priority;
1532
- constructor() {
1533
- const jobName = this.constructor.jobName;
1534
- if (jobName) {
1535
- jobRegistry.track(jobName, this);
1536
- }
1537
- }
1538
44
  }
1539
45
 
1540
46
  class SyncQueue {
1541
- async dispatch(job, payload) {
47
+ async dispatch(job, payload, options) {
48
+ if (options?.handoff !== undefined)
49
+ throw new Error("Identity handoff requires an application queue.");
1542
50
  await job.handle(payload);
1543
51
  }
1544
52
  }
@@ -1563,7 +71,9 @@ class AsyncQueue {
1563
71
  this.active.delete(running);
1564
72
  });
1565
73
  }
1566
- async dispatch(job, payload) {
74
+ async dispatch(job, payload, options) {
75
+ if (options?.handoff !== undefined)
76
+ throw new Error("Identity handoff requires an application queue.");
1567
77
  this.enqueue(() => job.handle(payload), (error) => {
1568
78
  console.error("[AsyncQueue] Job failed:", error);
1569
79
  });
@@ -1583,10 +93,19 @@ function createQueue(driver) {
1583
93
 
1584
94
  // ../../src/core/jobs/exportAuditLogsJob.ts
1585
95
  class ExportAuditLogsJob extends Job {
96
+ exporter;
97
+ static jobName = "audit.export";
1586
98
  maxAttempts = 2;
1587
99
  backoffMs = 5000;
1588
- async handle(_payload = {}) {
1589
- const exported = await exportPendingAuditLogs();
100
+ constructor(exporter) {
101
+ super();
102
+ this.exporter = exporter;
103
+ }
104
+ async handle(_payload = {}, context) {
105
+ const exporter = this.exporter ?? context?.auditExport;
106
+ if (!exporter)
107
+ throw new Error("Audit export requires an application-owned exporter.");
108
+ const exported = await exporter();
1590
109
  if (exported > 0) {
1591
110
  appLogger.info(`Exported ${exported} audit log entries to SIEM.`);
1592
111
  }