@getstrata/bootstrap 0.2.6 → 0.2.8

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 (39) hide show
  1. package/dist/bootstrap/contracts.d.ts +2 -0
  2. package/dist/bootstrap/http/securedRouteModelBinding.d.ts +11 -0
  3. package/dist/bootstrap/providers/storage.d.ts +3 -0
  4. package/dist/bootstrap/public-api.d.ts +1 -0
  5. package/dist/bootstrap/scimRoutes.d.ts +1 -1
  6. package/dist/core/auth/membershipScope.d.ts +16 -0
  7. package/dist/core/auth/membershipService.d.ts +24 -0
  8. package/dist/core/database/baseRepository.d.ts +6 -1
  9. package/dist/core/database/connectionContext.d.ts +2 -1
  10. package/dist/core/database/defaultConnection.d.ts +6 -0
  11. package/dist/core/database/queryProxy.d.ts +3 -0
  12. package/dist/core/database/repositoryConnection.d.ts +3 -3
  13. package/dist/core/http/securedRouteModelBinding.d.ts +2 -11
  14. package/dist/core/jobs/dispatchWebhookJob.d.ts +0 -1
  15. package/dist/core/queue/queueMetrics.d.ts +15 -0
  16. package/dist/core/security/safeFetch.d.ts +2 -0
  17. package/dist/core/security/safeUrl.d.ts +16 -1
  18. package/dist/core/tenant/tenantDatabaseScope.d.ts +2 -1
  19. package/dist/db/connection/index.d.ts +1 -1
  20. package/dist/domain/workhub.d.ts +35 -0
  21. package/dist/entries/applicationRegistry.js +185 -0
  22. package/dist/entries/config.js +42 -0
  23. package/dist/entries/context.js +4213 -0
  24. package/dist/entries/contracts.js +92 -0
  25. package/dist/entries/createWebRoutes.js +996 -0
  26. package/dist/entries/http/securedRouteModelBinding.js +383 -0
  27. package/dist/entries/httpKernel.js +264 -0
  28. package/dist/entries/providers/view.js +635 -0
  29. package/dist/entries/providers.js +4099 -0
  30. package/dist/framework/public-api.d.ts +30 -6
  31. package/dist/index.js +455 -110
  32. package/dist/modules/organization/repository.d.ts +14 -0
  33. package/dist/modules/organization/table.d.ts +3 -0
  34. package/dist/modules/organization/types.d.ts +10 -0
  35. package/dist/modules/scim/controller.d.ts +2 -1
  36. package/dist/modules/scim/scimResponse.d.ts +1 -1
  37. package/dist/modules/scim/service.d.ts +4 -7
  38. package/dist/modules/user/repository.d.ts +1 -0
  39. package/package.json +10 -4
@@ -0,0 +1,996 @@
1
+ // @bun
2
+ // ../../src/bootstrap/createWebRoutes.ts
3
+ import { join as join3 } from "path";
4
+
5
+ // ../../src/config/frontend.ts
6
+ function readFrontendMode() {
7
+ const mode = (process.env.FRONTEND_MODE ?? "api").trim();
8
+ if (mode === "server-htmx") {
9
+ return "server-htmx";
10
+ }
11
+ if (mode === "spa-react") {
12
+ return "spa-react";
13
+ }
14
+ return "api";
15
+ }
16
+ function isViewsEnabled() {
17
+ return readFrontendMode() === "server-htmx";
18
+ }
19
+
20
+ // ../../src/core/http/middleware.ts
21
+ function isRouteHandler(value) {
22
+ return typeof value === "function";
23
+ }
24
+ function isMethodRouteMap(value) {
25
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
26
+ return false;
27
+ }
28
+ const entries = Object.entries(value);
29
+ return entries.length > 0 && entries.every(([, handler]) => isRouteHandler(handler));
30
+ }
31
+ function composeMiddleware(...middleware) {
32
+ return (handler) => {
33
+ return async (request) => {
34
+ let index = 0;
35
+ const dispatch = async () => {
36
+ if (index >= middleware.length) {
37
+ return await handler(request);
38
+ }
39
+ const current = middleware[index];
40
+ index += 1;
41
+ if (!current) {
42
+ return await handler(request);
43
+ }
44
+ return await current(request, dispatch);
45
+ };
46
+ return await dispatch();
47
+ };
48
+ };
49
+ }
50
+ function wrapRouteHandler(handler, middleware) {
51
+ if (isMethodRouteMap(handler)) {
52
+ const wrapped = {};
53
+ for (const [method, routeHandler] of Object.entries(handler)) {
54
+ wrapped[method] = composeMiddleware(...middleware)(routeHandler);
55
+ }
56
+ return wrapped;
57
+ }
58
+ if (isRouteHandler(handler)) {
59
+ return composeMiddleware(...middleware)(handler);
60
+ }
61
+ return handler;
62
+ }
63
+ function applyMiddlewareToRoutes(routes, middleware) {
64
+ const wrapped = {};
65
+ for (const [path, routeHandler] of Object.entries(routes)) {
66
+ wrapped[path] = wrapRouteHandler(routeHandler, middleware);
67
+ }
68
+ return wrapped;
69
+ }
70
+
71
+ // ../../src/core/view/etaViewEngine.ts
72
+ import { join } from "path";
73
+ import { Eta } from "eta";
74
+ var DEFAULT_VIEWS_DIRECTORY = join(process.cwd(), "resources/views");
75
+ var DEFAULT_LAYOUT = "layouts/app.eta";
76
+
77
+ class EtaViewEngine {
78
+ eta;
79
+ resolveLayoutData;
80
+ constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
81
+ this.eta = new Eta({
82
+ views: viewsDirectory,
83
+ autoTrim: false
84
+ });
85
+ this.resolveLayoutData = resolveLayoutData;
86
+ }
87
+ async render(name, data = {}, options = {}) {
88
+ const template = name.endsWith(".eta") ? name : `${name}.eta`;
89
+ const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
90
+ const mergedData = { ...layoutData, ...data };
91
+ const body = await this.eta.renderAsync(template, mergedData);
92
+ const layout = options.layout ?? DEFAULT_LAYOUT;
93
+ if (layout === false) {
94
+ return body;
95
+ }
96
+ const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
97
+ return await this.eta.renderAsync(layoutTemplate, {
98
+ ...mergedData,
99
+ body
100
+ });
101
+ }
102
+ }
103
+ // ../../src/core/view/htmlResponse.ts
104
+ function htmlResponse(html, init = {}) {
105
+ return new Response(html, {
106
+ status: init.status ?? 200,
107
+ statusText: init.statusText,
108
+ headers: {
109
+ "Content-Type": "text/html; charset=utf-8"
110
+ }
111
+ });
112
+ }
113
+ // ../../src/bootstrap/config.ts
114
+ var APP_PORT_CONFIG_KEY = "app.port";
115
+ var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
116
+ var CACHE_MAX_ENTRIES_CONFIG_KEY = "cache.maxEntries";
117
+ var CACHE_DRIVER_CONFIG_KEY = "cache.driver";
118
+ var REDIS_URL_CONFIG_KEY = "cache.redisUrl";
119
+ var DATABASE_URL_CONFIG_KEY = "database.url";
120
+ var CORE_CONFIG_TOKEN = "core.config";
121
+ var CORE_CACHE_TOKEN = "core.cache";
122
+ var CORE_QUEUE_TOKEN = "core.queue";
123
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
124
+ var CORE_AUTH_TOKEN = "core.auth";
125
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
126
+ var AUTH_DEV_HEADERS_CONFIG_KEY = "auth.allowDevHeaders";
127
+ var DEFAULT_APP_PORT = 3000;
128
+ var DEFAULT_CACHE_TTL_MS = 3600000;
129
+ var DEFAULT_CACHE_MAX_ENTRIES = 100;
130
+ var DEFAULT_CACHE_DRIVER = "array";
131
+ var DEFAULT_API_TOKEN = "";
132
+ var DEFAULT_QUEUE_DRIVER = "sync";
133
+
134
+ // ../../src/modules/user/provider.ts
135
+ import { OidcProvider } from "@getstrata/core/auth/oauth/oidcProvider";
136
+ import { GitHubOAuthProvider, MockOAuthProvider } from "@getstrata/core/auth/oauth/providers";
137
+ import { SamlProvider } from "@getstrata/core/auth/oauth/samlProvider";
138
+
139
+ // ../../src/config/features.ts
140
+ function readFeatureFlags() {
141
+ return {
142
+ webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
143
+ fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
144
+ auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
145
+ oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
146
+ samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
147
+ scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
148
+ billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
149
+ siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
150
+ publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
151
+ emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
152
+ mfa: (process.env.FEATURE_MFA ?? "false") === "true"
153
+ };
154
+ }
155
+ var featureFlags = readFeatureFlags();
156
+ function isFeatureEnabled(feature) {
157
+ return readFeatureFlags()[feature];
158
+ }
159
+
160
+ // ../../src/modules/user/apiTokenRepository.ts
161
+ import { BaseRepository } from "@getstrata/core/database";
162
+
163
+ // ../../src/config/database.ts
164
+ function readInteger(name, fallback) {
165
+ const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
166
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
167
+ }
168
+ var databaseConfig = {
169
+ url: process.env.DATABASE_URL ?? "",
170
+ poolMax: readInteger("DB_POOL_MAX", 10),
171
+ idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
172
+ maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
173
+ connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
174
+ };
175
+
176
+ // ../../src/core/database/connectionContext.ts
177
+ import { AsyncLocalStorage } from "async_hooks";
178
+ var activeConnection = new AsyncLocalStorage;
179
+ function getActiveDatabaseConnection(fallback) {
180
+ return activeConnection.getStore() ?? fallback;
181
+ }
182
+
183
+ // ../../src/core/database/queryProxy.ts
184
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
185
+ function createDatabaseQueryProxy(pool) {
186
+ function resolveDatabase() {
187
+ return getActiveDatabaseConnection(pool);
188
+ }
189
+ function resolveDatabaseForProperty(property) {
190
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
191
+ return pool;
192
+ }
193
+ return resolveDatabase();
194
+ }
195
+ return new Proxy(function database() {}, {
196
+ apply(_target, _thisArg, args) {
197
+ return resolveDatabase()(...args);
198
+ },
199
+ get(_target, property) {
200
+ const connection = resolveDatabaseForProperty(property);
201
+ const value = connection[property];
202
+ return typeof value === "function" ? value.bind(connection) : value;
203
+ }
204
+ });
205
+ }
206
+
207
+ // ../../src/core/database/defaultConnection.ts
208
+ var defaultPool = {
209
+ connection: null
210
+ };
211
+ var defaultQuery = {
212
+ connection: null
213
+ };
214
+ function registerDefaultDatabasePool(connection) {
215
+ defaultPool.connection = connection;
216
+ defaultQuery.connection = createDatabaseQueryProxy(connection);
217
+ }
218
+ function getDefaultDatabaseQuery() {
219
+ if (!defaultQuery.connection) {
220
+ throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
221
+ }
222
+ return defaultQuery.connection;
223
+ }
224
+
225
+ // ../../src/db/connection/createConnection.ts
226
+ var {SQL } = globalThis.Bun;
227
+ function createDatabaseConnection(config) {
228
+ if (!config.url) {
229
+ throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
230
+ }
231
+ return new SQL({
232
+ url: config.url,
233
+ max: config.poolMax,
234
+ idleTimeout: config.idleTimeoutSeconds,
235
+ maxLifetime: config.maxLifetimeSeconds,
236
+ connectionTimeout: config.connectionTimeoutSeconds
237
+ });
238
+ }
239
+
240
+ // ../../src/db/connection/index.ts
241
+ var connectionHolder = {
242
+ connection: null
243
+ };
244
+ function getDatabase() {
245
+ if (!connectionHolder.connection) {
246
+ connectionHolder.connection = createDatabaseConnection(databaseConfig);
247
+ registerDefaultDatabasePool(connectionHolder.connection);
248
+ }
249
+ return connectionHolder.connection;
250
+ }
251
+ function getDb() {
252
+ getDatabase();
253
+ return getDefaultDatabaseQuery();
254
+ }
255
+ var db = new Proxy(function database() {}, {
256
+ apply(_target, _thisArg, args) {
257
+ return getDb()(...args);
258
+ },
259
+ get(_target, property) {
260
+ const connection = getDb();
261
+ const value = connection[property];
262
+ return typeof value === "function" ? value.bind(connection) : value;
263
+ }
264
+ });
265
+
266
+ // ../../src/modules/user/apiTokenTable.ts
267
+ import { defineTable } from "@getstrata/core/database";
268
+ var apiTokenTable = defineTable({
269
+ name: "api_token",
270
+ primaryKey: "id",
271
+ columns: [
272
+ "id",
273
+ "user_id",
274
+ "name",
275
+ "token_hash",
276
+ "abilities",
277
+ "last_used_at",
278
+ "expires_at",
279
+ "created_at"
280
+ ],
281
+ defaultOrderBy: { column: "id", direction: "ASC" }
282
+ });
283
+
284
+ // ../../src/modules/user/authService.ts
285
+ import { verifyPassword } from "@getstrata/core/auth/password";
286
+ import { revealMfaSecret } from "@getstrata/core/crypto/mfaSecret";
287
+ import { UnauthorizedError } from "@getstrata/core/errors/http";
288
+ import { logSecurityEvent } from "@getstrata/core/security/securityEvents";
289
+ import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
290
+ import { verifyTotp } from "@getstrata/core/security/totp";
291
+ import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
292
+
293
+ // ../../src/domain/abilities.ts
294
+ var MEMBER_ABILITIES = [
295
+ "organizations:read",
296
+ "projects:read",
297
+ "projects:create",
298
+ "tasks:read",
299
+ "tasks:create",
300
+ "comments:read",
301
+ "comments:create",
302
+ "attachments:read",
303
+ "attachments:create",
304
+ "auth:tokens:read",
305
+ "auth:tokens:write"
306
+ ];
307
+ var ADMIN_ABILITIES = [
308
+ ...MEMBER_ABILITIES,
309
+ "organizations:create",
310
+ "organizations:update",
311
+ "organizations:delete",
312
+ "projects:update",
313
+ "projects:delete",
314
+ "tasks:update",
315
+ "tasks:delete",
316
+ "comments:update",
317
+ "comments:delete",
318
+ "attachments:delete",
319
+ "webhooks:read",
320
+ "webhooks:write",
321
+ "audit:read"
322
+ ];
323
+ var PLATFORM_ADMIN_ABILITIES = ["*"];
324
+ function resolveAbilitiesForRole(role) {
325
+ if (role === "admin") {
326
+ return [...PLATFORM_ADMIN_ABILITIES];
327
+ }
328
+ return [...MEMBER_ABILITIES];
329
+ }
330
+
331
+ // ../../src/modules/user/authService.ts
332
+ class AuthService {
333
+ users;
334
+ tokens;
335
+ oauthIdentities;
336
+ oauthProviders = new Map;
337
+ constructor(users, tokens, oauthIdentities) {
338
+ this.users = users;
339
+ this.tokens = tokens;
340
+ this.oauthIdentities = oauthIdentities;
341
+ }
342
+ registerOAuthProvider(provider) {
343
+ this.oauthProviders.set(provider.name, provider);
344
+ }
345
+ getOAuthProvider(name) {
346
+ return this.oauthProviders.get(name);
347
+ }
348
+ async loginWithPassword(email, password, options = {}) {
349
+ const user = await this.users.findByEmail(email);
350
+ if (!user?.password_hash) {
351
+ logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
352
+ throw new UnauthorizedError("Invalid credentials.");
353
+ }
354
+ const valid = await verifyPassword(password, user.password_hash);
355
+ if (!valid) {
356
+ logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
357
+ throw new UnauthorizedError("Invalid credentials.");
358
+ }
359
+ if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
360
+ logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
361
+ throw new UnauthorizedError("Email address is not verified.");
362
+ }
363
+ if (isFeatureEnabled("mfa") && user.mfa_enabled) {
364
+ const mfaSecret = revealMfaSecret(user.mfa_secret);
365
+ if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
366
+ logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
367
+ throw new UnauthorizedError("Invalid MFA code.");
368
+ }
369
+ }
370
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
371
+ return await this.tokens.createToken(user.id, {
372
+ name: "password-login",
373
+ abilities: resolveAbilitiesForRole(user.role),
374
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
375
+ });
376
+ }
377
+ async loginWithOAuth(providerName, code) {
378
+ const provider = this.oauthProviders.get(providerName);
379
+ if (!provider) {
380
+ throw new UnauthorizedError("Unsupported OAuth provider.");
381
+ }
382
+ const profile = await provider.exchangeCode(code);
383
+ const user = await this.findOrCreateOAuthUser(providerName, profile);
384
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
385
+ return await this.tokens.createToken(user.id, {
386
+ name: `${providerName}-oauth`,
387
+ abilities: resolveAbilitiesForRole(user.role),
388
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
389
+ });
390
+ }
391
+ buildOAuthAuthorizationUrl(providerName, state) {
392
+ const provider = this.oauthProviders.get(providerName);
393
+ if (!provider) {
394
+ throw new UnauthorizedError("Unsupported OAuth provider.");
395
+ }
396
+ return provider.getAuthorizationUrl(state);
397
+ }
398
+ async findOrCreateOAuthUser(providerName, profile) {
399
+ const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
400
+ if (existingIdentity) {
401
+ return await this.users.findByIdOrThrow(existingIdentity.user_id);
402
+ }
403
+ const existingUser = await this.users.findByEmail(profile.email);
404
+ const user = existingUser ?? await this.users.create({
405
+ name: profile.name,
406
+ email: profile.email,
407
+ role: "member",
408
+ tenant_id: currentTenantId(),
409
+ email_verified_at: new Date,
410
+ created_at: new Date,
411
+ updated_at: new Date
412
+ });
413
+ await this.oauthIdentities.create({
414
+ user_id: user.id,
415
+ provider: providerName,
416
+ provider_user_id: profile.providerUserId,
417
+ email: profile.email,
418
+ created_at: new Date
419
+ });
420
+ return user;
421
+ }
422
+ }
423
+
424
+ // ../../src/modules/user/notificationRepository.ts
425
+ import { BaseRepository as BaseRepository2 } from "@getstrata/core/database";
426
+
427
+ // ../../src/modules/user/notificationTable.ts
428
+ import { defineTable as defineTable2 } from "@getstrata/core/database";
429
+ var notificationTable = defineTable2({
430
+ name: "notification",
431
+ primaryKey: "id",
432
+ columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
433
+ defaultOrderBy: { column: "created_at", direction: "DESC" }
434
+ });
435
+
436
+ // ../../src/modules/user/notificationService.ts
437
+ import { NotFoundError } from "@getstrata/core/errors/http";
438
+
439
+ // ../../src/modules/user/oauthIdentityRepository.ts
440
+ import { BaseRepository as BaseRepository3, defineTable as defineTable3 } from "@getstrata/core/database";
441
+ var oauthIdentityTable = defineTable3({
442
+ name: "oauth_identity",
443
+ primaryKey: "id",
444
+ columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
445
+ });
446
+
447
+ // ../../src/modules/user/repository.ts
448
+ import {
449
+ emailLookupForQuery,
450
+ protectEmail,
451
+ revealEmail
452
+ } from "@getstrata/core/crypto/fieldEncryption";
453
+ import { revealMfaSecret as revealMfaSecret2 } from "@getstrata/core/crypto/mfaSecret";
454
+ import { BaseRepository as BaseRepository4 } from "@getstrata/core/database";
455
+ import { currentTenantId as currentTenantId2 } from "@getstrata/core/tenant/tenantContext";
456
+
457
+ // ../../src/modules/user/table.ts
458
+ import { defineTable as defineTable4 } from "@getstrata/core/database";
459
+ var userTable = defineTable4({
460
+ name: "users",
461
+ primaryKey: "id",
462
+ columns: [
463
+ "id",
464
+ "name",
465
+ "email",
466
+ "email_lookup",
467
+ "role",
468
+ "tenant_id",
469
+ "password_hash",
470
+ "email_verified_at",
471
+ "mfa_secret",
472
+ "mfa_enabled",
473
+ "created_at",
474
+ "updated_at"
475
+ ],
476
+ defaultOrderBy: { column: "id", direction: "ASC" }
477
+ });
478
+
479
+ // ../../src/modules/user/tokenService.ts
480
+ import { hashApiToken } from "@getstrata/core/auth/tokenHash";
481
+ import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core/errors/http";
482
+ import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
483
+
484
+ // ../../src/modules/user/provider.ts
485
+ var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
486
+
487
+ // ../../src/core/auth/authContext.ts
488
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
489
+ var authContext = new AsyncLocalStorage2;
490
+ function currentAuthUser() {
491
+ return authContext.getStore() ?? null;
492
+ }
493
+
494
+ // ../../src/core/http/cookies.ts
495
+ function readRequestCookie(request, name) {
496
+ const cookies = request.cookies;
497
+ if (cookies && typeof cookies.get === "function") {
498
+ const value = cookies.get(name);
499
+ if (value) {
500
+ return value;
501
+ }
502
+ }
503
+ const header = request.headers.get("cookie");
504
+ if (!header) {
505
+ return null;
506
+ }
507
+ for (const part of header.split(";")) {
508
+ const idx = part.indexOf("=");
509
+ if (idx === -1)
510
+ continue;
511
+ const cookieName = part.slice(0, idx).trim();
512
+ if (cookieName !== name)
513
+ continue;
514
+ return decodeURIComponent(part.slice(idx + 1).trim());
515
+ }
516
+ return null;
517
+ }
518
+
519
+ // ../../src/core/http/requestMetaContext.ts
520
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
521
+ var requestMetaContext = new AsyncLocalStorage3;
522
+ function currentRequestMeta() {
523
+ return requestMetaContext.getStore() ?? {
524
+ ipAddress: null,
525
+ userAgent: null
526
+ };
527
+ }
528
+
529
+ // ../../src/core/http/csrfToken.ts
530
+ var CSRF_COOKIE = "workhub_csrf";
531
+ var CSRF_TTL_MS = 60 * 60 * 1000;
532
+ function resolveCsrfSecret() {
533
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
534
+ }
535
+ function csrfVerifyOptions() {
536
+ return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
537
+ }
538
+ function createCsrfTokenCookie() {
539
+ const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
540
+ return {
541
+ token,
542
+ cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
543
+ };
544
+ }
545
+ function resolveCsrfToken(request) {
546
+ const cookieValue = readRequestCookie(request, CSRF_COOKIE);
547
+ if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
548
+ return { token: cookieValue };
549
+ }
550
+ return createCsrfTokenCookie();
551
+ }
552
+ function resolveCsrfTokenForRequest(request) {
553
+ const metaToken = currentRequestMeta().csrfToken;
554
+ if (metaToken) {
555
+ return metaToken;
556
+ }
557
+ return resolveCsrfToken(request).token;
558
+ }
559
+
560
+ // ../../src/core/http/flashSession.ts
561
+ import { createHmac, timingSafeEqual } from "crypto";
562
+ var FLASH_COOKIE = "workhub_flash";
563
+ var FLASH_TTL_MS = 60 * 1000;
564
+ function resolveFlashSecret() {
565
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
566
+ }
567
+ function signFlashPayload(payload, issuedAt) {
568
+ const signature = createHmac("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
569
+ return `${payload}.${issuedAt}.${signature}`;
570
+ }
571
+ function readFlashCookie(request) {
572
+ const cookieHeader = request.headers.get("cookie");
573
+ if (!cookieHeader) {
574
+ return null;
575
+ }
576
+ for (const part of cookieHeader.split(";")) {
577
+ const [name, ...rest] = part.trim().split("=");
578
+ if (name === FLASH_COOKIE) {
579
+ return decodeURIComponent(rest.join("="));
580
+ }
581
+ }
582
+ return null;
583
+ }
584
+ function parseFlashCookie(cookieValue) {
585
+ const parts = cookieValue.split(".");
586
+ if (parts.length < 3) {
587
+ return null;
588
+ }
589
+ const signature = parts.pop();
590
+ const issuedAtRaw = parts.pop();
591
+ const payload = parts.join(".");
592
+ if (!signature || !issuedAtRaw || !payload) {
593
+ return null;
594
+ }
595
+ const issuedAt = Number.parseInt(issuedAtRaw, 10);
596
+ if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
597
+ return null;
598
+ }
599
+ const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
600
+ if (!expectedSignature) {
601
+ return null;
602
+ }
603
+ const expectedBuffer = Buffer.from(expectedSignature);
604
+ const actualBuffer = Buffer.from(signature);
605
+ if (expectedBuffer.length !== actualBuffer.length) {
606
+ return null;
607
+ }
608
+ if (!timingSafeEqual(expectedBuffer, actualBuffer)) {
609
+ return null;
610
+ }
611
+ try {
612
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
613
+ if (!parsed?.message || typeof parsed.message !== "string") {
614
+ return null;
615
+ }
616
+ if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
617
+ return null;
618
+ }
619
+ return parsed;
620
+ } catch {
621
+ return null;
622
+ }
623
+ }
624
+ function pullFlash(request) {
625
+ const cookieValue = readFlashCookie(request);
626
+ if (!cookieValue) {
627
+ return null;
628
+ }
629
+ return parseFlashCookie(cookieValue);
630
+ }
631
+
632
+ // ../../src/core/view/webLayoutData.ts
633
+ async function resolveWebLayoutData(container, request) {
634
+ const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
635
+ const flash = request ? currentRequestMeta().flash ?? pullFlash(request) : null;
636
+ const authUser = currentAuthUser();
637
+ if (!authUser) {
638
+ return { authUser: null, csrfToken, flash };
639
+ }
640
+ const userId = Number(authUser.id);
641
+ if (!Number.isInteger(userId) || userId <= 0) {
642
+ return { authUser: null, csrfToken, flash };
643
+ }
644
+ if (!container.has(tokenServiceToken)) {
645
+ return {
646
+ authUser: {
647
+ id: userId,
648
+ email: "",
649
+ role: authUser.role ?? "member"
650
+ },
651
+ csrfToken,
652
+ flash
653
+ };
654
+ }
655
+ const tokenService = container.resolve(tokenServiceToken);
656
+ try {
657
+ const user = await tokenService.findByIdOrThrow(userId);
658
+ return {
659
+ authUser: {
660
+ id: userId,
661
+ email: user.email ?? "",
662
+ role: authUser.role ?? user.role ?? "member"
663
+ },
664
+ csrfToken,
665
+ flash
666
+ };
667
+ } catch {
668
+ return { authUser: null, csrfToken, flash };
669
+ }
670
+ }
671
+ // ../../src/bootstrap/httpKernel.ts
672
+ import {
673
+ createAuthMiddleware,
674
+ createAuthorizeMiddleware,
675
+ createBodySizeLimitMiddleware,
676
+ createCorsMiddleware,
677
+ createCsrfMiddleware,
678
+ createFlashMiddleware,
679
+ createLoginThrottleMiddleware,
680
+ createMembershipMiddleware,
681
+ createMemoryThrottleMiddleware,
682
+ createMetricsMiddleware,
683
+ createRequestLoggingMiddleware,
684
+ createRequireAbilityMiddleware,
685
+ createRequireAuthMiddleware,
686
+ createRequireGlobalAdminMiddleware,
687
+ createRequireWebAuthMiddleware,
688
+ createSecurityHeadersMiddleware,
689
+ createTenantMiddleware,
690
+ createThrottleMiddleware,
691
+ createTracingMiddleware,
692
+ isPublicReadsEnabled,
693
+ requestIdMiddleware,
694
+ withMiddleware
695
+ } from "@getstrata/core";
696
+
697
+ // ../../src/config/rateLimit.ts
698
+ var LOCAL_LOGIN_RATE_LIMIT = {
699
+ maxAttempts: 100,
700
+ decaySeconds: 60
701
+ };
702
+ var PRODUCTION_LOGIN_RATE_LIMIT = {
703
+ maxAttempts: 5,
704
+ decaySeconds: 900
705
+ };
706
+ function isLocalAppEnv() {
707
+ return (process.env.APP_ENV ?? "local") === "local";
708
+ }
709
+ function parsePositiveInt(value, fallback) {
710
+ const parsed = Number(value);
711
+ if (!Number.isFinite(parsed) || parsed <= 0) {
712
+ return fallback;
713
+ }
714
+ return Math.trunc(parsed);
715
+ }
716
+ function resolveLoginRateLimit() {
717
+ const defaults = isLocalAppEnv() ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
718
+ return {
719
+ maxAttempts: parsePositiveInt(process.env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
720
+ decaySeconds: parsePositiveInt(process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, defaults.decaySeconds)
721
+ };
722
+ }
723
+ function resolveRegisterRateLimit() {
724
+ const defaults = isLocalAppEnv() ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
725
+ return {
726
+ maxAttempts: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
727
+ decaySeconds: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_WINDOW_SECONDS ?? process.env.REGISTER_RATE_LIMIT_WINDOW_MS ? String(Number(process.env.REGISTER_RATE_LIMIT_WINDOW_MS) / 1000) : undefined, defaults.decaySeconds)
728
+ };
729
+ }
730
+
731
+ // ../../src/bootstrap/httpKernel.ts
732
+ class HttpKernel {
733
+ dependencies;
734
+ constructor(dependencies) {
735
+ this.dependencies = dependencies;
736
+ }
737
+ globalMiddleware() {
738
+ const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
739
+ return [
740
+ createCorsMiddleware(),
741
+ createSecurityHeadersMiddleware(),
742
+ createBodySizeLimitMiddleware(),
743
+ createTracingMiddleware(),
744
+ createMetricsMiddleware(),
745
+ createRequestLoggingMiddleware(),
746
+ requestIdMiddleware,
747
+ createAuthMiddleware(auth),
748
+ createMembershipMiddleware(),
749
+ createTenantMiddleware()
750
+ ];
751
+ }
752
+ group(name) {
753
+ const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
754
+ switch (name) {
755
+ case "authenticated":
756
+ return [createRequireAuthMiddleware(auth)];
757
+ case "web":
758
+ return isViewsEnabled() ? [createFlashMiddleware(), createCsrfMiddleware()] : [];
759
+ case "api": {
760
+ if (!this.dependencies.container.has(CORE_CONFIG_TOKEN)) {
761
+ return [];
762
+ }
763
+ const config = this.dependencies.container.resolve(CORE_CONFIG_TOKEN);
764
+ const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim() ?? "";
765
+ if (!redisUrl) {
766
+ const maxAttempts2 = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
767
+ return [
768
+ createMemoryThrottleMiddleware({
769
+ maxAttempts: Number.isFinite(maxAttempts2) ? maxAttempts2 : 120,
770
+ decaySeconds: 60
771
+ })
772
+ ];
773
+ }
774
+ const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
775
+ return [
776
+ createThrottleMiddleware({
777
+ redisUrl,
778
+ maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
779
+ decaySeconds: 60
780
+ })
781
+ ];
782
+ }
783
+ default:
784
+ throw new Error(`Unknown middleware group "${name}".`);
785
+ }
786
+ }
787
+ wrap(groups, handler) {
788
+ const names = Array.isArray(groups) ? groups : [groups];
789
+ const middleware = names.flatMap((name) => this.group(name));
790
+ if (middleware.length === 0) {
791
+ return handler;
792
+ }
793
+ return withMiddleware(...middleware)(handler);
794
+ }
795
+ wrapApi(handler) {
796
+ return this.wrap(["api", "authenticated"], handler);
797
+ }
798
+ wrapWeb(handler) {
799
+ return handler;
800
+ }
801
+ wrapWebPublicRead(handler) {
802
+ if (isPublicReadsEnabled()) {
803
+ return this.wrapWeb(handler);
804
+ }
805
+ return this.wrapWebAuthenticated(handler);
806
+ }
807
+ wrapWebAuthenticated(handler) {
808
+ const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
809
+ return withMiddleware(createRequireWebAuthMiddleware(auth))(handler);
810
+ }
811
+ wrapWebAbility(ability, handler) {
812
+ const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
813
+ const abilityChecker = this.dependencies.container.resolve(CORE_TOKEN_SERVICE_TOKEN);
814
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker);
815
+ const middleware = [createRequireWebAuthMiddleware(auth), requireAbility(ability)];
816
+ return withMiddleware(...middleware)(handler);
817
+ }
818
+ wrapWebGlobalAdmin(handler) {
819
+ const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
820
+ const middleware = [createRequireWebAuthMiddleware(auth), createRequireGlobalAdminMiddleware()];
821
+ return withMiddleware(...middleware)(handler);
822
+ }
823
+ wrapAuthenticated(handler) {
824
+ return this.wrap("authenticated", handler);
825
+ }
826
+ wrapPublicRead(handler) {
827
+ if (isPublicReadsEnabled()) {
828
+ return handler;
829
+ }
830
+ return this.wrapAuthenticated(handler);
831
+ }
832
+ wrapGlobalAdmin(handler) {
833
+ const middleware = [...this.group("authenticated"), createRequireGlobalAdminMiddleware()];
834
+ return withMiddleware(...middleware)(handler);
835
+ }
836
+ wrapAbility(ability, handler) {
837
+ const abilityChecker = this.dependencies.container.resolve(CORE_TOKEN_SERVICE_TOKEN);
838
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker);
839
+ const middleware = [...this.group("authenticated"), requireAbility(ability)];
840
+ return withMiddleware(...middleware)(handler);
841
+ }
842
+ wrapPolicy(resource, action, handler) {
843
+ const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
844
+ const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
845
+ return withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler);
846
+ }
847
+ wrapLogin(handler) {
848
+ return this.wrapThrottle("login", resolveLoginRateLimit(), handler);
849
+ }
850
+ wrapRegister(handler) {
851
+ return this.wrapThrottle("register", resolveRegisterRateLimit(), handler);
852
+ }
853
+ wrapThrottle(scope, rateLimit, handler) {
854
+ const middleware = [];
855
+ const memoryKeyPrefix = scope === "login" ? "login-throttle:" : "register-throttle:";
856
+ if (this.dependencies.container.has(CORE_CONFIG_TOKEN)) {
857
+ const config = this.dependencies.container.resolve(CORE_CONFIG_TOKEN);
858
+ const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim() ?? "";
859
+ if (redisUrl) {
860
+ const throttle = scope === "login" ? createLoginThrottleMiddleware({
861
+ redisUrl,
862
+ maxAttempts: rateLimit.maxAttempts,
863
+ decaySeconds: rateLimit.decaySeconds
864
+ }) : createThrottleMiddleware({
865
+ redisUrl,
866
+ maxAttempts: rateLimit.maxAttempts,
867
+ decaySeconds: rateLimit.decaySeconds,
868
+ keyPrefix: memoryKeyPrefix
869
+ });
870
+ middleware.push(throttle);
871
+ } else {
872
+ middleware.push(createMemoryThrottleMiddleware({
873
+ maxAttempts: rateLimit.maxAttempts,
874
+ decaySeconds: rateLimit.decaySeconds,
875
+ keyPrefix: memoryKeyPrefix
876
+ }));
877
+ }
878
+ } else {
879
+ middleware.push(createMemoryThrottleMiddleware({
880
+ maxAttempts: rateLimit.maxAttempts,
881
+ decaySeconds: rateLimit.decaySeconds,
882
+ keyPrefix: memoryKeyPrefix
883
+ }));
884
+ }
885
+ if (middleware.length === 0) {
886
+ return handler;
887
+ }
888
+ return withMiddleware(...middleware)(handler);
889
+ }
890
+ }
891
+ function createHttpKernel(dependencies) {
892
+ return new HttpKernel(dependencies);
893
+ }
894
+
895
+ // ../../src/bootstrap/discoverModules.ts
896
+ import { readdirSync } from "fs";
897
+ import { join as join2 } from "path";
898
+ import { pathToFileURL } from "url";
899
+ async function loadDiscoveredModules() {
900
+ const modulesDirectory = join2(import.meta.dir, "../modules");
901
+ let moduleNames;
902
+ try {
903
+ moduleNames = readdirSync(modulesDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
904
+ } catch (error) {
905
+ if (error.code === "ENOENT") {
906
+ return [];
907
+ }
908
+ throw error;
909
+ }
910
+ const modules = await Promise.all(moduleNames.map(async (moduleName) => {
911
+ const moduleUrl = pathToFileURL(join2(modulesDirectory, moduleName, "index.ts")).href;
912
+ const loaded = await import(moduleUrl);
913
+ return loaded.default;
914
+ }));
915
+ return modules.filter((module) => module?.name !== undefined).sort((left, right) => (left.order ?? 100) - (right.order ?? 100));
916
+ }
917
+ var appModules = await loadDiscoveredModules();
918
+ // ../../src/bootstrap/routeRegistry.ts
919
+ class RouteRegistry {
920
+ routes = [];
921
+ register(route) {
922
+ this.routes.push(route);
923
+ }
924
+ clear() {
925
+ this.routes.length = 0;
926
+ }
927
+ list() {
928
+ return [...this.routes].sort((left, right) => left.path.localeCompare(right.path));
929
+ }
930
+ }
931
+ var routeRegistry = new RouteRegistry;
932
+
933
+ // ../../src/bootstrap/createWebRoutes.ts
934
+ function registerRoute(method, path, middleware) {
935
+ routeRegistry.register({ method, path, middleware });
936
+ }
937
+ function registerRouteMap(routes, middleware) {
938
+ const registered = {};
939
+ for (const [path, handler] of Object.entries(routes)) {
940
+ if (handler && typeof handler === "object" && !Array.isArray(handler)) {
941
+ const methodMap = handler;
942
+ registered[path] = methodMap;
943
+ for (const method of Object.keys(methodMap)) {
944
+ registerRoute(method.toUpperCase(), path, middleware);
945
+ }
946
+ continue;
947
+ }
948
+ registered[path] = handler;
949
+ registerRoute("GET", path, middleware);
950
+ }
951
+ return registered;
952
+ }
953
+ function createWebRoutes(dependencies) {
954
+ const kernel = createHttpKernel(dependencies);
955
+ const middleware = [...kernel.globalMiddleware(), ...kernel.group("web")];
956
+ const moduleRoutes = {
957
+ "/": () => Response.redirect("/organizations", 302)
958
+ };
959
+ registerRoute("GET", "/", ["global", "web"]);
960
+ for (const module of appModules) {
961
+ if (!module.webRoutes) {
962
+ continue;
963
+ }
964
+ Object.assign(moduleRoutes, module.webRoutes({
965
+ dependencies,
966
+ cachedJson: async () => htmlResponse(""),
967
+ kernel
968
+ }));
969
+ }
970
+ const wrappedRoutes = applyMiddlewareToRoutes(registerRouteMap(moduleRoutes, ["global", "web"]), middleware);
971
+ wrappedRoutes["/assets/*"] = async (request) => {
972
+ registerRoute("GET", "/assets/*", ["global", "web"]);
973
+ const pathname = new URL(request.url).pathname;
974
+ const relativePath = pathname.replace(/^\//, "");
975
+ const file = Bun.file(join3(process.cwd(), "public", relativePath));
976
+ if (!await file.exists()) {
977
+ return htmlResponse("Not Found", { status: 404 });
978
+ }
979
+ return new Response(file);
980
+ };
981
+ registerRoute("GET", "/assets/*", ["global", "web"]);
982
+ return wrappedRoutes;
983
+ }
984
+ function mergeWebRoutes(dependencies, routes) {
985
+ if (!isViewsEnabled()) {
986
+ return routes;
987
+ }
988
+ return {
989
+ ...createWebRoutes(dependencies),
990
+ ...routes
991
+ };
992
+ }
993
+ export {
994
+ mergeWebRoutes,
995
+ createWebRoutes
996
+ };