Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Centralize favicon render logic and make it format aware (#745)
Leendert de Borst915e12d541ac
diff --git a/browser-extension/src/entrypoints/contentScript/Popup.ts b/browser-extension/src/entrypoints/contentScript/Popup.tsindex 879d2f3d0..46373597a 100644--- a/browser-extension/src/entrypoints/contentScript/Popup.ts+++ b/browser-extension/src/entrypoints/contentScript/Popup.ts@@ -8,17 +8,13 @@ import { sendMessage } from "webext-bridge/content-script";import { CredentialsResponse } from '@/utils/types/messaging/CredentialsResponse';import { CombinedStopWords } from '../../utils/formDetector/FieldPatterns';import { PasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';+import SqliteClient from '../../utils/SqliteClient';/*** WeakMap to store event listeners for popup containers*/let popupListeners = new WeakMap<HTMLElement, EventListener>();-/**- * Placeholder base64 image for credentials without a logo.- */-const placeholderBase64 = 'UklGRjoEAABXRUJQVlA4IC4EAAAwFwCdASqAAIAAPpFCm0olo6Ihp5IraLASCWUA0eb/0s56RrLtCnYfLPiBshdXWMx8j1Ez65f169iA4xUDBTEV6ylMQeCIj2b7RngGi7gKZ9WjKdSoy9R8JcgOmjCMlDmLG20KhNo/i/Dc/Ah5GAvGfm8kfniV3AkR6fxN6eKwjDc6xrDgSfS48G5uGV6WzQt24YAVlLSK9BMwndzfHnePK1KFchFrL7O3ulB8cGNCeomu4o+l0SrS/JKblJ4WTzj0DAD++lCUEouSfgRKdiV2TiYCD+H+l3tANKSPQFPQuzi7rbvxqGeRmXB9kDwURaoSTTpYjA9REMUi9uA6aV7PWtBNXgUzMLowYMZeos6Xvyhb34GmufswMHA5ZyYpxzjTphOak4ZjNOiz8aScO5ygiTx99SqwX/uL+HSeVOSraHw8IymrMwm+jLxqN8BS8dGcItLlm/ioulqH2j4V8glDgSut+ExkxiD7m8TGPrrjCQNJbRDzpOFsyCyfBZupvp8QjGKW2KGziSZeIWes4aTB9tRmeEBhnUrmTDZQuXcc67Fg82KHrSfaeeOEq6jjuUjQ8wUnzM4Zz3dhrwSyslVz/WvnKqYkr4V/TTXPFF5EjF4rM1bHZ8bK63EfTnK41+n3n4gEFoYP4mXkNH0hntnYcdTqiE7Gn+q0BpRRxnkpBSZlA6Wa70jpW0FGqkw5e591A5/H+OV+60WAo+4Mi+NlsKrvLZ9EiVaPnoEFZlJQx1fA777AJ2MjXJ4KSsrWDWJi1lE8yPs8V6XvcC0chDTYt8456sKXAagCZyY+fzQriFMaddXyKQdG8qBqcdYjAsiIcjzaRFBBoOK9sU+sFY7N6B6+xtrlu3c37rQKkI3O2EoiJOris54EjJ5OFuumA0M6riNUuBf/MEPFBVx1JRcUEs+upEBsCnwYski7FT3TTqHrx7v5AjgFN97xhPTkmVpu6sxRnWBi1fxIRp8eWZeFM6mUcGgVk1WeVb1yhdV9hoMo2TsNEPE0tHo/wvuSJSzbZo7wibeXM9v/rRfKcx7X93rfiXVnyQ9f/5CaAQ4lxedPp/6uzLtOS4FyL0bCNeZ6L5w+AiuyWCTDFIYaUzhwfG+/YTQpWyeZCdQIKzhV+3GeXI2cxoP0ER/DlOKymf1gm+zRU3sqf1lBVQ0y+mK/Awl9bS3uaaQmI0FUyUwHUKP7PKuXnO+LcwDv4OfPT6hph8smc1EtMe5ib/apar/qZ9dyaEaElALJ1KKxnHziuvVl8atk1fINSQh7OtXDyqbPw9o/nGIpTnv5iFmwmWJLis2oyEgPkJqyx0vYI8rjkVEzKc8eQavAJBYSpjMwM193Swt+yJyjvaGYWPnqExxKiNarpB2WSO7soCAZXhS1uEYHryrK47BH6W1dRiruqT0xpLih3MXiwU3VDwAAAA==';-/*** Create basic popup with default style.*/@@ -539,22 +535,7 @@ function createCredentialList(credentials: Credential[], input: HTMLInputElementconst imgElement = document.createElement('img');imgElement.className = 'av-credential-logo';-- // Handle base64 image data- if (cred.Logo) {- try {- const logoBytes = toUint8Array(cred.Logo);- const base64Logo = base64Encode(logoBytes);- // Detect image type from first few bytes- const mimeType = detectMimeType(logoBytes);- imgElement.src = `data:${mimeType};base64,${base64Logo}`;- } catch (error) {- console.error('Error setting logo:', error);- imgElement.src = `data:image/x-icon;base64,${placeholderBase64}`;- }- } else {- imgElement.src = `data:image/x-icon;base64,${placeholderBase64}`;- }+ imgElement.src = SqliteClient.imgSrcFromBytes(cred.Logo);credentialInfo.appendChild(imgElement);const credTextContainer = document.createElement('div');@@ -791,40 +772,6 @@ export function openAutofillPopup(input: HTMLInputElement, container: HTMLElemen})();}-/**- * Convert various binary data formats to Uint8Array- */-function toUint8Array(buffer: Uint8Array | number[] | {[key: number]: number}): Uint8Array {- if (buffer instanceof Uint8Array) {- return buffer;- }-- if (Array.isArray(buffer)) {- return new Uint8Array(buffer);- }-- const length = Object.keys(buffer).length;- const arr = new Uint8Array(length);- for (let i = 0; i < length; i++) {- arr[i] = buffer[i];- }-- return arr;-}--/**- * Base64 encode binary data.- */-function base64Encode(buffer: Uint8Array | number[] | {[key: number]: number}): string | null {- try {- const arr = Array.from(toUint8Array(buffer));- return btoa(arr.reduce((data, byte) => data + String.fromCharCode(byte), ''));- } catch (error) {- console.error('Error encoding to base64:', error);- return null;- }-}-/*** Get favicon bytes from page and resize if necessary.*/@@ -928,45 +875,6 @@ async function resizeImage(imageData: Uint8Array, contentType: string, targetWid});}-/**- * Detect MIME type from file signature (magic numbers)- */-function detectMimeType(bytes: Uint8Array): string {- /**- * Check if the file is an SVG file.- */- const isSvg = () : boolean => {- const header = new TextDecoder().decode(bytes.slice(0, 5)).toLowerCase();- return header.includes('<?xml') || header.includes('<svg');- };-- /**- * Check if the file is an ICO file.- */- const isIco = () : boolean => {- return bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00;- };-- /**- * Check if the file is an PNG file.- */- const isPng = () : boolean => {- return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47;- };-- if (isSvg()) {- return 'image/svg+xml';- }- if (isIco()) {- return 'image/x-icon';- }- if (isPng()) {- return 'image/png';- }-- return 'image/x-icon';-}-/*** Dismiss vault locked popup for 4 hours if user is logged in, or for 3 days if user is not logged in.*/diff --git a/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx b/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsxindex 4c33b2bb6..a40392810 100644--- a/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx+++ b/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx@@ -1,12 +1,213 @@-import React, { useState, useEffect } from 'react';+import React, { useState, useEffect, useCallback } from 'react';import { useNavigate, useParams } from 'react-router-dom';import { useDb } from '../context/DbContext';import { Credential } from '../../../utils/types/Credential';-import { Buffer } from 'buffer';import { FormInputCopyToClipboard } from '../components/FormInputCopyToClipboard';import { EmailPreview } from '../components/EmailPreview';import { TotpViewer } from '../components/TotpViewer';import { useLoading } from '../context/LoadingContext';+import SqliteClient from '../../../utils/SqliteClient';++type BlockProps = {+ children: React.ReactNode;+ className?: string;+}++/**+ * Render a block.+ */+const Block: React.FC<BlockProps> = ({ children, className = '' }) => (+ <div className={`space-y-4 ${className}`}>+ {children}+ </div>+);++/**+ * Render the header block.+ */+const HeaderBlock: React.FC<{ credential: Credential; onOpenNewPopup: () => void }> = ({ credential, onOpenNewPopup }) => (+ <Block className="mb-6">+ <div className="flex items-center justify-between">+ <div className="flex items-center">+ <img+ src={SqliteClient.imgSrcFromBytes(credential.Logo)}+ alt={credential.ServiceName}+ className="w-12 h-12 rounded-lg mr-4"+ />+ <div>+ <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{credential.ServiceName}</h1>+ {credential.ServiceUrl && (+ <a+ href={credential.ServiceUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"+ >+ {credential.ServiceUrl}+ </a>+ )}+ </div>+ </div>+ <button+ onClick={onOpenNewPopup}+ className="text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"+ title="Open in new window"+ >+ <svg+ className="w-5 h-5"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"+ />+ </svg>+ </button>+ </div>+ </Block>+);++/**+ * Render the email block.+ */+const EmailBlock: React.FC<{ email: string; isSupported: boolean }> = ({ email, isSupported }) => (+ <Block>+ {isSupported && <EmailPreview email={email} />}+ </Block>+);++/**+ * Render the TOTP viewer block.+ */+const TotpBlock: React.FC<{ credentialId: string }> = ({ credentialId }) => (+ <Block>+ <TotpViewer credentialId={credentialId} />+ </Block>+);++/**+ * Render the login credentials block.+ */+const LoginCredentialsBlock: React.FC<{ credential: Credential }> = ({ credential }) => {+ const email = credential.Email?.trim();+ const username = credential.Username?.trim();+ const password = credential.Password?.trim();++ if (!email && !username && !password) {+ return null;+ }++ return (+ <Block>+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Login credentials</h2>+ {email && (+ <FormInputCopyToClipboard+ id="email"+ label="Email"+ value={email}+ />+ )}+ {username && (+ <FormInputCopyToClipboard+ id="username"+ label="Username"+ value={username}+ />+ )}+ {password && (+ <FormInputCopyToClipboard+ id="password"+ label="Password"+ value={password}+ type="password"+ />+ )}+ </Block>+ );+};++/**+ * Render the alias block.+ */+const AliasBlock: React.FC<{ credential: Credential; isValidDate: (date: string | null | undefined) => boolean }> = ({+ credential,+ isValidDate+}) => {+ const hasFirstName = Boolean(credential.Alias?.FirstName?.trim());+ const hasLastName = Boolean(credential.Alias?.LastName?.trim());+ const hasNickName = Boolean(credential.Alias?.NickName?.trim());+ const hasBirthDate = isValidDate(credential.Alias?.BirthDate);++ if (!hasFirstName && !hasLastName && !hasNickName && !hasBirthDate) {+ return null;+ }++ return (+ <Block>+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Alias</h2>+ {(hasFirstName || hasLastName) && (+ <FormInputCopyToClipboard+ id="fullName"+ label="Full Name"+ value={[credential.Alias?.FirstName, credential.Alias?.LastName].filter(Boolean).join(' ')}+ />+ )}+ {hasFirstName && (+ <FormInputCopyToClipboard+ id="firstName"+ label="First Name"+ value={credential.Alias?.FirstName}+ />+ )}+ {hasLastName && (+ <FormInputCopyToClipboard+ id="lastName"+ label="Last Name"+ value={credential.Alias?.LastName}+ />+ )}+ {hasBirthDate && (+ <FormInputCopyToClipboard+ id="birthDate"+ label="Birth Date"+ value={new Date(credential.Alias?.BirthDate).toISOString().split('T')[0]}+ />+ )}+ {hasNickName && (+ <FormInputCopyToClipboard+ id="nickName"+ label="Nickname"+ value={credential.Alias?.NickName ?? ''}+ />+ )}+ </Block>+ );+};++/**+ * Render the notes block.+ */+const NotesBlock: React.FC<{ notes: string | undefined }> = ({ notes }) => {+ if (!notes) {+ return null;+ }++ return (+ <Block>+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Notes</h2>+ <div className="p-4 bg-gray-50 rounded-lg dark:bg-gray-700">+ <p className="text-gray-900 dark:text-gray-100 whitespace-pre-wrap">+ {notes}+ </p>+ </div>+ </Block>+ );+};/*** Credential details page.@@ -17,12 +218,11 @@ const CredentialDetails: React.FC = () => {const dbContext = useDb();const [credential, setCredential] = useState<Credential | null>(null);const { setIsInitialLoading } = useLoading();- const [hasAlias, setHasAlias] = useState<boolean>(false);/*** Check if the current page is an expanded popup.*/- const isPopup = () : boolean => {+ const isPopup = (): boolean => {const urlParams = new URLSearchParams(window.location.search);return urlParams.get('expanded') === 'true';};@@ -30,7 +230,7 @@ const CredentialDetails: React.FC = () => {/*** Open the credential details in a new expanded popup.*/- const openInNewPopup = () : void => {+ const openInNewPopup = (): void => {const width = 380;const height = 600;const left = window.screen.width / 2 - width / 2;@@ -42,73 +242,39 @@ const CredentialDetails: React.FC = () => {`width=${width},height=${height},left=${left},top=${top},popup=true`);- // Close the current tabwindow.close();};/**- * Checks if the email domain is supported for email preview.- *- * @param email The email address to check- * @returns True if the domain is supported, false otherwise+ * Check if the email domain is supported.*/const isEmailDomainSupported = (email: string): boolean => {- // Extract domain from emailconst domain = email.split('@')[1]?.toLowerCase();-if (!domain) {return false;}- // Check if domain is in public or private domainsconst publicDomains = dbContext.publicEmailDomains ?? [];const privateDomains = dbContext.privateEmailDomains ?? [];- // Check if the domain ends with any of the supported domainsreturn [...publicDomains, ...privateDomains].some(supportedDomain =>domain === supportedDomain || domain.endsWith(`.${supportedDomain}`));};/**- * Check if a date is valid and not min value (1900-01-01)+ * Check if a date is valid.*/- const isValidDate = (date: string | null | undefined): boolean => {- /*- * TODO: after date field in alias data model is made optional and- * all min values have been replaced with null, we can remove this check.- */+ const isValidDate = useCallback((date: string | null | undefined): boolean => {if (!date || date === '0001-01-01 00:00:00') {return false;}-const dateObj = new Date(date);return !isNaN(dateObj.getTime());- };-- /**- * Check if alias has any non-empty fields- */- const checkHasAlias = (credential: Credential): boolean => {- // Return false if credential has no alias- if (!credential.Alias) {- return false;- }-- // Check if any of the alias fields have content- const hasFirstName = Boolean(credential.Alias.FirstName?.trim());- const hasLastName = Boolean(credential.Alias.LastName?.trim());- const hasNickName = Boolean(credential.Alias.NickName?.trim());- const hasBirthDate = isValidDate(credential.Alias.BirthDate);-- // Return true if any field has content- return hasFirstName || hasLastName || hasNickName || hasBirthDate;- };+ }, []);useEffect(() => {- // For popup windows, ensure we have proper history state for navigationif (isPopup()) {- // Clear existing history and create fresh entrieswindow.history.replaceState({}, '', `popup.html#/credentials`);window.history.pushState({}, '', `popup.html#/credentials/${id}`);}@@ -121,7 +287,6 @@ const CredentialDetails: React.FC = () => {const result = dbContext.sqliteClient.getCredentialById(id);if (result) {setCredential(result);- setHasAlias(checkHasAlias(result));setIsInitialLoading(false);} else {console.error('Credential not found');@@ -130,146 +295,33 @@ const CredentialDetails: React.FC = () => {} catch (err) {console.error('Error loading credential:', err);}- }, [dbContext.sqliteClient, id, navigate, setIsInitialLoading, checkHasAlias]);+ }, [dbContext.sqliteClient, id, navigate, setIsInitialLoading]);if (!credential) {return <div>Loading...</div>;}return (- <div className="">- <div className="space-y-4 mb-4">- <div className="flex items-center justify-between mb-6">- <div className="flex items-center">- <img- src={credential.Logo ? `data:image/x-icon;base64,${Buffer.from(credential.Logo).toString('base64')}` : '/assets/images/service-placeholder.webp'}- alt={credential.ServiceName}- className="w-12 h-12 rounded-lg mr-4"- />- <div>- <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{credential.ServiceName}</h1>- {credential.ServiceUrl && (- <a- href={credential.ServiceUrl}- target="_blank"- rel="noopener noreferrer"- className="text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"- >- {credential.ServiceUrl}- </a>- )}- </div>- </div>- <button- onClick={openInNewPopup}- className="text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"- title="Open in new window"- >- <svg- className="w-5 h-5"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- xmlns="http://www.w3.org/2000/svg"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"- />- </svg>- </button>- </div>-- {credential.Email && (- <>- {isEmailDomainSupported(credential.Email) && (- <EmailPreview- email={credential.Email}- />- )}- </>- )}-- <TotpViewer credentialId={credential.Id} />- </div>-- <div className="grid gap-6">- <div className="space-y-4 lg:col-span-2 xl:col-span-1">- <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Login credentials</h2>- {credential.Email && (- <FormInputCopyToClipboard- id="email"- label="Email"- value={credential.Email}- />- )}- <FormInputCopyToClipboard- id="username"- label="Username"- value={credential.Username}- />- <FormInputCopyToClipboard- id="password"- label="Password"- value={credential.Password}- type="password"- />-- {hasAlias && (- <div className="space-y-4">- <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Alias</h2>- {(credential.Alias.FirstName || credential.Alias.LastName) && (- <FormInputCopyToClipboard- id="fullName"- label="Full Name"- value={[credential.Alias.FirstName, credential.Alias.LastName].filter(Boolean).join(' ')}- />- )}- {credential.Alias.FirstName && (- <FormInputCopyToClipboard- id="firstName"- label="First Name"- value={credential.Alias.FirstName}- />- )}- {credential.Alias.LastName && (- <FormInputCopyToClipboard- id="lastName"- label="Last Name"- value={credential.Alias.LastName}- />- )}- {isValidDate(credential.Alias.BirthDate) && (- <FormInputCopyToClipboard- id="birthDate"- label="Birth Date"- value={new Date(credential.Alias.BirthDate!).toISOString().split('T')[0]}- />- )}- {credential.Alias.NickName && (- <FormInputCopyToClipboard- id="nickName"- label="Nickname"- value={credential.Alias.NickName}- />- )}- </div>- )}- </div>-- {credential.Notes && (- <div className="space-y-4 lg:col-span-2 xl:col-span-1">- <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Notes</h2>- <div className="p-4 bg-gray-50 rounded-lg dark:bg-gray-700">- <p className="text-gray-900 dark:text-gray-100 whitespace-pre-wrap">- {credential.Notes}- </p>- </div>- </div>- )}- </div>+ <div className="space-y-6">+ <HeaderBlock credential={credential} onOpenNewPopup={openInNewPopup} />++ {credential.Email && (+ <EmailBlock+ email={credential.Email}+ isSupported={isEmailDomainSupported(credential.Email)}+ />+ )}++ <TotpBlock credentialId={credential.Id} />++ <LoginCredentialsBlock credential={credential} />++ <AliasBlock+ credential={credential}+ isValidDate={isValidDate}+ />++ <NotesBlock notes={credential.Notes} /></div>);};diff --git a/browser-extension/src/entrypoints/popup/pages/CredentialsList.tsx b/browser-extension/src/entrypoints/popup/pages/CredentialsList.tsxindex b49094d13..d01ac870c 100644--- a/browser-extension/src/entrypoints/popup/pages/CredentialsList.tsx+++ b/browser-extension/src/entrypoints/popup/pages/CredentialsList.tsx@@ -1,7 +1,6 @@import React, { useState, useEffect, useCallback } from 'react';import { useDb } from '../context/DbContext';import { Credential } from '../../../utils/types/Credential';-import { Buffer } from 'buffer';import { useNavigate } from 'react-router-dom';import { useLoading } from '../context/LoadingContext';import { useWebApi } from '../context/WebApiContext';@@ -10,7 +9,7 @@ import ReloadButton from '../components/ReloadButton';import LoadingSpinner from '../components/LoadingSpinner';import { useMinDurationLoading } from '../../../hooks/useMinDurationLoading';import { sendMessage } from 'webext-bridge/popup';-+import SqliteClient from '../../../utils/SqliteClient';/*** Credentials list page.*/@@ -163,7 +162,7 @@ const CredentialsList: React.FC = () => {className="w-full p-2 border dark:border-gray-600 rounded flex items-center bg-white dark:bg-gray-800 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"><img- src={cred.Logo ? `data:image/x-icon;base64,${Buffer.from(cred.Logo).toString('base64')}` : '/assets/images/service-placeholder.webp'}+ src={SqliteClient.imgSrcFromBytes(cred.Logo)}alt={cred.ServiceName}className="w-8 h-8 mr-2 flex-shrink-0"onError={(e) => {diff --git a/browser-extension/src/utils/SqliteClient.tsx b/browser-extension/src/utils/SqliteClient.tsxindex 0e86ef57d..366460a34 100644--- a/browser-extension/src/utils/SqliteClient.tsx+++ b/browser-extension/src/utils/SqliteClient.tsx@@ -4,6 +4,11 @@ import { EncryptionKey } from './types/EncryptionKey';import { TotpCode } from './types/TotpCode';import { PasswordSettings } from './types/PasswordSettings';+/**+ * Placeholder base64 image for credentials without a logo.+ */+const placeholderBase64 = 'UklGRjoEAABXRUJQVlA4IC4EAAAwFwCdASqAAIAAPpFCm0olo6Ihp5IraLASCWUA0eb/0s56RrLtCnYfLPiBshdXWMx8j1Ez65f169iA4xUDBTEV6ylMQeCIj2b7RngGi7gKZ9WjKdSoy9R8JcgOmjCMlDmLG20KhNo/i/Dc/Ah5GAvGfm8kfniV3AkR6fxN6eKwjDc6xrDgSfS48G5uGV6WzQt24YAVlLSK9BMwndzfHnePK1KFchFrL7O3ulB8cGNCeomu4o+l0SrS/JKblJ4WTzj0DAD++lCUEouSfgRKdiV2TiYCD+H+l3tANKSPQFPQuzi7rbvxqGeRmXB9kDwURaoSTTpYjA9REMUi9uA6aV7PWtBNXgUzMLowYMZeos6Xvyhb34GmufswMHA5ZyYpxzjTphOak4ZjNOiz8aScO5ygiTx99SqwX/uL+HSeVOSraHw8IymrMwm+jLxqN8BS8dGcItLlm/ioulqH2j4V8glDgSut+ExkxiD7m8TGPrrjCQNJbRDzpOFsyCyfBZupvp8QjGKW2KGziSZeIWes4aTB9tRmeEBhnUrmTDZQuXcc67Fg82KHrSfaeeOEq6jjuUjQ8wUnzM4Zz3dhrwSyslVz/WvnKqYkr4V/TTXPFF5EjF4rM1bHZ8bK63EfTnK41+n3n4gEFoYP4mXkNH0hntnYcdTqiE7Gn+q0BpRRxnkpBSZlA6Wa70jpW0FGqkw5e591A5/H+OV+60WAo+4Mi+NlsKrvLZ9EiVaPnoEFZlJQx1fA777AJ2MjXJ4KSsrWDWJi1lE8yPs8V6XvcC0chDTYt8456sKXAagCZyY+fzQriFMaddXyKQdG8qBqcdYjAsiIcjzaRFBBoOK9sU+sFY7N6B6+xtrlu3c37rQKkI3O2EoiJOris54EjJ5OFuumA0M6riNUuBf/MEPFBVx1JRcUEs+upEBsCnwYski7FT3TTqHrx7v5AjgFN97xhPTkmVpu6sxRnWBi1fxIRp8eWZeFM6mUcGgVk1WeVb1yhdV9hoMo2TsNEPE0tHo/wvuSJSzbZo7wibeXM9v/rRfKcx7X93rfiXVnyQ9f/5CaAQ4lxedPp/6uzLtOS4FyL0bCNeZ6L5w+AiuyWCTDFIYaUzhwfG+/YTQpWyeZCdQIKzhV+3GeXI2cxoP0ER/DlOKymf1gm+zRU3sqf1lBVQ0y+mK/Awl9bS3uaaQmI0FUyUwHUKP7PKuXnO+LcwDv4OfPT6hph8smc1EtMe5ib/apar/qZ9dyaEaElALJ1KKxnHziuvVl8atk1fINSQh7OtXDyqbPw9o/nGIpTnv5iFmwmWJLis2oyEgPkJqyx0vYI8rjkVEzKc8eQavAJBYSpjMwM193Swt+yJyjvaGYWPnqExxKiNarpB2WSO7soCAZXhS1uEYHryrK47BH6W1dRiruqT0xpLih3MXiwU3VDwAAAA==';+/*** Client for interacting with the SQLite database.*/@@ -488,6 +493,100 @@ class SqliteClient {}}+ /**+ * Convert binary data to a base64 encoded image source.+ */+ public static imgSrcFromBytes(bytes: Uint8Array<ArrayBufferLike> | number[] | undefined): string {+ // Handle base64 image data+ if (bytes) {+ try {+ const logoBytes = this.toUint8Array(bytes);+ const base64Logo = this.base64Encode(logoBytes);+ // Detect image type from first few bytes+ const mimeType = this.detectMimeType(logoBytes);+ return `data:${mimeType};base64,${base64Logo}`;+ } catch (error) {+ console.error('Error setting logo:', error);+ return `data:image/x-icon;base64,${placeholderBase64}`;+ }+ } else {+ return `data:image/x-icon;base64,${placeholderBase64}`;+ }+ }++ /**+ * Detect MIME type from file signature (magic numbers)+ */+ private static detectMimeType(bytes: Uint8Array): string {+ /**+ * Check if the file is an SVG file.+ */+ const isSvg = () : boolean => {+ const header = new TextDecoder().decode(bytes.slice(0, 5)).toLowerCase();+ return header.includes('<?xml') || header.includes('<svg');+ };++ /**+ * Check if the file is an ICO file.+ */+ const isIco = () : boolean => {+ return bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00;+ };++ /**+ * Check if the file is an PNG file.+ */+ const isPng = () : boolean => {+ return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47;+ };++ if (isSvg()) {+ return 'image/svg+xml';+ }+ if (isIco()) {+ return 'image/x-icon';+ }+ if (isPng()) {+ return 'image/png';+ }++ return 'image/x-icon';+ }++ /**+ * Convert various binary data formats to Uint8Array+ */+ private static toUint8Array(buffer: Uint8Array | number[] | {[key: number]: number}): Uint8Array {+ if (buffer instanceof Uint8Array) {+ return buffer;+ }++ if (Array.isArray(buffer)) {+ return new Uint8Array(buffer);+ }++ const length = Object.keys(buffer).length;+ const arr = new Uint8Array(length);+ for (let i = 0; i < length; i++) {+ arr[i] = buffer[i];+ }++ return arr;+ }++ /**+ * Base64 encode binary data.+ */+ private static base64Encode(buffer: Uint8Array | number[] | {[key: number]: number}): string | null {+ try {+ const arr = Array.from(this.toUint8Array(buffer));+ return btoa(arr.reduce((data, byte) => data + String.fromCharCode(byte), ''));+ } catch (error) {+ console.error('Error encoding to base64:', error);+ return null;+ }+ }+/*** Check if a table exists in the database* @param tableName - The name of the table to check