@getstrata/core 0.5.13 → 0.5.15

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 (46) hide show
  1. package/README.md +16 -6
  2. package/dist/bootstrap/contracts.d.ts +2 -0
  3. package/dist/bootstrap/httpKernel.d.ts +1 -2
  4. package/dist/core/admin/registry.d.ts +1 -0
  5. package/dist/core/auth/membershipService.d.ts +5 -1
  6. package/dist/core/database/baseRepository.d.ts +6 -1
  7. package/dist/core/database/connectionContext.d.ts +2 -1
  8. package/dist/core/database/defaultConnection.d.ts +6 -0
  9. package/dist/core/database/queryProxy.d.ts +3 -0
  10. package/dist/core/database/repositoryConnection.d.ts +3 -3
  11. package/dist/core/jobs/dispatchWebhookJob.d.ts +0 -1
  12. package/dist/core/security/safeFetch.d.ts +2 -0
  13. package/dist/core/security/safeUrl.d.ts +16 -1
  14. package/dist/core/storage/storage.d.ts +6 -3
  15. package/dist/core/tenant/tenantDatabaseScope.d.ts +2 -1
  16. package/dist/db/connection/index.d.ts +1 -1
  17. package/dist/entries/auth/accessControl.js +1 -113
  18. package/dist/entries/auth/authContext.js +1 -15
  19. package/dist/entries/auth/guard.js +1 -3044
  20. package/dist/entries/auth/membershipContext.js +1 -276
  21. package/dist/entries/auth/membershipScope.js +1 -390
  22. package/dist/entries/auth/membershipService.js +1 -480
  23. package/dist/entries/auth/policy.js +1 -134
  24. package/dist/entries/database.js +1 -2398
  25. package/dist/entries/http/csrfToken.js +0 -6
  26. package/dist/entries/http/middleware.js +1 -68
  27. package/dist/entries/http/requestMetaContext.js +1 -18
  28. package/dist/entries/http/webErrorResponse.js +94 -563
  29. package/dist/entries/http/webFormRequest.js +0 -131
  30. package/dist/entries/http.js +1 -4091
  31. package/dist/entries/jobs/dispatchWebhookJob.js +109 -102
  32. package/dist/entries/queue/createAppQueue.js +111 -631
  33. package/dist/entries/queue/jobRunner.js +0 -3
  34. package/dist/entries/queue/publicQueue.js +45 -546
  35. package/dist/entries/queue/queueMetrics.js +111 -631
  36. package/dist/entries/security/safeUrl.js +29 -0
  37. package/dist/entries/security/securityEvents.js +1 -41
  38. package/dist/entries/storage/storage.js +14 -4
  39. package/dist/entries/tenant/tenantContext.js +1 -30
  40. package/dist/entries/tenant/tenantMiddleware.js +1 -312
  41. package/dist/entries/tracing/traceContext.js +1 -15
  42. package/dist/entries/view.js +94 -563
  43. package/dist/framework/public-api.d.ts +36 -4
  44. package/dist/index.js +2270 -1666
  45. package/dist/modules/user/repository.d.ts +1 -0
  46. package/package.json +6 -5
@@ -1,4 +1,7 @@
1
1
  // @bun
2
+ // ../../src/core/security/safeUrl.ts
3
+ import { lookup as dnsLookupImpl } from "dns/promises";
4
+
2
5
  // ../../src/core/errors/http.ts
3
6
  class HttpError extends Error {
4
7
  status;
@@ -66,6 +69,7 @@ class PreconditionFailedError extends HttpError {
66
69
  }
67
70
 
68
71
  // ../../src/core/security/safeUrl.ts
72
+ var dnsLookup = dnsLookupImpl;
69
73
  var BLOCKED_HOSTNAMES = new Set([
70
74
  "localhost",
71
75
  "127.0.0.1",
@@ -137,7 +141,32 @@ function assertSafeOutboundUrl(rawUrl, options = {}) {
137
141
  }
138
142
  return parsed;
139
143
  }
144
+ function isBlockedIpAddress(address) {
145
+ return isBlockedHostname(address.trim().toLowerCase());
146
+ }
147
+ async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
148
+ const parsed = assertSafeOutboundUrl(rawUrl, options);
149
+ if (options.resolveDns === false) {
150
+ return parsed;
151
+ }
152
+ const hostname = parsed.hostname.trim().toLowerCase();
153
+ const results = await dnsLookup(hostname, { all: true, verbatim: true });
154
+ if (results.some((result) => isBlockedIpAddress(result.address))) {
155
+ throw new BadRequestError("Webhook URL targets a blocked host.");
156
+ }
157
+ return parsed;
158
+ }
159
+ function setDnsLookupForTests(lookupFn) {
160
+ dnsLookup = lookupFn;
161
+ }
162
+ function resetDnsLookupForTests() {
163
+ dnsLookup = dnsLookupImpl;
164
+ }
140
165
  export {
166
+ setDnsLookupForTests,
167
+ resetDnsLookupForTests,
168
+ isBlockedIpAddress,
141
169
  isBlockedHostname,
170
+ assertSafeOutboundUrlResolved,
142
171
  assertSafeOutboundUrl
143
172
  };
@@ -1,41 +1 @@
1
- // @bun
2
- // ../../src/core/auth/authContext.ts
3
- import { AsyncLocalStorage } from "async_hooks";
4
- var authContext = new AsyncLocalStorage;
5
- function runWithAuthUser(user, callback) {
6
- return authContext.run(user, callback);
7
- }
8
- function currentAuthUser() {
9
- return authContext.getStore() ?? null;
10
- }
11
-
12
- // ../../src/core/http/requestMetaContext.ts
13
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
14
- var requestMetaContext = new AsyncLocalStorage2;
15
- function runWithRequestMeta(meta, callback) {
16
- return requestMetaContext.run(meta, callback);
17
- }
18
- function currentRequestMeta() {
19
- return requestMetaContext.getStore() ?? {
20
- ipAddress: null,
21
- userAgent: null
22
- };
23
- }
24
-
25
- // ../../src/core/security/securityEvents.ts
26
- function logSecurityEvent(event, details = {}) {
27
- const meta = currentRequestMeta();
28
- const user = currentAuthUser();
29
- console.log(JSON.stringify({
30
- level: "security",
31
- event,
32
- timestamp: new Date().toISOString(),
33
- ip_address: meta.ipAddress ?? null,
34
- user_agent: meta.userAgent ?? null,
35
- user_id: user?.id ?? null,
36
- ...details
37
- }));
38
- }
39
- export {
40
- logSecurityEvent
41
- };
1
+ export * from "../../index.js";
@@ -9,8 +9,11 @@ class LocalStorageDriver {
9
9
  constructor(rootDirectory) {
10
10
  this.rootDirectory = rootDirectory;
11
11
  }
12
+ resolveRootDirectory() {
13
+ return this.rootDirectory ?? process.env.STORAGE_PATH ?? "storage";
14
+ }
12
15
  resolvePath(path) {
13
- return join(this.rootDirectory, path.replace(/^\/+/, ""));
16
+ return join(this.resolveRootDirectory(), path.replace(/^\/+/, ""));
14
17
  }
15
18
  async put(path, contents) {
16
19
  const absolutePath = this.resolvePath(path);
@@ -106,15 +109,22 @@ function createStorageDriver() {
106
109
  if (driver === "s3") {
107
110
  return new S3StorageDriver(createS3Client());
108
111
  }
109
- return new LocalStorageDriver(process.env.STORAGE_PATH ?? "storage");
112
+ return new LocalStorageDriver;
110
113
  }
111
- var defaultStorage = new StorageManager(createStorageDriver());
114
+ var defaultStorage = { current: null };
112
115
  function storage() {
113
- return defaultStorage;
116
+ if (!defaultStorage.current) {
117
+ defaultStorage.current = new StorageManager(createStorageDriver());
118
+ }
119
+ return defaultStorage.current;
120
+ }
121
+ function resetDefaultStorage() {
122
+ defaultStorage.current = null;
114
123
  }
115
124
  export {
116
125
  storage,
117
126
  resolveS3Config,
127
+ resetDefaultStorage,
118
128
  createStorageDriver,
119
129
  createS3Client,
120
130
  StorageManager,
@@ -1,30 +1 @@
1
- // @bun
2
- // ../../src/core/tenant/tenantContext.ts
3
- import { AsyncLocalStorage } from "async_hooks";
4
- var tenantContext = new AsyncLocalStorage;
5
- function runWithTenant(tenant, callback) {
6
- return tenantContext.run(tenant, callback);
7
- }
8
- function currentTenant() {
9
- return tenantContext.getStore() ?? null;
10
- }
11
- function currentTenantId() {
12
- return currentTenant()?.id ?? 1;
13
- }
14
- function rateLimitMultiplierForPlan(plan) {
15
- switch (plan) {
16
- case "enterprise":
17
- return 4;
18
- case "pro":
19
- return 2;
20
- default:
21
- return 1;
22
- }
23
- }
24
- export {
25
- tenantContext,
26
- runWithTenant,
27
- rateLimitMultiplierForPlan,
28
- currentTenantId,
29
- currentTenant
30
- };
1
+ export * from "../../index.js";
@@ -1,312 +1 @@
1
- // @bun
2
- // ../../src/core/tenant/tenantMiddleware.ts
3
- import { createHash } from "crypto";
4
-
5
- // ../../src/config/database.ts
6
- function readInteger(name, fallback) {
7
- const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
8
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
9
- }
10
- var databaseConfig = {
11
- url: process.env.DATABASE_URL ?? "",
12
- poolMax: readInteger("DB_POOL_MAX", 10),
13
- idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
14
- maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
15
- connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
16
- };
17
-
18
- // ../../src/core/database/connectionContext.ts
19
- import { AsyncLocalStorage } from "async_hooks";
20
- var activeConnection = new AsyncLocalStorage;
21
- function runWithDatabaseConnection(connection, callback) {
22
- return activeConnection.run(connection, callback);
23
- }
24
- function getActiveDatabaseConnection(fallback) {
25
- return activeConnection.getStore() ?? fallback;
26
- }
27
-
28
- // ../../src/db/connection/createConnection.ts
29
- var {SQL } = globalThis.Bun;
30
- function createDatabaseConnection(config) {
31
- if (!config.url) {
32
- throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
33
- }
34
- return new SQL({
35
- url: config.url,
36
- max: config.poolMax,
37
- idleTimeout: config.idleTimeoutSeconds,
38
- maxLifetime: config.maxLifetimeSeconds,
39
- connectionTimeout: config.connectionTimeoutSeconds
40
- });
41
- }
42
-
43
- // ../../src/db/connection/index.ts
44
- var connectionHolder = {
45
- connection: null
46
- };
47
- function getDatabase() {
48
- if (!connectionHolder.connection) {
49
- connectionHolder.connection = createDatabaseConnection(databaseConfig);
50
- }
51
- return connectionHolder.connection;
52
- }
53
- var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
54
- function resolveDatabase() {
55
- return getActiveDatabaseConnection(getDatabase());
56
- }
57
- function resolveDatabaseForProperty(property) {
58
- if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
59
- return getDatabase();
60
- }
61
- return resolveDatabase();
62
- }
63
- var db = new Proxy(function database() {}, {
64
- apply(_target, _thisArg, args) {
65
- return resolveDatabase()(...args);
66
- },
67
- get(_target, property) {
68
- const connection = resolveDatabaseForProperty(property);
69
- const value = connection[property];
70
- return typeof value === "function" ? value.bind(connection) : value;
71
- }
72
- });
73
- var connection_default = db;
74
-
75
- // ../../src/core/errors/http.ts
76
- class HttpError extends Error {
77
- status;
78
- details;
79
- constructor(status, message, details) {
80
- super(message);
81
- this.name = new.target.name;
82
- this.status = status;
83
- this.details = details;
84
- }
85
- }
86
-
87
- class BadRequestError extends HttpError {
88
- constructor(message = "Bad Request", details) {
89
- super(400, message, details);
90
- }
91
- }
92
-
93
- class NotFoundError extends HttpError {
94
- constructor(message = "Not Found", details) {
95
- super(404, message, details);
96
- }
97
- }
98
-
99
- class ConflictError extends HttpError {
100
- constructor(message = "Conflict", details) {
101
- super(409, message, details);
102
- }
103
- }
104
-
105
- class UnprocessableEntityError extends HttpError {
106
- constructor(message = "Unprocessable Entity", details) {
107
- super(422, message, details);
108
- }
109
- }
110
-
111
- class ValidationError extends HttpError {
112
- constructor(message = "Validation failed", details) {
113
- super(422, message, details);
114
- }
115
- }
116
-
117
- class ForbiddenError extends HttpError {
118
- constructor(message = "Forbidden", details) {
119
- super(403, message, details);
120
- }
121
- }
122
-
123
- class UnauthorizedError extends HttpError {
124
- constructor(message = "Unauthorized", details) {
125
- super(401, message, details);
126
- }
127
- }
128
-
129
- class PayloadTooLargeError extends HttpError {
130
- constructor(message = "Payload Too Large", details) {
131
- super(413, message, details);
132
- }
133
- }
134
-
135
- class PreconditionFailedError extends HttpError {
136
- constructor(message = "Precondition Failed", details) {
137
- super(412, message, details);
138
- }
139
- }
140
-
141
- // ../../src/core/auth/authContext.ts
142
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
143
- var authContext = new AsyncLocalStorage2;
144
- function runWithAuthUser(user, callback) {
145
- return authContext.run(user, callback);
146
- }
147
- function currentAuthUser() {
148
- return authContext.getStore() ?? null;
149
- }
150
-
151
- // ../../src/core/auth/accessControl.ts
152
- var ROLE_RANK = {
153
- member: 1,
154
- admin: 2,
155
- owner: 3
156
- };
157
- function isGlobalAdmin(user) {
158
- return user?.role === "admin";
159
- }
160
- function hasMinimumOrgRole(role, minimum) {
161
- if (!role) {
162
- return false;
163
- }
164
- return ROLE_RANK[role] >= ROLE_RANK[minimum];
165
- }
166
- function requireAuthenticatedUser() {
167
- const user = currentAuthUser();
168
- if (!user) {
169
- throw new ForbiddenError("Authentication required.");
170
- }
171
- return user;
172
- }
173
- function resolveUserId(user) {
174
- const userId = typeof user.id === "number" ? user.id : Number(user.id);
175
- if (!Number.isInteger(userId) || userId <= 0) {
176
- throw new ForbiddenError("Invalid authenticated user.");
177
- }
178
- return userId;
179
- }
180
-
181
- // ../../src/core/tenant/databaseTenantContext.ts
182
- async function runWithMigrationBypass(callback) {
183
- await connection_default`SELECT set_config('app.bypass_rls', 'true', false)`;
184
- try {
185
- return await callback();
186
- } finally {
187
- await connection_default`SELECT set_config('app.bypass_rls', 'false', false)`;
188
- }
189
- }
190
-
191
- // ../../src/core/tenant/resolveTenant.ts
192
- async function resolveTenant(tenantId) {
193
- const rows = await connection_default`
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/tenantContext.ts
204
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
205
- var tenantContext = new AsyncLocalStorage3;
206
- function runWithTenant(tenant, callback) {
207
- return tenantContext.run(tenant, callback);
208
- }
209
- function currentTenant() {
210
- return tenantContext.getStore() ?? null;
211
- }
212
- function currentTenantId() {
213
- return currentTenant()?.id ?? 1;
214
- }
215
- function rateLimitMultiplierForPlan(plan) {
216
- switch (plan) {
217
- case "enterprise":
218
- return 4;
219
- case "pro":
220
- return 2;
221
- default:
222
- return 1;
223
- }
224
- }
225
-
226
- // ../../src/core/tenant/tenantDatabaseScope.ts
227
- async function applyTenantContextToTransaction(transaction, tenantId) {
228
- await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
229
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
230
- }
231
- async function runWithTenantDatabase(tenant, callback) {
232
- return await getDatabase().begin(async (transaction) => {
233
- await applyTenantContextToTransaction(transaction, tenant.id);
234
- return await runWithDatabaseConnection(transaction, async () => {
235
- return await runWithTenant(tenant, callback);
236
- });
237
- });
238
- }
239
-
240
- // ../../src/core/tenant/tenantMiddleware.ts
241
- var DEFAULT_TENANT = {
242
- id: 1,
243
- slug: "default",
244
- plan: "enterprise",
245
- region: "eu"
246
- };
247
- async function resolveUserTenantId(userId) {
248
- return await runWithMigrationBypass(async () => {
249
- const rows = await connection_default`
250
- SELECT tenant_id
251
- FROM users
252
- WHERE id = ${userId}
253
- LIMIT 1
254
- `;
255
- return rows[0]?.tenant_id ?? DEFAULT_TENANT.id;
256
- });
257
- }
258
- function auditChecksum(payload) {
259
- return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
260
- }
261
- async function resolveTenantForRequest(request) {
262
- const user = currentAuthUser();
263
- const headerValue = request.headers.get("x-tenant-id")?.trim();
264
- const parsedHeader = headerValue !== undefined && headerValue.length > 0 ? Number.parseInt(headerValue, 10) : Number.NaN;
265
- if (user) {
266
- const userId = typeof user.id === "number" ? user.id : Number.parseInt(String(user.id), 10);
267
- if (Number.isInteger(userId) && userId > 0) {
268
- const userTenantId = await resolveUserTenantId(userId);
269
- if (!isGlobalAdmin(user)) {
270
- if (Number.isInteger(parsedHeader) && parsedHeader > 0 && parsedHeader !== userTenantId) {
271
- throw new ForbiddenError("Tenant header does not match your account.");
272
- }
273
- return await resolveTenant(userTenantId) ?? DEFAULT_TENANT;
274
- }
275
- if (Number.isInteger(parsedHeader) && parsedHeader > 0) {
276
- return await resolveTenant(parsedHeader) ?? DEFAULT_TENANT;
277
- }
278
- return await resolveTenant(userTenantId) ?? DEFAULT_TENANT;
279
- }
280
- }
281
- const tenantId = Number.isInteger(parsedHeader) && parsedHeader > 0 ? parsedHeader : DEFAULT_TENANT.id;
282
- return await resolveTenant(tenantId) ?? DEFAULT_TENANT;
283
- }
284
- function createTenantMiddleware() {
285
- return async (request, next) => {
286
- try {
287
- const tenant = await resolveTenantForRequest(request);
288
- return await runWithTenantDatabase(tenant, async () => {
289
- const response = await next();
290
- const headers = new Headers(response.headers);
291
- headers.set("x-tenant-id", String(tenant.id));
292
- headers.set("x-tenant-region", tenant.region);
293
- return new Response(response.body, {
294
- status: response.status,
295
- statusText: response.statusText,
296
- headers
297
- });
298
- });
299
- } catch (error) {
300
- if (error instanceof HttpError) {
301
- return Response.json({ error: error.message }, { status: error.status });
302
- }
303
- throw error;
304
- }
305
- };
306
- }
307
- export {
308
- resolveUserTenantId,
309
- createTenantMiddleware,
310
- auditChecksum,
311
- DEFAULT_TENANT
312
- };
1
+ export * from "../../index.js";
@@ -1,15 +1 @@
1
- // @bun
2
- // ../../src/core/tracing/traceContext.ts
3
- import { AsyncLocalStorage } from "async_hooks";
4
- var traceContextStorage = new AsyncLocalStorage;
5
- function runWithTraceContext(context, callback) {
6
- return traceContextStorage.run(context, callback);
7
- }
8
- function currentTraceId() {
9
- return traceContextStorage.getStore()?.traceId ?? null;
10
- }
11
- export {
12
- traceContextStorage,
13
- runWithTraceContext,
14
- currentTraceId
15
- };
1
+ export * from "../../index.js";