@getstrata/bootstrap 0.2.8 → 0.2.9

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.
@@ -262,6 +262,7 @@ var db = new Proxy(function database() {}, {
262
262
  return typeof value === "function" ? value.bind(connection) : value;
263
263
  }
264
264
  });
265
+ var connection_default = db;
265
266
 
266
267
  // ../../src/modules/user/apiTokenTable.ts
267
268
  import { defineTable } from "@getstrata/core/database";
@@ -0,0 +1,480 @@
1
+ // @bun
2
+ // ../../src/core/errors/http.ts
3
+ class HttpError extends Error {
4
+ status;
5
+ details;
6
+ constructor(status, message, details) {
7
+ super(message);
8
+ this.name = new.target.name;
9
+ this.status = status;
10
+ this.details = details;
11
+ }
12
+ }
13
+
14
+ class BadRequestError extends HttpError {
15
+ constructor(message = "Bad Request", details) {
16
+ super(400, message, details);
17
+ }
18
+ }
19
+ class ConflictError extends HttpError {
20
+ constructor(message = "Conflict", details) {
21
+ super(409, message, details);
22
+ }
23
+ }
24
+
25
+ class UnprocessableEntityError extends HttpError {
26
+ constructor(message = "Unprocessable Entity", details) {
27
+ super(422, message, details);
28
+ }
29
+ }
30
+ class ForbiddenError extends HttpError {
31
+ constructor(message = "Forbidden", details) {
32
+ super(403, message, details);
33
+ }
34
+ }
35
+
36
+ class UnauthorizedError extends HttpError {
37
+ constructor(message = "Unauthorized", details) {
38
+ super(401, message, details);
39
+ }
40
+ }
41
+ class PreconditionFailedError extends HttpError {
42
+ constructor(message = "Precondition Failed", details) {
43
+ super(412, message, details);
44
+ }
45
+ }
46
+
47
+ // ../../src/core/auth/authContext.ts
48
+ import { AsyncLocalStorage } from "async_hooks";
49
+ var authContext = new AsyncLocalStorage;
50
+ function currentAuthUser() {
51
+ return authContext.getStore() ?? null;
52
+ }
53
+
54
+ // ../../src/core/auth/accessControl.ts
55
+ var ROLE_RANK = {
56
+ member: 1,
57
+ admin: 2,
58
+ owner: 3
59
+ };
60
+ function isGlobalAdmin(user) {
61
+ return user?.role === "admin";
62
+ }
63
+ function hasMinimumOrgRole(role, minimum) {
64
+ if (!role) {
65
+ return false;
66
+ }
67
+ return ROLE_RANK[role] >= ROLE_RANK[minimum];
68
+ }
69
+ function resolveUserId(user) {
70
+ const userId = typeof user.id === "number" ? user.id : Number(user.id);
71
+ if (!Number.isInteger(userId) || userId <= 0) {
72
+ throw new ForbiddenError("Invalid authenticated user.");
73
+ }
74
+ return userId;
75
+ }
76
+
77
+ // ../../src/core/auth/membershipContext.ts
78
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
79
+
80
+ // ../../src/config/database.ts
81
+ function readInteger(name, fallback) {
82
+ const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
83
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
84
+ }
85
+ var databaseConfig = {
86
+ url: process.env.DATABASE_URL ?? "",
87
+ poolMax: readInteger("DB_POOL_MAX", 10),
88
+ idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
89
+ maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
90
+ connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
91
+ };
92
+
93
+ // ../../src/core/database/connectionContext.ts
94
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
95
+ var activeConnection = new AsyncLocalStorage2;
96
+ function getActiveDatabaseConnection(fallback) {
97
+ return activeConnection.getStore() ?? fallback;
98
+ }
99
+
100
+ // ../../src/core/database/queryProxy.ts
101
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
102
+ function createDatabaseQueryProxy(pool) {
103
+ function resolveDatabase() {
104
+ return getActiveDatabaseConnection(pool);
105
+ }
106
+ function resolveDatabaseForProperty(property) {
107
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
108
+ return pool;
109
+ }
110
+ return resolveDatabase();
111
+ }
112
+ return new Proxy(function database() {}, {
113
+ apply(_target, _thisArg, args) {
114
+ return resolveDatabase()(...args);
115
+ },
116
+ get(_target, property) {
117
+ const connection = resolveDatabaseForProperty(property);
118
+ const value = connection[property];
119
+ return typeof value === "function" ? value.bind(connection) : value;
120
+ }
121
+ });
122
+ }
123
+
124
+ // ../../src/core/database/defaultConnection.ts
125
+ var defaultPool = {
126
+ connection: null
127
+ };
128
+ var defaultQuery = {
129
+ connection: null
130
+ };
131
+ function registerDefaultDatabasePool(connection) {
132
+ defaultPool.connection = connection;
133
+ defaultQuery.connection = createDatabaseQueryProxy(connection);
134
+ }
135
+ function getDefaultDatabaseQuery() {
136
+ if (!defaultQuery.connection) {
137
+ throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
138
+ }
139
+ return defaultQuery.connection;
140
+ }
141
+
142
+ // ../../src/db/connection/createConnection.ts
143
+ var {SQL } = globalThis.Bun;
144
+ function createDatabaseConnection(config) {
145
+ if (!config.url) {
146
+ throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
147
+ }
148
+ return new SQL({
149
+ url: config.url,
150
+ max: config.poolMax,
151
+ idleTimeout: config.idleTimeoutSeconds,
152
+ maxLifetime: config.maxLifetimeSeconds,
153
+ connectionTimeout: config.connectionTimeoutSeconds
154
+ });
155
+ }
156
+
157
+ // ../../src/db/connection/index.ts
158
+ var connectionHolder = {
159
+ connection: null
160
+ };
161
+ function getDatabase() {
162
+ if (!connectionHolder.connection) {
163
+ connectionHolder.connection = createDatabaseConnection(databaseConfig);
164
+ registerDefaultDatabasePool(connectionHolder.connection);
165
+ }
166
+ return connectionHolder.connection;
167
+ }
168
+ function getDb() {
169
+ getDatabase();
170
+ return getDefaultDatabaseQuery();
171
+ }
172
+ var db = new Proxy(function database() {}, {
173
+ apply(_target, _thisArg, args) {
174
+ return getDb()(...args);
175
+ },
176
+ get(_target, property) {
177
+ const connection = getDb();
178
+ const value = connection[property];
179
+ return typeof value === "function" ? value.bind(connection) : value;
180
+ }
181
+ });
182
+ var connection_default = db;
183
+
184
+ // ../../src/modules/organization/memberRepository.ts
185
+ class OrganizationMemberRepository {
186
+ constructor() {}
187
+ async findMembership(userId, organizationId) {
188
+ const rows = await connection_default`
189
+ SELECT id, organization_id, user_id, role, created_at
190
+ FROM organization_member
191
+ WHERE user_id = ${userId} AND organization_id = ${organizationId}
192
+ LIMIT 1
193
+ `;
194
+ return rows[0] ?? null;
195
+ }
196
+ async listForUser(userId) {
197
+ return await connection_default`
198
+ SELECT id, organization_id, user_id, role, created_at
199
+ FROM organization_member
200
+ WHERE user_id = ${userId}
201
+ ORDER BY organization_id
202
+ `;
203
+ }
204
+ async listForOrganization(organizationId) {
205
+ return await connection_default`
206
+ SELECT id, organization_id, user_id, role, created_at
207
+ FROM organization_member
208
+ WHERE organization_id = ${organizationId}
209
+ ORDER BY id
210
+ `;
211
+ }
212
+ async addMember(input) {
213
+ const rows = await connection_default`
214
+ INSERT INTO organization_member (organization_id, user_id, role)
215
+ VALUES (${input.organizationId}, ${input.userId}, ${input.role ?? "member"})
216
+ RETURNING id, organization_id, user_id, role, created_at
217
+ `;
218
+ const row = rows[0];
219
+ if (!row) {
220
+ throw new Error("Organization member insert did not return a row.");
221
+ }
222
+ return row;
223
+ }
224
+ async removeMember(organizationId, userId) {
225
+ const rows = await connection_default`
226
+ DELETE FROM organization_member
227
+ WHERE organization_id = ${organizationId} AND user_id = ${userId}
228
+ RETURNING id
229
+ `;
230
+ return rows.length > 0;
231
+ }
232
+ }
233
+ var memberRepository_default = OrganizationMemberRepository;
234
+
235
+ // ../../src/core/auth/membershipContext.ts
236
+ var membershipContext = new AsyncLocalStorage3;
237
+ var membershipRepository = new memberRepository_default;
238
+
239
+ // ../../src/core/auth/membershipService.ts
240
+ class MembershipService {
241
+ members;
242
+ constructor(members = membershipRepository) {
243
+ this.members = members;
244
+ }
245
+ async listOrganizationIdsForUser(userId) {
246
+ const memberships = await this.members.listForUser(userId);
247
+ return memberships.map((membership) => membership.organization_id);
248
+ }
249
+ async getOrgRole(userId, organizationId) {
250
+ const membership = await this.members.findMembership(userId, organizationId);
251
+ return membership?.role ?? null;
252
+ }
253
+ async requireOrgAccess(organizationId, minimumRole = "member", user = currentAuthUser()) {
254
+ if (!user) {
255
+ throw new ForbiddenError("Authentication required.");
256
+ }
257
+ if (isGlobalAdmin(user)) {
258
+ return "owner";
259
+ }
260
+ const role = await this.getOrgRole(resolveUserId(user), organizationId);
261
+ if (!role || !hasMinimumOrgRole(role, minimumRole)) {
262
+ throw new ForbiddenError("Organization membership required.");
263
+ }
264
+ return role;
265
+ }
266
+ async filterAccessibleOrganizationIds(organizationIds, user = currentAuthUser()) {
267
+ if (!user) {
268
+ return [];
269
+ }
270
+ if (isGlobalAdmin(user)) {
271
+ return organizationIds;
272
+ }
273
+ const allowed = new Set(await this.listOrganizationIdsForUser(resolveUserId(user)));
274
+ return organizationIds.filter((organizationId) => allowed.has(organizationId));
275
+ }
276
+ async addOwnerOnOrganizationCreate(organizationId, userId) {
277
+ await this.members.addMember({
278
+ organizationId,
279
+ userId,
280
+ role: "owner"
281
+ });
282
+ }
283
+ listMembersForOrganization(organizationId) {
284
+ return this.members.listForOrganization(organizationId);
285
+ }
286
+ addMember(input) {
287
+ return this.members.addMember(input);
288
+ }
289
+ removeMember(organizationId, userId) {
290
+ return this.members.removeMember(organizationId, userId);
291
+ }
292
+ }
293
+ var membershipService_default = MembershipService;
294
+
295
+ // ../../src/core/logging/logger.ts
296
+ class Logger {
297
+ channel;
298
+ constructor(channel = "app") {
299
+ this.channel = channel;
300
+ }
301
+ write(level, message, context = {}) {
302
+ const entry = {
303
+ level,
304
+ channel: this.channel,
305
+ message,
306
+ timestamp: new Date().toISOString(),
307
+ ...context
308
+ };
309
+ const line = JSON.stringify(entry);
310
+ if (level === "error") {
311
+ console.error(line);
312
+ return;
313
+ }
314
+ console.log(line);
315
+ }
316
+ debug(message, context) {
317
+ this.write("debug", message, context);
318
+ }
319
+ info(message, context) {
320
+ this.write("info", message, context);
321
+ }
322
+ warn(message, context) {
323
+ this.write("warn", message, context);
324
+ }
325
+ error(message, context) {
326
+ this.write("error", message, context);
327
+ }
328
+ }
329
+ var appLogger = new Logger("app");
330
+
331
+ // ../../src/bootstrap/config.ts
332
+ var APP_PORT_CONFIG_KEY = "app.port";
333
+ var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
334
+ var CACHE_MAX_ENTRIES_CONFIG_KEY = "cache.maxEntries";
335
+ var CACHE_DRIVER_CONFIG_KEY = "cache.driver";
336
+ var REDIS_URL_CONFIG_KEY = "cache.redisUrl";
337
+ var DATABASE_URL_CONFIG_KEY = "database.url";
338
+ var CORE_CONFIG_TOKEN = "core.config";
339
+ var CORE_CACHE_TOKEN = "core.cache";
340
+ var CORE_QUEUE_TOKEN = "core.queue";
341
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
342
+ var CORE_AUTH_TOKEN = "core.auth";
343
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
344
+ var AUTH_DEV_HEADERS_CONFIG_KEY = "auth.allowDevHeaders";
345
+ var DEFAULT_APP_PORT = 3000;
346
+ var DEFAULT_CACHE_TTL_MS = 3600000;
347
+ var DEFAULT_CACHE_MAX_ENTRIES = 100;
348
+ var DEFAULT_CACHE_DRIVER = "array";
349
+ var DEFAULT_API_TOKEN = "";
350
+ var DEFAULT_QUEUE_DRIVER = "sync";
351
+
352
+ // ../../src/bootstrap/contracts.ts
353
+ class ServiceContainer {
354
+ services = new Map;
355
+ singletonFactories = new Map;
356
+ bindings = new Map;
357
+ set(key, value) {
358
+ this.singletonFactories.delete(key);
359
+ this.bindings.delete(key);
360
+ this.services.set(key, value);
361
+ return value;
362
+ }
363
+ singleton(key, factory) {
364
+ this.bindings.delete(key);
365
+ this.services.delete(key);
366
+ this.singletonFactories.set(key, factory);
367
+ }
368
+ bind(key, factory) {
369
+ this.singletonFactories.delete(key);
370
+ this.services.delete(key);
371
+ this.bindings.set(key, factory);
372
+ }
373
+ get(key) {
374
+ if (this.services.has(key)) {
375
+ return this.services.get(key);
376
+ }
377
+ const singletonFactory = this.singletonFactories.get(key);
378
+ if (singletonFactory) {
379
+ const value = singletonFactory(this);
380
+ this.services.set(key, value);
381
+ return value;
382
+ }
383
+ const binding = this.bindings.get(key);
384
+ if (binding) {
385
+ return binding(this);
386
+ }
387
+ throw new Error(`Service "${key}" is not registered.`);
388
+ }
389
+ resolve(key) {
390
+ return this.get(key);
391
+ }
392
+ has(key) {
393
+ return this.services.has(key) || this.singletonFactories.has(key) || this.bindings.has(key);
394
+ }
395
+ }
396
+
397
+ class ConfigStore {
398
+ values = new Map;
399
+ set(key, value) {
400
+ this.values.set(key, value);
401
+ return value;
402
+ }
403
+ get(key) {
404
+ return this.values.get(key);
405
+ }
406
+ require(key) {
407
+ if (!this.values.has(key)) {
408
+ throw new Error(`Config key "${key}" is not defined.`);
409
+ }
410
+ return this.values.get(key);
411
+ }
412
+ has(key) {
413
+ return this.values.has(key);
414
+ }
415
+ }
416
+ var requiredDependencyKeys = [
417
+ "container",
418
+ "cache",
419
+ "storage"
420
+ ];
421
+ function getRequiredDependency(dependencies, key) {
422
+ const dependency = dependencies[key];
423
+ if (dependency === undefined) {
424
+ throw new Error(`Required dependency "${key}" is not registered.`);
425
+ }
426
+ return dependency;
427
+ }
428
+ function assertAppDependenciesComplete(dependencies) {
429
+ for (const key of requiredDependencyKeys) {
430
+ getRequiredDependency(dependencies, key);
431
+ }
432
+ }
433
+ function resolveService(dependencies, token) {
434
+ return dependencies.container.resolve(token);
435
+ }
436
+
437
+ // ../../src/bootstrap/applicationRegistry.ts
438
+ var activeContext;
439
+ function setActiveApplicationContext(context) {
440
+ activeContext = context;
441
+ }
442
+ function requireActiveApplicationContext() {
443
+ if (!activeContext) {
444
+ throw new Error("The application context has not been bootstrapped.");
445
+ }
446
+ return activeContext;
447
+ }
448
+ function resolveApplicationCache() {
449
+ return getRequiredDependency(requireActiveApplicationContext().dependencies, "cache");
450
+ }
451
+ function resolveApplicationQueue() {
452
+ return requireActiveApplicationContext().container.resolve(CORE_QUEUE_TOKEN);
453
+ }
454
+ function resolveApplicationAuth() {
455
+ return requireActiveApplicationContext().container.resolve(CORE_AUTH_TOKEN);
456
+ }
457
+ function resolveApplicationPolicyGate() {
458
+ return requireActiveApplicationContext().container.resolve(CORE_POLICY_GATE_TOKEN);
459
+ }
460
+ function resolveApplicationConfig() {
461
+ return requireActiveApplicationContext().config;
462
+ }
463
+ function resolveApplicationLogger() {
464
+ return appLogger;
465
+ }
466
+ function resolveApplicationDependencies() {
467
+ return requireActiveApplicationContext().dependencies;
468
+ }
469
+
470
+ // ../../src/bootstrap/membershipService.ts
471
+ function resolveMembershipService() {
472
+ const dependencies = resolveApplicationDependencies();
473
+ if (dependencies.container.has("core.membership")) {
474
+ return dependencies.container.resolve("core.membership");
475
+ }
476
+ return new membershipService_default;
477
+ }
478
+ export {
479
+ resolveMembershipService
480
+ };
@@ -218,6 +218,7 @@ var db = new Proxy(function database() {}, {
218
218
  return typeof value === "function" ? value.bind(connection) : value;
219
219
  }
220
220
  });
221
+ var connection_default = db;
221
222
 
222
223
  // ../../src/modules/user/apiTokenTable.ts
223
224
  import { defineTable } from "@getstrata/core/database";