Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add advanced fields option to TOTP code editor UI (#2492)
Leendert de Borst2a2d23724e9f
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpAdvancedFields.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpAdvancedFields.tsxnew file mode 100644index 000000000..444801c9b--- /dev/null+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpAdvancedFields.tsx@@ -0,0 +1,87 @@+import { hasCustomTotpParameters, totpParametersFrom } from '@aliasvault/client/items/OtpAuthUri';+import { TOTP_SUPPORTED_ALGORITHMS, TOTP_SUPPORTED_DIGITS } from '@aliasvault/models/vault';+import React from 'react';+import { useTranslation } from 'react-i18next';++import Icon from '@/entrypoints/popup/components/Icons/Icon';++import type { TotpAdvancedValues } from '@aliasvault/client/items/OtpAuthUri';++type TotpSettingsButtonProps = {+ id: string;+ isOpen: boolean;+ onToggle: () => void;+};++/**+ * Gear icon in the secret key label row that shows or hides the TOTP parameter fields.+ */+export const TotpSettingsButton: React.FC<TotpSettingsButtonProps> = ({ id, isOpen, onToggle }) => {+ const { t } = useTranslation();+ return (+ <button+ id={id}+ type="button"+ onClick={onToggle}+ className={`p-1 ${isOpen ? 'text-primary-600 dark:text-primary-500' : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}`}+ title={t('settings.advancedOptions')}+ aria-label={t('settings.advancedOptions')}+ aria-expanded={isOpen}+ >+ <Icon name="cog" className="w-5 h-5" />+ </button>+ );+};++type TotpAdvancedFieldsProps = {+ idPrefix: string;+ values: TotpAdvancedValues;+ onChange: (values: TotpAdvancedValues) => void;+ isOpen: boolean;+ onOpen: () => void;+};++const inputClassName = 'bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2 dark:bg-gray-600 dark:border-gray-500 dark:text-white';+const labelClassName = 'block mb-1 text-xs text-gray-500 dark:text-gray-400';++/**+ * The TOTP parameters under the secret key: one compact row when opened, else a summary when they differ from the defaults.+ */+const TotpAdvancedFields: React.FC<TotpAdvancedFieldsProps> = ({ idPrefix, values, onChange, isOpen, onOpen }) => {+ const { t } = useTranslation();++ if (!isOpen) {+ const parameters = totpParametersFrom(values);+ if (!hasCustomTotpParameters(parameters)) {+ return null;+ }+ return (+ <button id={`${idPrefix}-parameters`} type="button" onClick={onOpen} className="mt-1 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">+ {t('totp.parameterSummary', { algorithm: parameters.Algorithm, digits: parameters.Digits, period: parameters.Period })}+ </button>+ );+ }++ return (+ <div className="mt-2 grid grid-cols-3 gap-2">+ <div>+ <label htmlFor={`${idPrefix}-algorithm`} className={labelClassName}>{t('totp.algorithm')}</label>+ <select id={`${idPrefix}-algorithm`} value={values.algorithm} onChange={(e) => onChange({ ...values, algorithm: e.target.value })} className={inputClassName}>+ {TOTP_SUPPORTED_ALGORITHMS.map(algorithm => <option key={algorithm} value={algorithm}>{algorithm}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-digits`} className={labelClassName}>{t('totp.digits')}</label>+ <select id={`${idPrefix}-digits`} value={values.digits} onChange={(e) => onChange({ ...values, digits: Number(e.target.value) })} className={inputClassName}>+ {TOTP_SUPPORTED_DIGITS.map(digits => <option key={digits} value={digits}>{digits}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-period`} className={labelClassName}>{t('totp.period')}</label>+ <input id={`${idPrefix}-period`} type="number" min={1} max={300} value={values.period} onChange={(e) => onChange({ ...values, period: e.target.value })} className={inputClassName} />+ </div>+ </div>+ );+};++export default TotpAdvancedFields;diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsxindex 9aaa24774..2dfbffc24 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx@@ -1,5 +1,4 @@-import { buildOtpAuthUri, otpAuthDisplayName, parseOtpAuthUri } from '@aliasvault/client/items/OtpAuthUri';-import { TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';+import { buildOtpAuthUri, hasCustomTotpParameters, parseOtpAuthUri, resolveTotpEntry, totpAdvancedValues, totpParametersFrom, type TotpAdvancedValues } from '@aliasvault/client/items/OtpAuthUri';import QRCode from 'qrcode';import React, { useState } from 'react';import { useTranslation } from 'react-i18next';@@ -7,17 +6,20 @@ import { useTranslation } from 'react-i18next';import ConfirmDeleteModal from '@/entrypoints/popup/components/Dialogs/ConfirmDeleteModal';import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';import Icon from '@/entrypoints/popup/components/Icons/Icon';+import TotpAdvancedFields, { TotpSettingsButton } from '@/entrypoints/popup/components/Items/Details/TotpAdvancedFields';import { logFailure } from '@/utils/Diagnostics';import type { TotpCode } from '@aliasvault/models/vault';-type TotpFormData = {+export type TotpFormData = {name: string;secretKey: string;+ /** Algorithm, digits and time step; absent means the defaults. */+ advanced?: TotpAdvancedValues;}-type TotpEditorState = {+export type TotpEditorState = {isAddFormVisible: boolean;formData: TotpFormData;}@@ -54,50 +56,14 @@ const TotpEditor: React.FC<TotpEditorProps> = ({const [editName, setEditName] = useState('');const [showEditNameField, setShowEditNameField] = useState(false);const [editSecret, setEditSecret] = useState('');+ const [editAdvanced, setEditAdvanced] = useState<TotpAdvancedValues>(totpAdvancedValues());+ const [showAdvanced, setShowAdvanced] = useState(!!formData.advanced && hasCustomTotpParameters(totpParametersFrom(formData.advanced)));+ const [showEditAdvanced, setShowEditAdvanced] = useState(false);const [showQrCode, setShowQrCode] = useState(false);const [qrCodeDataUrl, setQrCodeDataUrl] = useState<string | null>(null);const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);const [totpToDelete, setTotpToDelete] = useState<TotpCode | null>(null);- /**- * Sanitizes the secret key by extracting it from a TOTP URI if needed- */- const sanitizeSecretKey = (secretKeyInput: string, nameInput: string): { secretKey: string, name: string, algorithm: string, digits: number, period: number } => {- let secretKey = secretKeyInput.trim();- let name = nameInput.trim();- let algorithm = TOTP_DEFAULT_ALGORITHM;- let digits = TOTP_DEFAULT_DIGITS;- let period = TOTP_DEFAULT_PERIOD;-- // Check if it's a TOTP URI- if (secretKey.toLowerCase().startsWith('otpauth://totp/')) {- const parsed = parseOtpAuthUri(secretKey);- if (!parsed) {- throw new Error(t('totp.errors.invalidSecretKey'));- }- secretKey = parsed.secret;- // Keep the URI's parameters instead of silently regenerating codes with the defaults.- algorithm = parsed.algorithm;- digits = parsed.digits;- period = parsed.period;- // If name is empty, use the issuer and account from the URI- if (!name) {- name = otpAuthDisplayName(parsed);- }- }-- // Remove spaces from the secret key- secretKey = secretKey.replace(/\s/g, '');-- // Validate the secret key format (base32)- if (!/^[A-Z2-7]+=*$/i.test(secretKey)) {- throw new Error(t('totp.errors.invalidSecretKey'));- }-- // Name is optional; keep it blank when none was provided or derived.- return { secretKey, name, algorithm, digits, period };- };-/*** Shows the add form*/@@ -108,6 +74,7 @@ const TotpEditor: React.FC<TotpEditorProps> = ({});setFormError(null);setShowNameField(false);+ setShowAdvanced(false);};/**@@ -132,6 +99,22 @@ const TotpEditor: React.FC<TotpEditorProps> = ({});};+ /**+ * Updates the secret; a pasted otpauth URI also fills the advanced fields with its parameters.+ */+ const updateSecretKey = (secretKey: string): void => {+ const parsed = parseOtpAuthUri(secretKey);+ if (!parsed) {+ updateFormData({ secretKey });+ return;+ }+ const parameters = { Algorithm: parsed.algorithm, Digits: parsed.digits, Period: parsed.period };+ updateFormData({ secretKey, advanced: totpAdvancedValues(parameters) });+ if (hasCustomTotpParameters(parameters)) {+ setShowAdvanced(true);+ }+ };+/*** Hides the optional name field again and clears any entered value*/@@ -153,34 +136,24 @@ const TotpEditor: React.FC<TotpEditorProps> = ({return;}- try {- // Sanitize the secret key- const { secretKey, name, algorithm, digits, period } = sanitizeSecretKey(formData.secretKey, formData.name);-- // Create new TOTP code- const newTotpCode: TotpCode = {- Id: crypto.randomUUID(),- Name: name,- SecretKey: secretKey,- Algorithm: algorithm,- Digits: digits,- Period: period,- ItemId: '' // Will be set when saving the item- };-- // Add to the list- const updatedTotpCodes = [...totpCodes, newTotpCode];- onTotpCodesChange(updatedTotpCodes);-- // Hide the form- hideAddForm();- } catch (error) {- if (error instanceof Error) {- setFormError(error.message);- } else {- setFormError(t('common.errors.unknownErrorTryAgain'));- }+ const entry = resolveTotpEntry(formData.secretKey, formData.name, formData.advanced);+ if (!entry) {+ setFormError(t('totp.errors.invalidSecretKey'));+ return;}++ const newTotpCode: TotpCode = {+ Id: crypto.randomUUID(),+ Name: entry.name,+ SecretKey: entry.secretKey,+ Algorithm: entry.algorithm,+ Digits: entry.digits,+ Period: entry.period,+ ItemId: '' // Will be set when saving the item+ };++ onTotpCodesChange([...totpCodes, newTotpCode]);+ hideAddForm();};/**@@ -237,6 +210,8 @@ const TotpEditor: React.FC<TotpEditorProps> = ({setEditName(totpCode.Name);setShowEditNameField(!!totpCode.Name);setEditSecret(totpCode.SecretKey);+ setEditAdvanced(totpAdvancedValues(totpCode));+ setShowEditAdvanced(hasCustomTotpParameters(totpCode));setIsEditModalOpen(true);setShowQrCode(false);};@@ -276,7 +251,7 @@ const TotpEditor: React.FC<TotpEditorProps> = ({const updatedTotpCodes = totpCodes.map(tc =>tc.Id === editingTotpCode.Id- ? { ...tc, Name: finalName, SecretKey: editSecret }+ ? { ...tc, Name: finalName, SecretKey: editSecret, ...totpParametersFrom(editAdvanced) }: tc);@@ -374,15 +349,18 @@ const TotpEditor: React.FC<TotpEditorProps> = ({)}<div className="mb-4">- <label htmlFor="totp-secret" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">- {t('totp.secretKey')}- </label>+ <div className="flex items-center justify-between mb-2">+ <label htmlFor="totp-secret" className="text-sm font-medium text-gray-900 dark:text-white">+ {t('totp.secretKey')}+ </label>+ <TotpSettingsButton id="totp-settings" isOpen={showAdvanced} onToggle={() => setShowAdvanced(!showAdvanced)} />+ </div><inputid="totp-secret"type="text"autoFocusvalue={formData.secretKey}- onChange={(e) => updateFormData({ secretKey: e.target.value })}+ onChange={(e) => updateSecretKey(e.target.value)}onKeyDown={(e) => {if (e.key === 'Enter') {e.preventDefault();@@ -391,6 +369,13 @@ const TotpEditor: React.FC<TotpEditorProps> = ({}}className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"/>+ <TotpAdvancedFields+ idPrefix="totp"+ values={formData.advanced ?? totpAdvancedValues()}+ onChange={(advanced) => updateFormData({ advanced })}+ isOpen={showAdvanced}+ onOpen={() => setShowAdvanced(true)}+ /></div>{/* Name is optional and hidden by default */}@@ -499,14 +484,17 @@ const TotpEditor: React.FC<TotpEditorProps> = ({<label className="text-sm font-medium text-gray-900 dark:text-white">{t('totp.secretKey')}</label>- <button- type="button"- onClick={toggleQrCode}- className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1"- title={showQrCode ? t('common.hide') + ' QR Code' : t('common.show') + ' QR Code'}- >- <Icon name="qrcode" className="w-5 h-5" />- </button>+ <div className="flex items-center">+ <TotpSettingsButton id="totp-edit-settings" isOpen={showEditAdvanced} onToggle={() => setShowEditAdvanced(!showEditAdvanced)} />+ <button+ type="button"+ onClick={toggleQrCode}+ className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1"+ title={showQrCode ? t('common.hide') + ' QR Code' : t('common.show') + ' QR Code'}+ >+ <Icon name="qrcode" className="w-5 h-5" />+ </button>+ </div></div><inputtype="text"@@ -515,6 +503,13 @@ const TotpEditor: React.FC<TotpEditorProps> = ({className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:text-white font-mono"placeholder={t('totp.secretKey')}/>+ <TotpAdvancedFields+ idPrefix="totp-edit"+ values={editAdvanced}+ onChange={setEditAdvanced}+ isOpen={showEditAdvanced}+ onOpen={() => setShowEditAdvanced(true)}+ />{showQrCode && qrCodeDataUrl && (<div className="flex justify-center mt-3"><div className="bg-white border-2 border-white rounded-lg">diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsxindex 0c531e18f..c5bb1f3d9 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx@@ -24,7 +24,7 @@ import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIconsimport Icon from '@/entrypoints/popup/components/Icons/Icon';import AttachmentUploader from '@/entrypoints/popup/components/Items/Details/AttachmentUploader';import PasskeyEditor from '@/entrypoints/popup/components/Items/Details/PasskeyEditor';-import TotpEditor from '@/entrypoints/popup/components/Items/Details/TotpEditor';+import TotpEditor, { type TotpEditorState } from '@/entrypoints/popup/components/Items/Details/TotpEditor';import ItemLogoPicker from '@/entrypoints/popup/components/Items/ItemLogoPicker';import ItemNameInput from '@/entrypoints/popup/components/Items/ItemNameInput';import ItemTypeSelector from '@/entrypoints/popup/components/Items/ItemTypeSelector';@@ -62,13 +62,7 @@ type PersistedFormData = {fieldValues: Record<string, string | string[]>;typeSwitchStash?: Record<string, FormFieldValue>;customFields: CustomFieldDefinition[];- totpEditorState?: {- isAddFormVisible: boolean;- formData: {- name: string;- secretKey: string;- };- };+ totpEditorState?: TotpEditorState;show2FA: boolean;showAttachments: boolean;manuallyAddedFields: string[];@@ -157,10 +151,7 @@ const ItemAddEdit: React.FC = () => {// TOTP codes stateconst [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);const [originalTotpCodeIds, setOriginalTotpCodeIds] = useState<string[]>([]);- const [totpEditorState, setTotpEditorState] = useState<{- isAddFormVisible: boolean;- formData: { name: string; secretKey: string };- }>({+ const [totpEditorState, setTotpEditorState] = useState<TotpEditorState>({isAddFormVisible: false,formData: { name: '', secretKey: '' }});diff --git a/apps/mobile-app/components/items/details/TotpAdvancedFields.tsx b/apps/mobile-app/components/items/details/TotpAdvancedFields.tsxnew file mode 100644index 000000000..25f55f08c--- /dev/null+++ b/apps/mobile-app/components/items/details/TotpAdvancedFields.tsx@@ -0,0 +1,125 @@+import { Ionicons } from '@expo/vector-icons';+import React, { useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { StyleSheet, TextInput, TouchableOpacity, View } from 'react-native';+import ContextMenu from 'react-native-context-menu-view';++import { ThemedText } from '@/components/themed/ThemedText';+import { useColors } from '@/hooks/useColorScheme';+import { hasCustomTotpParameters, totpParametersFrom, type TotpAdvancedValues } from '@aliasvault/client/items/OtpAuthUri';+import { TOTP_SUPPORTED_ALGORITHMS, TOTP_SUPPORTED_DIGITS } from '@aliasvault/models/vault';++type TotpSettingsButtonProps = {+ isOpen: boolean;+ onToggle: () => void;+};++/**+ * Gear icon in the secret key label row that shows or hides the TOTP parameter fields.+ */+export const TotpSettingsButton: React.FC<TotpSettingsButtonProps> = ({ isOpen, onToggle }) => {+ const { t } = useTranslation();+ const colors = useColors();+ return (+ <TouchableOpacity onPress={onToggle} style={{ padding: 4 }} accessibilityRole="button" accessibilityLabel={t('settings.advancedOptions')} accessibilityState={{ expanded: isOpen }} testID="totp-settings">+ <Ionicons name="settings-outline" size={20} color={isOpen ? colors.primary : colors.textMuted} />+ </TouchableOpacity>+ );+};++type TotpAdvancedFieldsProps = {+ values: TotpAdvancedValues;+ onChange: (values: TotpAdvancedValues) => void;+ isOpen: boolean;+ onOpen: () => void;+};++/**+ * The TOTP parameters under the secret key: one compact row when opened, else a summary when they differ from the defaults.+ */+export const TotpAdvancedFields: React.FC<TotpAdvancedFieldsProps> = ({ values, onChange, isOpen, onOpen }) => {+ const { t } = useTranslation();+ const colors = useColors();++ const styles = useMemo(() => StyleSheet.create({+ cell: {+ flex: 1,+ },+ field: {+ alignItems: 'center',+ backgroundColor: colors.background,+ borderColor: colors.accentBorder,+ borderRadius: 8,+ borderWidth: 1,+ flexDirection: 'row',+ height: 40,+ justifyContent: 'space-between',+ paddingHorizontal: 10,+ },+ fieldText: {+ color: colors.text,+ fontSize: 14,+ },+ label: {+ color: colors.textMuted,+ fontSize: 12,+ marginBottom: 4,+ },+ row: {+ flexDirection: 'row',+ gap: 8,+ marginTop: 8,+ },+ summary: {+ color: colors.textMuted,+ fontSize: 12,+ marginTop: 6,+ },+ }), [colors]);++ if (!isOpen) {+ const parameters = totpParametersFrom(values);+ if (!hasCustomTotpParameters(parameters)) {+ return null;+ }+ return (+ <TouchableOpacity onPress={onOpen} testID="totp-parameters">+ <ThemedText style={styles.summary}>+ {t('totp.parameterSummary', { algorithm: parameters.Algorithm, digits: parameters.Digits, period: parameters.Period })}+ </ThemedText>+ </TouchableOpacity>+ );+ }++ /**+ * A field that opens a native dropdown with the options.+ */+ const renderDropdown = <T extends string | number>(label: string, options: readonly T[], selected: T, onSelect: (value: T) => void): React.ReactNode => (+ <View style={styles.cell}>+ <ThemedText style={styles.label}>{label}</ThemedText>+ <ContextMenu dropdownMenuMode actions={options.map(option => ({ title: String(option), selected: option === selected }))} onPress={(event) => onSelect(options[event.nativeEvent.index])}>+ <View style={styles.field} accessible accessibilityRole="button" accessibilityLabel={label}>+ <ThemedText style={styles.fieldText}>{selected}</ThemedText>+ <Ionicons name="chevron-down" size={14} color={colors.textMuted} />+ </View>+ </ContextMenu>+ </View>+ );++ return (+ <View style={styles.row}>+ {renderDropdown(t('totp.algorithm'), TOTP_SUPPORTED_ALGORITHMS, values.algorithm as typeof TOTP_SUPPORTED_ALGORITHMS[number], algorithm => onChange({ ...values, algorithm }))}+ {renderDropdown(t('totp.digits'), TOTP_SUPPORTED_DIGITS, values.digits as typeof TOTP_SUPPORTED_DIGITS[number], digits => onChange({ ...values, digits }))}+ <View style={styles.cell}>+ <ThemedText style={styles.label}>{t('totp.period')}</ThemedText>+ <TextInput+ style={[styles.field, styles.fieldText]}+ value={values.period}+ onChangeText={period => onChange({ ...values, period: period.replace(/[^0-9]/g, '') })}+ keyboardType="number-pad"+ maxLength={3}+ />+ </View>+ </View>+ );+};diff --git a/apps/mobile-app/components/items/details/TotpEditor.tsx b/apps/mobile-app/components/items/details/TotpEditor.tsxindex 6981aa138..fd47828a0 100644--- a/apps/mobile-app/components/items/details/TotpEditor.tsx+++ b/apps/mobile-app/components/items/details/TotpEditor.tsx@@ -6,14 +6,14 @@ import { View, StyleSheet, TextInput, Modal, TouchableOpacity, ScrollView, Keyboimport QRCode from 'react-native-qrcode-svg';import { ModalBackdrop } from '@/components/common/ModalBackdrop';+import { TotpAdvancedFields, TotpSettingsButton } from '@/components/items/details/TotpAdvancedFields';import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';import { useDialog } from '@/context/DialogContext';import { useColors } from '@/hooks/useColorScheme';import NativeVaultManager from '@/specs/NativeVaultManager';import type { TotpCode } from '@aliasvault/models/vault';-import { TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';-import { buildOtpAuthUri, otpAuthDisplayName, parseOtpAuthUri } from '@aliasvault/client/items/OtpAuthUri';+import { buildOtpAuthUri, hasCustomTotpParameters, otpAuthDisplayName, parseOtpAuthUri, resolveTotpEntry, totpAdvancedValues, totpParametersFrom, type TotpAdvancedValues } from '@aliasvault/client/items/OtpAuthUri';type TotpFormData = {name: string;@@ -58,6 +58,10 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({const [editName, setEditName] = useState('');const [showEditNameField, setShowEditNameField] = useState(false);const [editSecret, setEditSecret] = useState('');+ const [advanced, setAdvanced] = useState<TotpAdvancedValues>(totpAdvancedValues());+ const [showAdvanced, setShowAdvanced] = useState(false);+ const [editAdvanced, setEditAdvanced] = useState<TotpAdvancedValues>(totpAdvancedValues());+ const [showEditAdvanced, setShowEditAdvanced] = useState(false);const [showQrCode, setShowQrCode] = useState(false);const hasLaunchedScanner = React.useRef(false);@@ -83,6 +87,8 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({setFormData({ name: '', secretKey: '' });setFormError(null);setShowNameField(false);+ setAdvanced(totpAdvancedValues());+ setShowAdvanced(false);setIsAddFormVisible(true);};@@ -153,41 +159,18 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({}, [showAddFormRef]);/**- * Sanitizes the secret key by extracting it from a TOTP URI if needed+ * Updates the secret; a pasted otpauth URI also fills the advanced fields with its parameters.*/- const sanitizeSecretKey = (secretKeyInput: string, nameInput: string): { secretKey: string, name: string, algorithm: string, digits: number, period: number } => {- let secretKey = secretKeyInput.trim();- let name = nameInput.trim();- let algorithm = TOTP_DEFAULT_ALGORITHM;- let digits = TOTP_DEFAULT_DIGITS;- let period = TOTP_DEFAULT_PERIOD;-- // Check if it's a TOTP URI- if (secretKey.toLowerCase().startsWith('otpauth://totp/')) {- const parsed = parseOtpAuthUri(secretKey);- if (!parsed) {- throw new Error(t('totp.errors.invalidSecretKey'));- }- secretKey = parsed.secret;- algorithm = parsed.algorithm;- digits = parsed.digits;- period = parsed.period;- // If name is empty, use the issuer and account from the URI- if (!name) {- name = otpAuthDisplayName(parsed);+ const updateSecretKey = (secretKey: string): void => {+ setFormData({ ...formData, secretKey });+ const parsed = parseOtpAuthUri(secretKey);+ if (parsed) {+ const parameters = { Algorithm: parsed.algorithm, Digits: parsed.digits, Period: parsed.period };+ setAdvanced(totpAdvancedValues(parameters));+ if (hasCustomTotpParameters(parameters)) {+ setShowAdvanced(true);}}-- // Remove spaces from the secret key- secretKey = secretKey.replace(/\s/g, '');-- // Validate the secret key format (base32)- if (!/^[A-Z2-7]+=*$/i.test(secretKey)) {- throw new Error(t('totp.errors.invalidSecretKey'));- }-- // Name is optional; keep it blank when none was provided or derived.- return { secretKey, name, algorithm, digits, period };};/**@@ -220,34 +203,24 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({return;}- try {- // Sanitize the secret key- const { secretKey, name, algorithm, digits, period } = sanitizeSecretKey(formData.secretKey, formData.name);-- // Create new TOTP code- const newTotpCode: TotpCode = {- Id: crypto.randomUUID(),- Name: name,- SecretKey: secretKey,- Algorithm: algorithm,- Digits: digits,- Period: period,- ItemId: '' // Will be set when saving the item- };-- // Add to the list- const updatedTotpCodes = [...totpCodes, newTotpCode];- onTotpCodesChange(updatedTotpCodes);-- // Hide the form- hideAddForm();- } catch (error) {- if (error instanceof Error) {- setFormError(error.message);- } else {- setFormError(t('common.errors.unknownErrorTryAgain'));- }+ const entry = resolveTotpEntry(formData.secretKey, formData.name, advanced);+ if (!entry) {+ setFormError(t('totp.errors.invalidSecretKey'));+ return;}++ const newTotpCode: TotpCode = {+ Id: crypto.randomUUID(),+ Name: entry.name,+ SecretKey: entry.secretKey,+ Algorithm: entry.algorithm,+ Digits: entry.digits,+ Period: entry.period,+ ItemId: '' // Will be set when saving the item+ };++ onTotpCodesChange([...totpCodes, newTotpCode]);+ hideAddForm();};/**@@ -295,6 +268,8 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({setEditName(totpCode.Name);setShowEditNameField(!!totpCode.Name);setEditSecret(totpCode.SecretKey);+ setEditAdvanced(totpAdvancedValues(totpCode));+ setShowEditAdvanced(hasCustomTotpParameters(totpCode));setShowQrCode(false);setIsEditModalOpen(true);};@@ -333,7 +308,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({const updatedTotpCodes = totpCodes.map(tc =>tc.Id === editingTotpCode.Id- ? { ...tc, Name: finalName, SecretKey: editSecret }+ ? { ...tc, Name: finalName, SecretKey: editSecret, ...totpParametersFrom(editAdvanced) }: tc);@@ -713,19 +688,25 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({{t('totp.instructions')}</ThemedText>- <ThemedText style={styles.label}>- {t('totp.secretKey')}- </ThemedText>+ <View style={styles.nameLabelRow}>+ <ThemedText style={styles.label}>+ {t('totp.secretKey')}+ </ThemedText>+ <View style={{ marginTop: 12 }}>+ <TotpSettingsButton isOpen={showAdvanced} onToggle={() => setShowAdvanced(!showAdvanced)} />+ </View>+ </View><TextInputstyle={[styles.input, formError && styles.inputError]}placeholderTextColor={colors.textMuted}value={formData.secretKey}- onChangeText={(text) => setFormData({ ...formData, secretKey: text })}+ onChangeText={updateSecretKey}autoCapitalize="characters"autoCorrect={false}autoFocusmultiline/>+ <TotpAdvancedFields values={advanced} onChange={setAdvanced} isOpen={showAdvanced} onOpen={() => setShowAdvanced(true)} />{formError && (<ThemedText style={styles.errorText}>@@ -827,12 +808,15 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({<ThemedText style={styles.label}>{t('totp.secretKey')}</ThemedText>- <TouchableOpacity- onPress={toggleQrCode}- style={{ padding: 4 }}- >- <Ionicons name="qr-code-outline" size={20} color={colors.textMuted} />- </TouchableOpacity>+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>+ <TotpSettingsButton isOpen={showEditAdvanced} onToggle={() => setShowEditAdvanced(!showEditAdvanced)} />+ <TouchableOpacity+ onPress={toggleQrCode}+ style={{ padding: 4 }}+ >+ <Ionicons name="qr-code-outline" size={20} color={colors.textMuted} />+ </TouchableOpacity>+ </View></View></View><TextInput@@ -845,6 +829,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({autoCorrect={false}multiline/>+ <TotpAdvancedFields values={editAdvanced} onChange={setEditAdvanced} isOpen={showEditAdvanced} onOpen={() => setShowEditAdvanced(true)} />{/* Name is optional; hidden by default unless a custom name was set. */}{showEditNameField ? (diff --git a/apps/web/src/components/totp/TotpAdvancedFields.tsx b/apps/web/src/components/totp/TotpAdvancedFields.tsxnew file mode 100644index 000000000..d219947ec--- /dev/null+++ b/apps/web/src/components/totp/TotpAdvancedFields.tsx@@ -0,0 +1,79 @@+import { hasCustomTotpParameters, totpParametersFrom } from '@aliasvault/client/items/OtpAuthUri';+import { TOTP_SUPPORTED_ALGORITHMS, TOTP_SUPPORTED_DIGITS } from '@aliasvault/models/vault';+import React from 'react';+import { useTranslation } from 'react-i18next';++import Icon from '@/components/shared/Icon';++import type { TotpAdvancedValues } from '@aliasvault/client/items/OtpAuthUri';++type TotpSettingsButtonProps = {+ id: string;+ isOpen: boolean;+ onToggle: () => void;+};++/**+ * Gear icon in the secret key label row that shows or hides the TOTP parameter fields.+ */+export const TotpSettingsButton: React.FC<TotpSettingsButtonProps> = ({ id, isOpen, onToggle }) => {+ const { t } = useTranslation();+ return (+ <button id={id} type="button" onClick={onToggle} className={`p-1 ${isOpen ? 'text-primary-600 dark:text-primary-500' : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}`} title={t('settings.advancedOptions')} aria-label={t('settings.advancedOptions')} aria-expanded={isOpen}>+ <Icon name="cog" className="w-5 h-5" />+ </button>+ );+};++type TotpAdvancedFieldsProps = {+ idPrefix: string;+ values: TotpAdvancedValues;+ onChange: (values: TotpAdvancedValues) => void;+ isOpen: boolean;+ onOpen: () => void;+};++const inputClassName = 'bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white';+const labelClassName = 'block mb-1 text-xs text-gray-500 dark:text-gray-400';++/**+ * The TOTP parameters under the secret key: one compact row when opened, else a summary when they differ from the defaults.+ */+const TotpAdvancedFields: React.FC<TotpAdvancedFieldsProps> = ({ idPrefix, values, onChange, isOpen, onOpen }) => {+ const { t } = useTranslation();++ if (!isOpen) {+ const parameters = totpParametersFrom(values);+ if (!hasCustomTotpParameters(parameters)) {+ return null;+ }+ return (+ <button id={`${idPrefix}-parameters`} type="button" onClick={onOpen} className="mt-1 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">+ {t('totp.parameterSummary', { algorithm: parameters.Algorithm, digits: parameters.Digits, period: parameters.Period })}+ </button>+ );+ }++ return (+ <div className="mt-2 grid grid-cols-3 gap-2 max-w-md">+ <div>+ <label htmlFor={`${idPrefix}-algorithm`} className={labelClassName}>{t('totp.algorithm')}</label>+ <select id={`${idPrefix}-algorithm`} value={values.algorithm} onChange={(e) => onChange({ ...values, algorithm: e.target.value })} className={inputClassName}>+ {TOTP_SUPPORTED_ALGORITHMS.map(algorithm => <option key={algorithm} value={algorithm}>{algorithm}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-digits`} className={labelClassName}>{t('totp.digits')}</label>+ <select id={`${idPrefix}-digits`} value={values.digits} onChange={(e) => onChange({ ...values, digits: Number(e.target.value) })} className={inputClassName}>+ {TOTP_SUPPORTED_DIGITS.map(digits => <option key={digits} value={digits}>{digits}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-period`} className={labelClassName}>{t('totp.period')}</label>+ <input id={`${idPrefix}-period`} type="number" min={1} max={300} value={values.period} onChange={(e) => onChange({ ...values, period: e.target.value })} className={inputClassName} />+ </div>+ </div>+ );+};++export default TotpAdvancedFields;diff --git a/apps/web/src/components/totp/TotpCodes.tsx b/apps/web/src/components/totp/TotpCodes.tsxindex 720262e01..001fbff05 100644--- a/apps/web/src/components/totp/TotpCodes.tsx+++ b/apps/web/src/components/totp/TotpCodes.tsx@@ -1,19 +1,20 @@-import { buildOtpAuthUri, otpAuthDisplayName, parseOtpAuthUri } from '@aliasvault/client/items/OtpAuthUri';-import { TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD, type TotpCode } from '@aliasvault/models/vault';+import { buildOtpAuthUri, hasCustomTotpParameters, parseOtpAuthUri, resolveTotpEntry, totpAdvancedValues, totpParametersFrom, type TotpAdvancedValues } from '@aliasvault/client/items/OtpAuthUri';import QRCode from 'qrcode';import React, { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import Button from '@/components/shared/Button';import Card from '@/components/shared/Card';-import FormLabel from '@/components/shared/FormLabel';import FormModal from '@/components/shared/FormModal';import Icon from '@/components/shared/Icon';import InputTextField from '@/components/shared/InputTextField';import SectionTitle from '@/components/shared/SectionTitle';+import TotpAdvancedFields, { TotpSettingsButton } from '@/components/totp/TotpAdvancedFields';import { useConfirmModal } from '@/context/ConfirmModalContext';import { useNotifications } from '@/context/NotificationContext';+import type { TotpCode } from '@aliasvault/models/vault';+type TotpCodesProps = {totpCodes: TotpCode[];onTotpCodesChange: (totpCodes: TotpCode[]) => void;@@ -23,37 +24,6 @@ type TotpCodesProps = {itemUsername: string;};-/**- * The secret, name and parameters of a TOTP entry from a raw secret or an otpauth URI.- */-const sanitizeSecretKey = (secretInput: string, nameInput: string, invalidMessage: string): { secretKey: string; name: string; algorithm: string; digits: number; period: number } => {- let secretKey = secretInput.trim();- let name = nameInput.trim();- let algorithm = TOTP_DEFAULT_ALGORITHM;- let digits = TOTP_DEFAULT_DIGITS;- let period = TOTP_DEFAULT_PERIOD;-- if (secretKey.toLowerCase().startsWith('otpauth://totp/')) {- const parsed = parseOtpAuthUri(secretKey);- if (!parsed) {- throw new Error(invalidMessage);- }- secretKey = parsed.secret;- algorithm = parsed.algorithm;- digits = parsed.digits;- period = parsed.period;- if (name.length === 0) {- name = otpAuthDisplayName(parsed);- }- }-- secretKey = secretKey.replace(/\s/g, '');- if (!/^[A-Z2-7]+=*$/i.test(secretKey)) {- throw new Error(invalidMessage);- }- return { secretKey, name, algorithm, digits, period };-};-/*** The two-factor codes editor of the item form.*/@@ -72,6 +42,10 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, canconst [editName, setEditName] = useState('');const [showEditNameField, setShowEditNameField] = useState(false);const [editSecret, setEditSecret] = useState('');+ const [newAdvanced, setNewAdvanced] = useState<TotpAdvancedValues>(totpAdvancedValues());+ const [showAdvanced, setShowAdvanced] = useState(false);+ const [editAdvanced, setEditAdvanced] = useState<TotpAdvancedValues>(totpAdvancedValues());+ const [showEditAdvanced, setShowEditAdvanced] = useState(false);const [showQrCode, setShowQrCode] = useState(false);const [qrCodeDataUrl, setQrCodeDataUrl] = useState<string | null>(null);@@ -83,9 +57,27 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, cansetNewName('');setSecretError('');setShowNameField(false);+ setNewAdvanced(totpAdvancedValues());+ setShowAdvanced(false);setIsAddFormVisible(true);};+ /**+ * Update the secret; a pasted otpauth URI also fills the advanced fields with its parameters.+ */+ const updateNewSecret = (value: string): void => {+ setNewSecret(value);+ setSecretError('');+ const parsed = parseOtpAuthUri(value);+ if (parsed) {+ const parameters = { Algorithm: parsed.algorithm, Digits: parsed.digits, Period: parsed.period };+ setNewAdvanced(totpAdvancedValues(parameters));+ if (hasCustomTotpParameters(parameters)) {+ setShowAdvanced(true);+ }+ }+ };+/*** Add the entered code to the list.*/@@ -94,14 +86,14 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, cansetSecretError(t('validation.secretKeyRequired'));return;}- try {- const sanitized = sanitizeSecretKey(newSecret, newName, t('totp.errors.invalidSecretKey'));- const code: TotpCode = { Id: crypto.randomUUID(), Name: sanitized.name, SecretKey: sanitized.secretKey, Algorithm: sanitized.algorithm, Digits: sanitized.digits, Period: sanitized.period, ItemId: '' };- onTotpCodesChange([...totpCodes, code]);- setIsAddFormVisible(false);- } catch (error) {- notifications.addErrorMessage(error instanceof Error ? error.message : String(error), true);+ const entry = resolveTotpEntry(newSecret, newName, newAdvanced);+ if (!entry) {+ notifications.addErrorMessage(t('totp.errors.invalidSecretKey'), true);+ return;}+ const code: TotpCode = { Id: crypto.randomUUID(), Name: entry.name, SecretKey: entry.secretKey, Algorithm: entry.algorithm, Digits: entry.digits, Period: entry.period, ItemId: '' };+ onTotpCodesChange([...totpCodes, code]);+ setIsAddFormVisible(false);};/**@@ -127,6 +119,8 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, cansetEditName(code.Name);setShowEditNameField(code.Name.length > 0);setEditSecret(code.SecretKey);+ setEditAdvanced(totpAdvancedValues(code));+ setShowEditAdvanced(hasCustomTotpParameters(code));setShowQrCode(false);setQrCodeDataUrl(null);};@@ -138,7 +132,7 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, canif (!editingCode) {return;}- onTotpCodesChange(totpCodes.map(c => c.Id === editingCode.Id ? { ...c, Name: editName.trim(), SecretKey: editSecret } : c));+ onTotpCodesChange(totpCodes.map(c => c.Id === editingCode.Id ? { ...c, Name: editName.trim(), SecretKey: editSecret, ...totpParametersFrom(editAdvanced) } : c));setEditingCode(null);};@@ -199,11 +193,12 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, can</div><p className="mb-4 text-sm text-gray-500 dark:text-gray-400">{t('totp.totpInstructions')}</p><div className="mb-4">- <FormLabel htmlFor="totp-secret">{t('totp.secretKey')}</FormLabel>- <InputTextField id="totp-secret" type="text" value={newSecret} onValueChange={(value) => {- setNewSecret(value);- setSecretError('');- }} placeholder={t('totp.secretKeyPlaceholder')} />+ <div className="flex items-center justify-between mb-2">+ <label htmlFor="totp-secret" className="text-sm font-medium text-gray-900 dark:text-white">{t('totp.secretKey')}</label>+ <TotpSettingsButton id="totp-settings" isOpen={showAdvanced} onToggle={() => setShowAdvanced(v => !v)} />+ </div>+ <InputTextField id="totp-secret" type="text" value={newSecret} onValueChange={updateNewSecret} placeholder={t('totp.secretKeyPlaceholder')} />+ <TotpAdvancedFields idPrefix="totp" values={newAdvanced} onChange={setNewAdvanced} isOpen={showAdvanced} onOpen={() => setShowAdvanced(true)} />{secretError.length > 0 && <div className="text-red-600 dark:text-red-400 text-sm mt-1">{secretError}</div>}</div>{showNameField ? (@@ -264,11 +259,15 @@ const TotpCodes: React.FC<TotpCodesProps> = ({ totpCodes, onTotpCodesChange, can<div><div className="flex items-center justify-between mb-2"><label className="text-sm font-medium text-gray-900 dark:text-white">{t('totp.secretKey')}</label>- <button type="button" onClick={() => setShowQrCode(v => !v)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1" title={`${showQrCode ? t('common.hide') : t('common.show')} QR Code`}>- <Icon name="qrcode" className="w-5 h-5" />- </button>+ <div className="flex items-center">+ <TotpSettingsButton id="totp-edit-settings" isOpen={showEditAdvanced} onToggle={() => setShowEditAdvanced(v => !v)} />+ <button type="button" onClick={() => setShowQrCode(v => !v)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1" title={`${showQrCode ? t('common.hide') : t('common.show')} QR Code`}>+ <Icon name="qrcode" className="w-5 h-5" />+ </button>+ </div></div><input type="text" value={editSecret} onChange={e => setEditSecret(e.target.value)} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:text-white font-mono" placeholder={t('totp.secretKey')} />+ <TotpAdvancedFields idPrefix="totp-edit" values={editAdvanced} onChange={setEditAdvanced} isOpen={showEditAdvanced} onOpen={() => setShowEditAdvanced(true)} />{showQrCode && qrCodeDataUrl && (<div className="flex justify-center mt-3"><img src={qrCodeDataUrl} alt={t('common.qrCode')} className="w-64 h-64" />diff --git a/core/client/src/items/OtpAuthUri.ts b/core/client/src/items/OtpAuthUri.tsindex f90ec612a..28093f321 100644--- a/core/client/src/items/OtpAuthUri.ts+++ b/core/client/src/items/OtpAuthUri.ts@@ -8,7 +8,7 @@ import type { TotpParameters } from './TotpUtility';export type OtpAuthUri = {/** URL-decoded path component, typically "Issuer:account". */label: string;- /** The label without its "Issuer:" prefix. */+ /** The label without its "Issuer:" prefix (kept when it differs from the `issuer` parameter). */account: string;/** Base32 secret from the `secret` query parameter. */secret: string;@@ -22,6 +22,14 @@ export type OtpAuthUri = {period: number;};+/**+ * Whether the input is an `otpauth://totp/` URI rather than a bare secret (scheme compared case-insensitively).+ * @param input - The secret or URI+ */+export function isOtpAuthUri(input: string): boolean {+ return input.trim().toLowerCase().startsWith('otpauth://totp/');+}+/*** Parse an `otpauth://totp/` URI (https://github.com/google/google-authenticator/wiki/Key-Uri-Format). HOTP URIs are* rejected, the vault only stores TOTP codes. The Base32 alphabet of the secret is not validated here; callers do that.@@ -31,7 +39,7 @@ export type OtpAuthUri = {export function parseOtpAuthUri(uri: string): OtpAuthUri | null {const trimmed = uri.trim();const prefix = 'otpauth://totp/';- if (trimmed.toLowerCase().slice(0, prefix.length) !== prefix) {+ if (!isOtpAuthUri(trimmed)) {return null;}@@ -55,9 +63,12 @@ export function parseOtpAuthUri(uri: string): OtpAuthUri | null {const issuer = params.get('issuer');const issuerSeparator = label.indexOf(':');+ // The label prefix is the issuer only when no issuer parameter contradicts it; otherwise the colon belongs to the account.+ const labelPrefix = issuerSeparator >= 0 ? label.slice(0, issuerSeparator).trim() : null;+ const prefixIsIssuer = labelPrefix !== null && (!issuer?.trim() || labelPrefix.toLowerCase() === issuer.trim().toLowerCase());return {label,- account: issuerSeparator >= 0 ? label.slice(issuerSeparator + 1).trim() : label,+ account: prefixIsIssuer ? label.slice(issuerSeparator + 1).trim() : label,secret,...(issuer ? { issuer } : {}),algorithm: normalizeTotpAlgorithm(params.get('algorithm')),@@ -105,3 +116,92 @@ export function buildOtpAuthUri(label: string, secretKey: string, issuer: string}return uri;}++/**+ * A TOTP code as entered in an editor or import: the Base32 secret, the name and its RFC 6238 parameters.+ */+export type TotpEntry = {+ secretKey: string;+ name: string;+ algorithm: string;+ digits: number;+ period: number;+};++/**+ * The advanced fields of a TOTP editor. Period is the raw text of its number input.+ */+export type TotpAdvancedValues = {+ algorithm: string;+ digits: number;+ period: string;+};++/**+ * The advanced field values for stored parameters, or the RFC 6238 defaults.+ * @param parameters - Stored algorithm/digits/period+ */+export function totpAdvancedValues(parameters?: TotpParameters): TotpAdvancedValues {+ return {+ algorithm: normalizeTotpAlgorithm(parameters?.Algorithm),+ digits: normalizeTotpDigits(parameters?.Digits),+ period: String(normalizeTotpPeriod(parameters?.Period)),+ };+}++/**+ * The normalized parameters for the advanced field values, falling back to the defaults for anything unusable.+ * @param advanced - The advanced field values+ */+export function totpParametersFrom(advanced: TotpAdvancedValues): Required<TotpParameters> {+ return { Algorithm: normalizeTotpAlgorithm(advanced.algorithm), Digits: normalizeTotpDigits(advanced.digits), Period: normalizeTotpPeriod(advanced.period) };+}++/**+ * Resolve a bare Base32 secret or an `otpauth://totp/` URI to a TOTP entry. A URI supplies its own parameters and, when+ * `nameInput` is blank, the name; `advanced` (picked by hand) overrides both the URI and the defaults.+ * @param secretInput - The bare secret or otpauth URI+ * @param nameInput - The name entered by the user, may be blank+ * @param advanced - Parameters picked by hand+ * @returns The entry, or null when the input holds no valid Base32 secret+ */+export function resolveTotpEntry(secretInput: string, nameInput: string, advanced?: TotpAdvancedValues): TotpEntry | null {+ let secretKey = secretInput.trim();+ let name = nameInput.trim();+ let algorithm = TOTP_DEFAULT_ALGORITHM;+ let digits = TOTP_DEFAULT_DIGITS;+ let period = TOTP_DEFAULT_PERIOD;++ if (isOtpAuthUri(secretKey)) {+ const parsed = parseOtpAuthUri(secretKey);+ if (!parsed) {+ return null;+ }+ secretKey = parsed.secret;+ ({ algorithm, digits, period } = parsed);+ if (name.length === 0) {+ name = otpAuthDisplayName(parsed);+ }+ }++ secretKey = secretKey.replace(/\s/g, '');+ if (!/^[A-Z2-7]+=*$/i.test(secretKey)) {+ return null;+ }++ if (advanced) {+ const parameters = totpParametersFrom(advanced);+ return { secretKey, name, algorithm: parameters.Algorithm, digits: parameters.Digits, period: parameters.Period };+ }+ return { secretKey, name, algorithm, digits, period };+}++/**+ * Whether any of the parameters differs from the RFC 6238 defaults, so an editor can open its advanced section.+ * @param parameters - Stored algorithm/digits/period+ */+export function hasCustomTotpParameters(parameters?: TotpParameters): boolean {+ return normalizeTotpAlgorithm(parameters?.Algorithm) !== TOTP_DEFAULT_ALGORITHM+ || normalizeTotpDigits(parameters?.Digits) !== TOTP_DEFAULT_DIGITS+ || normalizeTotpPeriod(parameters?.Period) !== TOTP_DEFAULT_PERIOD;+}diff --git a/core/client/src/transfer/import/writers/TotpHelper.ts b/core/client/src/transfer/import/writers/TotpHelper.tsindex 737c2497f..db21d939c 100644--- a/core/client/src/transfer/import/writers/TotpHelper.ts+++ b/core/client/src/transfer/import/writers/TotpHelper.ts@@ -1,75 +1,25 @@-import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';import * as OTPAuth from 'otpauth';-/**- * A TOTP secret with the name and the RFC 6238 parameters it was imported with.- */-export type SanitizedTotpSecret = {- secretKey: string;- name: string | null;- algorithm: string;- digits: number;- period: number;-};+import { isOtpAuthUri, resolveTotpEntry, type TotpEntry } from '../../../items/OtpAuthUri';/**- * Sanitize a TOTP secret that may be given as an otpauth:// URI.+ * Sanitize an imported TOTP secret that may be given as an otpauth:// URI.* @param secretKey - The bare Base32 secret or an otpauth://totp/ URI- * @param name - The name to use; derived from the URI's label and issuer when not provided- * @returns The secret, name and parameters+ * @returns The secret, name (derived from the URI's label and issuer, else blank) and parameters* @throws {Error} When the URI is malformed or the secret cannot generate a code.*/-export function sanitizeTotpSecretKey(secretKey: string, name?: string | null): SanitizedTotpSecret {- let secret = secretKey;- let algorithm = TOTP_DEFAULT_ALGORITHM;- let digits = TOTP_DEFAULT_DIGITS;- let period = TOTP_DEFAULT_PERIOD;- let resolvedName = name ?? null;-- if (secret.startsWith('otpauth://totp/')) {- try {- const rest = secret.substring('otpauth://totp/'.length);- const queryIndex = rest.indexOf('?');- const labelEncoded = queryIndex >= 0 ? rest.substring(0, queryIndex) : rest;- const params = new URLSearchParams(queryIndex >= 0 ? rest.substring(queryIndex + 1) : '');-- const secretParam = params.get('secret');- if (!secretParam) {- throw new Error('Secret not found in URI');- }- secret = secretParam;-- algorithm = normalizeTotpAlgorithm(params.get('algorithm'));- digits = normalizeTotpDigits(params.get('digits'));- period = normalizeTotpPeriod(params.get('period'));-- if (!resolvedName || resolvedName.trim().length === 0) {- // The label is everything after 'totp/' and before '?'.- const label = decodeURIComponent(labelEncoded.replace(/\+/g, ' '));- const issuer = params.get('issuer');-- // A label "issuer:account" is split only when the query carries no issuer, so account names with colons survive.- if (label.includes(':') && (!issuer || issuer.trim().length === 0)) {- resolvedName = label.substring(label.indexOf(':') + 1);- } else {- resolvedName = label;- }-- if (issuer && issuer.trim().length > 0) {- resolvedName = `${issuer}: ${resolvedName}`;- }- }- } catch {- throw new Error('Invalid TOTP URI format. Please check and try again.');- }+export function sanitizeTotpSecretKey(secretKey: string): TotpEntry {+ const entry = resolveTotpEntry(secretKey, '');+ if (!entry) {+ throw new Error(isOtpAuthUri(secretKey) ? 'Invalid TOTP URI format. Please check and try again.' : 'Invalid secret key. Please check and try again.');}// The secret must be valid, check by trying to generate a code.try {- new OTPAuth.TOTP({ secret: OTPAuth.Secret.fromBase32(secret), algorithm, digits, period }).generate();+ new OTPAuth.TOTP({ secret: OTPAuth.Secret.fromBase32(entry.secretKey), algorithm: entry.algorithm, digits: entry.digits, period: entry.period }).generate();} catch {throw new Error('Invalid secret key. Please check and try again.');}- return { secretKey: secret, name: resolvedName, algorithm, digits, period };+ return entry;}