@getstrata/core 0.5.56 → 0.5.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/dist/{domain/abilities.d.ts → core/auth/abilityCatalog.d.ts} +9 -1
  3. package/dist/core/auth/accessControl.d.ts +1 -1
  4. package/dist/core/auth/membershipContext.d.ts +6 -4
  5. package/dist/core/auth/membershipService.d.ts +5 -6
  6. package/dist/core/contracts/authUserDirectory.d.ts +11 -0
  7. package/dist/core/contracts/membership.d.ts +20 -0
  8. package/dist/core/http/clientIp.d.ts +3 -0
  9. package/dist/core/jobs/dispatchWebhookJob.d.ts +2 -0
  10. package/dist/core/tenant/tenancyConfig.d.ts +5 -0
  11. package/dist/core/tenant/tenantMiddleware.d.ts +1 -1
  12. package/dist/entries/auth/membershipMiddleware.js +21 -161
  13. package/dist/entries/auth/membershipScope.js +20 -160
  14. package/dist/entries/auth/membershipService.js +21 -161
  15. package/dist/entries/auth/scimAuthMiddleware.js +22 -4
  16. package/dist/entries/auth/sessionGuard.js +12 -258
  17. package/dist/entries/http/clientIp.js +19 -0
  18. package/dist/entries/http/csrfMiddleware.js +2 -1
  19. package/dist/entries/http/csrfToken.js +2 -1
  20. package/dist/entries/http/loginThrottleMiddleware.js +18 -1
  21. package/dist/entries/http/memoryThrottleMiddleware.js +16 -1
  22. package/dist/entries/http/response.js +28 -297
  23. package/dist/entries/http/scimThrottleMiddleware.js +40 -1
  24. package/dist/entries/http/throttleMiddleware.js +18 -1
  25. package/dist/entries/http/webErrorResponse.js +28 -297
  26. package/dist/entries/jobs/dispatchWebhookJob.js +111 -5
  27. package/dist/entries/logging/requestLoggingMiddleware.js +16 -1
  28. package/dist/entries/security/scimTenantTokens.js +1 -4
  29. package/dist/entries/tenant/tenancyConfig.js +12 -0
  30. package/dist/entries/tenant/tenantDatabaseScope.js +11 -0
  31. package/dist/entries/view.js +26 -295
  32. package/dist/framework/public-api.d.ts +4 -1
  33. package/dist/index.js +2186 -2243
  34. package/package.json +12 -2
  35. package/dist/config/database.d.ts +0 -10
  36. package/dist/db/connection/createConnection.d.ts +0 -6
  37. package/dist/db/connection/index.d.ts +0 -11
  38. package/dist/domain/auth.d.ts +0 -4
  39. package/dist/domain/scim.d.ts +0 -9
  40. package/dist/modules/organization/memberRepository.d.ts +0 -14
  41. package/dist/modules/organization/memberTypes.d.ts +0 -9
  42. package/dist/modules/user/apiTokenRepository.d.ts +0 -8
  43. package/dist/modules/user/apiTokenTable.d.ts +0 -3
  44. package/dist/modules/user/authService.d.ts +0 -23
  45. package/dist/modules/user/notificationRepository.d.ts +0 -6
  46. package/dist/modules/user/notificationService.d.ts +0 -25
  47. package/dist/modules/user/notificationTable.d.ts +0 -3
  48. package/dist/modules/user/notificationTypes.d.ts +0 -12
  49. package/dist/modules/user/oauthIdentityRepository.d.ts +0 -9
  50. package/dist/modules/user/provider.d.ts +0 -11
  51. package/dist/modules/user/repository.d.ts +0 -13
  52. package/dist/modules/user/table.d.ts +0 -3
  53. package/dist/modules/user/tokenService.d.ts +0 -29
  54. package/dist/modules/user/types.d.ts +0 -46
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // ../../src/core/http/webErrorResponse.ts
3
- import { HttpError as HttpError2, UnauthorizedError as UnauthorizedError2, ValidationError } from "@getstrata/core/errors/http";
3
+ import { HttpError as HttpError2, UnauthorizedError, ValidationError } from "@getstrata/core/errors/http";
4
4
 
5
5
  // ../../src/config/frontend.ts
6
6
  function readFrontendMode() {
@@ -310,298 +310,14 @@ function isHtmxRequest(request) {
310
310
  import { currentAuthUser } from "@getstrata/core/auth/authContext";
311
311
  import { currentRequestMeta as currentRequestMeta2 } from "@getstrata/core/http/requestMetaContext";
312
312
 
313
- // ../../src/bootstrap/config.ts
314
- import {
315
- CORE_AUTH_TOKEN,
316
- CORE_CACHE_TOKEN,
317
- CORE_CONFIG_TOKEN,
318
- CORE_EVENT_BUS_TOKEN,
319
- CORE_POLICY_GATE_TOKEN,
320
- CORE_QUEUE_TOKEN,
321
- CORE_TOKEN_SERVICE_TOKEN
322
- } from "@getstrata/core/contracts/serviceTokens";
323
- var DEFAULT_QUEUE_DRIVER = "sync";
324
-
325
- // ../../src/modules/user/provider.ts
326
- import { OidcProvider } from "@getstrata/core/auth/oauth/oidcProvider";
327
- import { GitHubOAuthProvider, MockOAuthProvider } from "@getstrata/core/auth/oauth/providers";
328
- import { SamlProvider } from "@getstrata/core/auth/oauth/samlProvider";
329
-
330
- // ../../src/config/features.ts
331
- function readFeatureFlags() {
332
- return {
333
- webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
334
- fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
335
- auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
336
- oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
337
- samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
338
- scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
339
- billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
340
- siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
341
- publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
342
- emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
343
- mfa: (process.env.FEATURE_MFA ?? "false") === "true"
344
- };
345
- }
346
- var featureFlags = readFeatureFlags();
347
- function isFeatureEnabled(feature) {
348
- return readFeatureFlags()[feature];
349
- }
350
-
351
- // ../../src/modules/user/apiTokenRepository.ts
352
- import { BaseRepository } from "@getstrata/core/database/baseRepository";
353
-
354
- // ../../src/config/database.ts
355
- function readInteger(name, fallback) {
356
- const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
357
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
358
- }
359
- var databaseConfig = {
360
- url: process.env.DATABASE_URL ?? "",
361
- poolMax: readInteger("DB_POOL_MAX", 10),
362
- idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
363
- maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
364
- connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
365
- };
366
-
367
- // ../../src/core/runtime/asyncContextStore.ts
368
- import { AsyncLocalStorage } from "async_hooks";
369
- function createAsyncContextStore(key) {
370
- const symbol = Symbol.for(key);
371
- const globalRecord = globalThis;
372
- const existing = globalRecord[symbol];
373
- if (existing) {
374
- return existing;
375
- }
376
- const store = new AsyncLocalStorage;
377
- globalRecord[symbol] = store;
378
- return store;
379
- }
380
-
381
- // ../../src/core/database/connectionContext.ts
382
- var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
383
- function runWithDatabaseConnection(connection, callback) {
384
- return activeConnection.run(connection, callback);
385
- }
386
- function getActiveDatabaseConnection(fallback) {
387
- return activeConnection.getStore() ?? fallback;
388
- }
389
- function hasActiveDatabaseConnection() {
390
- return activeConnection.getStore() !== undefined;
391
- }
392
-
393
- // ../../src/core/database/queryProxy.ts
394
- var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
395
- function createDatabaseQueryProxy(pool) {
396
- function resolveDatabase() {
397
- return getActiveDatabaseConnection(pool);
398
- }
399
- function resolveDatabaseForProperty(property) {
400
- if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
401
- return pool;
402
- }
403
- return resolveDatabase();
404
- }
405
- return new Proxy(function database() {}, {
406
- apply(_target, _thisArg, args) {
407
- return resolveDatabase()(...args);
408
- },
409
- get(_target, property) {
410
- const connection = resolveDatabaseForProperty(property);
411
- const value = connection[property];
412
- return typeof value === "function" ? value.bind(connection) : value;
413
- }
414
- });
415
- }
416
-
417
- // ../../src/core/database/defaultConnection.ts
418
- var defaultPool = {
419
- connection: null
420
- };
421
- var defaultQuery = {
422
- connection: null
423
- };
424
- function registerDefaultDatabasePool(connection) {
425
- defaultPool.connection = connection;
426
- defaultQuery.connection = createDatabaseQueryProxy(connection);
427
- }
428
- function getDefaultDatabaseQuery() {
429
- if (!defaultQuery.connection) {
430
- throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
431
- }
432
- return defaultQuery.connection;
433
- }
434
-
435
- // ../../src/db/connection/createConnection.ts
436
- var {SQL } = globalThis.Bun;
437
- function createDatabaseConnection(config) {
438
- if (!config.url) {
439
- throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
440
- }
441
- return new SQL({
442
- url: config.url,
443
- max: config.poolMax,
444
- idleTimeout: config.idleTimeoutSeconds,
445
- maxLifetime: config.maxLifetimeSeconds,
446
- connectionTimeout: config.connectionTimeoutSeconds
447
- });
448
- }
449
-
450
- // ../../src/db/connection/index.ts
451
- var connectionHolder = {
452
- connection: null
453
- };
454
- function getDatabase() {
455
- if (!connectionHolder.connection) {
456
- connectionHolder.connection = createDatabaseConnection(databaseConfig);
457
- registerDefaultDatabasePool(connectionHolder.connection);
458
- }
459
- return connectionHolder.connection;
460
- }
461
- function getDb() {
462
- getDatabase();
463
- return getDefaultDatabaseQuery();
464
- }
465
- var db = new Proxy(function database() {}, {
466
- apply(_target, _thisArg, args) {
467
- return getDb()(...args);
468
- },
469
- get(_target, property) {
470
- const connection = getDb();
471
- const value = connection[property];
472
- return typeof value === "function" ? value.bind(connection) : value;
473
- }
474
- });
475
- var connection_default = db;
476
-
477
- // ../../src/modules/user/apiTokenTable.ts
478
- import { defineTable } from "@getstrata/core/database/table";
479
- var apiTokenTable = defineTable({
480
- name: "api_token",
481
- primaryKey: "id",
482
- columns: [
483
- "id",
484
- "user_id",
485
- "name",
486
- "token_hash",
487
- "abilities",
488
- "last_used_at",
489
- "expires_at",
490
- "created_at"
491
- ],
492
- defaultOrderBy: { column: "id", direction: "ASC" }
493
- });
494
-
495
- // ../../src/modules/user/authService.ts
496
- import { verifyPassword } from "@getstrata/core/auth/password";
497
- import { revealMfaSecret } from "@getstrata/core/crypto/mfaSecret";
498
- import { UnauthorizedError } from "@getstrata/core/errors/http";
499
- import { logSecurityEvent } from "@getstrata/core/security/securityEvents";
500
- import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
501
- import { verifyTotp } from "@getstrata/core/security/totp";
502
- import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
503
-
504
- // ../../src/domain/abilities.ts
505
- var MEMBER_ABILITIES = [
506
- "organizations:read",
507
- "projects:read",
508
- "projects:create",
509
- "tasks:read",
510
- "tasks:create",
511
- "comments:read",
512
- "comments:create",
513
- "attachments:read",
514
- "attachments:create",
515
- "auth:tokens:read",
516
- "auth:tokens:write"
517
- ];
518
- var ADMIN_ABILITIES = [
519
- ...MEMBER_ABILITIES,
520
- "organizations:create",
521
- "organizations:update",
522
- "organizations:delete",
523
- "projects:update",
524
- "projects:delete",
525
- "tasks:update",
526
- "tasks:delete",
527
- "comments:update",
528
- "comments:delete",
529
- "attachments:delete",
530
- "webhooks:read",
531
- "webhooks:write",
532
- "audit:read"
533
- ];
534
- var PLATFORM_ADMIN_ABILITIES = ["*"];
535
- function resolveAbilitiesForRole(role) {
536
- if (role === "admin") {
537
- return [...PLATFORM_ADMIN_ABILITIES];
538
- }
539
- return [...MEMBER_ABILITIES];
540
- }
541
-
542
- // ../../src/modules/user/notificationRepository.ts
543
- import { BaseRepository as BaseRepository2 } from "@getstrata/core/database/baseRepository";
544
-
545
- // ../../src/modules/user/notificationTable.ts
546
- import { defineTable as defineTable2 } from "@getstrata/core/database/table";
547
- var notificationTable = defineTable2({
548
- name: "notification",
549
- primaryKey: "id",
550
- columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
551
- defaultOrderBy: { column: "created_at", direction: "DESC" }
552
- });
553
-
554
- // ../../src/modules/user/notificationService.ts
555
- import { NotFoundError } from "@getstrata/core/errors/http";
556
-
557
- // ../../src/modules/user/oauthIdentityRepository.ts
558
- import { BaseRepository as BaseRepository3 } from "@getstrata/core/database/baseRepository";
559
- import { defineTable as defineTable3 } from "@getstrata/core/database/table";
560
- var oauthIdentityTable = defineTable3({
561
- name: "oauth_identity",
562
- primaryKey: "id",
563
- columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
564
- });
565
-
566
- // ../../src/modules/user/repository.ts
567
- import {
568
- emailLookupForQuery,
569
- protectEmail,
570
- revealEmail
571
- } from "@getstrata/core/crypto/fieldEncryption";
572
- import { revealMfaSecret as revealMfaSecret2 } from "@getstrata/core/crypto/mfaSecret";
573
- import { BaseRepository as BaseRepository4 } from "@getstrata/core/database/baseRepository";
574
- import { currentTenantId as currentTenantId2 } from "@getstrata/core/tenant/tenantContext";
575
-
576
- // ../../src/modules/user/table.ts
577
- import { defineTable as defineTable4 } from "@getstrata/core/database/table";
578
- var userTable = defineTable4({
579
- name: "users",
580
- primaryKey: "id",
581
- columns: [
582
- "id",
583
- "name",
584
- "email",
585
- "email_lookup",
586
- "role",
587
- "tenant_id",
588
- "password_hash",
589
- "email_verified_at",
590
- "mfa_secret",
591
- "mfa_enabled",
592
- "created_at",
593
- "updated_at"
594
- ],
595
- defaultOrderBy: { column: "id", direction: "ASC" }
596
- });
597
-
598
- // ../../src/modules/user/tokenService.ts
599
- import { hashApiToken } from "@getstrata/core/auth/tokenHash";
600
- import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core/errors/http";
601
- import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
602
-
603
- // ../../src/modules/user/provider.ts
604
- var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
313
+ // ../../src/core/contracts/serviceTokens.ts
314
+ var CORE_CONFIG_TOKEN = "core.config";
315
+ var CORE_CACHE_TOKEN = "core.cache";
316
+ var CORE_QUEUE_TOKEN = "core.queue";
317
+ var CORE_EVENT_BUS_TOKEN = "core.eventBus";
318
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
319
+ var CORE_AUTH_TOKEN = "core.auth";
320
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
605
321
 
606
322
  // ../../src/core/http/csrfToken.ts
607
323
  import { timingSafeEqual } from "crypto";
@@ -634,6 +350,20 @@ function readBunRequestCookie(request, name) {
634
350
  return request.cookies.get(name) ?? readRequestCookie(request, name);
635
351
  }
636
352
 
353
+ // ../../src/core/runtime/asyncContextStore.ts
354
+ import { AsyncLocalStorage } from "async_hooks";
355
+ function createAsyncContextStore(key) {
356
+ const symbol = Symbol.for(key);
357
+ const globalRecord = globalThis;
358
+ const existing = globalRecord[symbol];
359
+ if (existing) {
360
+ return existing;
361
+ }
362
+ const store = new AsyncLocalStorage;
363
+ globalRecord[symbol] = store;
364
+ return store;
365
+ }
366
+
637
367
  // ../../src/core/http/requestMetaContext.ts
638
368
  var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
639
369
  function runWithRequestMeta(meta, callback) {
@@ -665,9 +395,10 @@ function tokensMatch(left, right) {
665
395
  }
666
396
  function createCsrfTokenCookie() {
667
397
  const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
398
+ const secure = process.env.APP_ENV === "production" ? "; Secure" : "";
668
399
  return {
669
400
  token,
670
- cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
401
+ cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}${secure}`
671
402
  };
672
403
  }
673
404
  function resolveCsrfToken(request) {
@@ -835,7 +566,7 @@ async function resolveWebLayoutData(container, request) {
835
566
  if (!Number.isInteger(userId) || userId <= 0) {
836
567
  return { authUser: null, csrfToken, flash };
837
568
  }
838
- if (!container.has(tokenServiceToken)) {
569
+ if (!container.has(CORE_TOKEN_SERVICE_TOKEN)) {
839
570
  return {
840
571
  authUser: {
841
572
  id: userId,
@@ -846,7 +577,7 @@ async function resolveWebLayoutData(container, request) {
846
577
  flash
847
578
  };
848
579
  }
849
- const tokenService = container.resolve(tokenServiceToken);
580
+ const tokenService = container.resolve(CORE_TOKEN_SERVICE_TOKEN);
850
581
  try {
851
582
  const user = await tokenService.findByIdOrThrow(userId);
852
583
  return {
@@ -907,7 +638,7 @@ function webErrorResponse(error, request) {
907
638
  return null;
908
639
  }
909
640
  const mappedError = error instanceof HttpError2 ? error : mapDatabaseError(error);
910
- if (mappedError instanceof UnauthorizedError2) {
641
+ if (mappedError instanceof UnauthorizedError) {
911
642
  const redirectTarget = encodeURIComponent(new URL(request.url).pathname);
912
643
  return Response.redirect(`/login?redirect=${redirectTarget}`, 302);
913
644
  }
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  // ../../src/core/jobs/dispatchWebhookJob.ts
3
3
  import { createHmac } from "crypto";
4
- import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
4
+ import { repositoryConnection as db2 } from "@getstrata/core/database/repositoryConnection";
5
5
 
6
6
  // ../../src/config/app.ts
7
7
  var appConfig = {
@@ -169,12 +169,118 @@ async function safeFetch(input, init = {}, options = {}) {
169
169
  }
170
170
  }
171
171
 
172
+ // ../../src/core/tenant/resolveTenant.ts
173
+ import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
174
+
175
+ // ../../src/core/tenant/tenancyConfig.ts
176
+ function readTenancyDriver(env = process.env) {
177
+ return env.TENANCY_DRIVER === "none" ? "none" : "rls";
178
+ }
179
+ function isTenancyEnabled(env = process.env) {
180
+ return readTenancyDriver(env) !== "none";
181
+ }
182
+
183
+ // ../../src/core/tenant/resolveTenant.ts
184
+ async function resolveTenant(tenantId) {
185
+ if (!isTenancyEnabled()) {
186
+ return {
187
+ id: tenantId,
188
+ slug: "default",
189
+ plan: "free",
190
+ region: "eu"
191
+ };
192
+ }
193
+ const rows = await db`
194
+ SELECT id, slug, plan, region
195
+ FROM tenant
196
+ WHERE id = ${tenantId}
197
+ LIMIT 1
198
+ `;
199
+ const row = rows[0];
200
+ return row ? { id: row.id, slug: row.slug, plan: row.plan, region: row.region ?? "eu" } : null;
201
+ }
202
+
203
+ // ../../src/core/tenant/tenantDatabaseScope.ts
204
+ import { getDefaultDatabasePool } from "@getstrata/core/database/defaultConnection";
205
+
206
+ // ../../src/core/runtime/asyncContextStore.ts
207
+ import { AsyncLocalStorage } from "async_hooks";
208
+ function createAsyncContextStore(key) {
209
+ const symbol = Symbol.for(key);
210
+ const globalRecord = globalThis;
211
+ const existing = globalRecord[symbol];
212
+ if (existing) {
213
+ return existing;
214
+ }
215
+ const store = new AsyncLocalStorage;
216
+ globalRecord[symbol] = store;
217
+ return store;
218
+ }
219
+
220
+ // ../../src/core/database/connectionContext.ts
221
+ var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
222
+ function runWithDatabaseConnection(connection, callback) {
223
+ return activeConnection.run(connection, callback);
224
+ }
225
+ function getActiveDatabaseConnection(fallback) {
226
+ return activeConnection.getStore() ?? fallback;
227
+ }
228
+ function hasActiveDatabaseConnection() {
229
+ return activeConnection.getStore() !== undefined;
230
+ }
231
+
232
+ // ../../src/core/tenant/tenantContext.ts
233
+ var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
234
+ function runWithTenant(tenant, callback) {
235
+ return tenantContext.run(tenant, callback);
236
+ }
237
+ function currentTenant() {
238
+ return tenantContext.getStore() ?? null;
239
+ }
240
+
241
+ // ../../src/core/tenant/tenantDatabaseScope.ts
242
+ async function applyTenantContextToTransaction(transaction, tenantId) {
243
+ await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
244
+ await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
245
+ }
246
+ async function runWithTenantDatabase(tenant, callback) {
247
+ if (!isTenancyEnabled()) {
248
+ return await runWithTenant(tenant, callback);
249
+ }
250
+ if (hasActiveDatabaseConnection()) {
251
+ const activeConnection2 = getActiveDatabaseConnection(getDefaultDatabasePool());
252
+ await applyTenantContextToTransaction(activeConnection2, tenant.id);
253
+ return await runWithTenant(tenant, callback);
254
+ }
255
+ return await getDefaultDatabasePool().begin(async (transaction) => {
256
+ await applyTenantContextToTransaction(transaction, tenant.id);
257
+ return await runWithDatabaseConnection(transaction, async () => {
258
+ return await runWithTenant(tenant, callback);
259
+ });
260
+ });
261
+ }
262
+ function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
263
+ return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
264
+ }
265
+
172
266
  // ../../src/core/jobs/dispatchWebhookJob.ts
173
267
  class DispatchWebhookJob extends Job {
174
268
  maxAttempts = 3;
175
269
  backoffMs = 2000;
176
270
  async handle(payload) {
177
- const rows = await db`
271
+ const tenant = await resolveTenant(payload.tenantId) ?? {
272
+ id: payload.tenantId,
273
+ slug: "job",
274
+ plan: "free",
275
+ region: "eu"
276
+ };
277
+ const failure = await runWithTenantDatabase(tenant, async () => await this.deliver(payload));
278
+ if (failure) {
279
+ throw failure;
280
+ }
281
+ }
282
+ async deliver(payload) {
283
+ const rows = await db2`
178
284
  SELECT id, url, secret
179
285
  FROM webhook
180
286
  WHERE id = ${payload.webhookId} AND active = TRUE
@@ -204,7 +310,7 @@ class DispatchWebhookJob extends Job {
204
310
  }
205
311
  } catch (error) {
206
312
  errorMessage = error instanceof Error ? error.message : String(error);
207
- await db`
313
+ await db2`
208
314
  INSERT INTO webhook_delivery (webhook_id, event, payload, response_status, error)
209
315
  VALUES (
210
316
  ${webhook.id},
@@ -214,9 +320,9 @@ class DispatchWebhookJob extends Job {
214
320
  ${errorMessage}
215
321
  )
216
322
  `;
217
- throw error instanceof Error ? error : new Error(errorMessage);
323
+ return error instanceof Error ? error : new Error(errorMessage);
218
324
  }
219
- await db`
325
+ await db2`
220
326
  INSERT INTO webhook_delivery (webhook_id, event, payload, response_status)
221
327
  VALUES (
222
328
  ${webhook.id},
@@ -2,6 +2,21 @@
2
2
  // ../../src/core/logging/requestLoggingMiddleware.ts
3
3
  import { runWithRequestMeta } from "@getstrata/core/http/requestMetaContext";
4
4
 
5
+ // ../../src/core/http/clientIp.ts
6
+ function trustForwardedFor(env = process.env) {
7
+ return (env.TRUST_FORWARDED_FOR ?? "false") === "true";
8
+ }
9
+ function readClientIp(request, env = process.env) {
10
+ if (!trustForwardedFor(env)) {
11
+ return;
12
+ }
13
+ const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
14
+ if (forwarded) {
15
+ return forwarded;
16
+ }
17
+ return request.headers.get("x-real-ip")?.trim() || undefined;
18
+ }
19
+
5
20
  // ../../src/core/logging/logger.ts
6
21
  class Logger {
7
22
  channel;
@@ -42,7 +57,7 @@ var appLogger = new Logger("app");
42
57
  function createRequestLoggingMiddleware() {
43
58
  return async (request, next) => {
44
59
  return await runWithRequestMeta({
45
- ipAddress: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip"),
60
+ ipAddress: readClientIp(request) ?? null,
46
61
  userAgent: request.headers.get("user-agent"),
47
62
  request
48
63
  }, async () => {
@@ -1,7 +1,4 @@
1
1
  // @bun
2
- // ../../src/domain/scim.ts
3
- var TEST_SCIM_BEARER_TOKEN = "workhub-scim-test-token";
4
-
5
2
  // ../../src/core/security/timingSafeCompare.ts
6
3
  import { timingSafeEqual } from "crypto";
7
4
  function timingSafeCompareString(left, right) {
@@ -39,7 +36,7 @@ function resolveScimTenantFromToken(token) {
39
36
  return tenantId;
40
37
  }
41
38
  }
42
- const fallbackToken = process.env.SCIM_BEARER_TOKEN ?? TEST_SCIM_BEARER_TOKEN;
39
+ const fallbackToken = process.env.SCIM_BEARER_TOKEN ?? "";
43
40
  if (timingSafeCompareString(token, fallbackToken)) {
44
41
  return 1;
45
42
  }
@@ -0,0 +1,12 @@
1
+ // @bun
2
+ // ../../src/core/tenant/tenancyConfig.ts
3
+ function readTenancyDriver(env = process.env) {
4
+ return env.TENANCY_DRIVER === "none" ? "none" : "rls";
5
+ }
6
+ function isTenancyEnabled(env = process.env) {
7
+ return readTenancyDriver(env) !== "none";
8
+ }
9
+ export {
10
+ isTenancyEnabled,
11
+ readTenancyDriver
12
+ };
@@ -28,6 +28,14 @@ function hasActiveDatabaseConnection() {
28
28
  return activeConnection.getStore() !== undefined;
29
29
  }
30
30
 
31
+ // ../../src/core/tenant/tenancyConfig.ts
32
+ function readTenancyDriver(env = process.env) {
33
+ return env.TENANCY_DRIVER === "none" ? "none" : "rls";
34
+ }
35
+ function isTenancyEnabled(env = process.env) {
36
+ return readTenancyDriver(env) !== "none";
37
+ }
38
+
31
39
  // ../../src/core/tenant/tenantContext.ts
32
40
  var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
33
41
  function runWithTenant(tenant, callback) {
@@ -43,6 +51,9 @@ async function applyTenantContextToTransaction(transaction, tenantId) {
43
51
  await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
44
52
  }
45
53
  async function runWithTenantDatabase(tenant, callback) {
54
+ if (!isTenancyEnabled()) {
55
+ return await runWithTenant(tenant, callback);
56
+ }
46
57
  if (hasActiveDatabaseConnection()) {
47
58
  const activeConnection2 = getActiveDatabaseConnection(getDefaultDatabasePool());
48
59
  await applyTenantContextToTransaction(activeConnection2, tenant.id);