@getstrata/core 0.5.55 → 0.5.57

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 (118) hide show
  1. package/README.md +3 -1
  2. package/dist/{domain/abilities.d.ts → core/auth/abilityCatalog.d.ts} +9 -1
  3. package/dist/core/auth/accessControl.d.ts +1 -1
  4. package/dist/core/auth/membershipContext.d.ts +6 -4
  5. package/dist/core/auth/membershipService.d.ts +5 -6
  6. package/dist/core/contracts/authUserDirectory.d.ts +11 -0
  7. package/dist/core/contracts/membership.d.ts +20 -0
  8. package/dist/core/http/clientIp.d.ts +3 -0
  9. package/dist/core/jobs/dispatchWebhookJob.d.ts +2 -0
  10. package/dist/core/media/imageTransform.d.ts +13 -0
  11. package/dist/core/scheduler/osCron.d.ts +14 -0
  12. package/dist/core/tenant/tenancyConfig.d.ts +5 -0
  13. package/dist/core/tenant/tenantMiddleware.d.ts +1 -1
  14. package/dist/core/terminal/runShell.d.ts +6 -0
  15. package/dist/core/view/assertEtaHtmlSource.d.ts +5 -0
  16. package/dist/core/view/etaViewEngine.d.ts +4 -0
  17. package/dist/entries/audit/exportAuditLogs.js +2 -2
  18. package/dist/entries/audit/siemFormatter.js +2 -2
  19. package/dist/entries/auth/accessControl.js +4 -4
  20. package/dist/entries/auth/membershipMiddleware.js +21 -161
  21. package/dist/entries/auth/membershipScope.js +26 -166
  22. package/dist/entries/auth/membershipService.js +21 -161
  23. package/dist/entries/auth/oauth/providers.js +2 -2
  24. package/dist/entries/auth/password.js +2 -2
  25. package/dist/entries/auth/policy.js +2 -2
  26. package/dist/entries/auth/scimAuthMiddleware.js +22 -4
  27. package/dist/entries/auth/sessionCookie.js +4 -4
  28. package/dist/entries/auth/sessionGuard.js +12 -349
  29. package/dist/entries/auth/tokenHash.js +2 -2
  30. package/dist/entries/config/envSchema.js +2 -2
  31. package/dist/entries/contracts/container.js +2 -2
  32. package/dist/entries/contracts/di.js +2 -2
  33. package/dist/entries/contracts/serviceTokens.js +6 -6
  34. package/dist/entries/crypto/fieldEncryption.js +8 -8
  35. package/dist/entries/crypto/mfaSecret.js +2 -2
  36. package/dist/entries/database/errors.js +2 -2
  37. package/dist/entries/database/migrations.js +8 -8
  38. package/dist/entries/database/model.js +5 -5
  39. package/dist/entries/database/query.js +19 -19
  40. package/dist/entries/database/relationships.js +13 -13
  41. package/dist/entries/database/schema.js +13 -13
  42. package/dist/entries/database/seeders.js +2 -2
  43. package/dist/entries/facades.js +8 -8
  44. package/dist/entries/http/authMiddleware.js +2 -2
  45. package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
  46. package/dist/entries/http/clientIp.js +19 -0
  47. package/dist/entries/http/cookies.js +2 -2
  48. package/dist/entries/http/csrfMiddleware.js +2 -1
  49. package/dist/entries/http/csrfProtection.js +2 -2
  50. package/dist/entries/http/csrfToken.js +8 -7
  51. package/dist/entries/http/etag.js +8 -8
  52. package/dist/entries/http/flashSession.js +4 -4
  53. package/dist/entries/http/formRequest.js +2 -2
  54. package/dist/entries/http/loginThrottleMiddleware.js +20 -3
  55. package/dist/entries/http/memoryThrottleMiddleware.js +16 -1
  56. package/dist/entries/http/metricsMiddleware.js +2 -2
  57. package/dist/entries/http/pagination.js +4 -4
  58. package/dist/entries/http/parseFormBody.js +2 -2
  59. package/dist/entries/http/parseMultipartUpload.js +2 -2
  60. package/dist/entries/http/resources.js +2 -2
  61. package/dist/entries/http/response.js +214 -395
  62. package/dist/entries/http/scimThrottleMiddleware.js +40 -1
  63. package/dist/entries/http/securedRouteModelBinding.js +2 -2
  64. package/dist/entries/http/throttleMiddleware.js +20 -3
  65. package/dist/entries/http/validation.js +13 -13
  66. package/dist/entries/http/webErrorResponse.js +212 -393
  67. package/dist/entries/jobs/dispatchWebhookJob.js +111 -5
  68. package/dist/entries/lifecycle/gracefulShutdown.js +3 -3
  69. package/dist/entries/logging/logger.js +2 -2
  70. package/dist/entries/logging/requestLoggingMiddleware.js +16 -1
  71. package/dist/entries/mail/mailer.js +6 -6
  72. package/dist/entries/mail/markdownMail.js +3 -3
  73. package/dist/entries/mail/markdownMailable.js +2 -2
  74. package/dist/entries/media/imageTransform.js +40 -0
  75. package/dist/entries/metrics/prometheus.js +2 -2
  76. package/dist/entries/openapi/generator.js +2 -2
  77. package/dist/entries/queue/createAppQueue.js +4 -4
  78. package/dist/entries/queue/publicQueue.js +10 -10
  79. package/dist/entries/queue/queueMetrics.js +2 -2
  80. package/dist/entries/queue/redisQueue.js +7 -7
  81. package/dist/entries/queue.js +3 -3
  82. package/dist/entries/scheduler/osCron.js +27 -0
  83. package/dist/entries/scheduler/schedule.js +2 -2
  84. package/dist/entries/security/oauthState.js +3 -3
  85. package/dist/entries/security/publicReads.js +2 -2
  86. package/dist/entries/security/safeFetch.js +2 -2
  87. package/dist/entries/security/safeUrl.js +5 -5
  88. package/dist/entries/security/scimTenantTokens.js +3 -6
  89. package/dist/entries/security/totp.js +2 -2
  90. package/dist/entries/storage/storage.js +7 -7
  91. package/dist/entries/tenant/tenancyConfig.js +12 -0
  92. package/dist/entries/tenant/tenantDatabaseScope.js +13 -2
  93. package/dist/entries/terminal/runShell.js +18 -0
  94. package/dist/entries/validation/rules.js +12 -12
  95. package/dist/entries/view.js +212 -393
  96. package/dist/framework/public-api.d.ts +4 -1
  97. package/dist/index.js +2591 -2686
  98. package/package.json +27 -2
  99. package/dist/config/database.d.ts +0 -10
  100. package/dist/db/connection/createConnection.d.ts +0 -6
  101. package/dist/db/connection/index.d.ts +0 -11
  102. package/dist/domain/auth.d.ts +0 -4
  103. package/dist/domain/scim.d.ts +0 -9
  104. package/dist/modules/organization/memberRepository.d.ts +0 -14
  105. package/dist/modules/organization/memberTypes.d.ts +0 -9
  106. package/dist/modules/user/apiTokenRepository.d.ts +0 -8
  107. package/dist/modules/user/apiTokenTable.d.ts +0 -3
  108. package/dist/modules/user/authService.d.ts +0 -23
  109. package/dist/modules/user/notificationRepository.d.ts +0 -6
  110. package/dist/modules/user/notificationService.d.ts +0 -25
  111. package/dist/modules/user/notificationTable.d.ts +0 -3
  112. package/dist/modules/user/notificationTypes.d.ts +0 -12
  113. package/dist/modules/user/oauthIdentityRepository.d.ts +0 -9
  114. package/dist/modules/user/provider.d.ts +0 -11
  115. package/dist/modules/user/repository.d.ts +0 -13
  116. package/dist/modules/user/table.d.ts +0 -3
  117. package/dist/modules/user/tokenService.d.ts +0 -29
  118. package/dist/modules/user/types.d.ts +0 -46
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // ../../src/core/http/webErrorResponse.ts
3
- import { HttpError as HttpError2, UnauthorizedError as UnauthorizedError2, ValidationError } from "@getstrata/core/errors/http";
3
+ import { HttpError as HttpError2, UnauthorizedError, ValidationError } from "@getstrata/core/errors/http";
4
4
 
5
5
  // ../../src/config/frontend.ts
6
6
  function readFrontendMode() {
@@ -81,8 +81,183 @@ async function withDatabaseErrorHandling(operation) {
81
81
  }
82
82
 
83
83
  // ../../src/core/view/etaViewEngine.ts
84
- import { join } from "path";
84
+ import { join, relative } from "path";
85
85
  import { Eta } from "eta";
86
+
87
+ // ../../src/core/view/assertEtaHtmlSource.ts
88
+ var HTML_TAGS = new Set([
89
+ "a",
90
+ "abbr",
91
+ "address",
92
+ "article",
93
+ "aside",
94
+ "audio",
95
+ "b",
96
+ "blockquote",
97
+ "body",
98
+ "button",
99
+ "canvas",
100
+ "caption",
101
+ "cite",
102
+ "code",
103
+ "col",
104
+ "colgroup",
105
+ "data",
106
+ "datalist",
107
+ "dd",
108
+ "del",
109
+ "details",
110
+ "dfn",
111
+ "dialog",
112
+ "div",
113
+ "dl",
114
+ "dt",
115
+ "em",
116
+ "fieldset",
117
+ "figcaption",
118
+ "figure",
119
+ "footer",
120
+ "form",
121
+ "h1",
122
+ "h2",
123
+ "h3",
124
+ "h4",
125
+ "h5",
126
+ "h6",
127
+ "header",
128
+ "hgroup",
129
+ "hr",
130
+ "html",
131
+ "i",
132
+ "iframe",
133
+ "img",
134
+ "input",
135
+ "ins",
136
+ "kbd",
137
+ "label",
138
+ "legend",
139
+ "li",
140
+ "main",
141
+ "map",
142
+ "mark",
143
+ "menu",
144
+ "meter",
145
+ "nav",
146
+ "object",
147
+ "ol",
148
+ "optgroup",
149
+ "option",
150
+ "output",
151
+ "p",
152
+ "picture",
153
+ "pre",
154
+ "progress",
155
+ "q",
156
+ "rp",
157
+ "rt",
158
+ "ruby",
159
+ "s",
160
+ "samp",
161
+ "script",
162
+ "search",
163
+ "section",
164
+ "select",
165
+ "slot",
166
+ "small",
167
+ "source",
168
+ "span",
169
+ "strong",
170
+ "style",
171
+ "sub",
172
+ "summary",
173
+ "sup",
174
+ "table",
175
+ "tbody",
176
+ "td",
177
+ "template",
178
+ "textarea",
179
+ "tfoot",
180
+ "th",
181
+ "thead",
182
+ "time",
183
+ "title",
184
+ "tr",
185
+ "track",
186
+ "u",
187
+ "ul",
188
+ "var",
189
+ "video",
190
+ "wbr"
191
+ ]);
192
+ var TAG_PATTERN = "([a-z][a-z0-9]*)";
193
+ var CLASS_OR_ID_PATTERN = "[.#][\\w-]+";
194
+ var CLASS_ID_SHORTHAND = new RegExp(`^${TAG_PATTERN}(?:${CLASS_OR_ID_PATTERN})+`);
195
+ var ATTRIBUTE_SHORTHAND = new RegExp(`^${TAG_PATTERN}(?:${CLASS_OR_ID_PATTERN})*\\s+[\\w:-]+=`);
196
+ var TAG_SHORTHAND = new RegExp(`^${TAG_PATTERN}(?:>|\\s+\\S|$)`);
197
+ function htmlTagName(match) {
198
+ const tag = match?.[1];
199
+ return tag && HTML_TAGS.has(tag) ? tag : undefined;
200
+ }
201
+ function describePugLikeLine(line) {
202
+ if (/^\|(?:\s|$)/.test(line)) {
203
+ return "piped text";
204
+ }
205
+ if (htmlTagName(line.match(CLASS_ID_SHORTHAND))) {
206
+ return "class/id shorthand";
207
+ }
208
+ if (htmlTagName(line.match(ATTRIBUTE_SHORTHAND))) {
209
+ return "attribute shorthand";
210
+ }
211
+ if (htmlTagName(line.match(TAG_SHORTHAND))) {
212
+ return "tag shorthand";
213
+ }
214
+ return;
215
+ }
216
+ function updateSkipBlock(lower, skipBlock) {
217
+ if (skipBlock) {
218
+ if (skipBlock === "comment" && lower.includes("-->")) {
219
+ return null;
220
+ }
221
+ if (skipBlock !== "comment" && lower.includes(`</${skipBlock}`)) {
222
+ return null;
223
+ }
224
+ return skipBlock;
225
+ }
226
+ if (lower.startsWith("<!--") && !lower.includes("-->")) {
227
+ return "comment";
228
+ }
229
+ if (lower.startsWith("<script") && !lower.includes("</script")) {
230
+ return "script";
231
+ }
232
+ if (lower.startsWith("<style") && !lower.includes("</style")) {
233
+ return "style";
234
+ }
235
+ return null;
236
+ }
237
+ function assertEtaHtmlSource(templateName, source) {
238
+ let skipBlock = null;
239
+ for (const rawLine of source.split(/\r?\n/)) {
240
+ const trimmed = rawLine.trim();
241
+ if (!trimmed) {
242
+ continue;
243
+ }
244
+ const lower = trimmed.toLowerCase();
245
+ const nextSkipBlock = updateSkipBlock(lower, skipBlock);
246
+ if (skipBlock || nextSkipBlock) {
247
+ skipBlock = nextSkipBlock;
248
+ continue;
249
+ }
250
+ if (trimmed.startsWith("<") || trimmed.startsWith("<%")) {
251
+ continue;
252
+ }
253
+ const kind = describePugLikeLine(trimmed);
254
+ if (kind) {
255
+ throw new Error(`Eta view "${templateName}" contains Pug-like markup (${kind}: ${trimmed}). Eta views must be HTML + <% %> tags, not Pug.`);
256
+ }
257
+ }
258
+ }
259
+
260
+ // ../../src/core/view/etaViewEngine.ts
86
261
  var DEFAULT_VIEWS_DIRECTORY = join(process.cwd(), "resources/views");
87
262
  var DEFAULT_LAYOUT = "layouts/app.eta";
88
263
 
@@ -95,6 +270,12 @@ class EtaViewEngine {
95
270
  autoTrim: false
96
271
  });
97
272
  this.resolveLayoutData = resolveLayoutData;
273
+ const readFile = this.eta.readFile?.bind(this.eta);
274
+ this.eta.readFile = (path) => {
275
+ const source = readFile ? readFile(path) : "";
276
+ assertEtaHtmlSource(relative(viewsDirectory, path) || path, source);
277
+ return source;
278
+ };
98
279
  }
99
280
  async render(name, data = {}, options = {}) {
100
281
  const template = name.endsWith(".eta") ? name : `${name}.eta`;
@@ -129,391 +310,14 @@ function isHtmxRequest(request) {
129
310
  import { currentAuthUser } from "@getstrata/core/auth/authContext";
130
311
  import { currentRequestMeta as currentRequestMeta2 } from "@getstrata/core/http/requestMetaContext";
131
312
 
132
- // ../../src/bootstrap/config.ts
133
- import {
134
- CORE_AUTH_TOKEN,
135
- CORE_CACHE_TOKEN,
136
- CORE_CONFIG_TOKEN,
137
- CORE_EVENT_BUS_TOKEN,
138
- CORE_POLICY_GATE_TOKEN,
139
- CORE_QUEUE_TOKEN,
140
- CORE_TOKEN_SERVICE_TOKEN
141
- } from "@getstrata/core/contracts/serviceTokens";
142
- var DEFAULT_QUEUE_DRIVER = "sync";
143
-
144
- // ../../src/modules/user/provider.ts
145
- import { OidcProvider } from "@getstrata/core/auth/oauth/oidcProvider";
146
- import { GitHubOAuthProvider, MockOAuthProvider } from "@getstrata/core/auth/oauth/providers";
147
- import { SamlProvider } from "@getstrata/core/auth/oauth/samlProvider";
148
-
149
- // ../../src/config/features.ts
150
- function readFeatureFlags() {
151
- return {
152
- webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
153
- fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
154
- auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
155
- oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
156
- samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
157
- scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
158
- billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
159
- siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
160
- publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
161
- emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
162
- mfa: (process.env.FEATURE_MFA ?? "false") === "true"
163
- };
164
- }
165
- var featureFlags = readFeatureFlags();
166
- function isFeatureEnabled(feature) {
167
- return readFeatureFlags()[feature];
168
- }
169
-
170
- // ../../src/modules/user/apiTokenRepository.ts
171
- import { BaseRepository } from "@getstrata/core/database/baseRepository";
172
-
173
- // ../../src/config/database.ts
174
- function readInteger(name, fallback) {
175
- const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
176
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
177
- }
178
- var databaseConfig = {
179
- url: process.env.DATABASE_URL ?? "",
180
- poolMax: readInteger("DB_POOL_MAX", 10),
181
- idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
182
- maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
183
- connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
184
- };
185
-
186
- // ../../src/core/runtime/asyncContextStore.ts
187
- import { AsyncLocalStorage } from "async_hooks";
188
- function createAsyncContextStore(key) {
189
- const symbol = Symbol.for(key);
190
- const globalRecord = globalThis;
191
- const existing = globalRecord[symbol];
192
- if (existing) {
193
- return existing;
194
- }
195
- const store = new AsyncLocalStorage;
196
- globalRecord[symbol] = store;
197
- return store;
198
- }
199
-
200
- // ../../src/core/database/connectionContext.ts
201
- var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
202
- function runWithDatabaseConnection(connection, callback) {
203
- return activeConnection.run(connection, callback);
204
- }
205
- function getActiveDatabaseConnection(fallback) {
206
- return activeConnection.getStore() ?? fallback;
207
- }
208
- function hasActiveDatabaseConnection() {
209
- return activeConnection.getStore() !== undefined;
210
- }
211
-
212
- // ../../src/core/database/queryProxy.ts
213
- var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
214
- function createDatabaseQueryProxy(pool) {
215
- function resolveDatabase() {
216
- return getActiveDatabaseConnection(pool);
217
- }
218
- function resolveDatabaseForProperty(property) {
219
- if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
220
- return pool;
221
- }
222
- return resolveDatabase();
223
- }
224
- return new Proxy(function database() {}, {
225
- apply(_target, _thisArg, args) {
226
- return resolveDatabase()(...args);
227
- },
228
- get(_target, property) {
229
- const connection = resolveDatabaseForProperty(property);
230
- const value = connection[property];
231
- return typeof value === "function" ? value.bind(connection) : value;
232
- }
233
- });
234
- }
235
-
236
- // ../../src/core/database/defaultConnection.ts
237
- var defaultPool = {
238
- connection: null
239
- };
240
- var defaultQuery = {
241
- connection: null
242
- };
243
- function registerDefaultDatabasePool(connection) {
244
- defaultPool.connection = connection;
245
- defaultQuery.connection = createDatabaseQueryProxy(connection);
246
- }
247
- function getDefaultDatabaseQuery() {
248
- if (!defaultQuery.connection) {
249
- throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
250
- }
251
- return defaultQuery.connection;
252
- }
253
-
254
- // ../../src/db/connection/createConnection.ts
255
- var {SQL } = globalThis.Bun;
256
- function createDatabaseConnection(config) {
257
- if (!config.url) {
258
- throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
259
- }
260
- return new SQL({
261
- url: config.url,
262
- max: config.poolMax,
263
- idleTimeout: config.idleTimeoutSeconds,
264
- maxLifetime: config.maxLifetimeSeconds,
265
- connectionTimeout: config.connectionTimeoutSeconds
266
- });
267
- }
268
-
269
- // ../../src/db/connection/index.ts
270
- var connectionHolder = {
271
- connection: null
272
- };
273
- function getDatabase() {
274
- if (!connectionHolder.connection) {
275
- connectionHolder.connection = createDatabaseConnection(databaseConfig);
276
- registerDefaultDatabasePool(connectionHolder.connection);
277
- }
278
- return connectionHolder.connection;
279
- }
280
- function getDb() {
281
- getDatabase();
282
- return getDefaultDatabaseQuery();
283
- }
284
- var db = new Proxy(function database() {}, {
285
- apply(_target, _thisArg, args) {
286
- return getDb()(...args);
287
- },
288
- get(_target, property) {
289
- const connection = getDb();
290
- const value = connection[property];
291
- return typeof value === "function" ? value.bind(connection) : value;
292
- }
293
- });
294
- var connection_default = db;
295
-
296
- // ../../src/modules/user/apiTokenTable.ts
297
- import { defineTable } from "@getstrata/core/database/table";
298
- var apiTokenTable = defineTable({
299
- name: "api_token",
300
- primaryKey: "id",
301
- columns: [
302
- "id",
303
- "user_id",
304
- "name",
305
- "token_hash",
306
- "abilities",
307
- "last_used_at",
308
- "expires_at",
309
- "created_at"
310
- ],
311
- defaultOrderBy: { column: "id", direction: "ASC" }
312
- });
313
-
314
- // ../../src/modules/user/authService.ts
315
- import { verifyPassword } from "@getstrata/core/auth/password";
316
- import { revealMfaSecret } from "@getstrata/core/crypto/mfaSecret";
317
- import { UnauthorizedError } from "@getstrata/core/errors/http";
318
- import { logSecurityEvent } from "@getstrata/core/security/securityEvents";
319
- import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
320
- import { verifyTotp } from "@getstrata/core/security/totp";
321
- import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
322
-
323
- // ../../src/domain/abilities.ts
324
- var MEMBER_ABILITIES = [
325
- "organizations:read",
326
- "projects:read",
327
- "projects:create",
328
- "tasks:read",
329
- "tasks:create",
330
- "comments:read",
331
- "comments:create",
332
- "attachments:read",
333
- "attachments:create",
334
- "auth:tokens:read",
335
- "auth:tokens:write"
336
- ];
337
- var ADMIN_ABILITIES = [
338
- ...MEMBER_ABILITIES,
339
- "organizations:create",
340
- "organizations:update",
341
- "organizations:delete",
342
- "projects:update",
343
- "projects:delete",
344
- "tasks:update",
345
- "tasks:delete",
346
- "comments:update",
347
- "comments:delete",
348
- "attachments:delete",
349
- "webhooks:read",
350
- "webhooks:write",
351
- "audit:read"
352
- ];
353
- var PLATFORM_ADMIN_ABILITIES = ["*"];
354
- function resolveAbilitiesForRole(role) {
355
- if (role === "admin") {
356
- return [...PLATFORM_ADMIN_ABILITIES];
357
- }
358
- return [...MEMBER_ABILITIES];
359
- }
360
-
361
- // ../../src/modules/user/authService.ts
362
- class AuthService {
363
- users;
364
- tokens;
365
- oauthIdentities;
366
- oauthProviders = new Map;
367
- constructor(users, tokens, oauthIdentities) {
368
- this.users = users;
369
- this.tokens = tokens;
370
- this.oauthIdentities = oauthIdentities;
371
- }
372
- registerOAuthProvider(provider) {
373
- this.oauthProviders.set(provider.name, provider);
374
- }
375
- getOAuthProvider(name) {
376
- return this.oauthProviders.get(name);
377
- }
378
- async loginWithPassword(email, password, options = {}) {
379
- const user = await this.users.findByEmail(email);
380
- if (!user?.password_hash) {
381
- logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
382
- throw new UnauthorizedError("Invalid credentials.");
383
- }
384
- const valid = await verifyPassword(password, user.password_hash);
385
- if (!valid) {
386
- logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
387
- throw new UnauthorizedError("Invalid credentials.");
388
- }
389
- if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
390
- logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
391
- throw new UnauthorizedError("Email address is not verified.");
392
- }
393
- if (isFeatureEnabled("mfa") && user.mfa_enabled) {
394
- const mfaSecret = revealMfaSecret(user.mfa_secret);
395
- if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
396
- logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
397
- throw new UnauthorizedError("Invalid MFA code.");
398
- }
399
- }
400
- logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
401
- return await this.tokens.createToken(user.id, {
402
- name: "password-login",
403
- abilities: resolveAbilitiesForRole(user.role),
404
- expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
405
- });
406
- }
407
- async loginWithOAuth(providerName, code) {
408
- const provider = this.oauthProviders.get(providerName);
409
- if (!provider) {
410
- throw new UnauthorizedError("Unsupported OAuth provider.");
411
- }
412
- const profile = await provider.exchangeCode(code);
413
- const user = await this.findOrCreateOAuthUser(providerName, profile);
414
- logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
415
- return await this.tokens.createToken(user.id, {
416
- name: `${providerName}-oauth`,
417
- abilities: resolveAbilitiesForRole(user.role),
418
- expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
419
- });
420
- }
421
- buildOAuthAuthorizationUrl(providerName, state) {
422
- const provider = this.oauthProviders.get(providerName);
423
- if (!provider) {
424
- throw new UnauthorizedError("Unsupported OAuth provider.");
425
- }
426
- return provider.getAuthorizationUrl(state);
427
- }
428
- async findOrCreateOAuthUser(providerName, profile) {
429
- const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
430
- if (existingIdentity) {
431
- return await this.users.findByIdOrThrow(existingIdentity.user_id);
432
- }
433
- const existingUser = await this.users.findByEmail(profile.email);
434
- const user = existingUser ?? await this.users.create({
435
- name: profile.name,
436
- email: profile.email,
437
- role: "member",
438
- tenant_id: currentTenantId(),
439
- email_verified_at: new Date,
440
- created_at: new Date,
441
- updated_at: new Date
442
- });
443
- await this.oauthIdentities.create({
444
- user_id: user.id,
445
- provider: providerName,
446
- provider_user_id: profile.providerUserId,
447
- email: profile.email,
448
- created_at: new Date
449
- });
450
- return user;
451
- }
452
- }
453
-
454
- // ../../src/modules/user/notificationRepository.ts
455
- import { BaseRepository as BaseRepository2 } from "@getstrata/core/database/baseRepository";
456
-
457
- // ../../src/modules/user/notificationTable.ts
458
- import { defineTable as defineTable2 } from "@getstrata/core/database/table";
459
- var notificationTable = defineTable2({
460
- name: "notification",
461
- primaryKey: "id",
462
- columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
463
- defaultOrderBy: { column: "created_at", direction: "DESC" }
464
- });
465
-
466
- // ../../src/modules/user/notificationService.ts
467
- import { NotFoundError } from "@getstrata/core/errors/http";
468
-
469
- // ../../src/modules/user/oauthIdentityRepository.ts
470
- import { BaseRepository as BaseRepository3 } from "@getstrata/core/database/baseRepository";
471
- import { defineTable as defineTable3 } from "@getstrata/core/database/table";
472
- var oauthIdentityTable = defineTable3({
473
- name: "oauth_identity",
474
- primaryKey: "id",
475
- columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
476
- });
477
-
478
- // ../../src/modules/user/repository.ts
479
- import {
480
- emailLookupForQuery,
481
- protectEmail,
482
- revealEmail
483
- } from "@getstrata/core/crypto/fieldEncryption";
484
- import { revealMfaSecret as revealMfaSecret2 } from "@getstrata/core/crypto/mfaSecret";
485
- import { BaseRepository as BaseRepository4 } from "@getstrata/core/database/baseRepository";
486
- import { currentTenantId as currentTenantId2 } from "@getstrata/core/tenant/tenantContext";
487
-
488
- // ../../src/modules/user/table.ts
489
- import { defineTable as defineTable4 } from "@getstrata/core/database/table";
490
- var userTable = defineTable4({
491
- name: "users",
492
- primaryKey: "id",
493
- columns: [
494
- "id",
495
- "name",
496
- "email",
497
- "email_lookup",
498
- "role",
499
- "tenant_id",
500
- "password_hash",
501
- "email_verified_at",
502
- "mfa_secret",
503
- "mfa_enabled",
504
- "created_at",
505
- "updated_at"
506
- ],
507
- defaultOrderBy: { column: "id", direction: "ASC" }
508
- });
509
-
510
- // ../../src/modules/user/tokenService.ts
511
- import { hashApiToken } from "@getstrata/core/auth/tokenHash";
512
- import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core/errors/http";
513
- import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
514
-
515
- // ../../src/modules/user/provider.ts
516
- var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
313
+ // ../../src/core/contracts/serviceTokens.ts
314
+ var CORE_CONFIG_TOKEN = "core.config";
315
+ var CORE_CACHE_TOKEN = "core.cache";
316
+ var CORE_QUEUE_TOKEN = "core.queue";
317
+ var CORE_EVENT_BUS_TOKEN = "core.eventBus";
318
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
319
+ var CORE_AUTH_TOKEN = "core.auth";
320
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
517
321
 
518
322
  // ../../src/core/http/csrfToken.ts
519
323
  import { timingSafeEqual } from "crypto";
@@ -546,6 +350,20 @@ function readBunRequestCookie(request, name) {
546
350
  return request.cookies.get(name) ?? readRequestCookie(request, name);
547
351
  }
548
352
 
353
+ // ../../src/core/runtime/asyncContextStore.ts
354
+ import { AsyncLocalStorage } from "async_hooks";
355
+ function createAsyncContextStore(key) {
356
+ const symbol = Symbol.for(key);
357
+ const globalRecord = globalThis;
358
+ const existing = globalRecord[symbol];
359
+ if (existing) {
360
+ return existing;
361
+ }
362
+ const store = new AsyncLocalStorage;
363
+ globalRecord[symbol] = store;
364
+ return store;
365
+ }
366
+
549
367
  // ../../src/core/http/requestMetaContext.ts
550
368
  var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
551
369
  function runWithRequestMeta(meta, callback) {
@@ -577,9 +395,10 @@ function tokensMatch(left, right) {
577
395
  }
578
396
  function createCsrfTokenCookie() {
579
397
  const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
398
+ const secure = process.env.APP_ENV === "production" ? "; Secure" : "";
580
399
  return {
581
400
  token,
582
- cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
401
+ cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}${secure}`
583
402
  };
584
403
  }
585
404
  function resolveCsrfToken(request) {
@@ -747,7 +566,7 @@ async function resolveWebLayoutData(container, request) {
747
566
  if (!Number.isInteger(userId) || userId <= 0) {
748
567
  return { authUser: null, csrfToken, flash };
749
568
  }
750
- if (!container.has(tokenServiceToken)) {
569
+ if (!container.has(CORE_TOKEN_SERVICE_TOKEN)) {
751
570
  return {
752
571
  authUser: {
753
572
  id: userId,
@@ -758,7 +577,7 @@ async function resolveWebLayoutData(container, request) {
758
577
  flash
759
578
  };
760
579
  }
761
- const tokenService = container.resolve(tokenServiceToken);
580
+ const tokenService = container.resolve(CORE_TOKEN_SERVICE_TOKEN);
762
581
  try {
763
582
  const user = await tokenService.findByIdOrThrow(userId);
764
583
  return {
@@ -819,7 +638,7 @@ function webErrorResponse(error, request) {
819
638
  return null;
820
639
  }
821
640
  const mappedError = error instanceof HttpError2 ? error : mapDatabaseError(error);
822
- if (mappedError instanceof UnauthorizedError2) {
641
+ if (mappedError instanceof UnauthorizedError) {
823
642
  const redirectTarget = encodeURIComponent(new URL(request.url).pathname);
824
643
  return Response.redirect(`/login?redirect=${redirectTarget}`, 302);
825
644
  }
@@ -834,6 +653,6 @@ function webErrorResponse(error, request) {
834
653
  });
835
654
  }
836
655
  export {
837
- webErrorResponse,
838
- normalizeFieldErrors
656
+ normalizeFieldErrors,
657
+ webErrorResponse
839
658
  };