@terreno/ui 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.
Files changed (361) hide show
  1. package/.ai/guidelines/core.md +1 -1
  2. package/CHANGELOG.md +2074 -0
  3. package/dist/Accordion.d.ts.map +1 -1
  4. package/dist/Accordion.js +3 -3
  5. package/dist/Accordion.js.map +1 -1
  6. package/dist/AreaChart.d.ts.map +1 -1
  7. package/dist/AreaChart.js +2 -2
  8. package/dist/AreaChart.js.map +1 -1
  9. package/dist/Avatar.d.ts.map +1 -1
  10. package/dist/Avatar.js +3 -1
  11. package/dist/Avatar.js.map +1 -1
  12. package/dist/BarChart.d.ts.map +1 -1
  13. package/dist/BarChart.js +2 -2
  14. package/dist/BarChart.js.map +1 -1
  15. package/dist/Box.d.ts.map +1 -1
  16. package/dist/Box.js +66 -8
  17. package/dist/Box.js.map +1 -1
  18. package/dist/Card.d.ts.map +1 -1
  19. package/dist/Card.js +5 -4
  20. package/dist/Card.js.map +1 -1
  21. package/dist/ChartCard.d.ts.map +1 -1
  22. package/dist/ChartCard.js +4 -2
  23. package/dist/ChartCard.js.map +1 -1
  24. package/dist/Common.d.ts +240 -14
  25. package/dist/Common.d.ts.map +1 -1
  26. package/dist/Common.js.map +1 -1
  27. package/dist/ConsentFormScreen.d.ts +1 -1
  28. package/dist/ConsentFormScreen.d.ts.map +1 -1
  29. package/dist/ConsentFormScreen.js +13 -4
  30. package/dist/ConsentFormScreen.js.map +1 -1
  31. package/dist/DateTimeField.d.ts.map +1 -1
  32. package/dist/DateTimeField.js +5 -3
  33. package/dist/DateTimeField.js.map +1 -1
  34. package/dist/DonutChart.d.ts.map +1 -1
  35. package/dist/DonutChart.js +2 -2
  36. package/dist/DonutChart.js.map +1 -1
  37. package/dist/Field.d.ts.map +1 -1
  38. package/dist/Field.js +2 -0
  39. package/dist/Field.js.map +1 -1
  40. package/dist/FormContainer.d.ts +68 -0
  41. package/dist/FormContainer.d.ts.map +1 -0
  42. package/dist/FormContainer.js +79 -0
  43. package/dist/FormContainer.js.map +1 -0
  44. package/dist/GPTChat.d.ts.map +1 -1
  45. package/dist/GPTChat.js +2 -1
  46. package/dist/GPTChat.js.map +1 -1
  47. package/dist/Heading.d.ts +1 -1
  48. package/dist/Heading.d.ts.map +1 -1
  49. package/dist/Heading.js +5 -2
  50. package/dist/Heading.js.map +1 -1
  51. package/dist/Icon.d.ts +4 -0
  52. package/dist/Icon.d.ts.map +1 -1
  53. package/dist/Icon.js +43 -2
  54. package/dist/Icon.js.map +1 -1
  55. package/dist/LabeledCheckBox.d.ts +22 -0
  56. package/dist/LabeledCheckBox.d.ts.map +1 -0
  57. package/dist/LabeledCheckBox.js +30 -0
  58. package/dist/LabeledCheckBox.js.map +1 -0
  59. package/dist/LineChart.d.ts.map +1 -1
  60. package/dist/LineChart.js +2 -2
  61. package/dist/LineChart.js.map +1 -1
  62. package/dist/ListDetailLayout.d.ts +36 -0
  63. package/dist/ListDetailLayout.d.ts.map +1 -0
  64. package/dist/ListDetailLayout.js +153 -0
  65. package/dist/ListDetailLayout.js.map +1 -0
  66. package/dist/MarkdownEditor.d.ts.map +1 -1
  67. package/dist/MarkdownEditor.js +2 -1
  68. package/dist/MarkdownEditor.js.map +1 -1
  69. package/dist/MediaQuery.d.ts +1 -1
  70. package/dist/MediaQuery.d.ts.map +1 -1
  71. package/dist/MediaQuery.js +1 -1
  72. package/dist/MediaQuery.js.map +1 -1
  73. package/dist/OtpField.d.ts +60 -0
  74. package/dist/OtpField.d.ts.map +1 -0
  75. package/dist/OtpField.js +154 -0
  76. package/dist/OtpField.js.map +1 -0
  77. package/dist/Page.d.ts +1 -0
  78. package/dist/Page.d.ts.map +1 -1
  79. package/dist/Page.js +10 -1
  80. package/dist/Page.js.map +1 -1
  81. package/dist/ProvisionalConsentSigner.d.ts +21 -0
  82. package/dist/ProvisionalConsentSigner.d.ts.map +1 -0
  83. package/dist/ProvisionalConsentSigner.js +199 -0
  84. package/dist/ProvisionalConsentSigner.js.map +1 -0
  85. package/dist/ResponsiveBreakpoint.d.ts +5 -0
  86. package/dist/ResponsiveBreakpoint.d.ts.map +1 -1
  87. package/dist/ResponsiveBreakpoint.js +7 -0
  88. package/dist/ResponsiveBreakpoint.js.map +1 -1
  89. package/dist/Scorecard.d.ts.map +1 -1
  90. package/dist/Scorecard.js +5 -2
  91. package/dist/Scorecard.js.map +1 -1
  92. package/dist/Skeleton.d.ts +39 -0
  93. package/dist/Skeleton.d.ts.map +1 -0
  94. package/dist/Skeleton.js +195 -0
  95. package/dist/Skeleton.js.map +1 -0
  96. package/dist/SocialLoginButton.d.ts +10 -0
  97. package/dist/SocialLoginButton.d.ts.map +1 -1
  98. package/dist/SocialLoginButton.js +26 -8
  99. package/dist/SocialLoginButton.js.map +1 -1
  100. package/dist/SplitPage.d.ts +12 -1
  101. package/dist/SplitPage.d.ts.map +1 -1
  102. package/dist/SplitPage.js +14 -7
  103. package/dist/SplitPage.js.map +1 -1
  104. package/dist/SplitPage.native.d.ts +1 -1
  105. package/dist/SplitPage.native.d.ts.map +1 -1
  106. package/dist/SplitPage.native.js +6 -3
  107. package/dist/SplitPage.native.js.map +1 -1
  108. package/dist/SplitPageLoading.d.ts +14 -0
  109. package/dist/SplitPageLoading.d.ts.map +1 -0
  110. package/dist/SplitPageLoading.js +19 -0
  111. package/dist/SplitPageLoading.js.map +1 -0
  112. package/dist/SyncStatusBanner.d.ts +7 -1
  113. package/dist/SyncStatusBanner.d.ts.map +1 -1
  114. package/dist/SyncStatusBanner.js +20 -4
  115. package/dist/SyncStatusBanner.js.map +1 -1
  116. package/dist/Text.d.ts +3 -1
  117. package/dist/Text.d.ts.map +1 -1
  118. package/dist/Text.js +2 -0
  119. package/dist/Text.js.map +1 -1
  120. package/dist/TextField.d.ts.map +1 -1
  121. package/dist/TextField.js +44 -10
  122. package/dist/TextField.js.map +1 -1
  123. package/dist/charts/ChartFrame.d.ts +2 -2
  124. package/dist/charts/ChartFrame.d.ts.map +1 -1
  125. package/dist/charts/ChartFrame.js +9 -2
  126. package/dist/charts/ChartFrame.js.map +1 -1
  127. package/dist/fieldElements/FieldError.d.ts.map +1 -1
  128. package/dist/fieldElements/FieldError.js +1 -1
  129. package/dist/fieldElements/FieldError.js.map +1 -1
  130. package/dist/index.d.ts +21 -3
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +16 -1
  133. package/dist/index.js.map +1 -1
  134. package/dist/lazyBoundaries/heavyOptionalExports.d.ts +3 -0
  135. package/dist/lazyBoundaries/heavyOptionalExports.d.ts.map +1 -1
  136. package/dist/lazyBoundaries/heavyOptionalExports.js +2 -0
  137. package/dist/lazyBoundaries/heavyOptionalExports.js.map +1 -1
  138. package/dist/login/LastUsedBadge.d.ts +14 -0
  139. package/dist/login/LastUsedBadge.d.ts.map +1 -0
  140. package/dist/login/LastUsedBadge.js +23 -0
  141. package/dist/login/LastUsedBadge.js.map +1 -0
  142. package/dist/login/LoginAccountCard.d.ts +38 -0
  143. package/dist/login/LoginAccountCard.d.ts.map +1 -0
  144. package/dist/login/LoginAccountCard.js +72 -0
  145. package/dist/login/LoginAccountCard.js.map +1 -0
  146. package/dist/login/LoginAccountList.d.ts +33 -0
  147. package/dist/login/LoginAccountList.d.ts.map +1 -0
  148. package/dist/login/LoginAccountList.js +30 -0
  149. package/dist/login/LoginAccountList.js.map +1 -0
  150. package/dist/login/LoginScreen.d.ts +4 -4
  151. package/dist/login/LoginScreen.d.ts.map +1 -1
  152. package/dist/login/LoginScreen.js +294 -13
  153. package/dist/login/LoginScreen.js.map +1 -1
  154. package/dist/login/OutlinePill.d.ts +28 -0
  155. package/dist/login/OutlinePill.d.ts.map +1 -0
  156. package/dist/login/OutlinePill.js +48 -0
  157. package/dist/login/OutlinePill.js.map +1 -0
  158. package/dist/login/TwoFactorChallengeScreen.d.ts +26 -0
  159. package/dist/login/TwoFactorChallengeScreen.d.ts.map +1 -0
  160. package/dist/login/TwoFactorChallengeScreen.js +139 -0
  161. package/dist/login/TwoFactorChallengeScreen.js.map +1 -0
  162. package/dist/login/loginMethods.d.ts +27 -0
  163. package/dist/login/loginMethods.d.ts.map +1 -0
  164. package/dist/login/loginMethods.js +37 -0
  165. package/dist/login/loginMethods.js.map +1 -0
  166. package/dist/login/loginTypes.d.ts +202 -5
  167. package/dist/login/loginTypes.d.ts.map +1 -1
  168. package/dist/pdfHtmlTemplate.d.ts +17 -0
  169. package/dist/pdfHtmlTemplate.d.ts.map +1 -1
  170. package/dist/pdfHtmlTemplate.js +78 -0
  171. package/dist/pdfHtmlTemplate.js.map +1 -1
  172. package/dist/security/AccountSecurityScreen.d.ts +10 -0
  173. package/dist/security/AccountSecurityScreen.d.ts.map +1 -0
  174. package/dist/security/AccountSecurityScreen.js +50 -0
  175. package/dist/security/AccountSecurityScreen.js.map +1 -0
  176. package/dist/security/LinkedAccountsCard.d.ts +32 -0
  177. package/dist/security/LinkedAccountsCard.d.ts.map +1 -0
  178. package/dist/security/LinkedAccountsCard.js +145 -0
  179. package/dist/security/LinkedAccountsCard.js.map +1 -0
  180. package/dist/security/PasskeysCard.d.ts +39 -0
  181. package/dist/security/PasskeysCard.d.ts.map +1 -0
  182. package/dist/security/PasskeysCard.js +168 -0
  183. package/dist/security/PasskeysCard.js.map +1 -0
  184. package/dist/security/PasswordCard.d.ts +32 -0
  185. package/dist/security/PasswordCard.d.ts.map +1 -0
  186. package/dist/security/PasswordCard.js +198 -0
  187. package/dist/security/PasswordCard.js.map +1 -0
  188. package/dist/security/SessionsCard.d.ts +39 -0
  189. package/dist/security/SessionsCard.d.ts.map +1 -0
  190. package/dist/security/SessionsCard.js +168 -0
  191. package/dist/security/SessionsCard.js.map +1 -0
  192. package/dist/security/TwoFactorSettingsCard.d.ts +55 -0
  193. package/dist/security/TwoFactorSettingsCard.d.ts.map +1 -0
  194. package/dist/security/TwoFactorSettingsCard.js +458 -0
  195. package/dist/security/TwoFactorSettingsCard.js.map +1 -0
  196. package/dist/security/securityMethods.d.ts +40 -0
  197. package/dist/security/securityMethods.d.ts.map +1 -0
  198. package/dist/security/securityMethods.js +66 -0
  199. package/dist/security/securityMethods.js.map +1 -0
  200. package/dist/security/securityTypes.d.ts +467 -0
  201. package/dist/security/securityTypes.d.ts.map +1 -0
  202. package/dist/security/securityTypes.js +2 -0
  203. package/dist/security/securityTypes.js.map +1 -0
  204. package/dist/security/userAgent.d.ts +26 -0
  205. package/dist/security/userAgent.d.ts.map +1 -0
  206. package/dist/security/userAgent.js +80 -0
  207. package/dist/security/userAgent.js.map +1 -0
  208. package/dist/signUp/OAuthButtons.d.ts +28 -5
  209. package/dist/signUp/OAuthButtons.d.ts.map +1 -1
  210. package/dist/signUp/OAuthButtons.js +44 -5
  211. package/dist/signUp/OAuthButtons.js.map +1 -1
  212. package/dist/signUp/SignUpScreen.d.ts.map +1 -1
  213. package/dist/signUp/SignUpScreen.js +50 -5
  214. package/dist/signUp/SignUpScreen.js.map +1 -1
  215. package/dist/signUp/signUpTypes.d.ts +21 -1
  216. package/dist/signUp/signUpTypes.d.ts.map +1 -1
  217. package/dist/useConsentForms.d.ts +9 -0
  218. package/dist/useConsentForms.d.ts.map +1 -1
  219. package/dist/useConsentForms.js +18 -0
  220. package/dist/useConsentForms.js.map +1 -1
  221. package/dist/useProvisionalConsent.d.ts +124 -0
  222. package/dist/useProvisionalConsent.d.ts.map +1 -0
  223. package/dist/useProvisionalConsent.js +79 -0
  224. package/dist/useProvisionalConsent.js.map +1 -0
  225. package/dist/withLoading.d.ts +20 -0
  226. package/dist/withLoading.d.ts.map +1 -0
  227. package/dist/withLoading.js +24 -0
  228. package/dist/withLoading.js.map +1 -0
  229. package/package.json +4 -2
  230. package/src/Accordion.test.tsx +5 -0
  231. package/src/Accordion.tsx +3 -8
  232. package/src/AreaChart.test.tsx +15 -0
  233. package/src/AreaChart.tsx +6 -0
  234. package/src/Avatar.test.tsx +8 -0
  235. package/src/Avatar.tsx +2 -0
  236. package/src/BarChart.test.tsx +15 -0
  237. package/src/BarChart.tsx +6 -0
  238. package/src/Box.test.tsx +131 -1
  239. package/src/Box.tsx +77 -8
  240. package/src/Card.test.tsx +48 -0
  241. package/src/Card.tsx +13 -2
  242. package/src/ChartCard.test.tsx +30 -0
  243. package/src/ChartCard.tsx +18 -1
  244. package/src/Common.ts +263 -14
  245. package/src/ConsentFormScreen.test.tsx +84 -0
  246. package/src/ConsentFormScreen.tsx +28 -4
  247. package/src/DateTimeField.tsx +5 -3
  248. package/src/DonutChart.test.tsx +15 -0
  249. package/src/DonutChart.tsx +6 -0
  250. package/src/Field.tsx +2 -0
  251. package/src/FilePickerButton.test.tsx +35 -0
  252. package/src/FormContainer.test.tsx +242 -0
  253. package/src/FormContainer.tsx +177 -0
  254. package/src/GPTChat.test.tsx +16 -0
  255. package/src/GPTChat.tsx +8 -2
  256. package/src/Heading.test.tsx +14 -0
  257. package/src/Heading.tsx +6 -1
  258. package/src/Icon.test.tsx +52 -1
  259. package/src/Icon.tsx +92 -3
  260. package/src/IconButton.test.tsx +85 -0
  261. package/src/LabeledCheckBox.test.tsx +45 -0
  262. package/src/LabeledCheckBox.tsx +89 -0
  263. package/src/LineChart.test.tsx +18 -0
  264. package/src/LineChart.tsx +6 -0
  265. package/src/ListDetailLayout.tsx +247 -0
  266. package/src/MarkdownEditor.tsx +2 -1
  267. package/src/MediaQuery.ts +1 -0
  268. package/src/OtpField.test.tsx +280 -0
  269. package/src/OtpField.tsx +307 -0
  270. package/src/Page.test.tsx +38 -0
  271. package/src/Page.tsx +38 -19
  272. package/src/ProvisionalConsentSigner.test.tsx +625 -0
  273. package/src/ProvisionalConsentSigner.tsx +423 -0
  274. package/src/ResponsiveBreakpoint.test.tsx +7 -0
  275. package/src/ResponsiveBreakpoint.tsx +14 -0
  276. package/src/RootImportRegression.test.tsx +3 -0
  277. package/src/Scorecard.test.tsx +11 -0
  278. package/src/Scorecard.tsx +21 -0
  279. package/src/Skeleton.test.tsx +262 -0
  280. package/src/Skeleton.tsx +430 -0
  281. package/src/SocialLoginButton.test.tsx +14 -0
  282. package/src/SocialLoginButton.tsx +51 -7
  283. package/src/SplitPage.native.tsx +16 -3
  284. package/src/SplitPage.tsx +29 -12
  285. package/src/SplitPageLoading.test.tsx +51 -0
  286. package/src/SplitPageLoading.tsx +53 -0
  287. package/src/SyncStatusBanner.test.tsx +61 -4
  288. package/src/SyncStatusBanner.tsx +29 -3
  289. package/src/Text.tsx +4 -1
  290. package/src/TextField.test.tsx +150 -0
  291. package/src/TextField.tsx +66 -8
  292. package/src/__snapshots__/AddressField.test.tsx.snap +12 -0
  293. package/src/__snapshots__/AiSuggestionBox.test.tsx.snap +15 -0
  294. package/src/__snapshots__/Avatar.test.tsx.snap +1 -0
  295. package/src/__snapshots__/CustomSelectField.test.tsx.snap +3 -0
  296. package/src/__snapshots__/EmailField.test.tsx.snap +6 -0
  297. package/src/__snapshots__/Field.test.tsx.snap +37 -0
  298. package/src/__snapshots__/HeightField.test.tsx.snap +2 -0
  299. package/src/__snapshots__/MobileAddressAutoComplete.test.tsx.snap +3 -0
  300. package/src/__snapshots__/NumberField.test.tsx.snap +3 -0
  301. package/src/__snapshots__/Page.test.tsx.snap +28 -5
  302. package/src/__snapshots__/PhoneNumberField.test.tsx.snap +12 -0
  303. package/src/__snapshots__/Slider.test.tsx.snap +1 -0
  304. package/src/__snapshots__/SocialLoginButton.test.tsx.snap +43 -22
  305. package/src/__snapshots__/SplitPage.test.tsx.snap +16 -0
  306. package/src/__snapshots__/TapToEdit.test.tsx.snap +3 -0
  307. package/src/__snapshots__/TextArea.test.tsx.snap +17 -1
  308. package/src/__snapshots__/TextField.test.tsx.snap +19 -2
  309. package/src/__snapshots__/TypedSignatureField.test.tsx.snap +3 -0
  310. package/src/__snapshots__/UnifiedAddressAutoComplete.test.tsx.snap +18 -0
  311. package/src/__snapshots__/WebAddressAutocomplete.test.tsx.snap +12 -0
  312. package/src/bunSetup.ts +13 -1
  313. package/src/charts/ChartFrame.tsx +19 -8
  314. package/src/fieldElements/FieldError.tsx +1 -0
  315. package/src/fieldElements/__snapshots__/FieldError.test.tsx.snap +2 -0
  316. package/src/index.tsx +44 -1
  317. package/src/isolated/ListDetailLayout.isolated.tsx +634 -0
  318. package/src/lazyBoundaries/heavyOptionalExports.tsx +7 -0
  319. package/src/login/LastUsedBadge.tsx +40 -0
  320. package/src/login/LoginAccountCard.tsx +205 -0
  321. package/src/login/LoginAccountList.tsx +115 -0
  322. package/src/login/LoginScreen.test.tsx +837 -1
  323. package/src/login/LoginScreen.tsx +674 -91
  324. package/src/login/OutlinePill.tsx +110 -0
  325. package/src/login/TwoFactorChallengeScreen.test.tsx +376 -0
  326. package/src/login/TwoFactorChallengeScreen.tsx +307 -0
  327. package/src/login/__snapshots__/LoginScreen.test.tsx.snap +1454 -334
  328. package/src/login/loginMethods.test.ts +53 -0
  329. package/src/login/loginMethods.ts +60 -0
  330. package/src/login/loginTypes.ts +208 -5
  331. package/src/pdfHtmlTemplate.test.ts +243 -4
  332. package/src/pdfHtmlTemplate.ts +93 -0
  333. package/src/security/AccountSecurityScreen.test.tsx +262 -0
  334. package/src/security/AccountSecurityScreen.tsx +156 -0
  335. package/src/security/LinkedAccountsCard.test.tsx +371 -0
  336. package/src/security/LinkedAccountsCard.tsx +297 -0
  337. package/src/security/PasskeysCard.test.tsx +378 -0
  338. package/src/security/PasskeysCard.tsx +371 -0
  339. package/src/security/PasswordCard.test.tsx +445 -0
  340. package/src/security/PasswordCard.tsx +342 -0
  341. package/src/security/SessionsCard.test.tsx +349 -0
  342. package/src/security/SessionsCard.tsx +362 -0
  343. package/src/security/TwoFactorSettingsCard.test.tsx +700 -0
  344. package/src/security/TwoFactorSettingsCard.tsx +872 -0
  345. package/src/security/securityMethods.test.ts +101 -0
  346. package/src/security/securityMethods.ts +104 -0
  347. package/src/security/securityTypes.ts +480 -0
  348. package/src/security/userAgent.test.ts +119 -0
  349. package/src/security/userAgent.ts +102 -0
  350. package/src/signUp/OAuthButtons.test.tsx +27 -0
  351. package/src/signUp/OAuthButtons.tsx +153 -19
  352. package/src/signUp/SignUpScreen.test.tsx +170 -1
  353. package/src/signUp/SignUpScreen.tsx +87 -25
  354. package/src/signUp/__snapshots__/SignUpScreen.test.tsx.snap +22 -11
  355. package/src/signUp/signUpTypes.ts +23 -1
  356. package/src/useConsentForms.test.ts +37 -1
  357. package/src/useConsentForms.ts +25 -0
  358. package/src/useProvisionalConsent.test.ts +256 -0
  359. package/src/useProvisionalConsent.ts +218 -0
  360. package/src/withLoading.test.tsx +61 -0
  361. package/src/withLoading.tsx +50 -0
@@ -0,0 +1,872 @@
1
+ import * as Clipboard from "expo-clipboard";
2
+ import {type FC, type ReactElement, useCallback, useEffect, useRef, useState} from "react";
3
+ import {AccessibilityInfo, Platform, Share, type TextInput, View} from "react-native";
4
+ import QRCode from "react-native-qrcode-svg";
5
+
6
+ import {Box} from "../Box";
7
+ import {Button} from "../Button";
8
+ import {Card} from "../Card";
9
+ import {FormContainer} from "../FormContainer";
10
+ import {Heading} from "../Heading";
11
+ import {LabeledCheckBox} from "../LabeledCheckBox";
12
+ import {Modal} from "../Modal";
13
+ import {OtpField} from "../OtpField";
14
+ import {Text} from "../Text";
15
+ import {TextField} from "../TextField";
16
+ import {getRejectionMessage} from "./securityMethods";
17
+ import type {TwoFactorEnrollment, TwoFactorSettingsCardProps} from "./securityTypes";
18
+
19
+ const DEFAULT_DIGITS = 6;
20
+ /** Fewer unused backup codes than this shows a warning. */
21
+ const LOW_BACKUP_CODES = 3;
22
+ const QR_SIZE = 176;
23
+ const COPY_STATUS_MS = 2000;
24
+ const BACKUP_CODES_FILE_NAME = "two-factor-backup-codes.txt";
25
+ const BACKUP_CODES_FILE_HEADER =
26
+ "Backup codes for two-factor authentication. Each code signs you in once.";
27
+ /**
28
+ * How long a downloaded file's object URL lives. Some browsers start reading the blob after
29
+ * `click()` returns, so revoking it at once can cancel the download.
30
+ */
31
+ const OBJECT_URL_LIFETIME_MS = 30000;
32
+
33
+ /** Why the card is asking for the password. */
34
+ type PasswordPurpose = "enroll" | "regenerate" | "disable";
35
+
36
+ /** Which step of which flow the card is showing. */
37
+ type TwoFactorFlow =
38
+ | {kind: "idle"; announcement?: string}
39
+ | {kind: "password"; purpose: PasswordPurpose}
40
+ | {kind: "scan"; enrollment: TwoFactorEnrollment}
41
+ | {kind: "verify"; enrollment: TwoFactorEnrollment}
42
+ | {kind: "codes"; codes: string[]; purpose: "enroll" | "regenerate"};
43
+
44
+ /** The callback in flight, for per-action spinners. */
45
+ type PendingAction = "enroll" | "regenerate" | "disable" | "verify";
46
+
47
+ /** What was copied, and whether the copy worked. */
48
+ interface CopyFeedback {
49
+ target: "secret" | "codes";
50
+ status: "copied" | "failed";
51
+ }
52
+
53
+ const IDLE: TwoFactorFlow = {kind: "idle"};
54
+
55
+ const PASSWORD_COPY: Record<PasswordPurpose, {prompt: string; submit: string}> = {
56
+ disable: {
57
+ prompt: "Enter your password to turn off two-factor authentication.",
58
+ submit: "Turn off",
59
+ },
60
+ enroll: {
61
+ prompt: "Enter your password to turn on two-factor authentication.",
62
+ submit: "Continue",
63
+ },
64
+ regenerate: {
65
+ prompt: "Enter your password to get new backup codes. Your current codes will stop working.",
66
+ submit: "Get new codes",
67
+ },
68
+ };
69
+
70
+ const SCAN_TEXT =
71
+ "Scan this QR code with an authenticator app, such as Google Authenticator, Microsoft Authenticator, or 1Password.";
72
+
73
+ const getVerifyText = (codeLength: number): string =>
74
+ `Enter the ${codeLength}-digit code your authenticator app shows.`;
75
+
76
+ const CODES_TITLE: Record<"enroll" | "regenerate", string> = {
77
+ enroll: "Two-factor authentication is on. Save your backup codes.",
78
+ regenerate: "Here are your new backup codes. Your old codes no longer work.",
79
+ };
80
+
81
+ /** Announced when Finish returns to the card. */
82
+ const FINISH_ANNOUNCEMENT: Record<"enroll" | "regenerate", string> = {
83
+ enroll: "Two-factor authentication is on.",
84
+ regenerate: "Your backup codes are updated.",
85
+ };
86
+
87
+ const COPY_STATUS_TEXT: Record<CopyFeedback["status"], string> = {
88
+ copied: "Copied",
89
+ failed: "Couldn't copy",
90
+ };
91
+
92
+ const REJECTION_FALLBACK: Record<PendingAction, string> = {
93
+ disable: "Couldn't turn off two-factor authentication. Try again.",
94
+ enroll: "Couldn't start two-factor setup. Try again.",
95
+ regenerate: "Couldn't create new backup codes. Try again.",
96
+ verify: "That code didn't work. Check your app and try again.",
97
+ };
98
+
99
+ /**
100
+ * Reads a query parameter from an `otpauth://` URI, or undefined when it has none. Parsed by hand
101
+ * because React Native's `URL` has no `searchParams` on every platform.
102
+ */
103
+ const getOtpauthParam = (totpURI: string, name: string): string | undefined => {
104
+ const match = new RegExp(`[?&]${name}=([^&#]+)`, "i").exec(totpURI);
105
+ if (!match) {
106
+ return undefined;
107
+ }
108
+ try {
109
+ return decodeURIComponent(match[1]);
110
+ } catch {
111
+ return match[1];
112
+ }
113
+ };
114
+
115
+ /** Reads the base32 `secret` parameter from an `otpauth://` URI, or undefined when it has none. */
116
+ export const parseTotpSecret = (totpURI: string): string | undefined => {
117
+ return getOtpauthParam(totpURI, "secret");
118
+ };
119
+
120
+ /** Reads the `digits` parameter from an `otpauth://` URI, or undefined when missing or invalid. */
121
+ export const parseTotpDigits = (totpURI: string): number | undefined => {
122
+ const value = getOtpauthParam(totpURI, "digits");
123
+ if (!value || !/^\d+$/.test(value)) {
124
+ return undefined;
125
+ }
126
+ const parsed = Number(value);
127
+ return parsed >= 4 && parsed <= 10 ? parsed : undefined;
128
+ };
129
+
130
+ /** Splits a secret into groups of four ("JBSW Y3DP ...") so it is easier to type. */
131
+ const formatSecret = (secret: string): string => {
132
+ return secret.match(/.{1,4}/g)?.join(" ") ?? secret;
133
+ };
134
+
135
+ /** The text written to the backup codes file or share sheet. */
136
+ const formatBackupCodesFile = (codes: string[]): string => {
137
+ return `${BACKUP_CODES_FILE_HEADER}\n\n${codes.join("\n")}\n`;
138
+ };
139
+
140
+ /** Saves text as a file through a temporary download link. Web only. */
141
+ const downloadTextFile = ({fileName, text}: {fileName: string; text: string}): void => {
142
+ const url = URL.createObjectURL(new Blob([text], {type: "text/plain;charset=utf-8"}));
143
+ const anchor = document.createElement("a");
144
+ anchor.href = url;
145
+ anchor.download = fileName;
146
+ anchor.style.display = "none";
147
+ document.body.appendChild(anchor);
148
+ anchor.click();
149
+ anchor.remove();
150
+ setTimeout(() => URL.revokeObjectURL(url), OBJECT_URL_LIFETIME_MS);
151
+ };
152
+
153
+ /**
154
+ * Turns two-factor authentication (an authenticator app, TOTP) on and off and manages backup
155
+ * codes. Turning on walks through four steps: confirm the password, scan a QR code (or type the
156
+ * secret shown under it), enter a code from the app, then save the backup codes, with Finish
157
+ * gated on "I saved these backup codes". Once on, the card offers new backup codes (password,
158
+ * then the new codes with the same gate) and Turn off (password, then a destructive confirm).
159
+ * Presentational: it reports each step through callbacks and never calls an auth client.
160
+ *
161
+ * @example
162
+ * ```tsx
163
+ * // The Better Auth client resolves {data, error} rather than throwing; throw so the card
164
+ * // shows the error.
165
+ * <TwoFactorSettingsCard
166
+ * enabled={Boolean(session.data?.user.twoFactorEnabled)}
167
+ * hasPassword={hasPasswordCredential(accounts)}
168
+ * onStartEnroll={async (password) => {
169
+ * const {data, error} = await authClient.twoFactor.enable({password: password ?? ""});
170
+ * // enable() resolves {method: "otp"} for the email/SMS OTP method; only TOTP has a URI.
171
+ * if (error || !data || !("totpURI" in data)) {
172
+ * throw new Error(error?.message ?? "Couldn't start two-factor setup.");
173
+ * }
174
+ * return {backupCodes: data.backupCodes, totpURI: data.totpURI};
175
+ * }}
176
+ * onVerify={async (code) => {
177
+ * const {error} = await authClient.twoFactor.verifyTotp({code});
178
+ * if (error) {
179
+ * throw new Error(error.message ?? "That code didn't work.");
180
+ * }
181
+ * }}
182
+ * onRegenerateBackupCodes={async (password) => {
183
+ * const {data, error} = await authClient.twoFactor.generateBackupCodes({
184
+ * password: password ?? "",
185
+ * });
186
+ * if (error || !data) {
187
+ * throw new Error(error?.message ?? "Couldn't create new backup codes.");
188
+ * }
189
+ * return data.backupCodes;
190
+ * }}
191
+ * onDisable={async (password) => {
192
+ * const {error} = await authClient.twoFactor.disable({password: password ?? ""});
193
+ * if (error) {
194
+ * throw new Error(error.message ?? "Couldn't turn off two-factor authentication.");
195
+ * }
196
+ * }}
197
+ * />
198
+ * ```
199
+ */
200
+ export const TwoFactorSettingsCard: FC<TwoFactorSettingsCardProps> = ({
201
+ enabled,
202
+ backupCodesRemaining,
203
+ onStartEnroll,
204
+ onVerify,
205
+ onRegenerateBackupCodes,
206
+ onDisable,
207
+ requirePassword = true,
208
+ hasPassword = true,
209
+ digits,
210
+ error,
211
+ disabled = false,
212
+ title = "Two-factor authentication",
213
+ description = "Sign in with a code from an authenticator app as well as your password.",
214
+ username,
215
+ testID = "two-factor-settings-card",
216
+ }) => {
217
+ const [flow, setFlow] = useState<TwoFactorFlow>(IDLE);
218
+ const [password, setPassword] = useState("");
219
+ const [passwordError, setPasswordError] = useState<string | undefined>(undefined);
220
+ const [code, setCode] = useState("");
221
+ const [hasSavedCodes, setHasSavedCodes] = useState(false);
222
+ const [isConfirmingDisable, setIsConfirmingDisable] = useState(false);
223
+ const [pendingAction, setPendingAction] = useState<PendingAction | undefined>(undefined);
224
+ const [actionError, setActionError] = useState<string | undefined>(undefined);
225
+ const [copyFeedback, setCopyFeedback] = useState<CopyFeedback | undefined>(undefined);
226
+ const passwordInputRef = useRef<TextInput | null>(null);
227
+ const stepHeadingRef = useRef<View | null>(null);
228
+ const isFirstRenderRef = useRef(true);
229
+
230
+ const isBusy = disabled || pendingAction !== undefined;
231
+ const shownError = error ?? actionError;
232
+ const cannotConfirmPassword = requirePassword && !hasPassword;
233
+ const enrollStepOffset = requirePassword ? 1 : 0;
234
+ const enrollStepCount = 3 + enrollStepOffset;
235
+ const enrollmentDigits =
236
+ flow.kind === "scan" || flow.kind === "verify"
237
+ ? parseTotpDigits(flow.enrollment.totpURI)
238
+ : undefined;
239
+ const codeLength = digits ?? enrollmentDigits ?? DEFAULT_DIGITS;
240
+
241
+ /** What a screen reader hears when the flow moves to its current step. */
242
+ const getStepAnnouncement = (): string | undefined => {
243
+ switch (flow.kind) {
244
+ case "password": {
245
+ const prompt = PASSWORD_COPY[flow.purpose].prompt;
246
+ return flow.purpose === "enroll" ? `Step 1 of ${enrollStepCount}. ${prompt}` : prompt;
247
+ }
248
+ case "scan":
249
+ return `Step ${1 + enrollStepOffset} of ${enrollStepCount}. ${SCAN_TEXT}`;
250
+ case "verify":
251
+ return `Step ${2 + enrollStepOffset} of ${enrollStepCount}. ${getVerifyText(codeLength)}`;
252
+ case "codes":
253
+ return CODES_TITLE[flow.purpose];
254
+ default:
255
+ return flow.announcement;
256
+ }
257
+ };
258
+ const stepAnnouncement = getStepAnnouncement();
259
+
260
+ // Each step replaces the content that had focus, so move focus to the new step: on web to the
261
+ // step's heading (or the field on the password and code steps), and on native announce the step,
262
+ // since a native View can't take focus.
263
+ // biome-ignore lint/correctness/useExhaustiveDependencies: runs once per step change.
264
+ useEffect(() => {
265
+ if (isFirstRenderRef.current) {
266
+ isFirstRenderRef.current = false;
267
+ return;
268
+ }
269
+ if (flow.kind === "password") {
270
+ passwordInputRef.current?.focus();
271
+ }
272
+ if (Platform.OS === "web") {
273
+ // The password and code steps focus their field instead, so the user can type at once.
274
+ if (flow.kind !== "password" && flow.kind !== "verify") {
275
+ (stepHeadingRef.current as unknown as HTMLElement | null)?.focus?.({preventScroll: true});
276
+ }
277
+ return;
278
+ }
279
+ if (stepAnnouncement) {
280
+ AccessibilityInfo.announceForAccessibility(stepAnnouncement);
281
+ }
282
+ }, [flow]);
283
+
284
+ // Clears the copy status 2 s after each copy; a new copy or unmounting cancels the pending clear.
285
+ useEffect(() => {
286
+ if (copyFeedback === undefined) {
287
+ return;
288
+ }
289
+ const timer = setTimeout(() => setCopyFeedback(undefined), COPY_STATUS_MS);
290
+ return (): void => clearTimeout(timer);
291
+ }, [copyFeedback]);
292
+
293
+ const goTo = useCallback((next: TwoFactorFlow): void => {
294
+ setFlow(next);
295
+ setActionError(undefined);
296
+ setCopyFeedback(undefined);
297
+ }, []);
298
+
299
+ /** Returns to the card, announcing what just happened when there is something to say. */
300
+ const reset = useCallback(
301
+ (announcement?: string): void => {
302
+ goTo(announcement ? {announcement, kind: "idle"} : IDLE);
303
+ setPassword("");
304
+ setPasswordError(undefined);
305
+ setCode("");
306
+ setHasSavedCodes(false);
307
+ setIsConfirmingDisable(false);
308
+ },
309
+ [goTo]
310
+ );
311
+
312
+ /** Runs a callback with a spinner; resolves its value, or undefined after showing the error. */
313
+ const runAction = useCallback(
314
+ async <T,>({
315
+ action,
316
+ run,
317
+ }: {
318
+ action: PendingAction;
319
+ run: () => Promise<T>;
320
+ }): Promise<{value: T} | undefined> => {
321
+ setActionError(undefined);
322
+ setPendingAction(action);
323
+ try {
324
+ return {value: await run()};
325
+ } catch (rejection: unknown) {
326
+ console.warn(`TwoFactorSettingsCard: ${action} rejected`, rejection);
327
+ setActionError(
328
+ getRejectionMessage({error: rejection, fallback: REJECTION_FALLBACK[action]})
329
+ );
330
+ return undefined;
331
+ } finally {
332
+ setPendingAction(undefined);
333
+ }
334
+ },
335
+ []
336
+ );
337
+
338
+ const startEnroll = useCallback(
339
+ async (confirmedPassword?: string): Promise<void> => {
340
+ const result = await runAction({
341
+ action: "enroll",
342
+ run: () => onStartEnroll(confirmedPassword),
343
+ });
344
+ if (!result) {
345
+ return;
346
+ }
347
+ // The password has done its job; don't keep it in memory through the rest of the flow.
348
+ setPassword("");
349
+ setCode("");
350
+ goTo({enrollment: result.value, kind: "scan"});
351
+ },
352
+ [goTo, onStartEnroll, runAction]
353
+ );
354
+
355
+ const regenerate = useCallback(
356
+ async (confirmedPassword?: string): Promise<void> => {
357
+ if (!onRegenerateBackupCodes) {
358
+ return;
359
+ }
360
+ const result = await runAction({
361
+ action: "regenerate",
362
+ run: () => onRegenerateBackupCodes(confirmedPassword),
363
+ });
364
+ if (!result) {
365
+ return;
366
+ }
367
+ setPassword("");
368
+ setHasSavedCodes(false);
369
+ goTo({codes: result.value, kind: "codes", purpose: "regenerate"});
370
+ },
371
+ [goTo, onRegenerateBackupCodes, runAction]
372
+ );
373
+
374
+ const handleEnable = useCallback(async (): Promise<void> => {
375
+ if (requirePassword) {
376
+ goTo({kind: "password", purpose: "enroll"});
377
+ return;
378
+ }
379
+ await startEnroll(undefined);
380
+ }, [goTo, requirePassword, startEnroll]);
381
+
382
+ const handleRegenerate = useCallback(async (): Promise<void> => {
383
+ if (requirePassword) {
384
+ goTo({kind: "password", purpose: "regenerate"});
385
+ return;
386
+ }
387
+ await regenerate(undefined);
388
+ }, [goTo, regenerate, requirePassword]);
389
+
390
+ const handleDisable = useCallback((): void => {
391
+ if (requirePassword) {
392
+ goTo({kind: "password", purpose: "disable"});
393
+ return;
394
+ }
395
+ setActionError(undefined);
396
+ setIsConfirmingDisable(true);
397
+ }, [goTo, requirePassword]);
398
+
399
+ const handlePasswordChange = useCallback((value: string): void => {
400
+ setPassword(value);
401
+ setPasswordError(undefined);
402
+ }, []);
403
+
404
+ const handlePasswordSubmit = useCallback(async (): Promise<void> => {
405
+ if (flow.kind !== "password" || isBusy) {
406
+ return;
407
+ }
408
+ if (!password) {
409
+ setPasswordError("Enter your password.");
410
+ passwordInputRef.current?.focus();
411
+ return;
412
+ }
413
+ if (flow.purpose === "enroll") {
414
+ await startEnroll(password);
415
+ } else if (flow.purpose === "regenerate") {
416
+ await regenerate(password);
417
+ } else {
418
+ setActionError(undefined);
419
+ setIsConfirmingDisable(true);
420
+ }
421
+ }, [flow, isBusy, password, regenerate, startEnroll]);
422
+
423
+ const handleConfirmDisable = useCallback(async (): Promise<void> => {
424
+ setIsConfirmingDisable(false);
425
+ if (!onDisable) {
426
+ return;
427
+ }
428
+ const confirmedPassword = requirePassword ? password : undefined;
429
+ const result = await runAction({action: "disable", run: () => onDisable(confirmedPassword)});
430
+ if (result) {
431
+ reset("Two-factor authentication is off.");
432
+ }
433
+ }, [onDisable, password, requirePassword, reset, runAction]);
434
+
435
+ const handleDismissDisable = useCallback((): void => {
436
+ setIsConfirmingDisable(false);
437
+ }, []);
438
+
439
+ const verify = useCallback(
440
+ async (submitted: string): Promise<void> => {
441
+ if (
442
+ flow.kind !== "verify" ||
443
+ pendingAction !== undefined ||
444
+ submitted.length !== codeLength
445
+ ) {
446
+ return;
447
+ }
448
+ const {enrollment} = flow;
449
+ const result = await runAction({action: "verify", run: () => onVerify(submitted)});
450
+ if (!result) {
451
+ setCode("");
452
+ return;
453
+ }
454
+ setHasSavedCodes(false);
455
+ goTo({codes: enrollment.backupCodes, kind: "codes", purpose: "enroll"});
456
+ },
457
+ [codeLength, flow, goTo, onVerify, pendingAction, runAction]
458
+ );
459
+
460
+ const handleVerifyPress = useCallback(async (): Promise<void> => {
461
+ await verify(code);
462
+ }, [code, verify]);
463
+
464
+ const copyText = useCallback(
465
+ async (target: CopyFeedback["target"], text: string): Promise<void> => {
466
+ let status: CopyFeedback["status"] = "copied";
467
+ try {
468
+ await Clipboard.setStringAsync(text);
469
+ } catch (rejection: unknown) {
470
+ console.warn("TwoFactorSettingsCard: copy failed", rejection);
471
+ status = "failed";
472
+ }
473
+ setCopyFeedback({status, target});
474
+ // VoiceOver ignores live regions, so iOS announces the result itself.
475
+ if (Platform.OS === "ios") {
476
+ AccessibilityInfo.announceForAccessibility(COPY_STATUS_TEXT[status]);
477
+ }
478
+ },
479
+ []
480
+ );
481
+
482
+ const handleSaveCodes = useCallback(async (codes: string[]): Promise<void> => {
483
+ const text = formatBackupCodesFile(codes);
484
+ if (Platform.OS === "web") {
485
+ downloadTextFile({fileName: BACKUP_CODES_FILE_NAME, text});
486
+ return;
487
+ }
488
+ try {
489
+ await Share.share({message: text, title: "Backup codes"});
490
+ } catch (rejection: unknown) {
491
+ console.warn("TwoFactorSettingsCard: share failed", rejection);
492
+ }
493
+ }, []);
494
+
495
+ const renderCopyStatus = (target: CopyFeedback["target"]): ReactElement => {
496
+ const feedback = copyFeedback?.target === target ? copyFeedback : undefined;
497
+ return (
498
+ <View
499
+ accessibilityLiveRegion="polite"
500
+ aria-live="polite"
501
+ role="status"
502
+ testID={`${testID}-copy-${target}-status`}
503
+ >
504
+ {feedback ? (
505
+ <Text color={feedback.status === "failed" ? "error" : "secondaryLight"} size="sm">
506
+ {COPY_STATUS_TEXT[feedback.status]}
507
+ </Text>
508
+ ) : null}
509
+ </View>
510
+ );
511
+ };
512
+
513
+ /**
514
+ * The step's step counter and lead text, as the element focus moves to on web when the step
515
+ * opens. Only one step renders at a time, so they share one ref.
516
+ */
517
+ const renderStepHeading = ({
518
+ step,
519
+ children,
520
+ }: {
521
+ step?: number;
522
+ children: ReactElement;
523
+ }): ReactElement => (
524
+ <View ref={stepHeadingRef} style={{gap: 4}} tabIndex={-1} testID={`${testID}-step-heading`}>
525
+ {step !== undefined && (
526
+ <Text color="secondaryLight" size="sm" testID={`${testID}-step`}>
527
+ {`Step ${step} of ${enrollStepCount}`}
528
+ </Text>
529
+ )}
530
+ {children}
531
+ </View>
532
+ );
533
+
534
+ const renderCancel = (): ReactElement => (
535
+ <Button
536
+ disabled={pendingAction !== undefined}
537
+ onClick={() => reset()}
538
+ testID={`${testID}-cancel`}
539
+ text="Cancel"
540
+ variant="muted"
541
+ />
542
+ );
543
+
544
+ const renderIdle = (): ReactElement => {
545
+ const isLow = backupCodesRemaining !== undefined && backupCodesRemaining < LOW_BACKUP_CODES;
546
+ return (
547
+ <Box gap={3}>
548
+ {renderStepHeading({
549
+ children: (
550
+ <Text>
551
+ {"Status: "}
552
+ <Text bold color={enabled ? "success" : "secondaryLight"} testID={`${testID}-status`}>
553
+ {enabled ? "On" : "Off"}
554
+ </Text>
555
+ </Text>
556
+ ),
557
+ })}
558
+
559
+ {enabled && backupCodesRemaining !== undefined && (
560
+ <Box gap={1}>
561
+ <Text testID={`${testID}-backup-codes-remaining`}>
562
+ {`${backupCodesRemaining} backup ${backupCodesRemaining === 1 ? "code" : "codes"} left`}
563
+ </Text>
564
+ {isLow && (
565
+ <Text color="warning" testID={`${testID}-backup-codes-low`}>
566
+ You're running low on backup codes. Get new ones so you don't get locked out.
567
+ </Text>
568
+ )}
569
+ </Box>
570
+ )}
571
+
572
+ {cannotConfirmPassword && (
573
+ <Text color="secondaryLight" testID={`${testID}-needs-password`}>
574
+ {enabled
575
+ ? "Set a password first. You'll confirm it to get new backup codes or turn off two-factor authentication."
576
+ : "Set a password first. You'll confirm it to turn on two-factor authentication."}
577
+ </Text>
578
+ )}
579
+
580
+ <Box direction="row" gap={2} wrap>
581
+ {!enabled && (
582
+ <Button
583
+ disabled={isBusy || cannotConfirmPassword}
584
+ iconName="shield-halved"
585
+ loading={pendingAction === "enroll"}
586
+ onClick={handleEnable}
587
+ testID={`${testID}-enable`}
588
+ text="Turn on"
589
+ />
590
+ )}
591
+ {enabled && Boolean(onRegenerateBackupCodes) && (
592
+ <Button
593
+ disabled={isBusy || cannotConfirmPassword}
594
+ loading={pendingAction === "regenerate"}
595
+ onClick={handleRegenerate}
596
+ testID={`${testID}-regenerate`}
597
+ text="Get new backup codes"
598
+ variant="secondary"
599
+ />
600
+ )}
601
+ {enabled && Boolean(onDisable) && (
602
+ <Button
603
+ disabled={isBusy || cannotConfirmPassword}
604
+ loading={pendingAction === "disable"}
605
+ onClick={handleDisable}
606
+ testID={`${testID}-disable`}
607
+ text="Turn off"
608
+ variant="outline"
609
+ />
610
+ )}
611
+ </Box>
612
+ </Box>
613
+ );
614
+ };
615
+
616
+ const renderPassword = (purpose: PasswordPurpose): ReactElement => {
617
+ const copy = PASSWORD_COPY[purpose];
618
+ // A form lets password managers fill the current password on web.
619
+ return (
620
+ <FormContainer
621
+ accessibilityLabel={copy.submit}
622
+ gap={3}
623
+ onSubmit={handlePasswordSubmit}
624
+ testID={`${testID}-password-form`}
625
+ username={username}
626
+ >
627
+ {renderStepHeading({
628
+ children: <Text testID={`${testID}-password-prompt`}>{copy.prompt}</Text>,
629
+ step: purpose === "enroll" ? 1 : undefined,
630
+ })}
631
+ <TextField
632
+ accessibilityLabel="Password"
633
+ autoComplete="current-password"
634
+ disabled={isBusy}
635
+ errorText={passwordError}
636
+ inputRef={(ref) => {
637
+ passwordInputRef.current = ref;
638
+ }}
639
+ onChange={handlePasswordChange}
640
+ onEnter={handlePasswordSubmit}
641
+ testID={`${testID}-password`}
642
+ title="Password"
643
+ type="password"
644
+ value={password}
645
+ />
646
+ <Box direction="row" gap={2} wrap>
647
+ <Button
648
+ disabled={isBusy}
649
+ loading={pendingAction === purpose}
650
+ onClick={handlePasswordSubmit}
651
+ testID={`${testID}-password-submit`}
652
+ text={copy.submit}
653
+ variant={purpose === "disable" ? "destructive" : "primary"}
654
+ />
655
+ {renderCancel()}
656
+ </Box>
657
+ </FormContainer>
658
+ );
659
+ };
660
+
661
+ const renderScan = (enrollment: TwoFactorEnrollment): ReactElement => {
662
+ const secret = parseTotpSecret(enrollment.totpURI);
663
+ return (
664
+ <Box gap={3}>
665
+ {renderStepHeading({children: <Text>{SCAN_TEXT}</Text>, step: 1 + enrollStepOffset})}
666
+ <Box alignItems="center">
667
+ <View
668
+ accessibilityLabel="QR code for your authenticator app"
669
+ aria-label="QR code for your authenticator app"
670
+ role="img"
671
+ style={{backgroundColor: "#FFFFFF", borderRadius: 8, padding: 12}}
672
+ testID={`${testID}-qr`}
673
+ >
674
+ <QRCode
675
+ backgroundColor="#FFFFFF"
676
+ color="#000000"
677
+ size={QR_SIZE}
678
+ value={enrollment.totpURI}
679
+ />
680
+ </View>
681
+ </Box>
682
+ {Boolean(secret) && (
683
+ <Box gap={2}>
684
+ <Text color="secondaryLight">Can't scan it? Enter this setup key in the app:</Text>
685
+ <Text bold testID={`${testID}-secret`}>
686
+ {formatSecret(secret!)}
687
+ </Text>
688
+ <Box alignItems="center" direction="row" gap={2}>
689
+ <Button
690
+ accessibilityLabel="Copy setup key"
691
+ iconName="copy"
692
+ onClick={() => copyText("secret", secret!)}
693
+ size="sm"
694
+ testID={`${testID}-copy-secret`}
695
+ text="Copy key"
696
+ variant="muted"
697
+ />
698
+ {renderCopyStatus("secret")}
699
+ </Box>
700
+ </Box>
701
+ )}
702
+ <Box direction="row" gap={2} wrap>
703
+ <Button
704
+ onClick={() => goTo({enrollment, kind: "verify"})}
705
+ testID={`${testID}-next`}
706
+ text="Next"
707
+ />
708
+ {renderCancel()}
709
+ </Box>
710
+ </Box>
711
+ );
712
+ };
713
+
714
+ const renderVerify = (enrollment: TwoFactorEnrollment): ReactElement => (
715
+ <Box gap={3}>
716
+ {renderStepHeading({
717
+ children: <Text>{getVerifyText(codeLength)}</Text>,
718
+ step: 2 + enrollStepOffset,
719
+ })}
720
+ <OtpField
721
+ accessibilityLabel="Authentication code"
722
+ autoFocus
723
+ disabled={pendingAction === "verify"}
724
+ length={codeLength}
725
+ onChange={setCode}
726
+ onComplete={verify}
727
+ testID={`${testID}-otp`}
728
+ title="Code"
729
+ value={code}
730
+ />
731
+ <Box direction="row" gap={2} wrap>
732
+ <Button
733
+ disabled={code.length !== codeLength || pendingAction !== undefined}
734
+ loading={pendingAction === "verify"}
735
+ onClick={handleVerifyPress}
736
+ testID={`${testID}-verify`}
737
+ text="Verify"
738
+ />
739
+ <Button
740
+ disabled={pendingAction !== undefined}
741
+ onClick={() => goTo({enrollment, kind: "scan"})}
742
+ testID={`${testID}-back`}
743
+ text="Back"
744
+ variant="secondary"
745
+ />
746
+ {renderCancel()}
747
+ </Box>
748
+ </Box>
749
+ );
750
+
751
+ const renderCodes = (codes: string[], purpose: "enroll" | "regenerate"): ReactElement => (
752
+ <Box gap={3}>
753
+ {renderStepHeading({
754
+ children: (
755
+ <Text bold testID={`${testID}-codes-title`}>
756
+ {CODES_TITLE[purpose]}
757
+ </Text>
758
+ ),
759
+ step: purpose === "enroll" ? 3 + enrollStepOffset : undefined,
760
+ })}
761
+ <Text color="secondaryLight">
762
+ Each code signs you in once if you lose your authenticator app. Keep them somewhere safe,
763
+ like a password manager.
764
+ </Text>
765
+ <View
766
+ aria-label="Backup codes"
767
+ role="list"
768
+ style={{columnGap: 16, flexDirection: "row", flexWrap: "wrap", rowGap: 8}}
769
+ testID={`${testID}-backup-codes`}
770
+ >
771
+ {codes.map((backupCode, index) => (
772
+ <View key={backupCode} role="listitem" style={{minWidth: 120}}>
773
+ <Text testID={`${testID}-backup-code-${index + 1}`}>{backupCode}</Text>
774
+ </View>
775
+ ))}
776
+ </View>
777
+ <Box alignItems="center" direction="row" gap={2} wrap>
778
+ <Button
779
+ accessibilityLabel="Copy backup codes"
780
+ iconName="copy"
781
+ onClick={() => copyText("codes", codes.join("\n"))}
782
+ size="sm"
783
+ testID={`${testID}-copy-codes`}
784
+ text="Copy"
785
+ variant="muted"
786
+ />
787
+ <Button
788
+ accessibilityLabel={
789
+ Platform.OS === "web" ? "Download backup codes" : "Share backup codes"
790
+ }
791
+ iconName={Platform.OS === "web" ? "download" : "share"}
792
+ onClick={() => handleSaveCodes(codes)}
793
+ size="sm"
794
+ testID={`${testID}-download-codes`}
795
+ text={Platform.OS === "web" ? "Download" : "Share"}
796
+ variant="muted"
797
+ />
798
+ {renderCopyStatus("codes")}
799
+ </Box>
800
+ <LabeledCheckBox
801
+ checked={hasSavedCodes}
802
+ label="I saved these backup codes"
803
+ onChange={setHasSavedCodes}
804
+ testID={`${testID}-saved`}
805
+ />
806
+ <Box alignItems="start">
807
+ <Button
808
+ disabled={!hasSavedCodes}
809
+ onClick={() => reset(FINISH_ANNOUNCEMENT[purpose])}
810
+ testID={`${testID}-finish`}
811
+ text="Finish"
812
+ />
813
+ </Box>
814
+ </Box>
815
+ );
816
+
817
+ const renderFlow = (): ReactElement => {
818
+ switch (flow.kind) {
819
+ case "password":
820
+ return renderPassword(flow.purpose);
821
+ case "scan":
822
+ return renderScan(flow.enrollment);
823
+ case "verify":
824
+ return renderVerify(flow.enrollment);
825
+ case "codes":
826
+ return renderCodes(flow.codes, flow.purpose);
827
+ default:
828
+ return renderIdle();
829
+ }
830
+ };
831
+
832
+ return (
833
+ <Card testID={testID}>
834
+ <Box gap={4}>
835
+ <Box gap={1}>
836
+ <Heading level={2} size="md" testID={`${testID}-title`}>
837
+ {title}
838
+ </Heading>
839
+ <Text color="secondaryLight">{description}</Text>
840
+ </Box>
841
+
842
+ {renderFlow()}
843
+
844
+ {Boolean(shownError) && (
845
+ <View role="alert" testID={`${testID}-error`}>
846
+ <Text color="error">{shownError}</Text>
847
+ </View>
848
+ )}
849
+ </Box>
850
+
851
+ {isConfirmingDisable && (
852
+ <Modal
853
+ onDismiss={handleDismissDisable}
854
+ primaryButtonOnClick={handleConfirmDisable}
855
+ primaryButtonText="Turn off"
856
+ secondaryButtonOnClick={handleDismissDisable}
857
+ secondaryButtonText="Cancel"
858
+ testIDs={{
859
+ dismiss: `${testID}-confirm-dismiss`,
860
+ primaryButton: `${testID}-confirm-submit`,
861
+ root: `${testID}-confirm`,
862
+ secondaryButton: `${testID}-confirm-cancel`,
863
+ title: `${testID}-confirm-title`,
864
+ }}
865
+ text="You'll sign in with just your password, and your backup codes will stop working. Your account will be easier to break into."
866
+ title="Turn off two-factor authentication?"
867
+ visible
868
+ />
869
+ )}
870
+ </Card>
871
+ );
872
+ };