@getstrata/bootstrap 0.2.5 → 0.2.7

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 (40) hide show
  1. package/README.md +3 -1
  2. package/dist/bootstrap/contracts.d.ts +2 -0
  3. package/dist/bootstrap/httpKernel.d.ts +1 -2
  4. package/dist/bootstrap/middleware.d.ts +1 -1
  5. package/dist/bootstrap/providers/storage.d.ts +3 -0
  6. package/dist/bootstrap/scimRoutes.d.ts +1 -1
  7. package/dist/core/admin/registry.d.ts +1 -0
  8. package/dist/core/auth/membershipScope.d.ts +16 -0
  9. package/dist/core/auth/membershipService.d.ts +24 -0
  10. package/dist/core/database/baseRepository.d.ts +6 -1
  11. package/dist/core/database/connectionContext.d.ts +2 -1
  12. package/dist/core/database/defaultConnection.d.ts +6 -0
  13. package/dist/core/database/queryProxy.d.ts +3 -0
  14. package/dist/core/database/repositoryConnection.d.ts +3 -3
  15. package/dist/core/jobs/dispatchWebhookJob.d.ts +0 -1
  16. package/dist/core/queue/queueMetrics.d.ts +15 -0
  17. package/dist/core/security/safeFetch.d.ts +2 -0
  18. package/dist/core/security/safeUrl.d.ts +16 -1
  19. package/dist/core/storage/storage.d.ts +6 -3
  20. package/dist/core/tenant/tenantDatabaseScope.d.ts +2 -1
  21. package/dist/db/connection/index.d.ts +1 -1
  22. package/dist/domain/workhub.d.ts +35 -0
  23. package/dist/entries/applicationRegistry.js +185 -0
  24. package/dist/entries/config.js +42 -0
  25. package/dist/entries/context.js +4208 -0
  26. package/dist/entries/contracts.js +92 -0
  27. package/dist/entries/createWebRoutes.js +996 -0
  28. package/dist/entries/httpKernel.js +264 -0
  29. package/dist/entries/providers/view.js +635 -0
  30. package/dist/entries/providers.js +4094 -0
  31. package/dist/framework/public-api.d.ts +36 -4
  32. package/dist/index.js +328 -1046
  33. package/dist/modules/organization/repository.d.ts +14 -0
  34. package/dist/modules/organization/table.d.ts +3 -0
  35. package/dist/modules/organization/types.d.ts +10 -0
  36. package/dist/modules/scim/controller.d.ts +2 -1
  37. package/dist/modules/scim/scimResponse.d.ts +1 -1
  38. package/dist/modules/scim/service.d.ts +4 -7
  39. package/dist/modules/user/repository.d.ts +1 -0
  40. package/package.json +5 -4
@@ -0,0 +1,635 @@
1
+ // @bun
2
+ // ../../src/config/frontend.ts
3
+ function readFrontendMode() {
4
+ const mode = (process.env.FRONTEND_MODE ?? "api").trim();
5
+ if (mode === "server-htmx") {
6
+ return "server-htmx";
7
+ }
8
+ if (mode === "spa-react") {
9
+ return "spa-react";
10
+ }
11
+ return "api";
12
+ }
13
+ function isViewsEnabled() {
14
+ return readFrontendMode() === "server-htmx";
15
+ }
16
+
17
+ // ../../src/core/http/requestMetaContext.ts
18
+ import { AsyncLocalStorage } from "async_hooks";
19
+ var requestMetaContext = new AsyncLocalStorage;
20
+ function currentRequestMeta() {
21
+ return requestMetaContext.getStore() ?? {
22
+ ipAddress: null,
23
+ userAgent: null
24
+ };
25
+ }
26
+
27
+ // ../../src/core/view/etaViewEngine.ts
28
+ import { join } from "path";
29
+ import { Eta } from "eta";
30
+ var DEFAULT_VIEWS_DIRECTORY = join(process.cwd(), "resources/views");
31
+ var DEFAULT_LAYOUT = "layouts/app.eta";
32
+
33
+ class EtaViewEngine {
34
+ eta;
35
+ resolveLayoutData;
36
+ constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
37
+ this.eta = new Eta({
38
+ views: viewsDirectory,
39
+ autoTrim: false
40
+ });
41
+ this.resolveLayoutData = resolveLayoutData;
42
+ }
43
+ async render(name, data = {}, options = {}) {
44
+ const template = name.endsWith(".eta") ? name : `${name}.eta`;
45
+ const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
46
+ const mergedData = { ...layoutData, ...data };
47
+ const body = await this.eta.renderAsync(template, mergedData);
48
+ const layout = options.layout ?? DEFAULT_LAYOUT;
49
+ if (layout === false) {
50
+ return body;
51
+ }
52
+ const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
53
+ return await this.eta.renderAsync(layoutTemplate, {
54
+ ...mergedData,
55
+ body
56
+ });
57
+ }
58
+ }
59
+ // ../../src/core/view/htmlResponse.ts
60
+ function htmlResponse(html, init = {}) {
61
+ return new Response(html, {
62
+ status: init.status ?? 200,
63
+ statusText: init.statusText,
64
+ headers: {
65
+ "Content-Type": "text/html; charset=utf-8"
66
+ }
67
+ });
68
+ }
69
+ // ../../src/bootstrap/config.ts
70
+ var APP_PORT_CONFIG_KEY = "app.port";
71
+ var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
72
+ var CACHE_MAX_ENTRIES_CONFIG_KEY = "cache.maxEntries";
73
+ var CACHE_DRIVER_CONFIG_KEY = "cache.driver";
74
+ var REDIS_URL_CONFIG_KEY = "cache.redisUrl";
75
+ var DATABASE_URL_CONFIG_KEY = "database.url";
76
+ var CORE_CONFIG_TOKEN = "core.config";
77
+ var CORE_CACHE_TOKEN = "core.cache";
78
+ var CORE_QUEUE_TOKEN = "core.queue";
79
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
80
+ var CORE_AUTH_TOKEN = "core.auth";
81
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
82
+ var AUTH_DEV_HEADERS_CONFIG_KEY = "auth.allowDevHeaders";
83
+ var DEFAULT_APP_PORT = 3000;
84
+ var DEFAULT_CACHE_TTL_MS = 3600000;
85
+ var DEFAULT_CACHE_MAX_ENTRIES = 100;
86
+ var DEFAULT_CACHE_DRIVER = "array";
87
+ var DEFAULT_API_TOKEN = "";
88
+ var DEFAULT_QUEUE_DRIVER = "sync";
89
+
90
+ // ../../src/modules/user/provider.ts
91
+ import { OidcProvider } from "@getstrata/core/auth/oauth/oidcProvider";
92
+ import { GitHubOAuthProvider, MockOAuthProvider } from "@getstrata/core/auth/oauth/providers";
93
+ import { SamlProvider } from "@getstrata/core/auth/oauth/samlProvider";
94
+
95
+ // ../../src/config/features.ts
96
+ function readFeatureFlags() {
97
+ return {
98
+ webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
99
+ fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
100
+ auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
101
+ oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
102
+ samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
103
+ scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
104
+ billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
105
+ siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
106
+ publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
107
+ emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
108
+ mfa: (process.env.FEATURE_MFA ?? "false") === "true"
109
+ };
110
+ }
111
+ var featureFlags = readFeatureFlags();
112
+ function isFeatureEnabled(feature) {
113
+ return readFeatureFlags()[feature];
114
+ }
115
+
116
+ // ../../src/modules/user/apiTokenRepository.ts
117
+ import { BaseRepository } from "@getstrata/core/database";
118
+
119
+ // ../../src/config/database.ts
120
+ function readInteger(name, fallback) {
121
+ const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
122
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
123
+ }
124
+ var databaseConfig = {
125
+ url: process.env.DATABASE_URL ?? "",
126
+ poolMax: readInteger("DB_POOL_MAX", 10),
127
+ idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
128
+ maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
129
+ connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
130
+ };
131
+
132
+ // ../../src/core/database/connectionContext.ts
133
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
134
+ var activeConnection = new AsyncLocalStorage2;
135
+ function getActiveDatabaseConnection(fallback) {
136
+ return activeConnection.getStore() ?? fallback;
137
+ }
138
+
139
+ // ../../src/core/database/queryProxy.ts
140
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
141
+ function createDatabaseQueryProxy(pool) {
142
+ function resolveDatabase() {
143
+ return getActiveDatabaseConnection(pool);
144
+ }
145
+ function resolveDatabaseForProperty(property) {
146
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
147
+ return pool;
148
+ }
149
+ return resolveDatabase();
150
+ }
151
+ return new Proxy(function database() {}, {
152
+ apply(_target, _thisArg, args) {
153
+ return resolveDatabase()(...args);
154
+ },
155
+ get(_target, property) {
156
+ const connection = resolveDatabaseForProperty(property);
157
+ const value = connection[property];
158
+ return typeof value === "function" ? value.bind(connection) : value;
159
+ }
160
+ });
161
+ }
162
+
163
+ // ../../src/core/database/defaultConnection.ts
164
+ var defaultPool = {
165
+ connection: null
166
+ };
167
+ var defaultQuery = {
168
+ connection: null
169
+ };
170
+ function registerDefaultDatabasePool(connection) {
171
+ defaultPool.connection = connection;
172
+ defaultQuery.connection = createDatabaseQueryProxy(connection);
173
+ }
174
+ function getDefaultDatabaseQuery() {
175
+ if (!defaultQuery.connection) {
176
+ throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
177
+ }
178
+ return defaultQuery.connection;
179
+ }
180
+
181
+ // ../../src/db/connection/createConnection.ts
182
+ var {SQL } = globalThis.Bun;
183
+ function createDatabaseConnection(config) {
184
+ if (!config.url) {
185
+ throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
186
+ }
187
+ return new SQL({
188
+ url: config.url,
189
+ max: config.poolMax,
190
+ idleTimeout: config.idleTimeoutSeconds,
191
+ maxLifetime: config.maxLifetimeSeconds,
192
+ connectionTimeout: config.connectionTimeoutSeconds
193
+ });
194
+ }
195
+
196
+ // ../../src/db/connection/index.ts
197
+ var connectionHolder = {
198
+ connection: null
199
+ };
200
+ function getDatabase() {
201
+ if (!connectionHolder.connection) {
202
+ connectionHolder.connection = createDatabaseConnection(databaseConfig);
203
+ registerDefaultDatabasePool(connectionHolder.connection);
204
+ }
205
+ return connectionHolder.connection;
206
+ }
207
+ function getDb() {
208
+ getDatabase();
209
+ return getDefaultDatabaseQuery();
210
+ }
211
+ var db = new Proxy(function database() {}, {
212
+ apply(_target, _thisArg, args) {
213
+ return getDb()(...args);
214
+ },
215
+ get(_target, property) {
216
+ const connection = getDb();
217
+ const value = connection[property];
218
+ return typeof value === "function" ? value.bind(connection) : value;
219
+ }
220
+ });
221
+
222
+ // ../../src/modules/user/apiTokenTable.ts
223
+ import { defineTable } from "@getstrata/core/database";
224
+ var apiTokenTable = defineTable({
225
+ name: "api_token",
226
+ primaryKey: "id",
227
+ columns: [
228
+ "id",
229
+ "user_id",
230
+ "name",
231
+ "token_hash",
232
+ "abilities",
233
+ "last_used_at",
234
+ "expires_at",
235
+ "created_at"
236
+ ],
237
+ defaultOrderBy: { column: "id", direction: "ASC" }
238
+ });
239
+
240
+ // ../../src/modules/user/authService.ts
241
+ import { verifyPassword } from "@getstrata/core/auth/password";
242
+ import { revealMfaSecret } from "@getstrata/core/crypto/mfaSecret";
243
+ import { UnauthorizedError } from "@getstrata/core/errors/http";
244
+ import { logSecurityEvent } from "@getstrata/core/security/securityEvents";
245
+ import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
246
+ import { verifyTotp } from "@getstrata/core/security/totp";
247
+ import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
248
+
249
+ // ../../src/domain/abilities.ts
250
+ var MEMBER_ABILITIES = [
251
+ "organizations:read",
252
+ "projects:read",
253
+ "projects:create",
254
+ "tasks:read",
255
+ "tasks:create",
256
+ "comments:read",
257
+ "comments:create",
258
+ "attachments:read",
259
+ "attachments:create",
260
+ "auth:tokens:read",
261
+ "auth:tokens:write"
262
+ ];
263
+ var ADMIN_ABILITIES = [
264
+ ...MEMBER_ABILITIES,
265
+ "organizations:create",
266
+ "organizations:update",
267
+ "organizations:delete",
268
+ "projects:update",
269
+ "projects:delete",
270
+ "tasks:update",
271
+ "tasks:delete",
272
+ "comments:update",
273
+ "comments:delete",
274
+ "attachments:delete",
275
+ "webhooks:read",
276
+ "webhooks:write",
277
+ "audit:read"
278
+ ];
279
+ var PLATFORM_ADMIN_ABILITIES = ["*"];
280
+ function resolveAbilitiesForRole(role) {
281
+ if (role === "admin") {
282
+ return [...PLATFORM_ADMIN_ABILITIES];
283
+ }
284
+ return [...MEMBER_ABILITIES];
285
+ }
286
+
287
+ // ../../src/modules/user/authService.ts
288
+ class AuthService {
289
+ users;
290
+ tokens;
291
+ oauthIdentities;
292
+ oauthProviders = new Map;
293
+ constructor(users, tokens, oauthIdentities) {
294
+ this.users = users;
295
+ this.tokens = tokens;
296
+ this.oauthIdentities = oauthIdentities;
297
+ }
298
+ registerOAuthProvider(provider) {
299
+ this.oauthProviders.set(provider.name, provider);
300
+ }
301
+ getOAuthProvider(name) {
302
+ return this.oauthProviders.get(name);
303
+ }
304
+ async loginWithPassword(email, password, options = {}) {
305
+ const user = await this.users.findByEmail(email);
306
+ if (!user?.password_hash) {
307
+ logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
308
+ throw new UnauthorizedError("Invalid credentials.");
309
+ }
310
+ const valid = await verifyPassword(password, user.password_hash);
311
+ if (!valid) {
312
+ logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
313
+ throw new UnauthorizedError("Invalid credentials.");
314
+ }
315
+ if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
316
+ logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
317
+ throw new UnauthorizedError("Email address is not verified.");
318
+ }
319
+ if (isFeatureEnabled("mfa") && user.mfa_enabled) {
320
+ const mfaSecret = revealMfaSecret(user.mfa_secret);
321
+ if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
322
+ logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
323
+ throw new UnauthorizedError("Invalid MFA code.");
324
+ }
325
+ }
326
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
327
+ return await this.tokens.createToken(user.id, {
328
+ name: "password-login",
329
+ abilities: resolveAbilitiesForRole(user.role),
330
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
331
+ });
332
+ }
333
+ async loginWithOAuth(providerName, code) {
334
+ const provider = this.oauthProviders.get(providerName);
335
+ if (!provider) {
336
+ throw new UnauthorizedError("Unsupported OAuth provider.");
337
+ }
338
+ const profile = await provider.exchangeCode(code);
339
+ const user = await this.findOrCreateOAuthUser(providerName, profile);
340
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
341
+ return await this.tokens.createToken(user.id, {
342
+ name: `${providerName}-oauth`,
343
+ abilities: resolveAbilitiesForRole(user.role),
344
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
345
+ });
346
+ }
347
+ buildOAuthAuthorizationUrl(providerName, state) {
348
+ const provider = this.oauthProviders.get(providerName);
349
+ if (!provider) {
350
+ throw new UnauthorizedError("Unsupported OAuth provider.");
351
+ }
352
+ return provider.getAuthorizationUrl(state);
353
+ }
354
+ async findOrCreateOAuthUser(providerName, profile) {
355
+ const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
356
+ if (existingIdentity) {
357
+ return await this.users.findByIdOrThrow(existingIdentity.user_id);
358
+ }
359
+ const existingUser = await this.users.findByEmail(profile.email);
360
+ const user = existingUser ?? await this.users.create({
361
+ name: profile.name,
362
+ email: profile.email,
363
+ role: "member",
364
+ tenant_id: currentTenantId(),
365
+ email_verified_at: new Date,
366
+ created_at: new Date,
367
+ updated_at: new Date
368
+ });
369
+ await this.oauthIdentities.create({
370
+ user_id: user.id,
371
+ provider: providerName,
372
+ provider_user_id: profile.providerUserId,
373
+ email: profile.email,
374
+ created_at: new Date
375
+ });
376
+ return user;
377
+ }
378
+ }
379
+
380
+ // ../../src/modules/user/notificationRepository.ts
381
+ import { BaseRepository as BaseRepository2 } from "@getstrata/core/database";
382
+
383
+ // ../../src/modules/user/notificationTable.ts
384
+ import { defineTable as defineTable2 } from "@getstrata/core/database";
385
+ var notificationTable = defineTable2({
386
+ name: "notification",
387
+ primaryKey: "id",
388
+ columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
389
+ defaultOrderBy: { column: "created_at", direction: "DESC" }
390
+ });
391
+
392
+ // ../../src/modules/user/notificationService.ts
393
+ import { NotFoundError } from "@getstrata/core/errors/http";
394
+
395
+ // ../../src/modules/user/oauthIdentityRepository.ts
396
+ import { BaseRepository as BaseRepository3, defineTable as defineTable3 } from "@getstrata/core/database";
397
+ var oauthIdentityTable = defineTable3({
398
+ name: "oauth_identity",
399
+ primaryKey: "id",
400
+ columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
401
+ });
402
+
403
+ // ../../src/modules/user/repository.ts
404
+ import {
405
+ emailLookupForQuery,
406
+ protectEmail,
407
+ revealEmail
408
+ } from "@getstrata/core/crypto/fieldEncryption";
409
+ import { revealMfaSecret as revealMfaSecret2 } from "@getstrata/core/crypto/mfaSecret";
410
+ import { BaseRepository as BaseRepository4 } from "@getstrata/core/database";
411
+ import { currentTenantId as currentTenantId2 } from "@getstrata/core/tenant/tenantContext";
412
+
413
+ // ../../src/modules/user/table.ts
414
+ import { defineTable as defineTable4 } from "@getstrata/core/database";
415
+ var userTable = defineTable4({
416
+ name: "users",
417
+ primaryKey: "id",
418
+ columns: [
419
+ "id",
420
+ "name",
421
+ "email",
422
+ "email_lookup",
423
+ "role",
424
+ "tenant_id",
425
+ "password_hash",
426
+ "email_verified_at",
427
+ "mfa_secret",
428
+ "mfa_enabled",
429
+ "created_at",
430
+ "updated_at"
431
+ ],
432
+ defaultOrderBy: { column: "id", direction: "ASC" }
433
+ });
434
+
435
+ // ../../src/modules/user/tokenService.ts
436
+ import { hashApiToken } from "@getstrata/core/auth/tokenHash";
437
+ import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core/errors/http";
438
+ import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
439
+
440
+ // ../../src/modules/user/provider.ts
441
+ var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
442
+
443
+ // ../../src/core/auth/authContext.ts
444
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
445
+ var authContext = new AsyncLocalStorage3;
446
+ function currentAuthUser() {
447
+ return authContext.getStore() ?? null;
448
+ }
449
+
450
+ // ../../src/core/http/cookies.ts
451
+ function readRequestCookie(request, name) {
452
+ const cookies = request.cookies;
453
+ if (cookies && typeof cookies.get === "function") {
454
+ const value = cookies.get(name);
455
+ if (value) {
456
+ return value;
457
+ }
458
+ }
459
+ const header = request.headers.get("cookie");
460
+ if (!header) {
461
+ return null;
462
+ }
463
+ for (const part of header.split(";")) {
464
+ const idx = part.indexOf("=");
465
+ if (idx === -1)
466
+ continue;
467
+ const cookieName = part.slice(0, idx).trim();
468
+ if (cookieName !== name)
469
+ continue;
470
+ return decodeURIComponent(part.slice(idx + 1).trim());
471
+ }
472
+ return null;
473
+ }
474
+
475
+ // ../../src/core/http/csrfToken.ts
476
+ var CSRF_COOKIE = "workhub_csrf";
477
+ var CSRF_TTL_MS = 60 * 60 * 1000;
478
+ function resolveCsrfSecret() {
479
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
480
+ }
481
+ function csrfVerifyOptions() {
482
+ return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
483
+ }
484
+ function createCsrfTokenCookie() {
485
+ const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
486
+ return {
487
+ token,
488
+ cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
489
+ };
490
+ }
491
+ function resolveCsrfToken(request) {
492
+ const cookieValue = readRequestCookie(request, CSRF_COOKIE);
493
+ if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
494
+ return { token: cookieValue };
495
+ }
496
+ return createCsrfTokenCookie();
497
+ }
498
+ function resolveCsrfTokenForRequest(request) {
499
+ const metaToken = currentRequestMeta().csrfToken;
500
+ if (metaToken) {
501
+ return metaToken;
502
+ }
503
+ return resolveCsrfToken(request).token;
504
+ }
505
+
506
+ // ../../src/core/http/flashSession.ts
507
+ import { createHmac, timingSafeEqual } from "crypto";
508
+ var FLASH_COOKIE = "workhub_flash";
509
+ var FLASH_TTL_MS = 60 * 1000;
510
+ function resolveFlashSecret() {
511
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
512
+ }
513
+ function signFlashPayload(payload, issuedAt) {
514
+ const signature = createHmac("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
515
+ return `${payload}.${issuedAt}.${signature}`;
516
+ }
517
+ function readFlashCookie(request) {
518
+ const cookieHeader = request.headers.get("cookie");
519
+ if (!cookieHeader) {
520
+ return null;
521
+ }
522
+ for (const part of cookieHeader.split(";")) {
523
+ const [name, ...rest] = part.trim().split("=");
524
+ if (name === FLASH_COOKIE) {
525
+ return decodeURIComponent(rest.join("="));
526
+ }
527
+ }
528
+ return null;
529
+ }
530
+ function parseFlashCookie(cookieValue) {
531
+ const parts = cookieValue.split(".");
532
+ if (parts.length < 3) {
533
+ return null;
534
+ }
535
+ const signature = parts.pop();
536
+ const issuedAtRaw = parts.pop();
537
+ const payload = parts.join(".");
538
+ if (!signature || !issuedAtRaw || !payload) {
539
+ return null;
540
+ }
541
+ const issuedAt = Number.parseInt(issuedAtRaw, 10);
542
+ if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
543
+ return null;
544
+ }
545
+ const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
546
+ if (!expectedSignature) {
547
+ return null;
548
+ }
549
+ const expectedBuffer = Buffer.from(expectedSignature);
550
+ const actualBuffer = Buffer.from(signature);
551
+ if (expectedBuffer.length !== actualBuffer.length) {
552
+ return null;
553
+ }
554
+ if (!timingSafeEqual(expectedBuffer, actualBuffer)) {
555
+ return null;
556
+ }
557
+ try {
558
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
559
+ if (!parsed?.message || typeof parsed.message !== "string") {
560
+ return null;
561
+ }
562
+ if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
563
+ return null;
564
+ }
565
+ return parsed;
566
+ } catch {
567
+ return null;
568
+ }
569
+ }
570
+ function pullFlash(request) {
571
+ const cookieValue = readFlashCookie(request);
572
+ if (!cookieValue) {
573
+ return null;
574
+ }
575
+ return parseFlashCookie(cookieValue);
576
+ }
577
+
578
+ // ../../src/core/view/webLayoutData.ts
579
+ async function resolveWebLayoutData(container, request) {
580
+ const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
581
+ const flash = request ? currentRequestMeta().flash ?? pullFlash(request) : null;
582
+ const authUser = currentAuthUser();
583
+ if (!authUser) {
584
+ return { authUser: null, csrfToken, flash };
585
+ }
586
+ const userId = Number(authUser.id);
587
+ if (!Number.isInteger(userId) || userId <= 0) {
588
+ return { authUser: null, csrfToken, flash };
589
+ }
590
+ if (!container.has(tokenServiceToken)) {
591
+ return {
592
+ authUser: {
593
+ id: userId,
594
+ email: "",
595
+ role: authUser.role ?? "member"
596
+ },
597
+ csrfToken,
598
+ flash
599
+ };
600
+ }
601
+ const tokenService = container.resolve(tokenServiceToken);
602
+ try {
603
+ const user = await tokenService.findByIdOrThrow(userId);
604
+ return {
605
+ authUser: {
606
+ id: userId,
607
+ email: user.email ?? "",
608
+ role: authUser.role ?? user.role ?? "member"
609
+ },
610
+ csrfToken,
611
+ flash
612
+ };
613
+ } catch {
614
+ return { authUser: null, csrfToken, flash };
615
+ }
616
+ }
617
+ // ../../src/bootstrap/providers/view.ts
618
+ var CORE_VIEW_TOKEN = "core.view";
619
+ var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
620
+ var viewProvider = {
621
+ name: "view",
622
+ register({ container, config }) {
623
+ if (!isViewsEnabled()) {
624
+ return;
625
+ }
626
+ const viewsDirectory = process.env.VIEW_DIRECTORY?.trim() || DEFAULT_VIEWS_DIRECTORY;
627
+ config.set(VIEW_DIRECTORY_CONFIG_KEY, viewsDirectory);
628
+ container.set(CORE_VIEW_TOKEN, new EtaViewEngine(viewsDirectory, () => resolveWebLayoutData(container, currentRequestMeta().request)));
629
+ }
630
+ };
631
+ export {
632
+ viewProvider,
633
+ VIEW_DIRECTORY_CONFIG_KEY,
634
+ CORE_VIEW_TOKEN
635
+ };