@getstrata/starter 2.2.42 → 2.2.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -116,9 +116,6 @@ function htmlAuthKit(auth) {
116
116
  function needsFrontendBuild(frontend) {
117
117
  return frontend === "spa-react" || frontend === "hybrid";
118
118
  }
119
- function nowTimestampLiteral(database) {
120
- return database === "mysql" ? `new Date().toISOString().slice(0, 19).replace("T", " ")` : "new Date().toISOString()";
121
- }
122
119
  function extraApplies(extra, auth) {
123
120
  if (extra === "metrics" || extra === "billing" || extra === "webhooks") {
124
121
  return true;
@@ -1202,16 +1199,14 @@ function renderAuthModule(layers) {
1202
1199
  imports.push(`import { appUrl } from "@getstrata/core/runtime/appKeyPrefix";`);
1203
1200
  }
1204
1201
  }
1205
- if (mfa) {
1206
- imports.push(`import { ConflictError } from "@getstrata/core/errors/http";`);
1207
- }
1202
+ imports.push(`import { ConflictError } from "@getstrata/core/errors/http";`);
1208
1203
  if (jsonApi) {
1209
1204
  imports.push(`import { AuthManager } from "@getstrata/core/auth/guard";`);
1210
1205
  }
1211
1206
  if (authUsesJwt(layers.auth)) {
1212
1207
  imports.push(`import { jwtTtlSeconds, signJwt } from "@getstrata/core/auth/jwt";`);
1213
1208
  }
1214
- imports.push(`import { runInTransaction } from "@getstrata/core/database/transaction";`);
1209
+ imports.push(`import { afterCommit, runInTransaction } from "@getstrata/core/database/transaction";`);
1215
1210
  imports.push(`import { hashPassword, verifyPassword } from "@getstrata/core/auth/password";`);
1216
1211
  imports.push(`import { AUTH_ONE_TIME_PURPOSES, consumeOneTimeToken, generateOneTimeToken, hashOneTimeToken, revokeUserSessions as revokeStoredUserSessions } from "@getstrata/core/auth/oneTimeToken";`);
1217
1212
  imports.push(`import { completePasswordLogin, persistConsumedRecoveryHash } from "@getstrata/core/auth/passwordLogin";`);
@@ -1220,9 +1215,9 @@ function renderAuthModule(layers) {
1220
1215
  }
1221
1216
  imports.push(`import { emailRule, minLength, required, stringRule, validateObject } from "@getstrata/core/validation/rules";`);
1222
1217
  imports.push(`import { parseJsonBody } from "@getstrata/core/http/validation";`);
1218
+ imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
1223
1219
  if (authUsesToken(layers.auth)) {
1224
1220
  imports.push(`import { hashApiToken } from "@getstrata/core/auth/tokenHash";`);
1225
- imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
1226
1221
  imports.push(`import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";`);
1227
1222
  }
1228
1223
  if (mfa) {
@@ -1309,7 +1304,7 @@ async function runAuthWrite<T>(identifier: string | number, callback: () => Prom
1309
1304
  return await runWithMigrationBypassForIdentifier(identifier, callback);
1310
1305
  }
1311
1306
 
1312
- async function issueSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
1307
+ async function prepareSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
1313
1308
  const issued = generateOneTimeToken();
1314
1309
  const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
1315
1310
  await runAuthWrite(userId, async () => {
@@ -1317,15 +1312,34 @@ async function issueSignedAuthMail(to: string, subject: string, path: string, pu
1317
1312
  purpose,
1318
1313
  user_id: userId,
1319
1314
  token_hash: issued.hash,
1320
- expires_at: expiresAt.toISOString(),
1315
+ expires_at: sqlTimestamp(expiresAt),
1321
1316
  });
1322
1317
  });
1323
1318
  const link = absoluteTemporarySignedUrl(path, 3600, { ...extra, token: issued.plain });
1324
- await mailer().send({
1325
- to,
1326
- subject,
1327
- body: \`\${subject}\\n\\n\${link}\\n\`,
1328
- });
1319
+ return { to, subject, body: \`\${subject}\\n\\n\${link}\\n\` };
1320
+ }
1321
+
1322
+ async function issueSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
1323
+ const message = await prepareSignedAuthMail(to, subject, path, purpose, userId, extra);
1324
+ await afterCommit(() => mailer().send(message));
1325
+ }
1326
+
1327
+ async function createRegistration(credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
1328
+ const { email } = credentials;
1329
+ try {
1330
+ return await runAuthWrite(email, () => runInTransaction(async () => {
1331
+ ${verify ? "const created = " : ""}await User.create({
1332
+ ...credentials,
1333
+ is_admin: false,${tenantCreateField}
1334
+ });
1335
+ ${verify ? `return prepareSignedAuthMail(email, "Verify your email", verificationPath, AUTH_ONE_TIME_PURPOSES.emailVerify, Number(created.get("id")), { id: String(created.get("id")) });` : ""}
1336
+ }));
1337
+ } catch (error) {
1338
+ // The failed transaction/savepoint is already rolled back before readback.
1339
+ // Only an actual account race is neutral; unrelated persistence failures propagate.
1340
+ if (!(error instanceof ConflictError) || !(await starterAuthDirectory.findByEmail(email))) throw error;
1341
+ return undefined;
1342
+ }
1329
1343
  }
1330
1344
 
1331
1345
  async function consumeSignedAuthToken(request: Request, purpose: string): Promise<number | null> {
@@ -1350,7 +1364,7 @@ async function completeSignedEmailVerification(request: Request): Promise<boolea
1350
1364
  await runAuthWrite(userId, async () => {
1351
1365
  const user = await User.find(userId);
1352
1366
  if (!user) throw new Error("Verification account no longer exists.");
1353
- await user.update({ email_verified_at: ${nowTimestampLiteral(layers.database)} });
1367
+ await user.update({ email_verified_at: sqlTimestamp() });
1354
1368
  });
1355
1369
  return true;
1356
1370
  });
@@ -1500,18 +1514,9 @@ async function completeBrowserSsoLogin(
1500
1514
  return privateJsonResponse({ ok: true }, { status: 201 });
1501
1515
  }
1502
1516
  const hashed = await hashPassword(password);
1503
- await runAuthWrite(email, async () => {
1504
- await User.create({
1505
- name,
1506
- email,
1507
- password: hashed,
1508
- is_admin: false,${tenantCreateField}
1509
- });
1510
- });
1511
- const created = await starterAuthDirectory.findByEmail?.(email);
1512
- ${verify ? `if (created) {
1513
- await issueSignedAuthMail(email, "Verify your email", "/api/v1/auth/verify-email", AUTH_ONE_TIME_PURPOSES.emailVerify, created.id, { id: String(created.id) });
1514
- }` : ""}
1517
+ ${verify ? "const verificationMail = " : ""}await createRegistration({ name, email, password: hashed }${verify ? ', "/api/v1/auth/verify-email"' : ""});
1518
+ ${verify ? `// SMTP follows the outermost commit, including request RLS.
1519
+ if (verificationMail) await afterCommit(() => mailer().send(verificationMail));` : ""}
1515
1520
  return privateJsonResponse({ ok: true }, { status: 201 });
1516
1521
  }))),
1517
1522
  },` : "";
@@ -1789,11 +1794,7 @@ async function completeBrowserSsoLogin(
1789
1794
  redirectTo("/login"),
1790
1795
  { level: "success", message: "If that email is available, continue from the sign-in page." },
1791
1796
  );`;
1792
- const verifyRegisterBranch = verify ? `await issueSignedAuthMail(email, "Verify your email", "/email/verify", AUTH_ONE_TIME_PURPOSES.emailVerify, insertedId, { id: String(insertedId) });
1793
- return flashResponse(
1794
- redirectTo("/login"),
1795
- { level: "success", message: "If that email is available, continue from the sign-in page." },
1796
- );` : `return flashResponse(
1797
+ const verifyRegisterBranch = `return flashResponse(
1797
1798
  redirectTo("/login"),
1798
1799
  { level: "success", message: "If that email is available, continue from the sign-in page." },
1799
1800
  );`;
@@ -1844,17 +1845,10 @@ async function completeBrowserSsoLogin(
1844
1845
  ${registerSuccessExisting}
1845
1846
  }
1846
1847
  const hashed = await hashPassword(password);
1847
- await runAuthWrite(email, async () => {
1848
- await User.create({
1849
- name,
1850
- email,
1851
- password: hashed,
1852
- is_admin: false,${tenantCreateField}
1853
- });
1854
- });
1855
- ${verify ? `const created = await starterAuthDirectory.findByEmail?.(email);
1856
- const insertedId = created?.id ?? 0;
1857
- ${verifyRegisterBranch}` : verifyRegisterBranch}
1848
+ ${verify ? "const verificationMail = " : ""}await createRegistration({ name, email, password: hashed }${verify ? ', "/email/verify"' : ""});
1849
+ ${verify ? `// SMTP follows the outermost commit, including request RLS.
1850
+ if (verificationMail) await afterCommit(() => mailer().send(verificationMail));` : ""}
1851
+ ${verifyRegisterBranch}
1858
1852
  },
1859
1853
  async (request) =>
1860
1854
  views.render("register.eta", { layout: { title: "Create account" }, errors: { form: "Too many registration attempts. Try again shortly." }, name: "", email: "", password: "" }, { request, status: 429 }),
@@ -3179,9 +3173,9 @@ function renderPackageJson(projectName, options = {}) {
3179
3173
  "@getstrata/cli": "workspace:*",
3180
3174
  "@getstrata/core": "workspace:*"
3181
3175
  } : {
3182
- "@getstrata/bootstrap": "^2.2.42",
3183
- "@getstrata/cli": "^2.2.42",
3184
- "@getstrata/core": "^2.2.42"
3176
+ "@getstrata/bootstrap": "^2.2.43",
3177
+ "@getstrata/cli": "^2.2.43",
3178
+ "@getstrata/core": "^2.2.43"
3185
3179
  };
3186
3180
  coreDeps.eta = "^4.6.0";
3187
3181
  if (options.layers?.database === "mysql") {
@@ -3287,15 +3281,24 @@ function renderSupportingToolsReadme(layers) {
3287
3281
  function renderApiDocs(projectName, layers) {
3288
3282
  const rows = ["| Method | Path | Notes |", "| --- | --- | --- |"];
3289
3283
  rows.push("| `GET` | `/health` | Plain text `ok` (200) when configured database/Redis checks succeed and `notes` is readable (zero rows is still 200). This infrastructure probe runs outside API auth/tenancy admission, never selects a tenant or bypasses RLS, and returns no rows. `degraded` (503) when a dependency or schema check fails. Docker HEALTHCHECK uses this path. |", '| `GET` | `/ready` | JSON from the framework: `{"status":"ready","checks":{"database":"ok","redis":"skipped"}}` (200) or `not_ready` (503). `redis` is `ok` or `error` when `REDIS_URL` is set and `skipped` otherwise. It does not check the schema, so use `/health` as the deploy gate. |');
3290
- rows.push("| `GET` | `/` | Welcome page. Restyle or replace it. |");
3291
3284
  if (authUsesToken(layers.auth)) {
3292
- rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` returns `{ token }`. Requires `GET /api/v1/auth/csrf` then `X-CSRF-Token`. |", "| `POST` | `/api/v1/auth/register` | Creates a user and returns a token. |", "| `GET` | `/api/v1/auth/me` | Requires `Authorization: Bearer <token>`. |");
3285
+ rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` returns `{ token }`. Requires `GET /api/v1/auth/csrf` then `X-CSRF-Token`. |", "| `GET` | `/api/v1/auth/me` | Requires `Authorization: Bearer <token>`. |");
3293
3286
  }
3294
3287
  if (authUsesJwt(layers.auth)) {
3295
3288
  rows.push("| `POST` | `/api/auth/token` | Mints a short-lived JWT. Not an HTML session. Requires CSRF like JSON login. |");
3296
3289
  }
3290
+ if (authUsesToken(layers.auth) || authUsesJwt(layers.auth)) {
3291
+ rows.push("| `POST` | `/api/v1/auth/register` | Returns neutral `{ ok: true }` (201); sign in separately. |", "| `POST` | `/api/v1/auth/forgot-password` | Sends a signed reset link through the mail driver. |", "| `POST` | `/api/v1/auth/reset-password` | Consumes the signed link. |", "| `GET` | `/api/user` | Current user for the active guard. |");
3292
+ }
3297
3293
  if (authNeedsUsers(layers.auth)) {
3298
- rows.push("| `POST` | `/api/v1/auth/forgot-password` | Sends a signed reset link through the mail driver. |", "| `POST` | `/api/v1/auth/reset-password` | Consumes the signed link. |", "| `GET` | `/api/user` | Current user for the active guard. |");
3294
+ rows.push("| `GET` | `/api/v1/auth/csrf` | Issues the CSRF cookie and JSON token for unauthenticated writes. |");
3295
+ }
3296
+ if (authUsesCookie(layers.auth)) {
3297
+ if (!authUsesToken(layers.auth))
3298
+ rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` sets the session cookie and returns `{ ok: true }`. Requires CSRF. |", "| `GET` | `/api/v1/auth/me` | Current user from the session cookie. |");
3299
+ }
3300
+ if (layers.extras.emailVerification && (authUsesToken(layers.auth) || authUsesJwt(layers.auth))) {
3301
+ rows.push("| `POST` | `/api/v1/auth/verify-email` | Consumes the signed verification token; requires CSRF. |");
3299
3302
  }
3300
3303
  if (layers.extras.metrics) {
3301
3304
  rows.push("| `GET` | `/metrics` | Prometheus text. Production requires `Authorization: Bearer <METRICS_TOKEN>`. |");
@@ -3312,10 +3315,10 @@ function renderApiDocs(projectName, layers) {
3312
3315
  if (layers.extras.oidc && authUsesCookie(layers.auth)) {
3313
3316
  rows.push("| `GET` | `/auth/oidc` | OIDC `createAuthorization()` plus `oidc_pkce` cookie. 404 unless `FEATURE_OAUTH=true`. |", "| `GET` | `/auth/oidc/callback` | Reads PKCE, exchanges the code, JIT user, MFA gate, cookie session. |");
3314
3317
  }
3315
- const authNote = layers.auth === "headers" ? `Auth is \`headers\`. Send \`x-authenticated-user-id\` (and optional \`x-authenticated-user-role\`) for local work and tests. There are no login endpoints and no \`users\` table. Production must set \`AUTH_DEV_HEADERS=false\`, which turns those headers off and leaves you without a guard, so pick another auth layer before you ship.` : authUsesToken(layers.auth) ? `Sign in with \`GET /api/v1/auth/csrf\` then \`POST /api/v1/auth/login\` (send \`X-CSRF-Token\`), then send \`Authorization: Bearer <token>\` on every request. Tokens are stored hashed in \`api_tokens\` and expire after \`API_TOKEN_DEFAULT_EXPIRY_DAYS\` (30 in \`.env.example\`). The response includes \`expires_at\`.` : `Mint a JWT with \`POST /api/auth/token\`, then send \`Authorization: Bearer <jwt>\`. JWTs expire; re-mint rather than refreshing in place.`;
3318
+ const authNote = layers.auth === "headers" ? `Auth is \`headers\`. Send \`x-authenticated-user-id\` (and optional \`x-authenticated-user-role\`) for local work and tests. There are no login endpoints and no \`users\` table. Production must set \`AUTH_DEV_HEADERS=false\`, which turns those headers off and leaves you without a guard, so pick another auth layer before you ship.` : authUsesToken(layers.auth) ? `Sign in with \`GET /api/v1/auth/csrf\` then \`POST /api/v1/auth/login\` (send \`X-CSRF-Token\`), then send \`Authorization: Bearer <token>\` on every request. Tokens are stored hashed in \`api_tokens\` and expire after \`API_TOKEN_DEFAULT_EXPIRY_DAYS\` (30 in \`.env.example\`). The response includes \`expires_at\`.` : authUsesCookie(layers.auth) ? `Sign in with \`GET /api/v1/auth/csrf\` then \`POST /api/v1/auth/login\`; preserve the session and CSRF cookies. The response sets a cookie and returns \`{ ok: true }\`. API mode does not serve HTML login or registration forms.` : `Mint a JWT with \`POST /api/auth/token\`, then send \`Authorization: Bearer <jwt>\`. JWTs expire; re-mint rather than refreshing in place.`;
3316
3319
  return `# ${projectName} API
3317
3320
 
3318
- \`FRONTEND_MODE=${layers.frontend}\`. ${layers.frontend === "api" ? "No server-rendered views beyond the welcome page and no SPA assets." : `HTML is served alongside this API. The SPA is mounted at \`${layers.spaPrefix}\`.`}
3321
+ \`FRONTEND_MODE=${layers.frontend}\`. ${layers.frontend === "api" ? "API-only: no server-rendered welcome/login pages or SPA assets. The root path is not a generated endpoint." : `HTML is served alongside this API. The SPA is mounted at \`${layers.spaPrefix}\`.`}
3319
3322
 
3320
3323
  ## Routes this app serves today
3321
3324
 
@@ -4040,7 +4043,7 @@ function renderMigrateTs(layers) {
4040
4043
  const tenancyOn = usesTenantTable(layers.tenancy);
4041
4044
  const ph = layers.database === "postgres";
4042
4045
  const verifyOn = layers.extras.emailVerification && authNeedsUsers(layers.auth);
4043
- const verifiedNow = nowTimestampLiteral(layers.database);
4046
+ const verifiedNow = "sqlTimestamp()";
4044
4047
  const seedTenant = tenancyOn ? `
4045
4048
  const [{ count: tenantCount }] = await sql.unsafe<{ count: string | number }>(
4046
4049
  "SELECT COUNT(*) AS count FROM tenant",
@@ -4074,7 +4077,8 @@ function renderMigrateTs(layers) {
4074
4077
  const rlsBypassImport = layers.tenancy === "rls" && layers.database === "postgres" ? `import { runWithMigrationBypass } from "@getstrata/core/tenant/databaseTenantContext";
4075
4078
  ` : "";
4076
4079
  const bindSql = seedTenant || layers.tenancy === "rls" && layers.database === "postgres" ? ` const sql = getSql();
4077
- ` : "";
4080
+ ` : ` getSql();
4081
+ `;
4078
4082
  const seedOpen = layers.tenancy === "rls" && layers.database === "postgres" ? ` await runWithMigrationBypass(async () => {
4079
4083
  ` : "";
4080
4084
  const seedClose = layers.tenancy === "rls" && layers.database === "postgres" ? `
@@ -4082,11 +4086,11 @@ function renderMigrateTs(layers) {
4082
4086
  const noteCreate = tenancyOn ? `await Note.create({ body: "Welcome to Strata!", tenant_id: 1 });` : `await Note.create({ body: "Welcome to Strata!" });`;
4083
4087
  const userImport = authNeedsUsers(layers.auth) ? `import { User } from "../models/User.ts";
4084
4088
  ` : "";
4085
- const needsSqlClient = Boolean(seedTenant) || layers.tenancy === "rls" && layers.database === "postgres";
4086
- const databaseImport = needsSqlClient ? `import { closeDatabase, getSql } from "../bootstrap/database.ts";
4087
- ` : `import { closeDatabase } from "../bootstrap/database.ts";
4089
+ const databaseImport = `import { closeDatabase, getSql } from "../bootstrap/database.ts";
4088
4090
  `;
4089
- return `${hashImport}${rlsBypassImport}${ensureImport(layers)}${databaseImport}import { migrateDatabase } from "@getstrata/core/database/migrations";
4091
+ const timestampImport = verifyOn ? `import { sqlTimestamp } from "@getstrata/core/database/dialect";
4092
+ ` : "";
4093
+ return `${hashImport}${timestampImport}${rlsBypassImport}${ensureImport(layers)}${databaseImport}import { migrateDatabase } from "@getstrata/core/database/migrations";
4090
4094
  import { Note } from "../models/Note.ts";
4091
4095
  ${userImport}import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
4092
4096
  import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
@@ -12,9 +12,9 @@
12
12
  "check": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@getstrata/bootstrap": "^2.2.42",
16
- "@getstrata/cli": "^2.2.42",
17
- "@getstrata/core": "^2.2.42",
15
+ "@getstrata/bootstrap": "^2.2.43",
16
+ "@getstrata/cli": "^2.2.43",
17
+ "@getstrata/core": "^2.2.43",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/starter",
3
- "version": "2.2.42",
3
+ "version": "2.2.43",
4
4
  "description": "Interactive create-strata wizard. Choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",