@getstrata/starter 2.2.43 → 2.2.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1172,7 +1172,9 @@ function renderAuthModule(layers) {
1172
1172
  const oidc = Boolean(layers.extras.oidc && cookie);
1173
1173
  const mfa = Boolean(layers.extras.mfa && cookie);
1174
1174
  const verify = Boolean(layers.extras.emailVerification);
1175
- const jsonApi = authUsesToken(layers.auth) || authUsesJwt(layers.auth);
1175
+ const bearerApi = authUsesToken(layers.auth) || authUsesJwt(layers.auth);
1176
+ const jsonCookieAccounts = cookie && (layers.frontend === "api" || layers.frontend === "spa-react");
1177
+ const jsonAccounts = bearerApi || jsonCookieAccounts;
1176
1178
  const tenantInsert = usesTenantTable(layers.tenancy);
1177
1179
  const tenantCreateField = tenantInsert ? `
1178
1180
  tenant_id: currentTenantId(),` : "";
@@ -1200,7 +1202,7 @@ function renderAuthModule(layers) {
1200
1202
  }
1201
1203
  }
1202
1204
  imports.push(`import { ConflictError } from "@getstrata/core/errors/http";`);
1203
- if (jsonApi) {
1205
+ if (bearerApi) {
1204
1206
  imports.push(`import { AuthManager } from "@getstrata/core/auth/guard";`);
1205
1207
  }
1206
1208
  if (authUsesJwt(layers.auth)) {
@@ -1213,6 +1215,9 @@ function renderAuthModule(layers) {
1213
1215
  if (mfa) {
1214
1216
  imports.push(`import { createPasswordConfirmCookie } from "@getstrata/core/auth/passwordConfirmCookie";`);
1215
1217
  }
1218
+ if (mfa && jsonCookieAccounts) {
1219
+ imports.push(`import { createRequirePasswordConfirmMiddleware } from "@getstrata/core/http/requirePasswordConfirmMiddleware";`, `import { withMiddleware } from "@getstrata/core/http/routeMiddleware";`);
1220
+ }
1216
1221
  imports.push(`import { emailRule, minLength, required, stringRule, validateObject } from "@getstrata/core/validation/rules";`);
1217
1222
  imports.push(`import { parseJsonBody } from "@getstrata/core/http/validation";`);
1218
1223
  imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
@@ -1230,7 +1235,7 @@ function renderAuthModule(layers) {
1230
1235
  }
1231
1236
  imports.push(oidc ? `import { clearOidcPkceCookie, createOAuthState, readOidcPkceCookie, sealOidcPkceCookie, verifyOAuthState } from "@getstrata/core/security/oauthState";` : `import { createOAuthState, verifyOAuthState } from "@getstrata/core/security/oauthState";`);
1232
1237
  }
1233
- if (jsonApi || cookie) {
1238
+ if (bearerApi || cookie) {
1234
1239
  imports.push(`import { privateJsonResponse, withErrorHandling } from "@getstrata/core/http/response";`);
1235
1240
  imports.push(`import { resolveCsrfTokenForRequest } from "@getstrata/core/http/csrfToken";`);
1236
1241
  }
@@ -1501,7 +1506,7 @@ async function completeBrowserSsoLogin(
1501
1506
  });
1502
1507
  }),
1503
1508
  },` : "";
1504
- const jsonRegister = jsonApi ? `
1509
+ const jsonRegister = jsonAccounts ? `
1505
1510
  "/api/v1/auth/register": {
1506
1511
  POST: kernel.wrap("api", kernel.wrapRegister(withErrorHandling(async (request) => {
1507
1512
  if ((process.env.FEATURE_REGISTRATION ?? "true") === "false") {
@@ -1549,7 +1554,7 @@ async function completeBrowserSsoLogin(
1549
1554
  });
1550
1555
  }))),
1551
1556
  },` : "";
1552
- const apiUser = jsonApi ? `
1557
+ const apiUser = bearerApi ? `
1553
1558
  "/api/user": {
1554
1559
  GET: kernel.wrapApi(async (request) => {
1555
1560
  const user = await dependencies.container.resolve<AuthManager>(CORE_AUTH_TOKEN).requireUser(request);
@@ -1565,7 +1570,7 @@ async function completeBrowserSsoLogin(
1565
1570
  ` : ""}return payload;
1566
1571
  })),
1567
1572
  },` : "";
1568
- const jsonPassword = jsonApi ? `
1573
+ const jsonPassword = jsonAccounts ? `
1569
1574
  "/api/v1/auth/forgot-password": {
1570
1575
  POST: kernel.wrap("api", withErrorHandling(async (request) => {
1571
1576
  const email = await parseJsonBody(request, parseForgotPasswordEmail);
@@ -1578,7 +1583,7 @@ async function completeBrowserSsoLogin(
1578
1583
  },
1579
1584
  "/api/v1/auth/reset-password": {
1580
1585
  POST: kernel.wrap("api", kernel.wrapSigned(withErrorHandling(async (request) => {
1581
- const body: unknown = await request.json();
1586
+ const body = await parseJsonBody(request, (payload) => payload);
1582
1587
  const password = typeof body === "object" && body !== null && "password" in body ? body.password : undefined;
1583
1588
  if (!(await completeSignedPasswordReset(request, password))) {
1584
1589
  return privateJsonResponse({ error: "Invalid or expired reset link." }, { status: 403 });
@@ -1586,7 +1591,7 @@ async function completeBrowserSsoLogin(
1586
1591
  return privateJsonResponse({ ok: true });
1587
1592
  }))),
1588
1593
  },` : "";
1589
- const jsonVerify = jsonApi && verify ? `
1594
+ const jsonVerify = jsonAccounts && verify ? `
1590
1595
  "/api/v1/auth/verify-email": {
1591
1596
  POST: kernel.wrap("api", kernel.wrapSigned(withErrorHandling(async (request) => {
1592
1597
  if (!(await completeSignedEmailVerification(request))) {
@@ -1595,13 +1600,53 @@ async function completeBrowserSsoLogin(
1595
1600
  return privateJsonResponse({ ok: true });
1596
1601
  }))),
1597
1602
  },` : "";
1603
+ const jsonAccountManagement = jsonCookieAccounts ? `
1604
+ ${verify ? `"/api/v1/auth/verification-notification": {
1605
+ POST: kernel.wrapApi(async (request) => {
1606
+ const user = await dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1607
+ await runWithLockedAuthUser(Number(user.id), async (record) => {
1608
+ if (!record?.is_active || record.auth_version !== user.authVersion) throw new ConflictError("Account changed. Sign in again.");
1609
+ if (!record.email_verified_at) await issueSignedAuthMail(record.email ?? "", "Verify your email", "/api/v1/auth/verify-email", AUTH_ONE_TIME_PURPOSES.emailVerify, record.id, { id: String(record.id) });
1610
+ });
1611
+ return privateJsonResponse({ ok: true });
1612
+ }),
1613
+ },` : ""}
1614
+ ${mfa ? `"/api/v1/auth/confirm-password": {
1615
+ POST: kernel.wrap("api", kernel.wrapVerified(async (request) => {
1616
+ const user = await dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1617
+ const { password } = await parseJsonBody(request, (payload) => validateObject(payload, { password: [required(), stringRule()] }));
1618
+ return runWithLockedAuthUser(Number(user.id), async (record) => {
1619
+ if (!record?.is_active || record.auth_version !== user.authVersion) throw new ConflictError("Account changed. Sign in again.");
1620
+ if (!record.password || !(await verifyPassword(String(password), record.password))) return privateJsonResponse({ error: "That password is not correct." }, { status: 422 });
1621
+ const response = privateJsonResponse({ ok: true });
1622
+ response.headers.append("set-cookie", createPasswordConfirmCookie(Number(user.id), record.auth_version));
1623
+ return response;
1624
+ });
1625
+ })),
1626
+ },
1627
+ "/api/v1/auth/mfa": {
1628
+ GET: kernel.wrap("api", kernel.wrapVerified(async (request) => {
1629
+ const user = await dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1630
+ const record = await starterAuthDirectory.findByIdOrThrow(Number(user.id));
1631
+ const secret = generateTotpSecret();
1632
+ return privateJsonResponse({ secret, otpauth: buildOtpauthUrl({ secret, account: record.email ?? "user", issuer: process.env.APP_NAME ?? "Strata" }) });
1633
+ })),
1634
+ POST: kernel.wrap("api", kernel.wrapVerified(withMiddleware(createRequirePasswordConfirmMiddleware())(async (request) => {
1635
+ const user = await dependencies.container.resolve<CookieSessionAuthManager>(CORE_AUTH_TOKEN).requireUser(request);
1636
+ const fields = await parseJsonBody(request, (payload) => validateObject(payload, { secret: [required(), stringRule()], code: [required(), stringRule()] }));
1637
+ const secret = String(fields.secret).trim();
1638
+ if (!verifyTotp(secret, String(fields.code).trim())) return privateJsonResponse({ error: "Could not confirm that code." }, { status: 422 });
1639
+ const recoveryCodes = await enrollMfa(user, secret);
1640
+ return privateJsonResponse({ recoveryCodes });
1641
+ }))),
1642
+ },` : ""}` : "";
1598
1643
  const csrfRoute = `
1599
1644
  "/api/v1/auth/csrf": {
1600
1645
  GET: kernel.wrap("api", withErrorHandling(async (request) => {
1601
1646
  return privateJsonResponse({ token: resolveCsrfTokenForRequest(request) });
1602
1647
  })),
1603
1648
  },`;
1604
- const cookieJsonAuth = cookie && !jsonApi ? `
1649
+ const cookieJsonAuth = cookie && !bearerApi ? `
1605
1650
  "/api/v1/auth/login": {
1606
1651
  POST: kernel.wrap("api", kernel.wrapLogin(withErrorHandling(async (request) => {
1607
1652
  const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
@@ -1775,9 +1820,9 @@ async function completeBrowserSsoLogin(
1775
1820
  return login;
1776
1821
  })),
1777
1822
  },` : "";
1778
- const apiRoutes = jsonApi || cookie ? `
1823
+ const apiRoutes = bearerApi || cookie ? `
1779
1824
  routes({ kernel, dependencies }) {
1780
- return {${csrfRoute}${samlRoutes}${githubRoutes}${oidcRoutes}${cookieJsonAuth}${tokenLogin}${jsonRegister}${jwtLogin}${apiUser}${jsonPassword}${jsonVerify}
1825
+ return {${csrfRoute}${samlRoutes}${githubRoutes}${oidcRoutes}${cookieJsonAuth}${tokenLogin}${jsonRegister}${jwtLogin}${apiUser}${jsonPassword}${jsonVerify}${jsonAccountManagement}
1781
1826
  };
1782
1827
  },` : "";
1783
1828
  const mfaLoginBranch = `const mfaResult = completePasswordLogin(user, { mfaCode: mfa_code });
@@ -2006,30 +2051,7 @@ async function completeBrowserSsoLogin(
2006
2051
  otpauth: buildOtpauthUrl({ secret, account: "user", issuer: process.env.APP_NAME ?? "Strata" }),
2007
2052
  }, { request });
2008
2053
  }
2009
- const recoveryCodes = generateRecoveryCodes();
2010
- const stored = protectMfaSecret(secret);
2011
- const previous = await runAuthWrite(Number(user.id), () => User.find(Number(user.id)));
2012
- if (!previous || previous.get("auth_version") !== user.authVersion || !(previous.get("is_active") === true || previous.get("is_active") === 1)) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
2013
- await runInTransaction(async () => {
2014
- await runAuthWrite(Number(user.id), async () => {
2015
- // Trusted, pre-protected security fields: atomically replace only the state we read.
2016
- const changed = await previous.getRepository().updateWhere({
2017
- mfa_secret: stored,
2018
- mfa_enabled: true,
2019
- mfa_recovery_codes: JSON.stringify(recoveryCodes.map((item) => hashRecoveryCode(item))),
2020
- }, { where: {
2021
- id: Number(user.id),
2022
- is_active: previous.get("is_active"),
2023
- auth_version: previous.get("auth_version"),
2024
- mfa_enabled: previous.get("mfa_enabled"),
2025
- mfa_secret: previous.get("mfa_secret"),
2026
- mfa_recovery_codes: previous.get("mfa_recovery_codes"),
2027
- session_valid_after: previous.get("session_valid_after"),
2028
- } });
2029
- if (changed !== 1) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
2030
- });
2031
- await revokeUserSessions(Number(user.id));
2032
- });
2054
+ const recoveryCodes = await enrollMfa(user, secret);
2033
2055
  return views.render("mfa-setup.eta", {
2034
2056
  layout: { title: "MFA" },
2035
2057
  errors: {},
@@ -2045,6 +2067,37 @@ async function completeBrowserSsoLogin(
2045
2067
  return `${imports.join(`
2046
2068
  `)}
2047
2069
  ${helpers}
2070
+
2071
+ ${mfa ? `
2072
+ async function enrollMfa(user: { id: string | number; authVersion?: number }, secret: string) {
2073
+ const recoveryCodes = generateRecoveryCodes();
2074
+ const stored = protectMfaSecret(secret);
2075
+ const previous = await runAuthWrite(Number(user.id), () => User.find(Number(user.id)));
2076
+ if (!previous || previous.get("auth_version") !== user.authVersion || !(previous.get("is_active") === true || previous.get("is_active") === 1)) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
2077
+ await runInTransaction(async () => {
2078
+ await runAuthWrite(Number(user.id), async () => {
2079
+ // Trusted, pre-protected security fields: atomically replace only the state we read.
2080
+ const changed = await previous.getRepository().updateWhere({
2081
+ mfa_secret: stored,
2082
+ mfa_enabled: true,
2083
+ mfa_recovery_codes: JSON.stringify(recoveryCodes.map((item) => hashRecoveryCode(item))),
2084
+ }, { where: {
2085
+ id: Number(user.id),
2086
+ is_active: previous.get("is_active"),
2087
+ auth_version: previous.get("auth_version"),
2088
+ mfa_enabled: previous.get("mfa_enabled"),
2089
+ mfa_secret: previous.get("mfa_secret"),
2090
+ mfa_recovery_codes: previous.get("mfa_recovery_codes"),
2091
+ session_valid_after: previous.get("session_valid_after"),
2092
+ } });
2093
+ if (changed !== 1) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
2094
+ });
2095
+ await revokeUserSessions(Number(user.id));
2096
+ });
2097
+ return recoveryCodes;
2098
+ }
2099
+ ` : ""}
2100
+
2048
2101
  const authModule: AppModule = {
2049
2102
  name: "auth",
2050
2103
  order: 2,${apiRoutes}${cookieRoutes}
@@ -3173,9 +3226,9 @@ function renderPackageJson(projectName, options = {}) {
3173
3226
  "@getstrata/cli": "workspace:*",
3174
3227
  "@getstrata/core": "workspace:*"
3175
3228
  } : {
3176
- "@getstrata/bootstrap": "^2.2.43",
3177
- "@getstrata/cli": "^2.2.43",
3178
- "@getstrata/core": "^2.2.43"
3229
+ "@getstrata/bootstrap": "^2.2.44",
3230
+ "@getstrata/cli": "^2.2.44",
3231
+ "@getstrata/core": "^2.2.44"
3179
3232
  };
3180
3233
  coreDeps.eta = "^4.6.0";
3181
3234
  if (options.layers?.database === "mysql") {
@@ -3287,8 +3340,8 @@ function renderApiDocs(projectName, layers) {
3287
3340
  if (authUsesJwt(layers.auth)) {
3288
3341
  rows.push("| `POST` | `/api/auth/token` | Mints a short-lived JWT. Not an HTML session. Requires CSRF like JSON login. |");
3289
3342
  }
3290
- if (authUsesToken(layers.auth) || authUsesJwt(layers.auth)) {
3291
- rows.push("| `POST` | `/api/v1/auth/register` | Returns neutral `{ ok: true }` (201); sign in separately. |", "| `POST` | `/api/v1/auth/forgot-password` | Sends a signed reset link through the mail driver. |", "| `POST` | `/api/v1/auth/reset-password` | Consumes the signed link. |", "| `GET` | `/api/user` | Current user for the active guard. |");
3343
+ if (authUsesToken(layers.auth) || authUsesJwt(layers.auth) || authUsesCookie(layers.auth)) {
3344
+ rows.push("| `POST` | `/api/v1/auth/register` | Returns neutral `{ ok: true }` (201); sign in separately. |", "| `POST` | `/api/v1/auth/forgot-password` | Sends a signed reset link through the mail driver. |", "| `POST` | `/api/v1/auth/reset-password` | Consumes the signed link. |", ...authUsesToken(layers.auth) || authUsesJwt(layers.auth) ? ["| `GET` | `/api/user` | Current user for the active guard. |"] : []);
3292
3345
  }
3293
3346
  if (authNeedsUsers(layers.auth)) {
3294
3347
  rows.push("| `GET` | `/api/v1/auth/csrf` | Issues the CSRF cookie and JSON token for unauthenticated writes. |");
@@ -3297,9 +3350,13 @@ function renderApiDocs(projectName, layers) {
3297
3350
  if (!authUsesToken(layers.auth))
3298
3351
  rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` sets the session cookie and returns `{ ok: true }`. Requires CSRF. |", "| `GET` | `/api/v1/auth/me` | Current user from the session cookie. |");
3299
3352
  }
3300
- if (layers.extras.emailVerification && (authUsesToken(layers.auth) || authUsesJwt(layers.auth))) {
3353
+ if (layers.extras.emailVerification && authNeedsUsers(layers.auth)) {
3301
3354
  rows.push("| `POST` | `/api/v1/auth/verify-email` | Consumes the signed verification token; requires CSRF. |");
3302
3355
  }
3356
+ if (authUsesCookie(layers.auth) && layers.extras.emailVerification)
3357
+ rows.push("| `POST` | `/api/v1/auth/verification-notification` | Authenticated owner resend; verification is not required. Requires CSRF. |");
3358
+ if (authUsesCookie(layers.auth) && layers.extras.mfa)
3359
+ rows.push("| `POST` | `/api/v1/auth/confirm-password` | Verify the current password and set an epoch-bound confirmation cookie. Requires verified session and CSRF. |", "| `GET` | `/api/v1/auth/mfa` | Returns a fresh proposed `{ secret, otpauth }`; requires verified session. Does not enable MFA. |", "| `POST` | `/api/v1/auth/mfa` | `{ secret, code }` enables MFA and returns `{ recoveryCodes }` once. Requires verified session, password confirmation and CSRF; revokes prior credentials. Login again with `mfa_code`. |");
3303
3360
  if (layers.extras.metrics) {
3304
3361
  rows.push("| `GET` | `/metrics` | Prometheus text. Production requires `Authorization: Bearer <METRICS_TOKEN>`. |");
3305
3362
  }
@@ -3479,7 +3536,7 @@ Optional development demo accounts: run \`bun run db:seed:demo\` explicitly afte
3479
3536
  - \`admin@example.test\` (admin)
3480
3537
  ` : `
3481
3538
  Header auth is on for local use. Send \`x-authenticated-user-id\` (and optional \`x-authenticated-user-role\`). Production must set \`AUTH_DEV_HEADERS=false\`.
3482
- `}${authUsesCookie(layers.auth) ? `
3539
+ `}${authUsesCookie(layers.auth) && (layers.frontend === "server-htmx" || layers.frontend === "hybrid") ? `
3483
3540
  HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
3484
3541
 
3485
3542
  - Welcome: \`/\`
@@ -3489,6 +3546,10 @@ HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
3489
3546
  - Reset password: signed \`/reset-password\` (mail log when \`MAIL_DRIVER=log\`)
3490
3547
  ${layers.extras.emailVerification ? "- Verify email: `/email/verify`\n" : ""}${layers.extras.mfa ? "- MFA challenge: `/login/mfa` and setup: `/account/mfa`\n" : ""}${layers.extras.oauthGithub ? "- GitHub: `/auth/github` (needs `FEATURE_OAUTH=true`). Failures on the callback are JSON, not the login page. State is the signed query value from `createOAuthState()`, not `createOAuthStateCookie()`.\n" : ""}${layers.extras.oidc ? "- OIDC: `/auth/oidc` (needs `FEATURE_OAUTH=true` plus `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`; otherwise the login link stays hidden and the route is 404). PKCE cookie `oidc_pkce`. Callback failures are JSON, not the login page.\n" : ""}
3491
3548
  Cookie name is \`strata_session\`. Forms send CSRF as \`_token\`.
3549
+ ` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react") ? `
3550
+ JSON cookie account flows: fetch \`GET /api/v1/auth/csrf\`, retain the cookie and send \`X-CSRF-Token\` on writes (browser clients use credentials). Register through \`POST /api/v1/auth/register\` (neutral 201), login through \`POST /api/v1/auth/login\` (session cookie), and read \`GET /api/v1/auth/me\`. Reset through \`POST /api/v1/auth/forgot-password\` then signed \`POST /api/v1/auth/reset-password\` with \`{ password }\`.
3551
+ ${layers.extras.emailVerification ? "Verify through signed `POST /api/v1/auth/verify-email`; authenticated unverified owners resend through `POST /api/v1/auth/verification-notification`.\n" : ""}${layers.extras.mfa ? "MFA setup: `GET /api/v1/auth/mfa`, confirm the current password through `POST /api/v1/auth/confirm-password`, then submit `{ secret, code }` to `POST /api/v1/auth/mfa`. Store the returned recovery codes safely; enrollment revokes credentials. Login again with `{ email, password, mfa_code }` using a TOTP or one-use recovery code. Missing code returns JSON 401 `mfa_required`.\n" : ""}
3552
+ These routes return JSON, not account pages. The client owns account forms and handling the signed mail URL: submit to its unchanged path/query, with CSRF; opening the URL with GET does not consume a token. No HTML registration/reset page or automatic login is generated for these modes. All auth JSON is private/no-store. API docs list routes; the SPA scaffold is an example client, not a complete account-management UI.
3492
3553
  ` : ""}${authUsesToken(layers.auth) ? `
3493
3554
  Opaque token login: \`POST /api/v1/auth/login\` with \`{ "email", "password" }\`. Register: \`POST /api/v1/auth/register\`. Forgot/reset: \`POST /api/v1/auth/forgot-password\` and signed \`POST /api/v1/auth/reset-password\`. Send \`Authorization: Bearer\` after login.
3494
3555
  ` : ""}${authUsesJwt(layers.auth) ? `
@@ -12,9 +12,9 @@
12
12
  "check": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@getstrata/bootstrap": "^2.2.43",
16
- "@getstrata/cli": "^2.2.43",
17
- "@getstrata/core": "^2.2.43",
15
+ "@getstrata/bootstrap": "^2.2.44",
16
+ "@getstrata/cli": "^2.2.44",
17
+ "@getstrata/core": "^2.2.44",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/starter",
3
- "version": "2.2.43",
3
+ "version": "2.2.44",
4
4
  "description": "Interactive create-strata wizard. Choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",