@getstrata/bootstrap 2.2.60 → 3.0.4

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 (90) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/bootstrap/app.d.ts +18 -7
  3. package/dist/bootstrap/buildModuleRoutes.d.ts +3 -5
  4. package/dist/bootstrap/buildWebModuleRoutes.d.ts +2 -3
  5. package/dist/bootstrap/cache/modelCacheTags.d.ts +3 -2
  6. package/dist/bootstrap/cachedJson.d.ts +7 -2
  7. package/dist/bootstrap/config.d.ts +1 -1
  8. package/dist/bootstrap/context.d.ts +25 -7
  9. package/dist/bootstrap/contracts.d.ts +1 -0
  10. package/dist/bootstrap/createWebRoutes.d.ts +2 -1
  11. package/dist/bootstrap/databaseReadiness.d.ts +3 -0
  12. package/dist/bootstrap/dependencies.d.ts +3 -2
  13. package/dist/bootstrap/discoverJobs.d.ts +3 -2
  14. package/dist/bootstrap/discoverListeners.d.ts +10 -7
  15. package/dist/bootstrap/discoverModels.d.ts +3 -2
  16. package/dist/bootstrap/discoverModules.d.ts +7 -6
  17. package/dist/bootstrap/health.d.ts +3 -2
  18. package/dist/bootstrap/http/securedRouteModelBinding.d.ts +1 -1
  19. package/dist/bootstrap/httpKernel.d.ts +43 -22
  20. package/dist/bootstrap/httpPersistence.d.ts +4 -0
  21. package/dist/bootstrap/inProcessCron.d.ts +5 -5
  22. package/dist/bootstrap/listeners/invalidateCacheOnModelWrite.d.ts +13 -12
  23. package/dist/bootstrap/metricsRoutes.d.ts +6 -1
  24. package/dist/bootstrap/moduleRouteMiddleware.d.ts +4 -4
  25. package/dist/bootstrap/modules.d.ts +1 -1
  26. package/dist/bootstrap/ownedHttpRoute.d.ts +23 -0
  27. package/dist/bootstrap/persistenceContracts.d.ts +70 -0
  28. package/dist/bootstrap/persistenceInvocation.d.ts +4 -0
  29. package/dist/bootstrap/providers/auth.d.ts +21 -0
  30. package/dist/bootstrap/providers/cache.d.ts +9 -3
  31. package/dist/bootstrap/providers/cacheProvider.d.ts +3 -0
  32. package/dist/bootstrap/providers/config.d.ts +6 -3
  33. package/dist/bootstrap/providers/events.d.ts +5 -2
  34. package/dist/bootstrap/providers/index.d.ts +3 -2
  35. package/dist/bootstrap/providers/listeners.d.ts +3 -3
  36. package/dist/bootstrap/providers/mail.d.ts +15 -0
  37. package/dist/bootstrap/providers/queue.d.ts +3 -2
  38. package/dist/bootstrap/providers/storage.d.ts +11 -2
  39. package/dist/bootstrap/providers/tracing.d.ts +4 -2
  40. package/dist/bootstrap/providers/view.d.ts +8 -5
  41. package/dist/bootstrap/public-api.d.ts +10 -7
  42. package/dist/bootstrap/queue/defaultJobs.d.ts +4 -2
  43. package/dist/bootstrap/rateLimit.d.ts +13 -3
  44. package/dist/bootstrap/routeCompiler.d.ts +20 -0
  45. package/dist/bootstrap/routeMetadata.d.ts +3 -3
  46. package/dist/bootstrap/routePlan.d.ts +11 -0
  47. package/dist/bootstrap/schedule.d.ts +11 -2
  48. package/dist/bootstrap/secretsGuard.d.ts +2 -3
  49. package/dist/bootstrap/web/routing.d.ts +6 -3
  50. package/dist/bootstrap/web/server.d.ts +14 -4
  51. package/dist/bootstrap/web/session.d.ts +23 -16
  52. package/dist/entries/buildModuleRoutes.js +602 -384
  53. package/dist/entries/buildWebModuleRoutes.js +596 -347
  54. package/dist/entries/cache/modelCacheTags.js +8 -186
  55. package/dist/entries/cachedJson.js +22 -0
  56. package/dist/entries/config.js +1 -3
  57. package/dist/entries/context.js +665 -700
  58. package/dist/entries/createSpaRoutes.js +194 -5
  59. package/dist/entries/createWebRoutes.js +618 -367
  60. package/dist/entries/databaseReadiness.js +267 -0
  61. package/dist/entries/dependencies.js +666 -701
  62. package/dist/entries/discoverJobs.js +18 -16
  63. package/dist/entries/discoverListeners.js +27 -38
  64. package/dist/entries/discoverModels.js +4 -3
  65. package/dist/entries/discoverModules.js +29 -67
  66. package/dist/entries/health.js +14 -34
  67. package/dist/entries/httpKernel.js +405 -89
  68. package/dist/entries/listeners/invalidateCacheOnModelWrite.js +43 -289
  69. package/dist/entries/metricsRoutes.js +9 -5
  70. package/dist/entries/persistenceContracts.js +1 -0
  71. package/dist/entries/persistenceInvocation.js +17 -0
  72. package/dist/entries/providers/auth.js +114 -0
  73. package/dist/entries/providers/cache.js +35 -0
  74. package/dist/entries/providers/events.js +55 -0
  75. package/dist/entries/providers/view.js +34 -44
  76. package/dist/entries/providers.js +392 -561
  77. package/dist/entries/queue/defaultJobs.js +9 -6
  78. package/dist/entries/routePlan.js +200 -0
  79. package/dist/entries/schedule.js +37 -37
  80. package/dist/entries/secretsGuard.js +10 -13
  81. package/dist/entries/web/routing.js +412 -96
  82. package/dist/entries/web/server.js +461 -29
  83. package/dist/entries/web/session.js +61 -73
  84. package/dist/index.js +1520 -1085
  85. package/dist/internal/ownedHttpRoute.js +66 -0
  86. package/package.json +52 -15
  87. package/dist/bootstrap/applicationRegistry.d.ts +0 -1
  88. package/dist/bootstrap/routeRegistry.d.ts +0 -10
  89. package/dist/entries/applicationRegistry.js +0 -24
  90. package/dist/entries/routeRegistry.js +0 -29
@@ -2,53 +2,27 @@
2
2
  // ../../src/bootstrap/web/session.ts
3
3
  import { createHmac, randomBytes } from "crypto";
4
4
  import { isAccountActive, matchesAuthVersion } from "@getstrata/core/auth/accountState";
5
- import { AuthManager } from "@getstrata/core/auth/guard";
6
- import { isSessionInvalidated } from "@getstrata/core/auth/sessionCookie";
7
- import { getBoundDatabaseConnection } from "@getstrata/core/database/boundConnection";
8
- import {
9
- getActiveDatabaseConnection,
10
- hasActiveDatabaseConnection
11
- } from "@getstrata/core/database/connectionContext";
12
5
  import {
13
- getDefaultDatabasePool,
14
- getDefaultDatabaseQuery
15
- } from "@getstrata/core/database/defaultConnection";
16
- import { currentSqlDialect, sqlTimestamp } from "@getstrata/core/database/dialect";
6
+ AuthManager,
7
+ authenticateProof,
8
+ authUserFromOutcome
9
+ } from "@getstrata/core/auth/guard";
10
+ import { isSessionInvalidated } from "@getstrata/core/auth/sessionCookie";
17
11
  import { UnauthorizedError } from "@getstrata/core/errors/http";
18
12
  import { readRequestCookie } from "@getstrata/core/http/cookies";
19
13
  import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
20
- import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
21
14
  import { timingSafeCompareString } from "@getstrata/core/security/timingSafeCompare";
22
- import { runWithMigrationBypassForIdentifier } from "@getstrata/core/tenant/databaseTenantContext";
23
- function sqlPlaceholder(index) {
24
- return currentSqlDialect().placeholder(index);
15
+ function sqlPlaceholder(sql, index) {
16
+ return sql.dialect.placeholder(index);
25
17
  }
26
- function sqlNow() {
27
- return currentSqlDialect().nowExpression();
18
+ function sqlNow(sql) {
19
+ return sql.dialect.nowExpression();
28
20
  }
29
- function isSqlClient(value) {
30
- return typeof value.unsafe === "function";
21
+ function executeSql(sql, text, params = []) {
22
+ return sql.execute({ text, params });
31
23
  }
32
- function resolveSql(source) {
33
- const client = isSqlClient(source) ? source : source();
34
- if (!hasActiveDatabaseConnection()) {
35
- return client;
36
- }
37
- try {
38
- if (client === getDefaultDatabasePool() || client === getDefaultDatabaseQuery()) {
39
- return getActiveDatabaseConnection(client);
40
- }
41
- } catch {
42
- return client;
43
- }
44
- return client;
45
- }
46
- function defaultSessionSql() {
47
- const bound = getBoundDatabaseConnection();
48
- if (bound) {
49
- return bound;
50
- }
51
- return getDefaultDatabasePool();
24
+ function identifier(sql, policy, productionRls, id, work) {
25
+ return productionRls ? policy.run(sql, { kind: "identifier", identifier: id }, work) : Promise.resolve(work(sql));
52
26
  }
53
27
  function defaultMapSessionUser(user) {
54
28
  return {
@@ -80,11 +54,11 @@ function mapSessionUserRow(row) {
80
54
  ...row.email_verified_at !== undefined ? { email_verified_at: row.email_verified_at } : {}
81
55
  };
82
56
  }
83
- async function defaultLoadSessionUser(sql, sessionId) {
84
- const sessionRows = await runWithMigrationBypassForIdentifier(sessionId, async () => {
85
- return await sql.unsafe(`SELECT *, created_at AS session_created_at
57
+ async function defaultLoadSessionUser(sql, policy, rls, sessionId) {
58
+ const sessionRows = await identifier(sql, policy, rls, sessionId, async (sql) => {
59
+ return await executeSql(sql, `SELECT *, created_at AS session_created_at
86
60
  FROM sessions
87
- WHERE id = ${sqlPlaceholder(1)} AND expires_at > ${sqlNow()}`, [sessionId]);
61
+ WHERE id = ${sqlPlaceholder(sql, 1)} AND expires_at > ${sqlNow(sql)}`, [sessionId]);
88
62
  });
89
63
  const session = sessionRows[0];
90
64
  if (!session)
@@ -93,10 +67,8 @@ async function defaultLoadSessionUser(sql, sessionId) {
93
67
  if (!Number.isInteger(userId) || userId <= 0) {
94
68
  return null;
95
69
  }
96
- return await runWithMigrationBypassForIdentifier(userId, async () => {
97
- const rows = await sql.unsafe(`SELECT * FROM users WHERE id = ${sqlPlaceholder(1)}`, [
98
- userId
99
- ]);
70
+ return await identifier(sql, policy, rls, userId, async (sql) => {
71
+ const rows = await executeSql(sql, `SELECT * FROM users WHERE id = ${sqlPlaceholder(sql, 1)}`, [userId]);
100
72
  const row = rows[0];
101
73
  if (!row)
102
74
  return null;
@@ -119,14 +91,18 @@ function redirectWithCookie(location, setCookie, status) {
119
91
  }
120
92
 
121
93
  class CookieSessionStore {
122
- sqlSource;
94
+ selected;
95
+ policy;
123
96
  secret;
97
+ config;
124
98
  cookieName;
125
99
  maxAgeSeconds;
126
100
  loadSessionUser;
127
- constructor(sqlSource, secret, cookieName = "strata_session", maxAgeSeconds = 60 * 60 * 24 * 14, loadSessionUser = defaultLoadSessionUser) {
128
- this.sqlSource = sqlSource;
101
+ constructor(selected, policy, secret, config, cookieName = "strata_session", maxAgeSeconds = 60 * 60 * 24 * 14, loadSessionUser = defaultLoadSessionUser) {
102
+ this.selected = selected;
103
+ this.policy = policy;
129
104
  this.secret = secret;
105
+ this.config = config;
130
106
  this.cookieName = cookieName;
131
107
  this.maxAgeSeconds = maxAgeSeconds;
132
108
  this.loadSessionUser = loadSessionUser;
@@ -138,6 +114,12 @@ class CookieSessionStore {
138
114
  clearCookieHeader() {
139
115
  return this.withSecureFlag(`${this.cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
140
116
  }
117
+ hasCredential(request) {
118
+ return readRequestCookie(request, this.cookieName) !== null || (request.headers.get("cookie")?.split(";").some((part) => {
119
+ const separator = part.indexOf("=");
120
+ return (separator === -1 ? part : part.slice(0, separator)).trim() === this.cookieName;
121
+ }) ?? false);
122
+ }
141
123
  sessionIdFromRequest(request) {
142
124
  const cookie = readRequestCookie(request, this.cookieName);
143
125
  const raw = cookie ?? null;
@@ -150,25 +132,22 @@ class CookieSessionStore {
150
132
  return sessionId;
151
133
  }
152
134
  withSecureFlag(header) {
153
- if (!isProductionEnv()) {
135
+ if (!this.config.production) {
154
136
  return header;
155
137
  }
156
138
  return header.includes("Secure") ? header : `${header}; Secure`;
157
139
  }
158
- sql() {
159
- return resolveSql(this.sqlSource);
160
- }
161
140
  async create(user, meta = {}) {
162
141
  if (!isAccountActive(user) || !matchesAuthVersion(user.auth_version, user.auth_version))
163
142
  throw new UnauthorizedError;
164
143
  const id = randomBytes(32).toString("hex");
165
144
  const expires = new Date(Date.now() + this.maxAgeSeconds * 1000);
166
- await runWithMigrationBypassForIdentifier(user.id, async () => {
167
- await this.sql().unsafe(`INSERT INTO sessions (id, user_id, expires_at, user_agent, ip_address, last_active_at, created_at${user.auth_version !== undefined ? ", auth_version" : ""})
168
- VALUES (${sqlPlaceholder(1)}, ${sqlPlaceholder(2)}, ${sqlPlaceholder(3)}, ${sqlPlaceholder(4)}, ${sqlPlaceholder(5)}, ${sqlNow()}, ${sqlNow()}${user.auth_version !== undefined ? `, ${sqlPlaceholder(6)}` : ""})`, [
145
+ await identifier(this.selected, this.policy, this.config.rls, user.id, async (sql) => {
146
+ await executeSql(sql, `INSERT INTO sessions (id, user_id, expires_at, user_agent, ip_address, last_active_at, created_at${user.auth_version !== undefined ? ", auth_version" : ""})
147
+ VALUES (${sqlPlaceholder(sql, 1)}, ${sqlPlaceholder(sql, 2)}, ${sqlPlaceholder(sql, 3)}, ${sqlPlaceholder(sql, 4)}, ${sqlPlaceholder(sql, 5)}, ${sqlNow(sql)}, ${sqlNow(sql)}${user.auth_version !== undefined ? `, ${sqlPlaceholder(sql, 6)}` : ""})`, [
169
148
  id,
170
149
  user.id,
171
- sqlTimestamp(expires),
150
+ sql.dialect.timestampValue(expires),
172
151
  meta.userAgent ?? null,
173
152
  meta.ipAddress ?? null,
174
153
  ...user.auth_version !== undefined ? [user.auth_version] : []
@@ -177,39 +156,41 @@ class CookieSessionStore {
177
156
  return id;
178
157
  }
179
158
  async destroy(sessionId) {
180
- await runWithMigrationBypassForIdentifier(sessionId, async () => {
181
- await this.sql().unsafe(`DELETE FROM sessions WHERE id = ${sqlPlaceholder(1)}`, [sessionId]);
159
+ await identifier(this.selected, this.policy, this.config.rls, sessionId, async (sql) => {
160
+ await executeSql(sql, `DELETE FROM sessions WHERE id = ${sqlPlaceholder(sql, 1)}`, [
161
+ sessionId
162
+ ]);
182
163
  });
183
164
  }
184
165
  async destroyAllSessions(userId) {
185
- await runWithMigrationBypassForIdentifier(userId, async () => {
186
- await this.sql().unsafe(`DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(1)}`, [
166
+ await identifier(this.selected, this.policy, this.config.rls, userId, async (sql) => {
167
+ await executeSql(sql, `DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(sql, 1)}`, [
187
168
  userId
188
169
  ]);
189
170
  });
190
171
  }
191
172
  async destroyOtherSessions(userId, keepSessionId) {
192
- await runWithMigrationBypassForIdentifier(userId, async () => {
193
- await this.sql().unsafe(`DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(1)} AND id <> ${sqlPlaceholder(2)}`, [userId, keepSessionId]);
173
+ await identifier(this.selected, this.policy, this.config.rls, userId, async (sql) => {
174
+ await executeSql(sql, `DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(sql, 1)} AND id <> ${sqlPlaceholder(sql, 2)}`, [userId, keepSessionId]);
194
175
  });
195
176
  }
196
177
  async listForUser(userId) {
197
- const dialect = currentSqlDialect();
198
- return await runWithMigrationBypassForIdentifier(userId, () => this.sql().unsafe(`SELECT id, user_id, user_agent, ip_address, last_active_at, expires_at
178
+ const dialect = this.selected.dialect;
179
+ return await identifier(this.selected, this.policy, this.config.rls, userId, (sql) => executeSql(sql, `SELECT id, user_id, user_agent, ip_address, last_active_at, expires_at
199
180
  FROM sessions
200
181
  WHERE user_id = ${dialect.placeholder(1)} AND expires_at > ${dialect.nowExpression()}
201
182
  ORDER BY last_active_at DESC${dialect.nullsLastSuffix()}, expires_at DESC`, [userId]));
202
183
  }
203
184
  async touch(sessionId) {
204
- await runWithMigrationBypassForIdentifier(sessionId, async () => {
205
- await this.sql().unsafe(`UPDATE sessions SET last_active_at = ${sqlNow()} WHERE id = ${sqlPlaceholder(1)}`, [sessionId]);
185
+ await identifier(this.selected, this.policy, this.config.rls, sessionId, async (sql) => {
186
+ await executeSql(sql, `UPDATE sessions SET last_active_at = ${sqlNow(sql)} WHERE id = ${sqlPlaceholder(sql, 1)}`, [sessionId]);
206
187
  });
207
188
  }
208
189
  async read(request) {
209
190
  const sessionId = this.sessionIdFromRequest(request);
210
191
  if (!sessionId)
211
192
  return null;
212
- const user = await this.loadSessionUser(this.sql(), sessionId);
193
+ const user = await this.loadSessionUser(this.selected, this.policy, this.config.rls, sessionId);
213
194
  return user && isAccountActive(user) ? user : null;
214
195
  }
215
196
  sign(value) {
@@ -224,7 +205,13 @@ class CookieSessionGuard {
224
205
  this.store = store;
225
206
  this.mapUser = mapUser;
226
207
  }
208
+ authenticate(request) {
209
+ return authenticateProof("session", () => this.store.hasCredential(request), () => this.resolveUser(request));
210
+ }
227
211
  async resolve(request) {
212
+ return authUserFromOutcome(await this.authenticate(request));
213
+ }
214
+ async resolveUser(request) {
228
215
  const user = await this.store.read(request);
229
216
  if (!user) {
230
217
  return null;
@@ -266,8 +253,10 @@ class CookieSessionAuthManager extends AuthManager {
266
253
  return redirectWithCookie(location, setCookie, status);
267
254
  }
268
255
  }
269
- function createCookieSessionAuthManager(options = {}) {
270
- const store = options.store ?? new CookieSessionStore(options.sql ?? defaultSessionSql, options.secret ?? process.env.SESSION_SECRET?.trim() ?? "", options.cookieName, options.maxAgeSeconds, options.loadSessionUser);
256
+ function createCookieSessionAuthManager(options) {
257
+ if (!options.secret)
258
+ throw new TypeError("An explicit session secret is required.");
259
+ const store = new CookieSessionStore(options.selected, options.policy, options.secret, { production: options.production, rls: options.rls }, options.cookieName, options.maxAgeSeconds, options.loadSessionUser);
271
260
  return new CookieSessionAuthManager(store, options.mapUser ?? defaultMapSessionUser);
272
261
  }
273
262
  export {
@@ -275,6 +264,5 @@ export {
275
264
  CookieSessionGuard,
276
265
  CookieSessionStore,
277
266
  createCookieSessionAuthManager,
278
- defaultMapSessionUser,
279
- defaultSessionSql
267
+ defaultMapSessionUser
280
268
  };