create-strata 3.0.7 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +20 -29
  2. package/dist/cli.js +665 -503
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -390,12 +390,19 @@ function compileStarterFeatures(input, reference) {
390
390
  const artifacts = [
391
391
  "package.json",
392
392
  "src/bootstrap/createApp.ts",
393
+ "src/routes/api.ts",
394
+ "src/routes/web.ts",
395
+ "src/routes/index.ts",
393
396
  "src/models/Note.ts",
394
397
  "src/models/register.ts",
395
398
  "src/db/migrations/0001_starter_schema.ts"
396
399
  ];
397
400
  if (decisions.users)
398
- artifacts.push("src/models/User.ts", "src/models/AuthOneTimeToken.ts", "src/db/migrations/0006_account_state.ts");
401
+ artifacts.push("src/http/controllers/AuthController.ts", "src/http/auth/account.ts", "src/models/User.ts", "src/models/AuthOneTimeToken.ts", "src/db/migrations/0006_account_state.ts");
402
+ if (decisions.cookie)
403
+ artifacts.push("src/http/controllers/AuthWebController.ts");
404
+ if (decisions.serverViews)
405
+ artifacts.push("src/http/controllers/HomeController.ts");
399
406
  if (decisions.token)
400
407
  artifacts.push("src/models/ApiToken.ts");
401
408
  if (decisions.frontendBuild)
@@ -407,13 +414,13 @@ function compileStarterFeatures(input, reference) {
407
414
  if (decisions.htmlAuth && layers.extras.emailVerification)
408
415
  artifacts.push("views/auth/verify-email.eta");
409
416
  if (layers.extras.scim)
410
- artifacts.push("src/modules/scim/index.ts");
417
+ artifacts.push("src/http/controllers/ScimController.ts");
411
418
  if (layers.extras.billing)
412
- artifacts.push("src/billing/applyStripeWebhook.ts", "src/modules/billing/index.ts");
419
+ artifacts.push("src/billing/applyStripeWebhook.ts", "src/http/controllers/BillingController.ts");
413
420
  if (layers.extras.webhooks)
414
421
  artifacts.push("src/jobs/dispatchOutboundWebhookJob.ts", "src/listeners/noteCreatedWebhookListener.ts");
415
422
  if (decisions.workTracker)
416
- artifacts.push("docs/WORK_TRACKER.md", "src/domain/workTracker.ts", "src/models/workTracker.ts", "src/modules/workTracker/index.ts", "src/db/migrations/0007_work_tracker.ts");
423
+ artifacts.push("docs/WORK_TRACKER.md", "src/domain/workTracker.ts", "src/models/workTracker.ts", "src/http/controllers/WorkTrackerController.ts", "src/http/requests/WorkRequest.ts", "src/db/migrations/0007_work_tracker.ts");
417
424
  return Object.freeze({
418
425
  version: 1,
419
426
  ...reference ? { reference } : {},
@@ -1390,18 +1397,62 @@ async function resolveStarterPlan(flags, injected) {
1390
1397
  }
1391
1398
  }
1392
1399
 
1400
+ // ../strata-starter/src/controllerActions.ts
1401
+ class ControllerActions {
1402
+ className;
1403
+ methods = new Map;
1404
+ constructor(className) {
1405
+ this.className = className;
1406
+ }
1407
+ add(name, handler) {
1408
+ if (this.methods.has(name))
1409
+ throw new Error(`Duplicate ${this.className}.${name}`);
1410
+ this.methods.set(name, handler);
1411
+ return `controller.${name}`;
1412
+ }
1413
+ render(construction = "", scope = []) {
1414
+ const methods = [...this.methods].map(([name, handler]) => {
1415
+ const arrow = handler.indexOf("=>");
1416
+ if (arrow < 0)
1417
+ throw new Error(`Missing arrow for ${this.className}.${name}`);
1418
+ const signature = handler.slice(0, arrow).trim();
1419
+ const body = handler.slice(arrow + 2).trim();
1420
+ const statements = body.startsWith("{") ? body.slice(1, -1) : `return ${body};`;
1421
+ const lines = statements.replace(/^\n/, "").replace(/\s+$/, "").split(`
1422
+ `);
1423
+ const indentation = Math.min(...lines.filter((line) => line.trim()).map((line) => line.match(/^\s*/)?.[0].length ?? 0));
1424
+ const formatted = lines.map((line) => line.trim() ? ` ${line.slice(indentation)}` : "").join(`
1425
+ `);
1426
+ return ` ${name}: BusinessRouteHandler = ${signature} => {${scope.length ? `
1427
+ const { ${scope.join(", ")} } = this;` : ""}
1428
+ ${formatted}
1429
+ };`;
1430
+ });
1431
+ return `export class ${this.className} {
1432
+ ${construction}
1433
+ ${methods.join(`
1434
+
1435
+ `)}
1436
+ }
1437
+ `;
1438
+ }
1439
+ }
1440
+ function renderAction(actions, name, handler) {
1441
+ return actions ? actions.add(name, handler) : handler;
1442
+ }
1443
+
1393
1444
  // ../strata-starter/src/auth/renderBrowserRoutes.ts
1394
- function renderMfaChallengeRoutes() {
1445
+ function renderMfaChallengeRoutes(actions) {
1395
1446
  return ` "/login/mfa": {
1396
- GET: kernel.wrapWebGuest(kernel.wrapIdentity(async (request, _ports) => {
1447
+ GET: kernel.wrapWebGuest(kernel.wrapIdentity(${renderAction(actions, "showMfaChallenge", `async (request, _ports) => {
1397
1448
  const pending = authServices.pendingMfa.read(request);
1398
1449
  const record = pending ? await authServices.directory(_ports).findByIdOrThrow(pending.userId).catch(() => null) : null;
1399
1450
  if (!record?.is_active || record.auth_version !== pending?.authVersion) return redirectTo("/login");
1400
1451
  return views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: {}, code: "" }, { request });
1401
- })),
1452
+ }`)})),
1402
1453
  POST: wrapWebLogin(
1403
1454
  kernel,
1404
- kernel.wrapIdentity(async (request, _ports) => {
1455
+ kernel.wrapIdentity(${renderAction(actions, "completeMfaChallenge", `async (request, _ports) => {
1405
1456
  const pending = authServices.pendingMfa.read(request);
1406
1457
  if (!pending) {
1407
1458
  return redirectTo("/login");
@@ -1423,18 +1474,14 @@ function renderMfaChallengeRoutes() {
1423
1474
  signed.headers.append("set-cookie", authServices.pendingMfa.clearCookie());
1424
1475
  return signed;
1425
1476
  });
1426
- }),
1427
- async (request) =>
1428
- views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: { code: "Too many login attempts. Try again shortly." }, code: "" }, { request, status: 429 }),
1477
+ }`)}),
1478
+ ${renderAction(actions, "mfaChallengeThrottled", `async (request) =>
1479
+ views.render("mfa-challenge.eta", { layout: { title: "MFA" }, errors: { code: "Too many login attempts. Try again shortly." }, code: "" }, { request, status: 429 })`)},
1429
1480
  ),
1430
1481
  },
1431
1482
  `;
1432
1483
  }
1433
- function renderBrowserAuthRoutes({
1434
- cookie,
1435
- mfa,
1436
- verify
1437
- }) {
1484
+ function renderBrowserAuthRoutes({ cookie, mfa, verify }, actions) {
1438
1485
  const mfaLoginBranch = `if (!mfaResult.ok) {
1439
1486
  ${mfa ? `if (mfaResult.error === "mfa_required") {
1440
1487
  const pending = redirectTo("/login/mfa");
@@ -1452,17 +1499,21 @@ function renderBrowserAuthRoutes({
1452
1499
  { level: "success", message: "If that email is available, continue from the sign-in page." }, authServices.flash,
1453
1500
  );`;
1454
1501
  const cookieRoutes = cookie ? `
1455
- webRoutes({ kernel, dependencies }) {
1502
+ ${actions ? `export function authWebRoutes(context: ModuleRouteContext): AppRouteMap {
1503
+ const { kernel, dependencies } = context;
1456
1504
  const authServices = dependencies.container.resolve(STARTER_AUTH_SERVICES);
1457
1505
  const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN).namespace("auth", { headers: { "Cache-Control": "private, no-store" } });
1506
+ const controller = new AuthWebController(authServices, views);` : ` webRoutes({ kernel, dependencies }) {
1507
+ const authServices = dependencies.container.resolve(STARTER_AUTH_SERVICES);
1508
+ const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN).namespace("auth", { headers: { "Cache-Control": "private, no-store" } });`}
1458
1509
  return {
1459
1510
  "/login": {
1460
- GET: kernel.wrapWebGuest(async (request) =>
1461
- views.render("login.eta", { layout: { title: "Sign in" }, errors: {}, email: "", password: "" }, { request }),
1511
+ GET: kernel.wrapWebGuest(${renderAction(actions, "showLogin", `async (request) =>
1512
+ views.render("login.eta", { layout: { title: "Sign in" }, errors: {}, email: "", password: "" }, { request })`)},
1462
1513
  ),
1463
1514
  POST: wrapWebLogin(
1464
1515
  kernel,
1465
- kernel.wrapIdentity(async (request, _ports) => {
1516
+ kernel.wrapIdentity(${renderAction(actions, "login", `async (request, _ports) => {
1466
1517
  const { fields } = await parseFormBody(request);
1467
1518
  const { email, password, mfa_code } = parseLoginCredentials(fields);
1468
1519
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
@@ -1471,21 +1522,21 @@ function renderBrowserAuthRoutes({
1471
1522
  const user = mfaResult.user;
1472
1523
  return authServices.session(_ports).signInRedirect(sessionUser(user), "/");
1473
1524
  });
1474
- }),
1475
- async (request) =>
1476
- views.render("login.eta", { layout: { title: "Sign in" }, errors: { email: "Too many login attempts. Try again shortly." }, email: "", password: "" }, { request, status: 429 }),
1525
+ }`)}),
1526
+ ${renderAction(actions, "loginThrottled", `async (request) =>
1527
+ views.render("login.eta", { layout: { title: "Sign in" }, errors: { email: "Too many login attempts. Try again shortly." }, email: "", password: "" }, { request, status: 429 })`)},
1477
1528
  ),
1478
1529
  },
1479
1530
  "/register": {
1480
- GET: kernel.wrapWebGuest(async (request, _ports) => {
1531
+ GET: kernel.wrapWebGuest(${renderAction(actions, "showRegistration", `async (request, _ports) => {
1481
1532
  if (!authServices.config.registrationEnabled) {
1482
1533
  return new Response("Not found", { status: 404 });
1483
1534
  }
1484
1535
  return views.render("register.eta", { layout: { title: "Create account" }, errors: {}, name: "", email: "", password: "" }, { request });
1485
- }),
1536
+ }`)}),
1486
1537
  POST: wrapWebRegister(
1487
1538
  kernel,
1488
- kernel.wrapIdentity(async (request, _ports) => {
1539
+ kernel.wrapIdentity(${renderAction(actions, "register", `async (request, _ports) => {
1489
1540
  if (!authServices.config.registrationEnabled) {
1490
1541
  return new Response("Not found", { status: 404 });
1491
1542
  }
@@ -1501,16 +1552,16 @@ function renderBrowserAuthRoutes({
1501
1552
  ${verify ? `// SMTP follows the outermost commit, including request RLS.
1502
1553
  if (verificationMail) await deferAuthEffect(_ports, () => authServices.mail.send(verificationMail));` : ""}
1503
1554
  ${verifyRegisterBranch}
1504
- }),
1505
- async (request) =>
1506
- views.render("register.eta", { layout: { title: "Create account" }, errors: { form: "Too many registration attempts. Try again shortly." }, name: "", email: "", password: "" }, { request, status: 429 }),
1555
+ }`)}),
1556
+ ${renderAction(actions, "registrationThrottled", `async (request) =>
1557
+ views.render("register.eta", { layout: { title: "Create account" }, errors: { form: "Too many registration attempts. Try again shortly." }, name: "", email: "", password: "" }, { request, status: 429 })`)},
1507
1558
  ),
1508
1559
  },
1509
1560
  "/forgot-password": {
1510
- GET: kernel.wrapWebGuest(async (request) =>
1511
- views.render("forgot-password.eta", { layout: { title: "Forgot password" }, errors: {}, email: "" }, { request }),
1561
+ GET: kernel.wrapWebGuest(${renderAction(actions, "showForgotPassword", `async (request) =>
1562
+ views.render("forgot-password.eta", { layout: { title: "Forgot password" }, errors: {}, email: "" }, { request })`)},
1512
1563
  ),
1513
- POST: kernel.wrapWeb(kernel.wrapIdentity(async (request, _ports) => {
1564
+ POST: kernel.wrapWeb(kernel.wrapIdentity(${renderAction(actions, "forgotPassword", `async (request, _ports) => {
1514
1565
  const { fields } = await parseFormBody(request);
1515
1566
  const email = parseForgotPasswordEmail(fields);
1516
1567
  const user = await authServices.directory(_ports).findByEmail?.(email);
@@ -1521,14 +1572,14 @@ function renderBrowserAuthRoutes({
1521
1572
  level: "success",
1522
1573
  message: "If that account exists, a reset link is on its way.",
1523
1574
  }, authServices.flash);
1524
- })),
1575
+ }`)})),
1525
1576
  },
1526
1577
  "/reset-password": {
1527
- GET: kernel.wrapWeb(kernel.wrapSigned(async (request, _ports) => {
1578
+ GET: kernel.wrapWeb(kernel.wrapSigned(${renderAction(actions, "showResetPassword", `async (request, _ports) => {
1528
1579
  const email = new URL(request.url).searchParams.get("email") ?? "";
1529
1580
  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 });
1530
- })),
1531
- POST: kernel.wrapWeb(kernel.wrapSigned(kernel.wrapIdentity(async (request, _ports) => {
1581
+ }`)})),
1582
+ POST: kernel.wrapWeb(kernel.wrapSigned(kernel.wrapIdentity(${renderAction(actions, "resetPassword", `async (request, _ports) => {
1532
1583
  const { fields } = await parseFormBody(request);
1533
1584
  const email = new URL(request.url).searchParams.get("email") ?? fields.email ?? "";
1534
1585
  const password = fields.password ?? "";
@@ -1536,13 +1587,13 @@ function renderBrowserAuthRoutes({
1536
1587
  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 });
1537
1588
  }
1538
1589
  return flashResponse(redirectTo("/login"), { level: "success", message: "Password updated. Sign in." }, authServices.flash);
1539
- }))),
1590
+ }`)}))),
1540
1591
  },
1541
1592
  "/logout": {
1542
- POST: kernel.wrapWebAuthenticatedAllowUnverified(kernel.wrapIdentity(async (request, _ports) => { return authServices.session(_ports).signOutRedirect(request, "/"); })),
1593
+ POST: kernel.wrapWebAuthenticatedAllowUnverified(kernel.wrapIdentity(${renderAction(actions, "logout", `async (request, _ports) => { return authServices.session(_ports).signOutRedirect(request, "/"); }`)})),
1543
1594
  },${verify ? `
1544
1595
  "/email/verify": {
1545
- GET: kernel.wrapWeb(kernel.wrapIdentity(async (request, _ports) => {
1596
+ GET: kernel.wrapWeb(kernel.wrapIdentity(${renderAction(actions, "verifyEmail", `async (request, _ports) => {
1546
1597
  const url = new URL(request.url);
1547
1598
  if (url.searchParams.get("signature")) {
1548
1599
  assertValidSignature(request, authServices.config.signatureSecret);
@@ -1558,23 +1609,23 @@ function renderBrowserAuthRoutes({
1558
1609
  );
1559
1610
  }
1560
1611
  return views.render("verify-email.eta", { layout: { title: "Verify email" } }, { request });
1561
- })),
1612
+ }`)})),
1562
1613
  },
1563
1614
  "/email/verification-notification": {
1564
- POST: kernel.wrapWebAuthenticatedAllowUnverified(kernel.wrapIdentity(async (request, _ports) => {
1615
+ POST: kernel.wrapWebAuthenticatedAllowUnverified(kernel.wrapIdentity(${renderAction(actions, "sendVerification", `async (request, _ports) => {
1565
1616
  const user = await _ports.auth.user(request);
1566
1617
  if (user) {
1567
1618
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1568
1619
  await issueSignedAuthMail(_ports, authServices, record.email ?? "", "Verify your email", "/email/verify", AUTH_ONE_TIME_PURPOSES.emailVerify, Number(record.id), { id: String(record.id) });
1569
1620
  }
1570
1621
  return flashResponse(redirectTo("/email/verify"), { level: "info", message: "Verification link sent." }, authServices.flash);
1571
- })),
1622
+ }`)})),
1572
1623
  },` : ""}${mfa ? `
1573
- ${renderMfaChallengeRoutes()} "/confirm-password": {
1574
- GET: kernel.wrapWebAuthenticated(async (request) =>
1575
- views.render("confirm-password.eta", { layout: { title: "Confirm password" }, errors: {}, password: "" }, { request }),
1624
+ ${renderMfaChallengeRoutes(actions)} "/confirm-password": {
1625
+ GET: kernel.wrapWebAuthenticated(${renderAction(actions, "showPasswordConfirmation", `async (request) =>
1626
+ views.render("confirm-password.eta", { layout: { title: "Confirm password" }, errors: {}, password: "" }, { request })`)},
1576
1627
  ),
1577
- POST: kernel.wrapWebAuthenticated(kernel.wrapIdentity(async (request, _ports) => {
1628
+ POST: kernel.wrapWebAuthenticated(kernel.wrapIdentity(${renderAction(actions, "confirmPassword", `async (request, _ports) => {
1578
1629
  const user = await _ports.auth.user(request);
1579
1630
  if (!user) {
1580
1631
  return redirectTo("/login");
@@ -1591,10 +1642,10 @@ ${renderMfaChallengeRoutes()} "/confirm-password": {
1591
1642
  confirmed.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id), record.auth_version, authServices.config.passwordConfirmation));
1592
1643
  return confirmed;
1593
1644
  });
1594
- })),
1645
+ }`)})),
1595
1646
  },
1596
1647
  "/account/mfa": {
1597
- GET: kernel.wrapWebAuthenticated(kernel.wrapIdentity(async (request, _ports) => {
1648
+ GET: kernel.wrapWebAuthenticated(kernel.wrapIdentity(${renderAction(actions, "showMfaSetup", `async (request, _ports) => {
1598
1649
  const secret = generateTotpSecret();
1599
1650
  const user = await _ports.auth.user(request);
1600
1651
  const record = user ? await authServices.directory(_ports).findByIdOrThrow(Number(user.id)) : null;
@@ -1604,8 +1655,8 @@ ${renderMfaChallengeRoutes()} "/confirm-password": {
1604
1655
  issuer: authServices.config.appName,
1605
1656
  });
1606
1657
  return views.render("mfa-setup.eta", { layout: { title: "MFA" }, errors: {}, code: "", secret, otpauth }, { request });
1607
- })),
1608
- POST: kernel.wrapWebPasswordConfirm(kernel.wrapIdentity(async (request, _ports) => {
1658
+ }`)})),
1659
+ POST: kernel.wrapWebPasswordConfirm(kernel.wrapIdentity(${renderAction(actions, "enrollMfa", `async (request, _ports) => {
1609
1660
  const user = await _ports.auth.user(request);
1610
1661
  if (!user) {
1611
1662
  return redirectTo("/login");
@@ -1631,10 +1682,10 @@ ${renderMfaChallengeRoutes()} "/confirm-password": {
1631
1682
  otpauth: buildOtpauthUrl({ secret, account: "user", issuer: authServices.config.appName }),
1632
1683
  recoveryCodes,
1633
1684
  }, { request });
1634
- })),
1685
+ }`)})),
1635
1686
  },` : ""}
1636
1687
  };
1637
- },` : "";
1688
+ }${actions ? "" : ","}` : "";
1638
1689
  return cookieRoutes;
1639
1690
  }
1640
1691
 
@@ -1649,15 +1700,15 @@ function renderApiAuthRoutes({
1649
1700
  bearerApi,
1650
1701
  jsonCookieAccounts,
1651
1702
  jsonAccounts
1652
- }) {
1703
+ }, actions) {
1653
1704
  const browserMfa = plan.decisions.mfaViews;
1654
1705
  const mfaContinuation = browserMfa ? `
1655
1706
  ...kernel.wrapRouteMap({
1656
- ${renderMfaChallengeRoutes()}
1707
+ ${renderMfaChallengeRoutes(actions)}
1657
1708
  }, kernel.group("api")),` : "";
1658
1709
  const tokenLogin = plan.decisions.token ? `
1659
1710
  "/api/v1/auth/login": {
1660
- POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(async (request, _ports) => {
1711
+ POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(${renderAction(actions, "loginWithToken", `async (request, _ports) => {
1661
1712
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1662
1713
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
1663
1714
  const mfaResult = await authenticatePasswordUser(_ports, authServices, candidate, password, mfa_code);
@@ -1690,10 +1741,10 @@ ${renderMfaChallengeRoutes()}
1690
1741
  payload.headers.append("set-cookie", setCookie);
1691
1742
  ` : ""}return payload;
1692
1743
  });
1693
- }))),
1744
+ }`)}))),
1694
1745
  },
1695
1746
  "/api/v1/auth/me": {
1696
- GET: kernel.wrapApi(kernel.wrapIdentity(async (request, _ports) => {
1747
+ GET: kernel.wrapApi(kernel.wrapIdentity(${renderAction(actions, "showTokenUser", `async (request, _ports) => {
1697
1748
  const user = await _ports.auth.requireUser(request);
1698
1749
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1699
1750
  return privateJsonResponse({
@@ -1702,11 +1753,11 @@ ${renderMfaChallengeRoutes()}
1702
1753
  email: record.email,
1703
1754
  role: record.role,
1704
1755
  });
1705
- })),
1756
+ }`)})),
1706
1757
  },` : "";
1707
1758
  const jsonRegister = jsonAccounts ? `
1708
1759
  "/api/v1/auth/register": {
1709
- POST: kernel.wrap("api", kernel.wrapRegister(kernel.wrapIdentity(async (request, _ports) => {
1760
+ POST: kernel.wrap("api", kernel.wrapRegister(kernel.wrapIdentity(${renderAction(actions, "register", `async (request, _ports) => {
1710
1761
  if (!authServices.config.registrationEnabled) {
1711
1762
  return privateJsonResponse({ error: "Not found" }, { status: 404 });
1712
1763
  }
@@ -1721,11 +1772,11 @@ ${renderMfaChallengeRoutes()}
1721
1772
  ${verify ? `// SMTP follows the outermost commit, including request RLS.
1722
1773
  if (verificationMail) await deferAuthEffect(_ports, () => authServices.mail.send(verificationMail));` : ""}
1723
1774
  return privateJsonResponse({ ok: true }, { status: 201 });
1724
- }))),
1775
+ }`)}))),
1725
1776
  },` : "";
1726
1777
  const jwtLogin = plan.decisions.jwt ? `
1727
1778
  "/api/auth/token": {
1728
- POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(async (request, _ports) => {
1779
+ POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(${renderAction(actions, "loginWithJwt", `async (request, _ports) => {
1729
1780
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1730
1781
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
1731
1782
  const mfaResult = await authenticatePasswordUser(_ports, authServices, candidate, password, mfa_code);
@@ -1750,67 +1801,67 @@ ${renderMfaChallengeRoutes()}
1750
1801
  expires_in: authServices.config.jwtTtlSeconds,
1751
1802
  });
1752
1803
  });
1753
- }))),
1804
+ }`)}))),
1754
1805
  },` : "";
1755
1806
  const apiUser = bearerApi ? `
1756
1807
  "/api/user": {
1757
- GET: kernel.wrapApi(async (request, _ports) => {
1808
+ GET: kernel.wrapApi(${renderAction(actions, "showUser", `async (request, _ports) => {
1758
1809
  const user = await _ports.auth.requireUser(request);
1759
1810
  return privateJsonResponse({ id: user.id, role: user.role ?? "member" });
1760
- }),
1811
+ }`)}),
1761
1812
  },
1762
1813
  "/api/v1/auth/logout": {
1763
- POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}async (request, _ports) => {
1814
+ POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}${renderAction(actions, "logoutBearer", `async (request, _ports) => {
1764
1815
  const payload = privateJsonResponse({ ok: true });
1765
1816
  ${cookie ? `const sessionAuth = authServices.session(_ports);
1766
1817
  const { setCookie } = await sessionAuth.signOut(request);
1767
1818
  payload.headers.append("set-cookie", setCookie);
1768
1819
  ` : ""}return payload;
1769
- }${cookie ? ")" : ""}),
1820
+ }`)}${cookie ? ")" : ""}),
1770
1821
  },` : "";
1771
1822
  const jsonPassword = jsonAccounts ? `
1772
1823
  "/api/v1/auth/forgot-password": {
1773
- POST: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1824
+ POST: kernel.wrap("api", kernel.wrapIdentity(${renderAction(actions, "forgotPassword", `async (request, _ports) => {
1774
1825
  const email = await parseJsonBody(request, parseForgotPasswordEmail);
1775
1826
  const user = await authServices.directory(_ports).findByEmail?.(email);
1776
1827
  if (user) {
1777
1828
  await issueSignedAuthMail(_ports, authServices, email, "Reset your password", "/api/v1/auth/reset-password", AUTH_ONE_TIME_PURPOSES.passwordReset, user.id, { email });
1778
1829
  }
1779
1830
  return privateJsonResponse({ ok: true });
1780
- })),
1831
+ }`)})),
1781
1832
  },
1782
1833
  "/api/v1/auth/reset-password": {
1783
- POST: kernel.wrap("api", kernel.wrapSigned(kernel.wrapIdentity(async (request, _ports) => {
1834
+ POST: kernel.wrap("api", kernel.wrapSigned(kernel.wrapIdentity(${renderAction(actions, "resetPassword", `async (request, _ports) => {
1784
1835
  const body = await parseJsonBody(request, (payload) => payload);
1785
1836
  const password = typeof body === "object" && body !== null && "password" in body ? body.password : undefined;
1786
1837
  if (!(await completeSignedPasswordReset(_ports, request, password))) {
1787
1838
  return privateJsonResponse({ error: "Invalid or expired reset link." }, { status: 403 });
1788
1839
  }
1789
1840
  return privateJsonResponse({ ok: true });
1790
- }))),
1841
+ }`)}))),
1791
1842
  },` : "";
1792
1843
  const jsonVerify = plan.decisions.jsonVerification ? `
1793
1844
  "/api/v1/auth/verify-email": {
1794
- POST: kernel.wrap("api", kernel.wrapSigned(kernel.wrapIdentity(async (request, _ports) => {
1845
+ POST: kernel.wrap("api", kernel.wrapSigned(kernel.wrapIdentity(${renderAction(actions, "verifyEmail", `async (request, _ports) => {
1795
1846
  if (!(await completeSignedEmailVerification(_ports, request))) {
1796
1847
  return privateJsonResponse({ error: "Invalid or expired verification link." }, { status: 403 });
1797
1848
  }
1798
1849
  return privateJsonResponse({ ok: true });
1799
- }))),
1850
+ }`)}))),
1800
1851
  },` : "";
1801
1852
  const jsonAccountManagement = jsonCookieAccounts ? `
1802
1853
  ${verify ? `"/api/v1/auth/verification-notification": {
1803
- POST: kernel.wrapApi(kernel.wrapIdentity(async (request, _ports) => {
1854
+ POST: kernel.wrapApi(kernel.wrapIdentity(${renderAction(actions, "sendVerification", `async (request, _ports) => {
1804
1855
  const user = await _ports.auth.requireUser(request);
1805
1856
  await runWithLockedAccount(_ports, Number(user.id), async (record, _ports) => {
1806
1857
  if (!record?.is_active || record.auth_version !== user.authVersion) throw new ConflictError("Account changed. Sign in again.");
1807
1858
  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) });
1808
1859
  });
1809
1860
  return privateJsonResponse({ ok: true });
1810
- })),
1861
+ }`)})),
1811
1862
  },` : ""}
1812
1863
  ${mfa ? `"/api/v1/auth/confirm-password": {
1813
- POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapIdentity(async (request, _ports) => {
1864
+ POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapIdentity(${renderAction(actions, "confirmPassword", `async (request, _ports) => {
1814
1865
  const user = await _ports.auth.requireUser(request);
1815
1866
  const { password } = await parseJsonBody(request, (payload) => validateObject(payload, { password: [required(), stringRule()] }));
1816
1867
  return runWithLockedAccount(_ports, Number(user.id), async (record, _ports) => {
@@ -1820,33 +1871,33 @@ ${renderMfaChallengeRoutes()}
1820
1871
  response.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id), record.auth_version, authServices.config.passwordConfirmation));
1821
1872
  return response;
1822
1873
  });
1823
- }))),
1874
+ }`)}))),
1824
1875
  },
1825
1876
  "/api/v1/auth/mfa": {
1826
- GET: kernel.wrap("api", kernel.wrapVerified(kernel.wrapIdentity(async (request, _ports) => {
1877
+ GET: kernel.wrap("api", kernel.wrapVerified(kernel.wrapIdentity(${renderAction(actions, "showMfaSetup", `async (request, _ports) => {
1827
1878
  const user = await _ports.auth.requireUser(request);
1828
1879
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1829
1880
  const secret = generateTotpSecret();
1830
1881
  return privateJsonResponse({ secret, otpauth: buildOtpauthUrl({ secret, account: record.email ?? "user", issuer: authServices.config.appName }) });
1831
- }))),
1832
- POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapPasswordConfirm(kernel.wrapIdentity(async (request, _ports) => {
1882
+ }`)}))),
1883
+ POST: kernel.wrap("api", kernel.wrapVerified(kernel.wrapPasswordConfirm(kernel.wrapIdentity(${renderAction(actions, "enrollMfa", `async (request, _ports) => {
1833
1884
  const user = await _ports.auth.requireUser(request);
1834
1885
  const fields = await parseJsonBody(request, (payload) => validateObject(payload, { secret: [required(), stringRule()], code: [required(), stringRule()] }));
1835
1886
  const secret = String(fields.secret).trim();
1836
1887
  if (!verifyTotp(secret, String(fields.code).trim())) return privateJsonResponse({ error: "Could not confirm that code." }, { status: 422 });
1837
1888
  const recoveryCodes = await enrollMfa(_ports, authServices, user, secret);
1838
1889
  return privateJsonResponse({ recoveryCodes });
1839
- })))),
1890
+ }`)})))),
1840
1891
  },` : ""}` : "";
1841
1892
  const csrfRoute = `
1842
1893
  "/api/v1/auth/csrf": {
1843
- GET: kernel.wrap("api", async (request, _ports) => {
1894
+ GET: kernel.wrap("api", ${renderAction(actions, "csrf", `async (request, _ports) => {
1844
1895
  return privateJsonResponse({ token: resolveCsrfTokenForRequest(request, authServices.csrf) });
1845
- }),
1896
+ }`)}),
1846
1897
  },`;
1847
1898
  const cookieJsonAuth = plan.decisions.cookieJsonLogin ? `
1848
1899
  "/api/v1/auth/login": {
1849
- POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(async (request, _ports) => {
1900
+ POST: kernel.wrap("api", kernel.wrapLogin(kernel.wrapIdentity(${renderAction(actions, "loginWithCookie", `async (request, _ports) => {
1850
1901
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
1851
1902
  return runWithLoginUser(_ports, email, async (candidate, _ports) => {
1852
1903
  const mfaResult = await authenticatePasswordUser(_ports, authServices, candidate, password, mfa_code);
@@ -1863,10 +1914,10 @@ ${renderMfaChallengeRoutes()}
1863
1914
  payload.headers.append("set-cookie", setCookie);
1864
1915
  return payload;
1865
1916
  });
1866
- }))),
1917
+ }`)}))),
1867
1918
  },
1868
1919
  "/api/v1/auth/me": {
1869
- GET: kernel.wrapApi(kernel.wrapIdentity(async (request, _ports) => {
1920
+ GET: kernel.wrapApi(kernel.wrapIdentity(${renderAction(actions, "showCookieUser", `async (request, _ports) => {
1870
1921
  const user = await _ports.auth.requireUser(request);
1871
1922
  const record = await authServices.directory(_ports).findByIdOrThrow(Number(user.id));
1872
1923
  return privateJsonResponse({
@@ -1875,30 +1926,30 @@ ${renderMfaChallengeRoutes()}
1875
1926
  email: record.email,
1876
1927
  role: record.role,
1877
1928
  });
1878
- })),
1929
+ }`)})),
1879
1930
  },
1880
1931
  "/api/v1/auth/logout": {
1881
- POST: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1932
+ POST: kernel.wrap("api", kernel.wrapIdentity(${renderAction(actions, "logoutCookie", `async (request, _ports) => {
1882
1933
  const sessionAuth = authServices.session(_ports);
1883
1934
  const { setCookie } = await sessionAuth.signOut(request);
1884
1935
  const payload = privateJsonResponse({ ok: true });
1885
1936
  payload.headers.append("set-cookie", setCookie);
1886
1937
  return payload;
1887
- })),
1938
+ }`)})),
1888
1939
  },` : "";
1889
1940
  const samlRoutes = cookie ? `
1890
1941
  "/auth/saml": {
1891
- GET: kernel.wrap("api", async (_request, _ports) => {
1942
+ GET: kernel.wrap("api", ${renderAction(actions, "startSaml", `async (_request, _ports) => {
1892
1943
  if (!authServices.config.samlEnabled) {
1893
1944
  return new Response("Not found", { status: 404 });
1894
1945
  }
1895
1946
  const issued = createSamlStateCookie(authServices.config.oauth);
1896
1947
  const url = await authServices.saml(_ports).authorizationUrl(issued.state);
1897
1948
  return new Response(null, { status: 302, headers: { location: url, "set-cookie": issued.cookie } });
1898
- }),
1949
+ }`)}),
1899
1950
  },
1900
1951
  "/auth/saml/acs": {
1901
- POST: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1952
+ POST: kernel.wrap("api", kernel.wrapIdentity(${renderAction(actions, "completeSaml", `async (request, _ports) => {
1902
1953
  if (!authServices.config.samlEnabled) {
1903
1954
  return new Response("Not found", { status: 404 });
1904
1955
  }
@@ -1921,11 +1972,11 @@ ${renderMfaChallengeRoutes()}
1921
1972
  const login = await completeBrowserSsoLogin(_ports, authServices, profile, "SAML");
1922
1973
  login.headers.append("set-cookie", clearSamlStateCookie());
1923
1974
  return login;
1924
- })),
1975
+ }`)})),
1925
1976
  },` : "";
1926
1977
  const githubRoutes = github ? `
1927
1978
  "/auth/github": {
1928
- GET: kernel.wrap("api", async (_request, _ports) => {
1979
+ GET: kernel.wrap("api", ${renderAction(actions, "startGitHub", `async (_request, _ports) => {
1929
1980
  if (!authServices.config.oauthEnabled) {
1930
1981
  return new Response("Not found", { status: 404 });
1931
1982
  }
@@ -1938,10 +1989,10 @@ ${renderMfaChallengeRoutes()}
1938
1989
  const issued = createOAuthStateCookie(authServices.config.oauth);
1939
1990
  const url = new GitHubOAuthProvider({ clientId, clientSecret, redirectUri, production: authServices.config.github.production, userAgent: authServices.config.github.userAgent }).getAuthorizationUrl(issued.state);
1940
1991
  return new Response(null, { status: 302, headers: { location: url, "set-cookie": issued.cookie } });
1941
- }),
1992
+ }`)}),
1942
1993
  },
1943
1994
  "/auth/github/callback": {
1944
- GET: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
1995
+ GET: kernel.wrap("api", kernel.wrapIdentity(${renderAction(actions, "completeGitHub", `async (request, _ports) => {
1945
1996
  if (!authServices.config.oauthEnabled) {
1946
1997
  return new Response("Not found", { status: 404 });
1947
1998
  }
@@ -1970,11 +2021,11 @@ ${renderMfaChallengeRoutes()}
1970
2021
  const login = await completeBrowserSsoLogin(_ports, authServices, profile, "GitHub");
1971
2022
  login.headers.append("set-cookie", clearOAuthStateCookie(authServices.config.oauth));
1972
2023
  return login;
1973
- })),
2024
+ }`)})),
1974
2025
  },` : "";
1975
2026
  const oidcRoutes = oidc ? `
1976
2027
  "/auth/oidc": {
1977
- GET: kernel.wrap("api", async (_request, _ports) => {
2028
+ GET: kernel.wrap("api", ${renderAction(actions, "startOidc", `async (_request, _ports) => {
1978
2029
  if (!authServices.config.oauthEnabled) {
1979
2030
  return new Response("Not found", { status: 404 });
1980
2031
  }
@@ -1994,10 +2045,10 @@ ${renderMfaChallengeRoutes()}
1994
2045
  sealOidcPkceCookie({ state: issued.state, nonce: handshake.nonce, codeVerifier: handshake.codeVerifier }, authServices.config.oauth),
1995
2046
  );
1996
2047
  return redirect;
1997
- }),
2048
+ }`)}),
1998
2049
  },
1999
2050
  "/auth/oidc/callback": {
2000
- GET: kernel.wrap("api", kernel.wrapIdentity(async (request, _ports) => {
2051
+ GET: kernel.wrap("api", kernel.wrapIdentity(${renderAction(actions, "completeOidc", `async (request, _ports) => {
2001
2052
  if (!authServices.config.oauthEnabled) {
2002
2053
  return new Response("Not found", { status: 404 });
2003
2054
  }
@@ -2028,16 +2079,20 @@ ${renderMfaChallengeRoutes()}
2028
2079
  const login = await completeBrowserSsoLogin(_ports, authServices, profile, "OIDC");
2029
2080
  login.headers.append("set-cookie", clearOidcPkceCookie(authServices.config.oauth));
2030
2081
  return login;
2031
- })),
2082
+ }`)})),
2032
2083
  },` : "";
2033
2084
  const apiRoutes = plan.decisions.users ? `
2034
- routes({ kernel, dependencies }) {
2085
+ ${actions ? `export function authApiRoutes(context: ModuleRouteContext): AppRouteMap {
2086
+ const { kernel, dependencies } = context;
2035
2087
  const authServices = dependencies.container.resolve(STARTER_AUTH_SERVICES);${browserMfa ? `
2088
+ const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN).namespace("auth", { headers: { "Cache-Control": "private, no-store" } });` : ""}
2089
+ const controller = new AuthController(authServices${browserMfa ? ", views" : ""});` : ` routes({ kernel, dependencies }) {
2090
+ const authServices = dependencies.container.resolve(STARTER_AUTH_SERVICES);`}${browserMfa && !actions ? `
2036
2091
  // Browser SSO requires only its continuation view, not general web routes.
2037
2092
  const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN).namespace("auth", { headers: { "Cache-Control": "private, no-store" } });` : ""}
2038
2093
  return {${mfaContinuation}${csrfRoute}${samlRoutes}${githubRoutes}${oidcRoutes}${cookieJsonAuth}${tokenLogin}${jsonRegister}${jwtLogin}${apiUser}${jsonPassword}${jsonVerify}${jsonAccountManagement}
2039
2094
  };
2040
- },` : "";
2095
+ }${actions ? "" : ","}` : "";
2041
2096
  return apiRoutes;
2042
2097
  }
2043
2098
 
@@ -2375,47 +2430,82 @@ export function createPendingMfaHelpers(options: Readonly<{secret:string;product
2375
2430
  }
2376
2431
  `;
2377
2432
  }
2378
- function renderSiteModule(_plan) {
2379
- return `import type { AppModule } from "@getstrata/bootstrap/contracts";
2380
- import { CORE_VIEW_RENDERER_TOKEN } from "@getstrata/core/view";
2381
-
2382
- const siteModule: AppModule = {
2383
- name: "site",
2384
- order: 1,
2385
- webRoutes({ kernel, dependencies }) {
2386
- const views = dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN);
2387
- return {
2388
- "/": kernel.wrapWeb(async (request) =>
2389
- views.renderHtmx("home.eta", { layout: { title: "Welcome", description: "Welcome to your Strata app. Restyle views/home.eta and public/assets/site.css." } }, { request }),
2390
- ),
2391
- };
2392
- },
2393
- };
2394
-
2395
- export default siteModule;
2396
- `;
2397
- }
2398
- function renderAuthModule(plan) {
2433
+ function renderAuthHttp(plan) {
2399
2434
  if (!plan.decisions.users)
2400
2435
  return null;
2401
2436
  const context = createAuthRenderingContext(plan);
2402
- const imports = renderAuthImports(context);
2403
- const helpers = renderAuthHelpers(context);
2404
- const apiRoutes = renderApiAuthRoutes(context);
2405
- const cookieRoutes = renderBrowserAuthRoutes(context);
2406
- return `${imports.join(`
2407
- `)}
2408
- ${helpers}
2409
-
2437
+ const imports = renderAuthImports(context).join(`
2438
+ `);
2439
+ const helperNames = [
2440
+ "runWithLockedAccount",
2441
+ "authTimestamp",
2442
+ "deferAuthEffect",
2443
+ "authenticatePasswordUser",
2444
+ "runWithLoginUser",
2445
+ "runAuthWrite",
2446
+ "issueSignedAuthMail",
2447
+ "createRegistration",
2448
+ "completeSignedPasswordReset",
2449
+ "persistAuthRecovery",
2450
+ ...context.verify ? ["completeSignedEmailVerification"] : [],
2451
+ ...context.cookie ? ["redirectTo", "sessionUser", "completeBrowserSsoLogin"] : [],
2452
+ ...context.mfa ? ["enrollMfa"] : []
2453
+ ];
2454
+ const helpers = `${imports}
2455
+ ${renderAuthHelpers(context)}
2410
2456
  ${renderMfaEnrollment(context.mfa)}
2457
+ export { ${helperNames.join(", ")} };
2458
+ `;
2459
+ const controllerDependencies = renderAuthImports(context).filter((line) => !line.includes("AppModule") && !line.includes("CORE_VIEW_RENDERER_TOKEN") && !line.includes("wrapWebLogin")).map((line) => line.includes("STARTER_AUTH_SERVICES") ? 'import type { StarterAuthServices } from "../../bootstrap/auth.ts";' : line).join(`
2460
+ `);
2461
+ const controllerImports = `${controllerDependencies}
2462
+ ${context.cookie ? `import type { NamespacedViewRenderer } from "@getstrata/core/view";
2463
+ ` : ""}
2464
+ import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
2465
+ import { ${helperNames.join(", ")} } from "../auth/account.ts";
2466
+ `;
2467
+ const apiActions = new ControllerActions("AuthController");
2468
+ const api = renderApiAuthRoutes(context, apiActions);
2469
+ const apiScope = ["authServices", ...plan.decisions.mfaViews ? ["views"] : []];
2470
+ const construction = (views) => ` constructor(private readonly authServices: StarterAuthServices${views ? ", private readonly views: NamespacedViewRenderer" : ""}) {}`;
2471
+ const files = {
2472
+ "http/auth/account.ts": helpers,
2473
+ "http/controllers/AuthController.ts": controllerImports + apiActions.render(construction(plan.decisions.mfaViews), apiScope)
2474
+ };
2475
+ const webActions = new ControllerActions("AuthWebController");
2476
+ const web = renderBrowserAuthRoutes(context, webActions);
2477
+ if (web)
2478
+ files["http/controllers/AuthWebController.ts"] = controllerImports + webActions.render(construction(true), ["authServices", "views"]);
2479
+ return {
2480
+ files,
2481
+ api: { name: "authApiRoutes", source: api },
2482
+ ...web ? { web: { name: "authWebRoutes", source: web } } : {}
2483
+ };
2484
+ }
2485
+ function renderHomeHttp() {
2486
+ return {
2487
+ files: {
2488
+ "http/controllers/HomeController.ts": `import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
2489
+ import type { ViewRenderer } from "@getstrata/core/view";
2411
2490
 
2412
- const authModule: AppModule = {
2413
- name: "auth",
2414
- order: 2,${apiRoutes}${cookieRoutes}
2415
- };
2491
+ export class HomeController {
2492
+ constructor(private readonly views: ViewRenderer) {}
2416
2493
 
2417
- export default authModule;
2418
- `;
2494
+ index: BusinessRouteHandler = async (request) =>
2495
+ this.views.renderHtmx("home.eta", { layout: { title: "Welcome", description: "Welcome to your Strata app. Restyle views/home.eta and public/assets/site.css." } }, { request });
2496
+ }
2497
+ `
2498
+ },
2499
+ web: {
2500
+ name: "homeWebRoutes",
2501
+ source: `export function homeWebRoutes(context: ModuleRouteContext): AppRouteMap {
2502
+ const views = context.dependencies.container.resolve(CORE_VIEW_RENDERER_TOKEN);
2503
+ const controller = new HomeController(views);
2504
+ return { "/": context.kernel.wrapWeb(controller.index) };
2505
+ }
2506
+ `
2507
+ }
2508
+ };
2419
2509
  }
2420
2510
  // ../strata-starter/src/renderAuthViews.ts
2421
2511
  function renderSiteCss() {
@@ -2986,7 +3076,8 @@ import config from "../config/app.ts";
2986
3076
  import paths from "../../strata.config.ts";
2987
3077
  import { databaseOptions } from "./database.ts";
2988
3078
  import { createStarterAuthServices, STARTER_AUTH_SERVICES } from "./auth.ts";
2989
- import { modelDefinitions, repositoryDefinitions } from "../models/register.ts";
3079
+ import { modelDefinitions${plan.decisions.workTracker ? ", repositoryDefinitions" : ""} } from "../models/register.ts";
3080
+ import { applicationRoutes } from "../routes/index.ts";
2990
3081
  import { Note } from "../models/Note.ts";
2991
3082
  import { migrate } from "../db/migrate.ts";
2992
3083
  import { listeners } from "../outbox/registry.ts";
@@ -3000,7 +3091,8 @@ const { bootstrapApp, createApp, createAppServer } = defineApp({
3000
3091
  database: databaseOptions,
3001
3092
  auth: { create: createStarterAuthServices, token: STARTER_AUTH_SERVICES },
3002
3093
  models: modelDefinitions,
3003
- repositories: repositoryDefinitions,
3094
+ routes: applicationRoutes,${plan.decisions.workTracker ? `
3095
+ repositories: repositoryDefinitions,` : ""}
3004
3096
  migrate,${plan.decisions.ensureDatabase ? `
3005
3097
  ensureDatabase: ensureAppDatabase,` : ""}
3006
3098
  outbox: { listeners${plan.decisions.workTracker ? ", token: WORK_TRACKER_OUTBOX" : ""} },
@@ -3363,31 +3455,30 @@ ${authNote}
3363
3455
 
3364
3456
  ## Adding a route
3365
3457
 
3366
- Create a module under \`src/modules/\` and return a route map. Modules are discovered on boot.
3458
+ Put HTTP actions in \`src/http/controllers/\` and register their paths and middleware in \`src/routes/api.ts\` or \`src/routes/web.ts\`. The bootstrap loads these route files once. Controller methods receive Bun's native \`Request\` and explicit request ports.
3367
3459
 
3368
3460
  \`\`\`typescript
3369
- // src/modules/notes/index.ts
3370
- import type { AppModule } from "@getstrata/bootstrap/contracts";
3371
- import { jsonResponse } from "@getstrata/core/http/response";
3461
+ // src/http/controllers/NoteController.ts
3462
+ import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
3372
3463
  import { Note } from "../../models/Note.ts";
3373
3464
 
3374
- const notesModule: AppModule = {
3375
- name: "notes",
3376
- order: 2,
3377
- routes({ kernel }) {
3378
- return {
3379
- "/api/v1/notes": kernel.wrap("api", async (_request, { database }) => {
3380
- const bodiesById = await database.model(Note).query().orderBy({ id: "desc" }).pluck("body", "id");
3381
- return jsonResponse({ data: Object.fromEntries(bodiesById) });
3382
- }),
3383
- };
3384
- },
3385
- };
3465
+ export class NoteController {
3466
+ index: BusinessRouteHandler = async (_request, { database }) => {
3467
+ const notes = await database.model(Note).query().orderBy({ id: "desc" }).get();
3468
+ return Response.json({ data: notes.map(note => note.toJSON()) });
3469
+ };
3470
+ }
3471
+ \`\`\`
3386
3472
 
3387
- export default notesModule;
3473
+ In \`src/routes/api.ts\`, import \`NoteController\` from \`../http/controllers/NoteController.ts\`, construct it in \`apiRoutes(context)\`, and add this map to that function's \`composeRouteMaps(...)\` arguments:
3474
+
3475
+ \`\`\`typescript
3476
+ { "/api/v1/notes": { GET: context.kernel.wrapApi(notes.index) } }
3388
3477
  \`\`\`
3389
3478
 
3390
- Use the handler\u2019s explicit \`database\` port to bind model definitions to the current application and execution. Public root and subpath imports share the same definitions and runtime classes.
3479
+ Here \`notes\` is \`const notes = new NoteController();\`. Keep existing route maps and middleware. Use the handler's \`database\` port to bind the model class to the current application and execution. Use \`src/http/requests/\` for application request validation; account credential validation and account workflows are provided by the framework.
3480
+
3481
+ Optional modules in \`src/modules/\` remain available for feature composition. They use the same kernel and execution ports.
3391
3482
 
3392
3483
  ## Docs
3393
3484
 
@@ -3409,13 +3500,13 @@ function renderIntegrationsReadme(plan) {
3409
3500
  "",
3410
3501
  "OAuth, billing, outbound webhooks, SIEM, and SAML are **off by default**. Commented placeholders live in `.env.example`. Framework map: [INTEGRATIONS.md](https://github.com/EyK-26/strata/blob/main/docs/INTEGRATIONS.md).",
3411
3502
  "",
3412
- "Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit modules, migrations, jobs, or listeners. `createApp` still calls `await discoverListeners()` and `await discoverJobs()`.",
3503
+ "Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit controllers, routes, migrations, jobs, or listeners. `createApp` still calls `await discoverListeners()` and `await discoverJobs()`.",
3413
3504
  ""
3414
3505
  ];
3415
3506
  if (enabled.length > 0) {
3416
3507
  lines.push("Enabled in this app:", "", ...enabled.map((row) => `- ${row}`), "");
3417
3508
  } else {
3418
- lines.push("This app did not pass those flags. Turn a flag on and re-run `create-strata`, or copy the commented env block and add a module yourself.", "");
3509
+ lines.push("This app did not pass those flags. Turn a flag on and re-run `create-strata`, or copy the commented env block and add the integration controller and routes yourself.", "");
3419
3510
  }
3420
3511
  return `${lines.join(`
3421
3512
  `)}
@@ -3488,6 +3579,18 @@ ${extras.length > 0 ? `| Extras | ${extras.join(", ")} |
3488
3579
  ` : ""}
3489
3580
  This file is the map for this app. Framework guides: [Building apps](https://github.com/EyK-26/strata/blob/main/docs/BUILDING-APPS.md), [Auth](https://github.com/EyK-26/strata/blob/main/docs/AUTH.md), [Starter](https://github.com/EyK-26/strata/blob/main/docs/STARTER.md), [Integrations](https://github.com/EyK-26/strata/blob/main/docs/INTEGRATIONS.md).
3490
3581
 
3582
+ ## Application files
3583
+
3584
+ - \`src/routes/web.ts\`: browser routes and middleware.
3585
+ - \`src/routes/api.ts\`: API and integration routes and middleware.
3586
+ - \`src/http/controllers/\`: named HTTP actions for the selected features.
3587
+ - \`src/http/requests/\`: application request validation when needed. Account parsers and workflows come from the framework.
3588
+ - \`src/models/\`: model classes extending \`defineModel(...)\`; register them in \`src/models/register.ts\`.
3589
+ - \`src/db/migrations/\`: explicit schema changes.
3590
+ - \`src/bootstrap/createApp.ts\`: application services and the route entry point. Optional \`src/modules/\` packages can add feature composition.
3591
+
3592
+ Start a feature with \`bunx strata make:model Task\`, \`bunx strata make:controller Task\`, and \`bunx strata make:request StoreTask\`. Register the model and route explicitly. Controller methods take Bun's native \`Request\` and execution ports; use \`database.model(Task)\` inside the action. Models declare fields, \`$fillable\`, and \`$timestamps\`; a normal model does not need a separate table, repository, or record declaration.
3593
+
3491
3594
  ${renderIntegrationsReadme(plan)}
3492
3595
  ## Run it
3493
3596
 
@@ -3987,9 +4090,9 @@ function renderPackageJson(projectName, options = {}) {
3987
4090
  "@getstrata/cli": "workspace:*",
3988
4091
  "@getstrata/core": "workspace:*"
3989
4092
  } : {
3990
- "@getstrata/bootstrap": "^3.0.7",
3991
- "@getstrata/cli": "^3.0.7",
3992
- "@getstrata/core": "^3.0.7"
4093
+ "@getstrata/bootstrap": "^3.1.0",
4094
+ "@getstrata/cli": "^3.1.0",
4095
+ "@getstrata/core": "^3.1.0"
3993
4096
  };
3994
4097
  if (!options.plan || options.plan.decisions.serverViews || options.plan.decisions.mfaViews)
3995
4098
  coreDeps.eta = "^4.6.0";
@@ -4048,89 +4151,6 @@ function renderLayersManifest(projectName, plan) {
4048
4151
  }, null, 2)}
4049
4152
  `;
4050
4153
  }
4051
- // ../strata-starter/src/renderInitialAdmin.ts
4052
- function renderInitialAdminMigration(plan) {
4053
- if (!plan.decisions.users)
4054
- return null;
4055
- const driver = plan.decisions.sqlDriver;
4056
- return `import { Schema } from "@getstrata/core/database/schema";
4057
- import { guardMigrationRollback } from "@getstrata/core/database/migrations";
4058
- import type { Migration } from "@getstrata/core/database/migrations/types";
4059
-
4060
- const migration: Migration = {
4061
- name: "0004_initial_admin_provisioning",
4062
- async up(db) {
4063
- await Schema.run(db, "${driver}", schema => {
4064
- schema.create("initial_admin_provisioning", table => {
4065
- table.integer("id").primary();
4066
- table.text("email");
4067
- table.timestamp("provisioned_at").defaultRaw("CURRENT_TIMESTAMP");
4068
- });
4069
- });
4070
- },
4071
- async down(db, context) {
4072
- await guardMigrationRollback(context, {
4073
- hasHistory: async () => (await db.unsafe("SELECT id FROM initial_admin_provisioning")).length > 0,
4074
- message: "Cannot discard a completed initial-admin provisioning claim.",
4075
- });
4076
- await Schema.run(db, "${driver}", schema => { schema.drop("initial_admin_provisioning"); });
4077
- },
4078
- };
4079
- export default migration;
4080
- `;
4081
- }
4082
- function renderInitialAdminCommand(plan) {
4083
- const layers = plan.layers;
4084
- if (!plan.decisions.users)
4085
- return null;
4086
- const tenant = plan.decisions.tenantTable;
4087
- const rls = plan.decisions.rls;
4088
- const placeholder = layers.database === "postgres" ? "$1" : "?";
4089
- const fields = ["name", "email", "password", "is_admin", ...tenant ? ["tenant_id"] : []];
4090
- const placeholders = fields.map((_, index) => layers.database === "postgres" ? `$${index + 1}` : "?");
4091
- return `import { runInitialAdminCommand } from "@getstrata/cli/initialAdmin";
4092
- import { hashPassword } from "@getstrata/core/auth/password";
4093
- import type { TransactionSession } from "@getstrata/core/database/session";
4094
- ${rls ? `import { assertRlsLiveDatabaseRole } from "@getstrata/bootstrap/secretsGuard";
4095
- ` : ""}import { bootstrapApp } from "../bootstrap/createApp.ts";
4096
-
4097
- export async function initialAdminCommand(...args: string[]): Promise<void> {
4098
- await runInitialAdminCommand(args, {
4099
- tenantRequired: ${tenant},
4100
- async provision(input) {
4101
- // Hash before acquiring the database claim; only the official auth helper owns crypto.
4102
- const passwordHash = await hashPassword(input.password);
4103
- const app = await bootstrapApp({ migrate: false, mode: "command" });
4104
- try {
4105
- await app.invoke({ kind: "command", actor: { kind: "system", policy: "cli.initial-admin" } }, async ports => {
4106
- ${rls ? ` await assertRlsLiveDatabaseRole({ ...process.env }, async () => { const rows = await ports.database.execute<{rolname:string;rolsuper:boolean;rolbypassrls:boolean}>({text:"SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user",params:[]});return rows[0] ?? null; });
4107
- ` : ""} const provision = async (db: TransactionSession) => {
4108
- // The singleton primary key serializes bootstrap commands across all tenants/processes.
4109
- await db.execute({text:"INSERT INTO initial_admin_provisioning (id, email) VALUES (1, ${placeholder})",params:[input.email]});
4110
- if ((await db.execute({text:"SELECT id FROM users WHERE is_admin = ${layers.database === "postgres" ? "TRUE" : "1"} LIMIT 1",params:[]})).length) {
4111
- throw new Error("An admin already exists.");
4112
- }
4113
- if ((await db.execute({text:"SELECT id FROM users WHERE LOWER(email) = ${placeholder}",params:[input.email]})).length) {
4114
- throw new Error("The account already exists; provisioning never promotes accounts.");
4115
- }
4116
- ${tenant ? ` if (!(await db.execute({text:"SELECT id FROM tenant WHERE id = ${placeholder}",params:[input.tenantId]})).length) {
4117
- throw new Error("The tenant does not exist.");
4118
- }
4119
- ` : ""} await db.execute({text:"INSERT INTO users (${fields.join(", ")}) VALUES (${placeholders.join(", ")})",params:[input.name, input.email, passwordHash, ${layers.database === "postgres" ? "true" : "1"}${tenant ? ", input.tenantId" : ""}]});
4120
- // Verification and MFA stay unenrolled; normal application flows remain authoritative.
4121
- };
4122
- await ${rls ? 'ports.policy.run(ports.database, {kind:"bypass"}, provision)' : "ports.database.transaction(provision)"};
4123
- });
4124
- } finally {
4125
- await app.context.dispose();
4126
- }
4127
- },
4128
- });
4129
- console.log("Initial admin provisioned. Complete email verification and MFA through the application.");
4130
- }
4131
- `;
4132
- }
4133
-
4134
4154
  // ../strata-starter/src/renderMigrations.ts
4135
4155
  function ensureImport(plan) {
4136
4156
  return plan.decisions.ensureDatabase ? `import { ensureAppDatabase } from "../bootstrap/ensureDatabase.ts";
@@ -4321,7 +4341,7 @@ function renderMigrateTs(plan) {
4321
4341
  const verifyOn = plan.decisions.emailVerification;
4322
4342
  const rlsOn = plan.decisions.rls;
4323
4343
  const imports = usersOn ? `import { hashPassword } from "@getstrata/core/auth/password";
4324
- import { User, UserRepository } from "../models/User.ts";
4344
+ import { User } from "../models/User.ts";
4325
4345
  ` : "";
4326
4346
  const tenant = plan.decisions.schemaTenants ? `
4327
4347
  const [tenant] = await selected.execute<{count:string|number}>({text:"SELECT COUNT(*) AS count FROM tenant",params:[]});
@@ -4341,7 +4361,7 @@ import { createPersistenceInvocation } from "@getstrata/bootstrap/persistenceInv
4341
4361
  import { migrateDatabase } from "@getstrata/core/database/migrations";
4342
4362
  import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
4343
4363
  import { databaseOptions, databaseEnvironment } from "../bootstrap/database.ts";
4344
- import { Note, NoteRepository } from "../models/Note.ts";
4364
+ import { Note } from "../models/Note.ts";
4345
4365
  import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
4346
4366
 
4347
4367
  /** An explicit development-only command owns its own canonical Application. */
@@ -4349,7 +4369,7 @@ export async function seed(input: Readonly<Record<string, string | undefined>> =
4349
4369
  const environment = databaseEnvironment(input);
4350
4370
  if (isProductionEnv(environment)) throw new Error("Demo seeding is disabled in production and staging.");
4351
4371
  ${ensureCall(plan)} const connection = databaseOptions(environment);
4352
- const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},repositories:[NoteRepository${usersOn ? ",UserRepository" : ""}],models:[Note${usersOn ? ",User" : ""}]})});
4372
+ const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},models:[Note${usersOn ? ",User" : ""}]})});
4353
4373
  await application.start();
4354
4374
  try {
4355
4375
  const invoke = createPersistenceInvocation(application, "main");
@@ -4696,9 +4716,9 @@ function renderNoteCreatedWebhookListener() {
4696
4716
  return `import type { ListenerDeclarations } from "@getstrata/bootstrap/discoverListeners";
4697
4717
  import { service } from "@getstrata/core/contracts/services";
4698
4718
  import { createServiceToken } from "@getstrata/core/contracts/token";
4699
- import { repositoryEffects, type AfterCommitRepositoryListener } from "@getstrata/core/database/definitions";
4719
+ import { modelEffects, type AfterCommitRepositoryListener } from "@getstrata/core/database/definitions";
4700
4720
  import { APPLICATION_QUEUE as STARTER_QUEUE_TOKEN, APPLICATION_WEBHOOKS as STARTER_WEBHOOK_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
4701
- import { NoteRepository, type NoteRecord } from "../models/Note.ts";
4721
+ import { Note, type NoteRecord } from "../models/Note.ts";
4702
4722
  import DispatchOutboundWebhookJob from "../jobs/dispatchOutboundWebhookJob.ts";
4703
4723
 
4704
4724
  const noteCreated = createServiceToken<AfterCommitRepositoryListener<NoteRecord>>("starter.webhooks.note-created");
@@ -4731,7 +4751,7 @@ const declarations: ListenerDeclarations = Object.freeze({
4731
4751
  }
4732
4752
  },
4733
4753
  })]),
4734
- repositoryEffects: Object.freeze([repositoryEffects(NoteRepository, [
4754
+ repositoryEffects: Object.freeze([modelEffects(Note, [
4735
4755
  {action: "created", afterCommit: noteCreated},
4736
4756
  ])]),
4737
4757
  });
@@ -4761,7 +4781,7 @@ export type { StripeWebhookEvent };
4761
4781
  export { applyStripeWebhook };
4762
4782
  `;
4763
4783
  }
4764
- function renderBillingModule(plan) {
4784
+ function renderBillingParts(plan, actions) {
4765
4785
  const layers = plan.layers;
4766
4786
  const tenancyOn = plan.decisions.tenantTable;
4767
4787
  const tenantPlaceholder = layers.database === "postgres" ? "$1" : "?";
@@ -4776,20 +4796,24 @@ function renderBillingModule(plan) {
4776
4796
  text: "SELECT plan, status, stripe_subscription_id, current_period_end FROM subscription LIMIT 1",
4777
4797
  params: [],
4778
4798
  });`;
4779
- return `import type { AppModule } from "@getstrata/bootstrap/contracts";
4799
+ const support = `import type { AppModule, ModuleRouteContext } from "@getstrata/bootstrap/contracts";
4780
4800
  import { jsonResponse } from "@getstrata/core/http/response";
4781
4801
  import { verifyStripeWebhookSignature } from "@getstrata/core/security/stripeWebhook";
4782
4802
  import { applyStripeWebhook } from "../../billing/applyStripeWebhook.ts";
4783
4803
  import { APPLICATION_BILLING as STARTER_BILLING_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
4784
4804
 
4785
- const billingModule: AppModule = {
4805
+ `;
4806
+ const routes = `${actions ? `export function billingApiRoutes(context: ModuleRouteContext): AppRouteMap {
4807
+ const { kernel, dependencies } = context;
4808
+ const { enabled, stripeSecret } = dependencies.container.get(STARTER_BILLING_OPTIONS_TOKEN);
4809
+ const controller = new BillingController(enabled, stripeSecret);` : `const billingModule: AppModule = {
4786
4810
  name: "billing",
4787
4811
  order: 40,
4788
4812
  routes({ kernel, dependencies }) {
4789
- const {enabled:billingEnabled,stripeSecret:secret} = dependencies.container.get(STARTER_BILLING_OPTIONS_TOKEN);
4813
+ const {enabled:billingEnabled,stripeSecret:secret} = dependencies.container.get(STARTER_BILLING_OPTIONS_TOKEN);`}
4790
4814
  return {
4791
4815
  "/billing/webhooks/stripe": {
4792
- POST: kernel.wrap("api", kernel.wrapIdentity(async (request, ports) => {
4816
+ POST: kernel.wrap("api", kernel.wrapIdentity(${renderAction(actions, "stripeWebhook", `async (request, ports) => {
4793
4817
  if (!billingEnabled) return new Response("Not found", { status: 404 });
4794
4818
  if (!secret) {
4795
4819
  return jsonResponse({ error: "STRIPE_WEBHOOK_SECRET is not set." }, { status: 503 });
@@ -4804,10 +4828,10 @@ const billingModule: AppModule = {
4804
4828
  }
4805
4829
  await applyStripeWebhook(event, ports);
4806
4830
  return jsonResponse({ received: true, id: event.id ?? null, type: event.type ?? null });
4807
- })),
4831
+ }`)})),
4808
4832
  },
4809
4833
  "/api/v1/billing/subscription": {
4810
- GET: kernel.wrapApi(async (_request, ports) => {
4834
+ GET: kernel.wrapApi(${renderAction(actions, "subscription", `async (_request, ports) => {
4811
4835
  if (!billingEnabled) return new Response("Not found", { status: 404 });
4812
4836
  ${subscriptionQuery}
4813
4837
  const row = rows[0];
@@ -4818,210 +4842,40 @@ ${subscriptionQuery}
4818
4842
  stripe_subscription_id: row.stripe_subscription_id ?? null,
4819
4843
  current_period_end: row.current_period_end ?? null,
4820
4844
  });
4821
- }),
4845
+ }`)}),
4822
4846
  },
4823
4847
  };
4824
- },
4848
+ }${actions ? "" : `,
4825
4849
  };
4826
4850
 
4827
- export default billingModule;
4828
- `;
4829
- }
4830
-
4831
- // ../strata-starter/src/renderModels.ts
4832
- function renderNoteModel(plan) {
4833
- const tenancyOn = plan.decisions.tenantTable;
4834
- const tenantField = tenancyOn ? `
4835
- tenant_id: number;` : "";
4836
- const tenantColumn = tenancyOn ? ', "tenant_id"' : "";
4837
- const fillable = tenancyOn ? '["body", "tenant_id"]' : '["body"]';
4838
- return `import { createModel, type Model } from "@getstrata/core/database/model";
4839
- import { defineTable } from "@getstrata/core/database/table";
4840
-
4841
- interface NoteRecord {
4842
- id: number;
4843
- body: string;${tenantField}
4844
- created_at: Date | string;
4845
- }
4846
-
4847
- const notesTable = defineTable<NoteRecord, "id">({
4848
- name: "notes",
4849
- primaryKey: "id",
4850
- columns: ["id", "body"${tenantColumn}, "created_at"],
4851
- defaultOrderBy: { column: "id", direction: "ASC" },
4852
- });
4853
-
4854
- type Note = Model<NoteRecord, "id">;
4855
-
4856
- const Note = createModel({
4857
- name: "Note", table: notesTable,
4858
- // created_at uses the table default; no client timestamp is sent.
4859
- attributes: { fillable: ${fillable}, timestamps: false },
4860
- });
4861
- const NoteRepository = Note.repository;
4862
-
4863
- export type { NoteRecord };
4864
- export { Note, NoteRepository };
4865
- `;
4866
- }
4867
- function renderUserModel(plan) {
4868
- const layers = plan.layers;
4869
- const tenancyOn = plan.decisions.schemaTenants;
4870
- const mfaOn = Boolean(layers.extras.mfa);
4871
- const tenantField = tenancyOn ? `
4872
- tenant_id: number;` : "";
4873
- const mfaFields = mfaOn ? `
4874
- mfa_secret: string | null;
4875
- mfa_enabled: number | boolean;
4876
- mfa_recovery_codes: string | null;` : "";
4877
- const columns = ["id", "name", "email", "password", "is_admin", "is_active", "auth_version"];
4878
- if (tenancyOn) {
4879
- columns.push("tenant_id");
4880
- }
4881
- if (mfaOn) {
4882
- columns.push("mfa_secret", "mfa_enabled", "mfa_recovery_codes");
4883
- }
4884
- columns.push("session_valid_after", "email_verified_at", "created_at");
4885
- const fillable = ["name", "email", "password", "is_admin", "is_active"];
4886
- if (tenancyOn) {
4887
- fillable.push("tenant_id");
4888
- }
4889
- if (mfaOn) {
4890
- fillable.push("mfa_secret", "mfa_enabled", "mfa_recovery_codes");
4891
- }
4892
- fillable.push("session_valid_after", "email_verified_at");
4893
- const hidden = ["password"];
4894
- if (mfaOn) {
4895
- hidden.push("mfa_secret", "mfa_recovery_codes");
4896
- }
4897
- const fillableLiteral = `[${fillable.map((column) => `"${column}"`).join(", ")}]`;
4898
- const hiddenLiteral = `[${hidden.map((column) => `"${column}"`).join(", ")}]`;
4899
- const columnsLiteral = columns.map((column) => `"${column}"`).join(", ");
4900
- return `import { createModel, type Model } from "@getstrata/core/database/model";
4901
- import { defineTable } from "@getstrata/core/database/table";
4902
-
4903
- interface UserRecord {
4904
- id: number;
4905
- name: string;
4906
- email: string;
4907
- password: string;
4908
- is_active: number | boolean;
4909
- auth_version: number;
4910
- is_admin: number | boolean;${tenantField}${mfaFields}
4911
- session_valid_after: Date | string | null;
4912
- email_verified_at: Date | string | null;
4913
- created_at: Date | string;
4914
- }
4915
-
4916
- const usersTable = defineTable<UserRecord, "id">({
4917
- name: "users",
4918
- primaryKey: "id",
4919
- columns: [${columnsLiteral}],
4920
- defaultOrderBy: { column: "id", direction: "ASC" },
4921
- });
4922
-
4923
- type User = Model<UserRecord, "id">;
4924
-
4925
- const User = createModel({
4926
- name: "User", table: usersTable,
4927
- // created_at uses the table default; no client timestamp is sent.
4928
- attributes: { fillable: ${fillableLiteral}, hidden: ${hiddenLiteral}, timestamps: false },
4929
- });
4930
- const UserRepository = User.repository;
4931
-
4932
- export type { UserRecord };
4933
- export { User, UserRepository };
4934
- `;
4935
- }
4936
- function renderApiTokenModel() {
4937
- return `import { createModel, type Model } from "@getstrata/core/database/model";
4938
- import { defineTable } from "@getstrata/core/database/table";
4939
-
4940
- interface ApiTokenRecord {
4941
- id: number;
4942
- user_id: number;
4943
- name: string;
4944
- token_hash: string;
4945
- abilities: string;
4946
- expires_at: Date | string | null;
4947
- last_used_at: Date | string | null;
4948
- created_at: Date | string;
4949
- }
4950
-
4951
- const apiTokensTable = defineTable<ApiTokenRecord, "id">({
4952
- name: "api_tokens",
4953
- primaryKey: "id",
4954
- columns: ["id", "user_id", "name", "token_hash", "abilities", "expires_at", "last_used_at", "created_at"],
4955
- defaultOrderBy: { column: "id", direction: "ASC" },
4956
- });
4957
-
4958
- type ApiToken = Model<ApiTokenRecord, "id">;
4959
-
4960
- const ApiToken = createModel({
4961
- name: "ApiToken", table: apiTokensTable,
4962
- // created_at uses the table default; no client timestamp is sent.
4963
- attributes: { fillable: ["user_id", "name", "token_hash", "abilities", "expires_at", "last_used_at"], timestamps: false },
4964
- });
4965
- const ApiTokenRepository = ApiToken.repository;
4966
-
4967
- export type { ApiTokenRecord };
4968
- export { ApiToken, ApiTokenRepository };
4969
- `;
4970
- }
4971
- function renderAuthOneTimeTokenModel() {
4972
- return `import { createModel, type Model } from "@getstrata/core/database/model";
4973
- import { defineTable } from "@getstrata/core/database/table";
4974
-
4975
- interface AuthOneTimeTokenRecord {
4976
- id: number;
4977
- purpose: string;
4978
- user_id: number;
4979
- token_hash: string;
4980
- expires_at: Date | string;
4981
- consumed_at: Date | string | null;
4982
- }
4983
-
4984
- const authOneTimeTokensTable = defineTable<AuthOneTimeTokenRecord, "id">({
4985
- name: "auth_one_time_tokens",
4986
- primaryKey: "id",
4987
- columns: ["id", "purpose", "user_id", "token_hash", "expires_at", "consumed_at"],
4988
- defaultOrderBy: { column: "id", direction: "ASC" },
4989
- });
4990
-
4991
- type AuthOneTimeToken = Model<AuthOneTimeTokenRecord, "id">;
4992
-
4993
- const AuthOneTimeToken = createModel({
4994
- name: "AuthOneTimeToken", table: authOneTimeTokensTable,
4995
- attributes: { fillable: ["purpose", "user_id", "token_hash", "expires_at", "consumed_at"], timestamps: false },
4996
- });
4997
- const AuthOneTimeTokenRepository = AuthOneTimeToken.repository;
4998
-
4999
- export type { AuthOneTimeTokenRecord };
5000
- export { AuthOneTimeToken, AuthOneTimeTokenRepository };
4851
+ export default billingModule;`}
5001
4852
  `;
4853
+ return { support, routes };
5002
4854
  }
5003
- function renderModelsRegister(plan) {
5004
- const workTracker = plan.decisions.workTracker;
5005
- const names = ["Note"];
5006
- if (plan.decisions.users)
5007
- names.push("User", "AuthOneTimeToken");
5008
- if (plan.decisions.token)
5009
- names.push("ApiToken");
5010
- return `${workTracker ? `import { workTrackerRepositories } from "./workTracker.ts";
5011
- ` : ""}${names.map((name) => `import { ${name}, ${name}Repository } from "./${name}";`).join(`
5012
- `)}
5013
-
5014
- export const repositoryDefinitions = Object.freeze([${names.map((name) => `${name}Repository`).join(", ")}${workTracker ? ", ...workTrackerRepositories" : ""}]);
5015
- export const modelDefinitions = Object.freeze([${names.join(", ")}]);
5016
- `;
4855
+ function renderBillingHttp(plan) {
4856
+ if (!plan.layers.extras.billing)
4857
+ return null;
4858
+ const actions = new ControllerActions("BillingController");
4859
+ const parts = renderBillingParts(plan, actions);
4860
+ const construction = ` constructor(private readonly billingEnabled: boolean, private readonly secret: string | undefined) {}`;
4861
+ const support = parts.support.replace(`import type { AppModule, ModuleRouteContext } from "@getstrata/bootstrap/contracts";
4862
+ `, "").replace(`import { APPLICATION_BILLING as STARTER_BILLING_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
4863
+ `, "");
4864
+ return {
4865
+ files: {
4866
+ "http/controllers/BillingController.ts": support + `import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
4867
+ ` + actions.render(construction, ["billingEnabled", "secret"])
4868
+ },
4869
+ api: { name: "billingApiRoutes", source: parts.routes }
4870
+ };
5017
4871
  }
5018
4872
 
5019
4873
  // ../strata-starter/src/renderScim.ts
5020
- function renderScimModule(plan) {
4874
+ function renderScimParts(plan, actions) {
5021
4875
  if (!plan.decisions.scim) {
5022
4876
  return null;
5023
4877
  }
5024
- return `import { randomBytes } from "node:crypto";
4878
+ const support = `import { randomBytes } from "node:crypto";
5025
4879
  import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
5026
4880
  import type { AppModule } from "@getstrata/bootstrap/contracts";
5027
4881
  import { routeParams } from "@getstrata/bootstrap/web/routing";
@@ -5177,7 +5031,7 @@ async function readScimBody(request: Request): Promise<Record<string, unknown> |
5177
5031
  }
5178
5032
  }
5179
5033
 
5180
- function wrapScim(kernel: HttpKernel, services:StarterAuthServices, handler: BusinessRouteHandler) {
5034
+ ${actions ? "export " : ""}function wrapScim(kernel: HttpKernel, services:StarterAuthServices, handler: BusinessRouteHandler) {
5181
5035
  const enabled = services.config.scimEnabled;
5182
5036
  const throttle = kernel.ownThrottle(createScimThrottleMiddleware({
5183
5037
  redisUrl: services.config.redisUrl,
@@ -5195,16 +5049,19 @@ function wrapScim(kernel: HttpKernel, services:StarterAuthServices, handler: Bus
5195
5049
  }, [throttle]);
5196
5050
  }
5197
5051
 
5198
- const scimModule: AppModule = {
5052
+ `;
5053
+ const routes = `${actions ? `export function scimApiRoutes(context: ModuleRouteContext): AppRouteMap {
5054
+ const { kernel, dependencies } = context;
5055
+ const controller = new ScimController();` : `const scimModule: AppModule = {
5199
5056
  name: "scim",
5200
5057
  order: 8,
5201
- routes({ kernel, dependencies }) {
5058
+ routes({ kernel, dependencies }) {`}
5202
5059
  const services = dependencies.container.resolve(STARTER_AUTH_SERVICES);
5203
5060
  return {
5204
5061
  "/scim/v2/ServiceProviderConfig": {
5205
5062
  GET: kernel.wrap(
5206
5063
  "api",
5207
- wrapScim(kernel, services, async () =>
5064
+ wrapScim(kernel, services, ${renderAction(actions, "configuration", `async () =>
5208
5065
  scimJson({
5209
5066
  schemas: [CONFIG_SCHEMA],
5210
5067
  patch: { supported: true },
@@ -5222,14 +5079,14 @@ const scimModule: AppModule = {
5222
5079
  primary: true,
5223
5080
  },
5224
5081
  ],
5225
- }),
5082
+ })`)},
5226
5083
  ),
5227
5084
  ),
5228
5085
  },
5229
5086
  "/scim/v2/Users": {
5230
5087
  GET: kernel.wrap(
5231
5088
  "api",
5232
- wrapScim(kernel, services, async (request, ports) => {
5089
+ wrapScim(kernel, services, ${renderAction(actions, "index", `async (request, ports) => {
5233
5090
  const url = new URL(request.url);
5234
5091
  const filter = url.searchParams.get("filter") ?? "";
5235
5092
  const match = /userName\\s+eq\\s+"([^"]+)"/i.exec(filter);
@@ -5257,11 +5114,11 @@ const scimModule: AppModule = {
5257
5114
  itemsPerPage: page.length,
5258
5115
  Resources: page.map(toScimUser),
5259
5116
  });
5260
- }),
5117
+ }`)}),
5261
5118
  ),
5262
5119
  POST: kernel.wrap(
5263
5120
  "api",
5264
- wrapScim(kernel, services, async (request, ports) => {
5121
+ wrapScim(kernel, services, ${renderAction(actions, "store", `async (request, ports) => {
5265
5122
  const body = await readScimBody(request);
5266
5123
  if (body instanceof Response) return body;
5267
5124
  const invalid = validateScimProfile(body);
@@ -5281,13 +5138,13 @@ const scimModule: AppModule = {
5281
5138
  return scimError("Could not create user.", 500);
5282
5139
  }
5283
5140
  return scimJson(toScimUser(created), 201);
5284
- }),
5141
+ }`)}),
5285
5142
  ),
5286
5143
  },
5287
5144
  "/scim/v2/Users/:id": {
5288
5145
  GET: kernel.wrap(
5289
5146
  "api",
5290
- wrapScim(kernel, services, async (request, ports) => {
5147
+ wrapScim(kernel, services, ${renderAction(actions, "show", `async (request, ports) => {
5291
5148
  const id = readScimUserId(request);
5292
5149
  if (id instanceof Response) {
5293
5150
  return id;
@@ -5297,11 +5154,11 @@ const scimModule: AppModule = {
5297
5154
  return scimError("User not found.", 404);
5298
5155
  }
5299
5156
  return scimJson(toScimUser(user));
5300
- }),
5157
+ }`)}),
5301
5158
  ),
5302
5159
  PUT: kernel.wrap(
5303
5160
  "api",
5304
- wrapScim(kernel, services, async (request, ports) => {
5161
+ wrapScim(kernel, services, ${renderAction(actions, "update", `async (request, ports) => {
5305
5162
  const id = readScimUserId(request);
5306
5163
  if (id instanceof Response) {
5307
5164
  return id;
@@ -5321,11 +5178,11 @@ const scimModule: AppModule = {
5321
5178
  }
5322
5179
  await applyAccountUpdate(ports, user, name, email, typeof body.active === "boolean" ? body.active : undefined);
5323
5180
  return scimJson(toScimUser(user));
5324
- }),
5181
+ }`)}),
5325
5182
  ),
5326
5183
  PATCH: kernel.wrap(
5327
5184
  "api",
5328
- wrapScim(kernel, services, async (request, ports) => {
5185
+ wrapScim(kernel, services, ${renderAction(actions, "patch", `async (request, ports) => {
5329
5186
  const id = readScimUserId(request);
5330
5187
  if (id instanceof Response) {
5331
5188
  return id;
@@ -5380,11 +5237,11 @@ const scimModule: AppModule = {
5380
5237
  }
5381
5238
  await applyAccountUpdate(ports, user, name, email, active);
5382
5239
  return scimJson(toScimUser(user));
5383
- }),
5240
+ }`)}),
5384
5241
  ),
5385
5242
  DELETE: kernel.wrap(
5386
5243
  "api",
5387
- wrapScim(kernel, services, async (request, ports) => {
5244
+ wrapScim(kernel, services, ${renderAction(actions, "destroy", `async (request, ports) => {
5388
5245
  const id = readScimUserId(request);
5389
5246
  if (id instanceof Response) {
5390
5247
  return id;
@@ -5394,15 +5251,29 @@ const scimModule: AppModule = {
5394
5251
  await user.delete();
5395
5252
  }
5396
5253
  return new Response(null, { status: 204 });
5397
- }),
5254
+ }`)}),
5398
5255
  ),
5399
5256
  },
5400
5257
  };
5401
- },
5258
+ }${actions ? "" : `,
5402
5259
  };
5403
5260
 
5404
- export default scimModule;
5261
+ export default scimModule;`}
5405
5262
  `;
5263
+ return { support, routes };
5264
+ }
5265
+ function renderScimHttp(plan) {
5266
+ const actions = new ControllerActions("ScimController");
5267
+ const parts = renderScimParts(plan, actions);
5268
+ if (!parts)
5269
+ return null;
5270
+ return {
5271
+ files: {
5272
+ "http/controllers/ScimController.ts": parts.support.replace(`import type { AppModule } from "@getstrata/bootstrap/contracts";
5273
+ `, "").replace("import { STARTER_AUTH_SERVICES, type StarterAuthServices }", "import type { StarterAuthServices }") + actions.render()
5274
+ },
5275
+ api: { name: "scimApiRoutes", source: parts.routes }
5276
+ };
5406
5277
  }
5407
5278
 
5408
5279
  // ../strata-starter/src/renderWorkTracker.ts
@@ -5573,8 +5444,8 @@ ${tables.map((table) => `await db.unsafe("DROP TABLE ${table}");`).join(`
5573
5444
  export default migration;
5574
5445
  `;
5575
5446
  }
5576
- function renderWorkTrackerModule() {
5577
- return `import type { AppModule, BusinessRequestPorts } from "@getstrata/bootstrap/contracts";
5447
+ function renderWorkTrackerParts(actions) {
5448
+ const support = `import type { AppModule, ModuleRouteContext, BusinessRequestPorts } from "@getstrata/bootstrap/contracts";
5578
5449
  import { BadRequestError, NotFoundError, UnauthorizedError } from "@getstrata/core/errors/http";
5579
5450
  import { jsonResponse } from "@getstrata/core/http/response";
5580
5451
  import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
@@ -5584,7 +5455,8 @@ function identity(ports:BusinessRequestPorts){
5584
5455
  if(!user)throw new UnauthorizedError();
5585
5456
  return {tenantId:ports.established.tenant.id,userId:Number(user.id)};
5586
5457
  }
5587
- async function fields(request:Request):Promise<Record<string,unknown>>{
5458
+ ${actions ? `import { readWorkFields as fields } from "../requests/WorkRequest.ts";
5459
+ ` : `async function fields(request:Request):Promise<Record<string,unknown>>{
5588
5460
  const content=request.headers.get("content-type")??"";
5589
5461
  if(content.includes("application/json")){
5590
5462
  const value:unknown=await request.json();
@@ -5593,6 +5465,7 @@ async function fields(request:Request):Promise<Record<string,unknown>>{
5593
5465
  }
5594
5466
  return Object.fromEntries(await request.formData());
5595
5467
  }
5468
+ `}
5596
5469
  async function mutate(input:Record<string,unknown>,ports:BusinessRequestPorts,publisher:WorkPublisher){
5597
5470
  try {
5598
5471
  const service=createWorkTracker(ports.database,publisher,identity(ports));
@@ -5612,22 +5485,30 @@ async function mutate(input:Record<string,unknown>,ports:BusinessRequestPorts,pu
5612
5485
  }
5613
5486
  }
5614
5487
  function escape(value:string){return value.replace(/[&<>"']/g,char=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[char]!);}
5615
- const module:AppModule={name:"work-tracker",order:5,
5488
+ `;
5489
+ const api = `${actions ? `export function workTrackerApiRoutes(context: ModuleRouteContext): AppRouteMap {
5490
+ const { kernel, dependencies } = context;
5491
+ const publisher = dependencies.container.resolve(WORK_TRACKER_OUTBOX);
5492
+ const controller = new WorkTrackerController(publisher);` : `const module:AppModule={name:"work-tracker",order:5,
5616
5493
  routes({kernel,dependencies}){
5617
- const publisher=dependencies.container.resolve(WORK_TRACKER_OUTBOX);
5494
+ const publisher=dependencies.container.resolve(WORK_TRACKER_OUTBOX);`}
5618
5495
  return {"/api/v1/work":{
5619
- GET:kernel.wrapApi(async(request,ports)=>{
5496
+ GET:kernel.wrapApi(${renderAction(actions, "index", `async(request,ports)=>{
5620
5497
  const service=createWorkTracker(ports.database,publisher,identity(ports));
5621
5498
  const organization=new URL(request.url).searchParams.get("organization");
5622
5499
  return jsonResponse(organization?await service.tasks(organization):await service.organizations());
5623
- }),
5624
- POST:kernel.wrapApi(async(request,ports)=>jsonResponse(await mutate(await fields(request),ports,publisher))),
5500
+ }`)}),
5501
+ POST:kernel.wrapApi(${renderAction(actions, "store", `async(request,ports)=>jsonResponse(await mutate(await fields(request),ports,publisher))`)}),
5625
5502
  }};
5626
- },
5627
- webRoutes({kernel,dependencies}){
5628
- const publisher=dependencies.container.resolve(WORK_TRACKER_OUTBOX);
5503
+ }${actions ? "" : ","}
5504
+ `;
5505
+ const web = `${actions ? `export function workTrackerWebRoutes(context: ModuleRouteContext): AppRouteMap {
5506
+ const { kernel, dependencies } = context;
5507
+ const publisher = dependencies.container.resolve(WORK_TRACKER_OUTBOX);
5508
+ const controller = new WorkTrackerController(publisher);` : ` webRoutes({kernel,dependencies}){
5509
+ const publisher=dependencies.container.resolve(WORK_TRACKER_OUTBOX);`}
5629
5510
  return {"/work":{
5630
- GET:kernel.wrapWebAuthenticated(async(request,ports)=>{
5511
+ GET:kernel.wrapWebAuthenticated(${renderAction(actions, "showPage", `async(request,ports)=>{
5631
5512
  const service=createWorkTracker(ports.database,publisher,identity(ports));
5632
5513
  const organization=new URL(request.url).searchParams.get("organization")??"";
5633
5514
  const organizations=await service.organizations();
@@ -5637,18 +5518,34 @@ const module:AppModule={name:"work-tracker",order:5,
5637
5518
  const form=(content:string)=>'<form method="post" action="/work">'+hidden+content+'</form>';
5638
5519
  const html='<!doctype html><title>Work tracker</title><h1>Work tracker</h1><nav>'+organizations.map(org=>'<a href="/work?organization='+encodeURIComponent(org.id)+'">'+escape(org.name)+'</a> ').join('')+'</nav>'+form('<input name="name" required maxlength="200" placeholder="Organization name"><button name="action" value="organization">Create organization</button>')+(organization?'<h2>Projects</h2>'+form('<input name="name" required maxlength="200" placeholder="Project name"><button name="action" value="project">Create project (owner)</button>')+projects.map(project=>'<h3>'+escape(project.name)+'</h3>'+form('<input type="hidden" name="project" value="'+escape(project.id)+'"><input name="title" required maxlength="200" placeholder="Task title"><button name="action" value="task">Create task</button>')).join('')+'<h2>Tasks</h2><ul>'+tasks.map(task=>'<li>'+escape(task.title)+' ('+escape(task.status)+')'+form('<input type="hidden" name="task" value="'+escape(task.id)+'"><button name="action" value="complete">Complete task</button>')+'</li>').join('')+'</ul>':'');
5639
5520
  return new Response(html,{headers:{"content-type":"text/html; charset=utf-8","cache-control":"private, no-store"}});
5640
- }),
5641
- POST:kernel.wrapWebAuthenticated(async(request,ports)=>{
5521
+ }`)}),
5522
+ POST:kernel.wrapWebAuthenticated(${renderAction(actions, "storeFromPage", `async(request,ports)=>{
5642
5523
  const input=await fields(request);
5643
5524
  const result=await mutate(input,ports,publisher);
5644
5525
  const organization=input.action==="organization"?(result as {id:string}).id:String(input.organization??"");
5645
5526
  return new Response(null,{status:303,headers:{location:"/work?organization="+encodeURIComponent(organization)}});
5646
- }),
5527
+ }`)}),
5647
5528
  }};
5648
- },
5529
+ }${actions ? "" : `,
5649
5530
  };
5650
- export default module;
5531
+ export default module;`}
5651
5532
  `;
5533
+ return { support, api, web };
5534
+ }
5535
+ function renderWorkTrackerHttp() {
5536
+ const actions = new ControllerActions("WorkTrackerController");
5537
+ const parts = renderWorkTrackerParts(actions);
5538
+ const construction = ` constructor(private readonly publisher: WorkPublisher) {}`;
5539
+ const support = parts.support.replace("AppModule, ModuleRouteContext, BusinessRequestPorts", "BusinessRequestPorts").replace("createWorkTracker, WORK_TRACKER_OUTBOX,", "createWorkTracker,");
5540
+ return {
5541
+ files: {
5542
+ "http/requests/WorkRequest.ts": renderWorkRequest(),
5543
+ "http/controllers/WorkTrackerController.ts": support + `import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
5544
+ ` + actions.render(construction, ["publisher"])
5545
+ },
5546
+ api: { name: "workTrackerApiRoutes", source: parts.api },
5547
+ web: { name: "workTrackerWebRoutes", source: parts.web }
5548
+ };
5652
5549
  }
5653
5550
  function renderWorkTrackerGuide() {
5654
5551
  return `# Work tracker reference
@@ -5687,6 +5584,283 @@ Column-tenancy drivers use explicit tenant/organization predicates and composite
5687
5584
  Schema commands use the migration connection; keep privileged credentials out of the runtime.
5688
5585
  `;
5689
5586
  }
5587
+ function renderWorkRequest() {
5588
+ return `import { BadRequestError } from "@getstrata/core/errors/http";
5589
+ export async function readWorkFields(request:Request):Promise<Record<string,unknown>>{
5590
+ const content=request.headers.get("content-type")??"";
5591
+ if(content.includes("application/json")){
5592
+ const value:unknown=await request.json();
5593
+ if(!value||typeof value!=="object"||Array.isArray(value))throw new BadRequestError("Expected an object.");
5594
+ return value as Record<string,unknown>;
5595
+ }
5596
+ return Object.fromEntries(await request.formData());
5597
+ }
5598
+ `;
5599
+ }
5600
+
5601
+ // ../strata-starter/src/renderHttp.ts
5602
+ function renderHttpFiles(plan) {
5603
+ const features = [
5604
+ ...plan.decisions.serverViews ? [renderHomeHttp()] : [],
5605
+ renderAuthHttp(plan),
5606
+ ...plan.decisions.workTracker ? [renderWorkTrackerHttp()] : [],
5607
+ renderScimHttp(plan),
5608
+ renderBillingHttp(plan)
5609
+ ].filter((feature) => feature !== null);
5610
+ const files = Object.assign({}, ...features.map((feature) => feature.files));
5611
+ const imports = {
5612
+ api: [
5613
+ ...plan.decisions.users ? [
5614
+ 'import { AuthController } from "../http/controllers/AuthController.ts";',
5615
+ 'import { STARTER_AUTH_SERVICES } from "../bootstrap/auth.ts";'
5616
+ ] : [],
5617
+ ...plan.decisions.mfaViews ? [
5618
+ 'import { wrapWebLogin } from "@getstrata/bootstrap/web/routing";',
5619
+ 'import { CORE_VIEW_RENDERER_TOKEN } from "@getstrata/core/view";'
5620
+ ] : [],
5621
+ ...plan.decisions.workTracker ? [
5622
+ 'import { WorkTrackerController } from "../http/controllers/WorkTrackerController.ts";',
5623
+ 'import { WORK_TRACKER_OUTBOX } from "../domain/workTracker.ts";'
5624
+ ] : [],
5625
+ ...plan.decisions.scim ? ['import { ScimController, wrapScim } from "../http/controllers/ScimController.ts";'] : [],
5626
+ ...plan.layers.extras.billing ? [
5627
+ 'import { BillingController } from "../http/controllers/BillingController.ts";',
5628
+ 'import { APPLICATION_BILLING as STARTER_BILLING_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";'
5629
+ ] : []
5630
+ ],
5631
+ web: [
5632
+ ...plan.decisions.serverViews || plan.decisions.cookie ? ['import { CORE_VIEW_RENDERER_TOKEN } from "@getstrata/core/view";'] : [],
5633
+ ...plan.decisions.serverViews ? ['import { HomeController } from "../http/controllers/HomeController.ts";'] : [],
5634
+ ...plan.decisions.cookie ? [
5635
+ 'import { AuthWebController } from "../http/controllers/AuthWebController.ts";',
5636
+ 'import { STARTER_AUTH_SERVICES } from "../bootstrap/auth.ts";',
5637
+ 'import { wrapWebLogin, wrapWebRegister } from "@getstrata/bootstrap/web/routing";'
5638
+ ] : [],
5639
+ ...plan.decisions.workTracker ? [
5640
+ 'import { WorkTrackerController } from "../http/controllers/WorkTrackerController.ts";',
5641
+ 'import { WORK_TRACKER_OUTBOX } from "../domain/workTracker.ts";'
5642
+ ] : []
5643
+ ]
5644
+ };
5645
+ for (const kind of ["api", "web"]) {
5646
+ const routes = features.flatMap((feature) => {
5647
+ const route = feature[kind];
5648
+ return route ? [route] : [];
5649
+ });
5650
+ files[`routes/${kind}.ts`] = `import type { AppRouteMap, ModuleRouteContext } from "@getstrata/bootstrap/contracts";
5651
+ import { composeRouteMaps } from "@getstrata/bootstrap/routePlan";
5652
+ ${imports[kind].join(`
5653
+ `)}
5654
+
5655
+ ${routes.map((route) => route.source).join(`
5656
+ `)}
5657
+ /** Register ${kind === "api" ? "API" : "browser"} endpoints and their middleware here. */
5658
+ export function ${kind}Routes(context: ModuleRouteContext): AppRouteMap {
5659
+ return composeRouteMaps(${routes.map((route) => `${route.name}(context)`).join(", ")});
5660
+ }
5661
+ `;
5662
+ }
5663
+ files["routes/index.ts"] = `import { buildApplicationRoutes } from "@getstrata/bootstrap/application";
5664
+ import type { AppDependencies, AppModule } from "@getstrata/bootstrap/contracts";
5665
+ import type { FrontendMode } from "@getstrata/core/runtime/frontendMode";
5666
+ import { apiRoutes } from "./api.ts";
5667
+ import { webRoutes } from "./web.ts";
5668
+
5669
+ /** App routes use the same kernel and middleware boundaries as optional modules. */
5670
+ export function applicationRoutes(dependencies: AppDependencies, modules: readonly AppModule[], options: { frontend: FrontendMode }) {
5671
+ return buildApplicationRoutes(dependencies, [
5672
+ ...modules,
5673
+ { name: "application", routes: apiRoutes, webRoutes },
5674
+ ], options);
5675
+ }
5676
+ `;
5677
+ return files;
5678
+ }
5679
+
5680
+ // ../strata-starter/src/renderInitialAdmin.ts
5681
+ function renderInitialAdminMigration(plan) {
5682
+ if (!plan.decisions.users)
5683
+ return null;
5684
+ const driver = plan.decisions.sqlDriver;
5685
+ return `import { Schema } from "@getstrata/core/database/schema";
5686
+ import { guardMigrationRollback } from "@getstrata/core/database/migrations";
5687
+ import type { Migration } from "@getstrata/core/database/migrations/types";
5688
+
5689
+ const migration: Migration = {
5690
+ name: "0004_initial_admin_provisioning",
5691
+ async up(db) {
5692
+ await Schema.run(db, "${driver}", schema => {
5693
+ schema.create("initial_admin_provisioning", table => {
5694
+ table.integer("id").primary();
5695
+ table.text("email");
5696
+ table.timestamp("provisioned_at").defaultRaw("CURRENT_TIMESTAMP");
5697
+ });
5698
+ });
5699
+ },
5700
+ async down(db, context) {
5701
+ await guardMigrationRollback(context, {
5702
+ hasHistory: async () => (await db.unsafe("SELECT id FROM initial_admin_provisioning")).length > 0,
5703
+ message: "Cannot discard a completed initial-admin provisioning claim.",
5704
+ });
5705
+ await Schema.run(db, "${driver}", schema => { schema.drop("initial_admin_provisioning"); });
5706
+ },
5707
+ };
5708
+ export default migration;
5709
+ `;
5710
+ }
5711
+ function renderInitialAdminCommand(plan) {
5712
+ const layers = plan.layers;
5713
+ if (!plan.decisions.users)
5714
+ return null;
5715
+ const tenant = plan.decisions.tenantTable;
5716
+ const rls = plan.decisions.rls;
5717
+ const placeholder = layers.database === "postgres" ? "$1" : "?";
5718
+ const fields = ["name", "email", "password", "is_admin", ...tenant ? ["tenant_id"] : []];
5719
+ const placeholders = fields.map((_, index) => layers.database === "postgres" ? `$${index + 1}` : "?");
5720
+ return `import { runInitialAdminCommand } from "@getstrata/cli/initialAdmin";
5721
+ import { hashPassword } from "@getstrata/core/auth/password";
5722
+ import type { TransactionSession } from "@getstrata/core/database/session";
5723
+ ${rls ? `import { assertRlsLiveDatabaseRole } from "@getstrata/bootstrap/secretsGuard";
5724
+ ` : ""}import { bootstrapApp } from "../bootstrap/createApp.ts";
5725
+
5726
+ export async function initialAdminCommand(...args: string[]): Promise<void> {
5727
+ await runInitialAdminCommand(args, {
5728
+ tenantRequired: ${tenant},
5729
+ async provision(input) {
5730
+ // Hash before acquiring the database claim; only the official auth helper owns crypto.
5731
+ const passwordHash = await hashPassword(input.password);
5732
+ const app = await bootstrapApp({ migrate: false, mode: "command" });
5733
+ try {
5734
+ await app.invoke({ kind: "command", actor: { kind: "system", policy: "cli.initial-admin" } }, async ports => {
5735
+ ${rls ? ` await assertRlsLiveDatabaseRole({ ...process.env }, async () => { const rows = await ports.database.execute<{rolname:string;rolsuper:boolean;rolbypassrls:boolean}>({text:"SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user",params:[]});return rows[0] ?? null; });
5736
+ ` : ""} const provision = async (db: TransactionSession) => {
5737
+ // The singleton primary key serializes bootstrap commands across all tenants/processes.
5738
+ await db.execute({text:"INSERT INTO initial_admin_provisioning (id, email) VALUES (1, ${placeholder})",params:[input.email]});
5739
+ if ((await db.execute({text:"SELECT id FROM users WHERE is_admin = ${layers.database === "postgres" ? "TRUE" : "1"} LIMIT 1",params:[]})).length) {
5740
+ throw new Error("An admin already exists.");
5741
+ }
5742
+ if ((await db.execute({text:"SELECT id FROM users WHERE LOWER(email) = ${placeholder}",params:[input.email]})).length) {
5743
+ throw new Error("The account already exists; provisioning never promotes accounts.");
5744
+ }
5745
+ ${tenant ? ` if (!(await db.execute({text:"SELECT id FROM tenant WHERE id = ${placeholder}",params:[input.tenantId]})).length) {
5746
+ throw new Error("The tenant does not exist.");
5747
+ }
5748
+ ` : ""} await db.execute({text:"INSERT INTO users (${fields.join(", ")}) VALUES (${placeholders.join(", ")})",params:[input.name, input.email, passwordHash, ${layers.database === "postgres" ? "true" : "1"}${tenant ? ", input.tenantId" : ""}]});
5749
+ // Verification and MFA stay unenrolled; normal application flows remain authoritative.
5750
+ };
5751
+ await ${rls ? 'ports.policy.run(ports.database, {kind:"bypass"}, provision)' : "ports.database.transaction(provision)"};
5752
+ });
5753
+ } finally {
5754
+ await app.context.dispose();
5755
+ }
5756
+ },
5757
+ });
5758
+ console.log("Initial admin provisioned. Complete email verification and MFA through the application.");
5759
+ }
5760
+ `;
5761
+ }
5762
+
5763
+ // ../strata-starter/src/renderModels.ts
5764
+ function renderModel(name, table, fields, fillable, hidden = []) {
5765
+ return `import { defineModel, field, type ModelAttributes } from "@getstrata/core/database/model";
5766
+
5767
+ class ${name} extends defineModel({
5768
+ table: "${table}",
5769
+ fields: {
5770
+ ${Object.entries(fields).map(([column, type]) => ` ${column}: ${type},`).join(`
5771
+ `)}
5772
+ },
5773
+ defaultOrderBy: { column: "id", direction: "ASC" },
5774
+ }) {
5775
+ static $fillable = ${JSON.stringify(fillable)} as const;
5776
+ ${hidden.length ? ` static $hidden = ${JSON.stringify(hidden)} as const;
5777
+ ` : ""} // Timestamp columns use database defaults; no client timestamp is sent.
5778
+ static $timestamps = false;
5779
+ }
5780
+
5781
+ type ${name}Record = ModelAttributes<${name}>;
5782
+ export type { ${name}Record };
5783
+ export { ${name} };
5784
+ `;
5785
+ }
5786
+ function renderNoteModel(plan) {
5787
+ const tenant = plan.decisions.tenantTable;
5788
+ return renderModel("Note", "notes", {
5789
+ id: "field.number()",
5790
+ body: "field.string()",
5791
+ ...tenant ? { tenant_id: "field.number()" } : {},
5792
+ created_at: "field.timestamp()"
5793
+ }, ["body", ...tenant ? ["tenant_id"] : []]);
5794
+ }
5795
+ function renderUserModel(plan) {
5796
+ const tenant = plan.decisions.schemaTenants;
5797
+ const mfa = plan.layers.extras.mfa;
5798
+ return renderModel("User", "users", {
5799
+ id: "field.number()",
5800
+ name: "field.string()",
5801
+ email: "field.string()",
5802
+ password: "field.string()",
5803
+ is_admin: "field.boolean()",
5804
+ is_active: "field.boolean()",
5805
+ auth_version: "field.number()",
5806
+ ...tenant ? { tenant_id: "field.number()" } : {},
5807
+ ...mfa ? {
5808
+ mfa_secret: "field.nullable(field.string())",
5809
+ mfa_enabled: "field.boolean()",
5810
+ mfa_recovery_codes: "field.nullable(field.string())"
5811
+ } : {},
5812
+ session_valid_after: "field.nullable(field.timestamp())",
5813
+ email_verified_at: "field.nullable(field.timestamp())",
5814
+ created_at: "field.timestamp()"
5815
+ }, [
5816
+ "name",
5817
+ "email",
5818
+ "password",
5819
+ "is_admin",
5820
+ "is_active",
5821
+ ...tenant ? ["tenant_id"] : [],
5822
+ ...mfa ? ["mfa_secret", "mfa_enabled", "mfa_recovery_codes"] : [],
5823
+ "session_valid_after",
5824
+ "email_verified_at"
5825
+ ], ["password", ...mfa ? ["mfa_secret", "mfa_recovery_codes"] : []]);
5826
+ }
5827
+ function renderApiTokenModel() {
5828
+ return renderModel("ApiToken", "api_tokens", {
5829
+ id: "field.number()",
5830
+ user_id: "field.number()",
5831
+ name: "field.string()",
5832
+ token_hash: "field.string()",
5833
+ abilities: "field.string()",
5834
+ expires_at: "field.nullable(field.timestamp())",
5835
+ last_used_at: "field.nullable(field.timestamp())",
5836
+ created_at: "field.timestamp()"
5837
+ }, ["user_id", "name", "token_hash", "abilities", "expires_at", "last_used_at"]);
5838
+ }
5839
+ function renderAuthOneTimeTokenModel() {
5840
+ return renderModel("AuthOneTimeToken", "auth_one_time_tokens", {
5841
+ id: "field.number()",
5842
+ purpose: "field.string()",
5843
+ user_id: "field.number()",
5844
+ token_hash: "field.string()",
5845
+ expires_at: "field.timestamp()",
5846
+ consumed_at: "field.nullable(field.timestamp())"
5847
+ }, ["purpose", "user_id", "token_hash", "expires_at", "consumed_at"]);
5848
+ }
5849
+ function renderModelsRegister(plan) {
5850
+ const names = ["Note"];
5851
+ if (plan.decisions.users)
5852
+ names.push("User", "AuthOneTimeToken");
5853
+ if (plan.decisions.token)
5854
+ names.push("ApiToken");
5855
+ return `${names.map((name) => `import { ${name} } from "./${name}";`).join(`
5856
+ `)}
5857
+
5858
+ export const modelDefinitions = Object.freeze([${names.join(", ")}]);
5859
+ ${plan.decisions.workTracker ? `
5860
+ // This optional domain example supplies custom data-access repositories.
5861
+ export { workTrackerRepositories as repositoryDefinitions } from "./workTracker.ts";
5862
+ ` : ""}`;
5863
+ }
5690
5864
 
5691
5865
  // ../strata-starter/src/generate.ts
5692
5866
  var PROJECT_NAME_PATTERN = /^[a-z0-9][a-z0-9-_]*$/i;
@@ -5695,11 +5869,11 @@ function starterPackageRoot() {
5695
5869
  }
5696
5870
  function resolveTemplateRoot(root = starterPackageRoot()) {
5697
5871
  const fromDist = join2(root, "templates");
5698
- if (existsSync2(join2(fromDist, "src"))) {
5872
+ if (existsSync2(join2(fromDist, "tsconfig.json"))) {
5699
5873
  return fromDist;
5700
5874
  }
5701
5875
  const nested = join2(root, "dist/templates");
5702
- if (existsSync2(join2(nested, "src"))) {
5876
+ if (existsSync2(join2(nested, "tsconfig.json"))) {
5703
5877
  return nested;
5704
5878
  }
5705
5879
  return fromDist;
@@ -5857,28 +6031,17 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
5857
6031
  writeText(join2(src, "db/seed.ts"), renderSeedTs());
5858
6032
  writeText(join2(src, "db/status.ts"), renderStatusTs(plan));
5859
6033
  writeText(join2(src, "db/rollback.ts"), renderRollbackTs(plan));
5860
- if (decisions.serverViews)
5861
- writeText(join2(src, "modules/site/index.ts"), renderSiteModule(plan));
6034
+ for (const [path, source] of Object.entries(renderHttpFiles(plan))) {
6035
+ writeText(join2(src, path), source);
6036
+ }
5862
6037
  const directory = renderAuthDirectory(plan);
5863
6038
  if (directory) {
5864
6039
  writeText(join2(src, "bootstrap/authDirectory.ts"), directory);
5865
6040
  }
5866
- const authModule = renderAuthModule(plan);
5867
- if (authModule) {
5868
- writeText(join2(src, "modules/auth/index.ts"), authModule);
5869
- }
5870
- const scimModule = renderScimModule(plan);
5871
- if (scimModule) {
5872
- writeText(join2(src, "modules/scim/index.ts"), scimModule);
5873
- } else {
5874
- removeIfExists(join2(src, "modules/scim/index.ts"));
5875
- }
5876
6041
  if (layers.extras.billing) {
5877
6042
  writeText(join2(src, "billing/applyStripeWebhook.ts"), renderApplyStripeWebhook());
5878
- writeText(join2(src, "modules/billing/index.ts"), renderBillingModule(plan));
5879
6043
  } else {
5880
6044
  removeIfExists(join2(src, "billing/applyStripeWebhook.ts"));
5881
- removeIfExists(join2(src, "modules/billing/index.ts"));
5882
6045
  }
5883
6046
  if (layers.extras.webhooks) {
5884
6047
  writeText(join2(src, "jobs/dispatchOutboundWebhookJob.ts"), renderDispatchOutboundWebhookJob(plan));
@@ -5933,7 +6096,6 @@ Open \`/work\` after signing in to the server app. See [the reference workflow](
5933
6096
  `);
5934
6097
  writeText(join2(src, "domain/workTracker.ts"), renderWorkTrackerDomain());
5935
6098
  writeText(join2(src, "models/workTracker.ts"), renderWorkTrackerModels());
5936
- writeText(join2(src, "modules/workTracker/index.ts"), renderWorkTrackerModule());
5937
6099
  writeText(join2(src, "db/migrations/0007_work_tracker.ts"), renderWorkTrackerMigration(plan));
5938
6100
  }
5939
6101
  mkdirSync2(join2(targetDir, "storage"), { recursive: true });