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