Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add iOS copy TOTP code after autofill scaffolding (#2006)

Leendert de Borst065f5095f960
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
index 1eb961a27..28422df7c 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
@@ -3,6 +3,7 @@ import SwiftUI
import VaultStoreKit
import VaultUI
import VaultModels
+import VaultUtils
/**
* Credential-specific functionality for CredentialProviderViewController
@@ -124,6 +125,18 @@ extension CredentialProviderViewController: CredentialProviderDelegate {
Thread.sleep(forTimeInterval: minimumDuration - elapsed)
}
+ // If the credential has a TOTP secret and the user has the
+ // copy-on-fill setting enabled (default), put the current
+ // TOTP code on the clipboard so they can paste it into the
+ // 2FA field after the autofill completes.
+ if matchingCredential.hasTotp,
+ let secret = matchingCredential.totpSecret,
+ AutofillSettings.shouldCopyTotpOnFill,
+ let code = TotpGenerator.generateCode(secret: secret),
+ !code.isEmpty {
+ UIPasteboard.general.string = code
+ }
+
// Use the identifier that matches the credential identity
let identifier = request.credentialIdentity.user
let passwordCredential = ASPasswordCredential(
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 699d02e95..bc196cbee 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -151,10 +151,22 @@
[vaultManager setAutofillShowSearchText:showSearchText resolver:resolve rejecter:reject];
}
+- (void)getAutofillCopyTotpOnFill:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getAutofillCopyTotpOnFill:resolve rejecter:reject];
+}
+
+- (void)setAutofillCopyTotpOnFill:(BOOL)enabled resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager setAutofillCopyTotpOnFill:enabled resolver:resolve rejecter:reject];
+}
+
- (void)copyToClipboardWithExpiration:(NSString *)text expirationSeconds:(double)expirationSeconds localOnly:(BOOL)localOnly resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager copyToClipboardWithExpiration:text expirationSeconds:expirationSeconds localOnly:localOnly resolver:resolve rejecter:reject];
}
+- (void)generateTotpCode:(NSString *)secret resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager generateTotpCode:secret resolver:resolve rejecter:reject];
+}
+
// MARK: - Android-specific methods (stubs for iOS)
- (void)isIgnoringBatteryOptimizations:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index b14175c6f..b5344b5d4 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -5,6 +5,7 @@ import VaultStoreKit
import VaultModels
import SwiftUI
import VaultUI
+import VaultUtils
import AVFoundation
import RustCoreFramework
import AuthenticationServices
@@ -392,6 +393,42 @@ public class VaultManager: NSObject {
resolve(nil)
}
+ @objc
+ func getAutofillCopyTotpOnFill(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ guard let defaults = UserDefaults(suiteName: VaultConstants.userDefaultsSuite) else {
+ resolve(true)
+ return
+ }
+ // Default to true when key has never been written.
+ if defaults.object(forKey: VaultConstants.autofillCopyTotpOnFillKey) == nil {
+ resolve(true)
+ return
+ }
+ resolve(defaults.bool(forKey: VaultConstants.autofillCopyTotpOnFillKey))
+ }
+
+ @objc
+ func setAutofillCopyTotpOnFill(_ enabled: Bool,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ guard let defaults = UserDefaults(suiteName: VaultConstants.userDefaultsSuite) else {
+ reject("AUTOFILL_SETTING_ERROR", "App Group UserDefaults unavailable", nil)
+ return
+ }
+ defaults.set(enabled, forKey: VaultConstants.autofillCopyTotpOnFillKey)
+ resolve(nil)
+ }
+
+ @objc
+ func generateTotpCode(_ secret: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ // Returns nil for invalid secrets; the JS side treats null as "code unavailable".
+ let code = TotpGenerator.generateCode(secret: secret)
+ resolve(code)
+ }
+
@objc
func copyToClipboardWithExpiration(_ text: String,
expirationSeconds: Double,
diff --git a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
index 0c8fbad5b..0fdd3db5a 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
@@ -5,7 +5,7 @@ import VaultModels
public struct VaultConstants {
static let keychainService = "net.aliasvault.autofill"
static let keychainAccessGroup = "group.net.aliasvault.autofill"
- static let userDefaultsSuite = "group.net.aliasvault.autofill"
+ public static let userDefaultsSuite = "group.net.aliasvault.autofill"
static let vaultMetadataKey = "aliasvault_vault_metadata"
static let encryptionKeyKey = "aliasvault_encryption_key"
@@ -17,6 +17,7 @@ public struct VaultConstants {
static let offlineModeKey = "aliasvault_offline_mode"
static let pinEnabledKey = "aliasvault_pin_enabled"
static let serverVersionKey = "aliasvault_server_version"
+ public static let autofillCopyTotpOnFillKey = "aliasvault_autofill_copy_totp_on_fill"
// Sync state keys (for offline sync and race detection)
static let isDirtyKey = "aliasvault_is_dirty"
diff --git a/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift b/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift
index ee29172ec..380ab7bc5 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/Components/CredentialCardView.swift
@@ -8,15 +8,13 @@ private let locBundle = Bundle.vaultUI
public struct AutofillCredentialCard: View {
let credential: AutofillCredential
let action: () -> Void
- let onCopy: () -> Void
@Environment(\.colorScheme) private var colorScheme
@State private var showCopyToast = false
@State private var copyToastMessage = ""
- public init(credential: AutofillCredential, action: @escaping () -> Void, onCopy: @escaping () -> Void) {
+ public init(credential: AutofillCredential, action: @escaping () -> Void) {
self.credential = credential
self.action = action
- self.onCopy = onCopy
}
private var colors: ColorConstants.Colors.Type {
@@ -72,15 +70,15 @@ public struct AutofillCredentialCard: View {
.cornerRadius(8)
}
.contextMenu(menuItems: {
+ // Copy actions only copy to the clipboard and show a toast — they
+ // intentionally leave the autofill picker open so the user can
+ // still pick a credential to fill afterwards (for example: copy
+ // TOTP first, then tap to fill username/password).
if let username = credential.username, !username.isEmpty {
Button(action: {
UIPasteboard.general.string = username
copyToastMessage = String(localized: "username_copied", bundle: locBundle)
showCopyToast = true
- // Delay for 1 second before calling onCopy which dismisses the view
- DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
- onCopy()
- }
}, label: {
Label(String(localized: "copy_username", bundle: locBundle), systemImage: "person")
})
@@ -91,10 +89,6 @@ public struct AutofillCredentialCard: View {
UIPasteboard.general.string = password
copyToastMessage = String(localized: "password_copied", bundle: locBundle)
showCopyToast = true
- // Delay for 1 second before calling onCopy which dismisses the view
- DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
- onCopy()
- }
}, label: {
Label(String(localized: "copy_password", bundle: locBundle), systemImage: "key")
})
@@ -105,18 +99,28 @@ public struct AutofillCredentialCard: View {
UIPasteboard.general.string = email
copyToastMessage = String(localized: "email_copied", bundle: locBundle)
showCopyToast = true
- // Delay for 1 second before calling onCopy which dismisses the view
- DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
- onCopy()
- }
}, label: {
Label(String(localized: "copy_email", bundle: locBundle), systemImage: "envelope")
})
}
+ if credential.hasTotp,
+ let secret = credential.totpSecret,
+ let code = TotpGenerator.generateCode(secret: secret),
+ !code.isEmpty {
+ Button(action: {
+ UIPasteboard.general.string = code
+ copyToastMessage = String(localized: "totp_code_copied", bundle: locBundle)
+ showCopyToast = true
+ }, label: {
+ Label(String(localized: "copy_totp_code", bundle: locBundle), systemImage: "number")
+ })
+ }
+
if (credential.username != nil && !credential.username!.isEmpty) ||
(credential.password != nil && !credential.password!.isEmpty) ||
- (credential.email != nil && !credential.email!.isEmpty) {
+ (credential.email != nil && !credential.email!.isEmpty) ||
+ credential.hasTotp {
Divider()
}
@@ -188,7 +192,6 @@ public func truncateText(_ text: String?, limit: Int) -> String {
createdAt: Date(),
updatedAt: Date()
),
- action: {},
- onCopy: {}
+ action: {}
)
}
diff --git a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
index 89fe99438..523b02da6 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
@@ -90,9 +90,6 @@ public struct CredentialProviderView: View {
username: username,
password: password
)
- },
- onCopy: {
- viewModel.cancel()
}
)
}
@@ -221,7 +218,6 @@ private struct AutofillCredentialCardWithSelection: View {
let credential: AutofillCredential
let isChoosingTextToInsert: Bool
let onSelect: (String, String) -> Void
- let onCopy: () -> Void
@State private var showSelectionSheet = false
@State private var totpCode: String?
@@ -239,10 +235,22 @@ private struct AutofillCredentialCardWithSelection: View {
// For normal autofill, use the credential's identifier property
let identifier = credential.identifier
+ // If the credential has a TOTP secret and the user has the
+ // copy-on-fill setting enabled (default), put the current
+ // TOTP code on the clipboard so they can paste it into the
+ // 2FA field after the autofill completes.
+ if credential.hasTotp,
+ let secret = credential.totpSecret,
+ AutofillSettings.shouldCopyTotpOnFill,
+ let code = TotpGenerator.generateCode(secret: secret),
+ !code.isEmpty {
+ UIPasteboard.general.string = code
+ }
+
// Fill both username and password immediately for normal autofill
onSelect(identifier, credential.password ?? "")
}
- }, onCopy: onCopy)
+ })
.confirmationDialog(
String(localized: "select_text_to_insert", bundle: locBundle),
isPresented: $showSelectionSheet,
diff --git a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
index 9cdb8bf1f..f32fa554c 100644
--- a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
+++ b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
@@ -35,10 +35,12 @@
"copy_username" = "Copy Username";
"copy_password" = "Copy Password";
"copy_email" = "Copy Email";
+"copy_totp_code" = "Copy TOTP Code";
"view_details" = "View Details";
"username_copied" = "Username copied";
"password_copied" = "Password copied";
"email_copied" = "Email copied";
+"totp_code_copied" = "TOTP code copied";
"totp_code" = "TOTP Code";
/* Search bar */
diff --git a/apps/mobile-app/ios/VaultUtils/AutofillSettings.swift b/apps/mobile-app/ios/VaultUtils/AutofillSettings.swift
new file mode 100644
index 000000000..ea8e85852
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUtils/AutofillSettings.swift
@@ -0,0 +1,30 @@
+import Foundation
+
+/// Read-only access to autofill-related preferences shared between the main app and
+/// the iOS Autofill extension via the App Group UserDefaults suite.
+///
+/// The setter side lives in NativeVaultManager (main app target) and writes to the
+/// same suite. Keys and the suite identifier must stay in sync with VaultConstants.
+public enum AutofillSettings {
+ /// App Group identifier — must match `VaultConstants.userDefaultsSuite` and
+ /// the autofill entitlements.
+ private static let suiteName = "group.net.aliasvault.autofill"
+
+ /// Key — must match `VaultConstants.autofillCopyTotpOnFillKey`.
+ private static let copyTotpOnFillKey = "aliasvault_autofill_copy_totp_on_fill"
+
+ private static var sharedDefaults: UserDefaults? {
+ UserDefaults(suiteName: suiteName)
+ }
+
+ /// Whether the autofill extension should copy a credential's current TOTP code to
+ /// the clipboard when the user selects it for autofill.
+ /// Defaults to `true` when the key has never been written.
+ public static var shouldCopyTotpOnFill: Bool {
+ guard let defaults = sharedDefaults else { return true }
+ if defaults.object(forKey: copyTotpOnFillKey) == nil {
+ return true
+ }
+ return defaults.bool(forKey: copyTotpOnFillKey)
+ }
+}
diff --git a/apps/mobile-app/package-lock.json b/apps/mobile-app/package-lock.json
index d0573f376..af298e64c 100644
--- a/apps/mobile-app/package-lock.json
+++ b/apps/mobile-app/package-lock.json
@@ -36,7 +36,6 @@
"fbemitter": "^3.0.0",
"i18next": "^25.3.2",
"lodash": "^4.18.1",
- "otpauth": "^9.4.0",
"react": "19.0.0",
"react-hook-form": "^7.56.1",
"react-i18next": "^15.6.0",
@@ -3161,18 +3160,6 @@
"@tybys/wasm-util": "^0.10.0"
}
},
- "node_modules/@noble/hashes": {
- "version": "1.8.0",
- "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
- "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
- "license": "MIT",
- "engines": {
- "node": "^14.21.3 || >=16"
- },
- "funding": {
- "url": "https://paulmillr.com/funding/"
- }
- },
"node_modules/@nodable/entities": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz",
@@ -11804,18 +11791,6 @@
"node": ">=8"
}
},
- "node_modules/otpauth": {
- "version": "9.4.1",
- "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.4.1.tgz",
- "integrity": "sha512-+iVvys36CFsyXEqfNftQm1II7SW23W1wx9RwNk0Cd97lbvorqAhBDksb/0bYry087QMxjiuBS0wokdoZ0iUeAw==",
- "license": "MIT",
- "dependencies": {
- "@noble/hashes": "1.8.0"
- },
- "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",
diff --git a/apps/mobile-app/package.json b/apps/mobile-app/package.json
index aa038d6ef..923429399 100644
--- a/apps/mobile-app/package.json
+++ b/apps/mobile-app/package.json
@@ -52,7 +52,6 @@
"fbemitter": "^3.0.0",
"i18next": "^25.3.2",
"lodash": "^4.18.1",
- "otpauth": "^9.4.0",
"react": "19.0.0",
"react-hook-form": "^7.56.1",
"react-i18next": "^15.6.0",
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 18e7b1cae..21501d710 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -67,10 +67,18 @@ export interface Spec extends TurboModule {
openAutofillSettingsPage(): Promise<void>;
getAutofillShowSearchText(): Promise<boolean>;
setAutofillShowSearchText(showSearchText: boolean): Promise<void>;
+ getAutofillCopyTotpOnFill(): Promise<boolean>;
+ setAutofillCopyTotpOnFill(enabled: boolean): Promise<void>;
// Clipboard management
copyToClipboardWithExpiration(text: string, expirationSeconds: number, localOnly: boolean): Promise<void>;
+ // TOTP code generation (RFC 6238, HMAC-SHA1, 6 digits, 30s period).
+ // Delegates to the platform-native TOTP generator so iOS, Android and the
+ // autofill extensions all share one implementation. Returns null when the
+ // secret is invalid.
+ generateTotpCode(secret: string): Promise<string | null>;
+
// Battery optimization management
isIgnoringBatteryOptimizations(): Promise<boolean>;
requestIgnoreBatteryOptimizations(): Promise<string>;
diff --git a/apps/mobile-app/utils/TotpUtility.ts b/apps/mobile-app/utils/TotpUtility.ts
index 0c9a275b7..be8daf8e3 100644
--- a/apps/mobile-app/utils/TotpUtility.ts
+++ b/apps/mobile-app/utils/TotpUtility.ts
@@ -1,23 +1,89 @@
-import * as OTPAuth from 'otpauth';
+import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Generates the current TOTP code for the given secret key.
- * Uses standard TOTP settings: SHA1, 6 digits, 30-second period.
+ *
+ * Delegates to the platform-native TOTP generator (Swift on iOS, Kotlin on
+ * Android) so the React Native layer, the iOS Autofill extension, and the
+ * Android Autofill service all share one RFC 6238 implementation. Standard
+ * settings: HMAC-SHA1, 6 digits, 30-second period.
*
* @param secretKey - Base32-encoded TOTP secret
* @returns The current 6-digit TOTP code, or empty string on error
*/
-export function generateTotpCode(secretKey: string): string {
+export async function generateTotpCode(secretKey: string): Promise<string> {
try {
- const totp = new OTPAuth.TOTP({
- secret: secretKey,
- algorithm: 'SHA1',
- digits: 6,
- period: 30
- });
- return totp.generate();
+ const code = await NativeVaultManager.generateTotpCode(secretKey);
+ return code ?? '';
} catch (error) {
console.error('Error generating TOTP code:', error);
return '';
}
}
+
+/**
+ * Parsed `otpauth://` URI components.
+ */
+export type OtpAuthUri = {
+ /** "totp" or "hotp" — only "totp" is supported elsewhere in the app. */
+ type: 'totp' | 'hotp';
+ /** URL-decoded path component, typically "Issuer:account". */
+ label: string;
+ /** Base32 secret from the `secret` query parameter. */
+ secret: string;
+ /** Optional `issuer` query parameter. */
+ issuer?: string;
+};
+
+/**
+ * Parse an `otpauth://` URI per
+ * https://github.com/google/google-authenticator/wiki/Key-Uri-Format.
+ *
+ * Returns null when the input is not a valid `otpauth://` URI or is missing
+ * a `secret` parameter. Does NOT validate the Base32 alphabet of the secret —
+ * callers (e.g. `sanitizeSecretKey` in TotpEditor) handle that separately.
+ */
+export function parseOtpAuthUri(uri: string): OtpAuthUri | null {
+ const trimmed = uri.trim();
+ const prefix = 'otpauth://';
+ if (trimmed.toLowerCase().slice(0, prefix.length) !== prefix) {
+ return null;
+ }
+
+ const afterScheme = trimmed.slice(prefix.length);
+ const slashIdx = afterScheme.indexOf('/');
+ if (slashIdx < 0) {
+ return null;
+ }
+
+ const typeRaw = afterScheme.slice(0, slashIdx).toLowerCase();
+ if (typeRaw !== 'totp' && typeRaw !== 'hotp') {
+ return null;
+ }
+
+ const rest = afterScheme.slice(slashIdx + 1);
+ const queryIdx = rest.indexOf('?');
+ const labelEncoded = queryIdx >= 0 ? rest.slice(0, queryIdx) : rest;
+ const queryString = queryIdx >= 0 ? rest.slice(queryIdx + 1) : '';
+
+ let label: string;
+ try {
+ label = decodeURIComponent(labelEncoded);
+ } catch {
+ label = labelEncoded;
+ }
+
+ const params = new URLSearchParams(queryString);
+ const secret = params.get('secret');
+ if (!secret) {
+ return null;
+ }
+
+ const issuer = params.get('issuer');
+ return {
+ type: typeRaw,
+ label,
+ secret,
+ ...(issuer ? { issuer } : {}),
+ };
+}