Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update components and utils (#2413)
Leendert de Borst5eb271105bfc
diff --git a/apps/web/src/components/attachments/AttachmentUploader.tsx b/apps/web/src/components/attachments/AttachmentUploader.tsxnew file mode 100644index 000000000..e53399abf--- /dev/null+++ b/apps/web/src/components/attachments/AttachmentUploader.tsx@@ -0,0 +1,81 @@+import React, { useRef, useState } from 'react';++import type { Attachment } from '@aliasvault/models/vault';++type AttachmentUploaderProps = {+ attachments: Attachment[];+ onAttachmentsChange: (attachments: Attachment[]) => void;+};++/** Largest file accepted. */+const MAX_FILE_SIZE = 1024 * 1024 * 10;++/**+ * File picker and list for the attachments of an item.+ */+const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({ attachments, onAttachmentsChange }) => {+ const originalIds = useRef<string[]>(attachments.map(a => a.Id));+ const [statusMessage, setStatusMessage] = useState('');+ const visible = attachments.filter(a => !a.IsDeleted);++ /**+ * Read the picked files into new attachments.+ */+ const handleFileSelection = async (event: React.ChangeEvent<HTMLInputElement>): Promise<void> => {+ const files = Array.from(event.target.files ?? []);+ event.target.value = '';+ setStatusMessage('Uploading...');+ let current = attachments;+ for (const file of files) {+ try {+ if (file.size > MAX_FILE_SIZE) {+ throw new Error(`File exceeds the maximum size of ${MAX_FILE_SIZE / 1024 / 1024} MB.`);+ }+ const now = new Date().toISOString();+ const attachment: Attachment = { Id: crypto.randomUUID(), Filename: file.name, Blob: new Uint8Array(await file.arrayBuffer()), ItemId: '', CreatedAt: now, UpdatedAt: now };+ current = [...current, attachment];+ setStatusMessage('File uploaded successfully.');+ } catch (error) {+ setStatusMessage(`Error uploading file: ${error instanceof Error ? error.message : String(error)}`);+ console.error('Error uploading file.', error);+ }+ }+ onAttachmentsChange(current);+ };++ /**+ * Delete an attachment: original ones are soft deleted, new ones dropped.+ */+ const deleteAttachment = (attachment: Attachment): void => {+ if (originalIds.current.includes(attachment.Id)) {+ onAttachmentsChange(attachments.map(a => a.Id === attachment.Id ? { ...a, IsDeleted: true, UpdatedAt: new Date().toISOString() } : a));+ } else {+ onAttachmentsChange(attachments.filter(a => a.Id !== attachment.Id));+ }+ setStatusMessage('Attachment deleted successfully.');+ };++ return (+ <div className="col-span-6 sm:col-span-3">+ <input type="file" multiple onChange={e => void handleFileSelection(e)} className="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" />+ {statusMessage.length > 0 && <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{statusMessage}</p>}+ {visible.length > 0 && (+ <div className="mt-4">+ <h4 className="mb-2 text-lg font-semibold dark:text-white">Attachments:</h4>+ <ul className="list-disc list-inside">+ {visible.map(attachment => (+ <li key={attachment.Id} className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-400">+ {(attachment.Blob?.length ?? 0) > 0+ ? <span>{attachment.Filename}</span>+ : <span className="text-gray-400 dark:text-gray-500" title="Attachment data unavailable">{attachment.Filename} (unavailable)</span>}+ <button type="button" onClick={() => deleteAttachment(attachment)} className="text-red-500 hover:text-red-700">Delete</button>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ );+};++export default AttachmentUploader;diff --git a/apps/web/src/components/attachments/AttachmentViewer.tsx b/apps/web/src/components/attachments/AttachmentViewer.tsxnew file mode 100644index 000000000..28f54257f--- /dev/null+++ b/apps/web/src/components/attachments/AttachmentViewer.tsx@@ -0,0 +1,67 @@+import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';+import React from 'react';++import type { Attachment } from '@aliasvault/models/vault';++type AttachmentViewerProps = {+ attachments: Attachment[];+};++/**+ * Human readable file size.+ */+const formatSize = (bytes: number): string => {+ const kib = 1024;+ const mib = kib * 1024;+ if (bytes < kib) {+ return `${bytes} B`;+ }+ if (bytes < mib) {+ return `${(bytes / kib).toFixed(1)} KB`;+ }+ return `${(bytes / mib).toFixed(1)} MB`;+};++/**+ * Lists the attachments of an item with download links.+ */+const AttachmentViewer: React.FC<AttachmentViewerProps> = ({ attachments }) => {+ const visible = attachments.filter(a => !a.IsDeleted);++ return (+ <div className="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">+ <h3 className="mb-4 text-xl font-semibold dark:text-white">Attachments</h3>+ {visible.length > 0 ? (+ <div className="overflow-x-auto">+ <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">+ <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">+ <tr>+ <th scope="col" className="px-6 py-3">Filename</th>+ <th scope="col" className="px-6 py-3">Size</th>+ </tr>+ </thead>+ <tbody>+ {visible.map((attachment) => {+ const size = attachment.Blob?.length ?? 0;+ return (+ <tr key={attachment.Id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">+ <td className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">+ {size > 0 && attachment.Blob+ ? <span onClick={() => downloadBytes(attachment.Filename, attachment.Blob!)} className="text-primary cursor-pointer">{attachment.Filename}</span>+ : <span className="text-gray-400 dark:text-gray-500" title="Attachment data unavailable">{attachment.Filename} (unavailable)</span>}+ </td>+ <td className="px-6 py-4">{formatSize(size)}</td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="text-gray-500 dark:text-gray-400">No attachments available.</p>+ )}+ </div>+ );+};++export default AttachmentViewer;diff --git a/apps/web/src/components/email/RecentEmails.tsx b/apps/web/src/components/email/RecentEmails.tsxindex 1d33c7bdc..04f931fc4 100644--- a/apps/web/src/components/email/RecentEmails.tsx+++ b/apps/web/src/components/email/RecentEmails.tsx@@ -246,7 +246,7 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {) : error.length > 0 ? (<AlertMessageError message={error} />) : mailboxEmails.length === 0 ? (- <div className="text-gray-500 dark:text-gray-400">{t('components.main.email.recentEmails.NoEmailsReceivedMessage')}</div>+ <div className="text-sm text-gray-600 dark:text-gray-400">{t('components.main.email.recentEmails.NoEmailsReceivedMessage')}</div>) : (<div className="flex flex-col mt-6"><div className="overflow-x-auto rounded-lg">diff --git a/apps/web/src/models/ItemEdit.ts b/apps/web/src/models/ItemEdit.tsnew file mode 100644index 000000000..2bcb380ea--- /dev/null+++ b/apps/web/src/models/ItemEdit.ts@@ -0,0 +1,279 @@+import { manifestForItemIn } from '@aliasvault/client/database/ItemRef';+import { FieldCategories, FieldTypes, getSystemField, type Attachment, type FieldCategory, type Item, type ItemField, type ItemType, ItemTypes, type Passkey, type TotpCode } from '@aliasvault/models/vault';++import type { FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';++/**+ * A field on the item form. Custom fields carry their definition id as FieldKey.+ */+export type FieldEdit = {+ FieldKey: string;+ Label: string;+ FieldType: string;+ Value: string;+ Values: string[];+ IsCustomField: boolean;+ IsHidden: boolean;+ EnableHistory: boolean;+ DisplayOrder: number;+ Category: FieldCategory;+ IsMultiValue: boolean;+};++/**+ * The item form state.+ */+export type ItemEdit = {+ Id: string;+ ManifestId: string;+ ItemType: ItemType;+ ServiceName: string;+ FolderId: string | null;+ CreatedAt: string;+ Fields: FieldEdit[];+ Attachments: Attachment[];+ TotpCodes: TotpCode[];+ Passkeys: Passkey[];+};++/** The URL placeholder of a new item. */+export const DEFAULT_SERVICE_URL = 'https://';++/**+ * A field edit for a system field with a value.+ */+const newSystemFieldEdit = (fieldKey: string, value: string): FieldEdit | null => {+ const systemField = getSystemField(fieldKey);+ if (!systemField) {+ return null;+ }+ return {+ FieldKey: fieldKey,+ Label: fieldKey,+ FieldType: systemField.FieldType,+ Value: value,+ Values: systemField.IsMultiValue ? [value] : [],+ IsCustomField: false,+ IsHidden: systemField.IsHidden,+ EnableHistory: systemField.EnableHistory,+ DisplayOrder: systemField.DefaultDisplayOrder,+ Category: systemField.Category,+ IsMultiValue: systemField.IsMultiValue,+ };+};++/**+ * An empty form for a new item in a folder, or outside any folder.+ * @param folder - The folder the item is created in, or null for none+ * @param personalManifestId - The user's personal manifest id+ */+export function createNewItemEdit(folder: FolderRef | null, personalManifestId: string | null): ItemEdit {+ const now = new Date().toISOString();+ let edit: ItemEdit = { Id: crypto.randomUUID(), ManifestId: manifestForItemIn(folder, personalManifestId), ItemType: ItemTypes.Login, ServiceName: '', FolderId: folder?.Id ?? null, CreatedAt: now, Fields: [], Attachments: [], TotpCodes: [], Passkeys: [] };+ edit = setFieldValue(edit, 'alias.birthdate', '');+ edit = setFieldValue(edit, 'login.url', DEFAULT_SERVICE_URL);+ return edit;+}++/**+ * The form for an existing item.+ */+export function itemEditFromItem(item: Item, totpCodes: TotpCode[], attachments: Attachment[], passkeys: Passkey[]): ItemEdit {+ const fields: FieldEdit[] = item.Fields.map((field: ItemField) => {+ const systemField = field.IsCustomField ? undefined : getSystemField(field.FieldKey);+ const isMultiValue = systemField?.IsMultiValue ?? false;+ const values = Array.isArray(field.Value) ? field.Value : [field.Value];+ return {+ FieldKey: field.FieldKey,+ Label: field.IsCustomField ? field.Label : field.FieldKey,+ FieldType: field.FieldType ?? FieldTypes.Text,+ Value: values[0] ?? '',+ Values: values,+ IsCustomField: field.IsCustomField,+ IsHidden: field.IsHidden,+ EnableHistory: field.EnableHistory,+ DisplayOrder: systemField?.DefaultDisplayOrder ?? field.DisplayOrder,+ Category: field.IsCustomField ? FieldCategories.Custom : systemField?.Category ?? FieldCategories.Custom,+ IsMultiValue: isMultiValue,+ };+ });++ return {+ Id: item.Id,+ ManifestId: item.ManifestId,+ ItemType: item.ItemType,+ ServiceName: item.Name ?? '',+ FolderId: item.FolderId ?? null,+ CreatedAt: item.CreatedAt,+ Fields: fields,+ Attachments: attachments.filter(a => !a.IsDeleted),+ TotpCodes: totpCodes.filter(t => !t.IsDeleted),+ Passkeys: passkeys,+ };+}++/**+ * Move the form to another folder, or out of any folder; the item's manifest follows the folder.+ * @param edit - The form+ * @param folder - The new folder, or null for none+ * @param personalManifestId - The user's personal manifest id+ */+export function setFolder(edit: ItemEdit, folder: FolderRef | null, personalManifestId: string | null): ItemEdit {+ return { ...edit, FolderId: folder?.Id ?? null, ManifestId: manifestForItemIn(folder, personalManifestId) };+}++/**+ * The field with a key, or null.+ */+export function getField(edit: ItemEdit, fieldKey: string): FieldEdit | null {+ return edit.Fields.find(f => f.FieldKey === fieldKey) ?? null;+}++/**+ * The value of a field, empty when absent.+ */+export function getFieldValue(edit: ItemEdit, fieldKey: string): string {+ return getField(edit, fieldKey)?.Value ?? '';+}++/**+ * The values of a multi-value field, at least one (possibly empty) entry.+ */+export function getFieldValues(edit: ItemEdit, fieldKey: string): string[] {+ const field = getField(edit, fieldKey);+ if (!field) {+ return [''];+ }+ if (field.Values.length > 0) {+ return field.Values;+ }+ return field.Value.length > 0 ? [field.Value] : [''];+}++/**+ * Set the value of a system field, adding the field when absent.+ */+export function setFieldValue(edit: ItemEdit, fieldKey: string, value: string): ItemEdit {+ const existing = getField(edit, fieldKey);+ if (existing) {+ const updated: FieldEdit = { ...existing, Value: value, Values: existing.IsMultiValue ? [value] : existing.Values };+ return { ...edit, Fields: edit.Fields.map(f => f === existing ? updated : f) };+ }+ const created = newSystemFieldEdit(fieldKey, value);+ return created ? { ...edit, Fields: [...edit.Fields, created] } : edit;+}++/**+ * Set the values of a multi-value system field.+ */+export function setFieldValues(edit: ItemEdit, fieldKey: string, values: string[]): ItemEdit {+ const withField = getField(edit, fieldKey) ? edit : setFieldValue(edit, fieldKey, '');+ return { ...withField, Fields: withField.Fields.map(f => f.FieldKey === fieldKey ? { ...f, Values: values, Value: values[0] ?? '' } : f) };+}++/**+ * Whether a field has a non-empty value.+ */+export function hasFieldValue(edit: ItemEdit, fieldKey: string): boolean {+ const field = getField(edit, fieldKey);+ if (!field) {+ return false;+ }+ return field.IsMultiValue ? field.Values.some(v => v.length > 0) : field.Value.length > 0;+}++/**+ * The custom fields in display order.+ */+export function getCustomFields(edit: ItemEdit): FieldEdit[] {+ return edit.Fields.filter(f => f.IsCustomField).sort((a, b) => a.DisplayOrder - b.DisplayOrder);+}++/**+ * Add a custom field. Its key is the id of the field definition that will be created on save.+ */+export function addCustomField(edit: ItemEdit, label: string, fieldType: string): ItemEdit {+ const field: FieldEdit = {+ FieldKey: crypto.randomUUID(),+ Label: label,+ FieldType: fieldType,+ Value: '',+ Values: [],+ IsCustomField: true,+ IsHidden: fieldType === FieldTypes.Hidden || fieldType === FieldTypes.Password,+ EnableHistory: false,+ DisplayOrder: edit.Fields.length,+ Category: FieldCategories.Custom,+ IsMultiValue: false,+ };+ return { ...edit, Fields: [...edit.Fields, field] };+}++/**+ * Remove a custom field.+ */+export function removeCustomField(edit: ItemEdit, fieldKey: string): ItemEdit {+ return { ...edit, Fields: edit.Fields.filter(f => !(f.IsCustomField && f.FieldKey === fieldKey)) };+}++/**+ * Change the label and type of a custom field.+ */+export function updateCustomField(edit: ItemEdit, fieldKey: string, label: string, fieldType: string): ItemEdit {+ const hidden = fieldType === FieldTypes.Hidden || fieldType === FieldTypes.Password;+ return { ...edit, Fields: edit.Fields.map(f => f.IsCustomField && f.FieldKey === fieldKey ? { ...f, Label: label, FieldType: fieldType, IsHidden: hidden } : f) };+}++/**+ * Replace the custom fields with a reordered list, renumbering their display order.+ */+export function reorderCustomFields(edit: ItemEdit, reordered: FieldEdit[]): ItemEdit {+ const renumbered = reordered.map((f, index) => ({ ...f, DisplayOrder: index }));+ return { ...edit, Fields: [...edit.Fields.filter(f => !f.IsCustomField), ...renumbered] };+}++/**+ * Whether any alias identity field is filled in.+ */+export function hasAliasValues(edit: ItemEdit): boolean {+ return ['alias.first_name', 'alias.last_name', 'alias.gender', 'alias.birthdate'].some(key => getFieldValue(edit, key).trim().length > 0);+}++/**+ * The item to store: system fields+ * without a value are dropped, as are an email that is only a domain and the URL placeholder; custom fields are+ * always kept, they only go when explicitly removed.+ */+export function itemEditToItem(edit: ItemEdit): Item {+ const fields: ItemField[] = [];+ for (const field of edit.Fields) {+ if (field.IsCustomField) {+ fields.push({ FieldKey: field.FieldKey, Label: field.Label, FieldType: field.FieldType as ItemField['FieldType'], Value: field.Value, IsHidden: field.IsHidden, DisplayOrder: field.DisplayOrder, IsCustomField: true, EnableHistory: false });+ continue;+ }++ let value: string | string[] = field.IsMultiValue ? field.Values.filter(v => v.length > 0) : field.Value;+ if (field.FieldKey === 'login.email' && typeof value === 'string' && value.startsWith('@')) {+ value = '';+ }+ if (field.FieldKey === 'login.url') {+ value = (Array.isArray(value) ? value : [value]).filter(v => v !== DEFAULT_SERVICE_URL && v.trim().length > 0);+ }+ const hasValue = Array.isArray(value) ? value.length > 0 : value.length > 0;+ if (!hasValue) {+ continue;+ }+ fields.push({ FieldKey: field.FieldKey, Label: field.FieldKey, FieldType: field.FieldType as ItemField['FieldType'], Value: value, IsHidden: field.IsHidden, DisplayOrder: field.DisplayOrder, IsCustomField: false, EnableHistory: field.EnableHistory });+ }++ return {+ Id: edit.Id,+ ManifestId: edit.ManifestId,+ Name: edit.ServiceName,+ ItemType: edit.ItemType,+ FolderId: edit.FolderId,+ Fields: fields,+ CreatedAt: edit.CreatedAt,+ UpdatedAt: new Date().toISOString(),+ };+}diff --git a/apps/web/src/utils/EmailViewModel.ts b/apps/web/src/utils/EmailViewModel.tsnew file mode 100644index 000000000..a1c96aaea--- /dev/null+++ b/apps/web/src/utils/EmailViewModel.ts@@ -0,0 +1,135 @@+import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';+import { getEmailAttachmentBytes } from '@aliasvault/client/email/EmailAttachments';+import { SpamOkClient } from '@aliasvault/client/email/SpamOkClient';+import { decodeEmailSource } from '@aliasvault/client/rust/RustCore';++import type { WebApiService } from '@aliasvault/client/api/WebApiService';+import type { SqliteClient } from '@aliasvault/client/database/SqliteClient';+import type { Email } from '@aliasvault/models/webapi';++/**+ * An attachment of an email as shown in the email modal.+ */+export type EmailAttachmentViewModel = {+ filename: string;+ mimeType: string;+ size: number;+ index: number;+ partIndex: number | null;+ /** The attachment id on SpamOK, for SpamOK mail. */+ spamOkId: number | null;+};++/**+ * A decrypted, parsed email ready for display.+ */+export type EmailViewModel = {+ id: number;+ subject: string;+ fromDisplay: string;+ fromLocal: string;+ fromDomain: string;+ toLocal: string;+ toDomain: string;+ dateSystem: string;+ isSpamOk: boolean;+ htmlBody: string | null;+ textBody: string | null;+ sourceBytes: Uint8Array | null;+ sourceText: string | null;+ attachments: EmailAttachmentViewModel[];+ /** The email as the API returned it, for decrypting detached attachment bodies. */+ raw: Email | null;+};++/**+ * Whether the email has a source to show.+ */+export const hasSource = (email: EmailViewModel): boolean => email.sourceBytes !== null || (email.sourceText !== null && email.sourceText.trim().length > 0);++/** The web app's SpamOK API client. */+export const spamOk = new SpamOkClient('av-web', __APP_VERSION__);++/**+ * Load a SpamOK email.+ */+export async function loadSpamOkEmail(emailPrefix: string, emailId: number): Promise<EmailViewModel | null> {+ const email = await spamOk.getEmail(emailPrefix, emailId);+ if (!email) {+ return null;+ }+ return {+ id: email.id,+ subject: email.subject,+ fromDisplay: email.fromDisplay,+ fromLocal: email.fromLocal,+ fromDomain: email.fromDomain,+ toLocal: email.toLocal,+ toDomain: email.toDomain,+ dateSystem: email.dateSystem,+ isSpamOk: true,+ htmlBody: email.messageHtml,+ textBody: email.messagePlain,+ sourceBytes: null,+ sourceText: email.messageSource,+ attachments: email.attachments.map((a, index) => ({ filename: a.filename, mimeType: a.mimeType, size: a.filesize, index, partIndex: null, spamOkId: a.id })),+ raw: null,+ };+}++/**+ * Load and decrypt an AliasVault email.+ */+export async function loadAliasVaultEmail(webApi: WebApiService, sqliteClient: SqliteClient, emailId: number): Promise<EmailViewModel> {+ const email = await webApi.get<Email>(`Email/${emailId}`);+ const decrypted = await EncryptionUtility.decryptEmail(email, sqliteClient.encryptionKeys.getAll());+ return {+ id: decrypted.email.id,+ subject: decrypted.email.subject,+ fromDisplay: decrypted.email.fromDisplay,+ fromLocal: decrypted.email.fromLocal,+ fromDomain: decrypted.email.fromDomain,+ toLocal: decrypted.email.toLocal,+ toDomain: decrypted.email.toDomain,+ dateSystem: decrypted.email.dateSystem,+ isSpamOk: false,+ htmlBody: decrypted.htmlBody,+ textBody: decrypted.textBody,+ sourceBytes: decrypted.sourceBytes,+ sourceText: null,+ attachments: decrypted.attachments.map((a, index) => ({ filename: a.filename, mimeType: a.mimeType, size: a.size, index, partIndex: a.detached ? a.partIndex : null, spamOkId: null })),+ raw: email,+ };+}++/**+ * The raw source of an email as text, decoded on first use.+ */+export async function getSourceText(email: EmailViewModel): Promise<string> {+ if (email.sourceText !== null) {+ return email.sourceText;+ }+ if (email.sourceBytes === null) {+ return '';+ }+ try {+ email.sourceText = new TextDecoder().decode(await decodeEmailSource(email.sourceBytes));+ } catch (error) {+ console.warn(`Could not decode the source of email ${email.id}.`, error);+ return '';+ }+ return email.sourceText;+}++/**+ * The bytes of an attachment, fetched from SpamOK or extracted from the decrypted source.+ */+export async function getAttachmentBytes(webApi: WebApiService, sqliteClient: SqliteClient, email: EmailViewModel, attachment: EmailAttachmentViewModel): Promise<Uint8Array | null> {+ if (email.isSpamOk) {+ return attachment.spamOkId === null ? null : spamOk.getAttachment(email.id, attachment.spamOkId);+ }+ if (email.sourceBytes === null || email.raw === null) {+ return null;+ }+ return getEmailAttachmentBytes(webApi, email.raw, sqliteClient.encryptionKeys.getAll(), email.sourceBytes, attachment.index, attachment.partIndex);+}diff --git a/apps/web/src/utils/IdentityGenerator.ts b/apps/web/src/utils/IdentityGenerator.tsnew file mode 100644index 000000000..64312305b--- /dev/null+++ b/apps/web/src/utils/IdentityGenerator.ts@@ -0,0 +1,152 @@+/**+ * Identity generator.+ */++import * as RustCore from '@aliasvault/client/rust/RustCore';+import { FieldKey } from '@aliasvault/models/vault';++import { getFieldValue, type ItemEdit } from '@/models/ItemEdit';+import { vaultStore } from '@/vault/VaultStore';++import type { WebApiService } from '@aliasvault/client/api/WebApiService';+import type SqliteClient from '@aliasvault/client/database/SqliteClient';++/** Maximum number of identities generated while looking for an email address that is not taken yet. */+const MAX_EMAIL_ATTEMPTS = 5;++/**+ * A generated alias identity with its login credentials.+ */+export type GeneratedAliasData = {+ email: string;+ firstName: string;+ lastName: string;+ gender: string;+ birthdate: string;+ username: string;+ password: string;+};++/**+ * The email domain for generated aliases that is used by default.+ * @param client - the open vault+ */+export async function resolveDefaultEmailDomain(client: SqliteClient): Promise<string> {+ const metadata = await vaultStore.getVaultMetadata();+ const privateEmailDomains = metadata?.privateEmailDomains ?? [];+ const publicEmailDomains = metadata?.publicEmailDomains ?? [];+ const hiddenPrivateEmailDomains = metadata?.hiddenPrivateEmailDomains ?? [];++ /**+ * Whether a domain can receive mail and is not hidden.+ */+ const isValidDomain = (domain: string): boolean => Boolean(domain) && domain !== 'DISABLED.TLD' && !hiddenPrivateEmailDomains.includes(domain) && (privateEmailDomains.includes(domain) || publicEmailDomains.includes(domain));++ const configuredDomain = client.settings.getDefaultEmailDomain();+ if (isValidDomain(configuredDomain)) {+ return configuredDomain;+ }++ return privateEmailDomains.find(isValidDomain) ?? publicEmailDomains.find(isValidDomain) ?? '';+}++/**+ * Prefix an email address with the default domain, when there is one.+ */+async function withDefaultDomain(client: SqliteClient, prefix: string): Promise<string> {+ const domain = await resolveDefaultEmailDomain(client);+ return domain.length > 0 ? `${prefix}@${domain}` : prefix;+}++/**+ * A random identity and password.+ * @param client - the open vault+ */+async function generateAlias(client: SqliteClient): Promise<GeneratedAliasData> {+ const identity = await RustCore.generateIdentity({+ language: await client.settings.getEffectiveIdentityLanguage(),+ gender: client.settings.getDefaultIdentityGender(),+ ageRange: client.settings.getDefaultIdentityAgeRange(),+ });+ const password = await RustCore.generatePassword(client.settings.getPasswordSettings());++ return {+ email: await withDefaultDomain(client, identity.emailPrefix),+ firstName: identity.firstName,+ lastName: identity.lastName,+ gender: identity.gender,+ birthdate: identity.birthDate,+ username: identity.nickName,+ password,+ };+}++/**+ * Whether the server already routes an email address to another account.+ */+async function isEmailTaken(webApi: WebApiService, email: string): Promise<boolean> {+ try {+ const result = await webApi.post<null, { isTaken: boolean }>(`Identity/CheckEmail/${encodeURIComponent(email)}`, null);+ return result.isTaken;+ } catch {+ return false;+ }+}++/**+ * Generate a random identity.+ * @param client - the open vault+ * @param webApi - the API to check the email address with+ */+export async function generateIdentity(client: SqliteClient, webApi: WebApiService): Promise<GeneratedAliasData | null> {+ try {+ let generated = await generateAlias(client);+ for (let attempt = 1; attempt < MAX_EMAIL_ATTEMPTS; attempt++) {+ if (!generated.email.includes('@') || !await isEmailTaken(webApi, generated.email)) {+ break;+ }+ generated = await generateAlias(client);+ }+ return generated;+ } catch (error) {+ console.error('Error generating random alias:', error);+ return null;+ }+}++/**+ * A username from the alias identity on the form, or from a random identity when the form has none.+ * @param client - the open vault+ * @param edit - the item form+ */+export async function generateUsername(client: SqliteClient, edit: ItemEdit): Promise<string> {+ let firstName = getFieldValue(edit, FieldKey.AliasFirstName);+ let lastName = getFieldValue(edit, FieldKey.AliasLastName);+ let birthDate = getFieldValue(edit, FieldKey.AliasBirthdate);+ if (firstName.trim().length === 0 && lastName.trim().length === 0 && birthDate.trim().length === 0) {+ ({ firstName, lastName, birthdate: birthDate } = await generateAlias(client));+ }+ return RustCore.generateIdentityUsername({ firstName, lastName, birthDate });+}++/**+ * An email address on the default domain, based on the alias identity when the form has one.+ * @param client - the open vault+ * @param edit - the item form+ */+export async function generateAliasEmail(client: SqliteClient, edit: ItemEdit): Promise<string> {+ const firstName = getFieldValue(edit, FieldKey.AliasFirstName);+ const lastName = getFieldValue(edit, FieldKey.AliasLastName);+ const prefix = firstName.trim().length === 0 && lastName.trim().length === 0+ ? await RustCore.generateRandomEmailPrefix()+ : await RustCore.generateIdentityEmailPrefix({ firstName, lastName, birthDate: getFieldValue(edit, FieldKey.AliasBirthdate) });+ return withDefaultDomain(client, prefix);+}++/**+ * A random email address on the default domain.+ * @param client - the open vault+ */+export async function generateRandomEmail(client: SqliteClient): Promise<string> {+ return withDefaultDomain(client, await RustCore.generateRandomEmailPrefix());+}diff --git a/apps/web/src/utils/LocalPreferences.ts b/apps/web/src/utils/LocalPreferences.tsnew file mode 100644index 000000000..55922b504--- /dev/null+++ b/apps/web/src/utils/LocalPreferences.ts@@ -0,0 +1,65 @@+/**+ * Local storage wrapper.+ */++/**+ * Read a string preference.+ * @param key - the localStorage key+ */+export function getLocalPreference(key: string): string | null {+ try {+ return localStorage.getItem(key);+ } catch {+ return null;+ }+}++/**+ * Write a string preference.+ * @param key - the localStorage key+ * @param value - the value+ */+export function setLocalPreference(key: string, value: string): void {+ try {+ localStorage.setItem(key, value);+ } catch {+ // Storage may be unavailable (private mode); the preference then simply does not persist.+ }+}++/**+ * Remove a preference.+ * @param key - the localStorage key+ */+export function removeLocalPreference(key: string): void {+ try {+ localStorage.removeItem(key);+ } catch {+ // See setLocalPreference.+ }+}++/**+ * Read a JSON preference.+ * @param key - the localStorage key+ */+export function getLocalPreferenceJson<T>(key: string): T | null {+ const raw = getLocalPreference(key);+ if (raw === null) {+ return null;+ }+ try {+ return JSON.parse(raw) as T;+ } catch {+ return null;+ }+}++/**+ * Write a JSON preference.+ * @param key - the localStorage key+ * @param value - the value+ */+export function setLocalPreferenceJson(key: string, value: unknown): void {+ setLocalPreference(key, JSON.stringify(value));+}diff --git a/apps/web/src/utils/StorageKeys.ts b/apps/web/src/utils/StorageKeys.tsnew file mode 100644index 000000000..0db7494ef--- /dev/null+++ b/apps/web/src/utils/StorageKeys.ts@@ -0,0 +1,44 @@+/**+ * All platform storage keys used by the web app: the client core's keys plus the web app's own.+ */++import {+ AUTH_STORAGE_KEYS as CORE_AUTH_STORAGE_KEYS,+ StorageKeys as CoreStorageKeys,+ VAULT_LOCK_STORAGE_KEYS as CORE_VAULT_LOCK_STORAGE_KEYS,+ type StorageKey,+ vaultDataStorageKeys as coreVaultDataStorageKeys,+} from '@aliasvault/client/constants/StorageKeys';++export { dirtyScopeStorageKey, type StorageKey } from '@aliasvault/client/constants/StorageKeys';++export const StorageKeys = {+ ...CoreStorageKeys,+} as const satisfies Record<string, StorageKey>;++/** Keys that hold auth tokens, ephemeral error state and account-scoped server state. Cleared on any logout. */+export const AUTH_STORAGE_KEYS: readonly StorageKey[] = CORE_AUTH_STORAGE_KEYS;++/** Keys that must not survive a vault lock: the decrypted keys. */+export const VAULT_LOCK_STORAGE_KEYS: readonly StorageKey[] = [...CORE_VAULT_LOCK_STORAGE_KEYS];++/** Session keys cleared on logout. */+export const SESSION_STORAGE_KEYS: readonly StorageKey[] = [...VAULT_LOCK_STORAGE_KEYS, StorageKeys.VAULT_SYNC_HOLD];++/** Every key holding vault data or state derived from it. Cleared on logout. */+export const vaultDataStorageKeys = (): StorageKey[] => [...coreVaultDataStorageKeys()];++/**+ * Browser localStorage keys for UI preferences. The names are the ones the previous web client used, so an existing+ * preference carries over to this app.+ */+export const LocalPreferenceKeys = {+ /** 'dark' | 'light'; unset means follow the system preference. */+ COLOR_THEME: 'color-theme',+ /** The UI language chosen before login. */+ APP_LANGUAGE: 'AppLanguage',+ /** Where to go after the vault is loaded. */+ RETURN_URL: 'returnUrl',+ /** Whether the items page groups items by folder. */+ ITEMS_SHOW_FOLDERS: 'items-show-folders',+} as const;diff --git a/apps/web/src/utils/WebAuthnService.ts b/apps/web/src/utils/WebAuthnService.tsnew file mode 100644index 000000000..8c3b06aca--- /dev/null+++ b/apps/web/src/utils/WebAuthnService.ts@@ -0,0 +1,196 @@+import { AppErrorCode, extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';+import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';+import { getPlatform } from '@aliasvault/client/platform';+import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';++import { getLocalPreference, removeLocalPreference, setLocalPreference } from '@/utils/LocalPreferences';+import { StorageKeys } from '@/utils/StorageKeys';++/** Local storage keys for the WebAuthn quick unlock. */+const KEYS = {+ enabled: 'webAuthnEnabled',+ credentialId: 'webAuthnCredentialId',+ salt: 'webAuthnSalt',+ encryptedKeys: 'webAuthnEncryptedEncryptionKey',+} as const;++/**+ * What the passkey-derived key encrypts: the session unlock key (the KEK), never the keys the chain opens.+ */+type WebAuthnSessionKeys = {+ UnlockKey: string;+};++/**+ * Thrown when the browser or authenticator has no PRF support.+ */+export class WebAuthnNotSupportedError extends Error {+ /**+ * Create the error.+ */+ public constructor() {+ super('WebAuthn PRF extension is not supported');+ this.name = 'WebAuthnNotSupportedError';+ }+}++/**+ * The PRF output of a credential assertion, or null when the authenticator returned none.+ */+const prfResult = (credential: Credential | null): ArrayBuffer | null => {+ const results = (credential as PublicKeyCredential | null)?.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer } } } | undefined;+ return results?.prf?.results?.first ?? null;+};++/**+ * Whether the PRF extension is present on a credential response.+ */+const hasPrf = (credential: Credential | null): boolean => {+ const results = (credential as PublicKeyCredential | null)?.getClientExtensionResults() as { prf?: unknown } | undefined;+ return results?.prf !== undefined;+};++/**+ * Ask the authenticator for the key derived from a stored credential and salt.+ */+async function getCredentialDerivedKey(credentialId: string, salt: string): Promise<string> {+ const credential = await navigator.credentials.get({+ publicKey: {+ challenge: crypto.getRandomValues(new Uint8Array(32)),+ rpId: window.location.hostname,+ userVerification: 'discouraged',+ allowCredentials: [{ id: base64ToBytes(credentialId), type: 'public-key' }],+ extensions: { prf: { eval: { first: base64ToBytes(salt) } } } as AuthenticationExtensionsClientInputs,+ },+ });+ if (!hasPrf(credential)) {+ throw new WebAuthnNotSupportedError();+ }+ const derived = prfResult(credential);+ if (!derived) {+ throw new Error('PRF_DERIVATION_FAILED');+ }+ return bytesToBase64(new Uint8Array(derived));+}++/**+ * Create a passkey and derive a key from it.+ */+async function createCredentialDerivedKey(username: string): Promise<{ credentialId: string; salt: string; derivedKey: string }> {+ const salt = crypto.getRandomValues(new Uint8Array(32));+ const created = await navigator.credentials.create({+ publicKey: {+ challenge: crypto.getRandomValues(new Uint8Array(32)),+ rp: { name: 'AliasVault Web Unlock', id: window.location.hostname },+ user: { id: crypto.getRandomValues(new Uint8Array(32)), name: username, displayName: username },+ pubKeyCredParams: [-7, -257, -37, -8, -35, -36, -259, -258, -38, -39].map(alg => ({ alg, type: 'public-key' as const })),+ authenticatorSelection: { userVerification: 'discouraged', residentKey: 'discouraged', requireResidentKey: false },+ extensions: { prf: { eval: { first: salt } } } as AuthenticationExtensionsClientInputs,+ },+ }) as PublicKeyCredential | null;+ if (!created) {+ throw new Error('WEBAUTHN_CREATE_ERROR');+ }+ if (!hasPrf(created)) {+ throw new WebAuthnNotSupportedError();+ }++ let derived = prfResult(created);+ if (!derived) {+ // Some authenticators (YubiKey among them) only return the PRF output on an assertion, not on creation.+ alert('Your authenticator has been successfully registered. Please use your authenticator again to complete the process.');+ const asserted = await navigator.credentials.get({+ publicKey: {+ challenge: crypto.getRandomValues(new Uint8Array(32)),+ rpId: window.location.hostname,+ userVerification: 'discouraged',+ allowCredentials: [{ id: created.rawId, type: 'public-key' }],+ extensions: { prf: { eval: { first: salt } } } as AuthenticationExtensionsClientInputs,+ },+ });+ derived = prfResult(asserted);+ }+ if (!derived) {+ throw new Error('PRF_DERIVATION_FAILED');+ }+ return { credentialId: bytesToBase64(new Uint8Array(created.rawId)), salt: bytesToBase64(salt), derivedKey: bytesToBase64(new Uint8Array(derived)) };+}++/**+ * Passkey quick unlock: the session unlock key encrypted with a key the passkey derives, kept in localStorage.+ */+export const WebAuthnService = {+ /**+ * Whether passkey unlock is set up on this browser.+ */+ isEnabled(): boolean {+ return getLocalPreference(KEYS.enabled) === 'true';+ },++ /**+ * Create a passkey and encrypt the current session unlock key with it.+ */+ async enable(username: string): Promise<void> {+ const unlockKey = await VaultKeyService.getSessionUnlockKey();+ if (!unlockKey) {+ throw new Error('Vault is locked');+ }+ const credential = await createCredentialDerivedKey(username);+ const payload: WebAuthnSessionKeys = { UnlockKey: unlockKey };+ const encrypted = await EncryptionUtility.symmetricEncrypt(JSON.stringify(payload), credential.derivedKey);+ setLocalPreference(KEYS.credentialId, credential.credentialId);+ setLocalPreference(KEYS.salt, credential.salt);+ setLocalPreference(KEYS.encryptedKeys, encrypted);+ setLocalPreference(KEYS.enabled, 'true');+ },++ /**+ * Forget the passkey and the encrypted unlock key.+ */+ disable(): void {+ setLocalPreference(KEYS.enabled, 'false');+ removeLocalPreference(KEYS.credentialId);+ removeLocalPreference(KEYS.salt);+ removeLocalPreference(KEYS.encryptedKeys);+ },++ /**+ * Decrypt the unlock key with the passkey, check it opens the key chain and put it in the session.+ */+ async unlock(): Promise<void> {+ const credentialId = getLocalPreference(KEYS.credentialId);+ const salt = getLocalPreference(KEYS.salt);+ const encrypted = getLocalPreference(KEYS.encryptedKeys);+ if (!credentialId || !salt || !encrypted) {+ throw new Error('WebAuthn encrypted encryption key is not set or WebAuthn credential ID is not set.');+ }+ const derivedKey = await getCredentialDerivedKey(credentialId, salt);+ const payload = await EncryptionUtility.symmetricDecrypt(encrypted, derivedKey);+ let keys: WebAuthnSessionKeys | null = null;+ try {+ keys = JSON.parse(payload) as WebAuthnSessionKeys;+ } catch {+ keys = null;+ }++ // Check for legacy storage (pre-0.31.0).+ // TODO: this can be removed in a future release once 0.31.0 has been released.+ const isLegacyStore = typeof keys?.UnlockKey !== 'string';+ const unlockKey = keys && !isLegacyStore ? keys.UnlockKey : payload;+ try {+ await VaultKeyService.verifyUnlockKey(unlockKey);+ } catch (error) {+ // A key the chain rejects (password changed since) is discarded, the password unlock still works.+ if (error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {+ WebAuthnService.disable();+ }+ throw error;+ }+ if (isLegacyStore) {+ const upgraded: WebAuthnSessionKeys = { UnlockKey: unlockKey };+ setLocalPreference(KEYS.encryptedKeys, await EncryptionUtility.symmetricEncrypt(JSON.stringify(upgraded), derivedKey));+ }+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, unlockKey);+ },+};