@getstrata/core 2.2.60 → 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 +22 -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 -256
- package/dist/entries/queue/failedJobRepository.js +17 -8
- package/dist/entries/queue/failedJobService.js +1 -0
- package/dist/entries/queue/jobRunner.js +141 -66
- package/dist/entries/queue/publicQueue.js +411 -257
- package/dist/entries/queue/queueConfig.js +61 -0
- package/dist/entries/queue/queueHandoff.js +318 -0
- package/dist/entries/queue/queueMetrics.js +989 -1386
- 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 +10435 -11351
- 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,1072 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var __esm = (fn, res, err) => () => {
|
|
3
|
-
if (fn)
|
|
4
|
-
try {
|
|
5
|
-
res = fn(fn = 0);
|
|
6
|
-
} catch (e) {
|
|
7
|
-
err = [e];
|
|
8
|
-
}
|
|
9
|
-
if (err)
|
|
10
|
-
throw err[0];
|
|
11
|
-
return res;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
// ../../src/core/database/boundConnection.ts
|
|
15
|
-
function boundConnectionState() {
|
|
16
|
-
const globalRecord = globalThis;
|
|
17
|
-
const existing = globalRecord[BOUND_CONNECTION_KEY];
|
|
18
|
-
if (existing) {
|
|
19
|
-
return existing;
|
|
20
|
-
}
|
|
21
|
-
const created = { connection: null };
|
|
22
|
-
globalRecord[BOUND_CONNECTION_KEY] = created;
|
|
23
|
-
return created;
|
|
24
|
-
}
|
|
25
|
-
function getBoundDatabaseConnection() {
|
|
26
|
-
return boundConnectionState().connection;
|
|
27
|
-
}
|
|
28
|
-
var BOUND_CONNECTION_KEY;
|
|
29
|
-
var init_boundConnection = __esm(() => {
|
|
30
|
-
BOUND_CONNECTION_KEY = Symbol.for("@getstrata/boundDatabaseConnection");
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
// ../../src/core/runtime/asyncContextStore.ts
|
|
34
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
35
|
-
function createAsyncContextStore(key) {
|
|
36
|
-
const symbol = Symbol.for(key);
|
|
37
|
-
const globalRecord = globalThis;
|
|
38
|
-
const existing = globalRecord[symbol];
|
|
39
|
-
if (existing) {
|
|
40
|
-
return existing;
|
|
41
|
-
}
|
|
42
|
-
const store = new AsyncLocalStorage;
|
|
43
|
-
globalRecord[symbol] = store;
|
|
44
|
-
return store;
|
|
45
|
-
}
|
|
46
|
-
var init_asyncContextStore = () => {};
|
|
47
|
-
|
|
48
|
-
// ../../src/core/database/connectionContext.ts
|
|
49
|
-
function runWithDatabaseConnection(connection, callback) {
|
|
50
|
-
return activeConnection.run(connection, callback);
|
|
51
|
-
}
|
|
52
|
-
function getActiveDatabaseConnection(fallback) {
|
|
53
|
-
return activeConnection.getStore() ?? fallback;
|
|
54
|
-
}
|
|
55
|
-
function hasActiveDatabaseConnection() {
|
|
56
|
-
return activeConnection.getStore() !== undefined;
|
|
57
|
-
}
|
|
58
|
-
var activeConnection;
|
|
59
|
-
var init_connectionContext = __esm(() => {
|
|
60
|
-
init_asyncContextStore();
|
|
61
|
-
activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
// ../../src/core/database/queryProxy.ts
|
|
65
|
-
var POOL_CONNECTION_METHODS;
|
|
66
|
-
var init_queryProxy = __esm(() => {
|
|
67
|
-
init_connectionContext();
|
|
68
|
-
POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
// ../../src/core/database/defaultConnection.ts
|
|
72
|
-
function defaultConnectionState() {
|
|
73
|
-
const globalRecord = globalThis;
|
|
74
|
-
const existing = globalRecord[DEFAULT_CONNECTION_KEY];
|
|
75
|
-
if (existing) {
|
|
76
|
-
return existing;
|
|
77
|
-
}
|
|
78
|
-
const created = { pool: null, query: null };
|
|
79
|
-
globalRecord[DEFAULT_CONNECTION_KEY] = created;
|
|
80
|
-
return created;
|
|
81
|
-
}
|
|
82
|
-
function getDefaultDatabasePool() {
|
|
83
|
-
const pool = defaultConnectionState().pool;
|
|
84
|
-
if (!pool) {
|
|
85
|
-
throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
86
|
-
}
|
|
87
|
-
return pool;
|
|
88
|
-
}
|
|
89
|
-
function getDefaultDatabaseQuery() {
|
|
90
|
-
const query = defaultConnectionState().query;
|
|
91
|
-
if (!query) {
|
|
92
|
-
throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
93
|
-
}
|
|
94
|
-
return query;
|
|
95
|
-
}
|
|
96
|
-
var DEFAULT_CONNECTION_KEY;
|
|
97
|
-
var init_defaultConnection = __esm(() => {
|
|
98
|
-
init_queryProxy();
|
|
99
|
-
DEFAULT_CONNECTION_KEY = Symbol.for("@getstrata/defaultDatabaseConnection");
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
// ../../src/core/tenant/tenantContext.ts
|
|
103
|
-
function runWithTenant(tenant, callback) {
|
|
104
|
-
return tenantContext.run(tenant, callback);
|
|
105
|
-
}
|
|
106
|
-
function currentTenant() {
|
|
107
|
-
return tenantContext.getStore() ?? null;
|
|
108
|
-
}
|
|
109
|
-
var tenantContext;
|
|
110
|
-
var init_tenantContext = __esm(() => {
|
|
111
|
-
init_asyncContextStore();
|
|
112
|
-
tenantContext = createAsyncContextStore("@getstrata/tenantContext");
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
// ../../src/core/events/eventBus.ts
|
|
116
|
-
class EventBus {
|
|
117
|
-
constructor() {}
|
|
118
|
-
transactionalListeners = new Map;
|
|
119
|
-
listenTransactional(event, listener) {
|
|
120
|
-
const handlers = this.transactionalListeners.get(event) ?? new Set;
|
|
121
|
-
handlers.add(listener);
|
|
122
|
-
this.transactionalListeners.set(event, handlers);
|
|
123
|
-
return () => {
|
|
124
|
-
handlers.delete(listener);
|
|
125
|
-
if (!handlers.size)
|
|
126
|
-
this.transactionalListeners.delete(event);
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
hasTransactionalListeners(event) {
|
|
130
|
-
return (this.transactionalListeners.get(event)?.size ?? 0) > 0;
|
|
131
|
-
}
|
|
132
|
-
async dispatchTransactional(event, payload) {
|
|
133
|
-
for (const listener of this.transactionalListeners.get(event) ?? [])
|
|
134
|
-
await listener(payload);
|
|
135
|
-
}
|
|
136
|
-
listeners = new Map;
|
|
137
|
-
on(event, listener) {
|
|
138
|
-
return this.listen(event, listener);
|
|
139
|
-
}
|
|
140
|
-
listen(event, listener) {
|
|
141
|
-
const handlers = this.listeners.get(event) ?? new Set;
|
|
142
|
-
handlers.add(listener);
|
|
143
|
-
this.listeners.set(event, handlers);
|
|
144
|
-
return () => {
|
|
145
|
-
handlers.delete(listener);
|
|
146
|
-
if (handlers.size === 0) {
|
|
147
|
-
this.listeners.delete(event);
|
|
148
|
-
}
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
async emit(event, payload) {
|
|
152
|
-
await this.dispatch(event, payload);
|
|
153
|
-
}
|
|
154
|
-
async dispatch(event, payload) {
|
|
155
|
-
const handlers = this.listeners.get(event);
|
|
156
|
-
if (!handlers || handlers.size === 0) {
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
for (const handler of handlers) {
|
|
160
|
-
await handler(payload);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
function readSharedEventBus() {
|
|
165
|
-
const globalBus = globalThis[EVENT_BUS_KEY];
|
|
166
|
-
if (globalBus) {
|
|
167
|
-
return globalBus;
|
|
168
|
-
}
|
|
169
|
-
const bus = new EventBus;
|
|
170
|
-
globalThis[EVENT_BUS_KEY] = bus;
|
|
171
|
-
return bus;
|
|
172
|
-
}
|
|
173
|
-
var EVENT_BUS_KEY, eventBus;
|
|
174
|
-
var init_eventBus = __esm(() => {
|
|
175
|
-
EVENT_BUS_KEY = Symbol.for("@getstrata/eventBus");
|
|
176
|
-
eventBus = readSharedEventBus();
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
// ../../src/core/database/transactionControl.ts
|
|
180
|
-
function unwrapTransactionRollback(error, depth = 0) {
|
|
181
|
-
if (error instanceof TransactionRollback) {
|
|
182
|
-
return error;
|
|
183
|
-
}
|
|
184
|
-
if (depth >= 5 || !(error instanceof Error) || error.cause === undefined) {
|
|
185
|
-
return null;
|
|
186
|
-
}
|
|
187
|
-
return unwrapTransactionRollback(error.cause, depth + 1);
|
|
188
|
-
}
|
|
189
|
-
function hasActiveTransaction() {
|
|
190
|
-
return hasActiveDatabaseConnection() && (transactionScopes.getStore()?.rollback.length ?? 0) > 0;
|
|
191
|
-
}
|
|
192
|
-
function requestTransactionRollback() {
|
|
193
|
-
const state = transactionScopes.getStore();
|
|
194
|
-
const index = state ? state.rollback.length - 1 : -1;
|
|
195
|
-
if (!state || index < 0) {
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
state.rollback[index] = true;
|
|
199
|
-
}
|
|
200
|
-
function scopeRequestsRollback() {
|
|
201
|
-
const state = transactionScopes.getStore();
|
|
202
|
-
if (!state || state.rollback.length === 0) {
|
|
203
|
-
return false;
|
|
204
|
-
}
|
|
205
|
-
return state.rollback[state.rollback.length - 1] === true;
|
|
206
|
-
}
|
|
207
|
-
async function commitOrRollbackScope(result) {
|
|
208
|
-
if (scopeRequestsRollback()) {
|
|
209
|
-
throw new TransactionRollback(result);
|
|
210
|
-
}
|
|
211
|
-
return result;
|
|
212
|
-
}
|
|
213
|
-
async function settleTransaction(work) {
|
|
214
|
-
try {
|
|
215
|
-
return await work();
|
|
216
|
-
} catch (error) {
|
|
217
|
-
const rollback = unwrapTransactionRollback(error);
|
|
218
|
-
if (rollback) {
|
|
219
|
-
return rollback.result;
|
|
220
|
-
}
|
|
221
|
-
throw error;
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
async function runWithTransactionScope(callback) {
|
|
225
|
-
const existing = transactionScopes.getStore();
|
|
226
|
-
if (existing) {
|
|
227
|
-
existing.rollback.push(false);
|
|
228
|
-
try {
|
|
229
|
-
return await callback();
|
|
230
|
-
} finally {
|
|
231
|
-
existing.rollback.pop();
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
const state = { rollback: [false] };
|
|
235
|
-
return await transactionScopes.run(state, callback);
|
|
236
|
-
}
|
|
237
|
-
var TransactionRollback, transactionScopes;
|
|
238
|
-
var init_transactionControl = __esm(() => {
|
|
239
|
-
init_asyncContextStore();
|
|
240
|
-
init_connectionContext();
|
|
241
|
-
TransactionRollback = class TransactionRollback extends Error {
|
|
242
|
-
result;
|
|
243
|
-
constructor(result) {
|
|
244
|
-
super("Transaction rolled back");
|
|
245
|
-
this.name = "TransactionRollback";
|
|
246
|
-
this.result = result;
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
transactionScopes = createAsyncContextStore("@getstrata/transactionScopes");
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
// ../../src/core/tenant/tenancyConfig.ts
|
|
253
|
-
function readTenancyDriver(env = process.env) {
|
|
254
|
-
const raw = env.TENANCY_DRIVER?.trim();
|
|
255
|
-
if (raw === undefined || raw === "") {
|
|
256
|
-
return "rls";
|
|
257
|
-
}
|
|
258
|
-
if (TENANCY_DRIVERS.includes(raw)) {
|
|
259
|
-
return raw;
|
|
260
|
-
}
|
|
261
|
-
throw new Error(`TENANCY_DRIVER must be one of ${TENANCY_DRIVERS.join(", ")}; received "${raw}".`);
|
|
262
|
-
}
|
|
263
|
-
function isTenancyEnabled(env = process.env) {
|
|
264
|
-
return readTenancyDriver(env) !== "none";
|
|
265
|
-
}
|
|
266
|
-
function isRlsTenancy(env = process.env) {
|
|
267
|
-
return readTenancyDriver(env) === "rls";
|
|
268
|
-
}
|
|
269
|
-
var TENANCY_DRIVERS;
|
|
270
|
-
var init_tenancyConfig = __esm(() => {
|
|
271
|
-
TENANCY_DRIVERS = ["rls", "column", "none"];
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
// ../../src/core/tenant/tenantDatabaseScope.ts
|
|
275
|
-
import { getDefaultDatabasePool as getDefaultDatabasePool2 } from "@getstrata/core/database/defaultConnection";
|
|
276
|
-
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
277
|
-
async function applyTenantContextToTransaction(transaction, tenantId) {
|
|
278
|
-
await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
|
|
279
|
-
await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
|
|
280
|
-
}
|
|
281
|
-
async function runWithTenantDatabase(tenant, callback) {
|
|
282
|
-
const outerTenant = currentTenant();
|
|
283
|
-
if (hasActiveDatabaseConnection() && outerTenant && outerTenant.id !== tenant.id) {
|
|
284
|
-
throw new Error("Cannot switch tenants inside an active database transaction.");
|
|
285
|
-
}
|
|
286
|
-
if (!isTenancyEnabled() || !isRlsTenancy()) {
|
|
287
|
-
return await runWithTenant(tenant, callback);
|
|
288
|
-
}
|
|
289
|
-
if (hasActiveDatabaseConnection()) {
|
|
290
|
-
const activeConnection = getActiveDatabaseConnection(getDefaultDatabasePool2());
|
|
291
|
-
return await runWithScopedTenantTransaction(() => applyTenantContextToTransaction(activeConnection, tenant.id), () => runWithTenant(tenant, callback));
|
|
292
|
-
}
|
|
293
|
-
const pool = getDefaultDatabasePool2();
|
|
294
|
-
const begin = pool.begin;
|
|
295
|
-
if (typeof begin !== "function") {
|
|
296
|
-
throw new Error("RLS tenant scope requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
|
|
297
|
-
}
|
|
298
|
-
return await settleTransaction(() => runWithDeferredModelEvents(async () => {
|
|
299
|
-
return await begin.bind(pool)(AsyncLocalStorage2.bind(async (transaction) => {
|
|
300
|
-
await applyTenantContextToTransaction(transaction, tenant.id);
|
|
301
|
-
return await runWithDatabaseConnection(transaction, async () => {
|
|
302
|
-
return await runWithTransactionScope(async () => commitOrRollbackScope(await runWithTenant(tenant, callback)));
|
|
303
|
-
});
|
|
304
|
-
}));
|
|
305
|
-
}));
|
|
306
|
-
}
|
|
307
|
-
function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
|
|
308
|
-
return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
|
|
309
|
-
}
|
|
310
|
-
var init_tenantDatabaseScope = __esm(() => {
|
|
311
|
-
init_connectionContext();
|
|
312
|
-
init_transactionControl();
|
|
313
|
-
init_deferredModelEvents();
|
|
314
|
-
init_databaseTenantContext();
|
|
315
|
-
init_tenancyConfig();
|
|
316
|
-
init_tenantContext();
|
|
317
|
-
});
|
|
318
|
-
|
|
319
|
-
// ../../src/core/events/deferredModelEvents.ts
|
|
320
|
-
function sameTenant(left, right) {
|
|
321
|
-
if (left === null && right === null) {
|
|
322
|
-
return true;
|
|
323
|
-
}
|
|
324
|
-
if (left === null || right === null) {
|
|
325
|
-
return false;
|
|
326
|
-
}
|
|
327
|
-
return left.id === right.id;
|
|
328
|
-
}
|
|
329
|
-
function groupQueuedModelEvents(queued) {
|
|
330
|
-
const groups = [];
|
|
331
|
-
for (const item of queued) {
|
|
332
|
-
const lastGroup = groups[groups.length - 1];
|
|
333
|
-
const last = lastGroup?.[lastGroup.length - 1];
|
|
334
|
-
if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant) || "callback" in last !== "callback" in item) {
|
|
335
|
-
groups.push([item]);
|
|
336
|
-
} else {
|
|
337
|
-
lastGroup.push(item);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
return groups;
|
|
341
|
-
}
|
|
342
|
-
async function dispatchEventBatch(batch) {
|
|
343
|
-
for (const item of batch) {
|
|
344
|
-
if ("callback" in item)
|
|
345
|
-
await item.callback();
|
|
346
|
-
else
|
|
347
|
-
await eventBus.dispatch(item.event, item.payload);
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
async function dispatchQueuedModelEvents(queued) {
|
|
351
|
-
if (queued.length === 0) {
|
|
352
|
-
return;
|
|
353
|
-
}
|
|
354
|
-
await Promise.resolve().then(() => init_tenantDatabaseScope());
|
|
355
|
-
for (const batch of groupQueuedModelEvents(queued)) {
|
|
356
|
-
const tenant = batch[0]?.tenant ?? null;
|
|
357
|
-
if (tenant) {
|
|
358
|
-
if (batch.some((item) => ("callback" in item))) {
|
|
359
|
-
await runWithTenant(tenant, () => dispatchEventBatch(batch));
|
|
360
|
-
} else {
|
|
361
|
-
await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
|
|
362
|
-
}
|
|
363
|
-
} else {
|
|
364
|
-
await dispatchEventBatch(batch);
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
async function dispatchModelEvent(event, payload) {
|
|
369
|
-
await eventBus.dispatchTransactional(event, payload);
|
|
370
|
-
const state = deferredModelEvents.getStore();
|
|
371
|
-
const frame = state?.frames[state.frames.length - 1];
|
|
372
|
-
if (frame) {
|
|
373
|
-
frame.push({
|
|
374
|
-
event,
|
|
375
|
-
payload,
|
|
376
|
-
tenant: currentTenant()
|
|
377
|
-
});
|
|
378
|
-
return;
|
|
379
|
-
}
|
|
380
|
-
await eventBus.dispatch(event, payload);
|
|
381
|
-
}
|
|
382
|
-
async function runWithDeferredModelEvents(callback) {
|
|
383
|
-
const existing = deferredModelEvents.getStore();
|
|
384
|
-
if (existing) {
|
|
385
|
-
existing.frames.push([]);
|
|
386
|
-
existing.rollbackFrames.push([]);
|
|
387
|
-
try {
|
|
388
|
-
const result = await callback();
|
|
389
|
-
const nested = existing.frames.pop() ?? [];
|
|
390
|
-
const rollback = existing.rollbackFrames.pop() ?? [];
|
|
391
|
-
existing.rollbackFrames.at(-1)?.push(...rollback);
|
|
392
|
-
const parent = existing.frames[existing.frames.length - 1];
|
|
393
|
-
if (parent) {
|
|
394
|
-
parent.push(...nested);
|
|
395
|
-
}
|
|
396
|
-
return result;
|
|
397
|
-
} catch (error) {
|
|
398
|
-
existing.frames.pop();
|
|
399
|
-
for (const rollback of (existing.rollbackFrames.pop() ?? []).reverse())
|
|
400
|
-
rollback();
|
|
401
|
-
throw error;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
const state = { frames: [[]], rollbackFrames: [[]] };
|
|
405
|
-
let result;
|
|
406
|
-
try {
|
|
407
|
-
result = await deferredModelEvents.run(state, callback);
|
|
408
|
-
} catch (error) {
|
|
409
|
-
for (const rollback of (state.rollbackFrames[0] ?? []).reverse())
|
|
410
|
-
rollback();
|
|
411
|
-
throw error;
|
|
412
|
-
}
|
|
413
|
-
await dispatchQueuedModelEvents(state.frames[0] ?? []);
|
|
414
|
-
return result;
|
|
415
|
-
}
|
|
416
|
-
var deferredModelEvents;
|
|
417
|
-
var init_deferredModelEvents = __esm(() => {
|
|
418
|
-
init_asyncContextStore();
|
|
419
|
-
init_tenantContext();
|
|
420
|
-
init_eventBus();
|
|
421
|
-
deferredModelEvents = createAsyncContextStore("@getstrata/deferredModelEvents");
|
|
422
|
-
});
|
|
423
|
-
|
|
424
|
-
// ../../src/core/database/acquisitionMetrics.ts
|
|
425
|
-
async function observeTransactionAcquisition(metrics, acquire, signal) {
|
|
426
|
-
const state = states.get(metrics);
|
|
427
|
-
if (!state)
|
|
428
|
-
throw new TypeError("Transaction acquisition metrics must be created by the framework factory.");
|
|
429
|
-
const started = performance.now();
|
|
430
|
-
state.inflight++;
|
|
431
|
-
let outcome = "acquired";
|
|
432
|
-
try {
|
|
433
|
-
return await acquire();
|
|
434
|
-
} catch (error) {
|
|
435
|
-
outcome = signal?.aborted ? "aborted" : "failed";
|
|
436
|
-
throw error;
|
|
437
|
-
} finally {
|
|
438
|
-
state.inflight--;
|
|
439
|
-
const elapsed = Math.max(0, performance.now() - started) / 1000;
|
|
440
|
-
const histogram = state.outcomes[outcomes.indexOf(outcome)];
|
|
441
|
-
if (histogram) {
|
|
442
|
-
histogram.count++;
|
|
443
|
-
histogram.sumSeconds += elapsed;
|
|
444
|
-
for (let index = 0;index < ACQUISITION_BUCKETS_SECONDS.length; index++) {
|
|
445
|
-
const bound = ACQUISITION_BUCKETS_SECONDS[index];
|
|
446
|
-
if (bound !== undefined && elapsed <= bound)
|
|
447
|
-
histogram.buckets[index] = (histogram.buckets[index] ?? 0) + 1;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
var ACQUISITION_BUCKETS_SECONDS, outcomes, metricsBrand, states;
|
|
453
|
-
var init_acquisitionMetrics = __esm(() => {
|
|
454
|
-
ACQUISITION_BUCKETS_SECONDS = [
|
|
455
|
-
0.001,
|
|
456
|
-
0.005,
|
|
457
|
-
0.01,
|
|
458
|
-
0.025,
|
|
459
|
-
0.05,
|
|
460
|
-
0.1,
|
|
461
|
-
0.25,
|
|
462
|
-
0.5,
|
|
463
|
-
1,
|
|
464
|
-
2.5,
|
|
465
|
-
5,
|
|
466
|
-
10
|
|
467
|
-
];
|
|
468
|
-
outcomes = ["acquired", "failed", "aborted"];
|
|
469
|
-
metricsBrand = Symbol("transaction acquisition metrics");
|
|
470
|
-
states = new WeakMap;
|
|
471
|
-
});
|
|
472
|
-
|
|
473
|
-
// ../../src/core/database/connection.ts
|
|
474
|
-
function createDatabaseConnection(source) {
|
|
475
|
-
return {
|
|
476
|
-
async unsafe(query, params = []) {
|
|
477
|
-
return await source.unsafe(query, params);
|
|
478
|
-
}
|
|
479
|
-
};
|
|
480
|
-
}
|
|
481
|
-
var init_connection = () => {};
|
|
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/contracts/container.ts
|
|
912
|
-
function createServiceToken(key) {
|
|
913
|
-
if (!key.trim())
|
|
914
|
-
throw new Error("Service token key must not be empty.");
|
|
915
|
-
return key;
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
class ServiceContainer {
|
|
919
|
-
services = new Map;
|
|
920
|
-
singletonFactories = new Map;
|
|
921
|
-
bindings = new Map;
|
|
922
|
-
resolutionPath = [];
|
|
923
|
-
set(key, value) {
|
|
924
|
-
this.singletonFactories.delete(key);
|
|
925
|
-
this.bindings.delete(key);
|
|
926
|
-
this.services.set(key, value);
|
|
927
|
-
return value;
|
|
928
|
-
}
|
|
929
|
-
singleton(key, factory) {
|
|
930
|
-
this.bindings.delete(key);
|
|
931
|
-
this.services.delete(key);
|
|
932
|
-
this.singletonFactories.set(key, factory);
|
|
933
|
-
}
|
|
934
|
-
bind(key, factory) {
|
|
935
|
-
this.singletonFactories.delete(key);
|
|
936
|
-
this.services.delete(key);
|
|
937
|
-
this.bindings.set(key, factory);
|
|
938
|
-
}
|
|
939
|
-
get(key) {
|
|
940
|
-
if (this.services.has(key)) {
|
|
941
|
-
return this.services.get(key);
|
|
942
|
-
}
|
|
943
|
-
const singletonFactory = this.singletonFactories.get(key);
|
|
944
|
-
if (singletonFactory) {
|
|
945
|
-
const value = this.resolveFactory(key, singletonFactory);
|
|
946
|
-
this.services.set(key, value);
|
|
947
|
-
return value;
|
|
948
|
-
}
|
|
949
|
-
const binding = this.bindings.get(key);
|
|
950
|
-
if (binding) {
|
|
951
|
-
return this.resolveFactory(key, binding);
|
|
952
|
-
}
|
|
953
|
-
throw new Error(`Service "${key}" is not registered.`);
|
|
954
|
-
}
|
|
955
|
-
resolveFactory(key, factory) {
|
|
956
|
-
if (this.resolutionPath.includes(key)) {
|
|
957
|
-
throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
|
|
958
|
-
}
|
|
959
|
-
this.resolutionPath.push(key);
|
|
960
|
-
try {
|
|
961
|
-
return factory(this);
|
|
962
|
-
} finally {
|
|
963
|
-
this.resolutionPath.pop();
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
resolve(key) {
|
|
967
|
-
return this.get(key);
|
|
968
|
-
}
|
|
969
|
-
make(key) {
|
|
970
|
-
return this.resolve(key);
|
|
971
|
-
}
|
|
972
|
-
instance(key, value) {
|
|
973
|
-
return this.set(key, value);
|
|
974
|
-
}
|
|
975
|
-
has(key) {
|
|
976
|
-
return this.services.has(key) || this.singletonFactories.has(key) || this.bindings.has(key);
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
class ConfigStore {
|
|
981
|
-
values = new Map;
|
|
982
|
-
set(key, value) {
|
|
983
|
-
this.values.set(key, value);
|
|
984
|
-
return value;
|
|
985
|
-
}
|
|
986
|
-
get(key) {
|
|
987
|
-
return this.values.get(key);
|
|
988
|
-
}
|
|
989
|
-
require(key) {
|
|
990
|
-
if (!this.values.has(key)) {
|
|
991
|
-
throw new Error(`Config key "${key}" is not defined.`);
|
|
992
|
-
}
|
|
993
|
-
return this.values.get(key);
|
|
994
|
-
}
|
|
995
|
-
has(key) {
|
|
996
|
-
return this.values.has(key);
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
// ../../src/core/contracts/serviceTokens.ts
|
|
1001
|
-
var CORE_THROTTLE_QUOTA_POLICY_TOKEN = createServiceToken("core.throttleQuotaPolicy");
|
|
1002
|
-
var CORE_PUBLIC_TENANCY_TOKEN = createServiceToken("core.publicTenancy");
|
|
1003
|
-
var CORE_TENANT_RESOLVER_TOKEN = createServiceToken("core.tenantResolver");
|
|
1004
|
-
var CORE_HTTP_CLEANUP_TOKEN = createServiceToken("core.httpCleanup");
|
|
1005
|
-
var CORE_CONFIG_TOKEN = "core.config";
|
|
1006
|
-
var CORE_CACHE_TOKEN = "core.cache";
|
|
1007
|
-
var CORE_QUEUE_TOKEN = "core.queue";
|
|
1008
|
-
var CORE_EVENT_BUS_TOKEN = "core.eventBus";
|
|
1009
|
-
var CORE_POLICY_GATE_TOKEN = "core.policyGate";
|
|
1010
|
-
var CORE_AUTH_TOKEN = "core.auth";
|
|
1011
|
-
var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
|
|
1012
|
-
var CORE_ABILITY_CHECKER_TOKEN = "core.abilityChecker";
|
|
1013
|
-
var CORE_AUTH_USER_DIRECTORY_TOKEN = "core.authUserDirectory";
|
|
1014
|
-
function isAbilityChecker(value) {
|
|
1015
|
-
if (!value || typeof value !== "object") {
|
|
1016
|
-
return false;
|
|
1017
|
-
}
|
|
1018
|
-
const candidate = value;
|
|
1019
|
-
return typeof candidate.tokenCan === "function" && typeof candidate.requireAbility === "function";
|
|
1020
|
-
}
|
|
1021
|
-
function isAuthUserDirectory(value) {
|
|
1022
|
-
if (!value || typeof value !== "object") {
|
|
1023
|
-
return false;
|
|
1024
|
-
}
|
|
1025
|
-
return typeof value.findByIdOrThrow === "function";
|
|
1026
|
-
}
|
|
1027
|
-
function resolveAbilityChecker(container) {
|
|
1028
|
-
if (container.has(CORE_ABILITY_CHECKER_TOKEN)) {
|
|
1029
|
-
return container.resolve(CORE_ABILITY_CHECKER_TOKEN);
|
|
1030
|
-
}
|
|
1031
|
-
return container.resolve(CORE_TOKEN_SERVICE_TOKEN);
|
|
1032
|
-
}
|
|
1033
|
-
function resolveAuthUserDirectory(container) {
|
|
1034
|
-
if (container.has(CORE_AUTH_USER_DIRECTORY_TOKEN)) {
|
|
1035
|
-
const directory = container.resolve(CORE_AUTH_USER_DIRECTORY_TOKEN);
|
|
1036
|
-
if (isAuthUserDirectory(directory)) {
|
|
1037
|
-
return directory;
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
if (container.has(CORE_TOKEN_SERVICE_TOKEN)) {
|
|
1041
|
-
const tokenService = container.resolve(CORE_TOKEN_SERVICE_TOKEN);
|
|
1042
|
-
if (isAuthUserDirectory(tokenService)) {
|
|
1043
|
-
return tokenService;
|
|
1044
|
-
}
|
|
1045
|
-
}
|
|
1046
|
-
return null;
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
2
|
// ../../src/core/auth/basicAuthGuard.ts
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
class HttpError extends Error {
|
|
1056
|
-
status;
|
|
1057
|
-
details;
|
|
1058
|
-
constructor(status, message, details) {
|
|
1059
|
-
super(message);
|
|
1060
|
-
this.name = new.target.name;
|
|
1061
|
-
this.status = status;
|
|
1062
|
-
this.details = details;
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
class UnprocessableEntityError extends HttpError {
|
|
1066
|
-
constructor(message = "Unprocessable Entity", details) {
|
|
1067
|
-
super(422, message, details);
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
3
|
+
import {
|
|
4
|
+
authenticateProof,
|
|
5
|
+
authUserFromOutcome
|
|
6
|
+
} from "@getstrata/core/auth/authOutcome";
|
|
7
|
+
import { UnprocessableEntityError as UnprocessableEntityError2 } from "@getstrata/core/errors/http";
|
|
1070
8
|
|
|
1071
9
|
// ../../src/core/http/statelessAuth.ts
|
|
1072
10
|
function authorizationScheme(request) {
|
|
@@ -1110,9 +48,6 @@ function readBasicCredentials(request) {
|
|
|
1110
48
|
}
|
|
1111
49
|
}
|
|
1112
50
|
|
|
1113
|
-
// ../../src/core/auth/basicAuthGuard.ts
|
|
1114
|
-
init_databaseTenantContext();
|
|
1115
|
-
|
|
1116
51
|
// ../../src/core/auth/accountState.ts
|
|
1117
52
|
function isAccountActive(record) {
|
|
1118
53
|
return record.is_active === undefined || record.is_active === true;
|
|
@@ -1137,6 +72,9 @@ async function verifyPassword(password, passwordHash) {
|
|
|
1137
72
|
return await Bun.password.verify(password, passwordHash);
|
|
1138
73
|
}
|
|
1139
74
|
|
|
75
|
+
// ../../src/core/auth/passwordLogin.ts
|
|
76
|
+
import { UnprocessableEntityError } from "@getstrata/core/errors/http";
|
|
77
|
+
|
|
1140
78
|
// ../../src/core/runtime/appEnv.ts
|
|
1141
79
|
var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
|
|
1142
80
|
function normalizeEnvValue(value) {
|
|
@@ -1162,8 +100,8 @@ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "crypt
|
|
|
1162
100
|
var ENCRYPTION_PREFIX = "enc:v1:";
|
|
1163
101
|
var IV_LENGTH = 12;
|
|
1164
102
|
var TAG_LENGTH = 16;
|
|
1165
|
-
function resolveEncryptionKey() {
|
|
1166
|
-
const raw =
|
|
103
|
+
function resolveEncryptionKey(env) {
|
|
104
|
+
const raw = env.KMS_ENCRYPTION_KEY?.trim();
|
|
1167
105
|
if (!raw) {
|
|
1168
106
|
return null;
|
|
1169
107
|
}
|
|
@@ -1176,15 +114,45 @@ function resolveEncryptionKey() {
|
|
|
1176
114
|
}
|
|
1177
115
|
throw new Error("KMS_ENCRYPTION_KEY must be 32 bytes (hex or base64).");
|
|
1178
116
|
}
|
|
1179
|
-
function
|
|
1180
|
-
const
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
117
|
+
function createFieldEncryptionCodec(env) {
|
|
118
|
+
const configured = resolveFieldEncryptionKeyring(env);
|
|
119
|
+
const key = resolveEncryptionKey(env);
|
|
120
|
+
const enabled = env.FEATURE_FIELD_ENCRYPTION === "false" ? false : env.FEATURE_FIELD_ENCRYPTION === "true" ? true : Boolean(configured || key);
|
|
121
|
+
return Object.freeze({
|
|
122
|
+
isFieldEncryptionEnabled: () => enabled,
|
|
123
|
+
protectEmail(email) {
|
|
124
|
+
const normalized = normalizeEmail(email);
|
|
125
|
+
if (configured && enabled)
|
|
126
|
+
return {
|
|
127
|
+
storedEmail: configured.encrypt(normalized, "email"),
|
|
128
|
+
emailLookup: configured.keyring.lookup(normalized)
|
|
129
|
+
};
|
|
130
|
+
if (!key || !enabled)
|
|
131
|
+
return { storedEmail: normalized, emailLookup: normalized };
|
|
132
|
+
return {
|
|
133
|
+
storedEmail: encryptField(normalized, key),
|
|
134
|
+
emailLookup: hashLookupValue(normalized, key)
|
|
135
|
+
};
|
|
136
|
+
},
|
|
137
|
+
revealEmail(storedEmail) {
|
|
138
|
+
if (configured && storedEmail.startsWith("enc:"))
|
|
139
|
+
return configured.keyring.decrypt(storedEmail, "email");
|
|
140
|
+
if (storedEmail.startsWith("enc:") && !storedEmail.startsWith(ENCRYPTION_PREFIX))
|
|
141
|
+
throw new Error("Identified encrypted fields require KMS_ENCRYPTION_KEYRING.");
|
|
142
|
+
if (!key || !storedEmail.startsWith(ENCRYPTION_PREFIX))
|
|
143
|
+
return storedEmail;
|
|
144
|
+
return decryptField(storedEmail, key);
|
|
145
|
+
},
|
|
146
|
+
emailLookupForQuery(email) {
|
|
147
|
+
const normalized = normalizeEmail(email);
|
|
148
|
+
if (configured && enabled)
|
|
149
|
+
return configured.keyring.lookup(normalized);
|
|
150
|
+
return !key || !enabled ? normalized : hashLookupValue(normalized, key);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
function isFieldEncryptionEnabled(codec) {
|
|
155
|
+
return codec.isFieldEncryptionEnabled();
|
|
1188
156
|
}
|
|
1189
157
|
function encryptField(plaintext, key) {
|
|
1190
158
|
const iv = randomBytes(IV_LENGTH);
|
|
@@ -1212,46 +180,14 @@ function hashLookupValue(normalizedValue, key) {
|
|
|
1212
180
|
function normalizeEmail(email) {
|
|
1213
181
|
return email.trim().toLowerCase();
|
|
1214
182
|
}
|
|
1215
|
-
function protectEmail(email) {
|
|
1216
|
-
|
|
1217
|
-
const configured = resolveFieldEncryptionKeyring();
|
|
1218
|
-
if (configured && isFieldEncryptionEnabled()) {
|
|
1219
|
-
return {
|
|
1220
|
-
storedEmail: configured.encrypt(normalized, "email"),
|
|
1221
|
-
emailLookup: configured.keyring.lookup(normalized)
|
|
1222
|
-
};
|
|
1223
|
-
}
|
|
1224
|
-
const key = resolveEncryptionKey();
|
|
1225
|
-
if (!key || !isFieldEncryptionEnabled()) {
|
|
1226
|
-
return { storedEmail: normalized, emailLookup: normalized };
|
|
1227
|
-
}
|
|
1228
|
-
return {
|
|
1229
|
-
storedEmail: encryptField(normalized, key),
|
|
1230
|
-
emailLookup: hashLookupValue(normalized, key)
|
|
1231
|
-
};
|
|
183
|
+
function protectEmail(email, codec) {
|
|
184
|
+
return codec.protectEmail(email);
|
|
1232
185
|
}
|
|
1233
|
-
function revealEmail(storedEmail) {
|
|
1234
|
-
|
|
1235
|
-
if (configured && storedEmail.startsWith("enc:"))
|
|
1236
|
-
return configured.keyring.decrypt(storedEmail, "email");
|
|
1237
|
-
if (storedEmail.startsWith("enc:") && !storedEmail.startsWith(ENCRYPTION_PREFIX))
|
|
1238
|
-
throw new Error("Identified encrypted fields require KMS_ENCRYPTION_KEYRING.");
|
|
1239
|
-
const key = resolveEncryptionKey();
|
|
1240
|
-
if (!key || !storedEmail.startsWith(ENCRYPTION_PREFIX)) {
|
|
1241
|
-
return storedEmail;
|
|
1242
|
-
}
|
|
1243
|
-
return decryptField(storedEmail, key);
|
|
186
|
+
function revealEmail(storedEmail, codec) {
|
|
187
|
+
return codec.revealEmail(storedEmail);
|
|
1244
188
|
}
|
|
1245
|
-
function emailLookupForQuery(email) {
|
|
1246
|
-
|
|
1247
|
-
const configured = resolveFieldEncryptionKeyring();
|
|
1248
|
-
if (configured && isFieldEncryptionEnabled())
|
|
1249
|
-
return configured.keyring.lookup(normalized);
|
|
1250
|
-
const key = resolveEncryptionKey();
|
|
1251
|
-
if (!key || !isFieldEncryptionEnabled()) {
|
|
1252
|
-
return normalized;
|
|
1253
|
-
}
|
|
1254
|
-
return hashLookupValue(normalized, key);
|
|
189
|
+
function emailLookupForQuery(email, codec) {
|
|
190
|
+
return codec.emailLookupForQuery(email);
|
|
1255
191
|
}
|
|
1256
192
|
function createFieldEncryptionKeyring(options) {
|
|
1257
193
|
const identifier = /^[A-Za-z0-9_-]{1,64}$/;
|
|
@@ -1332,7 +268,7 @@ function createFieldEncryptionKeyring(options) {
|
|
|
1332
268
|
}
|
|
1333
269
|
});
|
|
1334
270
|
}
|
|
1335
|
-
function resolveFieldEncryptionKeyring(env
|
|
271
|
+
function resolveFieldEncryptionKeyring(env) {
|
|
1336
272
|
const raw = env.KMS_ENCRYPTION_KEYRING;
|
|
1337
273
|
if (raw === undefined)
|
|
1338
274
|
return null;
|
|
@@ -1382,43 +318,45 @@ function resolveFieldEncryptionKeyring(env = process.env) {
|
|
|
1382
318
|
}
|
|
1383
319
|
|
|
1384
320
|
// ../../src/core/crypto/mfaSecret.ts
|
|
1385
|
-
function
|
|
1386
|
-
const configured = resolveFieldEncryptionKeyring();
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
321
|
+
function createMfaSecretCodec(env) {
|
|
322
|
+
const configured = resolveFieldEncryptionKeyring(env);
|
|
323
|
+
const key = resolveEncryptionKey(env);
|
|
324
|
+
const production = isProductionEnv(env);
|
|
325
|
+
return Object.freeze({
|
|
326
|
+
protectMfaSecret(secret) {
|
|
327
|
+
if (configured)
|
|
328
|
+
return configured.encrypt(secret, "mfa");
|
|
329
|
+
if (!key)
|
|
330
|
+
throw new Error("MFA secrets require KMS_ENCRYPTION_KEY.");
|
|
331
|
+
return encryptField(secret, key);
|
|
332
|
+
},
|
|
333
|
+
revealMfaSecret(stored) {
|
|
334
|
+
if (!stored)
|
|
335
|
+
return null;
|
|
336
|
+
if (configured) {
|
|
337
|
+
if (!stored.startsWith("enc:"))
|
|
338
|
+
throw new Error("MFA secrets must be encrypted.");
|
|
339
|
+
return configured.keyring.decrypt(stored, "mfa");
|
|
340
|
+
}
|
|
341
|
+
if (stored.startsWith("enc:") && !stored.startsWith("enc:v1:"))
|
|
342
|
+
throw new Error("Identified MFA secrets require KMS_ENCRYPTION_KEYRING.");
|
|
343
|
+
if (!stored.startsWith("enc:v1:")) {
|
|
344
|
+
if (production || key)
|
|
345
|
+
throw new Error("MFA secrets must be encrypted.");
|
|
346
|
+
return stored;
|
|
347
|
+
}
|
|
348
|
+
if (!key)
|
|
349
|
+
throw new Error("MFA secrets require KMS_ENCRYPTION_KEY.");
|
|
350
|
+
return decryptField(stored, key);
|
|
1410
351
|
}
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
return
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
function protectMfaSecret(secret, codec) {
|
|
355
|
+
return codec.protectMfaSecret(secret);
|
|
356
|
+
}
|
|
357
|
+
function revealMfaSecret(stored, codec) {
|
|
358
|
+
return codec.revealMfaSecret(stored);
|
|
1418
359
|
}
|
|
1419
|
-
|
|
1420
|
-
// ../../src/core/auth/passwordLogin.ts
|
|
1421
|
-
init_dialect();
|
|
1422
360
|
|
|
1423
361
|
// ../../src/core/security/recoveryCodes.ts
|
|
1424
362
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
@@ -1453,72 +391,6 @@ function recoveryCodeMatches(code, hash) {
|
|
|
1453
391
|
// ../../src/core/security/totp.ts
|
|
1454
392
|
import { createHmac as createHmac2, randomBytes as randomBytes3 } from "crypto";
|
|
1455
393
|
|
|
1456
|
-
// ../../src/core/runtime/appKeyPrefix.ts
|
|
1457
|
-
function appKeyPrefix() {
|
|
1458
|
-
return process.env.APP_KEY_PREFIX?.trim() || "strata";
|
|
1459
|
-
}
|
|
1460
|
-
function appCookieName(kind) {
|
|
1461
|
-
return `${appKeyPrefix()}_${kind}`;
|
|
1462
|
-
}
|
|
1463
|
-
function appDevSecret(kind) {
|
|
1464
|
-
return `${appKeyPrefix()}-dev-${kind}`;
|
|
1465
|
-
}
|
|
1466
|
-
function requireConfiguredSecret(names, devKind, env = process.env) {
|
|
1467
|
-
for (const name of names) {
|
|
1468
|
-
const value = env[name]?.trim();
|
|
1469
|
-
if (value) {
|
|
1470
|
-
return value;
|
|
1471
|
-
}
|
|
1472
|
-
}
|
|
1473
|
-
if (isProductionEnv(env)) {
|
|
1474
|
-
throw new Error(`${names[0]} must be set outside development. Do not derive secrets from the app name.`);
|
|
1475
|
-
}
|
|
1476
|
-
return appDevSecret(devKind);
|
|
1477
|
-
}
|
|
1478
|
-
function namespacedRedisKey(kind) {
|
|
1479
|
-
return `${appKeyPrefix()}:${kind}`;
|
|
1480
|
-
}
|
|
1481
|
-
function smtpEhloHost() {
|
|
1482
|
-
const raw = process.env.MAIL_EHLO?.trim() || `${appKeyPrefix()}.local`;
|
|
1483
|
-
const safe = raw.replace(/[^a-zA-Z0-9.-]/g, "");
|
|
1484
|
-
return safe || "strata.local";
|
|
1485
|
-
}
|
|
1486
|
-
function siemEventType() {
|
|
1487
|
-
return process.env.SIEM_EVENT_TYPE?.trim() || `${appKeyPrefix()}.audit`;
|
|
1488
|
-
}
|
|
1489
|
-
function appUserAgent() {
|
|
1490
|
-
return process.env.APP_USER_AGENT?.trim() || appKeyPrefix();
|
|
1491
|
-
}
|
|
1492
|
-
function otelServiceName() {
|
|
1493
|
-
return process.env.OTEL_SERVICE_NAME?.trim() || `${appKeyPrefix()}-api`;
|
|
1494
|
-
}
|
|
1495
|
-
function webhookSignatureHeader() {
|
|
1496
|
-
return process.env.WEBHOOK_SIGNATURE_HEADER?.trim() || `x-${appKeyPrefix()}-signature`;
|
|
1497
|
-
}
|
|
1498
|
-
function appDisplayName() {
|
|
1499
|
-
return process.env.APP_NAME?.trim() || "Strata";
|
|
1500
|
-
}
|
|
1501
|
-
function appEnv() {
|
|
1502
|
-
return process.env.APP_ENV?.trim() || "local";
|
|
1503
|
-
}
|
|
1504
|
-
function appUrl() {
|
|
1505
|
-
return (process.env.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "");
|
|
1506
|
-
}
|
|
1507
|
-
function apiPrefix() {
|
|
1508
|
-
const raw = process.env.API_PREFIX?.trim() || "/api/v1";
|
|
1509
|
-
const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
|
|
1510
|
-
const trimmed = withSlash.replace(/\/+$/, "");
|
|
1511
|
-
return trimmed || "/api/v1";
|
|
1512
|
-
}
|
|
1513
|
-
function sdkClientClassName() {
|
|
1514
|
-
const override = process.env.APP_SDK_CLASS?.trim();
|
|
1515
|
-
if (override && /^[A-Za-z_][A-Za-z0-9_]*$/.test(override)) {
|
|
1516
|
-
return override;
|
|
1517
|
-
}
|
|
1518
|
-
const fromName = appDisplayName().replace(/[^A-Za-z0-9]/g, "");
|
|
1519
|
-
return fromName ? `${fromName}Client` : "AppClient";
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
394
|
// ../../src/core/security/timingSafeCompare.ts
|
|
1523
395
|
import { timingSafeEqual } from "crypto";
|
|
1524
396
|
function timingSafeCompareString2(left, right) {
|
|
@@ -1565,7 +437,7 @@ function generateTotpSecret(byteLength = 20) {
|
|
|
1565
437
|
return encodeBase32(randomBytes3(byteLength));
|
|
1566
438
|
}
|
|
1567
439
|
function buildOtpauthUrl(options) {
|
|
1568
|
-
const issuer = options.issuer?.trim() ||
|
|
440
|
+
const issuer = options.issuer?.trim() || "Strata";
|
|
1569
441
|
const label = `${issuer}:${options.account}`;
|
|
1570
442
|
const params = new URLSearchParams({
|
|
1571
443
|
secret: options.secret,
|
|
@@ -1623,7 +495,7 @@ function parseRecoveryHashes(raw) {
|
|
|
1623
495
|
return [];
|
|
1624
496
|
}
|
|
1625
497
|
}
|
|
1626
|
-
function completePasswordLogin(user, options
|
|
498
|
+
function completePasswordLogin(user, options, mfaSecrets) {
|
|
1627
499
|
if (!isAccountActive(user))
|
|
1628
500
|
return { ok: false, error: "account_inactive" };
|
|
1629
501
|
if (!user.mfa_enabled) {
|
|
@@ -1633,7 +505,7 @@ function completePasswordLogin(user, options = {}) {
|
|
|
1633
505
|
if (!submitted) {
|
|
1634
506
|
return { ok: false, error: "mfa_required" };
|
|
1635
507
|
}
|
|
1636
|
-
const secret = revealMfaSecret(user.mfa_secret);
|
|
508
|
+
const secret = revealMfaSecret(user.mfa_secret, mfaSecrets);
|
|
1637
509
|
if (secret && verifyTotp(secret, submitted)) {
|
|
1638
510
|
return { ok: true };
|
|
1639
511
|
}
|
|
@@ -1652,43 +524,65 @@ async function persistConsumedRecoveryHash(sql, userId, currentRaw, consumedHash
|
|
|
1652
524
|
if (typeof currentRaw !== "string" || !hashes.includes(consumedHash)) {
|
|
1653
525
|
throw new UnprocessableEntityError("mfa_invalid");
|
|
1654
526
|
}
|
|
1655
|
-
const dialect =
|
|
527
|
+
const dialect = sql.dialect;
|
|
1656
528
|
const returning = dialect.returningClause("id");
|
|
1657
|
-
const rows = await sql.
|
|
529
|
+
const rows = await sql.execute({
|
|
530
|
+
text: `UPDATE users SET mfa_recovery_codes = ${dialect.placeholder(1)} WHERE id = ${dialect.placeholder(2)} AND mfa_recovery_codes = ${dialect.placeholder(3)}${returning}`,
|
|
531
|
+
params: [JSON.stringify(hashes.filter((hash) => hash !== consumedHash)), userId, currentRaw]
|
|
532
|
+
});
|
|
1658
533
|
const header = rows[0];
|
|
1659
534
|
const affected = returning ? rows.length : typeof header === "object" && header !== null && ("affectedRows" in header) ? Number(header.affectedRows) : 0;
|
|
1660
535
|
if (affected !== 1)
|
|
1661
536
|
throw new UnprocessableEntityError("mfa_invalid");
|
|
1662
537
|
}
|
|
1663
538
|
|
|
539
|
+
// ../../src/core/auth/requireAuthCapability.ts
|
|
540
|
+
function requireAuthCapability(value, methods, mechanism) {
|
|
541
|
+
if (!value || typeof value !== "object" || methods.some((method) => typeof Reflect.get(value, method) !== "function")) {
|
|
542
|
+
throw new TypeError(`Missing ${mechanism} authentication capability: ${methods.join(", ")}.`);
|
|
543
|
+
}
|
|
544
|
+
return value;
|
|
545
|
+
}
|
|
546
|
+
|
|
1664
547
|
// ../../src/core/auth/basicAuthGuard.ts
|
|
1665
548
|
class BasicAuthGuard {
|
|
1666
|
-
|
|
1667
|
-
constructor(
|
|
1668
|
-
this.
|
|
549
|
+
options;
|
|
550
|
+
constructor(options) {
|
|
551
|
+
this.options = options;
|
|
552
|
+
requireAuthCapability(options.accounts, ["findByIdOrThrow"], "Basic account");
|
|
553
|
+
requireAuthCapability(options, ["persistRecovery"], "Basic recovery");
|
|
554
|
+
requireAuthCapability(options.mfaSecrets, ["revealMfaSecret"], "Basic MFA codec");
|
|
555
|
+
if (options.emailLookup !== undefined) {
|
|
556
|
+
requireAuthCapability(options.emailLookup, ["findByEmail"], "Basic email lookup");
|
|
557
|
+
}
|
|
558
|
+
if (options.credentials !== undefined) {
|
|
559
|
+
requireAuthCapability(options.credentials, ["verifyCredentials"], "Basic credentials");
|
|
560
|
+
}
|
|
561
|
+
if (!options.emailLookup && !options.credentials) {
|
|
562
|
+
throw new TypeError("Basic authentication requires an email lookup or credential verifier.");
|
|
563
|
+
}
|
|
1669
564
|
}
|
|
1670
565
|
async persistRecovery(record, hash) {
|
|
1671
566
|
try {
|
|
1672
|
-
await
|
|
1673
|
-
await persistConsumedRecoveryHash(getActiveDatabaseConnection(getBoundDatabaseConnection() ?? getDefaultDatabasePool()), record.id, record.mfa_recovery_codes, hash);
|
|
1674
|
-
});
|
|
1675
|
-
return true;
|
|
567
|
+
return await this.options.persistRecovery(record, hash) === true;
|
|
1676
568
|
} catch (error) {
|
|
1677
|
-
if (error instanceof
|
|
569
|
+
if (error instanceof UnprocessableEntityError2 && error.message === "mfa_invalid")
|
|
1678
570
|
return false;
|
|
1679
571
|
throw error;
|
|
1680
572
|
}
|
|
1681
573
|
}
|
|
574
|
+
authenticate(request) {
|
|
575
|
+
return authenticateProof("basic", authorizationScheme(request) === "basic", () => this.resolveUser(request));
|
|
576
|
+
}
|
|
1682
577
|
async resolve(request) {
|
|
578
|
+
return authUserFromOutcome(await this.authenticate(request));
|
|
579
|
+
}
|
|
580
|
+
async resolveUser(request) {
|
|
1683
581
|
const credentials = readBasicCredentials(request);
|
|
1684
582
|
if (!credentials) {
|
|
1685
583
|
return null;
|
|
1686
584
|
}
|
|
1687
|
-
const
|
|
1688
|
-
if (!directory) {
|
|
1689
|
-
return null;
|
|
1690
|
-
}
|
|
1691
|
-
const record = typeof directory.findByEmail === "function" ? await directory.findByEmail(credentials.username) : null;
|
|
585
|
+
const record = this.options.emailLookup ? await this.options.emailLookup.findByEmail(credentials.username) : null;
|
|
1692
586
|
if (record && !isAccountActive(record))
|
|
1693
587
|
return null;
|
|
1694
588
|
if (record?.password) {
|
|
@@ -1697,7 +591,7 @@ class BasicAuthGuard {
|
|
|
1697
591
|
}
|
|
1698
592
|
const mfa = completePasswordLogin(record, {
|
|
1699
593
|
mfaCode: request.headers.get("x-mfa-code")
|
|
1700
|
-
});
|
|
594
|
+
}, this.options.mfaSecrets);
|
|
1701
595
|
if (!mfa.ok) {
|
|
1702
596
|
return null;
|
|
1703
597
|
}
|
|
@@ -1712,22 +606,23 @@ class BasicAuthGuard {
|
|
|
1712
606
|
emailVerifiedAt: record.email_verified_at ?? null
|
|
1713
607
|
};
|
|
1714
608
|
}
|
|
1715
|
-
if (
|
|
1716
|
-
const user = await
|
|
609
|
+
if (this.options.credentials) {
|
|
610
|
+
const user = await this.options.credentials.verifyCredentials(credentials.username, credentials.password);
|
|
1717
611
|
if (!user || !isAuthUserActive(user)) {
|
|
1718
612
|
return null;
|
|
1719
613
|
}
|
|
1720
|
-
|
|
614
|
+
const userId = typeof user.id === "number" ? user.id : typeof user.id === "string" ? Number(user.id) : NaN;
|
|
615
|
+
if (!Number.isSafeInteger(userId) || userId <= 0)
|
|
616
|
+
return null;
|
|
617
|
+
let record = this.options.emailLookup ? await this.options.emailLookup.findByEmail(credentials.username) : null;
|
|
1721
618
|
if (!record) {
|
|
1722
|
-
|
|
1723
|
-
record = await directory.findByIdOrThrow(Number(user.id));
|
|
1724
|
-
} catch {
|
|
1725
|
-
return null;
|
|
1726
|
-
}
|
|
619
|
+
record = await this.options.accounts.findByIdOrThrow(userId);
|
|
1727
620
|
}
|
|
621
|
+
if (record.id !== userId)
|
|
622
|
+
return null;
|
|
1728
623
|
const mfa = completePasswordLogin(record, {
|
|
1729
624
|
mfaCode: request.headers.get("x-mfa-code")
|
|
1730
|
-
});
|
|
625
|
+
}, this.options.mfaSecrets);
|
|
1731
626
|
if (!mfa.ok) {
|
|
1732
627
|
return null;
|
|
1733
628
|
}
|