@getstrata/bootstrap 0.2.28 → 0.2.29

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