Skip to content

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

Update clipboard copy clear logic, add stats databucket silent push logic (#2413)

Leendert de Borstb482ed6f2943
diff --git a/apps/web/src/components/forms/CopyPasteFormRow.tsx b/apps/web/src/components/forms/CopyPasteFormRow.tsx
index afd700043..ed742f95b 100644
--- a/apps/web/src/components/forms/CopyPasteFormRow.tsx
+++ b/apps/web/src/components/forms/CopyPasteFormRow.tsx
@@ -3,17 +3,20 @@ import React from 'react';
import FormLabel from '@/components/shared/FormLabel';
import { useClipboardCopy } from '@/hooks/useClipboardCopy';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
type CopyPasteFormRowProps = {
id: string;
label?: string | null;
value: string;
+ item?: ItemRef;
};
/**
* Read-only value that copies to the clipboard on click.
*/
-const CopyPasteFormRow: React.FC<CopyPasteFormRowProps> = ({ id, label = null, value }) => {
- const { copied, copyToClipboard } = useClipboardCopy(id);
+const CopyPasteFormRow: React.FC<CopyPasteFormRowProps> = ({ id, label = null, value, item }) => {
+ const { copied, copyToClipboard } = useClipboardCopy(id, item);
return (
<>
diff --git a/apps/web/src/components/forms/CopyPastePasswordFormRow.tsx b/apps/web/src/components/forms/CopyPastePasswordFormRow.tsx
index 49abfdf65..6c730d715 100644
--- a/apps/web/src/components/forms/CopyPastePasswordFormRow.tsx
+++ b/apps/web/src/components/forms/CopyPastePasswordFormRow.tsx
@@ -3,17 +3,20 @@ import React, { useState } from 'react';
import FormLabel from '@/components/shared/FormLabel';
import { useClipboardCopy } from '@/hooks/useClipboardCopy';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
type CopyPastePasswordFormRowProps = {
id: string;
label?: string;
value: string;
+ item?: ItemRef;
};
/**
* Read-only masked value that copies to the clipboard on click, with a show/hide toggle.
*/
-const CopyPastePasswordFormRow: React.FC<CopyPastePasswordFormRowProps> = ({ id, label = '', value }) => {
- const { copied, copyToClipboard } = useClipboardCopy(id);
+const CopyPastePasswordFormRow: React.FC<CopyPastePasswordFormRowProps> = ({ id, label = '', value, item }) => {
+ const { copied, copyToClipboard } = useClipboardCopy(id, item);
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const borderClasses = `${copied ? 'border-green-500 border-2' : 'border-gray-300'} ${copied ? 'dark:border-green-500' : 'dark:border-gray-600'}`;
diff --git a/apps/web/src/components/items/FieldBlock.tsx b/apps/web/src/components/items/FieldBlock.tsx
index bb7175ce9..e83307f63 100644
--- a/apps/web/src/components/items/FieldBlock.tsx
+++ b/apps/web/src/components/items/FieldBlock.tsx
@@ -115,7 +115,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, item, fullWidth = false,
return (
<div className={widthClass}>
{labelElement}
- <CopyPastePasswordFormRow id={fieldId} label="" value={field.Value} />
+ <CopyPastePasswordFormRow id={fieldId} label="" value={field.Value} item={item} />
</div>
);
case FieldTypes.TextArea:
@@ -140,7 +140,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, item, fullWidth = false,
return (
<div className={widthClass}>
{labelElement}
- <CopyPasteFormRow id={fieldId} label="" value={field.Value} />
+ <CopyPasteFormRow id={fieldId} label="" value={field.Value} item={item} />
</div>
);
}
diff --git a/apps/web/src/components/layout/ClipboardCountdownBar.tsx b/apps/web/src/components/layout/ClipboardCountdownBar.tsx
index 2aecf5cce..54ae4a8f1 100644
--- a/apps/web/src/components/layout/ClipboardCountdownBar.tsx
+++ b/apps/web/src/components/layout/ClipboardCountdownBar.tsx
@@ -9,66 +9,33 @@ import { clipboardCopyService, type ClipboardStatus } from '@/utils/ClipboardCop
*/
const ClipboardCountdownBar: React.FC = () => {
const { t } = useTranslation();
- const [isVisible, setIsVisible] = useState(false);
const [progress, setProgress] = useState(0);
- const [status, setStatus] = useState<ClipboardStatus>('active');
+ const [status, setStatus] = useState<ClipboardStatus>(clipboardCopyService.getStatus());
useEffect(() => {
- const unsubscribeProgress = clipboardCopyService.subscribeProgress((value) => {
- setProgress(value);
- if (value > 0) {
- setIsVisible(true);
- setStatus('active');
- } else {
- setStatus((current) => {
- if (current !== 'cleared') {
- setIsVisible(true);
- setProgress(1);
- return 'pending';
- }
- return current;
- });
- }
- });
- const unsubscribeStatus = clipboardCopyService.subscribeStatus((value) => {
- setStatus(value);
- if (value === 'cleared') {
- setIsVisible(false);
- setProgress(0);
- } else if (value === 'pending' || value === 'manual_clear_required') {
- setIsVisible(true);
- setProgress(1);
- }
- });
+ const unsubscribeProgress = clipboardCopyService.subscribeProgress(setProgress);
+ const unsubscribeStatus = clipboardCopyService.subscribeStatus(setStatus);
return (): void => {
unsubscribeProgress();
unsubscribeStatus();
};
}, []);
- /**
- * Clear the clipboard on the user's request.
- */
- const handleManualClear = async (): Promise<void> => {
- await clipboardCopyService.clearNow();
- setStatus('active');
- setIsVisible(true);
- setProgress(0);
- };
-
- if (!isVisible) {
+ if (status === 'cleared') {
return null;
}
- const barColorClass = status === 'pending' || status === 'manual_clear_required' ? 'bg-blue-500 dark:bg-blue-400' : 'bg-orange-500 dark:bg-orange-400';
- const animationClass = status === 'pending' ? 'animate-pulse' : '';
+ // Once the countdown ran out without a clear, the bar stays full (blue) until the clear goes through.
+ const waiting = status === 'pending' || status === 'manual_clear_required' || progress <= 0;
+ const barColorClass = waiting ? 'bg-blue-500 dark:bg-blue-400' : 'bg-orange-500 dark:bg-orange-400';
+ const animationClass = waiting && status !== 'manual_clear_required' ? 'animate-pulse' : '';
return (
<div className="fixed top-0 left-0 right-0 z-50 h-1 bg-gray-200 dark:bg-gray-700">
- <div className={`h-full ${barColorClass} transition-all duration-100 ease-linear ${animationClass}`} style={{ width: `${progress * 100}%` }}></div>
+ <div className={`h-full ${barColorClass} transition-all duration-100 ease-linear ${animationClass}`} style={{ width: `${waiting ? 100 : progress * 100}%` }}></div>
{status === 'manual_clear_required' && (
<div className="fixed top-2 left-1/2 transform -translate-x-1/2 z-50 bg-blue-500 dark:bg-blue-600 text-white px-4 py-2 rounded-md shadow-lg flex items-center gap-3">
- <button type="button" onClick={() => void handleManualClear()} className="px-3 py-1 bg-white dark:bg-gray-800 text-blue-600 dark:text-blue-400 rounded text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-700">
+ <button type="button" onClick={() => void clipboardCopyService.clearNow()} className="px-3 py-1 bg-white dark:bg-gray-800 text-blue-600 dark:text-blue-400 rounded text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-700">
{t('components.main.clipboardCountdownBar.ClearClipboardButton')}
</button>
</div>
diff --git a/apps/web/src/components/totp/TotpViewer.tsx b/apps/web/src/components/totp/TotpViewer.tsx
index 2ae6d0742..ca58971e4 100644
--- a/apps/web/src/components/totp/TotpViewer.tsx
+++ b/apps/web/src/components/totp/TotpViewer.tsx
@@ -6,8 +6,11 @@ import { useTranslation } from 'react-i18next';
import Card from '@/components/shared/Card';
import { useClipboardCopy } from '@/hooks/useClipboardCopy';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
type TotpViewerProps = {
totpCodes: TotpCode[];
+ item: ItemRef;
};
/**
@@ -18,9 +21,9 @@ const codeOf = (totpCode: TotpCode): string => generateTotpCode(totpCode.SecretK
/**
* A single TOTP row with its countdown.
*/
-const TotpRow: React.FC<{ totpCode: TotpCode; tick: number }> = ({ totpCode, tick }) => {
+const TotpRow: React.FC<{ totpCode: TotpCode; item: ItemRef; tick: number }> = ({ totpCode, item, tick }) => {
const { t } = useTranslation();
- const { copied, copyToClipboard } = useClipboardCopy(totpCode.Id);
+ const { copied, copyToClipboard } = useClipboardCopy(totpCode.Id, item);
const code = codeOf(totpCode);
const period = normalizeTotpPeriod(totpCode.Period);
const remaining = getTotpRemainingSeconds(totpCode);
@@ -56,7 +59,7 @@ const TotpRow: React.FC<{ totpCode: TotpCode; tick: number }> = ({ totpCode, tic
/**
* Shows the live two-factor codes of an item.
*/
-const TotpViewer: React.FC<TotpViewerProps> = ({ totpCodes }) => {
+const TotpViewer: React.FC<TotpViewerProps> = ({ totpCodes, item }) => {
const { t } = useTranslation();
const [tick, setTick] = useState(0);
@@ -79,7 +82,7 @@ const TotpViewer: React.FC<TotpViewerProps> = ({ totpCodes }) => {
</div>
) : (
<div className="grid grid-cols-1 gap-4 mt-4">
- {totpCodes.map(totpCode => <TotpRow key={totpCode.Id} totpCode={totpCode} tick={tick} />)}
+ {totpCodes.map(totpCode => <TotpRow key={totpCode.Id} totpCode={totpCode} item={item} tick={tick} />)}
</div>
)}
</Card>
diff --git a/apps/web/src/hooks/useClipboardCopy.ts b/apps/web/src/hooks/useClipboardCopy.ts
index 59b404bd5..33d9585d5 100644
--- a/apps/web/src/hooks/useClipboardCopy.ts
+++ b/apps/web/src/hooks/useClipboardCopy.ts
@@ -1,25 +1,43 @@
import { useCallback, useEffect, useState } from 'react';
import { useDb } from '@/context/DbContext';
+import { useVaultMutate } from '@/hooks/useVaultMutate';
import { clipboardCopyService } from '@/utils/ClipboardCopyService';
+import { devLog } from '@/utils/DevLogger';
+
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
const DEFAULT_CLIPBOARD_CLEAR_SECONDS = 10;
/**
* Copy a value to the clipboard and know whether this element is the one that was copied last.
* @param id - the id of the element the value belongs to
+ * @param item - the item the value belongs to, whose usage stats count the copy
*/
-export function useClipboardCopy(id: string): { copied: boolean; copyToClipboard: (value: string) => Promise<void> } {
+export function useClipboardCopy(id: string, item?: ItemRef): { copied: boolean; copyToClipboard: (value: string) => Promise<void> } {
const dbContext = useDb();
+ const { executeVaultMutationAsync } = useVaultMutate();
const [copied, setCopied] = useState(clipboardCopyService.getCopiedId() === id);
+ const itemId = item?.Id;
+ const manifestId = item?.ManifestId;
useEffect(() => clipboardCopyService.subscribe((copiedId) => setCopied(copiedId === id)), [id]);
const copyToClipboard = useCallback(async (value: string): Promise<void> => {
const stored = dbContext.sqliteClient?.settings.getSetting('ClipboardClearSeconds', String(DEFAULT_CLIPBOARD_CLEAR_SECONDS));
const clearAfterSeconds = Number.parseInt(stored ?? '', 10);
- await clipboardCopyService.copy(id, value, Number.isNaN(clearAfterSeconds) ? DEFAULT_CLIPBOARD_CLEAR_SECONDS : clearAfterSeconds);
- }, [dbContext.sqliteClient, id]);
+ const success = await clipboardCopyService.copy(id, value, Number.isNaN(clearAfterSeconds) ? DEFAULT_CLIPBOARD_CLEAR_SECONDS : clearAfterSeconds);
+ if (!success || !itemId || !manifestId) {
+ return;
+ }
+
+ // Stats-only writes push silently, without the sync indicator.
+ executeVaultMutationAsync(async () => {
+ if (!dbContext.sqliteClient?.itemStats.recordUsage({ Id: itemId, ManifestId: manifestId }, 'copy')) {
+ throw new Error('Item not found');
+ }
+ }).catch((error) => devLog('[Clipboard] Failed to record item usage', error));
+ }, [dbContext.sqliteClient, executeVaultMutationAsync, id, itemId, manifestId]);
return { copied, copyToClipboard };
}
diff --git a/apps/web/src/pages/items/View.tsx b/apps/web/src/pages/items/View.tsx
index 99c3bcf0f..b74188998 100644
--- a/apps/web/src/pages/items/View.tsx
+++ b/apps/web/src/pages/items/View.tsx
@@ -209,7 +209,7 @@ const ItemView: React.FC = () => {
{isLoginLike && emailAddress.length > 0 && <RecentEmails emailAddress={emailAddress} />}
- {totpCodes.length > 0 && <TotpViewer totpCodes={totpCodes} />}
+ {totpCodes.length > 0 && <TotpViewer totpCodes={totpCodes} item={item} />}
{item.ItemType !== ItemTypes.Note && notesFields.length > 0 && (
<Section title={t('pages.main.items.view.NotesSection')}>
@@ -268,7 +268,7 @@ const ItemView: React.FC = () => {
<div className="grid grid-cols-6 gap-6">
{firstName.trim().length > 0 && lastName.trim().length > 0 && (
<div className="col-span-6">
- <CopyPasteFormRow id="alias-full-name" label={t('pages.main.items.view.FullNameLabel')} value={`${firstName} ${lastName}`} />
+ <CopyPasteFormRow id="alias-full-name" label={t('pages.main.items.view.FullNameLabel')} value={`${firstName} ${lastName}`} item={item} />
</div>
)}
{aliasFields.map((field, index) => (
diff --git a/apps/web/src/utils/ClipboardCopyService.ts b/apps/web/src/utils/ClipboardCopyService.ts
index aefae4705..d541ec0a6 100644
--- a/apps/web/src/utils/ClipboardCopyService.ts
+++ b/apps/web/src/utils/ClipboardCopyService.ts
@@ -30,6 +30,7 @@ class ClipboardCopyService {
private progressListeners: ProgressListener[] = [];
private statusListeners: StatusListener[] = [];
private listenersAttached = false;
+ private status: ClipboardStatus = 'cleared';
/**
* Copy a value and schedule the clear. Returns whether the copy succeeded.
@@ -49,6 +50,11 @@ class ClipboardCopyService {
this.setCopied(id);
if (clearAfterSeconds > 0) {
this.scheduleClear(clearAfterSeconds);
+ } else {
+ // The new value replaced the one a running countdown was going to clear.
+ this.stopTimers();
+ this.clearByTime = null;
+ this.notifyStatus('cleared');
}
return true;
}
@@ -90,6 +96,13 @@ class ClipboardCopyService {
};
}
+ /**
+ * The current clear status.
+ */
+ public getStatus(): ClipboardStatus {
+ return this.status;
+ }
+
/**
* Clear the clipboard now, on the user's request.
*/
@@ -169,10 +182,11 @@ class ClipboardCopyService {
const notFocused = (error instanceof Error && error.name === 'NotAllowedError') || message.includes('Document is not focused');
if (!notFocused) {
console.warn('[Clipboard] Failed to clear clipboard:', error);
+ this.notifyStatus('manual_clear_required');
return false;
}
this.failedAttempts++;
- this.notifyStatus(this.failedAttempts >= 2 ? 'manual_clear_required' : 'pending');
+ this.notifyStatus(this.failedAttempts >= 2 || manual ? 'manual_clear_required' : 'pending');
return false;
}
}
@@ -221,6 +235,7 @@ class ClipboardCopyService {
* Tell the bar about a status change.
*/
private notifyStatus(status: ClipboardStatus): void {
+ this.status = status;
this.statusListeners.forEach(l => l(status));
}
}