create-strata 2.2.32 → 2.2.34

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.
package/dist/cli.js CHANGED
@@ -1154,55 +1154,15 @@ async function resolveStarterPlan(flags, injected) {
1154
1154
 
1155
1155
  // ../strata-starter/src/renderAuthFlows.ts
1156
1156
  function renderPendingMfaTs() {
1157
- return `import { createHmac, timingSafeEqual } from "node:crypto";
1157
+ return `import { createPendingMfaCookie, clearPendingMfaCookie, readPendingMfaCookie } from "@getstrata/core/auth/pendingMfaCookie";
1158
1158
  import { sessionSecret } from "./config.ts";
1159
1159
 
1160
- const COOKIE = "strata_mfa_pending";
1161
-
1162
- function sign(userId: number, issuedAt: number): string {
1163
- const payload = \`\${userId}.\${issuedAt}\`;
1164
- const signature = createHmac("sha256", sessionSecret()).update(payload).digest("hex");
1165
- return \`\${payload}.\${signature}\`;
1160
+ export function pendingMfaSetCookie(userId: number, authVersion: number): string {
1161
+ return createPendingMfaCookie(userId, authVersion, sessionSecret());
1166
1162
  }
1167
-
1168
- export function pendingMfaSetCookie(userId: number): string {
1169
- const issuedAt = Date.now();
1170
- const secure = process.env.APP_ENV === "production" || process.env.APP_ENV === "staging" ? "; Secure" : "";
1171
- return \`\${COOKIE}=\${sign(userId, issuedAt)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600\${secure}\`;
1172
- }
1173
-
1174
- export function pendingMfaClearCookie(): string {
1175
- const secure = process.env.APP_ENV === "production" || process.env.APP_ENV === "staging" ? "; Secure" : "";
1176
- return \`\${COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0\${secure}\`;
1177
- }
1178
-
1179
- export function readPendingMfaUserId(request: Request): number | null {
1180
- const header = request.headers.get("cookie") ?? "";
1181
- for (const part of header.split(";")) {
1182
- const [name, ...rest] = part.trim().split("=");
1183
- if (name !== COOKIE) {
1184
- continue;
1185
- }
1186
- const value = rest.join("=");
1187
- const pieces = value.split(".");
1188
- if (pieces.length !== 3) {
1189
- return null;
1190
- }
1191
- const userId = Number.parseInt(pieces[0] ?? "", 10);
1192
- const issuedAt = Number.parseInt(pieces[1] ?? "", 10);
1193
- const signature = pieces[2] ?? "";
1194
- if (!Number.isInteger(userId) || userId <= 0 || Date.now() - issuedAt > 10 * 60 * 1000) {
1195
- return null;
1196
- }
1197
- const expected = sign(userId, issuedAt).split(".").pop() ?? "";
1198
- const left = Buffer.from(signature);
1199
- const right = Buffer.from(expected);
1200
- if (left.length !== right.length || !timingSafeEqual(left, right)) {
1201
- return null;
1202
- }
1203
- return userId;
1204
- }
1205
- return null;
1163
+ export const pendingMfaClearCookie = clearPendingMfaCookie;
1164
+ export function readPendingMfaChallenge(request: Request) {
1165
+ return readPendingMfaCookie(request, sessionSecret());
1206
1166
  }
1207
1167
  `;
1208
1168
  }
@@ -1289,7 +1249,7 @@ function renderAuthModule(layers) {
1289
1249
  imports.push(`import { currentTenantId } from "@getstrata/core/tenant/tenantContext";`);
1290
1250
  }
1291
1251
  imports.push(`import { runWithMigrationBypassForIdentifier } from "@getstrata/core/tenant/databaseTenantContext";`);
1292
- imports.push(`import { starterAuthDirectory } from "../../bootstrap/authDirectory.ts";`);
1252
+ imports.push(`import { starterAuthDirectory, runWithLockedAuthUser, type StarterAuthUserRecord } from "../../bootstrap/authDirectory.ts";`);
1293
1253
  imports.push(`import { getSql } from "../../bootstrap/database.ts";`);
1294
1254
  imports.push(`import { User } from "../../models/User.ts";`);
1295
1255
  imports.push(`import { AuthOneTimeToken } from "../../models/AuthOneTimeToken.ts";`);
@@ -1300,7 +1260,7 @@ function renderAuthModule(layers) {
1300
1260
  imports.push(`import { CORE_VIEW_RENDERER_TOKEN } from "@getstrata/core/view";`);
1301
1261
  }
1302
1262
  if (mfa) {
1303
- imports.push(`import { pendingMfaClearCookie, pendingMfaSetCookie, readPendingMfaUserId } from "../../bootstrap/pendingMfa.ts";`);
1263
+ imports.push(`import { pendingMfaClearCookie, pendingMfaSetCookie, readPendingMfaChallenge } from "../../bootstrap/pendingMfa.ts";`);
1304
1264
  }
1305
1265
  const helpers = `
1306
1266
  function parseLoginCredentials(payload: unknown) {
@@ -1336,6 +1296,15 @@ function parseForgotPasswordEmail(payload: unknown) {
1336
1296
  return String(body.email).toLowerCase();
1337
1297
  }
1338
1298
 
1299
+ async function runWithLoginUser<T>(email: string, operation: (record: StarterAuthUserRecord | null) => Promise<T>): Promise<T> {
1300
+ const candidate = await starterAuthDirectory.findByEmail(email);
1301
+ if (!candidate) return operation(null);
1302
+ return runWithLockedAuthUser(candidate.id, async (record) => {
1303
+ // Recheck identity after locking: provisioning may have changed the email.
1304
+ return operation(record?.email === email.trim().toLowerCase() ? record : null);
1305
+ });
1306
+ }
1307
+
1339
1308
  async function runAuthWrite<T>(identifier: string | number, callback: () => Promise<T>): Promise<T> {
1340
1309
  return await runWithMigrationBypassForIdentifier(identifier, callback);
1341
1310
  }
@@ -1369,7 +1338,7 @@ async function consumeSignedAuthToken(request: Request, purpose: string): Promis
1369
1338
 
1370
1339
  async function revokeUserSessions(userId: number) {
1371
1340
  await runAuthWrite(userId, async () => {
1372
- await revokeStoredUserSessions(getSql(), userId);
1341
+ await revokeStoredUserSessions(getSql(), userId, { incrementAuthVersion: true });
1373
1342
  });
1374
1343
  }
1375
1344
 
@@ -1394,10 +1363,10 @@ async function completeSignedPasswordReset(request: Request, password: unknown):
1394
1363
  const userId = await consumeSignedAuthToken(request, AUTH_ONE_TIME_PURPOSES.passwordReset);
1395
1364
  if (!userId) return false;
1396
1365
  await runAuthWrite(userId, async () => {
1397
- const user = await User.find(userId);
1366
+ const user = await User.where({ id: userId })${layers.database === "sqlite" ? "" : ".lockForUpdate()"}.first();
1398
1367
  if (!user) throw new Error("Reset account no longer exists.");
1399
1368
  await user.update({ password: await hashPassword(password) });
1400
- await revokeStoredUserSessions(getSql(), userId);
1369
+ await revokeStoredUserSessions(getSql(), userId, { incrementAuthVersion: true });
1401
1370
  });
1402
1371
  return true;
1403
1372
  });
@@ -1417,12 +1386,14 @@ function redirectTo(path: string, status = 302): Response {
1417
1386
  return new Response(null, { status, headers: { location: path } });
1418
1387
  }
1419
1388
 
1420
- function sessionUser(user: { id: number; name?: string | null; email?: string | null; role: string }) {
1389
+ function sessionUser(user: StarterAuthUserRecord) {
1421
1390
  return {
1422
1391
  id: user.id,
1423
1392
  name: user.name ?? user.email ?? "",
1424
1393
  email: user.email ?? "",
1425
1394
  is_admin: user.role === "admin",
1395
+ is_active: user.is_active,
1396
+ auth_version: user.auth_version,
1426
1397
  };
1427
1398
  }
1428
1399
 
@@ -1455,20 +1426,23 @@ async function completeBrowserSsoLogin(
1455
1426
  if (!record) {
1456
1427
  return jsonResponse({ error: \`Could not complete \${label} login.\` }, { status: 500 });
1457
1428
  }
1429
+ return runWithLockedAuthUser(record.id, async (record) => {
1430
+ if (!record?.is_active || record.email !== email) return jsonResponse({ error: "Account unavailable." }, { status: 403 });
1458
1431
  ${mfa ? `if (record.mfa_enabled) {
1459
1432
  const pending = redirectTo("/login/mfa");
1460
- pending.headers.append("set-cookie", pendingMfaSetCookie(record.id));
1433
+ pending.headers.append("set-cookie", pendingMfaSetCookie(record.id, record.auth_version));
1461
1434
  return pending;
1462
1435
  }
1463
1436
  ` : ""}const auth = dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN);
1464
1437
  return auth.signInRedirect(sessionUser(record), "/");
1438
+ });
1465
1439
  }
1466
1440
  ` : ""}`;
1467
1441
  const tokenLogin = authUsesToken(layers.auth) ? `
1468
1442
  "/api/v1/auth/login": {
1469
1443
  POST: kernel.wrap("api", kernel.wrapLogin(withErrorHandling(async (request) => {
1470
1444
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1471
- const record = await starterAuthDirectory.findByEmail?.(email);
1445
+ return runWithLoginUser(email, async (record) => {
1472
1446
  if (!record?.password || !(await verifyPassword(password, record.password))) {
1473
1447
  return jsonResponse({ error: "Invalid credentials" }, { status: 422 });
1474
1448
  }
@@ -1498,6 +1472,7 @@ async function completeBrowserSsoLogin(
1498
1472
  const { setCookie } = await sessionAuth.signIn(sessionUser(record));
1499
1473
  payload.headers.append("set-cookie", setCookie);
1500
1474
  ` : ""}return payload;
1475
+ });
1501
1476
  }))),
1502
1477
  },
1503
1478
  "/api/v1/auth/me": {
@@ -1544,7 +1519,7 @@ async function completeBrowserSsoLogin(
1544
1519
  "/api/auth/token": {
1545
1520
  POST: kernel.wrap("api", kernel.wrapLogin(withErrorHandling(async (request) => {
1546
1521
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1547
- const record = await starterAuthDirectory.findByEmail?.(email);
1522
+ return runWithLoginUser(email, async (record) => {
1548
1523
  if (!record?.password || !(await verifyPassword(password, record.password))) {
1549
1524
  return jsonResponse({ error: "Invalid credentials" }, { status: 422 });
1550
1525
  }
@@ -1556,6 +1531,7 @@ async function completeBrowserSsoLogin(
1556
1531
  const user = { id: record.id, role: record.role, emailVerifiedAt: record.email_verified_at ?? null };
1557
1532
  const token = signJwt({
1558
1533
  sub: user.id,
1534
+ authVersion: record.auth_version,
1559
1535
  role: user.role,
1560
1536
  abilities: [],${verify ? `
1561
1537
  emailVerifiedAt: user.emailVerifiedAt ?? null,` : ""}
@@ -1565,6 +1541,7 @@ async function completeBrowserSsoLogin(
1565
1541
  token_type: "bearer",
1566
1542
  expires_in: jwtTtlSeconds(),
1567
1543
  });
1544
+ });
1568
1545
  }))),
1569
1546
  },` : "";
1570
1547
  const apiUser = jsonApi ? `
@@ -1623,7 +1600,7 @@ async function completeBrowserSsoLogin(
1623
1600
  "/api/v1/auth/login": {
1624
1601
  POST: kernel.wrap("api", kernel.wrapLogin(withErrorHandling(async (request) => {
1625
1602
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1626
- const record = await starterAuthDirectory.findByEmail?.(email);
1603
+ return runWithLoginUser(email, async (record) => {
1627
1604
  if (!record?.password || !(await verifyPassword(password, record.password))) {
1628
1605
  return jsonResponse({ error: "Invalid credentials" }, { status: 422 });
1629
1606
  }
@@ -1637,6 +1614,7 @@ async function completeBrowserSsoLogin(
1637
1614
  const payload = jsonResponse({ ok: true });
1638
1615
  payload.headers.append("set-cookie", setCookie);
1639
1616
  return payload;
1617
+ });
1640
1618
  }))),
1641
1619
  },
1642
1620
  "/api/v1/auth/me": {
@@ -1801,7 +1779,7 @@ async function completeBrowserSsoLogin(
1801
1779
  if (!mfaResult.ok) {
1802
1780
  ${mfa ? `if (mfaResult.error === "mfa_required") {
1803
1781
  const pending = redirectTo("/login/mfa");
1804
- pending.headers.append("set-cookie", pendingMfaSetCookie(user.id));
1782
+ pending.headers.append("set-cookie", pendingMfaSetCookie(user.id, user.auth_version));
1805
1783
  return pending;
1806
1784
  }` : ""}
1807
1785
  return views.render("login.eta", { layout: { title: "Sign in" }, errors: { email: "These credentials do not match our records." }, email, password: "" }, { request });
@@ -1833,12 +1811,13 @@ async function completeBrowserSsoLogin(
1833
1811
  async (request) => {
1834
1812
  const { fields } = await parseFormBody(request);
1835
1813
  const { email, password, mfa_code } = parseLoginCredentials(fields);
1836
- const user = await starterAuthDirectory.findByEmail?.(email);
1814
+ return runWithLoginUser(email, async (user) => {
1837
1815
  if (!user?.password || !(await verifyPassword(password, user.password))) {
1838
1816
  return views.render("login.eta", { layout: { title: "Sign in" }, errors: { email: "These credentials do not match our records." }, email, password: "" }, { request });
1839
1817
  }
1840
1818
  ${mfaLoginBranch}
1841
1819
  return auth.signInRedirect(sessionUser(user), "/");
1820
+ });
1842
1821
  },
1843
1822
  async (request) =>
1844
1823
  views.render("login.eta", { layout: { title: "Sign in" }, errors: { email: "Too many login attempts. Try again shortly." }, email: "", password: "" }, { request, status: 429 }),
@@ -1947,29 +1926,35 @@ async function completeBrowserSsoLogin(
1947
1926
  },` : ""}${mfa ? `
1948
1927
  "/login/mfa": {
1949
1928
  GET: kernel.wrapWebGuest(async (request) => {
1950
- if (!readPendingMfaUserId(request)) {
1951
- return redirectTo("/login");
1952
- }
1929
+ const pending = readPendingMfaChallenge(request);
1930
+ const record = pending ? await starterAuthDirectory.findByIdOrThrow(pending.userId).catch(() => null) : null;
1931
+ if (!record?.is_active || record.auth_version !== pending?.authVersion) return redirectTo("/login");
1953
1932
  return views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: {}, code: "" }, { request });
1954
1933
  }),
1955
1934
  POST: wrapWebLogin(
1956
1935
  kernel,
1957
1936
  async (request) => {
1958
- const pendingId = readPendingMfaUserId(request);
1959
- if (!pendingId) {
1937
+ const pending = readPendingMfaChallenge(request);
1938
+ if (!pending) {
1960
1939
  return redirectTo("/login");
1961
1940
  }
1962
1941
  const { fields } = await parseFormBody(request);
1963
1942
  const submitted = (fields.code ?? "").trim();
1964
- const record = await starterAuthDirectory.findByIdOrThrow(pendingId);
1943
+ return runWithLockedAuthUser(pending.userId, async (record) => {
1944
+ if (!record?.is_active || record.auth_version !== pending.authVersion) {
1945
+ const failed = redirectTo("/login");
1946
+ failed.headers.append("set-cookie", pendingMfaClearCookie());
1947
+ return failed;
1948
+ }
1965
1949
  const mfaResult = completePasswordLogin(record, { mfaCode: submitted });
1966
1950
  if (!mfaResult.ok) {
1967
1951
  return views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: { code: "That code is not valid." }, code: "" }, { request });
1968
1952
  }
1969
- await persistAuthRecovery(pendingId, record.mfa_recovery_codes, mfaResult.consumedRecoveryHash);
1953
+ await persistAuthRecovery(pending.userId, record.mfa_recovery_codes, mfaResult.consumedRecoveryHash);
1970
1954
  const signed = await auth.signInRedirect(sessionUser(record), "/");
1971
1955
  signed.headers.append("set-cookie", pendingMfaClearCookie());
1972
1956
  return signed;
1957
+ });
1973
1958
  },
1974
1959
  async (request) =>
1975
1960
  views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: { code: "Too many login attempts. Try again shortly." }, code: "" }, { request, status: 429 }),
@@ -1986,14 +1971,16 @@ async function completeBrowserSsoLogin(
1986
1971
  }
1987
1972
  const { fields } = await parseFormBody(request);
1988
1973
  const password = fields.password ?? "";
1989
- const record = await starterAuthDirectory.findByIdOrThrow(Number(user.id));
1974
+ return runWithLockedAuthUser(Number(user.id), async (record) => {
1975
+ if (!record?.is_active || record.auth_version !== user.authVersion) return redirectTo("/login");
1990
1976
  if (!record.password || !(await verifyPassword(password, record.password))) {
1991
1977
  return views.render("confirm-password.eta", { layout: { title: "Confirm password" }, errors: { password: "That password is not correct." }, password: "" }, { request });
1992
1978
  }
1993
1979
  const next = sanitizeInternalPath(new URL(request.url).searchParams.get("redirect") ?? "/account/mfa");
1994
1980
  const confirmed = redirectTo(next);
1995
- confirmed.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id)));
1981
+ confirmed.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id), record.auth_version));
1996
1982
  return confirmed;
1983
+ });
1997
1984
  }),
1998
1985
  },
1999
1986
  "/account/mfa": {
@@ -2028,7 +2015,7 @@ async function completeBrowserSsoLogin(
2028
2015
  const recoveryCodes = generateRecoveryCodes();
2029
2016
  const stored = protectMfaSecret(secret);
2030
2017
  const previous = await runAuthWrite(Number(user.id), () => User.find(Number(user.id)));
2031
- if (!previous) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
2018
+ if (!previous || previous.get("auth_version") !== user.authVersion || !(previous.get("is_active") === true || previous.get("is_active") === 1)) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
2032
2019
  await runInTransaction(async () => {
2033
2020
  await runAuthWrite(Number(user.id), async () => {
2034
2021
  // Trusted, pre-protected security fields: atomically replace only the state we read.
@@ -2038,6 +2025,8 @@ async function completeBrowserSsoLogin(
2038
2025
  mfa_recovery_codes: JSON.stringify(recoveryCodes.map((item) => hashRecoveryCode(item))),
2039
2026
  }, { where: {
2040
2027
  id: Number(user.id),
2028
+ is_active: previous.get("is_active"),
2029
+ auth_version: previous.get("auth_version"),
2041
2030
  mfa_enabled: previous.get("mfa_enabled"),
2042
2031
  mfa_secret: previous.get("mfa_secret"),
2043
2032
  mfa_recovery_codes: previous.get("mfa_recovery_codes"),
@@ -2420,6 +2409,8 @@ function renderAuthDirectory(layers) {
2420
2409
  if (!user) {
2421
2410
  return null;
2422
2411
  }
2412
+ const record = mapUserRow(user);
2413
+ if (!record.is_active) return null;
2423
2414
  let abilities: string[] = [];
2424
2415
  try {
2425
2416
  abilities = JSON.parse(String(tokenRow.get("abilities") ?? "[]")) as string[];
@@ -2428,6 +2419,8 @@ function renderAuthDirectory(layers) {
2428
2419
  }
2429
2420
  return {
2430
2421
  id: user_id,
2422
+ isActive: record.is_active,
2423
+ authVersion: record.auth_version,
2431
2424
  role: mapRole(user.get("is_admin")),
2432
2425
  abilities,
2433
2426
  tokenId: Number(tokenRow.get("id")),
@@ -2455,12 +2448,13 @@ function asNullableString(value: unknown): string | null {
2455
2448
  const mfaKeys = layers.extras.mfa ? ` | "mfa_enabled" | "mfa_secret" | "mfa_recovery_codes"` : "";
2456
2449
  return `import type { AuthUser } from "@getstrata/core/auth/authContext";
2457
2450
  import { verifyPassword } from "@getstrata/core/auth/password";
2451
+ import { runInTransaction } from "@getstrata/core/database/transaction";
2458
2452
  ${hashImport}import type { AuthUserDirectory, AuthUserRecord } from "@getstrata/core/contracts/authUserDirectory";
2459
2453
  import { runWithMigrationBypassForIdentifier } from "@getstrata/core/tenant/databaseTenantContext";
2460
2454
  ${apiTokenImport}import { User } from "../models/User.ts";
2461
2455
 
2462
2456
  type LoadedUser = {
2463
- get(key: "id" | "name" | "email" | "is_admin" | "email_verified_at" | "password" | "session_valid_after"${mfaKeys}): unknown;
2457
+ get(key: "id" | "name" | "email" | "is_admin" | "email_verified_at" | "password" | "session_valid_after" | "is_active" | "auth_version"${mfaKeys}): unknown;
2464
2458
  };
2465
2459
 
2466
2460
  function mapRole(isAdmin: unknown): string {
@@ -2471,8 +2465,17 @@ function asTimestamp(value: unknown): Date | string | null {
2471
2465
  return value instanceof Date || typeof value === "string" ? value : null;
2472
2466
  }
2473
2467
  ${nullableStringHelper}
2474
- function mapUserRow(user: LoadedUser): AuthUserRecord {
2468
+ export type StarterAuthUserRecord = AuthUserRecord & { is_active: boolean; auth_version: number };
2469
+
2470
+ function mapUserRow(user: LoadedUser): StarterAuthUserRecord {
2471
+ const active = user.get("is_active");
2472
+ const version = user.get("auth_version");
2473
+ if ((active !== true && active !== false && active !== 0 && active !== 1) || typeof version !== "number" || !Number.isSafeInteger(version) || version < 0) {
2474
+ throw new Error("Account state missing or invalid. Apply the account-state migration before deploying auth readers.");
2475
+ }
2475
2476
  return {
2477
+ is_active: active === true || active === 1,
2478
+ auth_version: version,
2476
2479
  id: Number(user.get("id")),
2477
2480
  name: String(user.get("name") ?? ""),
2478
2481
  email: String(user.get("email") ?? ""),
@@ -2500,7 +2503,14 @@ async function findUserByEmail(email: string) {
2500
2503
  });
2501
2504
  }
2502
2505
 
2503
- export const starterAuthDirectory: AuthUserDirectory = {
2506
+ export async function runWithLockedAuthUser<T>(id: number, operation: (record: StarterAuthUserRecord | null) => Promise<T>): Promise<T> {
2507
+ return runWithMigrationBypassForIdentifier(id, () => runInTransaction(async () => {
2508
+ const user = await User.where({ id })${layers.database === "sqlite" ? "" : ".lockForUpdate()"}.first();
2509
+ return operation(user ? mapUserRow(user) : null);
2510
+ }));
2511
+ }
2512
+
2513
+ export const starterAuthDirectory = {
2504
2514
  ${tokenLookup}
2505
2515
 
2506
2516
  findByIdOrThrow: findUserById,
@@ -2509,7 +2519,7 @@ ${tokenLookup}
2509
2519
 
2510
2520
  async verifyCredentials(email: string, password: string): Promise<AuthUser | null> {
2511
2521
  const user = await findUserByEmail(email);
2512
- if (!user?.password || !(await verifyPassword(password, user.password))) {
2522
+ if (!user?.is_active || !user.password || !(await verifyPassword(password, user.password))) {
2513
2523
  return null;
2514
2524
  }
2515
2525
  if ("mfa_enabled" in user && user.mfa_enabled) {
@@ -2517,11 +2527,13 @@ ${tokenLookup}
2517
2527
  }
2518
2528
  return {
2519
2529
  id: user.id,
2530
+ isActive: user.is_active,
2531
+ authVersion: user.auth_version,
2520
2532
  role: user.role,
2521
2533
  emailVerifiedAt: user.email_verified_at ?? null,
2522
2534
  };
2523
2535
  },
2524
- };
2536
+ } satisfies AuthUserDirectory;
2525
2537
  `;
2526
2538
  }
2527
2539
  function renderAuthProvider(layers) {
@@ -2580,6 +2592,8 @@ export default authProvider;
2580
2592
  cookieName: "strata_session",
2581
2593
  mapUser: (user) => ({
2582
2594
  id: user.id,
2595
+ authVersion: user.auth_version,
2596
+ isActive: user.is_active,
2583
2597
  role: user.is_admin ? "admin" : "member",
2584
2598
  ...(user.email_verified_at !== undefined ? { emailVerifiedAt: user.email_verified_at } : {}),
2585
2599
  }),
@@ -3163,9 +3177,9 @@ function renderPackageJson(projectName, options = {}) {
3163
3177
  "@getstrata/cli": "workspace:*",
3164
3178
  "@getstrata/core": "workspace:*"
3165
3179
  } : {
3166
- "@getstrata/bootstrap": "^2.2.32",
3167
- "@getstrata/cli": "^2.2.32",
3168
- "@getstrata/core": "^2.2.32"
3180
+ "@getstrata/bootstrap": "^2.2.34",
3181
+ "@getstrata/cli": "^2.2.34",
3182
+ "@getstrata/core": "^2.2.34"
3169
3183
  };
3170
3184
  coreDeps.eta = "^4.6.0";
3171
3185
  if (options.layers?.database === "mysql") {
@@ -4144,7 +4158,7 @@ function renderUserModel(layers) {
4144
4158
  mfa_secret: string | null;
4145
4159
  mfa_enabled: number | boolean;
4146
4160
  mfa_recovery_codes: string | null;` : "";
4147
- const columns = ["id", "name", "email", "password", "is_admin"];
4161
+ const columns = ["id", "name", "email", "password", "is_admin", "is_active", "auth_version"];
4148
4162
  if (tenancyOn) {
4149
4163
  columns.push("tenant_id");
4150
4164
  }
@@ -4152,7 +4166,7 @@ function renderUserModel(layers) {
4152
4166
  columns.push("mfa_secret", "mfa_enabled", "mfa_recovery_codes");
4153
4167
  }
4154
4168
  columns.push("session_valid_after", "email_verified_at", "created_at");
4155
- const fillable = ["name", "email", "password", "is_admin"];
4169
+ const fillable = ["name", "email", "password", "is_admin", "is_active"];
4156
4170
  if (tenancyOn) {
4157
4171
  fillable.push("tenant_id");
4158
4172
  }
@@ -4175,6 +4189,8 @@ interface UserRecord {
4175
4189
  name: string;
4176
4190
  email: string;
4177
4191
  password: string;
4192
+ is_active: number | boolean;
4193
+ auth_version: number;
4178
4194
  is_admin: number | boolean;${tenantField}${mfaFields}
4179
4195
  session_valid_after: Date | string | null;
4180
4196
  email_verified_at: Date | string | null;
@@ -4884,6 +4900,13 @@ const listeners: readonly DurableListener[] = [];
4884
4900
  export { listeners };
4885
4901
  `;
4886
4902
  }
4903
+ function renderAccountStateMigration(layers) {
4904
+ const driver = layers.database === "postgres" ? "pgsql" : layers.database;
4905
+ return `import { createAccountStateMigration } from "@getstrata/core/auth/accountStateMigration";
4906
+
4907
+ export default createAccountStateMigration("0006_account_state", "${driver}", { sessions: ${authUsesCookie(layers.auth)} });
4908
+ `;
4909
+ }
4887
4910
  function renderOutboxMigration(layers) {
4888
4911
  const driver = layers.database === "postgres" ? "pgsql" : layers.database;
4889
4912
  const rls = layers.tenancy === "rls" && layers.database === "postgres";
@@ -5299,7 +5322,10 @@ import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
5299
5322
  import type { AppModule } from "@getstrata/bootstrap/contracts";
5300
5323
  import { routeParams } from "@getstrata/bootstrap/web/routing";
5301
5324
  import { createScimAuthMiddleware } from "@getstrata/core/auth/scimAuthMiddleware";
5325
+ import { revokeUserSessions } from "@getstrata/core/auth/oneTimeToken";
5326
+ import { getSql } from "../../bootstrap/database.ts";
5302
5327
  import { hashPassword } from "@getstrata/core/auth/password";
5328
+ import { runInTransaction } from "@getstrata/core/database/transaction";
5303
5329
  import { BadRequestError } from "@getstrata/core/errors/http";
5304
5330
  import { parsePositiveIntParam } from "@getstrata/core/http/validation";
5305
5331
  import { withErrorHandling } from "@getstrata/core/http/response";
@@ -5348,7 +5374,7 @@ function scimError(detail: string, status: number): Response {
5348
5374
  return scimJson({ schemas: [ERROR_SCHEMA], detail, status: String(status) }, status);
5349
5375
  }
5350
5376
 
5351
- function toScimUser(user: { get(key: "id" | "name" | "email"): unknown }) {
5377
+ function toScimUser(user: { get(key: "id" | "name" | "email" | "is_active"): unknown }) {
5352
5378
  const email = String(user.get("email") ?? "");
5353
5379
  const name = String(user.get("name") ?? "");
5354
5380
  return {
@@ -5357,7 +5383,7 @@ function toScimUser(user: { get(key: "id" | "name" | "email"): unknown }) {
5357
5383
  userName: email,
5358
5384
  name: { formatted: name },
5359
5385
  emails: [{ value: email, primary: true }],
5360
- active: true,
5386
+ active: user.get("is_active") === true || user.get("is_active") === 1,
5361
5387
  meta: { resourceType: "User" },
5362
5388
  };
5363
5389
  }
@@ -5393,6 +5419,68 @@ function readName(body: Record<string, unknown>, fallback: string): string {
5393
5419
  return fallback;
5394
5420
  }
5395
5421
 
5422
+ function isScimObject(value: unknown): value is Record<string, unknown> {
5423
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5424
+ }
5425
+
5426
+ // Validate the complete operation before changing profile or account state.
5427
+ function validateScimProfile(body: Record<string, unknown>, strict = false): Response | null {
5428
+ if ("active" in body && typeof body.active !== "boolean") {
5429
+ return scimError("active must be a boolean.", 400);
5430
+ }
5431
+ const fields = ["userName", "emails", "name", "displayName", "active"];
5432
+ if (strict && Object.keys(body).some((key) => !fields.includes(key))) {
5433
+ return scimError("Unsupported profile attribute.", 400);
5434
+ }
5435
+ if (strict && !fields.some((key) => key in body)) return scimError("A profile value is required.", 400);
5436
+ for (const key of ["userName", "displayName"]) {
5437
+ const value = body[key];
5438
+ if (key in body && (typeof value !== "string" || !value.trim())) {
5439
+ return scimError("Profile strings must be non-empty.", 400);
5440
+ }
5441
+ }
5442
+ if ("emails" in body) {
5443
+ if (!Array.isArray(body.emails) || body.emails.length !== 1) {
5444
+ return scimError("Exactly one email value is supported.", 400);
5445
+ }
5446
+ const email = body.emails[0];
5447
+ if (!isScimObject(email) || typeof email.value !== "string" || !email.value.trim()) {
5448
+ return scimError("An email value is required.", 400);
5449
+ }
5450
+ if (Object.keys(email).some((key) => !["value", "primary"].includes(key)) || ("primary" in email && email.primary !== true)) {
5451
+ return scimError("Only one primary email value is supported.", 400);
5452
+ }
5453
+ }
5454
+ if ("name" in body) {
5455
+ if (!isScimObject(body.name) || Object.keys(body.name).some((key) => !["formatted", "givenName", "familyName"].includes(key))) {
5456
+ return scimError("Unsupported name value.", 400);
5457
+ }
5458
+ if (!Object.values(body.name).some((value) => typeof value === "string" && value.trim()) || Object.values(body.name).some((value) => typeof value !== "string")) {
5459
+ return scimError("Name values must be strings with a non-empty name.", 400);
5460
+ }
5461
+ }
5462
+ return null;
5463
+ }
5464
+
5465
+ async function applyAccountUpdate(user: InstanceType<typeof User>, name: string, email: string, active?: boolean) {
5466
+ const wasActive = user.get("is_active") === true || user.get("is_active") === 1;
5467
+ await user.update({ name, email, ...(active === undefined ? {} : { is_active: active }) });
5468
+ // The caller owns the transaction and row lock. Both transition directions fence
5469
+ // old proofs; repeated identical state is idempotent and does not advance the epoch.
5470
+ if (active !== undefined && active !== wasActive) {
5471
+ await revokeUserSessions(getSql(), Number(user.get("id")), { incrementAuthVersion: true });
5472
+ }
5473
+ }
5474
+
5475
+ async function readScimBody(request: Request): Promise<Record<string, unknown> | Response> {
5476
+ try {
5477
+ const body: unknown = await request.json();
5478
+ return isScimObject(body) ? body : scimError("An object body is required.", 400);
5479
+ } catch {
5480
+ return scimError("Invalid JSON body.", 400);
5481
+ }
5482
+ }
5483
+
5396
5484
  function wrapScim(kernel: HttpKernel, handler: (request: Request) => Promise<Response>) {
5397
5485
  const throttle = kernel.ownThrottle(createScimThrottleMiddleware({
5398
5486
  redisUrl: process.env.REDIS_URL,
@@ -5404,7 +5492,9 @@ function wrapScim(kernel: HttpKernel, handler: (request: Request) => Promise<Res
5404
5492
  if (!scimEnabled()) {
5405
5493
  return scimError("SCIM is off.", 404);
5406
5494
  }
5407
- return handler(request);
5495
+ return ["POST", "PUT", "PATCH", "DELETE"].includes(request.method)
5496
+ ? await runInTransaction(() => handler(request))
5497
+ : await handler(request);
5408
5498
  }),
5409
5499
  );
5410
5500
  }
@@ -5475,7 +5565,10 @@ const scimModule: AppModule = {
5475
5565
  POST: kernel.wrap(
5476
5566
  "api",
5477
5567
  wrapScim(kernel, async (request) => {
5478
- const body = (await request.json()) as Record<string, unknown>;
5568
+ const body = await readScimBody(request);
5569
+ if (body instanceof Response) return body;
5570
+ const invalid = validateScimProfile(body);
5571
+ if (invalid) return invalid;
5479
5572
  const email = readUserName(body);
5480
5573
  const name = readName(body, email.split("@")[0] ?? "User");
5481
5574
  if (!email) {
@@ -5486,7 +5579,7 @@ const scimModule: AppModule = {
5486
5579
  return scimError("User already exists.", 409);
5487
5580
  }
5488
5581
  const hashed = await hashPassword(randomBytes(18).toString("hex"));
5489
- const created = await User.create({ name, email, password: hashed, is_admin: false, tenant_id: tenantId() });
5582
+ const created = await User.create({ name, email, password: hashed, is_admin: false, is_active: body.active !== false, tenant_id: tenantId() });
5490
5583
  if (!created) {
5491
5584
  return scimError("Could not create user.", 500);
5492
5585
  }
@@ -5516,17 +5609,20 @@ const scimModule: AppModule = {
5516
5609
  if (id instanceof Response) {
5517
5610
  return id;
5518
5611
  }
5519
- const body = (await request.json()) as Record<string, unknown>;
5612
+ const body = await readScimBody(request);
5613
+ if (body instanceof Response) return body;
5614
+ const invalid = validateScimProfile(body);
5615
+ if (invalid) return invalid;
5520
5616
  const email = readUserName(body);
5521
5617
  const name = readName(body, email);
5522
5618
  if (!email || !name) {
5523
5619
  return scimError("userName and name are required.", 400);
5524
5620
  }
5525
- const user = await User.where({ id, tenant_id: tenantId() }).first();
5621
+ const user = await User.where({ id, tenant_id: tenantId() })${layers.database === "sqlite" ? "" : ".lockForUpdate()"}.first();
5526
5622
  if (!user) {
5527
5623
  return scimError("User not found.", 404);
5528
5624
  }
5529
- await user.update({ name, email });
5625
+ await applyAccountUpdate(user, name, email, typeof body.active === "boolean" ? body.active : undefined);
5530
5626
  return scimJson(toScimUser(user));
5531
5627
  }),
5532
5628
  ),
@@ -5537,37 +5633,55 @@ const scimModule: AppModule = {
5537
5633
  if (id instanceof Response) {
5538
5634
  return id;
5539
5635
  }
5540
- const user = await User.where({ id, tenant_id: tenantId() }).first();
5636
+ const user = await User.where({ id, tenant_id: tenantId() })${layers.database === "sqlite" ? "" : ".lockForUpdate()"}.first();
5541
5637
  if (!user) {
5542
5638
  return scimError("User not found.", 404);
5543
5639
  }
5544
- const body = (await request.json()) as { schemas?: string[]; Operations?: Array<{ op?: string; path?: string; value?: unknown }> };
5545
- if (body.schemas && !body.schemas.includes(PATCH_SCHEMA)) {
5640
+ const body = await readScimBody(request);
5641
+ if (body instanceof Response) return body;
5642
+ if (!Array.isArray(body.schemas) || !body.schemas.includes(PATCH_SCHEMA)) {
5546
5643
  return scimError("Unsupported patch schema.", 400);
5547
5644
  }
5645
+ if (!Array.isArray(body.Operations) || body.Operations.length === 0) {
5646
+ return scimError("A non-empty Operations array is required.", 400);
5647
+ }
5648
+ let active: boolean | undefined;
5548
5649
  let name = String(user.get("name") ?? "");
5549
5650
  let email = String(user.get("email") ?? "");
5550
- for (const operation of body.Operations ?? []) {
5551
- const op = (operation.op ?? "replace").toLowerCase();
5552
- if (op !== "replace" && op !== "add") {
5553
- continue;
5651
+ for (const operation of body.Operations) {
5652
+ if (!isScimObject(operation) || typeof operation.op !== "string" || !["replace", "add"].includes(operation.op.toLowerCase())) {
5653
+ return scimError("Only add and replace profile operations are supported.", 400);
5654
+ }
5655
+ if (operation.path !== undefined && typeof operation.path !== "string") {
5656
+ return scimError("Invalid patch path.", 400);
5554
5657
  }
5555
- const path = (operation.path ?? "").toLowerCase();
5556
- if (path === "username" || path === "emails") {
5557
- email = String(operation.value ?? email).trim().toLowerCase();
5558
- } else if (path === "name.formatted" || path === "displayname" || path === "name") {
5559
- if (typeof operation.value === "string") {
5560
- name = operation.value.trim() || name;
5561
- } else if (operation.value && typeof operation.value === "object") {
5562
- name = readName({ name: operation.value as Record<string, unknown> }, name);
5563
- }
5564
- } else if (!path && operation.value && typeof operation.value === "object") {
5565
- const value = operation.value as Record<string, unknown>;
5566
- email = readUserName(value) || email;
5567
- name = readName(value, name);
5658
+ const path = typeof operation.path === "string" ? operation.path.toLowerCase() : "";
5659
+ let value: Record<string, unknown>;
5660
+ if (!path) {
5661
+ if (!isScimObject(operation.value)) return scimError("A profile object is required.", 400);
5662
+ value = operation.value;
5663
+ } else if (path === "username") {
5664
+ value = { userName: operation.value };
5665
+ } else if (path === "emails") {
5666
+ value = { emails: operation.value };
5667
+ } else if (path === "name.formatted") {
5668
+ value = { name: { formatted: operation.value } };
5669
+ } else if (path === "displayname" || (path === "name" && typeof operation.value === "string")) {
5670
+ value = { displayName: operation.value };
5671
+ } else if (path === "name") {
5672
+ value = { name: operation.value };
5673
+ } else if (path === "active") {
5674
+ value = { active: operation.value };
5675
+ } else {
5676
+ return scimError("Unsupported patch path.", 400);
5568
5677
  }
5678
+ const invalid = validateScimProfile(value, true);
5679
+ if (invalid) return invalid;
5680
+ email = readUserName(value) || email;
5681
+ name = readName(value, name);
5682
+ if (typeof value.active === "boolean") active = value.active;
5569
5683
  }
5570
- await user.update({ name, email });
5684
+ await applyAccountUpdate(user, name, email, active);
5571
5685
  return scimJson(toScimUser(user));
5572
5686
  }),
5573
5687
  ),
@@ -5578,7 +5692,7 @@ const scimModule: AppModule = {
5578
5692
  if (id instanceof Response) {
5579
5693
  return id;
5580
5694
  }
5581
- const user = await User.where({ id, tenant_id: tenantId() }).first();
5695
+ const user = await User.where({ id, tenant_id: tenantId() })${layers.database === "sqlite" ? "" : ".lockForUpdate()"}.first();
5582
5696
  if (user) {
5583
5697
  await user.delete();
5584
5698
  }
@@ -5729,6 +5843,11 @@ function writeGeneratedFiles(options) {
5729
5843
  writeText(join2(src, "db/migrationRuntime.ts"), renderMigrationRuntimeTs(layers));
5730
5844
  writeText(join2(src, "db/migrations/0001_starter_schema.ts"), renderStarterSchemaMigration(layers));
5731
5845
  writeText(join2(src, "db/migrations/0005_outbox.ts"), renderOutboxMigration(layers));
5846
+ if (authNeedsUsers(layers.auth)) {
5847
+ writeText(join2(src, "db/migrations/0006_account_state.ts"), renderAccountStateMigration(layers));
5848
+ } else {
5849
+ removeIfExists(join2(src, "db/migrations/0006_account_state.ts"));
5850
+ }
5732
5851
  removeIfExists(join2(src, "db/migrations/0002_webhooks_schema.ts"));
5733
5852
  removeIfExists(join2(src, "db/migrations/0002_billing_schema.ts"));
5734
5853
  removeIfExists(join2(src, "db/migrations/0003_billing_schema.ts"));
@@ -12,9 +12,9 @@
12
12
  "check": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@getstrata/bootstrap": "^2.2.32",
16
- "@getstrata/cli": "^2.2.32",
17
- "@getstrata/core": "^2.2.32",
15
+ "@getstrata/bootstrap": "^2.2.34",
16
+ "@getstrata/cli": "^2.2.34",
17
+ "@getstrata/core": "^2.2.34",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-strata",
3
- "version": "2.2.32",
3
+ "version": "2.2.34",
4
4
  "description": "Create a new Strata app. Interactive wizard; choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",