@getstrata/core 2.2.59 → 3.0.3
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.
- package/CHANGELOG.md +27 -0
- package/dist/core/audit/exportAuditLogs.d.ts +12 -3
- package/dist/core/audit/exportStore.d.ts +6 -2
- package/dist/core/audit/siemFormatter.d.ts +2 -2
- package/dist/core/auth/abilityCatalog.d.ts +1 -9
- package/dist/core/auth/authContext.d.ts +2 -0
- package/dist/core/auth/authOutcome.d.ts +32 -0
- package/dist/core/auth/authReader.d.ts +22 -0
- package/dist/core/auth/basicAuthGuard.d.ts +19 -3
- package/dist/core/auth/emailVerification.d.ts +1 -1
- package/dist/core/auth/guard.d.ts +27 -6
- package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
- package/dist/core/auth/jwt.d.ts +5 -4
- package/dist/core/auth/jwtGuard.d.ts +7 -6
- package/dist/core/auth/membershipContext.d.ts +10 -7
- package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
- package/dist/core/auth/membershipMiddleware.d.ts +1 -2
- package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
- package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
- package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
- package/dist/core/auth/oauth/providers.d.ts +3 -1
- package/dist/core/auth/oneTimeToken.d.ts +2 -3
- package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
- package/dist/core/auth/passwordLogin.d.ts +5 -5
- package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
- package/dist/core/auth/policy.d.ts +23 -10
- package/dist/core/auth/requireAuthCapability.d.ts +3 -0
- package/dist/core/auth/resolveMembershipService.d.ts +3 -2
- package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
- package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
- package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
- package/dist/core/auth/sessionCookie.d.ts +20 -9
- package/dist/core/auth/sessionGuard.d.ts +14 -3
- package/dist/core/cache/createCacheStore.d.ts +6 -3
- package/dist/core/cache/redisCacheStore.d.ts +5 -1
- package/dist/core/cache/repository.d.ts +5 -1
- package/dist/core/cache/simpleCache.d.ts +2 -1
- package/dist/core/cache/tokens.d.ts +8 -0
- package/dist/core/config/applicationConfig.d.ts +21 -0
- package/dist/core/config/configSnapshot.d.ts +3 -0
- package/dist/core/config/envSchema.d.ts +3 -2
- package/dist/core/contracts/application.d.ts +153 -0
- package/dist/core/contracts/authUserDirectory.d.ts +24 -7
- package/dist/core/contracts/container.d.ts +20 -23
- package/dist/core/contracts/di.d.ts +4 -2
- package/dist/core/contracts/executionContext.d.ts +5 -0
- package/dist/core/contracts/executionOperations.d.ts +10 -0
- package/dist/core/contracts/executionOwnership.d.ts +38 -0
- package/dist/core/contracts/persistence.d.ts +20 -0
- package/dist/core/contracts/serviceTokens.d.ts +32 -18
- package/dist/core/contracts/services.d.ts +63 -0
- package/dist/core/contracts/token.d.ts +19 -0
- package/dist/core/crypto/fieldEncryption.d.ts +19 -7
- package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
- package/dist/core/crypto/mfaSecret.d.ts +10 -3
- package/dist/core/database/baseRepository.d.ts +14 -10
- package/dist/core/database/bindings.d.ts +6 -0
- package/dist/core/database/bunSql.d.ts +3 -12
- package/dist/core/database/definitions.d.ts +209 -0
- package/dist/core/database/dialect.d.ts +5 -24
- package/dist/core/database/driverPorts.d.ts +116 -0
- package/dist/core/database/errors.d.ts +47 -7
- package/dist/core/database/factory.d.ts +51 -31
- package/dist/core/database/index.d.ts +9 -10
- package/dist/core/database/keyset.d.ts +2 -1
- package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
- package/dist/core/database/manager.d.ts +12 -0
- package/dist/core/database/model.d.ts +91 -97
- package/dist/core/database/modelQuery.d.ts +9 -5
- package/dist/core/database/modelRegistry.d.ts +52 -33
- package/dist/core/database/mysqlConnection.d.ts +1 -19
- package/dist/core/database/mysqlNative.d.ts +38 -0
- package/dist/core/database/nativeTransactions.d.ts +16 -0
- package/dist/core/database/ormInternal.d.ts +85 -0
- package/dist/core/database/ormRuntime.d.ts +4 -0
- package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
- package/dist/core/database/postgresNative.d.ts +11 -0
- package/dist/core/database/query.d.ts +24 -23
- package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
- package/dist/core/database/rawMysql.d.ts +7 -0
- package/dist/core/database/rawPostgres.d.ts +23 -0
- package/dist/core/database/rawSqlite.d.ts +6 -0
- package/dist/core/database/relationQueries.d.ts +3 -2
- package/dist/core/database/relationQuery.d.ts +24 -6
- package/dist/core/database/repositoryQuery.d.ts +6 -1
- package/dist/core/database/schema/driver.d.ts +1 -1
- package/dist/core/database/seeders/types.d.ts +1 -1
- package/dist/core/database/session.d.ts +13 -0
- package/dist/core/database/sessionFactory.d.ts +9 -0
- package/dist/core/database/sqlDialects.d.ts +22 -0
- package/dist/core/database/tokens.d.ts +7 -0
- package/dist/core/database/transactionSession.d.ts +43 -0
- package/dist/core/errors/http.d.ts +4 -1
- package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
- package/dist/core/events/index.d.ts +2 -3
- package/dist/core/events/outbox/index.d.ts +44 -13
- package/dist/core/events/outbox/metrics.d.ts +4 -4
- package/dist/core/events/outbox/workerTransport.d.ts +17 -0
- package/dist/core/http/authMiddleware.d.ts +2 -2
- package/dist/core/http/authorizeMiddleware.d.ts +2 -2
- package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
- package/dist/core/http/conditionalResponse.d.ts +7 -2
- package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
- package/dist/core/http/corsMiddleware.d.ts +2 -1
- package/dist/core/http/csrfMiddleware.d.ts +6 -1
- package/dist/core/http/csrfToken.d.ts +17 -7
- package/dist/core/http/databaseError.d.ts +4 -0
- package/dist/core/http/etag.d.ts +5 -2
- package/dist/core/http/flashMiddleware.d.ts +1 -1
- package/dist/core/http/flashSession.d.ts +13 -7
- package/dist/core/http/index.d.ts +1 -1
- package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
- package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
- package/dist/core/http/parseMultipartUpload.d.ts +3 -2
- package/dist/core/http/requestMetaContext.d.ts +5 -0
- package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
- package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
- package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
- package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
- package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
- package/dist/core/http/response.d.ts +4 -3
- package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
- package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
- package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
- package/dist/core/http/signedUrl.d.ts +8 -6
- package/dist/core/http/throttleMiddleware.d.ts +9 -5
- package/dist/core/http/uploads.d.ts +9 -3
- package/dist/core/http/webErrorResponse.d.ts +8 -2
- package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
- package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
- package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
- package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
- package/dist/core/mail/mailer.d.ts +7 -5
- package/dist/core/openapi/generator.d.ts +12 -4
- package/dist/core/openapi/registeredRoute.d.ts +4 -4
- package/dist/core/queue/createAppQueue.d.ts +9 -4
- package/dist/core/queue/failedJobMetrics.d.ts +11 -2
- package/dist/core/queue/failedJobRepository.d.ts +6 -3
- package/dist/core/queue/failedJobService.d.ts +1 -0
- package/dist/core/queue/index.d.ts +16 -6
- package/dist/core/queue/jobRegistry.d.ts +3 -2
- package/dist/core/queue/jobRunner.d.ts +10 -4
- package/dist/core/queue/publicQueue.d.ts +18 -9
- package/dist/core/queue/queueConfig.d.ts +20 -10
- package/dist/core/queue/queueHandoff.d.ts +31 -0
- package/dist/core/queue/queueMetrics.d.ts +10 -3
- package/dist/core/queue/queueServices.d.ts +28 -0
- package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
- package/dist/core/queue/redisQueue.d.ts +19 -10
- package/dist/core/queue/redisQueueKeys.d.ts +5 -5
- package/dist/core/queue/redisStreams.d.ts +17 -10
- package/dist/core/queue/resilientQueue.d.ts +10 -4
- package/dist/core/queue/types.d.ts +1 -0
- package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
- package/dist/core/runtime/application.d.ts +7 -0
- package/dist/core/runtime/executionContext.d.ts +9 -0
- package/dist/core/runtime/executionTasks.d.ts +49 -0
- package/dist/core/runtime/resourceJournal.d.ts +67 -0
- package/dist/core/runtime/serviceGraph.d.ts +14 -0
- package/dist/core/security/oauthState.d.ts +13 -9
- package/dist/core/security/publicReads.d.ts +2 -2
- package/dist/core/security/safeFetch.d.ts +1 -0
- package/dist/core/security/safeUrl.d.ts +3 -0
- package/dist/core/security/scimTenantTokens.d.ts +1 -1
- package/dist/core/security/tokenExpiry.d.ts +1 -1
- package/dist/core/security/webhookSignature.d.ts +1 -1
- package/dist/core/storage/storage.d.ts +24 -16
- package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
- package/dist/core/tenant/resolveTenant.d.ts +2 -2
- package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
- package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
- package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
- package/dist/core/tracing/otel.d.ts +4 -6
- package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
- package/dist/core/view/etaViewEngine.d.ts +1 -1
- package/dist/core/view/index.d.ts +5 -4
- package/dist/core/view/tokens.d.ts +8 -0
- package/dist/core/view/viewRenderer.d.ts +2 -2
- package/dist/core/view/webErrorView.d.ts +8 -7
- package/dist/core/view/webLayoutData.d.ts +6 -4
- package/dist/entries/audit/exportAuditLogs.js +87 -1024
- package/dist/entries/audit/siemFormatter.js +4 -90
- package/dist/entries/auth/abilityCatalog.js +28 -0
- package/dist/entries/auth/accessControl.js +5 -16
- package/dist/entries/auth/accountStateMigration.js +216 -236
- package/dist/entries/auth/authOutcome.js +80 -0
- package/dist/entries/auth/authReader.js +68 -0
- package/dist/entries/auth/basicAuthGuard.js +144 -1249
- package/dist/entries/auth/emailVerification.js +2 -2
- package/dist/entries/auth/intendedUrlCookie.js +35 -59
- package/dist/entries/auth/jwt.js +22 -47
- package/dist/entries/auth/jwtGuard.js +99 -231
- package/dist/entries/auth/membershipMiddleware.js +71 -10
- package/dist/entries/auth/membershipScope.js +16 -22
- package/dist/entries/auth/membershipService.js +11 -28
- package/dist/entries/auth/oauth/oidcProvider.js +59 -64
- package/dist/entries/auth/oauth/providers.js +12 -95
- package/dist/entries/auth/oauth/samlProvider.js +53 -1080
- package/dist/entries/auth/oneTimeToken.js +27 -289
- package/dist/entries/auth/passwordConfirmCookie.js +40 -63
- package/dist/entries/auth/passwordLogin.js +94 -399
- package/dist/entries/auth/pendingMfaCookie.js +6 -6
- package/dist/entries/auth/policy.js +22 -56
- package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
- package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
- package/dist/entries/auth/sessionCookie.js +58 -73
- package/dist/entries/auth/sessionGuard.js +95 -248
- package/dist/entries/auth/tokenHash.js +11 -43
- package/dist/entries/cache/createCacheStore.js +126 -117
- package/dist/entries/cache/repository.js +25 -0
- package/dist/entries/cache/simpleCache.js +12 -7
- package/dist/entries/cache/tokens.js +9 -0
- package/dist/entries/config/applicationConfig.js +163 -0
- package/dist/entries/config/envSchema.js +21 -4
- package/dist/entries/contracts/application.js +1 -0
- package/dist/entries/contracts/authUserDirectory.js +10 -0
- package/dist/entries/contracts/container.js +99 -26
- package/dist/entries/contracts/di.js +3 -0
- package/dist/entries/contracts/executionContext.js +7 -0
- package/dist/entries/contracts/executionOperations.js +7 -0
- package/dist/entries/contracts/executionOwnership.js +7 -0
- package/dist/entries/contracts/membership.js +1 -0
- package/dist/entries/contracts/persistence.js +1 -0
- package/dist/entries/contracts/serviceTokens.js +26 -116
- package/dist/entries/contracts/services.js +98 -0
- package/dist/entries/contracts/token.js +41 -0
- package/dist/entries/crypto/fieldEncryption.js +49 -50
- package/dist/entries/crypto/mfaSecret.js +86 -82
- package/dist/entries/database/acquisitionMetrics.js +107 -0
- package/dist/entries/database/baseRepository.d.ts +2 -0
- package/dist/entries/database/bindings.js +2082 -0
- package/dist/entries/database/definitions.js +175 -0
- package/dist/entries/database/errors.js +114 -89
- package/dist/entries/database/factory.js +67 -28
- package/dist/entries/database/migrations.js +172 -224
- package/dist/entries/database/model.d.ts +1 -0
- package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
- package/dist/entries/database/query.js +159 -161
- package/dist/entries/database/repositoryQuery.d.ts +1 -0
- package/dist/entries/database/repositoryQuery.js +1 -1373
- package/dist/entries/database/schema.js +216 -236
- package/dist/entries/database/session.js +1 -0
- package/dist/entries/database/sqliteConnection.js +525 -83
- package/dist/entries/database/tokens.js +9 -0
- package/dist/entries/errors/http.js +118 -1
- package/dist/entries/http/authMiddleware.js +8 -5
- package/dist/entries/http/authorizeMiddleware.js +1 -1
- package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
- package/dist/entries/http/clientIp.js +2 -2
- package/dist/entries/http/conditionalResponse.js +19 -7
- package/dist/entries/http/corsMiddleware.js +6 -101
- package/dist/entries/http/csrfMiddleware.js +92 -106
- package/dist/entries/http/csrfToken.js +58 -94
- package/dist/entries/http/etag.js +7 -4
- package/dist/entries/http/flashMiddleware.js +57 -99
- package/dist/entries/http/flashSession.js +41 -68
- package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
- package/dist/entries/http/metricsMiddleware.js +2 -16
- package/dist/entries/http/parseMultipartUpload.js +15 -29
- package/dist/entries/http/requireAbilityMiddleware.js +2 -2
- package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
- package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
- package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
- package/dist/entries/http/response.js +67 -233
- package/dist/entries/http/routeMiddleware.js +0 -14
- package/dist/entries/http/scimThrottleMiddleware.js +43 -237
- package/dist/entries/http/securedRouteModelBinding.js +37 -25
- package/dist/entries/http/securityHeadersMiddleware.js +8 -25
- package/dist/entries/http/signedUrl.js +20 -110
- package/dist/entries/http/throttleMiddleware.js +41 -185
- package/dist/entries/http/uploads.js +9 -24
- package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
- package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
- package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
- package/dist/entries/mail/mailer.js +68 -78
- package/dist/entries/openapi/generator.js +33 -100
- package/dist/entries/queue/createAppQueue.js +416 -254
- package/dist/entries/queue/failedJobRepository.js +19 -8
- package/dist/entries/queue/failedJobService.js +1 -0
- package/dist/entries/queue/jobRunner.js +141 -66
- package/dist/entries/queue/publicQueue.js +411 -255
- package/dist/entries/queue/queueConfig.js +61 -0
- package/dist/entries/queue/queueHandoff.js +318 -0
- package/dist/entries/queue/queueMetrics.js +989 -1384
- package/dist/entries/queue/queueServices.js +133 -0
- package/dist/entries/queue/queueWorkerTransport.js +1703 -0
- package/dist/entries/queue/redisQueue.js +282 -180
- package/dist/entries/queue.js +6 -45
- package/dist/entries/runtime/application.js +1585 -0
- package/dist/entries/runtime/asyncContextStore.js +0 -16
- package/dist/entries/security/oauthState.js +35 -67
- package/dist/entries/security/publicReads.js +4 -4
- package/dist/entries/security/safeFetch.js +1 -0
- package/dist/entries/security/scimTenantTokens.js +3 -3
- package/dist/entries/security/tokenExpiry.js +2 -2
- package/dist/entries/security/totp.js +1 -87
- package/dist/entries/security/webhookSignature.js +2 -90
- package/dist/entries/storage/storage.js +120 -45
- package/dist/entries/tenant/databaseTenantContext.js +6 -907
- package/dist/entries/tenant/publicTenantHost.js +78 -0
- package/dist/entries/tenant/resolveTenant.js +14 -0
- package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
- package/dist/entries/tenant/tenancyConfig.js +1 -19
- package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
- package/dist/entries/tracing/tracingMiddleware.js +104 -173
- package/dist/entries/view/tokens.js +11 -0
- package/dist/framework/public-api.d.ts +62 -44
- package/dist/index.js +10433 -11347
- package/dist/internal/ormInternal.js +117 -0
- package/dist/internal/ormRuntime.js +5000 -0
- package/package.json +158 -46
- package/dist/core/database/bindConnection.d.ts +0 -1
- package/dist/core/database/boundConnection.d.ts +0 -5
- package/dist/core/database/defaultConnection.d.ts +0 -7
- package/dist/core/database/namedConnections.d.ts +0 -15
- package/dist/core/database/readOnlyCollector.d.ts +0 -7
- package/dist/core/database/repositoryConnection.d.ts +0 -4
- package/dist/core/database/transaction.d.ts +0 -23
- package/dist/core/database/transactionControl.d.ts +0 -6
- package/dist/core/events/deferredModelEvents.d.ts +0 -7
- package/dist/core/facades/index.d.ts +0 -10
- package/dist/core/runtime/applicationRegistry.d.ts +0 -18
- package/dist/entries/database/bindConnection.js +0 -1
- package/dist/entries/database/boundConnection.js +0 -1
- package/dist/entries/database/defaultConnection.js +0 -1
- package/dist/entries/database/namedConnections.js +0 -1
- package/dist/entries/database/repositoryConnection.js +0 -1
- package/dist/entries/database/transaction.js +0 -1
- package/dist/entries/facades.js +0 -711
- package/dist/entries/runtime/applicationRegistry.js +0 -1
|
@@ -1,913 +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
2
|
// ../../src/core/runtime/appEnv.ts
|
|
912
3
|
var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
|
|
913
4
|
function normalizeEnvValue(value) {
|
|
@@ -929,14 +20,14 @@ function envFlagEnabled(value) {
|
|
|
929
20
|
}
|
|
930
21
|
|
|
931
22
|
// ../../src/core/runtime/appKeyPrefix.ts
|
|
932
|
-
function appKeyPrefix() {
|
|
933
|
-
return
|
|
23
|
+
function appKeyPrefix(env = process.env) {
|
|
24
|
+
return env.APP_KEY_PREFIX?.trim() || "strata";
|
|
934
25
|
}
|
|
935
|
-
function appCookieName(kind) {
|
|
936
|
-
return `${appKeyPrefix()}_${kind}`;
|
|
26
|
+
function appCookieName(kind, env = process.env) {
|
|
27
|
+
return `${appKeyPrefix(env)}_${kind}`;
|
|
937
28
|
}
|
|
938
|
-
function appDevSecret(kind) {
|
|
939
|
-
return `${appKeyPrefix()}-dev-${kind}`;
|
|
29
|
+
function appDevSecret(kind, env = process.env) {
|
|
30
|
+
return `${appKeyPrefix(env)}-dev-${kind}`;
|
|
940
31
|
}
|
|
941
32
|
function requireConfiguredSecret(names, devKind, env = process.env) {
|
|
942
33
|
for (const name of names) {
|
|
@@ -948,50 +39,18 @@ function requireConfiguredSecret(names, devKind, env = process.env) {
|
|
|
948
39
|
if (isProductionEnv(env)) {
|
|
949
40
|
throw new Error(`${names[0]} must be set outside development. Do not derive secrets from the app name.`);
|
|
950
41
|
}
|
|
951
|
-
return appDevSecret(devKind);
|
|
42
|
+
return appDevSecret(devKind, env);
|
|
952
43
|
}
|
|
953
44
|
function namespacedRedisKey(kind) {
|
|
954
45
|
return `${appKeyPrefix()}:${kind}`;
|
|
955
46
|
}
|
|
956
|
-
function smtpEhloHost() {
|
|
957
|
-
const raw =
|
|
47
|
+
function smtpEhloHost(env = process.env) {
|
|
48
|
+
const raw = env.MAIL_EHLO?.trim() || `${appKeyPrefix(env)}.local`;
|
|
958
49
|
const safe = raw.replace(/[^a-zA-Z0-9.-]/g, "");
|
|
959
50
|
return safe || "strata.local";
|
|
960
51
|
}
|
|
961
|
-
function
|
|
962
|
-
return
|
|
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";
|
|
52
|
+
function otelServiceName(env = process.env) {
|
|
53
|
+
return env.OTEL_SERVICE_NAME?.trim() || `${appKeyPrefix(env)}-api`;
|
|
995
54
|
}
|
|
996
55
|
|
|
997
56
|
// ../../src/core/security/safeFetch.ts
|
|
@@ -1077,6 +136,7 @@ async function safeFetch(input, init = {}, options = {}) {
|
|
|
1077
136
|
}
|
|
1078
137
|
const maxRedirects = options.maxRedirects ?? 0;
|
|
1079
138
|
const urlOptions = {
|
|
139
|
+
production: options.production,
|
|
1080
140
|
allowHttp: options.allowHttp,
|
|
1081
141
|
resolveDns: options.resolveDns ?? true,
|
|
1082
142
|
allowPrivate: options.allowPrivate
|
|
@@ -1305,7 +365,7 @@ function isBlockedHostname(hostname) {
|
|
|
1305
365
|
return false;
|
|
1306
366
|
}
|
|
1307
367
|
function productionSafeOutboundOptions(options) {
|
|
1308
|
-
if (!isProductionEnv()) {
|
|
368
|
+
if (!(options.production ?? isProductionEnv())) {
|
|
1309
369
|
return options;
|
|
1310
370
|
}
|
|
1311
371
|
return { ...options, allowPrivate: false, resolveDns: true };
|
|
@@ -1331,44 +391,36 @@ function assertSafeOutboundUrl(rawUrl, options = {}) {
|
|
|
1331
391
|
}
|
|
1332
392
|
|
|
1333
393
|
// ../../src/core/audit/exportStore.ts
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
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
|
-
`;
|
|
394
|
+
async function readPendingAuditLogs(runSql, batchSize) {
|
|
395
|
+
return runSql(async (selected) => {
|
|
396
|
+
const rows = await selected.execute({
|
|
397
|
+
text: `SELECT id,user_id,action,subject_type,subject_id,payload,ip_address,user_agent,checksum,tenant_id,trace_id,created_at
|
|
398
|
+
FROM audit_log WHERE exported_at IS NULL ORDER BY id LIMIT ${selected.dialect.placeholder(1)}`,
|
|
399
|
+
params: [batchSize]
|
|
400
|
+
});
|
|
401
|
+
return rows.map((row) => ({
|
|
402
|
+
...row,
|
|
403
|
+
created_at: new Date(row.created_at),
|
|
404
|
+
payload: typeof row.payload === "string" ? JSON.parse(row.payload) : row.payload
|
|
405
|
+
}));
|
|
1357
406
|
});
|
|
1358
407
|
}
|
|
1359
|
-
async function acknowledgeAuditLogs(ids) {
|
|
1360
|
-
await
|
|
408
|
+
async function acknowledgeAuditLogs(runSql, ids) {
|
|
409
|
+
await runSql(async (selected) => {
|
|
1361
410
|
for (const id of ids) {
|
|
1362
|
-
await
|
|
411
|
+
await selected.execute({
|
|
412
|
+
text: `UPDATE audit_log SET exported_at = ${selected.dialect.nowExpression()} WHERE id = ${selected.dialect.placeholder(1)}`,
|
|
413
|
+
params: [id]
|
|
414
|
+
});
|
|
1363
415
|
}
|
|
1364
416
|
});
|
|
1365
417
|
}
|
|
1366
418
|
|
|
1367
419
|
// ../../src/core/audit/siemFormatter.ts
|
|
1368
|
-
function formatSiemAuditEvent(input) {
|
|
420
|
+
function formatSiemAuditEvent(input, eventType = "strata.audit") {
|
|
1369
421
|
return {
|
|
1370
422
|
timestamp: input.created_at.toISOString(),
|
|
1371
|
-
event_type:
|
|
423
|
+
event_type: eventType,
|
|
1372
424
|
actor_user_id: input.user_id,
|
|
1373
425
|
tenant_id: input.tenant_id ?? null,
|
|
1374
426
|
trace_id: input.trace_id ?? null,
|
|
@@ -1381,7 +433,7 @@ function formatSiemAuditEvent(input) {
|
|
|
1381
433
|
payload: input.payload ?? {}
|
|
1382
434
|
};
|
|
1383
435
|
}
|
|
1384
|
-
function formatCefLine(event) {
|
|
436
|
+
function formatCefLine(event, displayName = "Strata") {
|
|
1385
437
|
const extension = [
|
|
1386
438
|
`rt=${event.timestamp}`,
|
|
1387
439
|
`suid=${event.actor_user_id ?? "unknown"}`,
|
|
@@ -1394,62 +446,73 @@ function formatCefLine(event) {
|
|
|
1394
446
|
`src=${event.ip_address ?? ""}`,
|
|
1395
447
|
`request=${event.trace_id ?? ""}`
|
|
1396
448
|
].join(" ");
|
|
1397
|
-
return `CEF:0|${
|
|
449
|
+
return `CEF:0|${displayName}|API|1.0|${event.action}|${event.subject_type}|5|${extension}`;
|
|
1398
450
|
}
|
|
1399
451
|
|
|
1400
452
|
// ../../src/core/audit/exportAuditLogs.ts
|
|
1401
|
-
function resolveAuditExportConfig() {
|
|
1402
|
-
const endpoint =
|
|
453
|
+
function resolveAuditExportConfig(env = process.env) {
|
|
454
|
+
const endpoint = env.SIEM_EXPORT_URL?.trim();
|
|
1403
455
|
if (!endpoint) {
|
|
1404
456
|
return null;
|
|
1405
457
|
}
|
|
1406
|
-
assertSafeOutboundUrl(endpoint, { allowHttp:
|
|
1407
|
-
const batchSize = Number(
|
|
458
|
+
assertSafeOutboundUrl(endpoint, { allowHttp: !isProductionEnv(env) });
|
|
459
|
+
const batchSize = Number(env.SIEM_EXPORT_BATCH_SIZE ?? "100");
|
|
1408
460
|
return {
|
|
1409
461
|
endpoint,
|
|
1410
|
-
format:
|
|
462
|
+
format: env.SIEM_EXPORT_FORMAT === "cef" ? "cef" : "json",
|
|
1411
463
|
batchSize: Number.isFinite(batchSize) ? batchSize : 100
|
|
1412
464
|
};
|
|
1413
465
|
}
|
|
1414
|
-
|
|
1415
|
-
const
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
const
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
466
|
+
function createAuditExporter(options) {
|
|
467
|
+
const env = Object.freeze({ ...options.environment });
|
|
468
|
+
const config = resolveAuditExportConfig(env);
|
|
469
|
+
const runSql = options.runSql;
|
|
470
|
+
const token = env.SIEM_EXPORT_TOKEN;
|
|
471
|
+
const eventType = env.SIEM_EVENT_TYPE?.trim() || `${appKeyPrefix(env)}.audit`;
|
|
472
|
+
const displayName = env.APP_NAME?.trim() || "Strata";
|
|
473
|
+
return async () => {
|
|
474
|
+
if (!config) {
|
|
475
|
+
return 0;
|
|
476
|
+
}
|
|
477
|
+
const rows = await readPendingAuditLogs(runSql, config.batchSize);
|
|
478
|
+
if (rows.length === 0) {
|
|
479
|
+
return 0;
|
|
480
|
+
}
|
|
481
|
+
const events = rows.map((row) => formatSiemAuditEvent({
|
|
482
|
+
action: row.action,
|
|
483
|
+
subject_type: row.subject_type,
|
|
484
|
+
subject_id: row.subject_id,
|
|
485
|
+
user_id: row.user_id,
|
|
486
|
+
tenant_id: row.tenant_id,
|
|
487
|
+
trace_id: row.trace_id,
|
|
488
|
+
ip_address: row.ip_address,
|
|
489
|
+
user_agent: row.user_agent,
|
|
490
|
+
checksum: row.checksum,
|
|
491
|
+
payload: row.payload,
|
|
492
|
+
created_at: row.created_at
|
|
493
|
+
}, eventType));
|
|
494
|
+
const body = config.format === "cef" ? events.map((event) => formatCefLine(event, displayName)).join(`
|
|
1437
495
|
`) : JSON.stringify({ events });
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
496
|
+
const response = await safeFetch(config.endpoint, {
|
|
497
|
+
method: "POST",
|
|
498
|
+
headers: {
|
|
499
|
+
"content-type": config.format === "cef" ? "text/plain" : "application/json",
|
|
500
|
+
...token ? { authorization: `Bearer ${token}` } : {}
|
|
501
|
+
},
|
|
502
|
+
body
|
|
503
|
+
}, { allowHttp: !isProductionEnv(env) });
|
|
504
|
+
if (!response.ok) {
|
|
505
|
+
throw new Error(`SIEM export failed with status ${response.status}.`);
|
|
506
|
+
}
|
|
507
|
+
await acknowledgeAuditLogs(runSql, rows.map((row) => row.id));
|
|
508
|
+
return rows.length;
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
function exportPendingAuditLogs(runSql, environment = process.env) {
|
|
512
|
+
return createAuditExporter({ runSql, environment })();
|
|
1451
513
|
}
|
|
1452
514
|
export {
|
|
515
|
+
createAuditExporter,
|
|
1453
516
|
exportPendingAuditLogs,
|
|
1454
517
|
resolveAuditExportConfig
|
|
1455
518
|
};
|