@getstrata/starter 2.2.33 → 2.2.35

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
  // 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}\`;
1166
- }
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}\`;
1160
+ export function pendingMfaSetCookie(userId: number, authVersion: number): string {
1161
+ return createPendingMfaCookie(userId, authVersion, sessionSecret());
1172
1162
  }
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.33",
3167
- "@getstrata/cli": "^2.2.33",
3168
- "@getstrata/core": "^2.2.33"
3180
+ "@getstrata/bootstrap": "^2.2.35",
3181
+ "@getstrata/cli": "^2.2.35",
3182
+ "@getstrata/core": "^2.2.35"
3169
3183
  };
3170
3184
  coreDeps.eta = "^4.6.0";
3171
3185
  if (options.layers?.database === "mysql") {
@@ -3390,13 +3404,13 @@ function renderReadmeIntro(projectName, options) {
3390
3404
  if (options.dogfood) {
3391
3405
  return `# ${projectName}
3392
3406
 
3393
- This in-repo app is Strata dogfood for internal end-to-end testing (migrate, seed, boot, OpenAPI, smoke). It is not a product. Start a product app with \`bunx create-strata\`.
3407
+ This generated app is an internal acceptance fixture (migrate, seed, boot, OpenAPI, smoke). It is not a product. Framework CI generates disposable fixtures; product dogfood lives in the separate strata-shop repository. Start a product app with \`bunx create-strata\`.
3394
3408
  `;
3395
3409
  }
3396
3410
  if (options.inRepoExample) {
3397
3411
  return `# ${projectName}
3398
3412
 
3399
- This in-repo app is a generated sibling layer map. It is not a product and it is not CI dogfood. CI dogfood is \`apps/hiroapp\`. Start a product app with \`bunx create-strata\`.
3413
+ This is a generated sibling layer map. It is not a product and it is not CI dogfood. Framework CI generates disposable acceptance fixtures; product dogfood lives in the separate strata-shop repository. Start a product app with \`bunx create-strata\`.
3400
3414
  `;
3401
3415
  }
3402
3416
  return `# ${projectName}
@@ -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,6 +5322,8 @@ 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";
5303
5328
  import { runInTransaction } from "@getstrata/core/database/transaction";
5304
5329
  import { BadRequestError } from "@getstrata/core/errors/http";
@@ -5349,7 +5374,7 @@ function scimError(detail: string, status: number): Response {
5349
5374
  return scimJson({ schemas: [ERROR_SCHEMA], detail, status: String(status) }, status);
5350
5375
  }
5351
5376
 
5352
- function toScimUser(user: { get(key: "id" | "name" | "email"): unknown }) {
5377
+ function toScimUser(user: { get(key: "id" | "name" | "email" | "is_active"): unknown }) {
5353
5378
  const email = String(user.get("email") ?? "");
5354
5379
  const name = String(user.get("name") ?? "");
5355
5380
  return {
@@ -5358,7 +5383,7 @@ function toScimUser(user: { get(key: "id" | "name" | "email"): unknown }) {
5358
5383
  userName: email,
5359
5384
  name: { formatted: name },
5360
5385
  emails: [{ value: email, primary: true }],
5361
- active: true,
5386
+ active: user.get("is_active") === true || user.get("is_active") === 1,
5362
5387
  meta: { resourceType: "User" },
5363
5388
  };
5364
5389
  }
@@ -5398,11 +5423,10 @@ function isScimObject(value: unknown): value is Record<string, unknown> {
5398
5423
  return value !== null && typeof value === "object" && !Array.isArray(value);
5399
5424
  }
5400
5425
 
5401
- // This minimal adapter persists profile fields only. Never acknowledge a status
5402
- // change (or part of a PATCH) that it cannot actually apply.
5426
+ // Validate the complete operation before changing profile or account state.
5403
5427
  function validateScimProfile(body: Record<string, unknown>, strict = false): Response | null {
5404
- if ("active" in body && body.active !== true) {
5405
- return scimError("Account status changes are not supported; no deactivation was performed.", 400);
5428
+ if ("active" in body && typeof body.active !== "boolean") {
5429
+ return scimError("active must be a boolean.", 400);
5406
5430
  }
5407
5431
  const fields = ["userName", "emails", "name", "displayName", "active"];
5408
5432
  if (strict && Object.keys(body).some((key) => !fields.includes(key))) {
@@ -5438,6 +5462,16 @@ function validateScimProfile(body: Record<string, unknown>, strict = false): Res
5438
5462
  return null;
5439
5463
  }
5440
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
+
5441
5475
  async function readScimBody(request: Request): Promise<Record<string, unknown> | Response> {
5442
5476
  try {
5443
5477
  const body: unknown = await request.json();
@@ -5545,7 +5579,7 @@ const scimModule: AppModule = {
5545
5579
  return scimError("User already exists.", 409);
5546
5580
  }
5547
5581
  const hashed = await hashPassword(randomBytes(18).toString("hex"));
5548
- 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() });
5549
5583
  if (!created) {
5550
5584
  return scimError("Could not create user.", 500);
5551
5585
  }
@@ -5584,11 +5618,11 @@ const scimModule: AppModule = {
5584
5618
  if (!email || !name) {
5585
5619
  return scimError("userName and name are required.", 400);
5586
5620
  }
5587
- 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();
5588
5622
  if (!user) {
5589
5623
  return scimError("User not found.", 404);
5590
5624
  }
5591
- await user.update({ name, email });
5625
+ await applyAccountUpdate(user, name, email, typeof body.active === "boolean" ? body.active : undefined);
5592
5626
  return scimJson(toScimUser(user));
5593
5627
  }),
5594
5628
  ),
@@ -5599,7 +5633,7 @@ const scimModule: AppModule = {
5599
5633
  if (id instanceof Response) {
5600
5634
  return id;
5601
5635
  }
5602
- 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();
5603
5637
  if (!user) {
5604
5638
  return scimError("User not found.", 404);
5605
5639
  }
@@ -5611,6 +5645,7 @@ const scimModule: AppModule = {
5611
5645
  if (!Array.isArray(body.Operations) || body.Operations.length === 0) {
5612
5646
  return scimError("A non-empty Operations array is required.", 400);
5613
5647
  }
5648
+ let active: boolean | undefined;
5614
5649
  let name = String(user.get("name") ?? "");
5615
5650
  let email = String(user.get("email") ?? "");
5616
5651
  for (const operation of body.Operations) {
@@ -5644,8 +5679,9 @@ const scimModule: AppModule = {
5644
5679
  if (invalid) return invalid;
5645
5680
  email = readUserName(value) || email;
5646
5681
  name = readName(value, name);
5682
+ if (typeof value.active === "boolean") active = value.active;
5647
5683
  }
5648
- await user.update({ name, email });
5684
+ await applyAccountUpdate(user, name, email, active);
5649
5685
  return scimJson(toScimUser(user));
5650
5686
  }),
5651
5687
  ),
@@ -5656,7 +5692,7 @@ const scimModule: AppModule = {
5656
5692
  if (id instanceof Response) {
5657
5693
  return id;
5658
5694
  }
5659
- 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();
5660
5696
  if (user) {
5661
5697
  await user.delete();
5662
5698
  }
@@ -5807,6 +5843,11 @@ function writeGeneratedFiles(options) {
5807
5843
  writeText(join2(src, "db/migrationRuntime.ts"), renderMigrationRuntimeTs(layers));
5808
5844
  writeText(join2(src, "db/migrations/0001_starter_schema.ts"), renderStarterSchemaMigration(layers));
5809
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
+ }
5810
5851
  removeIfExists(join2(src, "db/migrations/0002_webhooks_schema.ts"));
5811
5852
  removeIfExists(join2(src, "db/migrations/0002_billing_schema.ts"));
5812
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.33",
16
- "@getstrata/cli": "^2.2.33",
17
- "@getstrata/core": "^2.2.33",
15
+ "@getstrata/bootstrap": "^2.2.35",
16
+ "@getstrata/cli": "^2.2.35",
17
+ "@getstrata/core": "^2.2.35",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/starter",
3
- "version": "2.2.33",
3
+ "version": "2.2.35",
4
4
  "description": "Interactive create-strata wizard. Choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",