create-terreno-app 57.18.0 → 57.20.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.
package/dist/generate.js CHANGED
@@ -92,8 +92,10 @@ const generateMcpSettings = (args) => {
92
92
  type: "http",
93
93
  url: `${mcpUrl}/mcp`,
94
94
  },
95
+ // Generated apps do not depend on @terreno/mcp, and no npm package is named
96
+ // `terreno-mcp-local`, so bunx must be told which package provides the bin.
95
97
  "terreno-local": {
96
- args: ["terreno-mcp-local"],
98
+ args: ["-p", "@terreno/mcp", "terreno-mcp-local"],
97
99
  command: "bunx",
98
100
  },
99
101
  },
@@ -123,6 +125,7 @@ const generateRootGitignore = () => {
123
125
  const DEPLOYMENT_BASELINE_DOC = "https://github.com/TerrenoLabs/terreno/blob/master/docs/explanation/deployment-baseline.md";
124
126
  const DEPLOY_BACKEND_CLOUD_RUN_DOC = "https://github.com/TerrenoLabs/terreno/blob/master/docs/how-to/deploy-backend-to-cloud-run.md";
125
127
  const BUILD_FOR_WEB_DOC = "https://github.com/TerrenoLabs/terreno/blob/master/docs/how-to/build-for-web.md";
128
+ const SET_UP_TERRENO_MCP_DOC = "https://github.com/TerrenoLabs/terreno/blob/master/docs/how-to/set-up-terreno-mcp.md";
126
129
  const generateRootReadme = (args) => {
127
130
  const { appDisplayName, appName } = args;
128
131
  const dbName = appName.replace(/-/g, "_");
@@ -172,6 +175,10 @@ After backend route changes, regenerate the OpenAPI SDK:
172
175
  cd frontend && bun run sdk
173
176
  \`\`\`
174
177
 
178
+ ## AI-assisted development
179
+
180
+ \`.cursor/mcp.json\` and \`.mcp.json\` connect your editor to the hosted Terreno MCP and \`terreno-mcp-local\` (logs, last error, client state, database); see [Set up Terreno MCP](${SET_UP_TERRENO_MCP_DOC}).
181
+
175
182
  ## Deploy
176
183
 
177
184
  Read the [deployment baseline](${DEPLOYMENT_BASELINE_DOC}) first (MongoDB replica set, auth secrets, \`EXPO_PUBLIC_*\` at build time, \`/health\`, and more).
@@ -211,7 +218,9 @@ Full walkthrough: [Build for web](${BUILD_FOR_WEB_DOC}).
211
218
  };
212
219
  const generateRootDockerfile = () => {
213
220
  return `# Consumer Terreno backend image — builds backend/ only (not the Terreno monorepo).
214
- FROM oven/bun:1-slim AS builder
221
+ # Pin 1.4.4 so the image includes the patched Brotli decoder (CVE-2026-111497).
222
+ # Floating oven/bun:1 can resolve to an affected release.
223
+ FROM oven/bun:1.4.4-slim AS builder
215
224
  WORKDIR /app
216
225
 
217
226
  COPY backend/package.json ./
@@ -219,7 +228,7 @@ RUN bun install
219
228
 
220
229
  COPY backend/ ./
221
230
 
222
- FROM oven/bun:1-slim
231
+ FROM oven/bun:1.4.4-slim
223
232
  WORKDIR /app
224
233
 
225
234
  RUN apt-get update \\
@@ -457,6 +466,8 @@ const generateBackendServer = (args) => {
457
466
  return `import {AdminApp} from "@terreno/admin-backend";
458
467
  import {HealthApp} from "@terreno/api-health";
459
468
  import {
469
+ AccountSecurityApp,
470
+ AuditApp,
460
471
  BetterAuthApp,
461
472
  checkModelsStrict,
462
473
  logger,
@@ -518,6 +529,10 @@ export const start = async (skipListen = false): Promise<express.Application> =>
518
529
  );
519
530
  }
520
531
 
532
+ // Account recovery for operators at /users/:id/security/*. Needs AuditApp: every recovery
533
+ // action writes a security AuditEvent.
534
+ terraApp.register(new AuditApp()).register(new AccountSecurityApp({accessControl: access}));
535
+
521
536
  return terraApp
522
537
  .register(userRouter)
523
538
  .register(
@@ -666,8 +681,9 @@ const seedSteps: SeedStep[] = [
666
681
  title: "Seed users require Better Auth to be enabled",
667
682
  });
668
683
  }
684
+ // Sign-up stays open on the seed's own instance, so AUTH_SIGN_UP=closed still seeds users.
669
685
  const auth = createBetterAuth({
670
- config,
686
+ config: {...config, signUp: undefined},
671
687
  mongoClient: getMongoClientFromMongoose(),
672
688
  userModel: User as unknown as TerrenoAuthUserModel,
673
689
  });
@@ -756,20 +772,59 @@ main().catch((error: unknown) => {
756
772
  `;
757
773
  };
758
774
  const generateBackendBetterAuthConfig = (args) => {
759
- const { appName } = args;
760
- return `import type {AuthProvider, BetterAuthConfig} from "@terreno/api";
775
+ const { appDisplayName, appName } = args;
776
+ return `import {
777
+ APIError,
778
+ type AuthProvider,
779
+ type BetterAuthAccountLinkingMode,
780
+ type BetterAuthConfig,
781
+ type BetterAuthPasskeyConfig,
782
+ logger,
783
+ } from "@terreno/api";
761
784
 
762
785
  const DEFAULT_BETTER_AUTH_URL = "http://localhost:4000";
786
+ const DEFAULT_FRONTEND_URL = "http://localhost:8082";
763
787
  const DEFAULT_WEB_ORIGINS = ["http://localhost:8082", "http://127.0.0.1:8082"];
764
788
  const APP_SCHEMES = ["${appName}://", "exp://"];
765
789
 
790
+ /** Name authenticator apps and passkey prompts show for this app. */
791
+ export const APP_NAME = ${JSON.stringify(appDisplayName)};
792
+
793
+ const ACCOUNT_LINKING_MODES: readonly BetterAuthAccountLinkingMode[] = [
794
+ "verified-email",
795
+ "explicit",
796
+ "never",
797
+ ];
798
+ const SIGN_UP_MODES: readonly ("open" | "closed")[] = ["open", "closed"];
799
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
800
+
766
801
  export const getAuthProvider = (): AuthProvider => {
767
802
  const provider = process.env.AUTH_PROVIDER as AuthProvider | undefined;
768
803
  return provider ?? "better-auth";
769
804
  };
770
805
 
806
+ /** The web app's public URL (\`FRONTEND_URL\`), used for auth mail links and passkeys. */
807
+ export const getFrontendUrl = (): string => process.env.FRONTEND_URL || DEFAULT_FRONTEND_URL;
808
+
809
+ /** The \`FRONTEND_URL\` origin, or undefined when it is not a URL (passkey setup reports that). */
810
+ const getFrontendOrigin = (): string | undefined => {
811
+ try {
812
+ return new URL(getFrontendUrl()).origin;
813
+ } catch {
814
+ return undefined;
815
+ }
816
+ };
817
+
818
+ /**
819
+ * Web origins for CORS and \`trustedOrigins\`: the dev origins, the \`FRONTEND_URL\` origin, and
820
+ * each \`CORS_ORIGINS\` entry.
821
+ */
771
822
  export const getWebOrigins = (): string[] => {
772
823
  const origins = new Set<string>(DEFAULT_WEB_ORIGINS);
824
+ const frontendOrigin = getFrontendOrigin();
825
+ if (frontendOrigin) {
826
+ origins.add(frontendOrigin);
827
+ }
773
828
  const fromEnv = process.env.CORS_ORIGINS?.split(",")
774
829
  .map((value) => value.trim())
775
830
  .filter(Boolean);
@@ -779,6 +834,90 @@ export const getWebOrigins = (): string[] => {
779
834
  return [...origins];
780
835
  };
781
836
 
837
+ /** \`AUTH_ACCOUNT_LINKING\`: \`verified-email\` (default), \`explicit\`, or \`never\`. */
838
+ const getAccountLinkingMode = (): BetterAuthAccountLinkingMode => {
839
+ const value = process.env.AUTH_ACCOUNT_LINKING || "verified-email";
840
+ const mode = ACCOUNT_LINKING_MODES.find((candidate) => candidate === value);
841
+ if (!mode) {
842
+ throw new APIError({
843
+ status: 500,
844
+ title: \`AUTH_ACCOUNT_LINKING must be one of \${ACCOUNT_LINKING_MODES.join(", ")}\`,
845
+ });
846
+ }
847
+ return mode;
848
+ };
849
+
850
+ /** \`AUTH_SIGN_UP\`: \`open\` (default) or \`closed\`. */
851
+ const getSignUpMode = (): "open" | "closed" => {
852
+ const value = process.env.AUTH_SIGN_UP || "open";
853
+ const mode = SIGN_UP_MODES.find((candidate) => candidate === value);
854
+ if (!mode) {
855
+ throw new APIError({status: 500, title: "AUTH_SIGN_UP must be open or closed"});
856
+ }
857
+ return mode;
858
+ };
859
+
860
+ const isOnRpID = (hostname: string, rpID: string): boolean =>
861
+ hostname === rpID || hostname.endsWith(\`.\${rpID}\`);
862
+
863
+ /**
864
+ * Passkeys are bound to \`PASSKEY_RP_ID\`, or to the \`FRONTEND_URL\` host when it is unset. The
865
+ * \`FRONTEND_URL\` origin always uses them; a CORS origin joins only when its host is the rpID or a
866
+ * subdomain of it, because a browser refuses a passkey anywhere else.
867
+ */
868
+ const buildPasskeyConfig = (): BetterAuthPasskeyConfig => {
869
+ let frontend: URL;
870
+ try {
871
+ frontend = new URL(getFrontendUrl());
872
+ } catch {
873
+ throw new APIError({status: 500, title: "FRONTEND_URL must be an http(s) URL"});
874
+ }
875
+ if (frontend.protocol !== "http:" && frontend.protocol !== "https:") {
876
+ throw new APIError({status: 500, title: "FRONTEND_URL must be an http(s) URL"});
877
+ }
878
+ const rpID = process.env.PASSKEY_RP_ID || frontend.hostname;
879
+ if (!isOnRpID(frontend.hostname, rpID)) {
880
+ throw new APIError({
881
+ status: 500,
882
+ title: \`PASSKEY_RP_ID "\${rpID}" must be the FRONTEND_URL host or a parent domain of it\`,
883
+ });
884
+ }
885
+ const origins = new Set<string>([frontend.origin]);
886
+ for (const origin of getWebOrigins()) {
887
+ try {
888
+ const url = new URL(origin);
889
+ if (url.origin === origin && isOnRpID(url.hostname, rpID)) {
890
+ origins.add(origin);
891
+ }
892
+ } catch {
893
+ // A malformed CORS origin can never use a passkey.
894
+ }
895
+ }
896
+ return {origin: [...origins], rpID, rpName: APP_NAME};
897
+ };
898
+
899
+ let warnedPasskeysOnLoopback = false;
900
+
901
+ /**
902
+ * The passkey config, or undefined in production while \`FRONTEND_URL\` is still a loopback URL:
903
+ * passkeys bound to \`localhost\` can never work for a deployed web app, so the login screen
904
+ * should not offer them.
905
+ */
906
+ const buildDeployablePasskeyConfig = (): BetterAuthPasskeyConfig | undefined => {
907
+ const passkey = buildPasskeyConfig();
908
+ if (process.env.NODE_ENV !== "production") {
909
+ return passkey;
910
+ }
911
+ if (!LOOPBACK_HOSTS.has(new URL(passkey.origin[0]).hostname)) {
912
+ return passkey;
913
+ }
914
+ if (!warnedPasskeysOnLoopback) {
915
+ warnedPasskeysOnLoopback = true;
916
+ logger.warn("Passkeys are off: set FRONTEND_URL to the deployed web app's URL to turn them on");
917
+ }
918
+ return undefined;
919
+ };
920
+
782
921
  export const buildBetterAuthConfig = (): BetterAuthConfig | undefined => {
783
922
  if (getAuthProvider() !== "better-auth") {
784
923
  return undefined;
@@ -789,13 +928,26 @@ export const buildBetterAuthConfig = (): BetterAuthConfig | undefined => {
789
928
  throw new Error("BETTER_AUTH_SECRET is required when AUTH_PROVIDER=better-auth");
790
929
  }
791
930
 
792
- return {
931
+ // The auth suite: env tunes the linking and sign-up policy; the rest is on.
932
+ const config: BetterAuthConfig = {
933
+ accountLinking: {mode: getAccountLinkingMode()},
793
934
  baseURL: process.env.BETTER_AUTH_URL ?? DEFAULT_BETTER_AUTH_URL,
794
935
  crossDomainCookies: process.env.CROSS_DOMAIN_AUTH_COOKIES === "true",
795
936
  enabled: true,
937
+ lastLoginMethod: true,
938
+ multiSession: {},
939
+ nativeApps: true,
940
+ publicAppUrl: getFrontendUrl(),
796
941
  secret,
942
+ signUp: {mode: getSignUpMode()},
797
943
  trustedOrigins: [...APP_SCHEMES, ...getWebOrigins()],
944
+ twoFactor: {issuer: APP_NAME, trustDeviceDays: 30},
798
945
  };
946
+ const passkey = buildDeployablePasskeyConfig();
947
+ if (passkey) {
948
+ config.passkey = passkey;
949
+ }
950
+ return config;
799
951
  };
800
952
  `;
801
953
  };
@@ -819,7 +971,8 @@ export function addDefaultPlugins(schema: mongoose.Schema<any, any, any, any>):
819
971
  `;
820
972
  };
821
973
  const generateBackendUserModel = () => {
822
- return `import mongoose from "mongoose";
974
+ return `import {rbacUserPlugin} from "@terreno/api";
975
+ import mongoose from "mongoose";
823
976
  import passportLocalMongoose from "passport-local-mongoose";
824
977
  import type {UserDocument, UserModel} from "../types";
825
978
  import {addDefaultPlugins} from "./modelPlugins";
@@ -858,6 +1011,9 @@ const userSchema = new mongoose.Schema<UserDocument, UserModel>(
858
1011
  userSchema.plugin(passportLocalMongoose, {
859
1012
  usernameField: "email",
860
1013
  });
1014
+ // \`roles\` holds the user's RBAC role names (access.ts). New users get Terreno's \`member\` role;
1015
+ // the seed adds \`operator\` to the admin, which grants the /users/:id/security recovery routes.
1016
+ userSchema.plugin(rbacUserPlugin, {defaultRoles: ["member"]});
861
1017
 
862
1018
  addDefaultPlugins(userSchema);
863
1019
 
@@ -1045,6 +1201,8 @@ export type UserDocument = DefaultDoc &
1045
1201
  betterAuthId?: string;
1046
1202
  email: string;
1047
1203
  name: string;
1204
+ /** RBAC role names, from rbacUserPlugin. */
1205
+ roles: string[];
1048
1206
  };
1049
1207
  `;
1050
1208
  };
@@ -1392,6 +1550,7 @@ import {Stack} from "expo-router";
1392
1550
  import {useEffect} from "react";
1393
1551
  import "react-native-reanimated";
1394
1552
  import {baseUrl, selectBetterAuthIsLoading, selectBetterAuthUserId} from "@terreno/rtk";
1553
+ import {installTerrenoDevConsoleLogger} from "@terreno/syncdb";
1395
1554
  import {SyncDbProvider} from "@terreno/syncdb/react";
1396
1555
  import {Spinner, TerrenoProvider} from "@terreno/ui";
1397
1556
  import {Provider, useSelector} from "react-redux";
@@ -1399,6 +1558,11 @@ import {PersistGate} from "redux-persist/integration/react";
1399
1558
  import store, {persistor, syncBetterAuthSession} from "@/store/index";
1400
1559
  import {setSyncDbReady, syncDb} from "@/store/syncdb";
1401
1560
 
1561
+ // Dev-only: forwards console errors/warnings and uncaught errors to the backend's
1562
+ // POST /__terreno/browser-logs so terreno-mcp-local \`read_logs\` / \`last_error\` can read them.
1563
+ // No-op outside __DEV__.
1564
+ installTerrenoDevConsoleLogger({baseUrl});
1565
+
1402
1566
  export {ErrorBoundary} from "expo-router";
1403
1567
 
1404
1568
  export const unstable_settings = {
@@ -1470,6 +1634,7 @@ function RootLayoutNav(): React.ReactElement {
1470
1634
  </Stack.Protected>
1471
1635
  <Stack.Protected guard={Boolean(userId)}>
1472
1636
  <Stack.Screen name="(tabs)" options={{headerShown: false}} />
1637
+ <Stack.Screen name="settings/security" options={{title: "Security"}} />
1473
1638
  </Stack.Protected>
1474
1639
  </Stack>
1475
1640
  </ThemeProvider>
@@ -1479,54 +1644,43 @@ function RootLayoutNav(): React.ReactElement {
1479
1644
  `;
1480
1645
  };
1481
1646
  const generateFrontendLogin = () => {
1482
- return `import {baseUrl} from "@terreno/rtk";
1483
- import {LoginScreen} from "@terreno/ui";
1484
- import {useRouter} from "expo-router";
1647
+ return `import {TerrenoLoginScreen} from "@terreno/rtk";
1648
+ import {useLocalSearchParams, useRouter} from "expo-router";
1485
1649
  import type React from "react";
1486
- import {useCallback, useState} from "react";
1487
- import {betterAuthClient} from "@/lib/betterAuth";
1650
+ import {useCallback} from "react";
1651
+ import {betterAuthClient, rememberedAccounts} from "@/lib/betterAuth";
1488
1652
  import {syncBetterAuthSession, useAppDispatch} from "@/store/index";
1489
1653
 
1654
+ /**
1655
+ * Renders only the sign-in methods the server's /terreno/methods turns on. A social sign-in
1656
+ * returns here (callbackURL), and a failed one brings back ?error=, which the screen maps to
1657
+ * guidance without showing the URL's text.
1658
+ */
1490
1659
  const Login: React.FC = () => {
1491
1660
  const router = useRouter();
1492
1661
  const dispatch = useAppDispatch();
1493
- const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
1494
- const [isSubmitting, setIsSubmitting] = useState(false);
1662
+ const {error} = useLocalSearchParams<{error?: string}>();
1495
1663
 
1496
- const handleSubmit = useCallback(
1497
- async (values: Record<string, string>): Promise<void> => {
1498
- const {email, password} = values;
1499
- setErrorMessage(undefined);
1500
- setIsSubmitting(true);
1501
- try {
1502
- const result = await betterAuthClient.signIn.email({email, password});
1503
- if (result.error) {
1504
- setErrorMessage(result.error.message ?? "Sign in failed.");
1505
- return;
1506
- }
1507
- await syncBetterAuthSession(dispatch);
1508
- router.replace("/(tabs)");
1509
- } catch (error: unknown) {
1510
- console.error("[login] Sign in threw", {baseUrl, error});
1511
- setErrorMessage("Sign in failed. Please try again.");
1512
- } finally {
1513
- setIsSubmitting(false);
1514
- }
1515
- },
1516
- [dispatch, router]
1517
- );
1664
+ const handleSignedIn = useCallback(async (): Promise<void> => {
1665
+ await syncBetterAuthSession(dispatch);
1666
+ router.replace("/(tabs)");
1667
+ }, [dispatch, router]);
1668
+
1669
+ const handleSignUpPress = useCallback((): void => {
1670
+ router.push("/signup");
1671
+ }, [router]);
1518
1672
 
1519
1673
  return (
1520
- <LoginScreen
1521
- error={errorMessage}
1522
- fields={[
1523
- {autoComplete: "off", label: "Email", name: "email", required: true, type: "email"},
1524
- {label: "Password", name: "password", required: true, type: "password"},
1525
- ]}
1526
- loading={isSubmitting}
1527
- onSignUpPress={() => router.push("/signup")}
1528
- onSubmit={handleSubmit}
1674
+ <TerrenoLoginScreen
1675
+ callbackURL="/login"
1676
+ client={betterAuthClient}
1677
+ error={error}
1678
+ onSignedIn={handleSignedIn}
1679
+ onSignUpPress={handleSignUpPress}
1680
+ rememberedAccounts={rememberedAccounts}
1681
+ rememberIdentity={false}
1529
1682
  title="Welcome"
1683
+ trustDeviceDays={30}
1530
1684
  />
1531
1685
  );
1532
1686
  };
@@ -1534,6 +1688,31 @@ const Login: React.FC = () => {
1534
1688
  export default Login;
1535
1689
  `;
1536
1690
  };
1691
+ const generateFrontendSettingsSecurity = () => {
1692
+ return `import {TerrenoAccountSecurityScreen} from "@terreno/rtk";
1693
+ import {useLocalSearchParams} from "expo-router";
1694
+ import type React from "react";
1695
+ import {betterAuthClient} from "@/lib/betterAuth";
1696
+
1697
+ /**
1698
+ * Linked accounts, password, passkeys, two-factor and sessions for the signed-in user. Each card
1699
+ * shows only when the server turns its feature on.
1700
+ */
1701
+ const SecurityScreen: React.FC = () => {
1702
+ const {error} = useLocalSearchParams<{error?: string}>();
1703
+ return (
1704
+ <TerrenoAccountSecurityScreen
1705
+ callbackURL="/settings/security"
1706
+ client={betterAuthClient}
1707
+ linkError={error}
1708
+ testID="security-screen"
1709
+ />
1710
+ );
1711
+ };
1712
+
1713
+ export default SecurityScreen;
1714
+ `;
1715
+ };
1537
1716
  const generateFrontendSignup = () => {
1538
1717
  return `import {SignUpScreen, simplePasswordRequirements} from "@terreno/ui";
1539
1718
  import {useRouter} from "expo-router";
@@ -1575,7 +1754,7 @@ const SignUp: React.FC = () => {
1575
1754
  error={errorMessage}
1576
1755
  fields={[
1577
1756
  {label: "Name", name: "name", required: true, type: "text"},
1578
- {autoComplete: "off", label: "Email", name: "email", required: true, type: "email"},
1757
+ {autoComplete: "email", label: "Email", name: "email", required: true, type: "email"},
1579
1758
  {label: "Password", name: "password", required: true, type: "password"},
1580
1759
  ]}
1581
1760
  loading={isSubmitting}
@@ -1667,6 +1846,7 @@ export default HomeScreen;
1667
1846
  };
1668
1847
  const generateFrontendTabsProfile = () => {
1669
1848
  return `import {Box, Button, Card, Heading, Page, Spinner, TapToEdit, Text, TextField} from "@terreno/ui";
1849
+ import {useRouter} from "expo-router";
1670
1850
  import type React from "react";
1671
1851
  import {useCallback, useEffect, useMemo, useState} from "react";
1672
1852
  import {signOut} from "@/lib/betterAuth";
@@ -1675,11 +1855,11 @@ import {useGetMeQuery, usePatchMeMutation} from "@/store/sdk";
1675
1855
 
1676
1856
  const ProfileScreen: React.FC = () => {
1677
1857
  const dispatch = useAppDispatch();
1858
+ const router = useRouter();
1678
1859
  const {data: profile, isLoading} = useGetMeQuery();
1679
1860
  const [updateProfile] = usePatchMeMutation();
1680
1861
  const [name, setName] = useState<string>("");
1681
1862
  const [email, setEmail] = useState<string>("");
1682
- const [password, setPassword] = useState<string>("");
1683
1863
  const [currentPassword, setCurrentPassword] = useState<string>("");
1684
1864
  const [saveError, setSaveError] = useState<string | null>(null);
1685
1865
 
@@ -1707,6 +1887,10 @@ const ProfileScreen: React.FC = () => {
1707
1887
  await syncBetterAuthSession(dispatch);
1708
1888
  }, [dispatch]);
1709
1889
 
1890
+ const handleOpenSecurity = useCallback((): void => {
1891
+ router.push("/settings/security");
1892
+ }, [router]);
1893
+
1710
1894
  const handleSaveName = useCallback(
1711
1895
  async (value: string): Promise<void> => {
1712
1896
  setSaveError(null);
@@ -1726,6 +1910,8 @@ const ProfileScreen: React.FC = () => {
1726
1910
  [email, user?.email]
1727
1911
  );
1728
1912
 
1913
+ // Changes the app User's email only. Better Auth keeps signing in with the old email until
1914
+ // self-service email change lands; passwords are changed on the Security screen.
1729
1915
  const handleSaveEmail = useCallback(
1730
1916
  async (value: string): Promise<void> => {
1731
1917
  setSaveError(null);
@@ -1743,23 +1929,6 @@ const ProfileScreen: React.FC = () => {
1743
1929
  [currentPassword, isEmailChanged, updateProfile]
1744
1930
  );
1745
1931
 
1746
- const handleSavePassword = useCallback(
1747
- async (value: string): Promise<void> => {
1748
- if (!value) {
1749
- return;
1750
- }
1751
- setSaveError(null);
1752
- try {
1753
- await updateProfile({password: value}).unwrap();
1754
- setPassword("");
1755
- } catch (err) {
1756
- console.error("Error updating password:", err);
1757
- setSaveError("Failed to update password");
1758
- }
1759
- },
1760
- [updateProfile]
1761
- );
1762
-
1763
1932
  if (isLoading) {
1764
1933
  return (
1765
1934
  <Page navigation={undefined} title="Profile">
@@ -1800,17 +1969,16 @@ const ProfileScreen: React.FC = () => {
1800
1969
  value={currentPassword}
1801
1970
  />
1802
1971
  )}
1803
- <TapToEdit
1804
- helperText="Leave blank to keep your current password"
1805
- onSave={handleSavePassword}
1806
- setValue={setPassword}
1807
- title="New Password"
1808
- type="password"
1809
- value={password}
1810
- />
1811
1972
  {saveError && <Text color="error">{saveError}</Text>}
1812
1973
  </Box>
1813
1974
  </Card>
1975
+ <Button
1976
+ fullWidth
1977
+ onClick={handleOpenSecurity}
1978
+ testID="profile-security-button"
1979
+ text="Security"
1980
+ variant="secondary"
1981
+ />
1814
1982
  <Box marginTop={4}>
1815
1983
  <Button fullWidth onClick={handleLogout} text="Logout" variant="outline" />
1816
1984
  </Box>
@@ -2110,10 +2278,10 @@ export interface ProfileResponse {
2110
2278
 
2111
2279
  export interface UpdateProfileRequest {
2112
2280
  name?: string;
2281
+ /** The app User's email; the Better Auth sign-in email does not change. */
2113
2282
  email?: string;
2114
2283
  /** Required by the server when \`email\` changes the mailbox. */
2115
2284
  currentPassword?: string;
2116
- password?: string;
2117
2285
  }
2118
2286
 
2119
2287
  export const terrenoApi = openapi
@@ -2329,6 +2497,15 @@ AUTH_PROVIDER=better-auth
2329
2497
  BETTER_AUTH_SECRET=
2330
2498
  BETTER_AUTH_URL=https://api.example.com
2331
2499
  CORS_ORIGINS=https://app.example.com
2500
+ # The web app's URL: auth mail links, and the passkey origin and default rpID. Passkeys stay off
2501
+ # in production while it is a localhost URL.
2502
+ FRONTEND_URL=https://app.example.com
2503
+ # Optional: a parent domain so passkeys work on every subdomain (e.g. example.com).
2504
+ PASSKEY_RP_ID=
2505
+ # verified-email (default), explicit, or never.
2506
+ AUTH_ACCOUNT_LINKING=verified-email
2507
+ # open (default) or closed.
2508
+ AUTH_SIGN_UP=open
2332
2509
  TOKEN_SECRET=
2333
2510
  TOKEN_ISSUER=
2334
2511
  REFRESH_TOKEN_SECRET=
@@ -2351,16 +2528,19 @@ const generateBackendEnv = (args) => {
2351
2528
  AUTH_PROVIDER=better-auth
2352
2529
  BETTER_AUTH_SECRET=${appName}-better-auth-secret-dev-only-32chars
2353
2530
  BETTER_AUTH_URL=http://localhost:4000
2531
+ FRONTEND_URL=http://localhost:8082
2354
2532
  TOKEN_SECRET=dev-token-secret
2355
2533
  TOKEN_ISSUER=${appName}-dev
2356
2534
  REFRESH_TOKEN_SECRET=dev-refresh-secret
2357
2535
  SESSION_SECRET=dev-session-secret
2358
2536
  PORT=4000
2537
+ # TerrenoApp registers POST /__terreno/browser-logs (terreno-mcp-local read_logs) only in development.
2538
+ NODE_ENV=development
2359
2539
  `;
2360
2540
  };
2361
2541
  const generateFrontendBetterAuthLib = (args) => {
2362
2542
  const { appName } = args;
2363
- return `import {baseUrl, createBetterAuthClient} from "@terreno/rtk";
2543
+ return `import {baseUrl, createBetterAuthClient, createRememberedAccountsStore} from "@terreno/rtk";
2364
2544
  import Constants from "expo-constants";
2365
2545
 
2366
2546
  const getAppScheme = (): string => {
@@ -2368,12 +2548,26 @@ const getAppScheme = (): string => {
2368
2548
  return expoExtra?.scheme ?? "${appName}";
2369
2549
  };
2370
2550
 
2551
+ // The client features match the auth suite backend/src/utils/betterAuthConfig.ts turns on.
2552
+ // The login screen shows the two-factor step itself, so twoFactor needs no redirect.
2371
2553
  export const betterAuthClient = createBetterAuthClient({
2372
2554
  baseURL: baseUrl,
2555
+ features: {
2556
+ lastLoginMethod: true,
2557
+ multiSession: true,
2558
+ passkey: true,
2559
+ twoFactor: true,
2560
+ },
2373
2561
  scheme: getAppScheme(),
2374
2562
  storagePrefix: "${appName}",
2375
2563
  });
2376
2564
 
2565
+ /**
2566
+ * Accounts signed in on this device, for the login screen's "Continue as" cards. Only the sign-in
2567
+ * method is kept; pass \`rememberIdentity: true\` to also keep name, masked email and avatar.
2568
+ */
2569
+ export const rememberedAccounts = createRememberedAccountsStore({rememberIdentity: false});
2570
+
2377
2571
  export const signOut = async (): Promise<void> => {
2378
2572
  await betterAuthClient.signOut();
2379
2573
  };
@@ -2606,6 +2800,7 @@ export const generateAllFiles = (args) => {
2606
2800
  { content: generateRootDockerfile(), path: "Dockerfile" },
2607
2801
  { content: generateCursorRules(args), path: ".cursorrules" },
2608
2802
  { content: generateMcpSettings(args), path: ".cursor/mcp.json" },
2803
+ { content: generateMcpSettings(args), path: ".mcp.json" },
2609
2804
  { content: generateClaudeMd(args), path: "CLAUDE.md" },
2610
2805
  // Backend files
2611
2806
  { content: generateBackendPackageJson(args), path: `${backendDir}/package.json` },
@@ -2653,6 +2848,10 @@ export const generateAllFiles = (args) => {
2653
2848
  { content: generateFrontendRootLayout(args), path: `${frontendDir}/app/_layout.tsx` },
2654
2849
  { content: generateFrontendLogin(), path: `${frontendDir}/app/login.tsx` },
2655
2850
  { content: generateFrontendSignup(), path: `${frontendDir}/app/signup.tsx` },
2851
+ {
2852
+ content: generateFrontendSettingsSecurity(),
2853
+ path: `${frontendDir}/app/settings/security.tsx`,
2854
+ },
2656
2855
  { content: generateFrontendNotFound(), path: `${frontendDir}/app/+not-found.tsx` },
2657
2856
  { content: generateFrontendTabsLayout(), path: `${frontendDir}/app/(tabs)/_layout.tsx` },
2658
2857
  { content: generateFrontendTabsIndex(args), path: `${frontendDir}/app/(tabs)/index.tsx` },