Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add two-factor auth viewer to mobile app (#771)
Leendert de Borstd88e0ca4cfdd
diff --git a/browser-extension/src/entrypoints/popup/components/CredentialDetails/TotpBlock.tsx b/browser-extension/src/entrypoints/popup/components/CredentialDetails/TotpBlock.tsxindex 4baedc9e5..cac6abebb 100644--- a/browser-extension/src/entrypoints/popup/components/CredentialDetails/TotpBlock.tsx+++ b/browser-extension/src/entrypoints/popup/components/CredentialDetails/TotpBlock.tsx@@ -1,17 +1,194 @@-import React from 'react';-import { TotpViewer } from '../../components/TotpViewer';+import React, { useState, useEffect } from 'react';+import { useDb } from '../../context/DbContext';+import { TotpCode } from '../../../../utils/types/TotpCode';+import * as OTPAuth from 'otpauth';type TotpBlockProps = {credentialId: string;}/**- * Render the TOTP viewer block.+ * This component shows TOTP codes for a credential.*/-const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId }) => (- <>- <TotpViewer credentialId={credentialId} />- </>-);+const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId }) => {+ const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);+ const [loading, setLoading] = useState(true);+ const [currentCodes, setCurrentCodes] = useState<Record<string, string>>({});+ const [copiedId, setCopiedId] = useState<string | null>(null);+ const dbContext = useDb();++ /**+ * Gets the remaining seconds for the TOTP code.+ */+ const getRemainingSeconds = (step = 30): number => {+ const totp = new OTPAuth.TOTP({+ secret: 'dummy', // We only need this for timing calculations+ algorithm: 'SHA1',+ digits: 6,+ period: step+ });+ return totp.period - (Math.floor(Date.now() / 1000) % totp.period);+ };++ /**+ * Gets the remaining percentage for the TOTP code.+ */+ const getRemainingPercentage = (): number => {+ const remaining = getRemainingSeconds();+ // Invert the percentage so it counts down instead of up+ return Math.floor(((30.0 - remaining) / 30.0) * 100);+ };++ /**+ * Generates a TOTP code for a given secret key.+ */+ const generateTotpCode = (secretKey: string): string => {+ try {+ const totp = new OTPAuth.TOTP({+ secret: secretKey,+ algorithm: 'SHA1',+ digits: 6,+ period: 30+ });+ return totp.generate();+ } catch (error) {+ console.error('Error generating TOTP code:', error);+ return 'Error';+ }+ };++ /**+ * Copies a TOTP code to the clipboard.+ */+ const copyToClipboard = async (code: string, id: string): Promise<void> => {+ try {+ await navigator.clipboard.writeText(code);+ setCopiedId(id);++ // Reset copied state after 2 seconds+ setTimeout(() => {+ setCopiedId(null);+ }, 2000);+ } catch (error) {+ console.error('Failed to copy:', error);+ }+ };++ useEffect(() => {+ /**+ * Loads the TOTP codes for the credential.+ */+ const loadTotpCodes = async (): Promise<void> => {+ if (!dbContext?.sqliteClient) {+ return;+ }++ try {+ const codes = dbContext.sqliteClient.getTotpCodesForCredential(credentialId);+ setTotpCodes(codes);+ } catch (error) {+ console.error('Error loading TOTP codes:', error);+ } finally {+ setLoading(false);+ }+ };++ loadTotpCodes();+ }, [credentialId, dbContext?.sqliteClient]);++ useEffect(() => {+ /**+ * Updates the current TOTP codes.+ */+ const updateTotpCodes = (prevCodes: Record<string, string>): Record<string, string> => {+ const newCodes: Record<string, string> = {};+ totpCodes.forEach(code => {+ const generatedCode = generateTotpCode(code.SecretKey);+ // Only update if we have a valid code+ if (generatedCode !== 'Error') {+ newCodes[code.Id] = generatedCode;+ } else {+ // Keep the previous code if there's an error+ newCodes[code.Id] = prevCodes[code.Id] ?? 'Error';+ }+ });+ return newCodes;+ };++ // Generate initial codes+ const initialCodes: Record<string, string> = {};+ totpCodes.forEach(code => {+ initialCodes[code.Id] = generateTotpCode(code.SecretKey);+ });+ setCurrentCodes(initialCodes);++ // Set up interval to refresh codes+ const intervalId = setInterval(() => {+ setCurrentCodes(updateTotpCodes);+ }, 1000);++ // Clean up interval on unmount or when totpCodes change+ return () : void => {+ clearInterval(intervalId);+ };+ }, [totpCodes]);++ if (loading) {+ return (+ <div className="text-gray-500 dark:text-gray-400 mb-4">+ <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">Two-factor authentication</h2>+ Loading TOTP codes...+ </div>+ );+ }++ if (totpCodes.length === 0) {+ return null;+ }++ return (+ <div className="mb-4">+ <div className="space-y-2">+ <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Two-factor authentication</h2>+ <div className="grid grid-cols-1 gap-2">+ {totpCodes.map(totpCode => (+ <button+ key={totpCode.Id}+ className={`w-full text-left p-2 ps-3 pe-3 rounded bg-white dark:bg-gray-800 shadow hover:shadow-md transition-all border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700`}+ onClick={() => copyToClipboard(currentCodes[totpCode.Id], totpCode.Id)}+ aria-label={`Copy ${totpCode.Name} code`}+ >+ <div className="flex justify-between items-center gap-2">+ <div className="flex items-center flex-1">+ <h4 className="text-sm font-medium text-gray-900 dark:text-white">{totpCode.Name}</h4>+ </div>+ <div className="flex items-center gap-2">+ <div className="flex flex-col items-end">+ <span className="text-lg font-bold text-gray-900 dark:text-white">+ {currentCodes[totpCode.Id]}+ </span>+ <div className="text-xs">+ {copiedId === totpCode.Id ? (+ <span className="text-green-600 dark:text-green-400">Copied!</span>+ ) : (+ <span className="text-gray-500 dark:text-gray-400">{getRemainingSeconds()}s</span>+ )}+ </div>+ </div>+ <div className="w-1 h-6 bg-gray-200 rounded-full dark:bg-gray-600">+ <div+ className="bg-blue-600 rounded-full transition-all"+ style={{ height: `${getRemainingPercentage()}%`, width: '100%' }}+ />+ </div>+ </div>+ </div>+ </button>+ ))}+ </div>+ </div>+ </div>+ );+};export default TotpBlock;\ No newline at end of filediff --git a/browser-extension/src/entrypoints/popup/components/TotpViewer.tsx b/browser-extension/src/entrypoints/popup/components/TotpViewer.tsxdeleted file mode 100644index 868c0e032..000000000--- a/browser-extension/src/entrypoints/popup/components/TotpViewer.tsx+++ /dev/null@@ -1,192 +0,0 @@-import React, { useState, useEffect } from 'react';-import { useDb } from '../context/DbContext';-import { TotpCode } from '../../../utils/types/TotpCode';-import * as OTPAuth from 'otpauth';--type TotpViewerProps = {- credentialId: string;-}--/**- * This component shows TOTP codes for a credential.- */-export const TotpViewer: React.FC<TotpViewerProps> = ({ credentialId }) => {- const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);- const [loading, setLoading] = useState(true);- const [currentCodes, setCurrentCodes] = useState<Record<string, string>>({});- const [copiedId, setCopiedId] = useState<string | null>(null);- const dbContext = useDb();-- /**- * Gets the remaining seconds for the TOTP code.- */- const getRemainingSeconds = (step = 30): number => {- const totp = new OTPAuth.TOTP({- secret: 'dummy', // We only need this for timing calculations- algorithm: 'SHA1',- digits: 6,- period: step- });- return totp.period - (Math.floor(Date.now() / 1000) % totp.period);- };-- /**- * Gets the remaining percentage for the TOTP code.- */- const getRemainingPercentage = (): number => {- const remaining = getRemainingSeconds();- // Invert the percentage so it counts down instead of up- return Math.floor(((30.0 - remaining) / 30.0) * 100);- };-- /**- * Generates a TOTP code for a given secret key.- */- const generateTotpCode = (secretKey: string): string => {- try {- const totp = new OTPAuth.TOTP({- secret: secretKey,- algorithm: 'SHA1',- digits: 6,- period: 30- });- return totp.generate();- } catch (error) {- console.error('Error generating TOTP code:', error);- return 'Error';- }- };-- /**- * Copies a TOTP code to the clipboard.- */- const copyToClipboard = async (code: string, id: string): Promise<void> => {- try {- await navigator.clipboard.writeText(code);- setCopiedId(id);-- // Reset copied state after 2 seconds- setTimeout(() => {- setCopiedId(null);- }, 2000);- } catch (error) {- console.error('Failed to copy:', error);- }- };-- useEffect(() => {- /**- * Loads the TOTP codes for the credential.- */- const loadTotpCodes = async (): Promise<void> => {- if (!dbContext?.sqliteClient) {- return;- }-- try {- const codes = dbContext.sqliteClient.getTotpCodesForCredential(credentialId);- setTotpCodes(codes);- } catch (error) {- console.error('Error loading TOTP codes:', error);- } finally {- setLoading(false);- }- };-- loadTotpCodes();- }, [credentialId, dbContext?.sqliteClient]);-- useEffect(() => {- /**- * Updates the current TOTP codes.- */- const updateTotpCodes = (prevCodes: Record<string, string>): Record<string, string> => {- const newCodes: Record<string, string> = {};- totpCodes.forEach(code => {- const generatedCode = generateTotpCode(code.SecretKey);- // Only update if we have a valid code- if (generatedCode !== 'Error') {- newCodes[code.Id] = generatedCode;- } else {- // Keep the previous code if there's an error- newCodes[code.Id] = prevCodes[code.Id] ?? 'Error';- }- });- return newCodes;- };-- // Generate initial codes- const initialCodes: Record<string, string> = {};- totpCodes.forEach(code => {- initialCodes[code.Id] = generateTotpCode(code.SecretKey);- });- setCurrentCodes(initialCodes);-- // Set up interval to refresh codes- const intervalId = setInterval(() => {- setCurrentCodes(updateTotpCodes);- }, 1000);-- // Clean up interval on unmount or when totpCodes change- return () : void => {- clearInterval(intervalId);- };- }, [totpCodes]);-- if (loading) {- return (- <div className="text-gray-500 dark:text-gray-400 mb-4">- <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">Two-factor authentication</h2>- Loading TOTP codes...- </div>- );- }-- if (totpCodes.length === 0) {- return null;- }-- return (- <div className="mb-4">- <div className="space-y-2">- <h2 className="text-base font-semibold text-gray-900 dark:text-white">Two-factor authentication</h2>- <div className="grid grid-cols-1 gap-2">- {totpCodes.map(totpCode => (- <button- key={totpCode.Id}- className={`w-full text-left p-2 ps-3 pe-3 rounded bg-white dark:bg-gray-800 shadow hover:shadow-md transition-all border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700`}- onClick={() => copyToClipboard(currentCodes[totpCode.Id], totpCode.Id)}- aria-label={`Copy ${totpCode.Name} code`}- >- <div className="flex justify-between items-center gap-2">- <div className="flex items-center flex-1">- <h4 className="text-sm font-medium text-gray-900 dark:text-white">{totpCode.Name}</h4>- </div>- <div className="flex items-center gap-2">- <div className="flex flex-col items-end">- <span className="text-lg font-bold text-gray-900 dark:text-white">- {currentCodes[totpCode.Id]}- </span>- <div className="text-xs">- {copiedId === totpCode.Id ? (- <span className="text-green-600 dark:text-green-400">Copied!</span>- ) : (- <span className="text-gray-500 dark:text-gray-400">{getRemainingSeconds()}s</span>- )}- </div>- </div>- <div className="w-1 h-6 bg-gray-200 rounded-full dark:bg-gray-600">- <div- className="bg-blue-600 rounded-full transition-all"- style={{ height: `${getRemainingPercentage()}%`, width: '100%' }}- />- </div>- </div>- </div>- </button>- ))}- </div>- </div>- </div>- );-};\ No newline at end of filediff --git a/mobile-app/app/(tabs)/(credentials)/[id].tsx b/mobile-app/app/(tabs)/(credentials)/[id].tsxindex 1bf4ee6c3..3cf15eac7 100644--- a/mobile-app/app/(tabs)/(credentials)/[id].tsx+++ b/mobile-app/app/(tabs)/(credentials)/[id].tsx@@ -12,6 +12,7 @@ import { LoginCredentials } from '@/components/credentialDetails/LoginCredentialimport { AliasDetails } from '@/components/credentialDetails/AliasDetails';import { NotesSection } from '@/components/credentialDetails/NotesSection';import { EmailPreview } from '@/components/credentialDetails/EmailPreview';+import { TotpSection } from '@/components/credentialDetails/TotpSection';export default function CredentialDetailsScreen() {const { id } = useLocalSearchParams();@@ -84,6 +85,7 @@ export default function CredentialDetailsScreen() {</View></ThemedView><EmailPreview email={credential.Alias.Email} />+ <TotpSection credential={credential} /><NotesSection credential={credential} /><LoginCredentials credential={credential} /><AliasDetails credential={credential} />diff --git a/mobile-app/components/credentialDetails/EmailPreview.tsx b/mobile-app/components/credentialDetails/EmailPreview.tsxindex aebbe8b0f..193fa833f 100644--- a/mobile-app/components/credentialDetails/EmailPreview.tsx+++ b/mobile-app/components/credentialDetails/EmailPreview.tsx@@ -125,7 +125,6 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {flexDirection: 'row',alignItems: 'center',gap: 8,- marginBottom: 8,},title: {fontSize: 20,diff --git a/mobile-app/components/credentialDetails/TotpSection.tsx b/mobile-app/components/credentialDetails/TotpSection.tsxnew file mode 100644index 000000000..8333f6257--- /dev/null+++ b/mobile-app/components/credentialDetails/TotpSection.tsx@@ -0,0 +1,204 @@+import React, { useState, useEffect } from 'react';+import { View, StyleSheet, Pressable, useColorScheme, TouchableOpacity } from 'react-native';+import { ThemedText } from '@/components/ThemedText';+import { ThemedView } from '@/components/ThemedView';+import { Credential } from '@/utils/types/Credential';+import { TotpCode } from '@/utils/types/TotpCode';+import * as OTPAuth from 'otpauth';+import * as Clipboard from 'expo-clipboard';+import { useDb } from '@/context/DbContext';+import Toast from 'react-native-toast-message';++type TotpSectionProps = {+ credential: Credential;+};++export const TotpSection: React.FC<TotpSectionProps> = ({ credential }) => {+ const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);+ const [currentCodes, setCurrentCodes] = useState<Record<string, string>>({});+ const colorScheme = useColorScheme();+ const isDarkMode = colorScheme === 'dark';+ const dbContext = useDb();++ const getRemainingSeconds = (step = 30): number => {+ const totp = new OTPAuth.TOTP({+ secret: 'dummy',+ algorithm: 'SHA1',+ digits: 6,+ period: step+ });+ return totp.period - (Math.floor(Date.now() / 1000) % totp.period);+ };++ const getRemainingPercentage = (): number => {+ const remaining = getRemainingSeconds();+ return Math.floor(((30.0 - remaining) / 30.0) * 100);+ };++ const generateTotpCode = (secretKey: string): string => {+ try {+ const totp = new OTPAuth.TOTP({+ secret: secretKey,+ algorithm: 'SHA1',+ digits: 6,+ period: 30+ });+ return totp.generate();+ } catch (error) {+ console.error('Error generating TOTP code:', error);+ return 'Error';+ }+ };++ const copyToClipboard = async (code: string): Promise<void> => {+ try {+ await Clipboard.setStringAsync(code);+ Toast.show({+ type: 'success',+ text1: 'Copied to clipboard',+ position: 'bottom',+ visibilityTime: 2000,+ });+ } catch (error) {+ console.error('Failed to copy:', error);+ }+ };++ useEffect(() => {+ const loadTotpCodes = async () => {+ if (!dbContext?.sqliteClient) {+ return;+ }++ try {+ const codes = await dbContext.sqliteClient.getTotpCodesForCredential(credential.Id);+ setTotpCodes(codes);+ } catch (error) {+ console.error('Error loading TOTP codes:', error);+ }+ };++ loadTotpCodes();+ }, [credential.Id, dbContext?.sqliteClient]);++ useEffect(() => {+ const updateTotpCodes = (prevCodes: Record<string, string>): Record<string, string> => {+ const newCodes: Record<string, string> = {};+ totpCodes.forEach(code => {+ const generatedCode = generateTotpCode(code.SecretKey);+ if (generatedCode !== 'Error') {+ newCodes[code.Id] = generatedCode;+ } else {+ newCodes[code.Id] = prevCodes[code.Id] ?? 'Error';+ }+ });+ return newCodes;+ };++ const initialCodes: Record<string, string> = {};+ totpCodes.forEach(code => {+ initialCodes[code.Id] = generateTotpCode(code.SecretKey);+ });+ setCurrentCodes(initialCodes);++ const intervalId = setInterval(() => {+ setCurrentCodes(updateTotpCodes);+ }, 1000);++ return () => clearInterval(intervalId);+ }, [totpCodes]);++ if (totpCodes.length === 0) {+ return null;+ }++ return (+ <ThemedView style={styles.container}>+ <ThemedText type="subtitle">+ Two-factor authentication+ </ThemedText>+ {totpCodes.map(totpCode => (+ <TouchableOpacity+ key={totpCode.Id}+ style={[+ styles.content,+ {+ backgroundColor: isDarkMode ? '#1f2937' : '#f3f4f6',+ borderColor: isDarkMode ? '#374151' : '#d1d5db',+ }+ ]}+ onPress={() => copyToClipboard(currentCodes[totpCode.Id])}+ >+ <View style={styles.codeContainer}>+ <View>+ <ThemedText style={[styles.label, { color: isDarkMode ? '#9ca3af' : '#6b7280' }]}>+ TOTP Code+ </ThemedText>+ <ThemedText style={[styles.code, { color: isDarkMode ? '#f3f4f6' : '#1f2937' }]}>+ {currentCodes[totpCode.Id]}+ </ThemedText>+ </View>+ <View style={styles.timerContainer}>+ <ThemedText style={[styles.timer, { color: isDarkMode ? '#9ca3af' : '#6b7280' }]}>+ {getRemainingSeconds()}s+ </ThemedText>+ <View style={styles.progressBar}>+ <View+ style={[+ styles.progressFill,+ { width: `${getRemainingPercentage()}%` }+ ]}+ />+ </View>+ </View>+ </View>+ </TouchableOpacity>+ ))}+ </ThemedView>+ );+};++const styles = StyleSheet.create({+ container: {+ padding: 16,+ marginTop: 16,+ },+ content: {+ marginTop: 8,+ borderRadius: 8,+ borderWidth: 1,+ padding: 12,+ },+ codeContainer: {+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ },+ label: {+ fontSize: 12,+ marginBottom: 4,+ },+ code: {+ fontSize: 24,+ fontWeight: 'bold',+ letterSpacing: 2,+ },+ timerContainer: {+ alignItems: 'flex-end',+ },+ timer: {+ fontSize: 12,+ marginBottom: 4,+ },+ progressBar: {+ width: 40,+ height: 4,+ backgroundColor: 'rgba(0, 0, 0, 0.1)',+ borderRadius: 2,+ overflow: 'hidden',+ },+ progressFill: {+ height: '100%',+ backgroundColor: '#007AFF',+ },+});\ No newline at end of filediff --git a/mobile-app/package-lock.json b/mobile-app/package-lock.jsonindex f1ec86f90..b1cba9a95 100644--- a/mobile-app/package-lock.json+++ b/mobile-app/package-lock.json@@ -31,6 +31,7 @@"expo-system-ui": "~4.0.9","expo-web-browser": "~14.0.2","fbemitter": "^3.0.0",+ "otpauth": "^9.4.0","react": "18.3.1","react-dom": "18.3.1","react-native": "0.76.9",@@ -3484,6 +3485,18 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@noble/hashes": {+ "version": "1.7.1",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.1.tgz",+ "integrity": "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ==",+ "license": "MIT",+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },"node_modules/@nodelib/fs.scandir": {"version": "2.1.5","resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",@@ -11958,6 +11971,18 @@"node": ">=4"}},+ "node_modules/otpauth": {+ "version": "9.4.0",+ "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.4.0.tgz",+ "integrity": "sha512-fHIfzIG5RqCkK9cmV8WU+dPQr9/ebR5QOwGZn2JAr1RQF+lmAuLL2YdtdqvmBjNmgJlYk3KZ4a0XokaEhg1Jsw==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "1.7.1"+ },+ "funding": {+ "url": "https://github.com/hectorm/otpauth?sponsor=1"+ }+ },"node_modules/p-finally": {"version": "1.0.0","resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",diff --git a/mobile-app/package.json b/mobile-app/package.jsonindex 452c3aefe..72e2ad226 100644--- a/mobile-app/package.json+++ b/mobile-app/package.json@@ -28,6 +28,7 @@"expo-font": "~13.0.4","expo-haptics": "~14.0.1","expo-linking": "~7.0.5",+ "expo-local-authentication": "~15.0.2","expo-router": "~4.0.20","expo-sharing": "~13.0.1","expo-splash-screen": "~0.29.22",@@ -37,6 +38,7 @@"expo-system-ui": "~4.0.9","expo-web-browser": "~14.0.2","fbemitter": "^3.0.0",+ "otpauth": "^9.4.0","react": "18.3.1","react-dom": "18.3.1","react-native": "0.76.9",@@ -52,8 +54,7 @@"react-native-toast-message": "^2.2.1","react-native-web": "~0.19.13","react-native-webview": "13.12.5",- "secure-remote-password": "github:LinusU/secure-remote-password#73e5f732b6ca0cdbdc19da1a0c5f48cdbad2cbf0",- "expo-local-authentication": "~15.0.2"+ "secure-remote-password": "github:LinusU/secure-remote-password#73e5f732b6ca0cdbdc19da1a0c5f48cdbad2cbf0"},"devDependencies": {"@babel/core": "^7.25.2",