@getstrata/starter 2.2.42 → 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 +159 -94
- package/dist/templates/package.json +3 -3
- package/package.json +1 -1
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;
|
|
@@ -1175,7 +1172,9 @@ function renderAuthModule(layers) {
|
|
|
1175
1172
|
const oidc = Boolean(layers.extras.oidc && cookie);
|
|
1176
1173
|
const mfa = Boolean(layers.extras.mfa && cookie);
|
|
1177
1174
|
const verify = Boolean(layers.extras.emailVerification);
|
|
1178
|
-
const
|
|
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;
|
|
1179
1178
|
const tenantInsert = usesTenantTable(layers.tenancy);
|
|
1180
1179
|
const tenantCreateField = tenantInsert ? `
|
|
1181
1180
|
tenant_id: currentTenantId(),` : "";
|
|
@@ -1202,27 +1201,28 @@ function renderAuthModule(layers) {
|
|
|
1202
1201
|
imports.push(`import { appUrl } from "@getstrata/core/runtime/appKeyPrefix";`);
|
|
1203
1202
|
}
|
|
1204
1203
|
}
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
}
|
|
1208
|
-
if (jsonApi) {
|
|
1204
|
+
imports.push(`import { ConflictError } from "@getstrata/core/errors/http";`);
|
|
1205
|
+
if (bearerApi) {
|
|
1209
1206
|
imports.push(`import { AuthManager } from "@getstrata/core/auth/guard";`);
|
|
1210
1207
|
}
|
|
1211
1208
|
if (authUsesJwt(layers.auth)) {
|
|
1212
1209
|
imports.push(`import { jwtTtlSeconds, signJwt } from "@getstrata/core/auth/jwt";`);
|
|
1213
1210
|
}
|
|
1214
|
-
imports.push(`import { runInTransaction } from "@getstrata/core/database/transaction";`);
|
|
1211
|
+
imports.push(`import { afterCommit, runInTransaction } from "@getstrata/core/database/transaction";`);
|
|
1215
1212
|
imports.push(`import { hashPassword, verifyPassword } from "@getstrata/core/auth/password";`);
|
|
1216
1213
|
imports.push(`import { AUTH_ONE_TIME_PURPOSES, consumeOneTimeToken, generateOneTimeToken, hashOneTimeToken, revokeUserSessions as revokeStoredUserSessions } from "@getstrata/core/auth/oneTimeToken";`);
|
|
1217
1214
|
imports.push(`import { completePasswordLogin, persistConsumedRecoveryHash } from "@getstrata/core/auth/passwordLogin";`);
|
|
1218
1215
|
if (mfa) {
|
|
1219
1216
|
imports.push(`import { createPasswordConfirmCookie } from "@getstrata/core/auth/passwordConfirmCookie";`);
|
|
1220
1217
|
}
|
|
1218
|
+
if (mfa && jsonCookieAccounts) {
|
|
1219
|
+
imports.push(`import { createRequirePasswordConfirmMiddleware } from "@getstrata/core/http/requirePasswordConfirmMiddleware";`, `import { withMiddleware } from "@getstrata/core/http/routeMiddleware";`);
|
|
1220
|
+
}
|
|
1221
1221
|
imports.push(`import { emailRule, minLength, required, stringRule, validateObject } from "@getstrata/core/validation/rules";`);
|
|
1222
1222
|
imports.push(`import { parseJsonBody } from "@getstrata/core/http/validation";`);
|
|
1223
|
+
imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
|
|
1223
1224
|
if (authUsesToken(layers.auth)) {
|
|
1224
1225
|
imports.push(`import { hashApiToken } from "@getstrata/core/auth/tokenHash";`);
|
|
1225
|
-
imports.push(`import { sqlTimestamp } from "@getstrata/core/database/dialect";`);
|
|
1226
1226
|
imports.push(`import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";`);
|
|
1227
1227
|
}
|
|
1228
1228
|
if (mfa) {
|
|
@@ -1235,7 +1235,7 @@ function renderAuthModule(layers) {
|
|
|
1235
1235
|
}
|
|
1236
1236
|
imports.push(oidc ? `import { clearOidcPkceCookie, createOAuthState, readOidcPkceCookie, sealOidcPkceCookie, verifyOAuthState } from "@getstrata/core/security/oauthState";` : `import { createOAuthState, verifyOAuthState } from "@getstrata/core/security/oauthState";`);
|
|
1237
1237
|
}
|
|
1238
|
-
if (
|
|
1238
|
+
if (bearerApi || cookie) {
|
|
1239
1239
|
imports.push(`import { privateJsonResponse, withErrorHandling } from "@getstrata/core/http/response";`);
|
|
1240
1240
|
imports.push(`import { resolveCsrfTokenForRequest } from "@getstrata/core/http/csrfToken";`);
|
|
1241
1241
|
}
|
|
@@ -1309,7 +1309,7 @@ async function runAuthWrite<T>(identifier: string | number, callback: () => Prom
|
|
|
1309
1309
|
return await runWithMigrationBypassForIdentifier(identifier, callback);
|
|
1310
1310
|
}
|
|
1311
1311
|
|
|
1312
|
-
async function
|
|
1312
|
+
async function prepareSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
|
|
1313
1313
|
const issued = generateOneTimeToken();
|
|
1314
1314
|
const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
|
|
1315
1315
|
await runAuthWrite(userId, async () => {
|
|
@@ -1317,15 +1317,34 @@ async function issueSignedAuthMail(to: string, subject: string, path: string, pu
|
|
|
1317
1317
|
purpose,
|
|
1318
1318
|
user_id: userId,
|
|
1319
1319
|
token_hash: issued.hash,
|
|
1320
|
-
expires_at: expiresAt
|
|
1320
|
+
expires_at: sqlTimestamp(expiresAt),
|
|
1321
1321
|
});
|
|
1322
1322
|
});
|
|
1323
1323
|
const link = absoluteTemporarySignedUrl(path, 3600, { ...extra, token: issued.plain });
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1324
|
+
return { to, subject, body: \`\${subject}\\n\\n\${link}\\n\` };
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
async function issueSignedAuthMail(to: string, subject: string, path: string, purpose: string, userId: number, extra: Record<string, string> = {}) {
|
|
1328
|
+
const message = await prepareSignedAuthMail(to, subject, path, purpose, userId, extra);
|
|
1329
|
+
await afterCommit(() => mailer().send(message));
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
async function createRegistration(credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
|
|
1333
|
+
const { email } = credentials;
|
|
1334
|
+
try {
|
|
1335
|
+
return await runAuthWrite(email, () => runInTransaction(async () => {
|
|
1336
|
+
${verify ? "const created = " : ""}await User.create({
|
|
1337
|
+
...credentials,
|
|
1338
|
+
is_admin: false,${tenantCreateField}
|
|
1339
|
+
});
|
|
1340
|
+
${verify ? `return prepareSignedAuthMail(email, "Verify your email", verificationPath, AUTH_ONE_TIME_PURPOSES.emailVerify, Number(created.get("id")), { id: String(created.get("id")) });` : ""}
|
|
1341
|
+
}));
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
// The failed transaction/savepoint is already rolled back before readback.
|
|
1344
|
+
// Only an actual account race is neutral; unrelated persistence failures propagate.
|
|
1345
|
+
if (!(error instanceof ConflictError) || !(await starterAuthDirectory.findByEmail(email))) throw error;
|
|
1346
|
+
return undefined;
|
|
1347
|
+
}
|
|
1329
1348
|
}
|
|
1330
1349
|
|
|
1331
1350
|
async function consumeSignedAuthToken(request: Request, purpose: string): Promise<number | null> {
|
|
@@ -1350,7 +1369,7 @@ async function completeSignedEmailVerification(request: Request): Promise<boolea
|
|
|
1350
1369
|
await runAuthWrite(userId, async () => {
|
|
1351
1370
|
const user = await User.find(userId);
|
|
1352
1371
|
if (!user) throw new Error("Verification account no longer exists.");
|
|
1353
|
-
await user.update({ email_verified_at:
|
|
1372
|
+
await user.update({ email_verified_at: sqlTimestamp() });
|
|
1354
1373
|
});
|
|
1355
1374
|
return true;
|
|
1356
1375
|
});
|
|
@@ -1487,7 +1506,7 @@ async function completeBrowserSsoLogin(
|
|
|
1487
1506
|
});
|
|
1488
1507
|
}),
|
|
1489
1508
|
},` : "";
|
|
1490
|
-
const jsonRegister =
|
|
1509
|
+
const jsonRegister = jsonAccounts ? `
|
|
1491
1510
|
"/api/v1/auth/register": {
|
|
1492
1511
|
POST: kernel.wrap("api", kernel.wrapRegister(withErrorHandling(async (request) => {
|
|
1493
1512
|
if ((process.env.FEATURE_REGISTRATION ?? "true") === "false") {
|
|
@@ -1500,18 +1519,9 @@ async function completeBrowserSsoLogin(
|
|
|
1500
1519
|
return privateJsonResponse({ ok: true }, { status: 201 });
|
|
1501
1520
|
}
|
|
1502
1521
|
const hashed = await hashPassword(password);
|
|
1503
|
-
await
|
|
1504
|
-
|
|
1505
|
-
|
|
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
|
-
}` : ""}
|
|
1522
|
+
${verify ? "const verificationMail = " : ""}await createRegistration({ name, email, password: hashed }${verify ? ', "/api/v1/auth/verify-email"' : ""});
|
|
1523
|
+
${verify ? `// SMTP follows the outermost commit, including request RLS.
|
|
1524
|
+
if (verificationMail) await afterCommit(() => mailer().send(verificationMail));` : ""}
|
|
1515
1525
|
return privateJsonResponse({ ok: true }, { status: 201 });
|
|
1516
1526
|
}))),
|
|
1517
1527
|
},` : "";
|
|
@@ -1544,7 +1554,7 @@ async function completeBrowserSsoLogin(
|
|
|
1544
1554
|
});
|
|
1545
1555
|
}))),
|
|
1546
1556
|
},` : "";
|
|
1547
|
-
const apiUser =
|
|
1557
|
+
const apiUser = bearerApi ? `
|
|
1548
1558
|
"/api/user": {
|
|
1549
1559
|
GET: kernel.wrapApi(async (request) => {
|
|
1550
1560
|
const user = await dependencies.container.resolve<AuthManager>(CORE_AUTH_TOKEN).requireUser(request);
|
|
@@ -1560,7 +1570,7 @@ async function completeBrowserSsoLogin(
|
|
|
1560
1570
|
` : ""}return payload;
|
|
1561
1571
|
})),
|
|
1562
1572
|
},` : "";
|
|
1563
|
-
const jsonPassword =
|
|
1573
|
+
const jsonPassword = jsonAccounts ? `
|
|
1564
1574
|
"/api/v1/auth/forgot-password": {
|
|
1565
1575
|
POST: kernel.wrap("api", withErrorHandling(async (request) => {
|
|
1566
1576
|
const email = await parseJsonBody(request, parseForgotPasswordEmail);
|
|
@@ -1573,7 +1583,7 @@ async function completeBrowserSsoLogin(
|
|
|
1573
1583
|
},
|
|
1574
1584
|
"/api/v1/auth/reset-password": {
|
|
1575
1585
|
POST: kernel.wrap("api", kernel.wrapSigned(withErrorHandling(async (request) => {
|
|
1576
|
-
const body
|
|
1586
|
+
const body = await parseJsonBody(request, (payload) => payload);
|
|
1577
1587
|
const password = typeof body === "object" && body !== null && "password" in body ? body.password : undefined;
|
|
1578
1588
|
if (!(await completeSignedPasswordReset(request, password))) {
|
|
1579
1589
|
return privateJsonResponse({ error: "Invalid or expired reset link." }, { status: 403 });
|
|
@@ -1581,7 +1591,7 @@ async function completeBrowserSsoLogin(
|
|
|
1581
1591
|
return privateJsonResponse({ ok: true });
|
|
1582
1592
|
}))),
|
|
1583
1593
|
},` : "";
|
|
1584
|
-
const jsonVerify =
|
|
1594
|
+
const jsonVerify = jsonAccounts && verify ? `
|
|
1585
1595
|
"/api/v1/auth/verify-email": {
|
|
1586
1596
|
POST: kernel.wrap("api", kernel.wrapSigned(withErrorHandling(async (request) => {
|
|
1587
1597
|
if (!(await completeSignedEmailVerification(request))) {
|
|
@@ -1590,13 +1600,53 @@ async function completeBrowserSsoLogin(
|
|
|
1590
1600
|
return privateJsonResponse({ ok: true });
|
|
1591
1601
|
}))),
|
|
1592
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
|
+
},` : ""}` : "";
|
|
1593
1643
|
const csrfRoute = `
|
|
1594
1644
|
"/api/v1/auth/csrf": {
|
|
1595
1645
|
GET: kernel.wrap("api", withErrorHandling(async (request) => {
|
|
1596
1646
|
return privateJsonResponse({ token: resolveCsrfTokenForRequest(request) });
|
|
1597
1647
|
})),
|
|
1598
1648
|
},`;
|
|
1599
|
-
const cookieJsonAuth = cookie && !
|
|
1649
|
+
const cookieJsonAuth = cookie && !bearerApi ? `
|
|
1600
1650
|
"/api/v1/auth/login": {
|
|
1601
1651
|
POST: kernel.wrap("api", kernel.wrapLogin(withErrorHandling(async (request) => {
|
|
1602
1652
|
const { email, password, mfa_code } = await parseJsonBody(request, parseLoginCredentials);
|
|
@@ -1770,9 +1820,9 @@ async function completeBrowserSsoLogin(
|
|
|
1770
1820
|
return login;
|
|
1771
1821
|
})),
|
|
1772
1822
|
},` : "";
|
|
1773
|
-
const apiRoutes =
|
|
1823
|
+
const apiRoutes = bearerApi || cookie ? `
|
|
1774
1824
|
routes({ kernel, dependencies }) {
|
|
1775
|
-
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}
|
|
1776
1826
|
};
|
|
1777
1827
|
},` : "";
|
|
1778
1828
|
const mfaLoginBranch = `const mfaResult = completePasswordLogin(user, { mfaCode: mfa_code });
|
|
@@ -1789,11 +1839,7 @@ async function completeBrowserSsoLogin(
|
|
|
1789
1839
|
redirectTo("/login"),
|
|
1790
1840
|
{ level: "success", message: "If that email is available, continue from the sign-in page." },
|
|
1791
1841
|
);`;
|
|
1792
|
-
const verifyRegisterBranch =
|
|
1793
|
-
return flashResponse(
|
|
1794
|
-
redirectTo("/login"),
|
|
1795
|
-
{ level: "success", message: "If that email is available, continue from the sign-in page." },
|
|
1796
|
-
);` : `return flashResponse(
|
|
1842
|
+
const verifyRegisterBranch = `return flashResponse(
|
|
1797
1843
|
redirectTo("/login"),
|
|
1798
1844
|
{ level: "success", message: "If that email is available, continue from the sign-in page." },
|
|
1799
1845
|
);`;
|
|
@@ -1844,17 +1890,10 @@ async function completeBrowserSsoLogin(
|
|
|
1844
1890
|
${registerSuccessExisting}
|
|
1845
1891
|
}
|
|
1846
1892
|
const hashed = await hashPassword(password);
|
|
1847
|
-
await
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
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}
|
|
1893
|
+
${verify ? "const verificationMail = " : ""}await createRegistration({ name, email, password: hashed }${verify ? ', "/email/verify"' : ""});
|
|
1894
|
+
${verify ? `// SMTP follows the outermost commit, including request RLS.
|
|
1895
|
+
if (verificationMail) await afterCommit(() => mailer().send(verificationMail));` : ""}
|
|
1896
|
+
${verifyRegisterBranch}
|
|
1858
1897
|
},
|
|
1859
1898
|
async (request) =>
|
|
1860
1899
|
views.render("register.eta", { layout: { title: "Create account" }, errors: { form: "Too many registration attempts. Try again shortly." }, name: "", email: "", password: "" }, { request, status: 429 }),
|
|
@@ -2012,30 +2051,7 @@ async function completeBrowserSsoLogin(
|
|
|
2012
2051
|
otpauth: buildOtpauthUrl({ secret, account: "user", issuer: process.env.APP_NAME ?? "Strata" }),
|
|
2013
2052
|
}, { request });
|
|
2014
2053
|
}
|
|
2015
|
-
const recoveryCodes =
|
|
2016
|
-
const stored = protectMfaSecret(secret);
|
|
2017
|
-
const previous = await runAuthWrite(Number(user.id), () => User.find(Number(user.id)));
|
|
2018
|
-
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.");
|
|
2019
|
-
await runInTransaction(async () => {
|
|
2020
|
-
await runAuthWrite(Number(user.id), async () => {
|
|
2021
|
-
// Trusted, pre-protected security fields: atomically replace only the state we read.
|
|
2022
|
-
const changed = await previous.getRepository().updateWhere({
|
|
2023
|
-
mfa_secret: stored,
|
|
2024
|
-
mfa_enabled: true,
|
|
2025
|
-
mfa_recovery_codes: JSON.stringify(recoveryCodes.map((item) => hashRecoveryCode(item))),
|
|
2026
|
-
}, { where: {
|
|
2027
|
-
id: Number(user.id),
|
|
2028
|
-
is_active: previous.get("is_active"),
|
|
2029
|
-
auth_version: previous.get("auth_version"),
|
|
2030
|
-
mfa_enabled: previous.get("mfa_enabled"),
|
|
2031
|
-
mfa_secret: previous.get("mfa_secret"),
|
|
2032
|
-
mfa_recovery_codes: previous.get("mfa_recovery_codes"),
|
|
2033
|
-
session_valid_after: previous.get("session_valid_after"),
|
|
2034
|
-
} });
|
|
2035
|
-
if (changed !== 1) throw new ConflictError("MFA configuration changed. Reload and confirm again.");
|
|
2036
|
-
});
|
|
2037
|
-
await revokeUserSessions(Number(user.id));
|
|
2038
|
-
});
|
|
2054
|
+
const recoveryCodes = await enrollMfa(user, secret);
|
|
2039
2055
|
return views.render("mfa-setup.eta", {
|
|
2040
2056
|
layout: { title: "MFA" },
|
|
2041
2057
|
errors: {},
|
|
@@ -2051,6 +2067,37 @@ async function completeBrowserSsoLogin(
|
|
|
2051
2067
|
return `${imports.join(`
|
|
2052
2068
|
`)}
|
|
2053
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
|
+
|
|
2054
2101
|
const authModule: AppModule = {
|
|
2055
2102
|
name: "auth",
|
|
2056
2103
|
order: 2,${apiRoutes}${cookieRoutes}
|
|
@@ -3179,9 +3226,9 @@ function renderPackageJson(projectName, options = {}) {
|
|
|
3179
3226
|
"@getstrata/cli": "workspace:*",
|
|
3180
3227
|
"@getstrata/core": "workspace:*"
|
|
3181
3228
|
} : {
|
|
3182
|
-
"@getstrata/bootstrap": "^2.2.
|
|
3183
|
-
"@getstrata/cli": "^2.2.
|
|
3184
|
-
"@getstrata/core": "^2.2.
|
|
3229
|
+
"@getstrata/bootstrap": "^2.2.44",
|
|
3230
|
+
"@getstrata/cli": "^2.2.44",
|
|
3231
|
+
"@getstrata/core": "^2.2.44"
|
|
3185
3232
|
};
|
|
3186
3233
|
coreDeps.eta = "^4.6.0";
|
|
3187
3234
|
if (options.layers?.database === "mysql") {
|
|
@@ -3287,16 +3334,29 @@ function renderSupportingToolsReadme(layers) {
|
|
|
3287
3334
|
function renderApiDocs(projectName, layers) {
|
|
3288
3335
|
const rows = ["| Method | Path | Notes |", "| --- | --- | --- |"];
|
|
3289
3336
|
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
3337
|
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`. |", "| `
|
|
3338
|
+
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
3339
|
}
|
|
3294
3340
|
if (authUsesJwt(layers.auth)) {
|
|
3295
3341
|
rows.push("| `POST` | `/api/auth/token` | Mints a short-lived JWT. Not an HTML session. Requires CSRF like JSON login. |");
|
|
3296
3342
|
}
|
|
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. |"] : []);
|
|
3345
|
+
}
|
|
3297
3346
|
if (authNeedsUsers(layers.auth)) {
|
|
3298
|
-
rows.push("| `
|
|
3347
|
+
rows.push("| `GET` | `/api/v1/auth/csrf` | Issues the CSRF cookie and JSON token for unauthenticated writes. |");
|
|
3299
3348
|
}
|
|
3349
|
+
if (authUsesCookie(layers.auth)) {
|
|
3350
|
+
if (!authUsesToken(layers.auth))
|
|
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. |");
|
|
3352
|
+
}
|
|
3353
|
+
if (layers.extras.emailVerification && authNeedsUsers(layers.auth)) {
|
|
3354
|
+
rows.push("| `POST` | `/api/v1/auth/verify-email` | Consumes the signed verification token; requires CSRF. |");
|
|
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`. |");
|
|
3300
3360
|
if (layers.extras.metrics) {
|
|
3301
3361
|
rows.push("| `GET` | `/metrics` | Prometheus text. Production requires `Authorization: Bearer <METRICS_TOKEN>`. |");
|
|
3302
3362
|
}
|
|
@@ -3312,10 +3372,10 @@ function renderApiDocs(projectName, layers) {
|
|
|
3312
3372
|
if (layers.extras.oidc && authUsesCookie(layers.auth)) {
|
|
3313
3373
|
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
3374
|
}
|
|
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.`;
|
|
3375
|
+
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
3376
|
return `# ${projectName} API
|
|
3317
3377
|
|
|
3318
|
-
\`FRONTEND_MODE=${layers.frontend}\`. ${layers.frontend === "api" ? "
|
|
3378
|
+
\`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
3379
|
|
|
3320
3380
|
## Routes this app serves today
|
|
3321
3381
|
|
|
@@ -3476,7 +3536,7 @@ Optional development demo accounts: run \`bun run db:seed:demo\` explicitly afte
|
|
|
3476
3536
|
- \`admin@example.test\` (admin)
|
|
3477
3537
|
` : `
|
|
3478
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\`.
|
|
3479
|
-
`}${authUsesCookie(layers.auth) ? `
|
|
3539
|
+
`}${authUsesCookie(layers.auth) && (layers.frontend === "server-htmx" || layers.frontend === "hybrid") ? `
|
|
3480
3540
|
HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
|
|
3481
3541
|
|
|
3482
3542
|
- Welcome: \`/\`
|
|
@@ -3486,6 +3546,10 @@ HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
|
|
|
3486
3546
|
- Reset password: signed \`/reset-password\` (mail log when \`MAIL_DRIVER=log\`)
|
|
3487
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" : ""}
|
|
3488
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.
|
|
3489
3553
|
` : ""}${authUsesToken(layers.auth) ? `
|
|
3490
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.
|
|
3491
3555
|
` : ""}${authUsesJwt(layers.auth) ? `
|
|
@@ -4040,7 +4104,7 @@ function renderMigrateTs(layers) {
|
|
|
4040
4104
|
const tenancyOn = usesTenantTable(layers.tenancy);
|
|
4041
4105
|
const ph = layers.database === "postgres";
|
|
4042
4106
|
const verifyOn = layers.extras.emailVerification && authNeedsUsers(layers.auth);
|
|
4043
|
-
const verifiedNow =
|
|
4107
|
+
const verifiedNow = "sqlTimestamp()";
|
|
4044
4108
|
const seedTenant = tenancyOn ? `
|
|
4045
4109
|
const [{ count: tenantCount }] = await sql.unsafe<{ count: string | number }>(
|
|
4046
4110
|
"SELECT COUNT(*) AS count FROM tenant",
|
|
@@ -4074,7 +4138,8 @@ function renderMigrateTs(layers) {
|
|
|
4074
4138
|
const rlsBypassImport = layers.tenancy === "rls" && layers.database === "postgres" ? `import { runWithMigrationBypass } from "@getstrata/core/tenant/databaseTenantContext";
|
|
4075
4139
|
` : "";
|
|
4076
4140
|
const bindSql = seedTenant || layers.tenancy === "rls" && layers.database === "postgres" ? ` const sql = getSql();
|
|
4077
|
-
` :
|
|
4141
|
+
` : ` getSql();
|
|
4142
|
+
`;
|
|
4078
4143
|
const seedOpen = layers.tenancy === "rls" && layers.database === "postgres" ? ` await runWithMigrationBypass(async () => {
|
|
4079
4144
|
` : "";
|
|
4080
4145
|
const seedClose = layers.tenancy === "rls" && layers.database === "postgres" ? `
|
|
@@ -4082,11 +4147,11 @@ function renderMigrateTs(layers) {
|
|
|
4082
4147
|
const noteCreate = tenancyOn ? `await Note.create({ body: "Welcome to Strata!", tenant_id: 1 });` : `await Note.create({ body: "Welcome to Strata!" });`;
|
|
4083
4148
|
const userImport = authNeedsUsers(layers.auth) ? `import { User } from "../models/User.ts";
|
|
4084
4149
|
` : "";
|
|
4085
|
-
const
|
|
4086
|
-
const databaseImport = needsSqlClient ? `import { closeDatabase, getSql } from "../bootstrap/database.ts";
|
|
4087
|
-
` : `import { closeDatabase } from "../bootstrap/database.ts";
|
|
4150
|
+
const databaseImport = `import { closeDatabase, getSql } from "../bootstrap/database.ts";
|
|
4088
4151
|
`;
|
|
4089
|
-
|
|
4152
|
+
const timestampImport = verifyOn ? `import { sqlTimestamp } from "@getstrata/core/database/dialect";
|
|
4153
|
+
` : "";
|
|
4154
|
+
return `${hashImport}${timestampImport}${rlsBypassImport}${ensureImport(layers)}${databaseImport}import { migrateDatabase } from "@getstrata/core/database/migrations";
|
|
4090
4155
|
import { Note } from "../models/Note.ts";
|
|
4091
4156
|
${userImport}import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
|
|
4092
4157
|
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.
|
|
16
|
-
"@getstrata/cli": "^2.2.
|
|
17
|
-
"@getstrata/core": "^2.2.
|
|
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": {
|