@getstrata/starter 3.0.5 → 3.0.8

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
@@ -1390,69 +1390,18 @@ async function resolveStarterPlan(flags, injected) {
1390
1390
  }
1391
1391
  }
1392
1392
 
1393
- // src/auth/routePersistence.ts
1394
- function matching(source, start, open, close) {
1395
- let depth = 0;
1396
- for (let index = start;index < source.length; index++) {
1397
- const char = source[index];
1398
- if (char === '"' || char === "'" || char === "`") {
1399
- const quote = char;
1400
- for (index++;index < source.length; index++) {
1401
- if (source[index] === "\\")
1402
- index++;
1403
- else if (source[index] === quote)
1404
- break;
1405
- }
1406
- continue;
1407
- }
1408
- if (char === "/" && source[index + 1] === "/") {
1409
- while (index < source.length && source[index] !== `
1410
- `)
1411
- index++;
1412
- continue;
1413
- }
1414
- if (char === "/" && source[index + 1] === "*") {
1415
- index = source.indexOf("*/", index + 2);
1416
- if (index < 0)
1417
- throw new Error("Unterminated generated auth comment.");
1418
- index++;
1419
- continue;
1420
- }
1421
- if (char === open)
1422
- depth++;
1423
- else if (char === close && --depth === 0)
1424
- return index;
1425
- }
1426
- throw new Error("Unbalanced generated auth handler.");
1427
- }
1428
- function portAuthRouteSource(input) {
1429
- let source = input;
1430
- const callbacks = /async \(request, _ports\) => \{/g;
1431
- for (let match = callbacks.exec(source);match; match = callbacks.exec(source)) {
1432
- const open = source.indexOf("{", match.index);
1433
- const end = matching(source, open, "{", "}");
1434
- const body = source.slice(open, end + 1);
1435
- if (/authServices\.(?:directory|session)|runWithLoginUser|runWithLockedAccount|runAuthWrite|createRegistration|issueSignedAuthMail|completeSigned|completeBrowserSsoLogin|enrollMfa/.test(body)) {
1436
- source = source.slice(0, match.index) + "kernel.wrapIdentity(" + source.slice(match.index, end + 1) + ")" + source.slice(end + 1);
1437
- callbacks.lastIndex = end + "kernel.wrapIdentity(".length + 2;
1438
- } else
1439
- callbacks.lastIndex = end + 1;
1440
- }
1441
- return source;
1442
- }
1443
-
1444
1393
  // src/auth/renderBrowserRoutes.ts
1445
1394
  function renderMfaChallengeRoutes() {
1446
1395
  return ` "/login/mfa": {
1447
- GET: kernel.wrapWebGuest(async (request, _ports) => {
1396
+ GET: kernel.wrapWebGuest(kernel.wrapIdentity(async (request, _ports) => {
1448
1397
  const pending = authServices.pendingMfa.read(request);
1449
1398
  const record = pending ? await authServices.directory(_ports).findByIdOrThrow(pending.userId).catch(() => null) : null;
1450
1399
  if (!record?.is_active || record.auth_version !== pending?.authVersion) return redirectTo("/login");
1451
1400
  return views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: {}, code: "" }, { request });
1452
- }),
1401
+ })),
1453
1402
  POST: wrapWebLogin(
1454
1403
  kernel,
1455
- async (request, _ports) => {
1404
+ kernel.wrapIdentity(async (request, _ports) => {
1456
1405
  const pending = authServices.pendingMfa.read(request);
1457
1406
  if (!pending) {
1458
1407
  return redirectTo("/login");
@@ -1474,7 +1423,7 @@ function renderMfaChallengeRoutes() {
1474
1423
  signed.headers.append("set-cookie", authServices.pendingMfa.clearCookie());
1475
1424
  return signed;
1476
1425
  });
1477
- },
1426
+ }),
1478
1427
  async (request) =>
1479
1428
  views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: { code: "Too many login attempts. Try again shortly." }, code: "" }, { request, status: 429 }),
1480
1429
  ),
@@ -1513,7 +1462,7 @@ function renderBrowserAuthRoutes({
1513
1462
  ),
1514
1463
  POST: wrapWebLogin(
1515
1464
  kernel,
1516
- async (request, _ports) => {
1465
+ kernel.wrapIdentity(async (request, _ports) => {
1517
1466
  const { fields } = await parseFormBody(request);
1518
1467
  const { email, password, mfa_code } = parseLoginCredentials(fields);
1519
1468
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
@@ -1522,7 +1471,7 @@ function renderBrowserAuthRoutes({
1522
1471
  const user = mfaResult.user;
1523
1472
  return authServices.session(_ports).signInRedirect(sessionUser(user), "/");
1524
1473
  });
1525
- },
1474
+ }),
1526
1475
  async (request) =>
1527
1476
  views.render("login.eta", { layout: { title: "Sign in" }, errors: { email: "Too many login attempts. Try again shortly." }, email: "", password: "" }, { request, status: 429 }),
1528
1477
  ),
@@ -1536,7 +1485,7 @@ function renderBrowserAuthRoutes({
1536
1485
  }),
1537
1486
  POST: wrapWebRegister(
1538
1487
  kernel,
1539
- async (request, _ports) => {
1488
+ kernel.wrapIdentity(async (request, _ports) => {
1540
1489
  if (!authServices.config.registrationEnabled) {
1541
1490
  return new Response("Not found", { status: 404 });
1542
1491
  }
@@ -1552,7 +1501,7 @@ function renderBrowserAuthRoutes({
1552
1501
  ${verify ? `// SMTP follows the outermost commit, including request RLS.
1553
1502
  if (verificationMail) await deferAuthEffect(_ports, () => authServices.mail.send(verificationMail));` : ""}
1554
1503
  ${verifyRegisterBranch}
1555
- },
1504
+ }),
1556
1505
  async (request) =>
1557
1506
  views.render("register.eta", { layout: { title: "Create account" }, errors: { form: "Too many registration attempts. Try again shortly." }, name: "", email: "", password: "" }, { request, status: 429 }),
1558
1507
  ),
@@ -1561,7 +1510,7 @@ function renderBrowserAuthRoutes({
1561
1510
  GET: kernel.wrapWebGuest(async (request) =>
1562
1511
  views.render("forgot-password.eta", { layout: { title: "Forgot password" }, errors: {}, email: "" }, { request }),
1563
1512
  ),
1564
- POST: kernel.wrapWeb(async (request, _ports) => {
1513
+ POST: kernel.wrapWeb(kernel.wrapIdentity(async (request, _ports) => {
1565
1514
  const { fields } = await parseFormBody(request);
1566
1515
  const email = parseForgotPasswordEmail(fields);
1567
1516
  const user = await authServices.directory(_ports).findByEmail?.(email);
@@ -1572,14 +1521,14 @@ function renderBrowserAuthRoutes({
1572
1521
  level: "success",
1573
1522
  message: "If that account exists, a reset link is on its way.",
1574
1523
  }, authServices.flash);
1575
- }),
1524
+ })),
1576
1525
  },
1577
1526
  "/reset-password": {
1578
1527
  GET: kernel.wrapWeb(kernel.wrapSigned(async (request, _ports) => {
1579
1528
  const email = new URL(request.url).searchParams.get("email") ?? "";
1580
1529
  return views.render("reset-password.eta", { layout: { title: "Reset password" }, errors: {}, password: "", email, action: \`\${new URL(request.url).pathname}\${new URL(request.url).search}\` }, { request });
1581
1530
  })),
1582
- POST: kernel.wrapWeb(kernel.wrapSigned(async (request, _ports) => {
1531
+ POST: kernel.wrapWeb(kernel.wrapSigned(kernel.wrapIdentity(async (request, _ports) => {
1583
1532
  const { fields } = await parseFormBody(request);
1584
1533
  const email = new URL(request.url).searchParams.get("email") ?? fields.email ?? "";
1585
1534
  const password = fields.password ?? "";
@@ -1587,13 +1536,13 @@ function renderBrowserAuthRoutes({
1587
1536
  return views.render("reset-password.eta", { layout: { title: "Reset password" }, errors: { password: "Invalid or expired reset link." }, password: "", email, action: \`\${new URL(request.url).pathname}\${new URL(request.url).search}\` }, { request });
1588
1537
  }
1589
1538
  return flashResponse(redirectTo("/login"), { level: "success", message: "Password updated. Sign in." }, authServices.flash);
1590
- })),
1539
+ }))),
1591
1540
  },
1592
1541
  "/logout": {
1593
- POST: kernel.wrapWebAuthenticatedAllowUnverified(async (request, _ports) => { return authServices.session(_ports).signOutRedirect(request, "/"); }),
1542
+ POST: kernel.wrapWebAuthenticatedAllowUnverified(kernel.wrapIdentity(async (request, _ports) => { return authServices.session(_ports).signOutRedirect(request, "/"); })),
1594
1543
  },${verify ? `
1595
1544
  "/email/verify": {
1596
- GET: kernel.wrapWeb(async (request, _ports) => {
1545
+ GET: kernel.wrapWeb(kernel.wrapIdentity(async (request, _ports) => {
1597
1546
  const url = new URL(request.url);
1598
1547
  if (url.searchParams.get("signature")) {
1599
1548
  assertValidSignature(request, authServices.config.signatureSecret);
@@ -1609,23 +1558,23 @@ function renderBrowserAuthRoutes({
1609
1558
  );
1610
1559
  }
1611
1560
  return views.render("verify-email.eta", { layout: { title: "Verify email" } }, { request });
1612
- }),
1561
+ })),
1613
1562
  },
1614
1563
  "/email/verification-notification": {
1615
- POST: kernel.wrapWebAuthenticatedAllowUnverified(async (request, _ports) => {
1564
+ POST: kernel.wrapWebAuthenticatedAllowUnverified(kernel.wrapIdentity(async (request, _ports) => {
1616
1565
  const user = await _ports.auth.user(request);
1617
1566
  if (user) {
1618
1567
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1619
1568
  await issueSignedAuthMail(_ports, authServices, record.email ?? "", "Verify your email", "/email/verify", AUTH_ONE_TIME_PURPOSES.emailVerify, Number(record.id), { id: String(record.id) });
1620
1569
  }
1621
1570
  return flashResponse(redirectTo("/email/verify"), { level: "info", message: "Verification link sent." }, authServices.flash);
1622
- }),
1571
+ })),
1623
1572
  },` : ""}${mfa ? `
1624
1573
  ${renderMfaChallengeRoutes()} "/confirm-password": {
1625
1574
  GET: kernel.wrapWebAuthenticated(async (request) =>
1626
1575
  views.render("confirm-password.eta", { layout: { title: "Confirm password" }, errors: {}, password: "" }, { request }),
1627
1576
  ),
1628
- POST: kernel.wrapWebAuthenticated(async (request, _ports) => {
1577
+ POST: kernel.wrapWebAuthenticated(kernel.wrapIdentity(async (request, _ports) => {
1629
1578
  const user = await _ports.auth.user(request);
1630
1579
  if (!user) {
1631
1580
  return redirectTo("/login");
@@ -1642,10 +1591,10 @@ ${renderMfaChallengeRoutes()} "/confirm-password": {
1642
1591
  confirmed.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id), record.auth_version, authServices.config.passwordConfirmation));
1643
1592
  return confirmed;
1644
1593
  });
1645
- }),
1594
+ })),
1646
1595
  },
1647
1596
  "/account/mfa": {
1648
- GET: kernel.wrapWebAuthenticated(async (request, _ports) => {
1597
+ GET: kernel.wrapWebAuthenticated(kernel.wrapIdentity(async (request, _ports) => {
1649
1598
  const secret = generateTotpSecret();
1650
1599
  const user = await _ports.auth.user(request);
1651
1600
  const record = user ? await authServices.directory(_ports).findByIdOrThrow(Number(user.id)) : null;
@@ -1655,8 +1604,8 @@ ${renderMfaChallengeRoutes()} "/confirm-password": {
1655
1604
  issuer: authServices.config.appName,
1656
1605
  });
1657
1606
  return views.render("mfa-setup.eta", { layout: { title: "MFA" }, errors: {}, code: "", secret, otpauth }, { request });
1658
- }),
1659
- POST: kernel.wrapWebPasswordConfirm(async (request, _ports) => {
1607
+ })),
1608
+ POST: kernel.wrapWebPasswordConfirm(kernel.wrapIdentity(async (request, _ports) => {
1660
1609
  const user = await _ports.auth.user(request);
1661
1610
  if (!user) {
1662
1611
  return redirectTo("/login");
@@ -1682,11 +1631,11 @@ ${renderMfaChallengeRoutes()} "/confirm-password": {
1682
1631
  otpauth: buildOtpauthUrl({ secret, account: "user", issuer: authServices.config.appName }),
1683
1632
  recoveryCodes,
1684
1633
  }, { request });
1685
- }),
1634
+ })),
1686
1635
  },` : ""}
1687
1636
  };
1688
1637
  },` : "";
1689
- return portAuthRouteSource(cookieRoutes);
1638
+ return cookieRoutes;
1690
1639
  }
1691
1640
 
1692
1641
  // src/auth/renderApiRoutes.ts
@@ -1708,7 +1657,7 @@ ${renderMfaChallengeRoutes()}
1708
1657
  }, kernel.group("api")),` : "";
1709
1658
  const tokenLogin = plan.decisions.token ? `
1710
1659
  "/api/v1/auth/login": {
1711
- POST: kernel.wrap("api", kernel.wrapLogin(async (request, _ports) => {
1660
+ POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(async (request, _ports) => {
1712
1661
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1713
1662
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
1714
1663
  const mfaResult = await authenticatePasswordUser(_ports, authServices, candidate, password, mfa_code);
@@ -1741,10 +1690,10 @@ ${renderMfaChallengeRoutes()}
1741
1690
  payload.headers.append("set-cookie", setCookie);
1742
1691
  ` : ""}return payload;
1743
1692
  });
1744
- })),
1693
+ }))),
1745
1694
  },
1746
1695
  "/api/v1/auth/me": {
1747
- GET: kernel.wrapApi(async (request, _ports) => {
1696
+ GET: kernel.wrapApi(kernel.wrapIdentity(async (request, _ports) => {
1748
1697
  const user = await _ports.auth.requireUser(request);
1749
1698
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1750
1699
  return privateJsonResponse({
@@ -1753,11 +1702,11 @@ ${renderMfaChallengeRoutes()}
1753
1702
  email: record.email,
1754
1703
  role: record.role,
1755
1704
  });
1756
- }),
1705
+ })),
1757
1706
  },` : "";
1758
1707
  const jsonRegister = jsonAccounts ? `
1759
1708
  "/api/v1/auth/register": {
1760
- POST: kernel.wrap("api", kernel.wrapRegister(async (request, _ports) => {
1709
+ POST: kernel.wrap("api", kernel.wrapRegister(kernel.wrapIdentity(async (request, _ports) => {
1761
1710
  if (!authServices.config.registrationEnabled) {
1762
1711
  return privateJsonResponse({ error: "Not found" }, { status: 404 });
1763
1712
  }
@@ -1772,11 +1721,11 @@ ${renderMfaChallengeRoutes()}
1772
1721
  ${verify ? `// SMTP follows the outermost commit, including request RLS.
1773
1722
  if (verificationMail) await deferAuthEffect(_ports, () => authServices.mail.send(verificationMail));` : ""}
1774
1723
  return privateJsonResponse({ ok: true }, { status: 201 });
1775
- })),
1724
+ }))),
1776
1725
  },` : "";
1777
1726
  const jwtLogin = plan.decisions.jwt ? `
1778
1727
  "/api/auth/token": {
1779
- POST: kernel.wrap("api", kernel.wrapLogin(async (request, _ports) => {
1728
+ POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(async (request, _ports) => {
1780
1729
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1781
1730
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
1782
1731
  const mfaResult = await authenticatePasswordUser(_ports, authServices, candidate, password, mfa_code);
@@ -1801,7 +1750,7 @@ ${renderMfaChallengeRoutes()}
1801
1750
  expires_in: authServices.config.jwtTtlSeconds,
1802
1751
  });
1803
1752
  });
1804
- })),
1753
+ }))),
1805
1754
  },` : "";
1806
1755
  const apiUser = bearerApi ? `
1807
1756
  "/api/user": {
@@ -1811,57 +1760,57 @@ ${renderMfaChallengeRoutes()}
1811
1760
  }),
1812
1761
  },
1813
1762
  "/api/v1/auth/logout": {
1814
- POST: kernel.wrap("api", async (request, _ports) => {
1763
+ POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}async (request, _ports) => {
1815
1764
  const payload = privateJsonResponse({ ok: true });
1816
1765
  ${cookie ? `const sessionAuth = authServices.session(_ports);
1817
1766
  const { setCookie } = await sessionAuth.signOut(request);
1818
1767
  payload.headers.append("set-cookie", setCookie);
1819
1768
  ` : ""}return payload;
1820
- }),
1769
+ }${cookie ? ")" : ""}),
1821
1770
  },` : "";
1822
1771
  const jsonPassword = jsonAccounts ? `
1823
1772
  "/api/v1/auth/forgot-password": {
1824
- POST: kernel.wrap("api", async (request, _ports) => {
1773
+ POST: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1825
1774
  const email = await parseJsonBody(request, parseForgotPasswordEmail);
1826
1775
  const user = await authServices.directory(_ports).findByEmail?.(email);
1827
1776
  if (user) {
1828
1777
  await issueSignedAuthMail(_ports, authServices, email, "Reset your password", "/api/v1/auth/reset-password", AUTH_ONE_TIME_PURPOSES.passwordReset, user.id, { email });
1829
1778
  }
1830
1779
  return privateJsonResponse({ ok: true });
1831
- }),
1780
+ })),
1832
1781
  },
1833
1782
  "/api/v1/auth/reset-password": {
1834
- POST: kernel.wrap("api", kernel.wrapSigned(async (request, _ports) => {
1783
+ POST: kernel.wrap("api", kernel.wrapSigned(kernel.wrapIdentity(async (request, _ports) => {
1835
1784
  const body = await parseJsonBody(request, (payload) => payload);
1836
1785
  const password = typeof body === "object" && body !== null && "password" in body ? body.password : undefined;
1837
1786
  if (!(await completeSignedPasswordReset(_ports, request, password))) {
1838
1787
  return privateJsonResponse({ error: "Invalid or expired reset link." }, { status: 403 });
1839
1788
  }
1840
1789
  return privateJsonResponse({ ok: true });
1841
- })),
1790
+ }))),
1842
1791
  },` : "";
1843
1792
  const jsonVerify = plan.decisions.jsonVerification ? `
1844
1793
  "/api/v1/auth/verify-email": {
1845
- POST: kernel.wrap("api", kernel.wrapSigned(async (request, _ports) => {
1794
+ POST: kernel.wrap("api", kernel.wrapSigned(kernel.wrapIdentity(async (request, _ports) => {
1846
1795
  if (!(await completeSignedEmailVerification(_ports, request))) {
1847
1796
  return privateJsonResponse({ error: "Invalid or expired verification link." }, { status: 403 });
1848
1797
  }
1849
1798
  return privateJsonResponse({ ok: true });
1850
- })),
1799
+ }))),
1851
1800
  },` : "";
1852
1801
  const jsonAccountManagement = jsonCookieAccounts ? `
1853
1802
  ${verify ? `"/api/v1/auth/verification-notification": {
1854
- POST: kernel.wrapApi(async (request, _ports) => {
1803
+ POST: kernel.wrapApi(kernel.wrapIdentity(async (request, _ports) => {
1855
1804
  const user = await _ports.auth.requireUser(request);
1856
1805
  await runWithLockedAccount(_ports, Number(user.id), async (record, _ports) => {
1857
1806
  if (!record?.is_active || record.auth_version !== user.authVersion) throw new ConflictError("Account changed. Sign in again.");
1858
1807
  if (!record.email_verified_at) await issueSignedAuthMail(_ports, authServices, record.email ?? "", "Verify your email", "/api/v1/auth/verify-email", AUTH_ONE_TIME_PURPOSES.emailVerify, record.id, { id: String(record.id) });
1859
1808
  });
1860
1809
  return privateJsonResponse({ ok: true });
1861
- }),
1810
+ })),
1862
1811
  },` : ""}
1863
1812
  ${mfa ? `"/api/v1/auth/confirm-password": {
1864
- POST: kernel.wrap("api", kernel.wrapVerified(async (request, _ports) => {
1813
+ POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapIdentity(async (request, _ports) => {
1865
1814
  const user = await _ports.auth.requireUser(request);
1866
1815
  const { password } = await parseJsonBody(request, (payload) => validateObject(payload, { password: [required(), stringRule()] }));
1867
1816
  return runWithLockedAccount(_ports, Number(user.id), async (record, _ports) => {
@@ -1871,23 +1820,23 @@ ${renderMfaChallengeRoutes()}
1871
1820
  response.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id), record.auth_version, authServices.config.passwordConfirmation));
1872
1821
  return response;
1873
1822
  });
1874
- })),
1823
+ }))),
1875
1824
  },
1876
1825
  "/api/v1/auth/mfa": {
1877
- GET: kernel.wrap("api", kernel.wrapVerified(async (request, _ports) => {
1826
+ GET: kernel.wrap("api", kernel.wrapVerified(kernel.wrapIdentity(async (request, _ports) => {
1878
1827
  const user = await _ports.auth.requireUser(request);
1879
1828
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1880
1829
  const secret = generateTotpSecret();
1881
1830
  return privateJsonResponse({ secret, otpauth: buildOtpauthUrl({ secret, account: record.email ?? "user", issuer: authServices.config.appName }) });
1882
- })),
1883
- POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapPasswordConfirm(async (request, _ports) => {
1831
+ }))),
1832
+ POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapPasswordConfirm(kernel.wrapIdentity(async (request, _ports) => {
1884
1833
  const user = await _ports.auth.requireUser(request);
1885
1834
  const fields = await parseJsonBody(request, (payload) => validateObject(payload, { secret: [required(), stringRule()], code: [required(), stringRule()] }));
1886
1835
  const secret = String(fields.secret).trim();
1887
1836
  if (!verifyTotp(secret, String(fields.code).trim())) return privateJsonResponse({ error: "Could not confirm that code." }, { status: 422 });
1888
1837
  const recoveryCodes = await enrollMfa(_ports, authServices, user, secret);
1889
1838
  return privateJsonResponse({ recoveryCodes });
1890
- }))),
1839
+ })))),
1891
1840
  },` : ""}` : "";
1892
1841
  const csrfRoute = `
1893
1842
  "/api/v1/auth/csrf": {
@@ -1897,7 +1846,7 @@ ${renderMfaChallengeRoutes()}
1897
1846
  },`;
1898
1847
  const cookieJsonAuth = plan.decisions.cookieJsonLogin ? `
1899
1848
  "/api/v1/auth/login": {
1900
- POST: kernel.wrap("api", kernel.wrapLogin(async (request, _ports) => {
1849
+ POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(async (request, _ports) => {
1901
1850
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1902
1851
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
1903
1852
  const mfaResult = await authenticatePasswordUser(_ports, authServices, candidate, password, mfa_code);
@@ -1914,10 +1863,10 @@ ${renderMfaChallengeRoutes()}
1914
1863
  payload.headers.append("set-cookie", setCookie);
1915
1864
  return payload;
1916
1865
  });
1917
- })),
1866
+ }))),
1918
1867
  },
1919
1868
  "/api/v1/auth/me": {
1920
- GET: kernel.wrapApi(async (request, _ports) => {
1869
+ GET: kernel.wrapApi(kernel.wrapIdentity(async (request, _ports) => {
1921
1870
  const user = await _ports.auth.requireUser(request);
1922
1871
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1923
1872
  return privateJsonResponse({
@@ -1926,16 +1875,16 @@ ${renderMfaChallengeRoutes()}
1926
1875
  email: record.email,
1927
1876
  role: record.role,
1928
1877
  });
1929
- }),
1878
+ })),
1930
1879
  },
1931
1880
  "/api/v1/auth/logout": {
1932
- POST: kernel.wrap("api", async (request, _ports) => {
1881
+ POST: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1933
1882
  const sessionAuth = authServices.session(_ports);
1934
1883
  const { setCookie } = await sessionAuth.signOut(request);
1935
1884
  const payload = privateJsonResponse({ ok: true });
1936
1885
  payload.headers.append("set-cookie", setCookie);
1937
1886
  return payload;
1938
- }),
1887
+ })),
1939
1888
  },` : "";
1940
1889
  const samlRoutes = cookie ? `
1941
1890
  "/auth/saml": {
@@ -1943,30 +1892,36 @@ ${renderMfaChallengeRoutes()}
1943
1892
  if (!authServices.config.samlEnabled) {
1944
1893
  return new Response("Not found", { status: 404 });
1945
1894
  }
1946
- const issued = createOAuthState(authServices.config.oauth);
1895
+ const issued = createSamlStateCookie(authServices.config.oauth);
1947
1896
  const url = await authServices.saml(_ports).authorizationUrl(issued.state);
1948
- return new Response(null, { status: 302, headers: { location: url } });
1897
+ return new Response(null, { status: 302, headers: { location: url, "set-cookie": issued.cookie } });
1949
1898
  }),
1950
1899
  },
1951
1900
  "/auth/saml/acs": {
1952
- POST: kernel.wrap("api", async (request, _ports) => {
1901
+ POST: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1953
1902
  if (!authServices.config.samlEnabled) {
1954
1903
  return new Response("Not found", { status: 404 });
1955
1904
  }
1956
1905
  const form = await request.formData();
1957
1906
  const samlResponse = String(form.get("SAMLResponse") ?? "");
1958
1907
  const relayState = String(form.get("RelayState") ?? "");
1959
- if (!verifyOAuthState(request, relayState, authServices.config.oauth)) {
1960
- return privateJsonResponse({ error: "Invalid SAML state." }, { status: 403 });
1908
+ if (!verifySamlState(request, relayState, authServices.config.oauth)) {
1909
+ const denied = privateJsonResponse({ error: "Invalid SAML state." }, { status: 403 });
1910
+ denied.headers.append("set-cookie", clearSamlStateCookie());
1911
+ return denied;
1961
1912
  }
1962
1913
  const profile = await authServices.saml(_ports)
1963
1914
  .consumePost(samlResponse, relayState)
1964
1915
  .catch(() => null);
1965
1916
  if (!profile) {
1966
- return privateJsonResponse({ error: "Invalid SAML response." }, { status: 400 });
1917
+ const failed = privateJsonResponse({ error: "Invalid SAML response." }, { status: 400 });
1918
+ failed.headers.append("set-cookie", clearSamlStateCookie());
1919
+ return failed;
1967
1920
  }
1968
- return completeBrowserSsoLogin(_ports, authServices, profile, "SAML");
1969
- }),
1921
+ const login = await completeBrowserSsoLogin(_ports, authServices, profile, "SAML");
1922
+ login.headers.append("set-cookie", clearSamlStateCookie());
1923
+ return login;
1924
+ })),
1970
1925
  },` : "";
1971
1926
  const githubRoutes = github ? `
1972
1927
  "/auth/github": {
@@ -1980,13 +1935,13 @@ ${renderMfaChallengeRoutes()}
1980
1935
  return new Response("Not found", { status: 404 });
1981
1936
  }
1982
1937
  const redirectUri = authServices.config.github.redirectUri;
1983
- const issued = createOAuthState(authServices.config.oauth);
1938
+ const issued = createOAuthStateCookie(authServices.config.oauth);
1984
1939
  const url = new GitHubOAuthProvider({ clientId, clientSecret, redirectUri, production: authServices.config.github.production, userAgent: authServices.config.github.userAgent }).getAuthorizationUrl(issued.state);
1985
- return new Response(null, { status: 302, headers: { location: url } });
1940
+ return new Response(null, { status: 302, headers: { location: url, "set-cookie": issued.cookie } });
1986
1941
  }),
1987
1942
  },
1988
1943
  "/auth/github/callback": {
1989
- GET: kernel.wrap("api", async (request, _ports) => {
1944
+ GET: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1990
1945
  if (!authServices.config.oauthEnabled) {
1991
1946
  return new Response("Not found", { status: 404 });
1992
1947
  }
@@ -1999,17 +1954,23 @@ ${renderMfaChallengeRoutes()}
1999
1954
  const code = url.searchParams.get("code");
2000
1955
  const state = url.searchParams.get("state");
2001
1956
  if (!code || !verifyOAuthState(request, state, authServices.config.oauth)) {
2002
- return privateJsonResponse({ error: "Invalid GitHub OAuth state." }, { status: 403 });
1957
+ const denied = privateJsonResponse({ error: "Invalid GitHub OAuth state." }, { status: 403 });
1958
+ denied.headers.append("set-cookie", clearOAuthStateCookie(authServices.config.oauth));
1959
+ return denied;
2003
1960
  }
2004
1961
  const redirectUri = authServices.config.github.redirectUri;
2005
1962
  const profile = await new GitHubOAuthProvider({ clientId, clientSecret, redirectUri, production: authServices.config.github.production, userAgent: authServices.config.github.userAgent })
2006
1963
  .exchangeCode(code)
2007
1964
  .catch(() => null);
2008
1965
  if (!profile) {
2009
- return privateJsonResponse({ error: "Invalid GitHub OAuth response." }, { status: 400 });
1966
+ const failed = privateJsonResponse({ error: "Invalid GitHub OAuth response." }, { status: 400 });
1967
+ failed.headers.append("set-cookie", clearOAuthStateCookie(authServices.config.oauth));
1968
+ return failed;
2010
1969
  }
2011
- return completeBrowserSsoLogin(_ports, authServices, profile, "GitHub");
2012
- }),
1970
+ const login = await completeBrowserSsoLogin(_ports, authServices, profile, "GitHub");
1971
+ login.headers.append("set-cookie", clearOAuthStateCookie(authServices.config.oauth));
1972
+ return login;
1973
+ })),
2013
1974
  },` : "";
2014
1975
  const oidcRoutes = oidc ? `
2015
1976
  "/auth/oidc": {
@@ -2036,7 +1997,7 @@ ${renderMfaChallengeRoutes()}
2036
1997
  }),
2037
1998
  },
2038
1999
  "/auth/oidc/callback": {
2039
- GET: kernel.wrap("api", async (request, _ports) => {
2000
+ GET: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
2040
2001
  if (!authServices.config.oauthEnabled) {
2041
2002
  return new Response("Not found", { status: 404 });
2042
2003
  }
@@ -2050,7 +2011,7 @@ ${renderMfaChallengeRoutes()}
2050
2011
  const code = url.searchParams.get("code");
2051
2012
  const state = url.searchParams.get("state");
2052
2013
  const pkce = readOidcPkceCookie(request, state, authServices.config.oauth);
2053
- if (!code || !verifyOAuthState(request, state, authServices.config.oauth) || !pkce) {
2014
+ if (!code || !verifySignedOAuthStateValue(state ?? "", authServices.config.oauth) || !pkce) {
2054
2015
  const denied = privateJsonResponse({ error: "Invalid OIDC state." }, { status: 403 });
2055
2016
  denied.headers.append("set-cookie", clearOidcPkceCookie(authServices.config.oauth));
2056
2017
  return denied;
@@ -2067,7 +2028,7 @@ ${renderMfaChallengeRoutes()}
2067
2028
  const login = await completeBrowserSsoLogin(_ports, authServices, profile, "OIDC");
2068
2029
  login.headers.append("set-cookie", clearOidcPkceCookie(authServices.config.oauth));
2069
2030
  return login;
2070
- }),
2031
+ })),
2071
2032
  },` : "";
2072
2033
  const apiRoutes = plan.decisions.users ? `
2073
2034
  routes({ kernel, dependencies }) {
@@ -2077,7 +2038,7 @@ ${renderMfaChallengeRoutes()}
2077
2038
  return {${mfaContinuation}${csrfRoute}${samlRoutes}${githubRoutes}${oidcRoutes}${cookieJsonAuth}${tokenLogin}${jsonRegister}${jwtLogin}${apiUser}${jsonPassword}${jsonVerify}${jsonAccountManagement}
2078
2039
  };
2079
2040
  },` : "";
2080
- return portAuthRouteSource(apiRoutes);
2041
+ return apiRoutes;
2081
2042
  }
2082
2043
 
2083
2044
  // src/auth/renderImports.ts
@@ -2088,13 +2049,15 @@ function renderAuthImports({
2088
2049
  oidc,
2089
2050
  mfa
2090
2051
  }) {
2091
- const imports = [];
2052
+ const imports = [
2053
+ `import { prepareAccountMail, registerAccount, completeAccountToken, authenticatePasswordAccount, withLoginAccount, parseLoginCredentials, parseRegisterCredentials, parseForgotPasswordEmail } from "@getstrata/bootstrap/auth/accountWorkflows";`
2054
+ ];
2092
2055
  if (plan.decisions.token || cookie) {
2093
2056
  imports.push(`import { randomBytes } from "node:crypto";`);
2094
2057
  }
2095
2058
  imports.push(`import type { BusinessRequestPorts } from "@getstrata/bootstrap/persistenceContracts";`);
2096
2059
  imports.push(`import type { SelectedSession } from "@getstrata/core/contracts/persistence";`);
2097
- imports.push(`import { STARTER_AUTH_SERVICES, type StarterAuthServices } from "../../bootstrap/providers/auth.ts";`);
2060
+ imports.push(`import { STARTER_AUTH_SERVICES, type StarterAuthServices } from "../../bootstrap/auth.ts";`);
2098
2061
  imports.push(`import type { AppModule } from "@getstrata/bootstrap/contracts";`);
2099
2062
  if (cookie) {
2100
2063
  imports.push(`import { parseFormBody } from "@getstrata/bootstrap/web/forms";`);
@@ -2113,11 +2076,11 @@ function renderAuthImports({
2113
2076
  }
2114
2077
  imports.push(`import { hashPassword, verifyPassword } from "@getstrata/core/auth/password";`);
2115
2078
  imports.push(`import { AUTH_ONE_TIME_PURPOSES, consumeOneTimeToken, generateOneTimeToken, hashOneTimeToken, revokeUserSessions as revokeStoredUserSessions } from "@getstrata/core/auth/oneTimeToken";`);
2116
- imports.push(`import { completePasswordLogin, persistConsumedRecoveryHash, type PasswordLoginResult } from "@getstrata/core/auth/passwordLogin";`);
2079
+ imports.push(`import { completePasswordLogin, persistConsumedRecoveryHash } from "@getstrata/core/auth/passwordLogin";`);
2117
2080
  if (mfa) {
2118
2081
  imports.push(`import { createPasswordConfirmCookie } from "@getstrata/core/auth/passwordConfirmCookie";`);
2119
2082
  }
2120
- imports.push(`import { emailRule, minLength, required, stringRule, validateObject } from "@getstrata/core/validation/rules";`);
2083
+ imports.push(`import { required, stringRule, validateObject } from "@getstrata/core/validation/rules";`);
2121
2084
  imports.push(`import { parseJsonBody } from "@getstrata/core/http/validation";`);
2122
2085
  if (plan.decisions.token) {
2123
2086
  imports.push(`import { hashApiToken } from "@getstrata/core/auth/tokenHash";`);
@@ -2128,7 +2091,12 @@ function renderAuthImports({
2128
2091
  if (mfa) {
2129
2092
  imports.push(`import { sanitizeInternalPath } from "@getstrata/core/http/safeInternalPath";`);
2130
2093
  }
2131
- imports.push(oidc ? `import { clearOidcPkceCookie, createOAuthState, readOidcPkceCookie, sealOidcPkceCookie, verifyOAuthState } from "@getstrata/core/security/oauthState";` : `import { createOAuthState, verifyOAuthState } from "@getstrata/core/security/oauthState";`);
2094
+ const oauthImports = ["createSamlStateCookie", "verifySamlState", "clearSamlStateCookie"];
2095
+ if (github)
2096
+ oauthImports.push("createOAuthStateCookie", "clearOAuthStateCookie", "verifyOAuthState");
2097
+ if (oidc)
2098
+ oauthImports.push("createOAuthState", "verifySignedOAuthStateValue", "clearOidcPkceCookie", "readOidcPkceCookie", "sealOidcPkceCookie");
2099
+ imports.push(`import { ${oauthImports.join(", ")} } from "@getstrata/core/security/oauthState";`);
2132
2100
  }
2133
2101
  if (plan.decisions.users) {
2134
2102
  imports.push(`import { privateJsonResponse } from "@getstrata/core/http/response";`);
@@ -2208,64 +2176,12 @@ ${!plan.decisions.tenantTable ? "" : `function establishedTenantId(ports: Busine
2208
2176
  return id!;
2209
2177
  }
2210
2178
  `}
2211
- type StarterPasswordLoginResult =
2212
- | { ok: false; error: "invalid_credentials" }
2213
- | (PasswordLoginResult & { user: StarterAuthUserRecord });
2214
-
2215
- async function authenticatePasswordUser(ports: BusinessRequestPorts, services: StarterAuthServices,
2216
- user: StarterAuthUserRecord | null,
2217
- password: string,
2218
- mfaCode: string | undefined,
2219
- ): Promise<StarterPasswordLoginResult> {
2220
- if (!user?.password || !(await verifyPassword(password, user.password))) {
2221
- return { ok: false, error: "invalid_credentials" };
2222
- }
2223
- const result = completePasswordLogin(user, { mfaCode }, services.mfaSecrets);
2224
- if (!result.ok) return { ...result, user };
2225
- await persistAuthRecovery(ports, user.id, user.mfa_recovery_codes, result.consumedRecoveryHash);
2226
- return { ...result, user };
2227
- }
2228
-
2229
- function parseLoginCredentials(payload: unknown) {
2230
- const body = validateObject(payload, {
2231
- email: [required(), stringRule(), emailRule()],
2232
- password: [required(), stringRule()],
2233
- mfa_code: [stringRule()],
2234
- });
2235
- return {
2236
- email: String(body.email).toLowerCase(),
2237
- password: String(body.password ?? ""),
2238
- mfa_code: typeof body.mfa_code === "string" ? body.mfa_code : undefined,
2239
- };
2179
+ function authenticatePasswordUser(ports: BusinessRequestPorts, services: StarterAuthServices, user: StarterAuthUserRecord | null, password: string, mfaCode: string | undefined) {
2180
+ return authenticatePasswordAccount(user, password, mfaCode, services.mfaSecrets,
2181
+ (account, hash) => persistAuthRecovery(ports, account.id, account.mfa_recovery_codes, hash));
2240
2182
  }
2241
-
2242
- function parseRegisterCredentials(payload: unknown) {
2243
- const body = validateObject(payload, {
2244
- name: [required(), stringRule()],
2245
- email: [required(), stringRule(), emailRule()],
2246
- password: [required(), stringRule(), minLength(8)],
2247
- });
2248
- return {
2249
- name: String(body.name ?? ""),
2250
- email: String(body.email).toLowerCase(),
2251
- password: String(body.password ?? ""),
2252
- };
2253
- }
2254
-
2255
- function parseForgotPasswordEmail(payload: unknown) {
2256
- const body = validateObject(payload, {
2257
- email: [required(), stringRule(), emailRule()],
2258
- });
2259
- return String(body.email).toLowerCase();
2260
- }
2261
-
2262
- async function runWithLoginUser<T>(ports: BusinessRequestPorts, email: string, operation: (record: StarterAuthUserRecord | null, ports: BusinessRequestPorts) => Promise<T>): Promise<T> {
2263
- const candidate = await createStarterAuthDirectory(ports).findByEmail(email);
2264
- if (!candidate) return operation(null, ports);
2265
- return runWithLockedAccount(ports, candidate.id, async (record, ports) => {
2266
- // Recheck identity after locking: provisioning may have changed the email.
2267
- return operation(record?.email === email.trim().toLowerCase() ? record : null, ports);
2268
- });
2183
+ function runWithLoginUser<T>(ports: BusinessRequestPorts, email: string, operation: (record: StarterAuthUserRecord | null, child: BusinessRequestPorts) => Promise<T>): Promise<T> {
2184
+ return withLoginAccount(ports, email, createStarterAuthDirectory, runWithLockedAccount, operation);
2269
2185
  }
2270
2186
 
2271
2187
  async function runAuthWrite<T>(ports: BusinessRequestPorts, identifier: string | number, callback: (ports: BusinessRequestPorts) => Promise<T>): Promise<T> {
@@ -2273,18 +2189,13 @@ async function runAuthWrite<T>(ports: BusinessRequestPorts, identifier: string |
2273
2189
  }
2274
2190
 
2275
2191
  async function prepareSignedAuthMail(ports: BusinessRequestPorts, services: StarterAuthServices, to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
2276
- const issued = generateOneTimeToken();
2277
- const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
2278
- await runAuthWrite(ports, userId, async (ports) => {
2279
- await ports.database.model(AuthOneTimeToken).create({
2280
- purpose,
2281
- user_id: userId,
2282
- token_hash: issued.hash,
2283
- expires_at: authTimestamp(ports, expiresAt),
2284
- });
2192
+ return prepareAccountMail(ports, { to, subject, path, purpose, userId, extra }, {
2193
+ issue: generateOneTimeToken,
2194
+ store: (ports, token) => runAuthWrite(ports, token.userId, async (ports) => {
2195
+ await ports.database.model(AuthOneTimeToken).create({ purpose: token.purpose, user_id: token.userId, token_hash: token.hash, expires_at: authTimestamp(ports, token.expiresAt) });
2196
+ }),
2197
+ sign: (path, ttl, parameters) => absoluteTemporarySignedUrl(path, ttl, parameters, services.config.appUrl, services.config.signatureSecret),
2285
2198
  });
2286
- const link = absoluteTemporarySignedUrl(path, 3600, { ...extra, token: issued.plain }, services.config.appUrl, services.config.signatureSecret);
2287
- return { to, subject, body: \`\${subject}\\n\\n\${link}\\n\` };
2288
2199
  }
2289
2200
 
2290
2201
  async function issueSignedAuthMail(ports: BusinessRequestPorts, services: StarterAuthServices, to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
@@ -2294,20 +2205,18 @@ async function issueSignedAuthMail(ports: BusinessRequestPorts, services: Starte
2294
2205
 
2295
2206
  async function createRegistration(ports: BusinessRequestPorts, services: StarterAuthServices, credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
2296
2207
  const { email } = credentials;
2297
- try {
2298
- return await runAuthWrite(ports, email, (ports) => runAuthTransaction(ports, async (ports) => {
2208
+ return registerAccount(ports, email, {
2209
+ write: runAuthWrite, transaction: runAuthTransaction,
2210
+ create: async (ports) => {
2299
2211
  ${verify ? "const created = " : ""}await ports.database.model(User).create({
2300
2212
  ...credentials,
2301
2213
  is_admin: false,${tenantCreateField}
2302
2214
  });
2303
2215
  ${verify ? `return prepareSignedAuthMail(ports, services, email, "Verify your email", verificationPath, AUTH_ONE_TIME_PURPOSES.emailVerify, Number(created.get("id")), { id: String(created.get("id")) });` : ""}
2304
- }));
2305
- } catch (error) {
2306
- // The failed transaction/savepoint is already rolled back before readback.
2307
- // Only an actual account race is neutral; unrelated persistence failures propagate.
2308
- if (!isUniqueConstraintError(error) || !(await createStarterAuthDirectory(ports).findByEmail(email))) throw error;
2309
- return undefined;
2310
- }
2216
+ },
2217
+ isUniqueViolation: isUniqueConstraintError,
2218
+ accountExists: async (ports, email) => Boolean(await createStarterAuthDirectory(ports).findByEmail(email)),
2219
+ });
2311
2220
  }
2312
2221
 
2313
2222
  async function consumeSignedAuthToken(ports: BusinessRequestPorts, request: Request, purpose: string): Promise<number | null> {
@@ -2326,31 +2235,27 @@ async function revokeUserSessions(ports: BusinessRequestPorts, userId: number) {
2326
2235
 
2327
2236
  ${verify ? `
2328
2237
  async function completeSignedEmailVerification(ports: BusinessRequestPorts, request: Request): Promise<boolean> {
2329
- return await runAuthTransaction(ports, async (ports) => {
2330
- const userId = await consumeSignedAuthToken(ports, request, AUTH_ONE_TIME_PURPOSES.emailVerify);
2331
- if (!userId) return false;
2332
- await runAuthWrite(ports, userId, async (ports) => {
2238
+ return completeAccountToken(ports, request, AUTH_ONE_TIME_PURPOSES.emailVerify, {
2239
+ transaction: runAuthTransaction, consume: consumeSignedAuthToken,
2240
+ update: (ports, userId) => runAuthWrite(ports, userId, async (ports) => {
2333
2241
  const user = await ports.database.model(User).find(userId);
2334
2242
  if (!user) throw new Error("Verification account no longer exists.");
2335
2243
  await user.update({ email_verified_at: authTimestamp(ports) });
2336
- });
2337
- return true;
2244
+ }),
2338
2245
  });
2339
2246
  }
2340
2247
  ` : ""}
2341
2248
 
2342
2249
  async function completeSignedPasswordReset(ports: BusinessRequestPorts, request: Request, password: unknown): Promise<boolean> {
2343
2250
  if (typeof password !== "string" || password.length < 8) return false;
2344
- return await runAuthTransaction(ports, async (ports) => {
2345
- const userId = await consumeSignedAuthToken(ports, request, AUTH_ONE_TIME_PURPOSES.passwordReset);
2346
- if (!userId) return false;
2347
- await runAuthWrite(ports, userId, async (ports) => {
2251
+ return completeAccountToken(ports, request, AUTH_ONE_TIME_PURPOSES.passwordReset, {
2252
+ transaction: runAuthTransaction, consume: consumeSignedAuthToken,
2253
+ update: (ports, userId) => runAuthWrite(ports, userId, async (ports) => {
2348
2254
  const user = await ports.database.model(User).where({ id: userId })${plan.decisions.rowLocks ? ".lockForUpdate()" : ""}.first();
2349
2255
  if (!user) throw new Error("Reset account no longer exists.");
2350
2256
  await user.update({ password: await hashPassword(password) });
2351
2257
  await revokeStoredUserSessions(ports.database, userId, { incrementAuthVersion: true });
2352
- });
2353
- return true;
2258
+ }),
2354
2259
  });
2355
2260
  }
2356
2261
 
@@ -2985,59 +2890,31 @@ function renderAuthProvider(plan) {
2985
2890
  const users = plan.decisions.users;
2986
2891
  const cookie = plan.decisions.cookie;
2987
2892
  const mechanisms = plan.decisions.authMechanisms;
2988
- return `import { CORE_AUTH_TOKEN } from "@getstrata/bootstrap/config";
2989
- import type { ServiceProvider } from "@getstrata/bootstrap/contracts";
2893
+ return `import { createAuthRuntimeConfig } from "@getstrata/bootstrap/auth/runtimeConfig";
2990
2894
  import type { MetadataFactory } from "@getstrata/bootstrap/persistenceContracts";
2991
2895
  ${users ? 'import { createMetadataAuthManager, type MetadataAuthOptions } from "@getstrata/bootstrap/providers/auth";' : 'import type { MetadataAuthOptions } from "@getstrata/bootstrap/providers/auth";'}
2992
2896
  ${cookie ? `import { createCookieSessionAuthManager, type CookieSessionAuthManager } from "@getstrata/bootstrap/web/session";
2993
- ` : ""}import { establishedAuthReader } from "@getstrata/core/auth/authReader";
2994
- ${users ? `import { persistConsumedRecoveryHash } from "@getstrata/core/auth/passwordLogin";
2897
+ ` : ""}${users ? `import { persistConsumedRecoveryHash } from "@getstrata/core/auth/passwordLogin";
2995
2898
  ` : `import { AuthManager, GuestGuard } from "@getstrata/core/auth/guard";
2996
- `}import { createTokenAbilityChecker } from "@getstrata/core/auth/tokenAbilityChecker";
2997
- import { csrfTokenOptionsFromEnvironment } from "@getstrata/core/http/csrfToken";
2899
+ `}import { csrfTokenOptionsFromEnvironment } from "@getstrata/core/http/csrfToken";
2998
2900
  import { intendedUrlCookieOptionsFromEnvironment } from "@getstrata/core/auth/intendedUrlCookie";
2999
2901
  import { flashSessionOptionsFromEnvironment } from "@getstrata/core/http/flashSession";
3000
- import { resolveScimTenantFromToken } from "@getstrata/core/security/scimTenantTokens";
3001
2902
  ${users ? `import { createFieldEncryptionCodec } from "@getstrata/core/crypto/fieldEncryption";
3002
2903
  import { createMfaSecretCodec } from "@getstrata/core/crypto/mfaSecret";
3003
2904
  ` : ""}
3004
- import type { OAuthStateOptions } from "@getstrata/core/security/oauthState";
3005
- ${cookie ? `import { createSamlServiceProvider, createSqlSamlAssertionReplayStore, readSamlEnvOptions, type SamlServiceProvider, type SamlServiceProviderConfig } from "@getstrata/core/auth/saml/samlServiceProvider";
2905
+ ${cookie ? `import { createSamlServiceProvider, createSqlSamlAssertionReplayStore, type SamlServiceProvider } from "@getstrata/core/auth/saml/samlServiceProvider";
3006
2906
  ` : ""}${users ? `import { Mailer, createMailDriver } from "@getstrata/core/mail/mailer";
3007
- import { requireConfiguredSecret } from "@getstrata/core/runtime/appKeyPrefix";
3008
2907
  ` : ""}
3009
- import { ${cookie ? "passwordConfirmCookieName, passwordConfirmTtlSeconds, " : ""}type PasswordConfirmWriteOptions } from "@getstrata/core/auth/passwordConfirmCookie";
3010
- ${plan.decisions.pendingMfa ? `import { createPendingMfaHelpers } from "../pendingMfa.ts";
3011
- ` : ""}import { CORE_ABILITY_CHECKER_TOKEN } from "@getstrata/core/contracts/serviceTokens";
3012
- import { createServiceToken } from "@getstrata/core/contracts/token";
2908
+ import { type PasswordConfirmWriteOptions } from "@getstrata/core/auth/passwordConfirmCookie";
2909
+ ${plan.decisions.pendingMfa ? `import { createPendingMfaHelpers } from "./pendingMfa.ts";
2910
+ ` : ""}import { createServiceToken } from "@getstrata/core/contracts/token";
3013
2911
  import type { ExecutionPersistence } from "@getstrata/core/contracts/persistence";
3014
2912
  ${plan.decisions.tenantTable ? `import { resolveTenant } from "@getstrata/core/tenant/resolveTenant";
3015
- ` : ""}${users ? `import { createStarterAuthDirectory, withAuthIdentifier, type StarterAuthPersistence } from "../authDirectory.ts";
3016
- ` : ""}${plan.decisions.tenantUsers ? `import { User } from "../../models/User.ts";
2913
+ ` : ""}${users ? `import { createStarterAuthDirectory, withAuthIdentifier, type StarterAuthPersistence } from "./authDirectory.ts";
2914
+ ` : ""}${plan.decisions.tenantUsers ? `import { User } from "../models/User.ts";
3017
2915
  ` : ""}
3018
2916
  export type StarterAuthServicesOptions = Omit<MetadataAuthOptions, "mechanisms" | "sessionGuard" | "mfaSecrets"> & { readonly environment:Readonly<Record<string,string|undefined>>; readonly sessionSecret?: string; readonly signatureSecret?:string; readonly oauthStateSecret?:string; readonly passwordConfirmation?:PasswordConfirmWriteOptions };
3019
- export interface StarterAuthRuntime {
3020
- readonly registrationEnabled: boolean;
3021
- readonly scimEnabled: boolean;
3022
- readonly redisUrl: string | undefined;
3023
- readonly samlEnabled: boolean;
3024
- readonly oauthEnabled: boolean;
3025
- readonly appName: string;
3026
- readonly appUrl: string;${cookie ? `
3027
- readonly saml: Readonly<SamlServiceProviderConfig> | undefined;` : ""}
3028
- readonly github: Readonly<{clientId:string;clientSecret:string;redirectUri:string;production:boolean;userAgent:string}>;
3029
- readonly oidc: Readonly<{issuer:string;clientId:string;clientSecret:string;redirectUri:string;networkPolicy:Readonly<{production:boolean;allowPrivate:boolean}>}>;
3030
- readonly throttleNamespace:string;
3031
- readonly trustForwardedFor:boolean;
3032
- readonly scimTenantForToken:(token:string)=>number|null;
3033
- readonly tokenExpiryDays: number | null;
3034
- readonly jwtTtlSeconds: number;
3035
- readonly jwtSecret: string;
3036
- readonly signatureSecret: string;
3037
- readonly sessionCookie:Readonly<{cookieName:string;production:boolean}>;
3038
- readonly oauth: OAuthStateOptions;
3039
- readonly passwordConfirmation: PasswordConfirmWriteOptions;
3040
- }
2917
+ export type StarterAuthRuntime = ReturnType<typeof createAuthRuntimeConfig>;
3041
2918
  export interface StarterAuthServices {
3042
2919
  readonly config: StarterAuthRuntime;${users ? `
3043
2920
  readonly mail: Mailer;` : ""}${cookie ? `
@@ -3056,29 +2933,7 @@ export const STARTER_AUTH_SERVICES = createServiceToken<StarterAuthServices>("st
3056
2933
  export function createStarterAuthServices(options: StarterAuthServicesOptions): StarterAuthServices {
3057
2934
  const env = Object.freeze({...options.environment});
3058
2935
  const snapshot = Object.freeze({ ...options, abilities: Object.freeze({ admin: Object.freeze([...options.abilities.admin]), member: Object.freeze([...options.abilities.member]) }) });
3059
- ${users ? "const secretsEnv = Object.freeze({...env,...(snapshot.sessionSecret ? {SESSION_SECRET:snapshot.sessionSecret} : {})});" : ""}
3060
- ${plan.decisions.jwt ? 'if (!snapshot.jwtSecret.trim()) throw new TypeError("An explicit JWT secret is required.");' : ""}
3061
- const configuredAppUrl = env.APP_URL ?? "http://localhost:3000";
3062
- const appUrl = configuredAppUrl.endsWith("/") ? configuredAppUrl.slice(0, -1) : configuredAppUrl;
3063
- const config: StarterAuthRuntime = Object.freeze({
3064
- sessionCookie:Object.freeze({cookieName:env.SESSION_COOKIE_NAME?.trim() || (env.APP_KEY_PREFIX?.trim() || "strata") + "_session",production:snapshot.production}),
3065
- registrationEnabled: (env.FEATURE_REGISTRATION ?? "true") !== "false",
3066
- scimEnabled: (env.FEATURE_SCIM ?? "false") === "true", redisUrl:env.REDIS_URL,
3067
- samlEnabled: env.FEATURE_SAML === "true",
3068
- oauthEnabled: env.FEATURE_OAUTH === "true",
3069
- appName: env.APP_NAME ?? "Strata", appUrl,${cookie ? `
3070
- saml: env.FEATURE_SAML === "true" ? Object.freeze(readSamlEnvOptions(env)) : undefined,` : ""}
3071
- github: Object.freeze({clientId:env.GITHUB_CLIENT_ID?.trim() ?? "",clientSecret:env.GITHUB_CLIENT_SECRET?.trim() ?? "",redirectUri:env.GITHUB_REDIRECT_URI?.trim() || appUrl + "/auth/github/callback",production:snapshot.production,userAgent:env.APP_USER_AGENT?.trim()||env.APP_KEY_PREFIX?.trim()||"strata"}),
3072
- oidc: Object.freeze({issuer:env.OIDC_ISSUER?.trim() ?? "",clientId:env.OIDC_CLIENT_ID?.trim() ?? "",clientSecret:env.OIDC_CLIENT_SECRET?.trim() ?? "",redirectUri:env.OIDC_REDIRECT_URI?.trim() || appUrl + "/auth/oidc/callback",networkPolicy:Object.freeze({production:snapshot.production,allowPrivate:env.OIDC_ALLOW_PRIVATE === "true"})}),
3073
- throttleNamespace:env.APP_KEY_PREFIX?.trim()||"strata",
3074
- trustForwardedFor:env.TRUST_FORWARDED_FOR === "true",
3075
- scimTenantForToken:(token:string)=>resolveScimTenantFromToken(token,env),
3076
- tokenExpiryDays: ${plan.decisions.token ? '(() => { const days=Number.parseInt(env.API_TOKEN_DEFAULT_EXPIRY_DAYS?.trim() ?? "",10); return Number.isInteger(days) && days > 0 ? days : null; })()' : "null"},
3077
- jwtTtlSeconds: ${plan.decisions.jwt ? '(() => { const ttl=Number.parseInt(env.JWT_TTL_SECONDS ?? "",10); return Number.isInteger(ttl) && ttl > 0 ? ttl : 3600; })()' : "3600"}, jwtSecret:snapshot.jwtSecret,
3078
- signatureSecret: ${plan.decisions.signedUrls ? 'options.signatureSecret ?? requireConfiguredSecret(["SIGNED_URL_SECRET","SESSION_SECRET","OAUTH_STATE_SECRET"],"signed-url-secret",secretsEnv)' : "options.signatureSecret ?? snapshot.jwtSecret"},
3079
- oauth: Object.freeze({secret:${cookie ? 'options.oauthStateSecret ?? requireConfiguredSecret(["OAUTH_STATE_SECRET","SESSION_SECRET"],"oauth-state-secret",secretsEnv)' : "options.oauthStateSecret ?? snapshot.jwtSecret"},production:snapshot.production}),
3080
- passwordConfirmation: Object.freeze(options.passwordConfirmation ? {...options.passwordConfirmation} : {secret:${cookie ? 'requireConfiguredSecret(["SESSION_SECRET","OAUTH_STATE_SECRET"],"session-secret",secretsEnv)' : "snapshot.jwtSecret"},cookieName:${cookie ? "passwordConfirmCookieName(env)" : JSON.stringify("strata_password_confirmed")},ttlSeconds:${cookie ? "passwordConfirmTtlSeconds(env)" : "10800"},production:snapshot.production}),
3081
- });
2936
+ const config: StarterAuthRuntime = createAuthRuntimeConfig(options, ${JSON.stringify({ users, cookie, token: plan.decisions.token, jwt: plan.decisions.jwt, signedUrls: plan.decisions.signedUrls })});
3082
2937
  ${cookie ? `if (!snapshot.sessionSecret?.trim()) throw new TypeError("SESSION_SECRET is required for cookie authentication.");
3083
2938
  const session = (ports: StarterAuthPersistence) => createCookieSessionAuthManager({ selected: ports.database, policy: ports.policy, secret: snapshot.sessionSecret!, production: snapshot.production, rls: ${String(plan.decisions.rls)}, cookieName: config.sessionCookie.cookieName, mapUser: user => ({ id: user.id, name: user.name, email: user.email, authVersion: user.auth_version, isActive: user.is_active, role: user.is_admin ? "admin" : "member", ...(user.email_verified_at !== undefined ? {emailVerifiedAt:user.email_verified_at} : {}) }) });` : ""}
3084
2939
  ${users ? "const fieldEncryption=createFieldEncryptionCodec(env), mfaSecrets=createMfaSecretCodec(env);" : ""}
@@ -3103,396 +2958,74 @@ export function createStarterAuthServices(options: StarterAuthServicesOptions):
3103
2958
  };
3104
2959
  return Object.freeze({ config, metadata, csrf:csrfTokenOptionsFromEnvironment(env), intendedUrl:intendedUrlCookieOptionsFromEnvironment(env),flash:flashSessionOptionsFromEnvironment(env)${users ? ",fieldEncryption,mfaSecrets" : ""}${users ? ", mail: new Mailer(createMailDriver(env))" : ""}${cookie ? ', saml: (ports:StarterAuthPersistence) => { if(!config.saml) throw new Error("SAML is not configured.");return createSamlServiceProvider({...config.saml,replayStore:createSqlSamlAssertionReplayStore(ports.database)}); }' : ""}${plan.decisions.pendingMfa ? ", pendingMfa: createPendingMfaHelpers({secret:snapshot.sessionSecret!,production:snapshot.production})" : ""}${users ? ", directory: createStarterAuthDirectory" : ""}${cookie ? ", session" : ""} });
3105
2960
  }
3106
- export function createStarterAuthProvider(services: StarterAuthServices): ServiceProvider {
3107
- return {
3108
- name: "starter.auth",
3109
- register({ container }) {
3110
- container.set(STARTER_AUTH_SERVICES, services);
3111
- container.set(CORE_AUTH_TOKEN, establishedAuthReader);
3112
- container.set(CORE_ABILITY_CHECKER_TOKEN, createTokenAbilityChecker());
3113
- },
3114
- };
3115
- }
3116
2961
  `;
3117
2962
  }
3118
2963
 
3119
2964
  // src/renderBootstrap.ts
3120
- function renderPreloadTs(plan, projectName) {
3121
- const layers = plan.layers;
3122
- const fallback = defaultDatabaseUrl(layers, projectName);
3123
- const migrationFallback = defaultMigrationDatabaseUrl(layers, projectName);
3124
- const migrationLine = migrationFallback ? `process.env.MIGRATION_DATABASE_URL ??= ${JSON.stringify(migrationFallback)};
3125
- ` : "";
3126
- const databaseDefaults = plan.decisions.ensureDatabase ? `if (!isProductionEnv()) {
3127
- process.env.DATABASE_URL ??= ${JSON.stringify(fallback)};
3128
- ${migrationLine.trim()}
3129
- }
3130
- ` : `process.env.DATABASE_URL ??= ${JSON.stringify(fallback)};
3131
- `;
3132
- return `${plan.decisions.ensureDatabase ? `import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3133
- ` : ""}
3134
-
3135
- ${databaseDefaults}process.env.FRONTEND_MODE ??= ${JSON.stringify(layers.frontend)};
3136
- process.env.SPA_PREFIX ??= ${JSON.stringify(layers.spaPrefix)};
3137
- process.env.CACHE_DRIVER ??= ${JSON.stringify(layers.cache)};
3138
- process.env.QUEUE_DRIVER ??= ${JSON.stringify(layers.queue)};
3139
- ${plan.decisions.redisQueue ? `process.env.QUEUE_REDIS_TRANSPORT ??= "streams";
3140
- ` : ""}process.env.MAIL_DRIVER ??= ${JSON.stringify(layers.mail)};
3141
- process.env.TENANCY_DRIVER ??= ${JSON.stringify(layers.tenancy)};
3142
- `;
3143
- }
3144
- function renderConfigTs() {
3145
- return `export interface AppConfig {
3146
- port: number;
3147
- /** Optional listen address; independent of the trusted public APP_URL. */
3148
- hostname?: string;
3149
- appUrl: string;
3150
- databaseUrl: string;
3151
- }
3152
-
3153
- export function loadConfig(env:Readonly<Record<string,string|undefined>>=process.env): AppConfig {
3154
- const databaseUrl = env.DATABASE_URL;
3155
- if (!databaseUrl) {
3156
- throw new Error("DATABASE_URL is required");
3157
- }
3158
-
3159
- return {
3160
- port: Number(env.PORT ?? 3000),
3161
- hostname: env.HOST?.trim() || undefined,
3162
- appUrl: env.APP_URL ?? "http://localhost:3000",
3163
- databaseUrl,
2965
+ function renderConfigTs(plan, projectName) {
2966
+ const { layers, decisions } = plan;
2967
+ const defaults = {
2968
+ DATABASE_URL: defaultDatabaseUrl(layers, projectName),
2969
+ ...defaultMigrationDatabaseUrl(layers, projectName) ? { MIGRATION_DATABASE_URL: defaultMigrationDatabaseUrl(layers, projectName) } : {},
2970
+ FRONTEND_MODE: layers.frontend,
2971
+ SPA_PREFIX: layers.spaPrefix,
2972
+ CACHE_DRIVER: layers.cache,
2973
+ QUEUE_DRIVER: layers.queue,
2974
+ ...decisions.redisQueue ? { QUEUE_REDIS_TRANSPORT: "streams" } : {},
2975
+ MAIL_DRIVER: layers.mail,
2976
+ TENANCY_DRIVER: layers.tenancy
3164
2977
  };
3165
- }
3166
-
3167
- /** Cookie sessions and signed cookies are keyed by this; there is no default. */
3168
- export function sessionSecret(): string {
3169
- const secret = process.env.SESSION_SECRET?.trim();
3170
- if (!secret) {
3171
- throw new Error(
3172
- "SESSION_SECRET is required. Copy .env.example to .env and set it (32+ characters).",
3173
- );
3174
- }
3175
- return secret;
3176
- }
3177
- `;
3178
- }
3179
- function renderConfigProvider(plan) {
3180
- const layers = plan.layers;
3181
- return `import {
3182
- APP_PORT_CONFIG_KEY,
3183
- CORE_CONFIG_TOKEN,
3184
- CORE_PUBLIC_TENANCY_TOKEN,
3185
- CSRF_TARGET_ORIGIN_CONFIG_KEY,
3186
- DATABASE_URL_CONFIG_KEY,
3187
- REDIS_URL_CONFIG_KEY,
3188
- } from "@getstrata/bootstrap/config";
3189
- import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3190
- import { normalizeTenantHostname } from "@getstrata/core/tenant/tenantMiddleware";
3191
- import type { ServiceProvider } from "@getstrata/core/contracts/di";
3192
- import { loadConfig } from "../config.ts";
3193
-
3194
- export function createConfigProvider(appConfig:ReturnType<typeof loadConfig>,env:Readonly<Record<string,string|undefined>>):ServiceProvider {
3195
- env=Object.freeze({...env});
3196
- return {
3197
- name: "starter.config",
3198
- register({ container, config }) {
3199
-
3200
- container.set(CORE_CONFIG_TOKEN, config);
3201
- if (env.CSRF_TARGET_ORIGIN !== undefined)
3202
- config.set(CSRF_TARGET_ORIGIN_CONFIG_KEY, env.CSRF_TARGET_ORIGIN);
3203
- // One approved origin for the starter tenant. Multi-tenant apps replace this lookup.
3204
- if (isProductionEnv(env)) {
3205
- const publicHost = normalizeTenantHostname(new URL(appConfig.appUrl).host);
3206
- container.set(CORE_PUBLIC_TENANCY_TOKEN, {
3207
- resolveTenantId: async (hostname) => hostname === publicHost ? 1 : null,
3208
- });
3209
- }
3210
- config.set(DATABASE_URL_CONFIG_KEY, appConfig.databaseUrl);
3211
- config.set(APP_PORT_CONFIG_KEY, appConfig.port);
3212
- config.set(REDIS_URL_CONFIG_KEY, env.REDIS_URL ?? "");
3213
- config.set("app.url", appConfig.appUrl);
3214
- config.set("app.debug", env.APP_DEBUG === "true");
3215
- config.set("cache.driver", env.CACHE_DRIVER ?? "${layers.cache}");
3216
- config.set("cache.ttlMs", 3_600_000);
3217
- config.set("cache.maxEntries", 100);
3218
- config.set("queue.driver", env.QUEUE_DRIVER ?? "${layers.queue}");
3219
- },
3220
- };
3221
-
3222
- }
3223
- `;
3224
- }
3225
- function renderQueueProvider() {
3226
- return `import type { ServiceProvider } from "@getstrata/core/contracts/di";
3227
- import type { Queue } from "@getstrata/core/queue";
3228
- import { FAILED_JOB_SERVICE_TOKEN, type QueueServices } from "@getstrata/core/queue/createAppQueue";
3229
- import { CORE_QUEUE_TOKEN } from "@getstrata/core/contracts/serviceTokens";
3230
- /** Bridge graph-owned resources into transport module declarations; it never owns their shutdown. */
3231
- export function createQueueProvider(queue:Queue,services:QueueServices):ServiceProvider {
3232
- return {name:"starter.queue",register({container}){container.set(CORE_QUEUE_TOKEN,queue);container.set(FAILED_JOB_SERVICE_TOKEN,services);}};
3233
- }
3234
- `;
3235
- }
3236
- function renderPolicyProvider() {
3237
- return `import { CORE_POLICY_GATE_TOKEN } from "@getstrata/bootstrap/config";
3238
- import { PolicyGate } from "@getstrata/core/auth/policy";
3239
- import type { ServiceProvider } from "@getstrata/core/contracts/di";
3240
-
3241
- const policyProvider: ServiceProvider = {
3242
- name: "core.policy",
3243
- register({ container }) {
3244
- container.set(CORE_POLICY_GATE_TOKEN, new PolicyGate());
3245
- },
3246
- };
3247
-
3248
- export default policyProvider;
3249
- `;
3250
- }
3251
- function renderProvidersIndex() {
3252
- return `import { createTracingProvider } from "@getstrata/bootstrap";
3253
- import { createEventBindings, createEventsProvider } from "@getstrata/bootstrap/providers/events";
3254
- import type { ServiceProvider } from "@getstrata/core/contracts/di";
3255
- import { createServiceToken } from "@getstrata/core/contracts/token";
3256
- import { resourceService, valueService, service, type ServiceDeclaration } from "@getstrata/core/contracts/services";
3257
- import { createAuditExporter } from "@getstrata/core/audit/exportAuditLogs";
3258
- import { createCacheStore, snapshotCacheStoreOptions } from "@getstrata/core/cache/createCacheStore";
3259
- import { CacheRepository } from "@getstrata/core/cache/repository";
3260
- import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3261
- import { createAppQueue, createSystemQueueServices, type QueueServices, FAILED_JOB_SERVICE_TOKEN } from "@getstrata/core/queue/createAppQueue";
3262
- import type { Queue } from "@getstrata/core/queue";
3263
- import { JobRegistry, QUEUE_JOB_REGISTRY_TOKEN } from "@getstrata/core/queue/jobRegistry";
3264
- import { CORE_CACHE_TOKEN, CORE_QUEUE_TOKEN } from "@getstrata/bootstrap/config";
3265
- import { createStarterAuthProvider, type StarterAuthServices } from "./auth.ts";
3266
- import { loadConfig } from "../config.ts";
3267
- import { createConfigProvider } from "./config.ts";
3268
- import { createStorageProvider } from "./storage.ts";
3269
- import { createStorageDriver, resolveStorageConfig, StorageManager } from "@getstrata/core/storage/storage";
3270
- import { createStarterViewProvider } from "./view.ts";
3271
- import policyProvider from "./policy.ts";
3272
- import { registerDefaultJobs } from "@getstrata/bootstrap/queue/defaultJobs";
3273
- import { discoverJobs } from "@getstrata/bootstrap/discoverJobs";
3274
-
3275
- export const STARTER_STORAGE_TOKEN = createServiceToken<StorageManager>("starter.storage");
3276
- export const STARTER_CACHE_TOKEN = createServiceToken<CacheRepository>("starter.cache");
3277
- export const STARTER_QUEUE_TOKEN = createServiceToken<Queue>("starter.queue");
3278
- export const STARTER_QUEUE_SERVICES_TOKEN = createServiceToken<QueueServices>("starter.queueServices");
3279
- export const STARTER_AUDIT_EXPORT_TOKEN=createServiceToken<()=>Promise<number>>("starter.auditExporter");
3280
- export const STARTER_BILLING_OPTIONS_TOKEN=createServiceToken<Readonly<{enabled:boolean;stripeSecret:string}>>("starter.billing.options");
3281
- export const STARTER_WEBHOOK_OPTIONS_TOKEN = createServiceToken<Readonly<{allowPrivate:boolean;signatureHeader:string}>>("starter.webhook.options");
3282
- export function createStarterServices(env:Readonly<Record<string,string|undefined>>, invoke:import("@getstrata/core/contracts/persistence").PersistenceInvocation):readonly ServiceDeclaration[] {
3283
- const storageConfig = resolveStorageConfig(env);
3284
- const cacheOptions = snapshotCacheStoreOptions({driver:(env.CACHE_DRIVER??"array") as "array"|"redis",ttlMs:3600000,maxEntries:100,redisUrl:env.REDIS_URL,namespace:(env.APP_KEY_PREFIX?.trim()||"strata")+":cache:v3:"});
3285
- const driver=(env.QUEUE_DRIVER??"sync") as "sync"|"async"|"redis";
3286
- if(!["sync","async","redis"].includes(driver))throw new TypeError("Unsupported queue driver.");
3287
- return Object.freeze([
3288
- ...createEventBindings(),
3289
- valueService(QUEUE_JOB_REGISTRY_TOKEN,new JobRegistry()),
3290
- service(STARTER_STORAGE_TOKEN,{lifetime:"application",dependencies:[] as const,create:()=>new StorageManager(createStorageDriver(storageConfig))}),
3291
- valueService(STARTER_BILLING_OPTIONS_TOKEN,Object.freeze({enabled:env.FEATURE_BILLING==="true",stripeSecret:env.STRIPE_WEBHOOK_SECRET?.trim()??""})),
3292
- service(STARTER_AUDIT_EXPORT_TOKEN,{lifetime:"application",dependencies:[] as const,create:()=>createAuditExporter({environment:env,runSql:work=>invoke({kind:"command",actor:{kind:"system",policy:"audit.export"}},({database,policy})=>env.TENANCY_DRIVER==="rls"?policy.run(database,{kind:"bypass"},work):database.transaction(work))})}),
3293
- service(STARTER_QUEUE_SERVICES_TOKEN,{lifetime:"application",dependencies:[STARTER_CACHE_TOKEN,STARTER_AUDIT_EXPORT_TOKEN] as const,create:(cache,auditExport)=>createSystemQueueServices(invoke,{cache,auditExport})}),
3294
- valueService(STARTER_WEBHOOK_OPTIONS_TOKEN,Object.freeze({allowPrivate:!isProductionEnv(env)&&env.WEBHOOK_ALLOW_PRIVATE==="true",signatureHeader:env.WEBHOOK_SIGNATURE_HEADER?.trim()||"x-"+(env.APP_KEY_PREFIX?.trim()||"strata")+"-signature"})),
3295
- resourceService(STARTER_CACHE_TOKEN,{lifetime:"application",dependencies:[] as const,create:()=>({name:"starter.cache",open:()=>({ok:true,value:new CacheRepository(createCacheStore(cacheOptions))}),close:cache=>cache.close()})}),
3296
- resourceService(STARTER_QUEUE_TOKEN,{lifetime:"application",dependencies:[STARTER_QUEUE_SERVICES_TOKEN,QUEUE_JOB_REGISTRY_TOKEN] as const,create:(services,registry)=>({name:"starter.queue",open:()=>({ok:true,value:createAppQueue(driver,env.REDIS_URL,services,registry)}),drain:queue=>driver==="async"?queue.close?.():undefined,close:queue=>driver!=="async"?queue.close?.():undefined})}),
3297
- ]);
3298
- }
3299
- export function createStarterProviders(env:Readonly<Record<string,string|undefined>>, auth:StarterAuthServices, cache:CacheRepository, queue:Queue, queueServices:QueueServices,events:import("@getstrata/core/events").EventBus,billing:Readonly<{enabled:boolean;stripeSecret:string}>,storage:StorageManager,registry:JobRegistry):readonly ServiceProvider[] {
3300
- const appConfig=loadConfig(env);
3301
- return Object.freeze([
3302
- createConfigProvider(appConfig,env),
3303
- {name:"starter.billing-config",register({container}){container.set(STARTER_BILLING_OPTIONS_TOKEN,billing);}},
3304
- createTracingProvider({ env }),
3305
- {name:"starter.cache",register({container,dependencies}){container.set(CORE_CACHE_TOKEN,cache);dependencies.cache=cache;}},
3306
- createStorageProvider(storage),
3307
- {name:"starter.queue",async register({container}){container.set(CORE_QUEUE_TOKEN,queue);container.set(FAILED_JOB_SERVICE_TOKEN,queueServices);container.set(QUEUE_JOB_REGISTRY_TOKEN,registry);registerDefaultJobs(registry);await discoverJobs(registry);}},
3308
- createStarterAuthProvider(auth),createStarterViewProvider(env),policyProvider,createEventsProvider(events),
3309
- ]);
3310
- }
2978
+ return `/** Application choices; secrets and deployment values belong in the environment. */
2979
+ export default ${JSON.stringify({ frontend: layers.frontend, tenancy: layers.tenancy, views: decisions.serverViews || decisions.mfaViews, scim: layers.extras.scim, metrics: layers.extras.metrics, defaults }, null, 2)} as const;
3311
2980
  `;
3312
2981
  }
3313
2982
  function renderCreateAppTs(plan) {
3314
- const workTracker = plan.decisions.workTracker;
3315
- const layers = plan.layers;
3316
- const ensure = plan.decisions.ensureDatabase ? `import { ensureAppDatabase } from "./ensureDatabase.ts";
3317
- ` : "";
3318
- const metricsImports = layers.extras.metrics ? `import { createMetricsRoutes, createMetricsRuntime, type MetricsRuntime, type MetricsRuntimeOptions } from "@getstrata/bootstrap/metricsRoutes";
3319
- import { createOwnedReadOnlyObservation } from "@getstrata/core/database/ownedReadOnlyObservation";
3320
- ` : "";
3321
- return `import "./preload.ts";
3322
- ${workTracker ? `import { WORK_TRACKER_OUTBOX } from "../domain/workTracker.ts";
3323
- ` : ""}import { join } from "node:path";
3324
- import { createApplicationContext, type InitializedAppContext } from "@getstrata/bootstrap/context";
3325
- import { assertAppDependenciesComplete, type AppRouteMap, type ServiceProvider } from "@getstrata/bootstrap/contracts";
3326
- import type { Application } from "@getstrata/core/contracts/application";
3327
- import type { PersistenceInvocation } from "@getstrata/core/contracts/persistence";
3328
- import { createDatabaseBindings } from "@getstrata/core/database/bindings";
3329
- import { CORE_QUEUE_TOKEN } from "@getstrata/core/contracts/serviceTokens";
3330
- import { composeRouteMaps } from "@getstrata/bootstrap/routePlan";
3331
- import { createSqlOutboxBindings, createOutboxWorkerTransport, type SqlOutbox } from "@getstrata/core/events/outbox";
3332
- import { listeners as durableListeners } from "../outbox/registry.ts";
3333
- import { failedJobRepository } from "@getstrata/core/queue/failedJobRepository";
3334
- import type { QueueServices } from "@getstrata/core/queue/createAppQueue";
3335
- import { createQueueWorkerTransport } from "@getstrata/core/queue/queueWorkerTransport";
3336
- import { type JobRegistry, QUEUE_JOB_REGISTRY_TOKEN } from "@getstrata/core/queue/jobRegistry";
3337
- import { createHttpKernel } from "@getstrata/bootstrap/httpKernel";
3338
- import { resolveHttpResponsePolicy } from "@getstrata/bootstrap/providers";
3339
- import { createHealthRoutes } from "@getstrata/bootstrap/health";
3340
- import { mergeSpaRoutes } from "@getstrata/bootstrap/createSpaRoutes";
3341
- import { discoverListeners } from "@getstrata/bootstrap/discoverListeners";
3342
- import { createModelCacheInvalidationEffects } from "@getstrata/bootstrap/listeners/invalidateCacheOnModelWrite";
3343
- import { ensureModulesLoaded } from "@getstrata/bootstrap/discoverModules";
3344
- import { assertProductionSecrets } from "@getstrata/bootstrap/secretsGuard";
3345
- import { CORE_WEB_ERROR_VIEW_TOKEN } from "@getstrata/core/view/tokens";
3346
- import type { WebErrorView } from "@getstrata/core/view";
3347
- import { webServerResource, type NativeServerOptions } from "@getstrata/bootstrap/web/server";
3348
- import type { Server } from "bun";
3349
- import { ADMIN_ABILITIES, MEMBER_ABILITIES, resolveAbilitiesForRole } from "@getstrata/core/auth/abilityCatalog";
3350
- import { clearSessionCookie } from "@getstrata/core/auth/sessionCookie";
3351
- import { intendedUrlCookieOptionsFromEnvironment } from "@getstrata/core/auth/intendedUrlCookie";
3352
- import { flashSessionOptionsFromEnvironment } from "@getstrata/core/http/flashSession";
3353
- import { csrfTokenOptionsFromEnvironment } from "@getstrata/core/http/csrfToken";
3354
- import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3355
- import { createDatabaseReadinessBindings } from "@getstrata/bootstrap/databaseReadiness";
3356
- import { APPLICATION_EVENT_BUS_TOKEN } from "@getstrata/bootstrap/providers/events";
3357
- ${layers.extras.scim ? `import { createScimAuthenticator } from "@getstrata/core/auth/scimAuthMiddleware";
3358
- import { resolveScimTenantFromToken } from "@getstrata/core/security/scimTenantTokens";
3359
- import { resolveTenant } from "@getstrata/core/tenant/resolveTenant";
3360
- ` : ""}${metricsImports}import { createStarterAuthServices } from "./providers/auth.ts";
3361
- import { createStarterProviders, createStarterServices, STARTER_CACHE_TOKEN, STARTER_QUEUE_TOKEN, STARTER_QUEUE_SERVICES_TOKEN,STARTER_BILLING_OPTIONS_TOKEN,STARTER_AUDIT_EXPORT_TOKEN, STARTER_STORAGE_TOKEN } from "./providers/index.ts";
3362
- import { repositoryDefinitions, modelDefinitions } from "../models/register.ts";
2983
+ return `import { defineApp, type BootstrappedApp, type BootstrapOptions } from "@getstrata/bootstrap/application";
2984
+ import { resolve } from "node:path";
2985
+ import config from "../config/app.ts";
2986
+ import paths from "../../strata.config.ts";
2987
+ import { databaseOptions } from "./database.ts";
2988
+ import { createStarterAuthServices, STARTER_AUTH_SERVICES } from "./auth.ts";
2989
+ import { modelDefinitions, repositoryDefinitions } from "../models/register.ts";
3363
2990
  import { Note } from "../models/Note.ts";
3364
2991
  import { migrate } from "../db/migrate.ts";
3365
- import { buildRoutes } from "../routes.ts";
3366
- import { loadConfig } from "./config.ts";
3367
- import { databaseOptions } from "./database.ts";
3368
- ${ensure}
3369
- export interface BootstrapOptions {
3370
- migrate?:boolean;
3371
- transports?:readonly import("@getstrata/core/contracts/application").TransportDefinition[];
3372
- services?:readonly import("@getstrata/core/contracts/services").ServiceDeclaration[];
3373
- persistence?:Pick<import("@getstrata/core/database/bindings").DatabaseDefinition,"repositories"|"models"|"repositoryEffects">;
3374
- mode?:"http"|"command"|"worker"|"outbox-worker";
3375
- server?:{port?:number;native?:NativeServerOptions};
3376
- onConstructed?:(application:Application)=>undefined;${layers.extras.metrics ? `
3377
- runtimeMetrics?:Omit<MetricsRuntimeOptions,"failedJobs"|"outbox"> & {failedJobs?:Omit<NonNullable<MetricsRuntimeOptions["failedJobs"]>,"observeReadOnly">;outbox?:Omit<NonNullable<MetricsRuntimeOptions["outbox"]>,"observeReadOnly">};` : ""}
3378
- }
3379
- export interface BootstrappedApp {
3380
- application:Application;
3381
- auditExport:()=>Promise<number>;
3382
- invoke:PersistenceInvocation;
3383
- readonly outbox:Readonly<Pick<SqlOutbox,"publish">>;
3384
- context:InitializedAppContext;
3385
- routes:AppRouteMap;
3386
- config:ReturnType<typeof loadConfig>;
3387
- queue:import("@getstrata/core/queue").Queue;
3388
- queueServices:import("@getstrata/core/queue/createAppQueue").QueueServices;
3389
- registry:JobRegistry;
3390
- server?:Server<unknown>;
3391
- worker?:ReturnType<typeof createQueueWorkerTransport>;
3392
- outboxWorker?:ReturnType<typeof createOutboxWorkerTransport>;
3393
- }
3394
- export function bootstrapApp(options:BootstrapOptions & {mode:"outbox-worker"}):Promise<BootstrappedApp & {outboxWorker:ReturnType<typeof createOutboxWorkerTransport>}>;
3395
- export function bootstrapApp(options?:BootstrapOptions):Promise<BootstrappedApp>;
3396
- export async function bootstrapApp(options:BootstrapOptions={}):Promise<BootstrappedApp> {
3397
- const env=Object.freeze({...process.env});
3398
- const production=isProductionEnv(env);
3399
- const runMigrate=options.migrate??!production;
3400
- if(production)assertProductionSecrets(env);
3401
- ${plan.decisions.ensureDatabase ? "await ensureAppDatabase({provision:!production&&runMigrate});" : ""}
3402
- // Schema commands finish and close their own separate resources before runtime starts.
3403
- if(runMigrate)await migrate();
3404
- const config=loadConfig(env);
3405
- const dbOptions=databaseOptions(env);
3406
- const modules=await ensureModulesLoaded({modulesDir:join(import.meta.dir,"../modules")});
3407
- const listenerDeclarations=await discoverListeners({directory:join(import.meta.dir,"../listeners")});
3408
- const cacheEffects=createModelCacheInvalidationEffects(repositoryDefinitions,modules,{cache:STARTER_CACHE_TOKEN,queue:STARTER_QUEUE_TOKEN});
3409
- const catalog=[cacheEffects,...listenerDeclarations];
3410
- const secret=env.SESSION_SECRET?.trim()??"";
3411
- const abilities=Object.freeze({admin:ADMIN_ABILITIES,member:MEMBER_ABILITIES,resolveForRole:resolveAbilitiesForRole});
3412
- const auth=createStarterAuthServices({environment:env,production,allowDevHeaders:!production&&env.AUTH_DEV_HEADERS==="true",jwtSecret:env.JWT_SECRET?.trim()||secret,sessionSecret:secret,
3413
- signatureSecret:env.SIGNED_URL_SECRET?.trim()||secret||env.OAUTH_STATE_SECRET?.trim()||"",
3414
- readSession:()=>null,
3415
- abilities,roleAbilities:role=>[...(role==="admin"?abilities.admin:abilities.member)],
3416
- });
3417
- let invoke:PersistenceInvocation|undefined;
3418
- let auditExport:(()=>Promise<number>)|undefined;
3419
- const run:PersistenceInvocation=(envelope,work)=>{if(!invoke)throw new Error("Application owner has not been constructed.");return invoke(envelope,work);};
3420
- let readyQueueServices:QueueServices|undefined;
3421
- let readyRegistry:JobRegistry|undefined;
3422
- const selectedRegistry=()=>{if(!readyRegistry)throw new Error("Job registry is not assembled.");return readyRegistry;};
3423
- const selectedQueueServices=()=>{if(!readyQueueServices)throw new Error("Queue services are not assembled.");return readyQueueServices;};
3424
- const queueServices:QueueServices={
3425
- recordFailure:(...args)=>selectedQueueServices().recordFailure(...args),
3426
- listRecent:(...args)=>selectedQueueServices().listRecent(...args),
3427
- retry:(...args)=>selectedQueueServices().retry(...args),
3428
- delete:(...args)=>selectedQueueServices().delete(...args),
3429
- flush:()=>selectedQueueServices().flush(),
3430
- runAttempt:(...args)=>selectedQueueServices().runAttempt(...args),
3431
- };
3432
- const outbox=createSqlOutboxBindings({invoke:run,connection:"main",tenancy:${JSON.stringify(layers.tenancy)},listeners:durableListeners});
3433
- let publisher:BootstrappedApp["outbox"]|undefined;
3434
- const mode=options.mode??"command";
3435
- if(mode==="worker"&&!env.REDIS_URL)throw new Error("queue:work requires REDIS_URL.");
3436
- const worker=mode==="worker"?createQueueWorkerTransport({redisUrl:env.REDIS_URL!,queueServices,registry:selectedRegistry}):undefined;
3437
- const outboxWorker=mode==="outbox-worker"?createOutboxWorkerTransport(outbox.token):undefined;
3438
- let server:Server<unknown>|undefined;
3439
- let routes:AppRouteMap|undefined;
3440
- let errorView:WebErrorView|undefined;
3441
- let kernel:ReturnType<typeof createHttpKernel>|undefined;${layers.extras.metrics ? `
3442
- let metrics:MetricsRuntime|undefined;` : ""}
3443
- const assembly:ServiceProvider={name:"starter.routes",async boot({dependencies,onCleanup}){
3444
- assertAppDependenciesComplete(dependencies);
3445
- kernel=createHttpKernel(dependencies);
3446
- errorView=dependencies.container.has(CORE_WEB_ERROR_VIEW_TOKEN)?dependencies.container.resolve(CORE_WEB_ERROR_VIEW_TOKEN):undefined;
3447
- ${layers.extras.metrics ? 'const {failedJobs,outbox,...runtime}=options.runtimeMetrics??{};metrics=createMetricsRuntime({...runtime,...(failedJobs?{failedJobs:{...failedJobs,observeReadOnly:createOwnedReadOnlyObservation(handle.application,"main",dbOptions)}}:{}),...(outbox?{outbox:{...outbox,observeReadOnly:createOwnedReadOnlyObservation(handle.application,"main",dbOptions,{postgresPolicy:"bypass"})}}:{})});onCleanup(()=>metrics!.close(),"drain");' : "void onCleanup;"}
3448
- routes=mergeSpaRoutes(dependencies,composeRouteMaps(
3449
- Object.fromEntries(Object.entries(createHealthRoutes(dependencies,{pingOnHealth:true,healthFormat:"text",schemaCheck:()=>dependencies.invoke({kind:"request",actor:{kind:"system",policy:"http.schema-health"}},async({database})=>{try{await database.model(Note).query().limit(1).select("id").get();return true;}catch{return false;}})})).map(([path,handler])=>[path,kernel!.wrapPublicDocument(handler)])),
3450
- buildRoutes(dependencies, modules),${layers.extras.metrics ? `
3451
- Object.fromEntries(Object.entries(createMetricsRoutes({...metrics?.options,authorization:{token:env.METRICS_TOKEN,production}})).map(([path,handler])=>[path,kernel!.wrapPublicDocument(handler)])),` : ""}
3452
- ),{distDirectory:join(import.meta.dir,"../../frontend/dist"),wrap:handler=>kernel!.wrapPublicDocument(handler)});
3453
- }};
3454
- const handle=createApplicationContext([],{
3455
- connection:"main",
3456
- http:{metadata:auth.metadata,invalidSessionCookie:{name:auth.config.sessionCookie.cookieName,expiredHeader:clearSessionCookie(auth.config.sessionCookie)},responsePolicy:resolveHttpResponsePolicy(env),intendedUrl:intendedUrlCookieOptionsFromEnvironment(env),flash:flashSessionOptionsFromEnvironment(env),features:{emailVerificationRequired:env.FEATURE_EMAIL_VERIFICATION==="true",viewsEnabled:["server-htmx","hybrid"].includes(env.FRONTEND_MODE??${JSON.stringify(layers.frontend)}),publicReadsEnabled:env.FEATURE_PUBLIC_READS==="true",etagEnabled:env.FEATURE_ETAG!=="false"},csrf:{token:csrfTokenOptionsFromEnvironment(env),allowDevelopmentHeaders:!production&&env.AUTH_DEV_HEADERS==="true",samlAcsUrl:env.SAML_ACS_URL??""},tenancy:${JSON.stringify(layers.tenancy)},production,allowTenantDevHeaders:!production&&env.TENANT_DEV_HEADERS==="true",signatureSecret:auth.config.signatureSecret,passwordConfirmation:auth.config.passwordConfirmation,
3457
- ...(production?{publicTenancy:{resolveTenantId:async(host:string)=>host===new URL(config.appUrl).hostname?1:null}}:{}),${layers.extras.scim ? `
3458
- scim:createScimAuthenticator({resolveToken:token=>resolveScimTenantFromToken(token,env),resolveTenant}),` : ""}
3459
- },
3460
- onConstructed:owner=>{invoke=owner.invoke;options.onConstructed?.(owner.application);return undefined;},
3461
- providersFromScope:scope=>{readyRegistry=scope.resolve(QUEUE_JOB_REGISTRY_TOKEN);auditExport=scope.resolve(STARTER_AUDIT_EXPORT_TOKEN);readyQueueServices=scope.resolve(STARTER_QUEUE_SERVICES_TOKEN);const coordinator=scope.resolve(outbox.token);const publish=coordinator.publish;publisher=Object.freeze({publish:(...args:Parameters<SqlOutbox["publish"]>)=>publish.call(coordinator,...args)});return [...createStarterProviders(env,auth,scope.resolve(STARTER_CACHE_TOKEN),scope.resolve(STARTER_QUEUE_TOKEN),scope.resolve(STARTER_QUEUE_SERVICES_TOKEN),scope.resolve(APPLICATION_EVENT_BUS_TOKEN),scope.resolve(STARTER_BILLING_OPTIONS_TOKEN),scope.resolve(STARTER_STORAGE_TOKEN),selectedRegistry()),${workTracker ? '{name:"starter.workTracker",register({container}){container.set(WORK_TRACKER_OUTBOX,publisher!);}},' : ""}...modules.flatMap(module=>module.providers??[]),assembly];},
3462
- definition:{config:{application:{url:config.appUrl,production}},services:[
3463
- ...(options.services??[]),...outbox.services,...createStarterServices(env,run),...createDatabaseReadinessBindings("main",env),...catalog.flatMap(declaration=>declaration.services),
3464
- ...createDatabaseBindings({default:"main",connections:{main:dbOptions},preparation:[outbox.token],repositories:[...repositoryDefinitions,failedJobRepository,...(options.persistence?.repositories??[])],models:[...modelDefinitions,...(options.persistence?.models??[])],repositoryEffects:[...catalog.flatMap(declaration=>declaration.repositoryEffects),...(options.persistence?.repositoryEffects??[])]}),
3465
- ],providers:[],transports:[...(options.transports??[]),...(worker?[worker.transport]:[]),...(outboxWorker?[outboxWorker.transport]:[]),...(mode==="http"?[{name:"starter.http",async setup(scope:import("@getstrata/core/contracts/application").ProviderScope){
3466
- if(!routes||!kernel)throw new Error("Route assembly did not finish before transport setup.");
3467
- server=await scope.acquire(webServerResource({env,port:options.server?.port??config.port,native:{maxRequestBodySize:resolveHttpResponsePolicy(env).maxBodyBytes,...(config.hostname?{hostname:config.hostname}:{}),...options.server?.native},cors:resolveHttpResponsePolicy(env).cors,routes,errorView,publicDir:join(import.meta.dir,"../../public"),enter:(request,handler)=>kernel!.run(request,handler)}));
3468
- }}]:[]) ]},
3469
- });
3470
- const context=await handle.start();
3471
- try {
3472
- if(!routes)throw new Error("Routes were not assembled.");
3473
- if(!publisher)throw new Error("Outbox publisher was not assembled.");
3474
- return {application:handle.application,auditExport:auditExport!,invoke:handle.invoke,outbox:publisher,context,routes,config,queue:context.container.resolve(CORE_QUEUE_TOKEN),queueServices:selectedQueueServices(),registry:selectedRegistry(),...(server?{server}:{}),...(worker?{worker}:{}),...(outboxWorker?{outboxWorker}:{})};
3475
- }catch(error){await handle.application.stop({reason:"STARTUP_FAILED"});throw error;}
3476
- }
3477
- export function createApp(options:BootstrapOptions={}) {return bootstrapApp({migrate:false,...options});}
3478
- /** HTTP acquisition is declared before startup, never added to an already ready application. */
3479
- export function createAppServer(options:Omit<BootstrapOptions,"mode">={}) {return bootstrapApp({...options,mode:"http"});}
2992
+ import { listeners } from "../outbox/registry.ts";
2993
+ ${plan.decisions.ensureDatabase ? `import { ensureAppDatabase } from "./ensureDatabase.ts";
2994
+ ` : ""}${plan.decisions.workTracker ? `import { WORK_TRACKER_OUTBOX } from "../domain/workTracker.ts";
2995
+ ` : ""}
2996
+ const { bootstrapApp, createApp, createAppServer } = defineApp({
2997
+ ...config,
2998
+ root: resolve(import.meta.dir, "../.."),
2999
+ modulesDirectory: paths.modulesDirectory,
3000
+ database: databaseOptions,
3001
+ auth: { create: createStarterAuthServices, token: STARTER_AUTH_SERVICES },
3002
+ models: modelDefinitions,
3003
+ repositories: repositoryDefinitions,
3004
+ migrate,${plan.decisions.ensureDatabase ? `
3005
+ ensureDatabase: ensureAppDatabase,` : ""}
3006
+ outbox: { listeners${plan.decisions.workTracker ? ", token: WORK_TRACKER_OUTBOX" : ""} },
3007
+ health: async database => { await database.model(Note).query().limit(1).select("id").get(); return true; },
3008
+ });
3009
+ export { bootstrapApp, createApp, createAppServer };
3010
+ export type { BootstrappedApp, BootstrapOptions };
3480
3011
  `;
3481
3012
  }
3482
- function renderRoutesTs() {
3483
- return `import { buildModuleRoutes } from "@getstrata/bootstrap/buildModuleRoutes";
3484
- import { buildWebModuleRoutes } from "@getstrata/bootstrap/buildWebModuleRoutes";
3485
- import { composeRouteMaps } from "@getstrata/bootstrap/routePlan";
3486
- import { isViewsEnabled } from "@getstrata/core/runtime/frontendMode";
3487
- import type { AppDependencies, AppModule, AppRouteMap } from "@getstrata/bootstrap/contracts";
3488
-
3489
- export function buildRoutes(dependencies: AppDependencies, modules: readonly AppModule[]): AppRouteMap {
3490
- const api = buildModuleRoutes(dependencies, { modules });
3491
- return composeRouteMaps(
3492
- ...(isViewsEnabled() ? [buildWebModuleRoutes(dependencies, { modules })] : []),
3493
- api,
3494
- );
3013
+ function renderServerTs() {
3014
+ return `import { serveApplication } from "@getstrata/bootstrap/application";
3015
+ import { createAppServer } from "./createApp.ts";
3016
+ await serveApplication(createAppServer);
3017
+ `;
3495
3018
  }
3019
+ function renderStrataConfigTs() {
3020
+ return `export default {
3021
+ application: "./src/bootstrap/createApp.ts",
3022
+ server: "./src/bootstrap/server.ts",
3023
+ schedule: "./src/bootstrap/schedule.ts",
3024
+ modulesDirectory: "./src/modules",
3025
+ commands: "./src/cli/register.ts",
3026
+ migrate: "./src/db/migrate.ts",
3027
+ fresh: "./src/db/fresh.ts",
3028
+ };
3496
3029
  `;
3497
3030
  }
3498
3031
  function renderOutboxRegistryTs(plan) {
@@ -3514,35 +3047,6 @@ export function createSchedule(app:Pick<BootstrappedApp,"invoke"|"auditExport">,
3514
3047
  }
3515
3048
  `;
3516
3049
  }
3517
- function renderViewProvider(plan) {
3518
- const layers = plan.layers;
3519
- return `import { join } from "node:path";
3520
- import { createViewProvider } from "@getstrata/bootstrap/providers/view";
3521
- import { establishedAuthReader } from "@getstrata/core/auth/authReader";
3522
-
3523
- export function createStarterViewProvider(env:Readonly<Record<string,string|undefined>>) {
3524
- const appName = env.APP_NAME?.trim() || "Strata";
3525
- ${layers.extras.oidc ? 'const oidcLogin = env.FEATURE_OAUTH === "true" && Boolean(env.OIDC_CLIENT_ID?.trim() && env.OIDC_CLIENT_SECRET?.trim());' : "void env;"}
3526
- return createViewProvider({
3527
- env,
3528
- enabled: ${plan.decisions.mfaViews ? "true" : `["server-htmx","hybrid"].includes(env.FRONTEND_MODE??${JSON.stringify(layers.frontend)})`},
3529
- directory: join(import.meta.dir, "../../../views"),
3530
- data: {
3531
- userKey: "currentUser",
3532
- loadUser: async (_container, request) => {
3533
- const user = await establishedAuthReader.user(request);
3534
- return user ? { id: Number(user.id), name: user.name ?? "", email: user.email ?? "", role: user.role ?? "member" } : null;
3535
- },${layers.extras.oidc ? `
3536
- extra: () => ({
3537
- appName,
3538
- oidcLogin,
3539
- }),` : `
3540
- extra: { appName },`}
3541
- },
3542
- });
3543
- }
3544
- `;
3545
- }
3546
3050
 
3547
3051
  // src/renderCli.ts
3548
3052
  function renderCliRegisterTs(plan) {
@@ -3550,108 +3054,32 @@ function renderCliRegisterTs(plan) {
3550
3054
 
3551
3055
  const commands: StrataCommandMap = {${plan?.decisions.users ? `
3552
3056
  "auth:provision-admin": async () => (await import("./initialAdmin.ts")).initialAdminCommand,` : ""}
3553
- "make:module": async () => (await import("@getstrata/cli/scaffold")).makeModuleCommand,
3554
- "make:model": async () => (await import("@getstrata/cli/scaffold")).makeModelCommand,
3555
- "make:view": async () => (await import("@getstrata/cli/scaffold")).makeViewCommand,
3556
- "make:policy": async () => (await import("@getstrata/cli/scaffold")).makePolicyCommand,
3557
- "make:job": async () => (await import("@getstrata/cli/scaffold")).makeJobCommand,
3558
- "make:listener": async () => (await import("@getstrata/cli/scaffold")).makeListenerCommand,
3559
- "make:request": async () => (await import("@getstrata/cli/scaffold")).makeRequestCommand,
3560
- "make:factory": async () => (await import("@getstrata/cli/scaffold")).makeFactoryCommand,
3561
- "make:migration": async () => (await import("@getstrata/cli/scaffold")).makeMigrationCommand,
3562
- "queue:work": async () => (await import("./queueWork.ts")).queueWorkCommand,
3563
- "outbox:work": async () => (await import("./outboxWork.ts")).outboxWorkCommand,
3564
- "queue:failed": async () => (await import("./queueFailed.ts")).queueFailedCommand,
3565
- "queue:retry": async () => (await import("./queueFailed.ts")).queueRetryCommand,
3566
- "queue:flush-failed": async () => (await import("./queueFailed.ts")).queueFlushFailedCommand,
3567
- "openapi:generate": async () => (await import("./openapi.ts")).openapiGenerateCommand,
3568
- "openapi:validate": async () => (await import("./openapi.ts")).openapiValidateCommand,
3569
- "openapi:check": async () => (await import("./openapi.ts")).openapiCheckCommand,
3570
- "schedule:run": async () => (await import("./scheduleRun.ts")).scheduleRunCommand,
3057
+
3571
3058
  };
3572
3059
 
3573
3060
  export { commands };
3574
3061
  `;
3575
3062
  }
3576
- function renderCliQueueWorkTs() {
3577
- return `import { runQueueWorkerCommand } from "@getstrata/cli/queueWorker";
3578
- import { bootstrapApp } from "../bootstrap/createApp.ts";
3579
- async function queueWorkCommand():Promise<void> {
3580
- await runQueueWorkerCommand({boot:()=>bootstrapApp({migrate:false,mode:"worker"})});
3581
- }
3582
- export {queueWorkCommand};
3583
- `;
3584
- }
3585
- function renderCliOutboxWorkTs() {
3586
- return `async function outboxWorkCommand(): Promise<void> {
3587
- const { runOutboxWorkerCommand } = await import("@getstrata/cli/outboxWorker");
3588
- const { bootstrapApp } = await import("../bootstrap/createApp.ts");
3589
- await runOutboxWorkerCommand({
3590
- boot: () => bootstrapApp({ migrate: false, mode: "outbox-worker" }),
3591
- });
3592
- }
3593
-
3594
- export { outboxWorkCommand };
3595
- `;
3596
- }
3597
- function renderCliQueueFailedTs() {
3598
- return `import { createQueueFailedCommands } from "@getstrata/cli/queueFailed";
3599
- import { bootstrapApp } from "../bootstrap/createApp.ts";
3600
- const {queueFailedCommand,queueFlushFailedCommand,queueRetryCommand}=createQueueFailedCommands(
3601
- ()=>bootstrapApp({migrate:false,mode:"command"}),
3602
- );
3603
- export {queueFailedCommand,queueFlushFailedCommand,queueRetryCommand};
3604
- `;
3605
- }
3606
- function renderCliOpenApiTs() {
3607
- return `import { createApp } from "../bootstrap/createApp.ts";
3608
- import { createOpenApiGenerateCommand, createOpenApiValidateCommand, createOpenApiCheckCommand } from "@getstrata/cli/openapi";
3609
- type CommandFactory=typeof createOpenApiGenerateCommand;
3610
- async function execute(factory:CommandFactory):Promise<void> {
3611
- let app:Awaited<ReturnType<typeof createApp>>|undefined;
3612
- await factory(async()=>{app=await createApp({migrate:false,mode:"command"});return app;},async()=>{await app?.context.dispose();})();
3613
- }
3614
- async function openapiGenerateCommand(){await execute(createOpenApiGenerateCommand);}
3615
- async function openapiValidateCommand(){await execute(createOpenApiValidateCommand);}
3616
- async function openapiCheckCommand(){await execute(createOpenApiCheckCommand);}
3617
- export {openapiGenerateCommand,openapiValidateCommand,openapiCheckCommand};
3618
- `;
3619
- }
3620
- function renderCliScheduleRunTs() {
3621
- return `import { createScheduleRunCommand } from "@getstrata/cli/schedule";
3622
- import { createScheduleRunOptions } from "@getstrata/bootstrap/schedule";
3623
- import { bootstrapApp } from "../bootstrap/createApp.ts";
3624
- async function scheduleRunCommand():Promise<void> {
3625
- const environment=Object.freeze({...process.env});
3626
- let app:Awaited<ReturnType<typeof bootstrapApp>>|undefined;
3627
- await createScheduleRunCommand(async()=>{
3628
- app=await bootstrapApp({migrate:false,mode:"command"});const {createSchedule}=await import("../bootstrap/schedule.ts");return createSchedule(app,environment);
3629
- },async()=>{await app?.context.dispose();},{scheduler:createScheduleRunOptions(environment)})();
3630
- }
3631
- export {scheduleRunCommand};
3632
- `;
3633
- }
3634
3063
 
3635
3064
  // src/renderDatabase.ts
3636
- function renderDatabaseTs(plan) {
3637
- const layers = plan.layers;
3638
- const driver = plan.decisions.sqlDriver;
3639
- const filename = layers.database === "sqlite" ? `
3640
- function sqliteFilename(url: string): string {
3641
- const trimmed = url.trim();
3642
- if (trimmed === ":memory:" || trimmed === "sqlite::memory:") return ":memory:";
3643
- if (trimmed.startsWith("sqlite:")) return trimmed.slice("sqlite:".length).replace(/^\\/\\//, "") || "./storage/app.sqlite";
3644
- return trimmed || "./storage/app.sqlite";
3065
+ function renderDatabaseTs(plan, projectName = "strata") {
3066
+ return `import { resolve } from "node:path";
3067
+ import type { DatabaseSession, TransactionSession } from "@getstrata/core/database/session";
3068
+ import { resolveDatabaseOptions } from "@getstrata/bootstrap/databaseCommands";
3069
+ import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3070
+
3071
+ export function databaseEnvironment(input: Readonly<Record<string, string | undefined>> = process.env) {
3072
+ const environment = { ...input };
3073
+ if (!isProductionEnv(environment) && !environment.APP_DATABASE_URL?.trim() && !environment.DATABASE_URL?.trim()) {
3074
+ environment.DATABASE_URL = ${JSON.stringify(defaultDatabaseUrl(plan.layers, projectName))};
3075
+ ${defaultMigrationDatabaseUrl(plan.layers, projectName) ? ` environment.MIGRATION_DATABASE_URL ??= ${JSON.stringify(defaultMigrationDatabaseUrl(plan.layers, projectName))};` : ""}
3076
+ }
3077
+ return Object.freeze(environment);
3645
3078
  }
3646
- ` : "";
3647
- const options = layers.database === "sqlite" ? `return Object.freeze({ driver: "sqlite", filename: sqliteFilename(url) });` : `return Object.freeze({ driver: "${driver}", url${driver === "pgsql" ? ", max: 5" : ""} });`;
3648
- return `import type { DatabaseConnectionOptions, DatabaseSession, TransactionSession } from "@getstrata/core/database/session";
3649
- ${filename}
3079
+
3650
3080
  /** Copy configuration once at composition; opening and closing belong to the Application. */
3651
- export function databaseOptions(env: Readonly<Record<string, string | undefined>> = process.env): DatabaseConnectionOptions {
3652
- const url = env.APP_DATABASE_URL?.trim() || env.DATABASE_URL?.trim();
3653
- if (!url) throw new Error("DATABASE_URL is required");
3654
- ${options}
3081
+ export function databaseOptions(environment: Readonly<Record<string, string | undefined>> = process.env) {
3082
+ return resolveDatabaseOptions(databaseEnvironment(environment), { driver: "${plan.decisions.sqlDriver}", defaultUrl: ${JSON.stringify(defaultDatabaseUrl(plan.layers, projectName))}, root: resolve(import.meta.dir, "../..") });
3655
3083
  }
3656
3084
 
3657
3085
  export async function pingDatabase(selected: DatabaseSession | TransactionSession): Promise<boolean> {
@@ -3665,104 +3093,22 @@ export async function pingDatabase(selected: DatabaseSession | TransactionSessio
3665
3093
  `;
3666
3094
  }
3667
3095
  function renderEnsureDatabaseTs(plan, projectName) {
3668
- const layers = plan.layers;
3669
- if (layers.database === "sqlite") {
3096
+ if (plan.layers.database === "sqlite")
3670
3097
  return null;
3671
- }
3672
- const fallback = defaultDatabaseUrl(layers, projectName);
3673
- const resolveUrl = `/**
3674
- * Runtime URL. Superuser CREATE ROLE / CREATE DATABASE / GRANT / migrate uses
3675
- * MIGRATION_DATABASE_URL when set.
3676
- */
3677
- function resolveAppDatabaseUrl(): string {
3678
- const explicit = process.env.APP_DATABASE_URL?.trim();
3679
- if (explicit) {
3680
- return explicit;
3681
- }
3682
- const configured = process.env.DATABASE_URL?.trim();
3683
- if (configured) return configured;
3684
- if (isProductionEnv()) throw new Error("DATABASE_URL or APP_DATABASE_URL is required in production/staging.");
3685
- return DEFAULT_DATABASE_URL;
3686
- }
3687
- `;
3688
- const safeName = `/** Reject anything we would have to quote before interpolating into DDL. */
3689
- function safeDatabaseName(url: string): string {
3690
- let name = "";
3691
- try {
3692
- name = decodeURIComponent(new URL(url).pathname.replace(/^\\//, ""));
3693
- } catch {
3694
- throw new Error(\`DATABASE_URL is not a valid URL: \${url}\`);
3695
- }
3696
- if (!name) {
3697
- throw new Error("DATABASE_URL is missing a database name.");
3698
- }
3699
- if (name.replace(/[^A-Za-z0-9_]/g, "") !== name) {
3700
- throw new Error(\`Refusing to create a database with an unsafe name: \${name}\`);
3701
- }
3702
- return name;
3703
- }
3704
- `;
3705
- if (layers.database === "mysql") {
3706
- return `import { createConnection } from "mysql2/promise";
3707
- import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3708
-
3709
- const DEFAULT_DATABASE_URL = ${JSON.stringify(fallback)};
3710
-
3711
- ${resolveUrl}${safeName}
3712
- export async function ensureAppDatabase(options: { provision?: boolean } = {}): Promise<string> {
3713
- const url = resolveAppDatabaseUrl();
3714
- if (!(options.provision ?? !isProductionEnv())) {
3715
- process.env.DATABASE_URL = url;
3716
- return url;
3717
- }
3718
- const name = safeDatabaseName(url);
3719
-
3720
- // Explicit schema operations use the administrative connection when supplied.
3721
- const admin = new URL(process.env.MIGRATION_DATABASE_URL?.trim() || url);
3722
- admin.pathname = "/";
3723
- const connection = await createConnection(admin.toString());
3724
- try {
3725
- await connection.query(\`CREATE DATABASE IF NOT EXISTS \${name}\`);
3726
- } finally {
3727
- await connection.end();
3728
- }
3729
-
3730
- process.env.DATABASE_URL = url;
3731
- return url;
3732
- }
3733
- `;
3734
- }
3735
- return `import {
3736
- ensurePostgresDatabaseAndAppRole,
3737
- POSTGRES_APP_ROLE_PASSWORD,
3738
- } from "@getstrata/core/tenant/enableTenantRls";
3098
+ return `import { resolve } from "node:path";
3099
+ import { ensureDatabase, resolveDatabaseOptions } from "@getstrata/bootstrap/databaseCommands";
3739
3100
  import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
3101
+ import { databaseEnvironment } from "./database.ts";
3740
3102
 
3741
- const DEFAULT_DATABASE_URL = ${JSON.stringify(fallback)};
3742
-
3743
- ${resolveUrl}
3744
- export async function ensureAppDatabase(options: { provision?: boolean } = {}): Promise<string> {
3745
- const url = resolveAppDatabaseUrl();
3746
- if (options.provision ?? !isProductionEnv()) {
3747
- if (isProductionEnv()) {
3748
- if (!process.env.MIGRATION_DATABASE_URL?.trim()) throw new Error("MIGRATION_DATABASE_URL is required for production/staging provisioning.");
3749
- const password = process.env.STRATA_APP_PASSWORD?.trim();
3750
- if (!password || password === POSTGRES_APP_ROLE_PASSWORD) throw new Error("Set an explicit non-development STRATA_APP_PASSWORD for production/staging provisioning.");
3751
- }
3752
- await ensurePostgresDatabaseAndAppRole({
3753
- runtimeUrl: url,
3754
- migrationUrl: process.env.MIGRATION_DATABASE_URL,
3755
- password: process.env.STRATA_APP_PASSWORD ?? POSTGRES_APP_ROLE_PASSWORD,
3756
- });
3757
- }
3758
- process.env.DATABASE_URL = url;
3759
- return url;
3103
+ export async function ensureAppDatabase(options: { provision?: boolean; environment?: Readonly<Record<string, string | undefined>> } = {}): Promise<string> {
3104
+ const environment = databaseEnvironment(options.environment ?? process.env);
3105
+ const connection = resolveDatabaseOptions(environment, { driver: "${plan.decisions.sqlDriver}", defaultUrl: ${JSON.stringify(defaultDatabaseUrl(plan.layers, projectName))}, root: resolve(import.meta.dir, "../..") });
3106
+ if (connection.driver === "sqlite") throw new Error("Unexpected provisioning database driver");
3107
+ return ensureDatabase({ driver: connection.driver, runtimeUrl: connection.url, migrationUrl: environment.MIGRATION_DATABASE_URL,
3108
+ password: environment.STRATA_APP_PASSWORD, production: isProductionEnv(environment), provision: options.provision });
3760
3109
  }
3761
3110
  `;
3762
3111
  }
3763
- function renderSidecarsTs(_plan) {
3764
- return null;
3765
- }
3766
3112
 
3767
3113
  // src/renderDocker.ts
3768
3114
  function renderServiceHealthcheck(test) {
@@ -4173,8 +3519,9 @@ HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
4173
3519
  - Register: \`/register\`
4174
3520
  - Forgot password: \`/forgot-password\`
4175
3521
  - Reset password: signed \`/reset-password\` (mail log when \`MAIL_DRIVER=log\`)
4176
- ${layers.extras.emailVerification ? "- Verify email: `/email/verify`\n" : ""}${layers.extras.mfa ? "- MFA challenge: `/login/mfa` and setup: `/account/mfa`\n" : ""}${layers.extras.oauthGithub ? "- GitHub: `/auth/github` (needs `FEATURE_OAUTH=true`). Failures on the callback are JSON, not the login page. State is the signed query value from `createOAuthState()`, not `createOAuthStateCookie()`.\n" : ""}${layers.extras.oidc ? "- OIDC: `/auth/oidc` (needs `FEATURE_OAUTH=true` plus `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`; otherwise the login link stays hidden and the route is 404). PKCE cookie `oidc_pkce`. Callback failures are JSON, not the login page.\n" : ""}
3522
+ ${layers.extras.emailVerification ? "- Verify email: `/email/verify`\n" : ""}${layers.extras.mfa ? "- MFA challenge: `/login/mfa` and setup: `/account/mfa`\n" : ""}${layers.extras.oauthGithub ? "- GitHub: `/auth/github` (needs `FEATURE_OAUTH=true`). Failures on the callback are JSON, not the login page. State is signed and bound to the browser by the HttpOnly `oauth_state` cookie from `createOAuthStateCookie()`. The callback requires the matching cookie and clears it.\n" : ""}${layers.extras.oidc ? "- OIDC: `/auth/oidc` (needs `FEATURE_OAUTH=true` plus `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`; otherwise the login link stays hidden and the route is 404). PKCE cookie `oidc_pkce`. Callback failures are JSON, not the login page.\n" : ""}
4177
3523
  Cookie name is \`strata_session\`. Forms send CSRF as \`_token\`.
3524
+ SAML start/ACS bind RelayState to a dedicated HttpOnly \`saml_state\` cookie with \`SameSite=None; Secure\`. Browser SAML login requires HTTPS, including development.
4178
3525
  ` : ""}${plan.decisions.jsonCookieAccounts ? `
4179
3526
  JSON cookie account flows: fetch \`GET /api/v1/auth/csrf\`, retain the cookie and send \`X-CSRF-Token\` on writes (browser clients use credentials). Register through \`POST /api/v1/auth/register\` (neutral 201), login through \`POST /api/v1/auth/login\` (session cookie), and read \`GET /api/v1/auth/me\`. Reset through \`POST /api/v1/auth/forgot-password\` then signed \`POST /api/v1/auth/reset-password\` with \`{ password }\`.
4180
3527
  ${layers.extras.emailVerification ? "Verify through signed `POST /api/v1/auth/verify-email`; authenticated unverified owners resend through `POST /api/v1/auth/verification-notification`.\n" : ""}${layers.extras.mfa ? "MFA setup: `GET /api/v1/auth/mfa`, confirm the current password through `POST /api/v1/auth/confirm-password`, then submit `{ secret, code }` to `POST /api/v1/auth/mfa`. Store the returned recovery codes safely; enrollment revokes credentials. Login again with `{ email, password, mfa_code }` using a TOTP or one-use recovery code. Missing code returns JSON 401 `mfa_required`.\n" : ""}
@@ -4640,11 +3987,12 @@ function renderPackageJson(projectName, options = {}) {
4640
3987
  "@getstrata/cli": "workspace:*",
4641
3988
  "@getstrata/core": "workspace:*"
4642
3989
  } : {
4643
- "@getstrata/bootstrap": "^3.0.5",
4644
- "@getstrata/cli": "^3.0.5",
4645
- "@getstrata/core": "^3.0.5"
3990
+ "@getstrata/bootstrap": "^3.0.8",
3991
+ "@getstrata/cli": "^3.0.8",
3992
+ "@getstrata/core": "^3.0.8"
4646
3993
  };
4647
- coreDeps.eta = "^4.6.0";
3994
+ if (!options.plan || options.plan.decisions.serverViews || options.plan.decisions.mfaViews)
3995
+ coreDeps.eta = "^4.6.0";
4648
3996
  if (options.plan?.decisions.mysqlDependency) {
4649
3997
  coreDeps.mysql2 = "^3.24.3";
4650
3998
  }
@@ -4696,7 +4044,7 @@ function renderLayersManifest(projectName, plan) {
4696
4044
  extras: layers.extras,
4697
4045
  docker: layers.docker
4698
4046
  },
4699
- notes: "Generated by create-strata. Change layers later with flags or by editing env and bootstrap files."
4047
+ notes: "Generated by create-strata. Generation provenance only. Runtime choices live in src/config/app.ts and environment configuration; changing this file does not modify the application."
4700
4048
  }, null, 2)}
4701
4049
  `;
4702
4050
  }
@@ -4789,7 +4137,7 @@ function ensureImport(plan) {
4789
4137
  ` : "";
4790
4138
  }
4791
4139
  function ensureCall(plan, provision = true) {
4792
- return plan.decisions.ensureDatabase ? ` await ensureAppDatabase({ provision: ${provision} });
4140
+ return plan.decisions.ensureDatabase ? ` await ensureAppDatabase({ provision: ${provision}, environment });
4793
4141
  ` : "";
4794
4142
  }
4795
4143
  function dialectFragments(database) {
@@ -4950,44 +4298,20 @@ ${downCalls}
4950
4298
  export default migration;
4951
4299
  `;
4952
4300
  }
4953
- function renderMigrationRuntimeTs(plan) {
4954
- const layers = plan.layers;
4955
- const driver = plan.decisions.sqlDriver;
4956
- const imports = layers.database === "postgres" ? `import { grantPostgresAppRolePrivileges, openPostgresAdminConnection, postgresDatabaseNameFromUrl } from "@getstrata/core/tenant/enableTenantRls";` : layers.database === "mysql" ? `import { createMysqlConnection } from "@getstrata/core/database/mysqlConnection";` : `import { mkdirSync } from "node:fs";
4957
- import { dirname } from "node:path";
4958
- import { createSqliteConnection } from "@getstrata/core/database/sqliteConnection";`;
4959
- const opening = layers.database === "postgres" ? `const connection = await openPostgresAdminConnection({runtimeUrl: options.url, migrationUrl: process.env.MIGRATION_DATABASE_URL});` : layers.database === "mysql" ? `const connection = createMysqlConnection(process.env.MIGRATION_DATABASE_URL?.trim() || options.url);` : `if (options.filename !== ":memory:") mkdirSync(dirname(options.filename), { recursive: true });
4960
- const connection = createSqliteConnection(options.filename);`;
4961
- const grantOption = layers.database === "postgres" ? `,
4962
- controls: { grantRuntimePrivileges?: boolean } = {}` : "";
4963
- const grants = layers.database === "postgres" ? `
4964
- if (controls.grantRuntimePrivileges !== false) await grantPostgresAppRolePrivileges(connection, {database: postgresDatabaseNameFromUrl(options.url)});` : "";
4301
+ function renderMigrationRuntimeTs(_plan) {
4965
4302
  return `import { join } from "node:path";
4966
4303
  import { loadMigrationsFromDirectory } from "@getstrata/core/database/migrations";
4967
4304
  import type { MigrationDatabase } from "@getstrata/core/database/migrations/types";
4968
- import { runWithSqlDialect } from "@getstrata/core/database/dialect";
4969
- ${imports}
4970
- import { databaseOptions } from "../bootstrap/database.ts";
4971
-
4972
- const MIGRATIONS_DIRECTORY = join(import.meta.dir, "migrations");
4305
+ import { withMigrationDatabase as runMigrationDatabase } from "@getstrata/bootstrap/databaseCommands";
4306
+ import { databaseOptions, databaseEnvironment } from "../bootstrap/database.ts";
4973
4307
 
4974
- export async function loadStarterMigrations() {
4975
- return loadMigrationsFromDirectory(MIGRATIONS_DIRECTORY);
4308
+ export function loadStarterMigrations() {
4309
+ return loadMigrationsFromDirectory(join(import.meta.dir, "migrations"));
4976
4310
  }
4977
4311
 
4978
- /** Schema commands own this connection; it never becomes the runtime pool. */
4979
- export async function withMigrationDatabase<T>(
4980
- fn: (db: MigrationDatabase) => Promise<T>${grantOption},
4981
- ): Promise<T> {
4982
- const options = databaseOptions();
4983
- if (options.driver !== "${driver}") throw new Error("Unexpected migration database driver");
4984
- ${opening}
4985
- try {
4986
- const result = await runWithSqlDialect("${driver}", () => fn(connection));${grants}
4987
- return result;
4988
- } finally {
4989
- await connection.close?.();
4990
- }
4312
+ export function withMigrationDatabase<T>(operation: (db: MigrationDatabase) => Promise<T>, controls: { grantRuntimePrivileges?: boolean; environment?: Readonly<Record<string, string | undefined>> } = {}): Promise<T> {
4313
+ const environment = databaseEnvironment(controls.environment ?? process.env);
4314
+ return runMigrationDatabase(databaseOptions(environment), operation, { ...controls, environment });
4991
4315
  }
4992
4316
  `;
4993
4317
  }
@@ -5016,14 +4340,15 @@ import type { DatabaseSession, TransactionSession } from "@getstrata/core/databa
5016
4340
  import { createPersistenceInvocation } from "@getstrata/bootstrap/persistenceInvocation";
5017
4341
  import { migrateDatabase } from "@getstrata/core/database/migrations";
5018
4342
  import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
5019
- import { databaseOptions } from "../bootstrap/database.ts";
4343
+ import { databaseOptions, databaseEnvironment } from "../bootstrap/database.ts";
5020
4344
  import { Note, NoteRepository } from "../models/Note.ts";
5021
4345
  import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
5022
4346
 
5023
4347
  /** An explicit development-only command owns its own canonical Application. */
5024
- export async function seed() {
5025
- if (isProductionEnv()) throw new Error("Demo seeding is disabled in production and staging.");
5026
- ${ensureCall(plan)} const connection = databaseOptions();
4348
+ export async function seed(input: Readonly<Record<string, string | undefined>> = process.env) {
4349
+ const environment = databaseEnvironment(input);
4350
+ if (isProductionEnv(environment)) throw new Error("Demo seeding is disabled in production and staging.");
4351
+ ${ensureCall(plan)} const connection = databaseOptions(environment);
5027
4352
  const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},repositories:[NoteRepository${usersOn ? ",UserRepository" : ""}],models:[Note${usersOn ? ",User" : ""}]})});
5028
4353
  await application.start();
5029
4354
  try {
@@ -5040,10 +4365,11 @@ ${ensureCall(plan)} const connection = databaseOptions();
5040
4365
  }
5041
4366
  }
5042
4367
 
5043
- export async function migrate() {
4368
+ export async function migrate(input: Readonly<Record<string, string | undefined>> = process.env) {
4369
+ const environment = databaseEnvironment(input);
5044
4370
  ${ensureCall(plan)} await withMigrationDatabase(async (db) => {
5045
4371
  await migrateDatabase(db, await loadStarterMigrations());
5046
- });
4372
+ }, { environment });
5047
4373
  }
5048
4374
 
5049
4375
  if (import.meta.main) {
@@ -5075,12 +4401,14 @@ function renderFreshTs(plan) {
5075
4401
  return `${ensureImport(plan)}import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
5076
4402
  import { freshDatabase } from "@getstrata/core/database/migrations";
5077
4403
  import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
4404
+ import { databaseEnvironment } from "../bootstrap/database.ts";
5078
4405
 
5079
- export async function fresh() {
5080
- if (isProductionEnv()) throw new Error("migrate:fresh is only available in development/test environments.");
4406
+ export async function fresh(input: Readonly<Record<string, string | undefined>> = process.env) {
4407
+ const environment = databaseEnvironment(input);
4408
+ if (isProductionEnv(environment)) throw new Error("migrate:fresh is only available in development/test environments.");
5081
4409
  ${ensureCall(plan)} await withMigrationDatabase(async (db) => {
5082
- await freshDatabase(db, await loadStarterMigrations(), { destructive: true });
5083
- });
4410
+ await freshDatabase(db, await loadStarterMigrations(), { destructive: true, environment });
4411
+ }, { environment });
5084
4412
  }
5085
4413
 
5086
4414
  if (import.meta.main) {
@@ -5105,11 +4433,13 @@ function renderStatusTs(plan) {
5105
4433
  const layers = plan.layers;
5106
4434
  return `${ensureImport(plan)}import { getMigrationStatus } from "@getstrata/core/database/migrations";
5107
4435
  import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
4436
+ import { databaseEnvironment } from "../bootstrap/database.ts";
5108
4437
 
5109
- export async function status() {
4438
+ export async function status(input: Readonly<Record<string, string | undefined>> = process.env) {
4439
+ const environment = databaseEnvironment(input);
5110
4440
  ${ensureCall(plan, false)} const rows = await withMigrationDatabase(async (db) => {
5111
4441
  return getMigrationStatus(db, await loadStarterMigrations());
5112
- }${layers.database === "postgres" ? ", { grantRuntimePrivileges: false }" : ""});
4442
+ }, { environment${layers.database === "postgres" ? ", grantRuntimePrivileges: false" : ""} });
5113
4443
  console.log("Migrations:");
5114
4444
  for (const row of rows) {
5115
4445
  const batch = row.batch == null ? "" : \` (batch \${row.batch})\`;
@@ -5126,15 +4456,17 @@ if (import.meta.main) {
5126
4456
  function renderRollbackTs(plan) {
5127
4457
  return `${ensureImport(plan)}import { rollbackDatabase } from "@getstrata/core/database/migrations";
5128
4458
  import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
4459
+ import { databaseEnvironment } from "../bootstrap/database.ts";
5129
4460
 
5130
- export async function rollback() {
4461
+ export async function rollback(input: Readonly<Record<string, string | undefined>> = process.env) {
4462
+ const environment = databaseEnvironment(input);
5131
4463
  ${ensureCall(plan, false)} const rolledBack = await withMigrationDatabase(async (db) => {
5132
4464
  return rollbackDatabase(db, await loadStarterMigrations(), {
5133
4465
  onMigration: (name) => {
5134
4466
  console.log(\`rolled back \${name}\`);
5135
4467
  },
5136
4468
  });
5137
- });
4469
+ }, { environment });
5138
4470
  if (rolledBack === 0) {
5139
4471
  console.log("Nothing to roll back.");
5140
4472
  }
@@ -5365,7 +4697,7 @@ function renderNoteCreatedWebhookListener() {
5365
4697
  import { service } from "@getstrata/core/contracts/services";
5366
4698
  import { createServiceToken } from "@getstrata/core/contracts/token";
5367
4699
  import { repositoryEffects, type AfterCommitRepositoryListener } from "@getstrata/core/database/definitions";
5368
- import { STARTER_QUEUE_TOKEN, STARTER_WEBHOOK_OPTIONS_TOKEN } from "../bootstrap/providers/index.ts";
4700
+ import { APPLICATION_QUEUE as STARTER_QUEUE_TOKEN, APPLICATION_WEBHOOKS as STARTER_WEBHOOK_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
5369
4701
  import { NoteRepository, type NoteRecord } from "../models/Note.ts";
5370
4702
  import DispatchOutboundWebhookJob from "../jobs/dispatchOutboundWebhookJob.ts";
5371
4703
 
@@ -5448,7 +4780,7 @@ function renderBillingModule(plan) {
5448
4780
  import { jsonResponse } from "@getstrata/core/http/response";
5449
4781
  import { verifyStripeWebhookSignature } from "@getstrata/core/security/stripeWebhook";
5450
4782
  import { applyStripeWebhook } from "../../billing/applyStripeWebhook.ts";
5451
- import { STARTER_BILLING_OPTIONS_TOKEN } from "../../bootstrap/providers/index.ts";
4783
+ import { APPLICATION_BILLING as STARTER_BILLING_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
5452
4784
 
5453
4785
  const billingModule: AppModule = {
5454
4786
  name: "billing",
@@ -5503,9 +4835,7 @@ function renderNoteModel(plan) {
5503
4835
  tenant_id: number;` : "";
5504
4836
  const tenantColumn = tenancyOn ? ', "tenant_id"' : "";
5505
4837
  const fillable = tenancyOn ? '["body", "tenant_id"]' : '["body"]';
5506
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
5507
- import { defineModel, defineRepository } from "@getstrata/core/database/definitions";
5508
- import { Model } from "@getstrata/core/database/model";
4838
+ return `import { createModel, type Model } from "@getstrata/core/database/model";
5509
4839
  import { defineTable } from "@getstrata/core/database/table";
5510
4840
 
5511
4841
  interface NoteRecord {
@@ -5521,22 +4851,17 @@ const notesTable = defineTable<NoteRecord, "id">({
5521
4851
  defaultOrderBy: { column: "id", direction: "ASC" },
5522
4852
  });
5523
4853
 
5524
- class NoteEntity extends Model<NoteRecord, "id"> {}
5525
- type Note = NoteEntity;
4854
+ type Note = Model<NoteRecord, "id">;
5526
4855
 
5527
- const NoteRepository = defineRepository<NoteRecord, "id", BaseRepository<NoteRecord, "id">, readonly []>({
5528
- name: "NoteRepository", table: notesTable, dependencies: [],
5529
- create: binding => new BaseRepository(binding),
5530
- });
5531
- const Note = defineModel<NoteRecord, "id", NoteEntity, BaseRepository<NoteRecord, "id">, readonly []>({
5532
- name: "Note", repository: NoteRepository, dependencies: [],
4856
+ const Note = createModel({
4857
+ name: "Note", table: notesTable,
5533
4858
  // created_at uses the table default; no client timestamp is sent.
5534
4859
  attributes: { fillable: ${fillable}, timestamps: false },
5535
- construct: (state, binding) => new NoteEntity(state, binding),
5536
4860
  });
4861
+ const NoteRepository = Note.repository;
5537
4862
 
5538
4863
  export type { NoteRecord };
5539
- export { Note, NoteEntity, NoteRepository };
4864
+ export { Note, NoteRepository };
5540
4865
  `;
5541
4866
  }
5542
4867
  function renderUserModel(plan) {
@@ -5572,9 +4897,7 @@ function renderUserModel(plan) {
5572
4897
  const fillableLiteral = `[${fillable.map((column) => `"${column}"`).join(", ")}]`;
5573
4898
  const hiddenLiteral = `[${hidden.map((column) => `"${column}"`).join(", ")}]`;
5574
4899
  const columnsLiteral = columns.map((column) => `"${column}"`).join(", ");
5575
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
5576
- import { defineModel, defineRepository } from "@getstrata/core/database/definitions";
5577
- import { Model } from "@getstrata/core/database/model";
4900
+ return `import { createModel, type Model } from "@getstrata/core/database/model";
5578
4901
  import { defineTable } from "@getstrata/core/database/table";
5579
4902
 
5580
4903
  interface UserRecord {
@@ -5597,28 +4920,21 @@ const usersTable = defineTable<UserRecord, "id">({
5597
4920
  defaultOrderBy: { column: "id", direction: "ASC" },
5598
4921
  });
5599
4922
 
5600
- class UserEntity extends Model<UserRecord, "id"> {}
5601
- type User = UserEntity;
4923
+ type User = Model<UserRecord, "id">;
5602
4924
 
5603
- const UserRepository = defineRepository<UserRecord, "id", BaseRepository<UserRecord, "id">, readonly []>({
5604
- name: "UserRepository", table: usersTable, dependencies: [],
5605
- create: binding => new BaseRepository(binding),
5606
- });
5607
- const User = defineModel<UserRecord, "id", UserEntity, BaseRepository<UserRecord, "id">, readonly []>({
5608
- name: "User", repository: UserRepository, dependencies: [],
4925
+ const User = createModel({
4926
+ name: "User", table: usersTable,
5609
4927
  // created_at uses the table default; no client timestamp is sent.
5610
4928
  attributes: { fillable: ${fillableLiteral}, hidden: ${hiddenLiteral}, timestamps: false },
5611
- construct: (state, binding) => new UserEntity(state, binding),
5612
4929
  });
4930
+ const UserRepository = User.repository;
5613
4931
 
5614
4932
  export type { UserRecord };
5615
- export { User, UserEntity, UserRepository };
4933
+ export { User, UserRepository };
5616
4934
  `;
5617
4935
  }
5618
4936
  function renderApiTokenModel() {
5619
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
5620
- import { defineModel, defineRepository } from "@getstrata/core/database/definitions";
5621
- import { Model } from "@getstrata/core/database/model";
4937
+ return `import { createModel, type Model } from "@getstrata/core/database/model";
5622
4938
  import { defineTable } from "@getstrata/core/database/table";
5623
4939
 
5624
4940
  interface ApiTokenRecord {
@@ -5639,28 +4955,21 @@ const apiTokensTable = defineTable<ApiTokenRecord, "id">({
5639
4955
  defaultOrderBy: { column: "id", direction: "ASC" },
5640
4956
  });
5641
4957
 
5642
- class ApiTokenEntity extends Model<ApiTokenRecord, "id"> {}
5643
- type ApiToken = ApiTokenEntity;
4958
+ type ApiToken = Model<ApiTokenRecord, "id">;
5644
4959
 
5645
- const ApiTokenRepository = defineRepository<ApiTokenRecord, "id", BaseRepository<ApiTokenRecord, "id">, readonly []>({
5646
- name: "ApiTokenRepository", table: apiTokensTable, dependencies: [],
5647
- create: binding => new BaseRepository(binding),
5648
- });
5649
- const ApiToken = defineModel<ApiTokenRecord, "id", ApiTokenEntity, BaseRepository<ApiTokenRecord, "id">, readonly []>({
5650
- name: "ApiToken", repository: ApiTokenRepository, dependencies: [],
4960
+ const ApiToken = createModel({
4961
+ name: "ApiToken", table: apiTokensTable,
5651
4962
  // created_at uses the table default; no client timestamp is sent.
5652
4963
  attributes: { fillable: ["user_id", "name", "token_hash", "abilities", "expires_at", "last_used_at"], timestamps: false },
5653
- construct: (state, binding) => new ApiTokenEntity(state, binding),
5654
4964
  });
4965
+ const ApiTokenRepository = ApiToken.repository;
5655
4966
 
5656
4967
  export type { ApiTokenRecord };
5657
- export { ApiToken, ApiTokenEntity, ApiTokenRepository };
4968
+ export { ApiToken, ApiTokenRepository };
5658
4969
  `;
5659
4970
  }
5660
4971
  function renderAuthOneTimeTokenModel() {
5661
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
5662
- import { defineModel, defineRepository } from "@getstrata/core/database/definitions";
5663
- import { Model } from "@getstrata/core/database/model";
4972
+ return `import { createModel, type Model } from "@getstrata/core/database/model";
5664
4973
  import { defineTable } from "@getstrata/core/database/table";
5665
4974
 
5666
4975
  interface AuthOneTimeTokenRecord {
@@ -5679,21 +4988,16 @@ const authOneTimeTokensTable = defineTable<AuthOneTimeTokenRecord, "id">({
5679
4988
  defaultOrderBy: { column: "id", direction: "ASC" },
5680
4989
  });
5681
4990
 
5682
- class AuthOneTimeTokenEntity extends Model<AuthOneTimeTokenRecord, "id"> {}
5683
- type AuthOneTimeToken = AuthOneTimeTokenEntity;
4991
+ type AuthOneTimeToken = Model<AuthOneTimeTokenRecord, "id">;
5684
4992
 
5685
- const AuthOneTimeTokenRepository = defineRepository<AuthOneTimeTokenRecord, "id", BaseRepository<AuthOneTimeTokenRecord, "id">, readonly []>({
5686
- name: "AuthOneTimeTokenRepository", table: authOneTimeTokensTable, dependencies: [],
5687
- create: binding => new BaseRepository(binding),
5688
- });
5689
- const AuthOneTimeToken = defineModel<AuthOneTimeTokenRecord, "id", AuthOneTimeTokenEntity, BaseRepository<AuthOneTimeTokenRecord, "id">, readonly []>({
5690
- name: "AuthOneTimeToken", repository: AuthOneTimeTokenRepository, dependencies: [],
4993
+ const AuthOneTimeToken = createModel({
4994
+ name: "AuthOneTimeToken", table: authOneTimeTokensTable,
5691
4995
  attributes: { fillable: ["purpose", "user_id", "token_hash", "expires_at", "consumed_at"], timestamps: false },
5692
- construct: (state, binding) => new AuthOneTimeTokenEntity(state, binding),
5693
4996
  });
4997
+ const AuthOneTimeTokenRepository = AuthOneTimeToken.repository;
5694
4998
 
5695
4999
  export type { AuthOneTimeTokenRecord };
5696
- export { AuthOneTimeToken, AuthOneTimeTokenEntity, AuthOneTimeTokenRepository };
5000
+ export { AuthOneTimeToken, AuthOneTimeTokenRepository };
5697
5001
  `;
5698
5002
  }
5699
5003
  function renderModelsRegister(plan) {
@@ -5728,7 +5032,7 @@ import { BadRequestError } from "@getstrata/core/errors/http";
5728
5032
  import { parsePositiveIntParam } from "@getstrata/core/http/validation";
5729
5033
  import { createScimThrottleMiddleware } from "@getstrata/core/http/scimThrottleMiddleware";
5730
5034
  import { User } from "../../models/User.ts";
5731
- import { STARTER_AUTH_SERVICES, type StarterAuthServices } from "../../bootstrap/providers/auth.ts";
5035
+ import { STARTER_AUTH_SERVICES, type StarterAuthServices } from "../../bootstrap/auth.ts";
5732
5036
 
5733
5037
  const USER_SCHEMA = "urn:ietf:params:scim:schemas:core:2.0:User";
5734
5038
  const LIST_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
@@ -6391,11 +5695,11 @@ function starterPackageRoot() {
6391
5695
  }
6392
5696
  function resolveTemplateRoot(root = starterPackageRoot()) {
6393
5697
  const fromDist = join2(root, "templates");
6394
- if (existsSync2(join2(fromDist, "src"))) {
5698
+ if (existsSync2(join2(fromDist, "tsconfig.json"))) {
6395
5699
  return fromDist;
6396
5700
  }
6397
5701
  const nested = join2(root, "dist/templates");
6398
- if (existsSync2(join2(nested, "src"))) {
5702
+ if (existsSync2(join2(nested, "tsconfig.json"))) {
6399
5703
  return nested;
6400
5704
  }
6401
5705
  return fromDist;
@@ -6489,11 +5793,10 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
6489
5793
  removeIfExists(join2(targetDir, "db/ensure-postgres-app-role.sql"));
6490
5794
  removeIfExists(join2(targetDir, "docker/postgres-init"));
6491
5795
  }
6492
- writeText(join2(src, "routes.ts"), renderRoutesTs());
6493
- writeText(join2(src, "bootstrap/providers/view.ts"), renderViewProvider(plan));
6494
- writeText(join2(src, "bootstrap/config.ts"), renderConfigTs());
6495
- writeText(join2(src, "bootstrap/preload.ts"), renderPreloadTs(plan, projectName));
6496
- writeText(join2(src, "bootstrap/database.ts"), renderDatabaseTs(plan));
5796
+ writeText(join2(src, "config/app.ts"), renderConfigTs(plan, projectName));
5797
+ writeText(join2(src, "bootstrap/server.ts"), renderServerTs());
5798
+ writeText(join2(targetDir, "strata.config.ts"), renderStrataConfigTs());
5799
+ writeText(join2(src, "bootstrap/database.ts"), renderDatabaseTs(plan, projectName));
6497
5800
  const ensureDatabase = renderEnsureDatabaseTs(plan, projectName);
6498
5801
  if (ensureDatabase) {
6499
5802
  writeText(join2(src, "bootstrap/ensureDatabase.ts"), ensureDatabase);
@@ -6512,17 +5815,8 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
6512
5815
  removeIfExists(join2(src, "cli/initialAdmin.ts"));
6513
5816
  removeIfExists(join2(src, "db/migrations/0004_initial_admin_provisioning.ts"));
6514
5817
  }
6515
- writeText(join2(src, "cli/queueWork.ts"), renderCliQueueWorkTs());
6516
- writeText(join2(src, "cli/outboxWork.ts"), renderCliOutboxWorkTs());
6517
5818
  writeText(join2(src, "outbox/registry.ts"), renderOutboxRegistryTs(plan));
6518
- writeText(join2(src, "cli/queueFailed.ts"), renderCliQueueFailedTs());
6519
- writeText(join2(src, "cli/openapi.ts"), renderCliOpenApiTs());
6520
- writeText(join2(src, "cli/scheduleRun.ts"), renderCliScheduleRunTs());
6521
- writeText(join2(src, "bootstrap/providers/config.ts"), renderConfigProvider(plan));
6522
- writeText(join2(src, "bootstrap/providers/queue.ts"), renderQueueProvider());
6523
- writeText(join2(src, "bootstrap/providers/policy.ts"), renderPolicyProvider());
6524
- writeText(join2(src, "bootstrap/providers/index.ts"), renderProvidersIndex());
6525
- writeText(join2(src, "bootstrap/providers/auth.ts"), renderAuthProvider(plan));
5819
+ writeText(join2(src, "bootstrap/auth.ts"), renderAuthProvider(plan));
6526
5820
  writeText(join2(src, "models/Note.ts"), renderNoteModel(plan));
6527
5821
  if (decisions.users) {
6528
5822
  writeText(join2(src, "models/User.ts"), renderUserModel(plan));
@@ -6563,15 +5857,12 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
6563
5857
  writeText(join2(src, "db/seed.ts"), renderSeedTs());
6564
5858
  writeText(join2(src, "db/status.ts"), renderStatusTs(plan));
6565
5859
  writeText(join2(src, "db/rollback.ts"), renderRollbackTs(plan));
6566
- writeText(join2(src, "modules/site/index.ts"), renderSiteModule(plan));
5860
+ if (decisions.serverViews)
5861
+ writeText(join2(src, "modules/site/index.ts"), renderSiteModule(plan));
6567
5862
  const directory = renderAuthDirectory(plan);
6568
5863
  if (directory) {
6569
5864
  writeText(join2(src, "bootstrap/authDirectory.ts"), directory);
6570
5865
  }
6571
- const sidecars = renderSidecarsTs(plan);
6572
- if (sidecars) {
6573
- writeText(join2(src, "bootstrap/sidecars.ts"), sidecars);
6574
- }
6575
5866
  const authModule = renderAuthModule(plan);
6576
5867
  if (authModule) {
6577
5868
  writeText(join2(src, "modules/auth/index.ts"), authModule);
@@ -6601,20 +5892,23 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
6601
5892
  } else {
6602
5893
  removeIfExists(join2(src, "bootstrap/pendingMfa.ts"));
6603
5894
  }
6604
- writeText(join2(targetDir, "public/assets/site.css"), renderSiteCss());
6605
- const htmxSource = join2(options.templateRoot ?? starterPackageRoot(), "public/assets/htmx.min.js");
6606
- const htmxFallback = join2(starterPackageRoot(), "templates/public/assets/htmx.min.js");
6607
- const htmxPath = existsSync2(htmxSource) ? htmxSource : htmxFallback;
6608
- if (existsSync2(htmxPath)) {
6609
- mkdirSync2(join2(targetDir, "public/assets"), { recursive: true });
6610
- copyFileSync(htmxPath, join2(targetDir, "public/assets/htmx.min.js"));
6611
- const versionSidecar = `${htmxPath}.version`;
6612
- if (existsSync2(versionSidecar)) {
6613
- copyFileSync(versionSidecar, join2(targetDir, "public/assets/htmx.min.js.version"));
5895
+ if (decisions.serverViews || decisions.mfaViews) {
5896
+ writeText(join2(targetDir, "public/assets/site.css"), renderSiteCss());
5897
+ const htmxSource = join2(options.templateRoot ?? starterPackageRoot(), "public/assets/htmx.min.js");
5898
+ const htmxFallback = join2(starterPackageRoot(), "templates/public/assets/htmx.min.js");
5899
+ const htmxPath = existsSync2(htmxSource) ? htmxSource : htmxFallback;
5900
+ if (existsSync2(htmxPath)) {
5901
+ mkdirSync2(join2(targetDir, "public/assets"), { recursive: true });
5902
+ copyFileSync(htmxPath, join2(targetDir, "public/assets/htmx.min.js"));
5903
+ const versionSidecar = `${htmxPath}.version`;
5904
+ if (existsSync2(versionSidecar)) {
5905
+ copyFileSync(versionSidecar, join2(targetDir, "public/assets/htmx.min.js.version"));
5906
+ }
6614
5907
  }
5908
+ if (decisions.serverViews)
5909
+ writeText(join2(targetDir, "views/home.eta"), renderHomeView(projectName, plan));
5910
+ writeText(join2(targetDir, "views/layouts/app.eta"), renderLayout(plan, projectName));
6615
5911
  }
6616
- writeText(join2(targetDir, "views/home.eta"), renderHomeView(projectName, plan));
6617
- writeText(join2(targetDir, "views/layouts/app.eta"), renderLayout(plan, projectName));
6618
5912
  if (decisions.htmlAuth) {
6619
5913
  writeText(join2(targetDir, "views/auth/login.eta"), renderLoginView(plan));
6620
5914
  writeText(join2(targetDir, "views/auth/register.eta"), renderRegisterView());
@@ -6694,7 +5988,7 @@ function generateProject(options) {
6694
5988
  }
6695
5989
  const owned = lstatSync(options.targetDir);
6696
5990
  try {
6697
- copyTree(options.templateRoot, options.targetDir, options.projectName, new Set(["overlays"]));
5991
+ copyTree(options.templateRoot, options.targetDir, options.projectName, new Set(["overlays", "public", "views"]));
6698
5992
  applyFrontendOverlays(options.overlayRoot, options.targetDir, plan);
6699
5993
  writeGeneratedFiles({ ...options, layers: plan.layers }, plan);
6700
5994
  for (const artifact of plan.artifacts) {
@@ -6706,10 +6000,10 @@ function generateProject(options) {
6706
6000
  const path = prefix ? `${prefix}/${entry.name}` : entry.name;
6707
6001
  return entry.isDirectory() ? inventory(join2(directory, entry.name), path) : [path];
6708
6002
  });
6709
- writeText(join2(options.targetDir, "strata.features.json"), JSON.stringify({
6003
+ writeText(join2(options.targetDir, ".strata/generator.json"), JSON.stringify({
6710
6004
  ...plan,
6711
6005
  emittedArtifacts: [
6712
- ...new Set([...inventory(options.targetDir), "strata.features.json"])
6006
+ ...new Set([...inventory(options.targetDir), ".strata/generator.json"])
6713
6007
  ].sort()
6714
6008
  }, null, 2));
6715
6009
  } catch (error) {