Skip to content

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

Add web app utils and refactor to use shared logic (#2413)

Leendert de Borst0cc84326b5cd
diff --git a/apps/browser-extension/package-lock.json b/apps/browser-extension/package-lock.json
index 1687d60f3..9a17d7b72 100644
--- a/apps/browser-extension/package-lock.json
+++ b/apps/browser-extension/package-lock.json
@@ -16,10 +16,8 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^5.1.1",
- "@types/dompurify": "^3.0.5",
"@webext-core/messaging": "^3.0.1",
"buffer": "^6.0.3",
- "dompurify": "^3.4.12",
"globals": "^16.0.0",
"i18next": "^26.2.0",
"otpauth": "^9.3.6",
@@ -69,6 +67,7 @@
"dependencies": {
"@aliasvault/models": "file:../models",
"@aliasvault/vault": "file:../vault",
+ "dompurify": "^3.4.12",
"fflate": "^0.8.3",
"otpauth": "^9.3.6"
},
@@ -1385,15 +1384,6 @@
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"license": "MIT"
},
- "node_modules/@types/dompurify": {
- "version": "3.0.5",
- "resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.0.5.tgz",
- "integrity": "sha512-1Wg0g3BtQF7sSb27fJQAKck1HECM6zV1EB66j8JH9i3LCjYabJa0FSdiSgsD5K/RbrsR0SiraKacLB+T8ZVYAg==",
- "license": "MIT",
- "dependencies": {
- "@types/trusted-types": "*"
- }
- },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -1497,12 +1487,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/trusted-types": {
- "version": "2.0.7",
- "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
- "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
- "license": "MIT"
- },
"node_modules/@types/yup": {
"version": "0.29.14",
"resolved": "https://registry.npmjs.org/@types/yup/-/yup-0.29.14.tgz",
@@ -3510,15 +3494,6 @@
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
- "node_modules/dompurify": {
- "version": "3.4.13",
- "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.13.tgz",
- "integrity": "sha512-2vmYIoqjze2d+kakP8S/nS5shfsl587kzwEjcGlTdiksUVgFHnFCsLYDVj/JNqJVOQZGSYBTmuycv0PodwmnMQ==",
- "license": "(MPL-2.0 OR Apache-2.0)",
- "optionalDependencies": {
- "@types/trusted-types": "^2.0.7"
- }
- },
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
diff --git a/apps/browser-extension/package.json b/apps/browser-extension/package.json
index 6d906fbd6..1bac3d867 100644
--- a/apps/browser-extension/package.json
+++ b/apps/browser-extension/package.json
@@ -37,10 +37,8 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^5.1.1",
- "@types/dompurify": "^3.0.5",
"@webext-core/messaging": "^3.0.1",
"buffer": "^6.0.3",
- "dompurify": "^3.4.12",
"globals": "^16.0.0",
"i18next": "^26.2.0",
"otpauth": "^9.3.6",
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
index 1b35b2839..39b1f46bf 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
@@ -124,21 +124,13 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
if (isPublic) {
// For public domains (SpamOK), use the SpamOK API directly
const emailPrefix = email.split('@')[0];
- const response = await spamOk.request('GET', `EmailBox/${emailPrefix}`);
-
- if (!response.ok) {
- markPollFailed(`The mailbox request returned HTTP ${response.status}`);
+ const allMails = await spamOk.getMailbox(emailPrefix);
+ if (!allMails) {
+ markPollFailed('The mailbox request failed');
setError(t('common.errors.unknownError'));
return;
}
- const data = await response.json();
-
- // Store all emails, sorted by date
- const allMails = data?.mails
- ?.toSorted((a: MailboxEmail, b: MailboxEmail) =>
- new Date(b.dateSystem).getTime() - new Date(a.dateSystem).getTime()) ?? [];
-
if (loading && allMails.length > 0) {
setLastEmailId(allMails[0].id);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
index 077a6dc2c..8f6c0d753 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
@@ -1,3 +1,4 @@
+import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,23 +27,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId, manifestId })
*/
const downloadAttachment = (attachment: Attachment): void => {
try {
- // Convert Uint8Array or number[] to Uint8Array
- const byteArray = attachment.Blob instanceof Uint8Array ? attachment.Blob : new Uint8Array(attachment.Blob ?? []);
-
- // Create blob and download
- const blob = new Blob([byteArray as BlobPart]);
- const url = URL.createObjectURL(blob);
-
- // Create temporary download link
- const a = document.createElement('a');
- a.href = url;
- a.download = attachment.Filename;
- document.body.appendChild(a);
- a.click();
-
- // Cleanup
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
+ downloadBytes(attachment.Filename, attachment.Blob ?? []);
} catch (error) {
logFailure('Error downloading attachment', error);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
index 2f949bb99..19a12da60 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
@@ -1,6 +1,8 @@
import EncryptionUtility, { type DecryptedEmail } from '@aliasvault/client/crypto/EncryptionUtility';
import { getEmailAttachmentBytes } from '@aliasvault/client/email/EmailAttachments';
+import { sanitizeEmailHtml } from '@aliasvault/client/email/EmailHtmlSanitizer';
import { decodeEmailSource, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';
+import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';
import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';
@@ -12,7 +14,6 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
-import ConversionUtility from '@/entrypoints/popup/utils/ConversionUtility';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { logFailure } from '@/utils/Diagnostics';
@@ -156,7 +157,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
.catch(err => setError(err instanceof Error ? err.message : 'Failed to decode email source'));
}, [viewMode, sourceText, sourceBytes]);
- const sanitizedHtmlBody = useMemo(() => htmlBody ? ConversionUtility.sanitizeAndPrepareEmailHtml(htmlBody) : null, [htmlBody]);
+ const sanitizedHtmlBody = useMemo(() => htmlBody ? sanitizeEmailHtml(htmlBody) : null, [htmlBody]);
const formatLabels = useMemo<Record<'html' | 'plain' | 'source', string>>(() => ({
html: t('emails.formatHtml'),
@@ -198,25 +199,6 @@ const EmailDetails: React.FC = (): React.ReactElement => {
PopoutUtility.openInNewPopup(`/emails/${id}`, fromPath ?? undefined);
}, [id, fromPath]);
- /**
- * Trigger a browser download for raw attachment bytes.
- */
- const triggerAttachmentDownload = (bytes: Uint8Array, mimeType: string | null, filename: string): void => {
- const blob = new Blob([bytes], { type: mimeType ?? 'application/octet-stream' });
-
- // Create download link and trigger download
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
-
- // Cleanup
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
- };
-
/**
* Handle downloading an attachment contained in the message source.
*/
@@ -234,7 +216,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();
const bytes = await getEmailAttachmentBytes(webApi, email, encryptionKeys, sourceBytes, index, attachment.detached ? attachment.partIndex : null);
- triggerAttachmentDownload(bytes, attachment.mimeType, attachment.filename);
+ downloadBytes(attachment.filename, bytes, attachment.mimeType);
} catch (err) {
logFailure('[Email] Downloading the attachment failed', err);
setError(err instanceof Error ? err.message : 'Failed to download attachment');
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
deleted file mode 100644
index 103a6c7b7..000000000
--- a/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import DOMPurify from 'dompurify';
-
-import { logExpected } from '@/utils/Diagnostics';
-
-/**
- * DOMPurify configuration for email viewing.
- * Allows safe HTML elements for email display while blocking XSS vectors.
- */
-const EMAIL_SANITIZER_CONFIG = {
- ALLOWED_TAGS: [
- 'div', 'span', 'p', 'br', 'hr',
- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
- 'ul', 'ol', 'li',
- 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
- 'a', 'img',
- 'b', 'i', 'u', 's', 'strike', 'strong', 'em', 'small', 'sub', 'sup',
- 'blockquote', 'pre', 'code',
- 'font', 'center'
- ],
- ALLOWED_ATTR: [
- 'style', 'class', 'id',
- 'width', 'height', 'align', 'valign',
- 'bgcolor', 'color', 'border',
- 'cellpadding', 'cellspacing', 'colspan', 'rowspan',
- 'face', 'size',
- 'href', 'target', 'rel',
- 'src', 'alt', 'title'
- ],
- ALLOW_DATA_ATTR: false,
- ADD_ATTR: ['target'],
- FORBID_TAGS: ['script', 'object', 'embed', 'iframe', 'frame', 'frameset',
- 'form', 'input', 'button', 'textarea', 'select', 'option',
- 'link', 'meta', 'base', 'applet'],
- FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onmouseout',
- 'onfocus', 'onblur', 'onchange', 'onsubmit', 'onreset', 'onkeydown',
- 'onkeyup', 'onkeypress', 'ondblclick', 'oncontextmenu', 'onmousedown',
- 'onmouseup', 'onmousemove', 'ondrag', 'ondrop']
-};
-
-/**
- * Utility class for conversion operations.
- * TODO: make this a shared utility class in root /core/ folder so we can reuse it between browser extension/mobile app
- * and possibly WASM client.
- */
-class ConversionUtility {
-
- /**
- * Sanitizes HTML content for safe display in email viewers.
- * Removes all script tags, event handlers, and other XSS attack vectors.
- * @param html The HTML content to sanitize.
- * @returns Sanitized HTML safe for display.
- */
- public sanitizeHtmlForEmailViewing(html: string): string {
- if (!html || html.trim() === '') {
- return html;
- }
-
- try {
- return DOMPurify.sanitize(html, EMAIL_SANITIZER_CONFIG);
- } catch (ex) {
- logExpected(`[Email] Sanitizing the email HTML failed: ${ex instanceof Error ? ex.message : String(ex)}`);
- // Return empty string on error to prevent potential XSS
- return '';
- }
- }
-
- /**
- * Sanitizes HTML content and converts anchor tags to open in a new tab.
- * This is a convenience method that combines sanitization with anchor tag conversion.
- * @param html The HTML content to process.
- * @returns Sanitized HTML with anchor tags configured to open in new tabs.
- */
- public sanitizeAndPrepareEmailHtml(html: string): string {
- if (!html || html.trim() === '') {
- return html;
- }
-
- // First sanitize to remove XSS vectors
- const sanitizedHtml = this.sanitizeHtmlForEmailViewing(html);
-
- // Then convert anchor tags to open in new tab
- return this.convertAnchorTagsToOpenInNewTab(sanitizedHtml);
- }
-
- /**
- * Convert all anchor tags to open in a new tab.
- * @param html HTML input.
- * @returns HTML with all anchor tags converted to open in a new tab when clicked on.
- *
- * Note: same implementation exists in c-sharp version in AliasVault.Shared.Utilities.ConversionUtility.cs
- */
- public convertAnchorTagsToOpenInNewTab(html: string): string {
- try {
- // Create a DOM parser
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
-
- // Select all anchor tags with href attribute
- const anchors = doc.querySelectorAll('a[href]');
-
- if (anchors.length > 0) {
- anchors.forEach((anchor: Element) => {
- // Handle target attribute
- if (!anchor.hasAttribute('target') || anchor.getAttribute('target') !== '_blank') {
- anchor.setAttribute('target', '_blank');
- }
-
- // Handle rel attribute for security
- if (!anchor.hasAttribute('rel')) {
- anchor.setAttribute('rel', 'noopener noreferrer');
- } else {
- const relValue = anchor.getAttribute('rel') ?? '';
- const relValues = new Set(relValue.split(' ').filter(val => val.trim() !== ''));
-
- relValues.add('noopener');
- relValues.add('noreferrer');
-
- anchor.setAttribute('rel', Array.from(relValues).join(' '));
- }
- });
- }
-
- return doc.documentElement.outerHTML;
- } catch (ex) {
- // Log the exception
- logExpected(`[Email] Rewriting the email's links failed: ${ex instanceof Error ? ex.message : String(ex)}`);
-
- // Return the original HTML if an error occurs
- return html;
- }
- }
-}
-
-export default new ConversionUtility();
diff --git a/apps/mobile-app/components/items/details/EmailPreview.tsx b/apps/mobile-app/components/items/details/EmailPreview.tsx
index efbcb1784..b1d90e209 100644
--- a/apps/mobile-app/components/items/details/EmailPreview.tsx
+++ b/apps/mobile-app/components/items/details/EmailPreview.tsx
@@ -161,21 +161,13 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
if (isPublic) {
// For public domains (SpamOK), use the SpamOK API directly
const emailPrefix = email.split('@')[0];
- const response = await spamOk.request('GET', `EmailBox/${emailPrefix}`);
-
- if (!response.ok) {
- markPollFailed(`The mailbox request returned HTTP ${response.status}`);
+ const allMails = await spamOk.getMailbox(emailPrefix);
+ if (!allMails) {
+ markPollFailed('The mailbox request failed');
setError(t('items.emailLoadError'));
return;
}
- const data = await response.json();
-
- // Store all emails, sorted by date
- const allMails = data?.mails
- ?.sort((a: MailboxEmail, b: MailboxEmail) =>
- new Date(b.dateSystem).getTime() - new Date(a.dateSystem).getTime()) ?? [];
-
if (loading && allMails.length > 0) {
setLastEmailId(allMails[0].id);
}
diff --git a/apps/mobile-app/utils/ConversionUtility.ts b/apps/mobile-app/utils/ConversionUtility.ts
index a35406990..df08379bb 100644
--- a/apps/mobile-app/utils/ConversionUtility.ts
+++ b/apps/mobile-app/utils/ConversionUtility.ts
@@ -1,3 +1,4 @@
+import { EMAIL_ALLOWED_TAGS } from '@aliasvault/client/email/EmailHtmlPolicy';
import sanitizeHtml from 'sanitize-html';
/**
@@ -10,16 +11,7 @@ const EMAIL_SANITIZER_CONFIG: sanitizeHtml.IOptions = {
// Disable style parsing as it requires PostCSS which doesn't work in React Native
// See: https://github.com/apostrophecms/sanitize-html/issues/547
parseStyleAttributes: false,
- allowedTags: [
- 'div', 'span', 'p', 'br', 'hr',
- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
- 'ul', 'ol', 'li',
- 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
- 'a', 'img',
- 'b', 'i', 'u', 's', 'strike', 'strong', 'em', 'small', 'sub', 'sup',
- 'blockquote', 'pre', 'code',
- 'font', 'center'
- ],
+ allowedTags: EMAIL_ALLOWED_TAGS,
allowedAttributes: {
'*': ['style', 'class', 'id'],
'table': ['width', 'height', 'align', 'valign', 'bgcolor', 'border', 'cellpadding', 'cellspacing'],
diff --git a/apps/web/package-lock.json b/apps/web/package-lock.json
index 80912909c..fadd33f28 100644
--- a/apps/web/package-lock.json
+++ b/apps/web/package-lock.json
@@ -12,8 +12,6 @@
"@aliasvault/client": "file:../../core/client",
"@aliasvault/models": "file:../../core/models",
"@aliasvault/vault": "file:../../core/vault",
- "buffer": "^6.0.3",
- "dompurify": "^3.4.12",
"i18next": "^26.2.0",
"otpauth": "^9.3.6",
"qrcode": "^1.5.4",
@@ -23,7 +21,6 @@
"react-router-dom": "^7.18.1"
},
"devDependencies": {
- "@types/dompurify": "^3.0.5",
"@types/node": "^22.13.10",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.0.7",
@@ -53,10 +50,12 @@
"dependencies": {
"@aliasvault/models": "file:../models",
"@aliasvault/vault": "file:../vault",
+ "dompurify": "^3.4.12",
"fflate": "^0.8.3",
"otpauth": "^9.3.6"
},
"devDependencies": {
+ "@types/node": "^22.13.10",
"@typescript-eslint/eslint-plugin": "^8.65.0",
"@typescript-eslint/parser": "^8.65.0",
"eslint": "^9.39.5",
@@ -65,7 +64,7 @@
"eslint-plugin-jsdoc": "^50.6.3",
"globals": "^16.5.0",
"typescript": "^5.6.3",
- "vitest": "^4.1.8"
+ "vitest": "^5.0.1"
}
},
"../../core/models": {
@@ -78,7 +77,7 @@
"eslint": "^9.19.0",
"tsup": "^8.4.0",
"typescript": "^5.3.3",
- "vitest": "^4.1.8"
+ "vitest": "^5.0.1"
}
},
"../../core/vault": {
@@ -88,11 +87,11 @@
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^8.21.0",
"@typescript-eslint/parser": "^8.21.0",
- "@vitest/coverage-v8": "^4.1.8",
+ "@vitest/coverage-v8": "^5.0.1",
"eslint": "^9.19.0",
"tsup": "^8.4.0",
"typescript": "^5.3.3",
- "vitest": "^4.1.8"
+ "vitest": "^5.0.1"
}
},
"node_modules/@aliasvault/client": {
@@ -881,16 +880,6 @@
"tslib": "^2.4.0"
}
},
- "node_modules/@types/dompurify": {
- "version": "3.0.5",
- "resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.0.5.tgz",
- "integrity": "sha512-1Wg0g3BtQF7sSb27fJQAKck1HECM6zV1EB66j8JH9i3LCjYabJa0FSdiSgsD5K/RbrsR0SiraKacLB+T8ZVYAg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/trusted-types": "*"
- }
- },
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -952,13 +941,6 @@
"@types/react": "^19.3.0"
}
},
- "node_modules/@types/trusted-types": {
- "version": "2.0.7",
- "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
- "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
- "devOptional": true,
- "license": "MIT"
- },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.70.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz",
@@ -1907,26 +1889,6 @@
"node": "18 || 20 || >=22"
}
},
- "node_modules/base64-js": {
- "version": "1.5.1",
- "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
- "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "MIT"
- },
"node_modules/baseline-browser-mapping": {
"version": "2.11.23",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.23.tgz",
@@ -2013,30 +1975,6 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
- "node_modules/buffer": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
- "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "base64-js": "^1.3.1",
- "ieee754": "^1.2.1"
- }
- },
"node_modules/call-bind": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz",
@@ -2463,15 +2401,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/dompurify": {
- "version": "3.4.15",
- "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz",
- "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==",
- "license": "(MPL-2.0 OR Apache-2.0)",
- "optionalDependencies": {
- "@types/trusted-types": "^2.0.7"
- }
- },
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -3741,26 +3670,6 @@
}
}
},
- "node_modules/ieee754": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
- "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "BSD-3-Clause"
- },
"node_modules/ignore": {
"version": "7.0.9",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.9.tgz",
diff --git a/apps/web/package.json b/apps/web/package.json
index 9e97fceac..7446007bc 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -18,8 +18,6 @@
"@aliasvault/client": "file:../../core/client",
"@aliasvault/models": "file:../../core/models",
"@aliasvault/vault": "file:../../core/vault",
- "buffer": "^6.0.3",
- "dompurify": "^3.4.12",
"i18next": "^26.2.0",
"otpauth": "^9.3.6",
"qrcode": "^1.5.4",
@@ -29,7 +27,6 @@
"react-router-dom": "^7.18.1"
},
"devDependencies": {
- "@types/dompurify": "^3.0.5",
"@types/node": "^22.13.10",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.0.7",
diff --git a/apps/web/src/components/email/EmailModal.tsx b/apps/web/src/components/email/EmailModal.tsx
index 4fed7a3ae..be1d99e0a 100644
--- a/apps/web/src/components/email/EmailModal.tsx
+++ b/apps/web/src/components/email/EmailModal.tsx
@@ -1,3 +1,4 @@
+import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -10,7 +11,6 @@ import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { useEmailBody } from '@/hooks/useEmailBody';
import { type EmailAttachmentViewModel, type EmailViewModel, getAttachmentBytes, spamOk } from '@/utils/EmailViewModel';
-import { downloadBytes } from '@/utils/FileDownload';
import { itemRoute } from '@/utils/ItemRoute';
import type { ItemRef } from '@aliasvault/client/database/ItemRef';
diff --git a/apps/web/src/components/email/EmailPreview.tsx b/apps/web/src/components/email/EmailPreview.tsx
index cdff16c7a..4adfcd4d7 100644
--- a/apps/web/src/components/email/EmailPreview.tsx
+++ b/apps/web/src/components/email/EmailPreview.tsx
@@ -1,3 +1,4 @@
+import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';
import React from 'react';
import { useTranslation } from 'react-i18next';
@@ -7,7 +8,6 @@ import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { useEmailBody } from '@/hooks/useEmailBody';
import { type EmailAttachmentViewModel, type EmailViewModel, getAttachmentBytes, spamOk } from '@/utils/EmailViewModel';
-import { downloadBytes } from '@/utils/FileDownload';
import type { ItemRef } from '@aliasvault/client/database/ItemRef';
diff --git a/apps/web/src/utils/ApiErrors.ts b/apps/web/src/utils/ApiErrors.ts
new file mode 100644
index 000000000..67bb3cde6
--- /dev/null
+++ b/apps/web/src/utils/ApiErrors.ts
@@ -0,0 +1,18 @@
+import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
+
+import type { TFunction } from 'i18next';
+
+/**
+ * The message for a failed API call: the translated API error code when the server sent one, else the fallback.
+ * @param error - the thrown error
+ * @param t - the translation function
+ * @param fallback - the message when no known code is present
+ */
+export function apiErrorMessage(error: unknown, t: TFunction, fallback: string): string {
+ if (error instanceof ApiRequestError && error.apiErrorCode) {
+ const key = `apiErrors.${error.apiErrorCode}`;
+ const translated = t(key);
+ return translated === key ? fallback : translated;
+ }
+ return fallback;
+}
diff --git a/apps/web/src/utils/ClipboardCopyService.ts b/apps/web/src/utils/ClipboardCopyService.ts
new file mode 100644
index 000000000..aefae4705
--- /dev/null
+++ b/apps/web/src/utils/ClipboardCopyService.ts
@@ -0,0 +1,229 @@
+/**
+ * Clipboard copy with auto-clear behaviour.
+ */
+
+/** Clipboard clear status. */
+export type ClipboardStatus = 'active' | 'pending' | 'manual_clear_required' | 'cleared';
+
+type CopyListener = (copiedId: string) => void;
+type ProgressListener = (progress: number) => void;
+type StatusListener = (status: ClipboardStatus) => void;
+
+/** How long the "copied" highlight stays on the copied element. */
+const COPIED_STATE_MS = 2000;
+
+/** Tolerance on the clear timer to account for slightly early ticks. */
+const CLEAR_TOLERANCE_MS = 100;
+
+/**
+ * Clipboard copy and clear coordinator.
+ */
+class ClipboardCopyService {
+ private currentCopiedId = '';
+ private copiedStateTimer: ReturnType<typeof setTimeout> | null = null;
+ private progressTimer: ReturnType<typeof setInterval> | null = null;
+ private clearTimer: ReturnType<typeof setTimeout> | null = null;
+ private clearByTime: number | null = null;
+ private clearDurationMs = 0;
+ private failedAttempts = 0;
+ private copyListeners: CopyListener[] = [];
+ private progressListeners: ProgressListener[] = [];
+ private statusListeners: StatusListener[] = [];
+ private listenersAttached = false;
+
+ /**
+ * Copy a value and schedule the clear. Returns whether the copy succeeded.
+ * @param id - the id of the element the value came from
+ * @param value - the value to copy
+ * @param clearAfterSeconds - seconds until the clipboard is cleared, 0 to never clear
+ */
+ public async copy(id: string, value: string, clearAfterSeconds: number): Promise<boolean> {
+ try {
+ await navigator.clipboard.writeText(value);
+ } catch (error) {
+ console.error('[Clipboard] Failed to copy to clipboard:', error);
+ return false;
+ }
+
+ this.attachWindowListeners();
+ this.setCopied(id);
+ if (clearAfterSeconds > 0) {
+ this.scheduleClear(clearAfterSeconds);
+ }
+ return true;
+ }
+
+ /**
+ * The id of the element whose value was copied last, empty once the highlight expired.
+ */
+ public getCopiedId(): string {
+ return this.currentCopiedId;
+ }
+
+ /**
+ * Subscribe to copies. Returns the unsubscribe function.
+ */
+ public subscribe(listener: CopyListener): () => void {
+ this.copyListeners.push(listener);
+ return (): void => {
+ this.copyListeners = this.copyListeners.filter(l => l !== listener);
+ };
+ }
+
+ /**
+ * Subscribe to countdown progress (1 at the start of the countdown, 0 when done). Returns the unsubscribe function.
+ */
+ public subscribeProgress(listener: ProgressListener): () => void {
+ this.progressListeners.push(listener);
+ return (): void => {
+ this.progressListeners = this.progressListeners.filter(l => l !== listener);
+ };
+ }
+
+ /**
+ * Subscribe to clear status changes. Returns the unsubscribe function.
+ */
+ public subscribeStatus(listener: StatusListener): () => void {
+ this.statusListeners.push(listener);
+ return (): void => {
+ this.statusListeners = this.statusListeners.filter(l => l !== listener);
+ };
+ }
+
+ /**
+ * Clear the clipboard now, on the user's request.
+ */
+ public async clearNow(): Promise<boolean> {
+ return this.attemptClear(true);
+ }
+
+ /**
+ * Mark an element as copied and start the highlight timer.
+ */
+ private setCopied(id: string): void {
+ this.currentCopiedId = id;
+ this.copyListeners.forEach(l => l(id));
+
+ if (this.copiedStateTimer) {
+ clearTimeout(this.copiedStateTimer);
+ }
+ this.copiedStateTimer = setTimeout(() => {
+ this.currentCopiedId = '';
+ this.copiedStateTimer = null;
+ this.copyListeners.forEach(l => l(''));
+ }, COPIED_STATE_MS);
+ }
+
+ /**
+ * Start the countdown to the clear.
+ */
+ private scheduleClear(seconds: number): void {
+ this.stopTimers();
+ this.failedAttempts = 0;
+ this.clearDurationMs = seconds * 1000;
+ this.clearByTime = Date.now() + this.clearDurationMs;
+ this.notifyStatus('active');
+
+ this.progressTimer = setInterval(() => this.updateProgress(), 100);
+ this.updateProgress();
+ this.clearTimer = setTimeout(() => void this.attemptClear(false), this.clearDurationMs);
+ }
+
+ /**
+ * Push the remaining fraction of the countdown to the bar.
+ */
+ private updateProgress(): void {
+ if (this.clearByTime === null || this.clearDurationMs <= 0) {
+ return;
+ }
+ const progress = Math.max(0, this.clearByTime - Date.now()) / this.clearDurationMs;
+ this.progressListeners.forEach(l => l(progress));
+ if (progress <= 0 && this.progressTimer) {
+ clearInterval(this.progressTimer);
+ this.progressTimer = null;
+ }
+ }
+
+ /**
+ * Try to clear the clipboard. The browser refuses while the document is not focused, in which case the clear
+ * is retried on focus and, after two failures, marked as manual clear required.
+ */
+ private async attemptClear(manual: boolean): Promise<boolean> {
+ if (this.clearByTime === null) {
+ return false;
+ }
+ if (!manual && this.clearByTime - Date.now() > CLEAR_TOLERANCE_MS) {
+ return false;
+ }
+
+ try {
+ await navigator.clipboard.writeText('');
+ this.clearByTime = null;
+ this.failedAttempts = 0;
+ this.stopTimers();
+ this.progressListeners.forEach(l => l(0));
+ this.notifyStatus('cleared');
+ return true;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ const notFocused = (error instanceof Error && error.name === 'NotAllowedError') || message.includes('Document is not focused');
+ if (!notFocused) {
+ console.warn('[Clipboard] Failed to clear clipboard:', error);
+ return false;
+ }
+ this.failedAttempts++;
+ this.notifyStatus(this.failedAttempts >= 2 ? 'manual_clear_required' : 'pending');
+ return false;
+ }
+ }
+
+ /**
+ * Retry a due clear once the page regains focus or visibility.
+ */
+ private checkAndClear(): void {
+ if (this.clearByTime !== null && Date.now() >= this.clearByTime) {
+ setTimeout(() => void this.attemptClear(false), 100);
+ }
+ }
+
+ /**
+ * Listen for the page becoming visible again, once.
+ */
+ private attachWindowListeners(): void {
+ if (this.listenersAttached) {
+ return;
+ }
+ this.listenersAttached = true;
+ window.addEventListener('focus', () => this.checkAndClear());
+ window.addEventListener('pageshow', () => this.checkAndClear());
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') {
+ this.checkAndClear();
+ }
+ });
+ }
+
+ /**
+ * Stop the countdown timers.
+ */
+ private stopTimers(): void {
+ if (this.progressTimer) {
+ clearInterval(this.progressTimer);
+ this.progressTimer = null;
+ }
+ if (this.clearTimer) {
+ clearTimeout(this.clearTimer);
+ this.clearTimer = null;
+ }
+ }
+
+ /**
+ * Tell the bar about a status change.
+ */
+ private notifyStatus(status: ClipboardStatus): void {
+ this.statusListeners.forEach(l => l(status));
+ }
+}
+
+/** The page's clipboard service. */
+export const clipboardCopyService = new ClipboardCopyService();
diff --git a/apps/web/src/utils/DevLogger.ts b/apps/web/src/utils/DevLogger.ts
new file mode 100644
index 000000000..2e8bf494e
--- /dev/null
+++ b/apps/web/src/utils/DevLogger.ts
@@ -0,0 +1,51 @@
+/**
+ * Dev-only console logging. Every trace carries a `[Channel]` tag as its first bracketed token.
+ */
+
+/**
+ * Emit a timestamped dev trace, only in development builds.
+ * @param level - console method to use
+ * @param message - the message (should start with a `[Channel]` tag)
+ * @param args - additional console arguments
+ */
+function emit(level: 'info' | 'warn' | 'error', message: string, args: unknown[]): void {
+ if (!import.meta.env.DEV) {
+ return;
+ }
+ const time = new Date().toISOString().slice(11, 23);
+ const line = `[${time}] ${message}`;
+ if (level === 'error') {
+ console.error(line, ...args);
+ } else if (level === 'warn') {
+ console.warn(line, ...args);
+ } else {
+ console.info(line, ...args);
+ }
+}
+
+/**
+ * Log a timestamped, channel-scoped trace for debugging.
+ * @param message - the message (should start with a `[Channel]` tag)
+ * @param args - additional console arguments
+ */
+export function devLog(message: string, ...args: unknown[]): void {
+ emit('info', message, args);
+}
+
+/**
+ * Like {@link devLog} but at `console.warn` level.
+ * @param message - the message (should start with a `[Channel]` tag)
+ * @param args - additional console arguments
+ */
+export function devWarn(message: string, ...args: unknown[]): void {
+ emit('warn', message, args);
+}
+
+/**
+ * Like {@link devLog} but at `console.error` level.
+ * @param message - the message (should start with a `[Channel]` tag)
+ * @param args - additional console arguments
+ */
+export function devError(message: string, ...args: unknown[]): void {
+ emit('error', message, args);
+}
diff --git a/apps/web/src/utils/ItemRoute.ts b/apps/web/src/utils/ItemRoute.ts
new file mode 100644
index 000000000..d1952ea37
--- /dev/null
+++ b/apps/web/src/utils/ItemRoute.ts
@@ -0,0 +1,21 @@
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+import type { FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
+
+/**
+ * The route of an item.
+ * @param item - The item, named by its manifest and id
+ * @param edit - True for the edit page instead of the details page
+ * @returns The route path
+ */
+export function itemRoute(item: ItemRef, edit: boolean = false): string {
+ return `/items/${encodeURIComponent(item.ManifestId)}/${encodeURIComponent(item.Id)}${edit ? '/edit' : ''}`;
+}
+
+/**
+ * The route of a folder's item list.
+ * @param folder - The folder, named by its manifest and id
+ * @returns The route path
+ */
+export function folderRoute(folder: FolderRef): string {
+ return `/items/folder/${encodeURIComponent(folder.ManifestId)}/${encodeURIComponent(folder.Id)}`;
+}
diff --git a/core/client/package-lock.json b/core/client/package-lock.json
index 9544b3b50..81191e3db 100644
--- a/core/client/package-lock.json
+++ b/core/client/package-lock.json
@@ -11,6 +11,7 @@
"dependencies": {
"@aliasvault/models": "file:../models",
"@aliasvault/vault": "file:../vault",
+ "dompurify": "^3.4.12",
"fflate": "^0.8.3",
"otpauth": "^9.3.6"
},
@@ -831,6 +832,13 @@
"undici-types": "~6.21.0"
}
},
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.70.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz",
@@ -1977,6 +1985,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/dompurify": {
+ "version": "3.4.16",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz",
+ "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
diff --git a/core/client/package.json b/core/client/package.json
index 4ad058490..50777feac 100644
--- a/core/client/package.json
+++ b/core/client/package.json
@@ -22,6 +22,7 @@
"dependencies": {
"@aliasvault/models": "file:../models",
"@aliasvault/vault": "file:../vault",
+ "dompurify": "^3.4.12",
"fflate": "^0.8.3",
"otpauth": "^9.3.6"
},
diff --git a/core/client/src/email/EmailHtmlPolicy.ts b/core/client/src/email/EmailHtmlPolicy.ts
new file mode 100644
index 000000000..4222fbc7b
--- /dev/null
+++ b/core/client/src/email/EmailHtmlPolicy.ts
@@ -0,0 +1,49 @@
+/**
+ * What an email's HTML body may contain when shown in a viewer, independent of the sanitizer library.
+ */
+
+/**
+ * Elements kept in a displayed email.
+ */
+export const EMAIL_ALLOWED_TAGS = [
+ 'div', 'span', 'p', 'br', 'hr',
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
+ 'ul', 'ol', 'li',
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
+ 'a', 'img',
+ 'b', 'i', 'u', 's', 'strike', 'strong', 'em', 'small', 'sub', 'sup',
+ 'blockquote', 'pre', 'code',
+ 'font', 'center',
+];
+
+/**
+ * Attributes kept on any allowed element.
+ */
+export const EMAIL_ALLOWED_ATTRIBUTES = [
+ 'style', 'class', 'id',
+ 'width', 'height', 'align', 'valign',
+ 'bgcolor', 'color', 'border',
+ 'cellpadding', 'cellspacing', 'colspan', 'rowspan',
+ 'face', 'size',
+ 'href', 'target', 'rel',
+ 'src', 'alt', 'title',
+];
+
+/**
+ * Elements always removed, even if a future edit adds them to the allowed list.
+ */
+export const EMAIL_FORBIDDEN_TAGS = [
+ 'script', 'object', 'embed', 'iframe', 'frame', 'frameset',
+ 'form', 'input', 'button', 'textarea', 'select', 'option',
+ 'link', 'meta', 'base', 'applet',
+];
+
+/**
+ * Event handler attributes always removed, as a backstop to the allowed list.
+ */
+export const EMAIL_FORBIDDEN_ATTRIBUTES = [
+ 'onerror', 'onload', 'onclick', 'onmouseover', 'onmouseout',
+ 'onfocus', 'onblur', 'onchange', 'onsubmit', 'onreset', 'onkeydown',
+ 'onkeyup', 'onkeypress', 'ondblclick', 'oncontextmenu', 'onmousedown',
+ 'onmouseup', 'onmousemove', 'ondrag', 'ondrop',
+];
diff --git a/core/client/src/email/EmailHtmlSanitizer.ts b/core/client/src/email/EmailHtmlSanitizer.ts
new file mode 100644
index 000000000..e52a90a82
--- /dev/null
+++ b/core/client/src/email/EmailHtmlSanitizer.ts
@@ -0,0 +1,61 @@
+import DOMPurify, { type Config, type DOMPurify as DOMPurifyInstance } from 'dompurify';
+
+import { logExpected } from '../utilities/Diagnostics';
+
+import { EMAIL_ALLOWED_ATTRIBUTES, EMAIL_ALLOWED_TAGS, EMAIL_FORBIDDEN_ATTRIBUTES, EMAIL_FORBIDDEN_TAGS } from './EmailHtmlPolicy';
+
+/**
+ * DOMPurify options built from the shared email HTML policy.
+ */
+const SANITIZER_CONFIG: Config = {
+ ALLOWED_TAGS: EMAIL_ALLOWED_TAGS,
+ ALLOWED_ATTR: EMAIL_ALLOWED_ATTRIBUTES,
+ ALLOW_DATA_ATTR: false,
+ FORBID_TAGS: EMAIL_FORBIDDEN_TAGS,
+ FORBID_ATTR: EMAIL_FORBIDDEN_ATTRIBUTES,
+};
+
+/**
+ * Own DOMPurify instance, so the link hook below never touches other DOMPurify users. Created on first use.
+ */
+let purifier: DOMPurifyInstance | null = null;
+
+/**
+ * The email sanitizer, which also makes every link open in a new tab within the same pass.
+ */
+function getPurifier(): DOMPurifyInstance {
+ if (purifier) {
+ return purifier;
+ }
+ purifier = DOMPurify(window);
+ purifier.addHook('afterSanitizeAttributes', node => {
+ if (node.nodeName !== 'A' || !node.hasAttribute('href')) {
+ return;
+ }
+ node.setAttribute('target', '_blank');
+ const rel = new Set((node.getAttribute('rel') ?? '').split(' ').filter(value => value.trim() !== ''));
+ rel.add('noopener');
+ rel.add('noreferrer');
+ node.setAttribute('rel', Array.from(rel).join(' '));
+ });
+ return purifier;
+}
+
+/**
+ * Sanitize an email's HTML body for display and make its links open in a new tab.
+ * @param html - the HTML body of the email
+ * @returns HTML safe for display, or an empty string when sanitizing fails
+ */
+export function sanitizeEmailHtml(html: string): string {
+ if (!html || html.trim() === '') {
+ return html;
+ }
+
+ try {
+ return getPurifier().sanitize(html, SANITIZER_CONFIG);
+ } catch (error) {
+ logExpected('[Email] Sanitizing the email HTML failed', error);
+ // Show nothing rather than risk showing unsanitized HTML.
+ return '';
+ }
+}
diff --git a/core/client/src/email/SpamOkClient.ts b/core/client/src/email/SpamOkClient.ts
index 7c247e3a9..0eaa5ca2d 100644
--- a/core/client/src/email/SpamOkClient.ts
+++ b/core/client/src/email/SpamOkClient.ts
@@ -39,7 +39,7 @@ export class SpamOkClient {
}
/**
- * The mails in a mailbox, or null when the request failed.
+ * The mails in a mailbox, newest first, or null when the request failed.
* @param emailPrefix - the local part of the address
*/
public async getMailbox(emailPrefix: string): Promise<MailboxEmail[] | null> {
@@ -48,7 +48,7 @@ export class SpamOkClient {
return null;
}
const mailbox = await response.json() as { mails?: MailboxEmail[] };
- return mailbox.mails ?? [];
+ return [...(mailbox.mails ?? [])].sort((a, b) => new Date(b.dateSystem).getTime() - new Date(a.dateSystem).getTime());
}
/**
diff --git a/core/client/src/items/BulkFaviconService.ts b/core/client/src/items/BulkFaviconService.ts
new file mode 100644
index 000000000..ef015443c
--- /dev/null
+++ b/core/client/src/items/BulkFaviconService.ts
@@ -0,0 +1,97 @@
+import { ApiRequestError } from '../api/errors/ApiRequestError';
+import { base64ToBytes } from '../utilities/Base64';
+
+import type { WebApiService } from '../api/WebApiService';
+import type { FaviconTarget } from '../rust/RustCore';
+
+/**
+ * Outcome of a bulk extraction.
+ */
+export type BulkExtractStatus = 'completed' | 'cancelled' | 'rateLimited';
+
+/**
+ * Result of a bulk extraction: favicons keyed by source so one fetched favicon serves every item on that domain.
+ */
+export type BulkExtractResult = {
+ favicons: Map<string, Uint8Array>;
+ status: BulkExtractStatus;
+};
+
+/**
+ * One entry of the server's batch response.
+ */
+type FaviconExtractBatchResult = {
+ url: string;
+ /** The image bytes, base64 encoded, or null when none could be fetched. */
+ image: string | null;
+};
+
+/**
+ * URLs per batch request; mirrors the server's FaviconController.MaxBatchSize.
+ */
+const BATCH_SIZE = 10;
+
+/**
+ * Bulk favicon extraction for imports. Single-item favicon logic lives in FaviconService.
+ */
+export class BulkFaviconService {
+ /**
+ * Fetch favicons for many targets in server-side batches.
+ * @param webApi The WebAPI service for making the requests
+ * @param targets The favicon targets
+ * @param onProgress Called after each batch with the number of sources processed so far
+ * @param signal Aborts the extraction between batches
+ * @returns The favicons by source plus the outcome
+ */
+ public static async extractBulk(webApi: WebApiService, targets: FaviconTarget[], onProgress?: (processed: number) => Promise<void> | void, signal?: AbortSignal): Promise<BulkExtractResult> {
+ const favicons = new Map<string, Uint8Array>();
+
+ const urlBySource = new Map<string, string>();
+ for (const target of targets) {
+ if (!urlBySource.has(target.source)) {
+ urlBySource.set(target.source, target.url);
+ }
+ }
+
+ if (urlBySource.size === 0) {
+ return { favicons, status: 'completed' };
+ }
+
+ const entries = [...urlBySource.entries()];
+ let processed = 0;
+
+ for (let i = 0; i < entries.length; i += BATCH_SIZE) {
+ if (signal?.aborted) {
+ return { favicons, status: 'cancelled' };
+ }
+
+ const chunk = entries.slice(i, i + BATCH_SIZE);
+ let results: FaviconExtractBatchResult[] | undefined;
+ try {
+ const response = await webApi.post<{ urls: string[] }, { results?: FaviconExtractBatchResult[] }>('Favicon/ExtractBatch', { urls: chunk.map(([, url]) => url) });
+ results = response?.results;
+ } catch (error) {
+ if (error instanceof ApiRequestError && error.statusCode === 429) {
+ return { favicons, status: 'rateLimited' };
+ }
+ // A transport or server error fails the whole chunk; the rest continues.
+ results = undefined;
+ }
+
+ if (results) {
+ // Matched by index: the server echoes the URL, but the index is robust against URL normalization.
+ for (let j = 0; j < results.length && j < chunk.length; j++) {
+ const image = results[j].image;
+ if (image) {
+ favicons.set(chunk[j][0], base64ToBytes(image));
+ }
+ }
+ }
+
+ processed += chunk.length;
+ await onProgress?.(processed);
+ }
+
+ return { favicons, status: 'completed' };
+ }
+}
diff --git a/core/client/src/utilities/FileDownload.ts b/core/client/src/utilities/FileDownload.ts
new file mode 100644
index 000000000..a01a56c1d
--- /dev/null
+++ b/core/client/src/utilities/FileDownload.ts
@@ -0,0 +1,19 @@
+/**
+ * Hand bytes to the browser as a file download.
+ * @param filename - the name the file is saved as
+ * @param bytes - the file contents
+ * @param mimeType - the content type, octet-stream when unknown
+ */
+export function downloadBytes(filename: string, bytes: Uint8Array | number[], mimeType: string | null = null): void {
+ const data = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes);
+ const blob = new Blob([data as BlobPart], { type: mimeType ?? 'application/octet-stream' });
+ const url = window.URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = filename;
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+ // The browser reads the URL after click() returns, so revoking it right away can drop the download silently.
+ setTimeout(() => window.URL.revokeObjectURL(url), 10000);
+}