Skip to content

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

Add clear clipboard logic to mobile app iOS implementation (#881)

Leendert de Borst7b1066548864
diff --git a/apps/mobile-app/components/credentials/CredentialCard.tsx b/apps/mobile-app/components/credentials/CredentialCard.tsx
index 9852c9e6d..5952d9b16 100644
--- a/apps/mobile-app/components/credentials/CredentialCard.tsx
+++ b/apps/mobile-app/components/credentials/CredentialCard.tsx
@@ -1,3 +1,4 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Clipboard from 'expo-clipboard';
import { router } from 'expo-router';
import { useTranslation } from 'react-i18next';
@@ -10,6 +11,7 @@ import type { Credential } from '@/utils/dist/shared/models/vault';
import { useColors } from '@/hooks/useColorScheme';
import { CredentialIcon } from '@/components/credentials/CredentialIcon';
+import NativeVaultManager from '@/specs/NativeVaultManager';
type CredentialCardProps = {
credential: Credential;
@@ -58,11 +60,31 @@ export function CredentialCard({ credential, onCredentialDelete }: CredentialCar
return returnValue.length > 33 ? returnValue.slice(0, 30) + '...' : returnValue;
};
+ /**
+ * Helper function to copy text to clipboard with auto-clear
+ */
+ const copyToClipboard = async (text: string): Promise<void> => {
+ try {
+ await Clipboard.setStringAsync(text);
+
+ // Get clipboard clear timeout from settings
+ const timeoutStr = await AsyncStorage.getItem('clipboard_clear_timeout');
+ const timeoutSeconds = timeoutStr ? parseInt(timeoutStr, 10) : 10;
+
+ // Schedule clipboard clear if timeout is set
+ if (timeoutSeconds > 0) {
+ await NativeVaultManager.clearClipboardAfterDelay(timeoutSeconds);
+ }
+ } catch (error) {
+ console.error('Failed to copy to clipboard:', error);
+ }
+ };
+
/**
* Handles the context menu action when an item is selected.
* @param event - The event object containing the selected action details
*/
- const handleContextMenuAction = (event: OnPressMenuItemEvent): void => {
+ const handleContextMenuAction = async (event: OnPressMenuItemEvent): Promise<void> => {
const { name } = event.nativeEvent;
switch (name) {
@@ -100,7 +122,7 @@ export function CredentialCard({ credential, onCredentialDelete }: CredentialCar
break;
case 'Copy Username':
if (credential.Username) {
- Clipboard.setStringAsync(credential.Username);
+ await copyToClipboard(credential.Username);
if (Platform.OS === 'ios') {
Toast.show({
type: 'success',
@@ -112,7 +134,7 @@ export function CredentialCard({ credential, onCredentialDelete }: CredentialCar
break;
case 'Copy Email':
if (credential.Alias?.Email) {
- Clipboard.setStringAsync(credential.Alias.Email);
+ await copyToClipboard(credential.Alias.Email);
if (Platform.OS === 'ios') {
Toast.show({
type: 'success',
@@ -124,7 +146,7 @@ export function CredentialCard({ credential, onCredentialDelete }: CredentialCar
break;
case 'Copy Password':
if (credential.Password) {
- Clipboard.setStringAsync(credential.Password);
+ await copyToClipboard(credential.Password);
if (Platform.OS === 'ios') {
Toast.show({
type: 'success',
diff --git a/apps/mobile-app/components/credentials/details/TotpSection.tsx b/apps/mobile-app/components/credentials/details/TotpSection.tsx
index 1f1f36ae0..be612edca 100644
--- a/apps/mobile-app/components/credentials/details/TotpSection.tsx
+++ b/apps/mobile-app/components/credentials/details/TotpSection.tsx
@@ -1,3 +1,4 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Clipboard from 'expo-clipboard';
import * as OTPAuth from 'otpauth';
import React, { useState, useEffect } from 'react';
@@ -12,6 +13,7 @@ import { useColors } from '@/hooks/useColorScheme';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { useDb } from '@/context/DbContext';
+import NativeVaultManager from '@/specs/NativeVaultManager';
type TotpSectionProps = {
credential: Credential;
@@ -69,9 +71,18 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ credential }) : React.
/**
* Copy the totp code to the clipboard.
*/
- const copyToClipboard = async (code: string): Promise<void> => {
+ const copyToClipboardWithClear = async (code: string): Promise<void> => {
try {
await Clipboard.setStringAsync(code);
+
+ // Get clipboard clear timeout from settings
+ const timeoutStr = await AsyncStorage.getItem('clipboard_clear_timeout');
+ const timeoutSeconds = timeoutStr ? parseInt(timeoutStr, 10) : 10;
+
+ // Schedule clipboard clear if timeout is set
+ if (timeoutSeconds > 0) {
+ await NativeVaultManager.clearClipboardAfterDelay(timeoutSeconds);
+ }
if (Platform.OS !== 'android') {
// Only show toast on iOS, Android already shows a native toast on clipboard interactions.
@@ -194,7 +205,7 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ credential }) : React.
<TouchableOpacity
key={totpCode.Id}
style={styles.content}
- onPress={() => copyToClipboard(currentCodes[totpCode.Id])}
+ onPress={() => copyToClipboardWithClear(currentCodes[totpCode.Id])}
>
<View style={styles.codeContainer}>
<View>
diff --git a/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx b/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx
index 8174e3eef..2fed3cea2 100644
--- a/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx
+++ b/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx
@@ -1,11 +1,15 @@
import { MaterialIcons } from '@expo/vector-icons';
+import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Clipboard from 'expo-clipboard';
import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
import { View, Text, TouchableOpacity, StyleSheet, Platform } from 'react-native';
import Toast from 'react-native-toast-message';
import { useColors } from '@/hooks/useColorScheme';
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
type FormInputCopyToClipboardProps = {
label: string;
value: string | undefined;
@@ -22,19 +26,40 @@ const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({
}) : React.ReactNode => {
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const colors = useColors();
+ const { t } = useTranslation();
/**
* Copy the value to the clipboard.
*/
const copyToClipboard = async () : Promise<void> => {
if (value) {
- await Clipboard.setStringAsync(value);
+ try {
+ // Copy to clipboard using expo-clipboard
+ await Clipboard.setStringAsync(value);
+
+ // Get clipboard clear timeout from settings
+ const timeoutStr = await AsyncStorage.getItem('clipboard_clear_timeout');
+ const timeoutSeconds = timeoutStr ? parseInt(timeoutStr, 10) : 10;
+
+ // Schedule clipboard clear if timeout is set
+ if (timeoutSeconds > 0) {
+ await NativeVaultManager.clearClipboardAfterDelay(timeoutSeconds);
+ }
- if (Platform.OS !== 'android') {
- // Only show toast on iOS, Android already shows a native toast on clipboard interactions.
+ if (Platform.OS !== 'android') {
+ // Only show toast on iOS, Android already shows a native toast on clipboard interactions.
+ Toast.show({
+ type: 'success',
+ text1: t('common.copied'),
+ position: 'bottom',
+ visibilityTime: 2000,
+ });
+ }
+ } catch (error) {
+ console.error('Failed to copy to clipboard:', error);
Toast.show({
- type: 'success',
- text1: 'Copied to clipboard',
+ type: 'error',
+ text1: t('common.error'),
position: 'bottom',
visibilityTime: 2000,
});
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index ccd00dac3..a3e42655f 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -89,6 +89,10 @@
[vaultManager setAutoLockTimeout:timeout resolver:resolve rejecter:reject];
}
+- (void)clearClipboardAfterDelay:(double)delayInSeconds resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager clearClipboardAfterDelay:delayInSeconds resolver:resolve rejecter:reject];
+}
+
- (void)storeDatabase:(NSString *)base64EncryptedDb resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager storeDatabase:base64EncryptedDb resolver:resolve rejecter:reject];
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index a661d4104..7a0b7384c 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -12,6 +12,8 @@ import VaultModels
@objc(VaultManager)
public class VaultManager: NSObject {
private let vaultStore = VaultStore.shared
+ private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
+ private var clipboardClearTimer: DispatchSourceTimer?
override init() {
super.init()
@@ -253,8 +255,52 @@ public class VaultManager: NSObject {
}
@objc
- func requiresMainQueueSetup() -> Bool {
- return false
+ func clearClipboardAfterDelay(_ delayInSeconds: Double,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ NSLog("VaultManager: Scheduling clipboard clear after %.0f seconds", delayInSeconds)
+
+ if delayInSeconds <= 0 {
+ NSLog("VaultManager: Delay is 0 or negative, not scheduling clipboard clear")
+ resolve(nil)
+ return
+ }
+
+ // Cancel any existing clipboard clear operations
+ cancelClipboardClear()
+
+ // Start background task to keep app alive during clipboard clear
+ backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "ClipboardClear") { [weak self] in
+ NSLog("VaultManager: Background task expired, cleaning up")
+ self?.endBackgroundTask()
+ }
+
+ clipboardClearTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
+ clipboardClearTimer?.schedule(deadline: .now() + delayInSeconds)
+ clipboardClearTimer?.setEventHandler { [weak self] in
+ NSLog("VaultManager: Clearing clipboard after %.0f seconds delay", delayInSeconds)
+ UIPasteboard.general.string = ""
+ NSLog("VaultManager: Clipboard cleared successfully")
+ self?.endBackgroundTask()
+ self?.clipboardClearTimer?.cancel()
+ self?.clipboardClearTimer = nil
+ }
+ clipboardClearTimer?.resume()
+
+ resolve(nil)
+ }
+
+ private func cancelClipboardClear() {
+ clipboardClearTimer?.cancel()
+ clipboardClearTimer = nil
+ endBackgroundTask()
+ }
+
+ private func endBackgroundTask() {
+ if backgroundTaskIdentifier != .invalid {
+ UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
+ backgroundTaskIdentifier = .invalid
+ }
}
@objc
@@ -301,7 +347,7 @@ public class VaultManager: NSObject {
@objc
func commitTransaction(_ resolve: @escaping RCTPromiseResolveBlock,
- rejecter reject: @escaping RCTPromiseRejectBlock) {
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
try vaultStore.commitTransaction()
resolve(nil)
@@ -312,7 +358,7 @@ public class VaultManager: NSObject {
@objc
func rollbackTransaction(_ resolve: @escaping RCTPromiseResolveBlock,
- rejecter reject: @escaping RCTPromiseRejectBlock) {
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
try vaultStore.rollbackTransaction()
resolve(nil)
@@ -334,6 +380,11 @@ public class VaultManager: NSObject {
}
}
+ @objc
+ func requiresMainQueueSetup() -> Bool {
+ return false
+ }
+
@objc
static func moduleName() -> String! {
return "VaultManager"
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index bece5e940..a3b82404d 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -37,6 +37,9 @@ export interface Spec extends TurboModule {
getAutoLockTimeout(): Promise<number>;
getAuthMethods(): Promise<string[]>;
openAutofillSettingsPage(): Promise<void>;
+
+ // Clipboard management
+ clearClipboardAfterDelay(delayInSeconds: number): Promise<void>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeVaultManager');