Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Prepopulate service title and URL based on current tab in browser extension (#1250)
Leendert de Borst35b8f0abae39
diff --git a/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.tsindex 654c7c612..055177c3e 100644--- a/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts@@ -70,6 +70,9 @@ export function handleOpenPopupCreateCredential(message: any) : Promise<BoolRespif (serviceUrl) {urlParams.set('serviceUrl', serviceUrl);}+ if (message.currentUrl) {+ urlParams.set('currentUrl', message.currentUrl);+ }browser.windows.create({url: browser.runtime.getURL(`/popup.html?${urlParams.toString()}#/credentials/add`),diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.tsindex 2faf045c3..1980f7254 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts@@ -7,8 +7,8 @@ import { DISABLED_SITES_KEY, TEMPORARY_DISABLED_SITES_KEY, GLOBAL_AUTOFILL_POPUPimport { CreateIdentityGenerator } from '@/utils/dist/shared/identity-generator';import type { Credential } from '@/utils/dist/shared/models/vault';import { CreatePasswordGenerator, PasswordGenerator, PasswordSettings } from '@/utils/dist/shared/password-generator';-import { FormDetector } from '@/utils/formDetector/FormDetector';import { ClickValidator } from '@/utils/security/ClickValidator';+import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';import { SqliteClient } from '@/utils/SqliteClient';import { CredentialsResponse } from '@/utils/types/messaging/CredentialsResponse';import { IdentitySettingsResponse } from '@/utils/types/messaging/IdentitySettingsResponse';@@ -227,8 +227,8 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:e.stopPropagation();e.stopImmediatePropagation();- const suggestedNames = FormDetector.getSuggestedServiceName(document, window.location);- const result = await createAliasCreationPopup(suggestedNames, rootContainer);+ const serviceInfo = ServiceDetectionUtility.getServiceInfo(document, window.location);+ const result = await createAliasCreationPopup(serviceInfo.suggestedNames, rootContainer);if (!result) {// User cancelled@@ -1057,8 +1057,11 @@ export async function createAliasCreationPopup(suggestedNames: string[], rootCone.preventDefault();e.stopPropagation();const serviceName = inputServiceName.value.trim();- const currentUrl = window.location.href;- sendMessage('OPEN_POPUP_CREATE_CREDENTIAL', { serviceName, currentUrl }, 'background');+ const encodedServiceInfo = ServiceDetectionUtility.getEncodedServiceInfo(document, window.location);+ sendMessage('OPEN_POPUP_CREATE_CREDENTIAL', {+ serviceName: serviceName || encodedServiceInfo.serviceName,+ currentUrl: encodedServiceInfo.currentUrl+ }, 'background');closePopup(null);});diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsxindex a60569d71..4bdc11945 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx@@ -27,6 +27,7 @@ import { SKIP_FORM_RESTORE_KEY } from '@/utils/Constants';import { IdentityHelperUtils, CreateIdentityGenerator, CreateUsernameEmailGenerator, Identity, Gender } from '@/utils/dist/shared/identity-generator';import type { Attachment, Credential } from '@/utils/dist/shared/models/vault';import { CreatePasswordGenerator } from '@/utils/dist/shared/password-generator';+import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';import { browser } from '#imports';@@ -233,17 +234,63 @@ const CredentialAddEdit: React.FC = () => {}if (!id) {- // On create mode, check for URL parameters and prefill if present+ // On create mode, check for URL parameters first, then fallback to tab detectionconst urlParams = new URLSearchParams(window.location.search);const serviceName = urlParams.get('serviceName');const serviceUrl = urlParams.get('serviceUrl');+ const currentUrl = urlParams.get('currentUrl');- if (serviceName) {- setValue('ServiceName', decodeURIComponent(serviceName));- }- if (serviceUrl) {- setValue('ServiceUrl', decodeURIComponent(serviceUrl));- }+ /**+ * Initialize service detection from URL parameters or current tab+ */+ const initializeServiceDetection = async (): Promise<void> => {+ try {+ // If URL parameters are present (e.g., from content script popout), use them+ if (serviceName || serviceUrl || currentUrl) {+ if (serviceName) {+ setValue('ServiceName', decodeURIComponent(serviceName));+ }+ if (serviceUrl) {+ setValue('ServiceUrl', decodeURIComponent(serviceUrl));+ }++ // If we have currentUrl but missing serviceName or serviceUrl, derive them+ if (currentUrl && (!serviceName || !serviceUrl)) {+ const decodedCurrentUrl = decodeURIComponent(currentUrl);+ const serviceInfo = ServiceDetectionUtility.getServiceInfoFromTab(decodedCurrentUrl);++ if (!serviceName && serviceInfo.suggestedNames.length > 0) {+ setValue('ServiceName', serviceInfo.suggestedNames[0]);+ }+ if (!serviceUrl && serviceInfo.serviceUrl) {+ setValue('ServiceUrl', serviceInfo.serviceUrl);+ }+ }+ return;+ }++ // Otherwise, detect from current active tab (for dashboard case)+ const [activeTab] = await browser.tabs.query({ active: true, currentWindow: true });++ if (activeTab?.url) {+ const serviceInfo = ServiceDetectionUtility.getServiceInfoFromTab(+ activeTab.url,+ activeTab.title+ );++ if (serviceInfo.suggestedNames.length > 0) {+ setValue('ServiceName', serviceInfo.suggestedNames[0]);+ }+ if (serviceInfo.serviceUrl) {+ setValue('ServiceUrl', serviceInfo.serviceUrl);+ }+ }+ } catch (error) {+ console.error('Error detecting service information:', error);+ }+ };++ initializeServiceDetection();// Focus the service name field after a short delay to ensure the component is mounted.setTimeout(() => {diff --git a/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.ts b/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.tsnew file mode 100644index 000000000..8e97be4b4--- /dev/null+++ b/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.ts@@ -0,0 +1,148 @@+import { FormDetector } from '../formDetector/FormDetector';++/**+ * Utility for detecting service name and URL information+ * Shared between content script and popup dashboard+ */+export class ServiceDetectionUtility {+ /**+ * Get service information from the current page+ */+ public static getServiceInfo(document: Document, location: Location): ServiceInfo {+ // Get suggested service names using FormDetector+ const suggestedNames = FormDetector.getSuggestedServiceName(document, location);++ // Get the current URL+ const currentUrl = location.href;++ // Process the URL to extract service URL (origin + pathname)+ let serviceUrl = '';+ try {+ const url = new URL(currentUrl);+ // Only include http/https URLs+ if (url.protocol === 'http:' || url.protocol === 'https:') {+ serviceUrl = url.origin + url.pathname;+ // Remove trailing slash+ if (serviceUrl.endsWith('/')) {+ serviceUrl = serviceUrl.slice(0, -1);+ }+ }+ } catch (error) {+ console.error('Error parsing current URL:', error);+ }++ return {+ suggestedNames,+ currentUrl,+ serviceUrl,+ domain: location.hostname.replace(/^www\./, '')+ };+ }++ /**+ * Get service information from tab data (for use in popup dashboard)+ */+ public static getServiceInfoFromTab(tabUrl: string, tabTitle?: string): ServiceInfo {+ try {+ const url = new URL(tabUrl);+ const location = {+ href: tabUrl,+ hostname: url.hostname,+ protocol: url.protocol,+ pathname: url.pathname,+ origin: url.origin+ } as Location;++ // Create a minimal document object for service name detection+ const mockDocument = {+ title: tabTitle || url.hostname+ } as Document;++ // Use FormDetector logic for service name detection+ const suggestedNames = FormDetector.getSuggestedServiceName(mockDocument, location);++ // Get service URL (origin + pathname)+ let serviceUrl = '';+ if (url.protocol === 'http:' || url.protocol === 'https:') {+ serviceUrl = url.origin + url.pathname;+ // Remove trailing slash+ if (serviceUrl.endsWith('/')) {+ serviceUrl = serviceUrl.slice(0, -1);+ }+ }++ return {+ suggestedNames,+ currentUrl: tabUrl,+ serviceUrl,+ domain: url.hostname.replace(/^www\./, '')+ };+ } catch (error) {+ console.error('Error parsing tab URL:', error);+ // Fallback to basic hostname detection+ const domain = tabUrl.replace(/^https?:\/\/(www\.)?/, '').split('/')[0];+ return {+ suggestedNames: [domain],+ currentUrl: tabUrl,+ serviceUrl: tabUrl,+ domain+ };+ }+ }++ /**+ * Get encoded service information suitable for URL parameters+ */+ public static getEncodedServiceInfo(document: Document, location: Location): EncodedServiceInfo {+ const serviceInfo = this.getServiceInfo(document, location);++ return {+ serviceName: serviceInfo.suggestedNames.length > 0 ? encodeURIComponent(serviceInfo.suggestedNames[0]) : '',+ serviceUrl: serviceInfo.serviceUrl ? encodeURIComponent(serviceInfo.serviceUrl) : '',+ currentUrl: encodeURIComponent(serviceInfo.currentUrl),+ domain: encodeURIComponent(serviceInfo.domain)+ };+ }++ /**+ * Get encoded service information from tab data+ */+ public static getEncodedServiceInfoFromTab(tabUrl: string, tabTitle?: string): EncodedServiceInfo {+ const serviceInfo = this.getServiceInfoFromTab(tabUrl, tabTitle);++ return {+ serviceName: serviceInfo.suggestedNames.length > 0 ? encodeURIComponent(serviceInfo.suggestedNames[0]) : '',+ serviceUrl: serviceInfo.serviceUrl ? encodeURIComponent(serviceInfo.serviceUrl) : '',+ currentUrl: encodeURIComponent(serviceInfo.currentUrl),+ domain: encodeURIComponent(serviceInfo.domain)+ };+ }+}++/**+ * Service information interface+ */+export type ServiceInfo = {+ /** Array of suggested service names */+ suggestedNames: string[];+ /** Current page URL */+ currentUrl: string;+ /** Service URL (origin + pathname) */+ serviceUrl: string;+ /** Domain name without www prefix */+ domain: string;+}++/**+ * Encoded service information interface+ */+export type EncodedServiceInfo = {+ /** URL-encoded primary service name */+ serviceName: string;+ /** URL-encoded service URL */+ serviceUrl: string;+ /** URL-encoded current page URL */+ currentUrl: string;+ /** URL-encoded domain */+ domain: string;+}