Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add TotpViewer component (#672)
Leendert de Borst4fa3fedea238
diff --git a/browser-extension/package-lock.json b/browser-extension/package-lock.jsonindex a38eccbd7..8a47515bc 100644--- a/browser-extension/package-lock.json+++ b/browser-extension/package-lock.json@@ -9,9 +9,11 @@"version": "0.0.0","hasInstallScript": true,"dependencies": {+ "@types/node": "^22.13.10","argon2-browser": "^1.18.0","buffer": "^6.0.3","globals": "^16.0.0",+ "otpauth": "^9.3.6","react": "^19.0.0","react-dom": "^19.0.0","react-router-dom": "^7.1.4",@@ -1473,6 +1475,18 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@noble/hashes": {+ "version": "1.6.1",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.6.1.tgz",+ "integrity": "sha512-pq5D8h10hHBjyqX+cfBm0i8JUXJ0UhczFc4r74zbuT9XgewFo2E3J1cOaGtdZynILNmQ685YWGzGE1Zv6io50w==",+ "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",@@ -2056,10 +2070,9 @@"license": "MIT"},"node_modules/@types/node": {- "version": "22.13.9",- "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.9.tgz",- "integrity": "sha512-acBjXdRJ3A6Pb3tqnw9HZmyR3Fiol3aGxRCK1x3d+6CDAMjl7I649wpSd+yNURCjbOUGu9tqtLKnTGxmK6CyGw==",- "devOptional": true,+ "version": "22.13.10",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.10.tgz",+ "integrity": "sha512-I6LPUvlRH+O6VRUqYOcMudhaIdUVWfsjnZavnsraHvpBwaEyMN29ry+0UVJhImYL16xsscu0aske3yA+uPOWfw==","license": "MIT","dependencies": {"undici-types": "~6.20.0"@@ -9114,6 +9127,18 @@"node": ">= 0.4.0"}},+ "node_modules/otpauth": {+ "version": "9.3.6",+ "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.3.6.tgz",+ "integrity": "sha512-eIcCvuEvcAAPHxUKC9Q4uCe0Fh/yRc5jv9z+f/kvyIF2LPrhgAOuLB7J9CssGYhND/BL8M9hlHBTFmffpoQlMQ==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "1.6.1"+ },+ "funding": {+ "url": "https://github.com/hectorm/otpauth?sponsor=1"+ }+ },"node_modules/own-keys": {"version": "1.0.1","resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",@@ -12223,7 +12248,6 @@"version": "6.20.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz","integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==",- "devOptional": true,"license": "MIT"},"node_modules/unimport": {diff --git a/browser-extension/package.json b/browser-extension/package.jsonindex 65258a9b1..74ede67f3 100644--- a/browser-extension/package.json+++ b/browser-extension/package.json@@ -24,9 +24,11 @@"postinstall": "wxt prepare"},"dependencies": {+ "@types/node": "^22.13.10","argon2-browser": "^1.18.0","buffer": "^6.0.3","globals": "^16.0.0",+ "otpauth": "^9.3.6","react": "^19.0.0","react-dom": "^19.0.0","react-router-dom": "^7.1.4",diff --git a/browser-extension/src/entrypoints/popup/components/TotpViewer.tsx b/browser-extension/src/entrypoints/popup/components/TotpViewer.tsxnew file mode 100644index 000000000..983563d30--- /dev/null+++ b/browser-extension/src/entrypoints/popup/components/TotpViewer.tsx@@ -0,0 +1,190 @@+import React, { useState, useEffect, useRef } 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();+ const intervalRef = useRef<NodeJS.Timeout | null>(null);++ /**+ * 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';+ }+ };++ /**+ * Refreshes the TOTP codes.+ */+ const refreshCodes = (): void => {+ 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] = currentCodes[code.Id] || 'Error';+ }+ });++ setCurrentCodes(newCodes);+ };++ /**+ * 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(() => {+ 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(() => {+ // 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 interval = setInterval(refreshCodes, 1000);+ intervalRef.current = interval;++ // Clean up interval on unmount or when totpCodes change+ return () => {+ clearInterval(interval);+ intervalRef.current = null;+ };+ }, [totpCodes]);++ if (loading) {+ return (+ <div className="text-gray-500 dark:text-gray-400 mb-4">+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-2">Two-factor authentication</h2>+ Loading TOTP codes...+ </div>+ );+ }++ if (totpCodes.length === 0) {+ return null; // Don't show anything if there are no TOTP codes+ }++ 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 => (+ <div key={totpCode.Id} className="p-2 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-700 dark:border-gray-600">+ <div className="flex justify-between items-center gap-2">+ <div className="flex items-center flex-1">+ <h4 className="text-base 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">+ <div+ className="text-xl font-bold cursor-pointer text-gray-900 dark:text-white hover:text-primary-600 dark:hover:text-primary-400 transition-colors"+ onClick={() => copyToClipboard(currentCodes[totpCode.Id], totpCode.Id)}+ >+ {currentCodes[totpCode.Id]}+ </div>+ <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>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+};\ No newline at end of filediff --git a/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx b/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsxindex 7abce820f..2ca507bb3 100644--- a/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx+++ b/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx@@ -5,6 +5,7 @@ import { Credential } from '../../../utils/types/Credential';import { Buffer } from 'buffer';import { FormInputCopyToClipboard } from '../components/FormInputCopyToClipboard';import { EmailPreview } from '../components/EmailPreview';+import { TotpViewer } from '../components/TotpViewer';import { useLoading } from '../context/LoadingContext';/**@@ -157,6 +158,8 @@ const CredentialDetails: React.FC = () => {)}</div>+ <TotpViewer credentialId={credential.Id} />+<div className="grid gap-6"><div className="space-y-4 lg:col-span-2 xl:col-span-1"><h2 className="text-xl font-semibold text-gray-900 dark:text-white">Login credentials</h2>diff --git a/browser-extension/src/utils/SqliteClient.tsx b/browser-extension/src/utils/SqliteClient.tsxindex 71c60df98..b4aa4add9 100644--- a/browser-extension/src/utils/SqliteClient.tsx+++ b/browser-extension/src/utils/SqliteClient.tsx@@ -1,6 +1,7 @@import initSqlJs, { Database } from 'sql.js';import { Credential } from './types/Credential';import { EncryptionKey } from './types/EncryptionKey';+import { TotpCode } from './types/TotpCode';/*** Client for interacting with the SQLite database.@@ -421,6 +422,64 @@ class SqliteClient {throw error;}}++ /**+ * Get TOTP codes for a credential+ * @param credentialId - The ID of the credential to get TOTP codes for+ * @returns Array of TotpCode objects+ */+ public getTotpCodesForCredential(credentialId: string): TotpCode[] {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ // Check if TotpCodes table exists (for backward compatibility).+ // TODO: whenever the browser extension has a minimum client DB version of 1.5.0+,+ // we can remove this check as the TotpCodes table then is guaranteed to exist.+ if (!this.tableExists('TotpCodes')) {+ return [];+ }++ const query = `+ SELECT+ Id,+ Name,+ SecretKey,+ CredentialId+ FROM TotpCodes+ WHERE CredentialId = ? AND IsDeleted = 0`;++ return this.executeQuery<TotpCode>(query, [credentialId]);+ } catch (error) {+ console.error('Error getting TOTP codes:', error);+ // Return empty array instead of throwing to be robust+ return [];+ }+ }++ /**+ * Check if a table exists in the database+ * @param tableName - The name of the table to check+ * @returns True if the table exists, false otherwise+ */+ private tableExists(tableName: string): boolean {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ const query = `+ SELECT name FROM sqlite_master+ WHERE type='table' AND name=?`;++ const results = this.executeQuery(query, [tableName]);+ return results.length > 0;+ } catch (error) {+ console.error(`Error checking if table ${tableName} exists:`, error);+ return false;+ }+ }}export default SqliteClient;\ No newline at end of filediff --git a/browser-extension/src/utils/generators/Totp/TotpGenerator.ts b/browser-extension/src/utils/generators/Totp/TotpGenerator.tsnew file mode 100644index 000000000..684771331--- /dev/null+++ b/browser-extension/src/utils/generators/Totp/TotpGenerator.ts@@ -0,0 +1,196 @@+/**+ * TOTP Generator utility for generating Time-based One-Time Passwords.+ * Based on RFC 6238 (https://tools.ietf.org/html/rfc6238).+ */+export class TotpGenerator {+ /**+ * Generates a Time-based One-Time Password (TOTP) for the given secret key.+ * @param secretKey The secret key in Base32 encoding.+ * @param digits The number of digits in the generated code. Default is 6.+ * @param step The time step in seconds. Default is 30.+ * @returns The generated TOTP code.+ */+ public static generateTotpCode(secretKey: string, digits: number = 6, step: number = 30): string {+ // Remove any whitespace and hyphens from the secret key+ secretKey = secretKey.replace(/\s|-/g, '');++ // Convert the secret key from Base32 to byte array+ const keyBytes = this.base32ToBytes(secretKey);++ // Get the current Unix timestamp and calculate the counter value+ const counter = Math.floor(Date.now() / 1000 / step);++ // Generate the TOTP code+ return this.generateHOTP(keyBytes, counter, digits);+ }++ /**+ * Calculates the remaining seconds until the next TOTP code generation.+ * @param step The time step in seconds. Default is 30.+ * @returns The remaining seconds.+ */+ public static getRemainingSeconds(step: number = 30): number {+ const unixTimestamp = Math.floor(Date.now() / 1000);+ return step - (unixTimestamp % step);+ }++ /**+ * Calculates the remaining percentage until the next TOTP code generation.+ * @param step The time step in seconds. Default is 30.+ * @returns The remaining percentage (0-100).+ */+ public static getRemainingPercentage(step: number = 30): number {+ const remaining = this.getRemainingSeconds(step);+ // Invert the percentage so it counts down instead of up+ return Math.floor(((step - remaining) / step) * 100);+ }++ /**+ * Generates an HMAC-based One-Time Password (HOTP) for the given key and counter.+ * @param key The secret key as a byte array.+ * @param counter The counter value.+ * @param digits The number of digits in the generated code.+ * @returns The generated HOTP code.+ */+ private static generateHOTP(key: Uint8Array, counter: number, digits: number): string {+ // Convert counter to a byte array (8 bytes, big-endian)+ const counterBytes = new Uint8Array(8);+ for (let i = 7; i >= 0; i--) {+ counterBytes[i] = counter & 0xff;+ counter = counter >> 8;+ }++ // Calculate HMAC-SHA1+ const hmac = this.hmacSha1(key, counterBytes);++ // Dynamic truncation+ const offset = hmac[hmac.length - 1] & 0xf;+ const binary =+ ((hmac[offset] & 0x7f) << 24) |+ ((hmac[offset + 1] & 0xff) << 16) |+ ((hmac[offset + 2] & 0xff) << 8) |+ (hmac[offset + 3] & 0xff);++ // Generate the code+ const code = binary % Math.pow(10, digits);+ return code.toString().padStart(digits, '0');+ }++ /**+ * Converts a Base32 encoded string to a byte array.+ * @param base32 The Base32 encoded string.+ * @returns The byte array.+ */+ private static base32ToBytes(base32: string): Uint8Array {+ // Base32 character set (RFC 4648)+ const base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';++ // Convert to uppercase and remove padding+ base32 = base32.toUpperCase().replace(/=+$/, '');++ // Initialize variables+ const length = base32.length;+ const output = new Uint8Array(Math.floor(length * 5 / 8));+ let bits = 0;+ let value = 0;+ let index = 0;++ // Process each character+ for (let i = 0; i < length; i++) {+ const charValue = base32Chars.indexOf(base32[i]);+ if (charValue === -1) {+ throw new Error('Invalid Base32 character: ' + base32[i]);+ }++ // Add 5 bits to the buffer+ value = (value << 5) | charValue;+ bits += 5;++ // If we have at least 8 bits, extract a byte+ if (bits >= 8) {+ bits -= 8;+ output[index++] = (value >> bits) & 0xff;+ }+ }++ return output;+ }++ /**+ * Calculates the HMAC-SHA1 of a message using a key.+ * @param key The key as a byte array.+ * @param message The message as a byte array.+ * @returns The HMAC-SHA1 digest as a byte array.+ */+ private static hmacSha1(key: Uint8Array, message: Uint8Array): Uint8Array {+ // Simple implementation of HMAC-SHA1+ // In a real implementation, you would use a crypto library+ // This is a placeholder that should be replaced with a proper implementation++ // For now, we'll use the Web Crypto API if available+ if (typeof crypto !== 'undefined' && crypto.subtle) {+ // This is async, but we need a sync implementation for this example+ // In a real implementation, you would make this method async+ console.warn('Web Crypto API is available but not used in this synchronous implementation');+ }++ // Fallback implementation (not secure, for demonstration only)+ // In a real implementation, use a proper crypto library+ const blockSize = 64;++ // Prepare the key+ let keyToUse = key;+ if (key.length > blockSize) {+ // If key is too long, hash it+ keyToUse = this.sha1(key);+ }+ if (key.length < blockSize) {+ // If key is too short, pad it with zeros+ const paddedKey = new Uint8Array(blockSize);+ paddedKey.set(keyToUse);+ keyToUse = paddedKey;+ }++ // Prepare the inner and outer padded keys+ const innerPadded = new Uint8Array(blockSize);+ const outerPadded = new Uint8Array(blockSize);++ for (let i = 0; i < blockSize; i++) {+ innerPadded[i] = keyToUse[i] ^ 0x36;+ outerPadded[i] = keyToUse[i] ^ 0x5c;+ }++ // Concatenate inner padded key with message+ const innerData = new Uint8Array(innerPadded.length + message.length);+ innerData.set(innerPadded);+ innerData.set(message, innerPadded.length);++ // Hash the inner data+ const innerHash = this.sha1(innerData);++ // Concatenate outer padded key with inner hash+ const outerData = new Uint8Array(outerPadded.length + innerHash.length);+ outerData.set(outerPadded);+ outerData.set(innerHash, outerPadded.length);++ // Hash the outer data+ return this.sha1(outerData);+ }++ /**+ * Calculates the SHA-1 hash of a message.+ * @param message The message as a byte array.+ * @returns The SHA-1 hash as a byte array.+ */+ private static sha1(message: Uint8Array): Uint8Array {+ // This is a placeholder for a proper SHA-1 implementation+ // In a real implementation, use a proper crypto library++ // For demonstration purposes, we'll return a fixed-length array+ // This is NOT a real SHA-1 implementation+ console.warn('Using placeholder SHA-1 implementation - NOT SECURE');++ // Return a 20-byte array (SHA-1 digest length)+ return new Uint8Array(20).fill(1);+ }+}\ No newline at end of filediff --git a/browser-extension/src/utils/types/TotpCode.ts b/browser-extension/src/utils/types/TotpCode.tsnew file mode 100644index 000000000..0dc11bdb6--- /dev/null+++ b/browser-extension/src/utils/types/TotpCode.ts@@ -0,0 +1,16 @@+/**+ * TotpCode SQLite database type.+ */+export type TotpCode = {+ /** The ID of the TOTP code */+ Id: string;++ /** The name of the TOTP code */+ Name: string;++ /** The secret key for the TOTP code */+ SecretKey: string;++ /** The credential ID this TOTP code belongs to */+ CredentialId: string;+};\ No newline at end of file