@getstrata/starter 2.2.41 → 2.2.43

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
@@ -116,9 +116,6 @@ function htmlAuthKit(auth) {
116
116
  function needsFrontendBuild(frontend) {
117
117
  return frontend === "spa-react" || frontend === "hybrid";
118
118
  }
119
- function nowTimestampLiteral(database) {
120
- return database === "mysql" ? `new Date().toISOString().slice(0, 19).replace("T", " ")` : "new Date().toISOString()";
121
- }
122
119
  function extraApplies(extra, auth) {
123
120
  if (extra === "metrics" || extra === "billing" || extra === "webhooks") {
124
121
  return true;
@@ -1202,16 +1199,14 @@ function renderAuthModule(layers) {
1202
1199
  imports.push(`import { appUrl } from "@getstrata/core/runtime/appKeyPrefix";`);
1203
1200
  }
1204
1201
  }
1205
- if (mfa) {
1206
- imports.push(`import { ConflictError } from "@getstrata/core/errors/http";`);
1207
- }
1202
+ imports.push(`import { ConflictError } from "@getstrata/core/errors/http";`);
1208
1203
  if (jsonApi) {
1209
1204
  imports.push(`import { AuthManager } from "@getstrata/core/auth/guard";`);
1210
1205
  }
1211
1206
  if (authUsesJwt(layers.auth)) {
1212
1207
  imports.push(`import { jwtTtlSeconds, signJwt } from "@getstrata/core/auth/jwt";`);
1213
1208
  }
1214
- imports.push(`import { runInTransaction } from "@getstrata/core/database/transaction";`);
1209
+ imports.push(`import { afterCommit, runInTransaction } from "@getstrata/core/database/transaction";`);
1215
1210
  imports.push(`import { hashPassword, verifyPassword } from "@getstrata/core/auth/password";`);
1216
1211
  imports.push(`import { AUTH_ONE_TIME_PURPOSES, consumeOneTimeToken, generateOneTimeToken, hashOneTimeToken, revokeUserSessions as revokeStoredUserSessions } from "@getstrata/core/auth/oneTimeToken";`);
1217
1212
  imports.push(`import { completePasswordLogin, persistConsumedRecoveryHash } from "@getstrata/core/auth/passwordLogin";`);
@@ -1220,9 +1215,9 @@ function renderAuthModule(layers) {
1220
1215
  }
1221
1216
  imports.push(`import { emailRule, minLength, required, stringRule, validateObject } from "@getstrata/core/validation/rules";`);
1222
1217
  imports.push(`import { parseJsonBody } from "@getstrata/core/http/validation";`);
1218
+ imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
1223
1219
  if (authUsesToken(layers.auth)) {
1224
1220
  imports.push(`import { hashApiToken } from "@getstrata/core/auth/tokenHash";`);
1225
- imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
1226
1221
  imports.push(`import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";`);
1227
1222
  }
1228
1223
  if (mfa) {
@@ -1236,7 +1231,7 @@ function renderAuthModule(layers) {
1236
1231
  imports.push(oidc ? `import { clearOidcPkceCookie, createOAuthState, readOidcPkceCookie, sealOidcPkceCookie, verifyOAuthState } from "@getstrata/core/security/oauthState";` : `import { createOAuthState, verifyOAuthState } from "@getstrata/core/security/oauthState";`);
1237
1232
  }
1238
1233
  if (jsonApi || cookie) {
1239
- imports.push(`import { jsonResponse, withErrorHandling } from "@getstrata/core/http/response";`);
1234
+ imports.push(`import { privateJsonResponse, withErrorHandling } from "@getstrata/core/http/response";`);
1240
1235
  imports.push(`import { resolveCsrfTokenForRequest } from "@getstrata/core/http/csrfToken";`);
1241
1236
  }
1242
1237
  imports.push(cookie && verify ? `import { absoluteTemporarySignedUrl, assertValidSignature } from "@getstrata/core/http/signedUrl";` : `import { absoluteTemporarySignedUrl } from "@getstrata/core/http/signedUrl";`);
@@ -1309,7 +1304,7 @@ async function runAuthWrite<T>(identifier: string | number, callback: () => Prom
1309
1304
  return await runWithMigrationBypassForIdentifier(identifier, callback);
1310
1305
  }
1311
1306
 
1312
- async function issueSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
1307
+ async function prepareSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
1313
1308
  const issued = generateOneTimeToken();
1314
1309
  const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
1315
1310
  await runAuthWrite(userId, async () => {
@@ -1317,15 +1312,34 @@ async function issueSignedAuthMail(to: string, subject: string, path: string, pu
1317
1312
  purpose,
1318
1313
  user_id: userId,
1319
1314
  token_hash: issued.hash,
1320
- expires_at: expiresAt.toISOString(),
1315
+ expires_at: sqlTimestamp(expiresAt),
1321
1316
  });
1322
1317
  });
1323
1318
  const link = absoluteTemporarySignedUrl(path, 3600, { ...extra, token: issued.plain });
1324
- await mailer().send({
1325
- to,
1326
- subject,
1327
- body: \`\${subject}\\n\\n\${link}\\n\`,
1328
- });
1319
+ return { to, subject, body: \`\${subject}\\n\\n\${link}\\n\` };
1320
+ }
1321
+
1322
+ async function issueSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
1323
+ const message = await prepareSignedAuthMail(to, subject, path, purpose, userId, extra);
1324
+ await afterCommit(() => mailer().send(message));
1325
+ }
1326
+
1327
+ async function createRegistration(credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
1328
+ const { email } = credentials;
1329
+ try {
1330
+ return await runAuthWrite(email, () => runInTransaction(async () => {
1331
+ ${verify ? "const created = " : ""}await User.create({
1332
+ ...credentials,
1333
+ is_admin: false,${tenantCreateField}
1334
+ });
1335
+ ${verify ? `return prepareSignedAuthMail(email, "Verify your email", verificationPath, AUTH_ONE_TIME_PURPOSES.emailVerify, Number(created.get("id")), { id: String(created.get("id")) });` : ""}
1336
+ }));
1337
+ } catch (error) {
1338
+ // The failed transaction/savepoint is already rolled back before readback.
1339
+ // Only an actual account race is neutral; unrelated persistence failures propagate.
1340
+ if (!(error instanceof ConflictError) || !(await starterAuthDirectory.findByEmail(email))) throw error;
1341
+ return undefined;
1342
+ }
1329
1343
  }
1330
1344
 
1331
1345
  async function consumeSignedAuthToken(request: Request, purpose: string): Promise<number | null> {
@@ -1350,7 +1364,7 @@ async function completeSignedEmailVerification(request: Request): Promise<boolea
1350
1364
  await runAuthWrite(userId, async () => {
1351
1365
  const user = await User.find(userId);
1352
1366
  if (!user) throw new Error("Verification account no longer exists.");
1353
- await user.update({ email_verified_at: ${nowTimestampLiteral(layers.database)} });
1367
+ await user.update({ email_verified_at: sqlTimestamp() });
1354
1368
  });
1355
1369
  return true;
1356
1370
  });
@@ -1406,7 +1420,7 @@ async function completeBrowserSsoLogin(
1406
1420
  let record = await starterAuthDirectory.findByEmail?.(email);
1407
1421
  if (!record) {
1408
1422
  if ((process.env.FEATURE_REGISTRATION ?? "true") === "false") {
1409
- return jsonResponse({ error: \`\${label} user is not provisioned.\` }, { status: 403 });
1423
+ return privateJsonResponse({ error: \`\${label} user is not provisioned.\` }, { status: 403 });
1410
1424
  }
1411
1425
  const hashed = await hashPassword(randomBytes(18).toString("hex"));
1412
1426
  try {
@@ -1424,10 +1438,10 @@ async function completeBrowserSsoLogin(
1424
1438
  record = await starterAuthDirectory.findByEmail?.(email);
1425
1439
  }
1426
1440
  if (!record) {
1427
- return jsonResponse({ error: \`Could not complete \${label} login.\` }, { status: 500 });
1441
+ return privateJsonResponse({ error: \`Could not complete \${label} login.\` }, { status: 500 });
1428
1442
  }
1429
1443
  return runWithLockedAuthUser(record.id, async (record) => {
1430
- if (!record?.is_active || record.email !== email) return jsonResponse({ error: "Account unavailable." }, { status: 403 });
1444
+ if (!record?.is_active || record.email !== email) return privateJsonResponse({ error: "Account unavailable." }, { status: 403 });
1431
1445
  ${mfa ? `if (record.mfa_enabled) {
1432
1446
  const pending = redirectTo("/login/mfa");
1433
1447
  pending.headers.append("set-cookie", pendingMfaSetCookie(record.id, record.auth_version));
@@ -1444,11 +1458,11 @@ async function completeBrowserSsoLogin(
1444
1458
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1445
1459
  return runWithLoginUser(email, async (record) => {
1446
1460
  if (!record?.password || !(await verifyPassword(password, record.password))) {
1447
- return jsonResponse({ error: "Invalid credentials" }, { status: 422 });
1461
+ return privateJsonResponse({ error: "Invalid credentials" }, { status: 422 });
1448
1462
  }
1449
1463
  const mfaResult = completePasswordLogin(record, { mfaCode: mfa_code });
1450
1464
  if (!mfaResult.ok) {
1451
- return jsonResponse({ error: mfaResult.error }, { status: mfaResult.error === "mfa_required" ? 401 : 422 });
1465
+ return privateJsonResponse({ error: mfaResult.error }, { status: mfaResult.error === "mfa_required" ? 401 : 422 });
1452
1466
  }
1453
1467
  await persistAuthRecovery(record.id, record.mfa_recovery_codes, mfaResult.consumedRecoveryHash);
1454
1468
  const user = { id: record.id, role: record.role };
@@ -1467,7 +1481,7 @@ async function completeBrowserSsoLogin(
1467
1481
  expires_at: expiresAt ? sqlTimestamp(expiresAt) : null,
1468
1482
  });
1469
1483
  });
1470
- const payload = jsonResponse({ token: plain, expires_at: expiresAt?.toISOString() ?? null });
1484
+ const payload = privateJsonResponse({ token: plain, expires_at: expiresAt?.toISOString() ?? null });
1471
1485
  ${cookie ? `const sessionAuth = dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN);
1472
1486
  const { setCookie } = await sessionAuth.signIn(sessionUser(record));
1473
1487
  payload.headers.append("set-cookie", setCookie);
@@ -1479,7 +1493,7 @@ async function completeBrowserSsoLogin(
1479
1493
  GET: kernel.wrapApi(async (request) => {
1480
1494
  const user = await dependencies.container.resolve<AuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1481
1495
  const record = await starterAuthDirectory.findByIdOrThrow(Number(user.id));
1482
- return jsonResponse({
1496
+ return privateJsonResponse({
1483
1497
  id: record.id,
1484
1498
  name: record.name ?? record.email,
1485
1499
  email: record.email,
@@ -1491,28 +1505,19 @@ async function completeBrowserSsoLogin(
1491
1505
  "/api/v1/auth/register": {
1492
1506
  POST: kernel.wrap("api", kernel.wrapRegister(withErrorHandling(async (request) => {
1493
1507
  if ((process.env.FEATURE_REGISTRATION ?? "true") === "false") {
1494
- return jsonResponse({ error: "Not found" }, { status: 404 });
1508
+ return privateJsonResponse({ error: "Not found" }, { status: 404 });
1495
1509
  }
1496
1510
  const { name, email, password } = await parseJsonBody(request, parseRegisterCredentials);
1497
1511
  const existing = await starterAuthDirectory.findByEmail?.(email);
1498
1512
  await hashPassword(password);
1499
1513
  if (existing) {
1500
- return jsonResponse({ ok: true }, { status: 201 });
1514
+ return privateJsonResponse({ ok: true }, { status: 201 });
1501
1515
  }
1502
1516
  const hashed = await hashPassword(password);
1503
- await runAuthWrite(email, async () => {
1504
- await User.create({
1505
- name,
1506
- email,
1507
- password: hashed,
1508
- is_admin: false,${tenantCreateField}
1509
- });
1510
- });
1511
- const created = await starterAuthDirectory.findByEmail?.(email);
1512
- ${verify ? `if (created) {
1513
- await issueSignedAuthMail(email, "Verify your email", "/api/v1/auth/verify-email", AUTH_ONE_TIME_PURPOSES.emailVerify, created.id, { id: String(created.id) });
1514
- }` : ""}
1515
- return jsonResponse({ ok: true }, { status: 201 });
1517
+ ${verify ? "const verificationMail = " : ""}await createRegistration({ name, email, password: hashed }${verify ? ', "/api/v1/auth/verify-email"' : ""});
1518
+ ${verify ? `// SMTP follows the outermost commit, including request RLS.
1519
+ if (verificationMail) await afterCommit(() => mailer().send(verificationMail));` : ""}
1520
+ return privateJsonResponse({ ok: true }, { status: 201 });
1516
1521
  }))),
1517
1522
  },` : "";
1518
1523
  const jwtLogin = authUsesJwt(layers.auth) ? `
@@ -1521,11 +1526,11 @@ async function completeBrowserSsoLogin(
1521
1526
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1522
1527
  return runWithLoginUser(email, async (record) => {
1523
1528
  if (!record?.password || !(await verifyPassword(password, record.password))) {
1524
- return jsonResponse({ error: "Invalid credentials" }, { status: 422 });
1529
+ return privateJsonResponse({ error: "Invalid credentials" }, { status: 422 });
1525
1530
  }
1526
1531
  const mfaResult = completePasswordLogin(record, { mfaCode: mfa_code });
1527
1532
  if (!mfaResult.ok) {
1528
- return jsonResponse({ error: mfaResult.error }, { status: mfaResult.error === "mfa_required" ? 401 : 422 });
1533
+ return privateJsonResponse({ error: mfaResult.error }, { status: mfaResult.error === "mfa_required" ? 401 : 422 });
1529
1534
  }
1530
1535
  await persistAuthRecovery(record.id, record.mfa_recovery_codes, mfaResult.consumedRecoveryHash);
1531
1536
  const user = { id: record.id, role: record.role, emailVerifiedAt: record.email_verified_at ?? null };
@@ -1536,7 +1541,7 @@ async function completeBrowserSsoLogin(
1536
1541
  abilities: [],${verify ? `
1537
1542
  emailVerifiedAt: user.emailVerifiedAt ?? null,` : ""}
1538
1543
  });
1539
- return jsonResponse({
1544
+ return privateJsonResponse({
1540
1545
  token,
1541
1546
  token_type: "bearer",
1542
1547
  expires_in: jwtTtlSeconds(),
@@ -1548,12 +1553,12 @@ async function completeBrowserSsoLogin(
1548
1553
  "/api/user": {
1549
1554
  GET: kernel.wrapApi(async (request) => {
1550
1555
  const user = await dependencies.container.resolve<AuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1551
- return jsonResponse({ id: user.id, role: user.role ?? "member" });
1556
+ return privateJsonResponse({ id: user.id, role: user.role ?? "member" });
1552
1557
  }),
1553
1558
  },
1554
1559
  "/api/v1/auth/logout": {
1555
1560
  POST: kernel.wrap("api", withErrorHandling(async (request) => {
1556
- const payload = jsonResponse({ ok: true });
1561
+ const payload = privateJsonResponse({ ok: true });
1557
1562
  ${cookie ? `const sessionAuth = dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN);
1558
1563
  const { setCookie } = await sessionAuth.signOut(request);
1559
1564
  payload.headers.append("set-cookie", setCookie);
@@ -1568,7 +1573,7 @@ async function completeBrowserSsoLogin(
1568
1573
  if (user) {
1569
1574
  await issueSignedAuthMail(email, "Reset your password", "/api/v1/auth/reset-password", AUTH_ONE_TIME_PURPOSES.passwordReset, user.id, { email });
1570
1575
  }
1571
- return jsonResponse({ ok: true });
1576
+ return privateJsonResponse({ ok: true });
1572
1577
  })),
1573
1578
  },
1574
1579
  "/api/v1/auth/reset-password": {
@@ -1576,24 +1581,24 @@ async function completeBrowserSsoLogin(
1576
1581
  const body: unknown = await request.json();
1577
1582
  const password = typeof body === "object" && body !== null && "password" in body ? body.password : undefined;
1578
1583
  if (!(await completeSignedPasswordReset(request, password))) {
1579
- return jsonResponse({ error: "Invalid or expired reset link." }, { status: 403 });
1584
+ return privateJsonResponse({ error: "Invalid or expired reset link." }, { status: 403 });
1580
1585
  }
1581
- return jsonResponse({ ok: true });
1586
+ return privateJsonResponse({ ok: true });
1582
1587
  }))),
1583
1588
  },` : "";
1584
1589
  const jsonVerify = jsonApi && verify ? `
1585
1590
  "/api/v1/auth/verify-email": {
1586
1591
  POST: kernel.wrap("api", kernel.wrapSigned(withErrorHandling(async (request) => {
1587
1592
  if (!(await completeSignedEmailVerification(request))) {
1588
- return jsonResponse({ error: "Invalid or expired verification link." }, { status: 403 });
1593
+ return privateJsonResponse({ error: "Invalid or expired verification link." }, { status: 403 });
1589
1594
  }
1590
- return jsonResponse({ ok: true });
1595
+ return privateJsonResponse({ ok: true });
1591
1596
  }))),
1592
1597
  },` : "";
1593
1598
  const csrfRoute = `
1594
1599
  "/api/v1/auth/csrf": {
1595
1600
  GET: kernel.wrap("api", withErrorHandling(async (request) => {
1596
- return jsonResponse({ token: resolveCsrfTokenForRequest(request) });
1601
+ return privateJsonResponse({ token: resolveCsrfTokenForRequest(request) });
1597
1602
  })),
1598
1603
  },`;
1599
1604
  const cookieJsonAuth = cookie && !jsonApi ? `
@@ -1602,16 +1607,16 @@ async function completeBrowserSsoLogin(
1602
1607
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1603
1608
  return runWithLoginUser(email, async (record) => {
1604
1609
  if (!record?.password || !(await verifyPassword(password, record.password))) {
1605
- return jsonResponse({ error: "Invalid credentials" }, { status: 422 });
1610
+ return privateJsonResponse({ error: "Invalid credentials" }, { status: 422 });
1606
1611
  }
1607
1612
  const mfaResult = completePasswordLogin(record, { mfaCode: mfa_code });
1608
1613
  if (!mfaResult.ok) {
1609
- return jsonResponse({ error: mfaResult.error }, { status: mfaResult.error === "mfa_required" ? 401 : 422 });
1614
+ return privateJsonResponse({ error: mfaResult.error }, { status: mfaResult.error === "mfa_required" ? 401 : 422 });
1610
1615
  }
1611
1616
  await persistAuthRecovery(record.id, record.mfa_recovery_codes, mfaResult.consumedRecoveryHash);
1612
1617
  const sessionAuth = dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN);
1613
1618
  const { setCookie } = await sessionAuth.signIn(sessionUser(record));
1614
- const payload = jsonResponse({ ok: true });
1619
+ const payload = privateJsonResponse({ ok: true });
1615
1620
  payload.headers.append("set-cookie", setCookie);
1616
1621
  return payload;
1617
1622
  });
@@ -1621,7 +1626,7 @@ async function completeBrowserSsoLogin(
1621
1626
  GET: kernel.wrapApi(async (request) => {
1622
1627
  const user = await dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1623
1628
  const record = await starterAuthDirectory.findByIdOrThrow(Number(user.id));
1624
- return jsonResponse({
1629
+ return privateJsonResponse({
1625
1630
  id: record.id,
1626
1631
  name: record.name ?? record.email,
1627
1632
  email: record.email,
@@ -1633,7 +1638,7 @@ async function completeBrowserSsoLogin(
1633
1638
  POST: kernel.wrap("api", withErrorHandling(async (request) => {
1634
1639
  const sessionAuth = dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN);
1635
1640
  const { setCookie } = await sessionAuth.signOut(request);
1636
- const payload = jsonResponse({ ok: true });
1641
+ const payload = privateJsonResponse({ ok: true });
1637
1642
  payload.headers.append("set-cookie", setCookie);
1638
1643
  return payload;
1639
1644
  })),
@@ -1658,13 +1663,13 @@ async function completeBrowserSsoLogin(
1658
1663
  const samlResponse = String(form.get("SAMLResponse") ?? "");
1659
1664
  const relayState = String(form.get("RelayState") ?? "");
1660
1665
  if (!verifyOAuthState(request, relayState)) {
1661
- return jsonResponse({ error: "Invalid SAML state." }, { status: 403 });
1666
+ return privateJsonResponse({ error: "Invalid SAML state." }, { status: 403 });
1662
1667
  }
1663
1668
  const profile = await createSamlServiceProvider()
1664
1669
  .consumePost(samlResponse, relayState)
1665
1670
  .catch(() => null);
1666
1671
  if (!profile) {
1667
- return jsonResponse({ error: "Invalid SAML response." }, { status: 400 });
1672
+ return privateJsonResponse({ error: "Invalid SAML response." }, { status: 400 });
1668
1673
  }
1669
1674
  return completeBrowserSsoLogin(dependencies, profile, "SAML");
1670
1675
  })),
@@ -1700,14 +1705,14 @@ async function completeBrowserSsoLogin(
1700
1705
  const code = url.searchParams.get("code");
1701
1706
  const state = url.searchParams.get("state");
1702
1707
  if (!code || !verifyOAuthState(request, state)) {
1703
- return jsonResponse({ error: "Invalid GitHub OAuth state." }, { status: 403 });
1708
+ return privateJsonResponse({ error: "Invalid GitHub OAuth state." }, { status: 403 });
1704
1709
  }
1705
1710
  const redirectUri = process.env.GITHUB_REDIRECT_URI?.trim() || \`\${appUrl()}/auth/github/callback\`;
1706
1711
  const profile = await new GitHubOAuthProvider({ clientId, clientSecret, redirectUri })
1707
1712
  .exchangeCode(code)
1708
1713
  .catch(() => null);
1709
1714
  if (!profile) {
1710
- return jsonResponse({ error: "Invalid GitHub OAuth response." }, { status: 400 });
1715
+ return privateJsonResponse({ error: "Invalid GitHub OAuth response." }, { status: 400 });
1711
1716
  }
1712
1717
  return completeBrowserSsoLogin(dependencies, profile, "GitHub");
1713
1718
  })),
@@ -1752,7 +1757,7 @@ async function completeBrowserSsoLogin(
1752
1757
  const state = url.searchParams.get("state");
1753
1758
  const pkce = readOidcPkceCookie(request, state);
1754
1759
  if (!code || !verifyOAuthState(request, state) || !pkce) {
1755
- const denied = jsonResponse({ error: "Invalid OIDC state." }, { status: 403 });
1760
+ const denied = privateJsonResponse({ error: "Invalid OIDC state." }, { status: 403 });
1756
1761
  denied.headers.append("set-cookie", clearOidcPkceCookie());
1757
1762
  return denied;
1758
1763
  }
@@ -1761,7 +1766,7 @@ async function completeBrowserSsoLogin(
1761
1766
  .exchangeCode(code, redirectUri, pkce)
1762
1767
  .catch(() => null);
1763
1768
  if (!profile) {
1764
- const failed = jsonResponse({ error: "Invalid OIDC response." }, { status: 400 });
1769
+ const failed = privateJsonResponse({ error: "Invalid OIDC response." }, { status: 400 });
1765
1770
  failed.headers.append("set-cookie", clearOidcPkceCookie());
1766
1771
  return failed;
1767
1772
  }
@@ -1789,18 +1794,14 @@ async function completeBrowserSsoLogin(
1789
1794
  redirectTo("/login"),
1790
1795
  { level: "success", message: "If that email is available, continue from the sign-in page." },
1791
1796
  );`;
1792
- const verifyRegisterBranch = verify ? `await issueSignedAuthMail(email, "Verify your email", "/email/verify", AUTH_ONE_TIME_PURPOSES.emailVerify, insertedId, { id: String(insertedId) });
1793
- return flashResponse(
1794
- redirectTo("/login"),
1795
- { level: "success", message: "If that email is available, continue from the sign-in page." },
1796
- );` : `return flashResponse(
1797
+ const verifyRegisterBranch = `return flashResponse(
1797
1798
  redirectTo("/login"),
1798
1799
  { level: "success", message: "If that email is available, continue from the sign-in page." },
1799
1800
  );`;
1800
1801
  const cookieRoutes = cookie ? `
1801
1802
  webRoutes({ kernel, dependencies }) {
1802
1803
  const auth = dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN);
1803
- const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN).namespace("auth");
1804
+ const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN).namespace("auth", { headers: { "Cache-Control": "private, no-store" } });
1804
1805
  return {
1805
1806
  "/login": {
1806
1807
  GET: kernel.wrapWebGuest(async (request) =>
@@ -1844,17 +1845,10 @@ async function completeBrowserSsoLogin(
1844
1845
  ${registerSuccessExisting}
1845
1846
  }
1846
1847
  const hashed = await hashPassword(password);
1847
- await runAuthWrite(email, async () => {
1848
- await User.create({
1849
- name,
1850
- email,
1851
- password: hashed,
1852
- is_admin: false,${tenantCreateField}
1853
- });
1854
- });
1855
- ${verify ? `const created = await starterAuthDirectory.findByEmail?.(email);
1856
- const insertedId = created?.id ?? 0;
1857
- ${verifyRegisterBranch}` : verifyRegisterBranch}
1848
+ ${verify ? "const verificationMail = " : ""}await createRegistration({ name, email, password: hashed }${verify ? ', "/email/verify"' : ""});
1849
+ ${verify ? `// SMTP follows the outermost commit, including request RLS.
1850
+ if (verificationMail) await afterCommit(() => mailer().send(verificationMail));` : ""}
1851
+ ${verifyRegisterBranch}
1858
1852
  },
1859
1853
  async (request) =>
1860
1854
  views.render("register.eta", { layout: { title: "Create account" }, errors: { form: "Too many registration attempts. Try again shortly." }, name: "", email: "", password: "" }, { request, status: 429 }),
@@ -3179,9 +3173,9 @@ function renderPackageJson(projectName, options = {}) {
3179
3173
  "@getstrata/cli": "workspace:*",
3180
3174
  "@getstrata/core": "workspace:*"
3181
3175
  } : {
3182
- "@getstrata/bootstrap": "^2.2.41",
3183
- "@getstrata/cli": "^2.2.41",
3184
- "@getstrata/core": "^2.2.41"
3176
+ "@getstrata/bootstrap": "^2.2.43",
3177
+ "@getstrata/cli": "^2.2.43",
3178
+ "@getstrata/core": "^2.2.43"
3185
3179
  };
3186
3180
  coreDeps.eta = "^4.6.0";
3187
3181
  if (options.layers?.database === "mysql") {
@@ -3287,15 +3281,24 @@ function renderSupportingToolsReadme(layers) {
3287
3281
  function renderApiDocs(projectName, layers) {
3288
3282
  const rows = ["| Method | Path | Notes |", "| --- | --- | --- |"];
3289
3283
  rows.push("| `GET` | `/health` | Plain text `ok` (200) when configured database/Redis checks succeed and `notes` is readable (zero rows is still 200). This infrastructure probe runs outside API auth/tenancy admission, never selects a tenant or bypasses RLS, and returns no rows. `degraded` (503) when a dependency or schema check fails. Docker HEALTHCHECK uses this path. |", '| `GET` | `/ready` | JSON from the framework: `{"status":"ready","checks":{"database":"ok","redis":"skipped"}}` (200) or `not_ready` (503). `redis` is `ok` or `error` when `REDIS_URL` is set and `skipped` otherwise. It does not check the schema, so use `/health` as the deploy gate. |');
3290
- rows.push("| `GET` | `/` | Welcome page. Restyle or replace it. |");
3291
3284
  if (authUsesToken(layers.auth)) {
3292
- rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` returns `{ token }`. Requires `GET /api/v1/auth/csrf` then `X-CSRF-Token`. |", "| `POST` | `/api/v1/auth/register` | Creates a user and returns a token. |", "| `GET` | `/api/v1/auth/me` | Requires `Authorization: Bearer <token>`. |");
3285
+ rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` returns `{ token }`. Requires `GET /api/v1/auth/csrf` then `X-CSRF-Token`. |", "| `GET` | `/api/v1/auth/me` | Requires `Authorization: Bearer <token>`. |");
3293
3286
  }
3294
3287
  if (authUsesJwt(layers.auth)) {
3295
3288
  rows.push("| `POST` | `/api/auth/token` | Mints a short-lived JWT. Not an HTML session. Requires CSRF like JSON login. |");
3296
3289
  }
3290
+ if (authUsesToken(layers.auth) || authUsesJwt(layers.auth)) {
3291
+ rows.push("| `POST` | `/api/v1/auth/register` | Returns neutral `{ ok: true }` (201); sign in separately. |", "| `POST` | `/api/v1/auth/forgot-password` | Sends a signed reset link through the mail driver. |", "| `POST` | `/api/v1/auth/reset-password` | Consumes the signed link. |", "| `GET` | `/api/user` | Current user for the active guard. |");
3292
+ }
3297
3293
  if (authNeedsUsers(layers.auth)) {
3298
- rows.push("| `POST` | `/api/v1/auth/forgot-password` | Sends a signed reset link through the mail driver. |", "| `POST` | `/api/v1/auth/reset-password` | Consumes the signed link. |", "| `GET` | `/api/user` | Current user for the active guard. |");
3294
+ rows.push("| `GET` | `/api/v1/auth/csrf` | Issues the CSRF cookie and JSON token for unauthenticated writes. |");
3295
+ }
3296
+ if (authUsesCookie(layers.auth)) {
3297
+ if (!authUsesToken(layers.auth))
3298
+ rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` sets the session cookie and returns `{ ok: true }`. Requires CSRF. |", "| `GET` | `/api/v1/auth/me` | Current user from the session cookie. |");
3299
+ }
3300
+ if (layers.extras.emailVerification && (authUsesToken(layers.auth) || authUsesJwt(layers.auth))) {
3301
+ rows.push("| `POST` | `/api/v1/auth/verify-email` | Consumes the signed verification token; requires CSRF. |");
3299
3302
  }
3300
3303
  if (layers.extras.metrics) {
3301
3304
  rows.push("| `GET` | `/metrics` | Prometheus text. Production requires `Authorization: Bearer <METRICS_TOKEN>`. |");
@@ -3312,10 +3315,10 @@ function renderApiDocs(projectName, layers) {
3312
3315
  if (layers.extras.oidc && authUsesCookie(layers.auth)) {
3313
3316
  rows.push("| `GET` | `/auth/oidc` | OIDC `createAuthorization()` plus `oidc_pkce` cookie. 404 unless `FEATURE_OAUTH=true`. |", "| `GET` | `/auth/oidc/callback` | Reads PKCE, exchanges the code, JIT user, MFA gate, cookie session. |");
3314
3317
  }
3315
- const authNote = layers.auth === "headers" ? `Auth is \`headers\`. Send \`x-authenticated-user-id\` (and optional \`x-authenticated-user-role\`) for local work and tests. There are no login endpoints and no \`users\` table. Production must set \`AUTH_DEV_HEADERS=false\`, which turns those headers off and leaves you without a guard, so pick another auth layer before you ship.` : authUsesToken(layers.auth) ? `Sign in with \`GET /api/v1/auth/csrf\` then \`POST /api/v1/auth/login\` (send \`X-CSRF-Token\`), then send \`Authorization: Bearer <token>\` on every request. Tokens are stored hashed in \`api_tokens\` and expire after \`API_TOKEN_DEFAULT_EXPIRY_DAYS\` (30 in \`.env.example\`). The response includes \`expires_at\`.` : `Mint a JWT with \`POST /api/auth/token\`, then send \`Authorization: Bearer <jwt>\`. JWTs expire; re-mint rather than refreshing in place.`;
3318
+ const authNote = layers.auth === "headers" ? `Auth is \`headers\`. Send \`x-authenticated-user-id\` (and optional \`x-authenticated-user-role\`) for local work and tests. There are no login endpoints and no \`users\` table. Production must set \`AUTH_DEV_HEADERS=false\`, which turns those headers off and leaves you without a guard, so pick another auth layer before you ship.` : authUsesToken(layers.auth) ? `Sign in with \`GET /api/v1/auth/csrf\` then \`POST /api/v1/auth/login\` (send \`X-CSRF-Token\`), then send \`Authorization: Bearer <token>\` on every request. Tokens are stored hashed in \`api_tokens\` and expire after \`API_TOKEN_DEFAULT_EXPIRY_DAYS\` (30 in \`.env.example\`). The response includes \`expires_at\`.` : authUsesCookie(layers.auth) ? `Sign in with \`GET /api/v1/auth/csrf\` then \`POST /api/v1/auth/login\`; preserve the session and CSRF cookies. The response sets a cookie and returns \`{ ok: true }\`. API mode does not serve HTML login or registration forms.` : `Mint a JWT with \`POST /api/auth/token\`, then send \`Authorization: Bearer <jwt>\`. JWTs expire; re-mint rather than refreshing in place.`;
3316
3319
  return `# ${projectName} API
3317
3320
 
3318
- \`FRONTEND_MODE=${layers.frontend}\`. ${layers.frontend === "api" ? "No server-rendered views beyond the welcome page and no SPA assets." : `HTML is served alongside this API. The SPA is mounted at \`${layers.spaPrefix}\`.`}
3321
+ \`FRONTEND_MODE=${layers.frontend}\`. ${layers.frontend === "api" ? "API-only: no server-rendered welcome/login pages or SPA assets. The root path is not a generated endpoint." : `HTML is served alongside this API. The SPA is mounted at \`${layers.spaPrefix}\`.`}
3319
3322
 
3320
3323
  ## Routes this app serves today
3321
3324
 
@@ -4040,7 +4043,7 @@ function renderMigrateTs(layers) {
4040
4043
  const tenancyOn = usesTenantTable(layers.tenancy);
4041
4044
  const ph = layers.database === "postgres";
4042
4045
  const verifyOn = layers.extras.emailVerification && authNeedsUsers(layers.auth);
4043
- const verifiedNow = nowTimestampLiteral(layers.database);
4046
+ const verifiedNow = "sqlTimestamp()";
4044
4047
  const seedTenant = tenancyOn ? `
4045
4048
  const [{ count: tenantCount }] = await sql.unsafe<{ count: string | number }>(
4046
4049
  "SELECT COUNT(*) AS count FROM tenant",
@@ -4074,7 +4077,8 @@ function renderMigrateTs(layers) {
4074
4077
  const rlsBypassImport = layers.tenancy === "rls" && layers.database === "postgres" ? `import { runWithMigrationBypass } from "@getstrata/core/tenant/databaseTenantContext";
4075
4078
  ` : "";
4076
4079
  const bindSql = seedTenant || layers.tenancy === "rls" && layers.database === "postgres" ? ` const sql = getSql();
4077
- ` : "";
4080
+ ` : ` getSql();
4081
+ `;
4078
4082
  const seedOpen = layers.tenancy === "rls" && layers.database === "postgres" ? ` await runWithMigrationBypass(async () => {
4079
4083
  ` : "";
4080
4084
  const seedClose = layers.tenancy === "rls" && layers.database === "postgres" ? `
@@ -4082,11 +4086,11 @@ function renderMigrateTs(layers) {
4082
4086
  const noteCreate = tenancyOn ? `await Note.create({ body: "Welcome to Strata!", tenant_id: 1 });` : `await Note.create({ body: "Welcome to Strata!" });`;
4083
4087
  const userImport = authNeedsUsers(layers.auth) ? `import { User } from "../models/User.ts";
4084
4088
  ` : "";
4085
- const needsSqlClient = Boolean(seedTenant) || layers.tenancy === "rls" && layers.database === "postgres";
4086
- const databaseImport = needsSqlClient ? `import { closeDatabase, getSql } from "../bootstrap/database.ts";
4087
- ` : `import { closeDatabase } from "../bootstrap/database.ts";
4089
+ const databaseImport = `import { closeDatabase, getSql } from "../bootstrap/database.ts";
4088
4090
  `;
4089
- return `${hashImport}${rlsBypassImport}${ensureImport(layers)}${databaseImport}import { migrateDatabase } from "@getstrata/core/database/migrations";
4091
+ const timestampImport = verifyOn ? `import { sqlTimestamp } from "@getstrata/core/database/dialect";
4092
+ ` : "";
4093
+ return `${hashImport}${timestampImport}${rlsBypassImport}${ensureImport(layers)}${databaseImport}import { migrateDatabase } from "@getstrata/core/database/migrations";
4090
4094
  import { Note } from "../models/Note.ts";
4091
4095
  ${userImport}import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
4092
4096
  import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
@@ -12,9 +12,9 @@
12
12
  "check": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@getstrata/bootstrap": "^2.2.41",
16
- "@getstrata/cli": "^2.2.41",
17
- "@getstrata/core": "^2.2.41",
15
+ "@getstrata/bootstrap": "^2.2.43",
16
+ "@getstrata/cli": "^2.2.43",
17
+ "@getstrata/core": "^2.2.43",
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.41",
3
+ "version": "2.2.43",
4
4
  "description": "Interactive create-strata wizard. Choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",