Skip to content

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

Add dictionary loader vite plugin to inject identity generator dict content (#541)

Leendert de Borste5ead966e9dd
diff --git a/browser-extensions/chrome/src/contentScript.ts b/browser-extensions/chrome/src/contentScript.ts
index c93d750d0..ae1c1cfc8 100644
--- a/browser-extensions/chrome/src/contentScript.ts
+++ b/browser-extensions/chrome/src/contentScript.ts
@@ -1,5 +1,7 @@
import { detectForms } from './utils/FormDetector';
import { Credential } from './types/Credential';
+import { IdentityGeneratorEn } from './generators/Identity/implementations/IdentityGeneratorEn';
+import { PasswordGenerator } from './generators/Password/PasswordGenerator';
type CredentialResponse = {
status: 'OK' | 'LOCKED';
@@ -267,9 +269,26 @@ function createPopup(input: HTMLInputElement, credentials: Credential[]) : void
</svg>
New Alias
`;
- createButton.addEventListener('click', () => {
- chrome.runtime.sendMessage({ type: 'OPEN_NEW_CREDENTIAL' });
- removeExistingPopup();
+ createButton.addEventListener('click', async () => {
+ // TODO: Implement new credential popup if necessary? otherwise remove if simple implementation is sufficient for now.
+ // chrome.runtime.sendMessage({ type: 'OPEN_NEW_CREDENTIAL' });
+ // removeExistingPopup();
+
+ // Generate new identity locally
+ const identityGenerator = new IdentityGeneratorEn();
+ const identity = await identityGenerator.generateRandomIdentity();
+
+ const passwordGenerator = new PasswordGenerator();
+ const password = passwordGenerator.generateRandomPassword();
+
+ // create alert with all identity details
+ alert(`
+ First name: ${identity.firstName}
+ Last name: ${identity.lastName}
+ Gender: ${identity.gender}
+ Email: ${identity.emailPrefix}
+ Password: ${password}
+ `);
});
// Search button
diff --git a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts
index a77677610..a00cb5024 100644
--- a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts
+++ b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts
@@ -1,16 +1,15 @@
import { BaseIdentityGenerator } from "./base/BaseIdentityGenerator";
-import * as path from 'path';
export class IdentityGeneratorEn extends BaseIdentityGenerator {
- protected getFirstNamesMaleFilePath(): string {
- return path.join(__dirname, 'dictionaries/en/firstnames_male');
+ protected getFirstNamesMaleJson(): string[] {
+ return '__FIRSTNAMES_MALE_EN__'; // This will be replaced by dictionary-loader
}
- protected getFirstNamesFemaleFilePath(): string {
- return path.join(__dirname, 'dictionaries/en/firstnames_female');
+ protected getFirstNamesFemaleJson(): string[] {
+ return '__FIRSTNAMES_FEMALE_EN__'; // This will be replaced by dictionary-loader
}
- protected getLastNamesFilePath(): string {
- return path.join(__dirname, 'dictionaries/en/lastnames');
+ protected getLastNamesJson(): string[] {
+ return '__LASTNAMES_EN__'; // This will be replaced by dictionary-loader
}
}
diff --git a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts
index 8237b2e38..0ae28d102 100644
--- a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts
+++ b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts
@@ -1,16 +1,15 @@
import { BaseIdentityGenerator } from "./base/BaseIdentityGenerator";
-import * as path from 'path';
export class IdentityGeneratorNl extends BaseIdentityGenerator {
- protected getFirstNamesMaleFilePath(): string {
- return path.join(__dirname, 'dictionaries/nl/firstnames_male');
+ protected getFirstNamesMaleJson(): string[] {
+ return '__FIRSTNAMES_MALE_NL__'; // This will be replaced by dictionary-loader
}
- protected getFirstNamesFemaleFilePath(): string {
- return path.join(__dirname, 'dictionaries/nl/firstnames_female');
+ protected getFirstNamesFemaleJson(): string[] {
+ return '__FIRSTNAMES_FEMALE_NL__'; // This will be replaced by dictionary-loader
}
- protected getLastNamesFilePath(): string {
- return path.join(__dirname, 'dictionaries/nl/lastnames');
+ protected getLastNamesJson(): string[] {
+ return '__LASTNAMES_NL__'; // This will be replaced by dictionary-loader
}
}
diff --git a/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts b/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts
index 4ed795ef3..a070a291b 100644
--- a/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts
+++ b/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts
@@ -2,52 +2,23 @@ import { UsernameEmailGenerator } from '../../UsernameEmailGenerator';
import { Gender } from '../../types/Gender';
import { IIdentityGenerator } from '../../interfaces/IIdentityGenerator';
import { Identity } from '../../types/Identity';
-import * as fs from 'fs';
export abstract class BaseIdentityGenerator implements IIdentityGenerator {
- private firstNamesMale: string[] = [];
- private firstNamesFemale: string[] = [];
- private lastNames: string[] = [];
+ protected firstNamesMale: string[] = [];
+ protected firstNamesFemale: string[] = [];
+ protected lastNames: string[] = [];
private random = Math.random;
constructor() {
- this.loadNameLists();
+ // Each implementing class should provide these as static JSON strings
+ this.firstNamesMale = this.getFirstNamesMaleJson();
+ this.firstNamesFemale = this.getFirstNamesFemaleJson();
+ this.lastNames = this.getLastNamesJson();
}
- // Methods to be overridden by implementations to specify file paths
- protected abstract getFirstNamesMaleFilePath(): string;
- protected abstract getFirstNamesFemaleFilePath(): string;
- protected abstract getLastNamesFilePath(): string;
-
- private loadNameLists(): void {
- try {
- // Load male first names
- const maleNamesPath = this.getFirstNamesMaleFilePath();
- const maleNamesContent = fs.readFileSync(maleNamesPath, 'utf8');
- this.firstNamesMale = maleNamesContent
- .split('\n')
- .map(line => line.trim())
- .filter(line => line.length > 0);
-
- // Load female first names
- const femaleNamesPath = this.getFirstNamesFemaleFilePath();
- const femaleNamesContent = fs.readFileSync(femaleNamesPath, 'utf8');
- this.firstNamesFemale = femaleNamesContent
- .split('\n')
- .map(line => line.trim())
- .filter(line => line.length > 0);
-
- // Load last names
- const lastNamesPath = this.getLastNamesFilePath();
- const lastNamesContent = fs.readFileSync(lastNamesPath, 'utf8');
- this.lastNames = lastNamesContent
- .split('\n')
- .map(line => line.trim())
- .filter(line => line.length > 0);
- } catch (error) {
- throw new Error(`Failed to load name lists: ${error.message}`);
- }
- }
+ protected abstract getFirstNamesMaleJson(): string[];
+ protected abstract getFirstNamesFemaleJson(): string[];
+ protected abstract getLastNamesJson(): string[];
protected generateRandomDateOfBirth(): Date {
const today = new Date();
diff --git a/browser-extensions/chrome/vite-plugins/dictionary-loader.ts b/browser-extensions/chrome/vite-plugins/dictionary-loader.ts
new file mode 100644
index 000000000..5745fcdf0
--- /dev/null
+++ b/browser-extensions/chrome/vite-plugins/dictionary-loader.ts
@@ -0,0 +1,76 @@
+import fs from 'fs';
+import path from 'path';
+
+/**
+ * Vite plugin to load dictionary files for the identity generator and
+ * inject the content into the code during the build process.
+ *
+ * This allows to keep separate dictionary files for improved maintainability
+ * but include the contents in the resulting extension code without needing to bundle
+ * the files separately.
+ */
+export default function dictionaryLoader() {
+ return {
+ name: 'dictionary-loader',
+ transform(code: string, id: string) {
+ // Only transform identity generator files
+ // TODO: refactor to dynamically load all dictionaries for all languages
+ // instead of hardcoding the languages here.
+ if (id.includes('IdentityGeneratorEn.ts') || id.includes('IdentityGeneratorNl.ts')) {
+ const lang = id.includes('IdentityGeneratorEn.ts') ? 'en' : 'nl';
+ const dictionaryPath = path.resolve(__dirname, `../src/generators/Identity/implementations/dictionaries/${lang}`);
+
+ try {
+ // Read dictionary files and clean up entries
+ const firstNamesMale = fs.readFileSync(path.join(dictionaryPath, 'firstnames_male'), 'utf-8')
+ .split('\n')
+ .filter(name => name.trim())
+ .map(name => name.trim());
+
+ const firstNamesFemale = fs.readFileSync(path.join(dictionaryPath, 'firstnames_female'), 'utf-8')
+ .split('\n')
+ .filter(name => name.trim())
+ .map(name => name.trim());
+
+ const lastNames = fs.readFileSync(path.join(dictionaryPath, 'lastnames'), 'utf-8')
+ .split('\n')
+ .filter(name => name.trim())
+ .map(name => name.trim());
+
+ console.log('Raw code:', code);
+ console.log('Searching for placeholders:', {
+ male: `__FIRSTNAMES_MALE_${lang.toUpperCase()}__`,
+ female: `__FIRSTNAMES_FEMALE_${lang.toUpperCase()}__`,
+ last: `__LASTNAMES_${lang.toUpperCase()}__`
+ });
+
+ // Replace the placeholder strings with stringified arrays
+ code = code.replace(
+ new RegExp(`['"\`]__FIRSTNAMES_MALE_${lang.toUpperCase()}__['"\`]`, 'g'),
+ `[${firstNamesMale.map(name => `"${name}"`).join(',')}]`
+ );
+
+ code = code.replace(
+ new RegExp(`['"\`]__FIRSTNAMES_FEMALE_${lang.toUpperCase()}__['"\`]`, 'g'),
+ `[${firstNamesFemale.map(name => `"${name}"`).join(',')}]`
+ );
+
+ code = code.replace(
+ new RegExp(`['"\`]__LASTNAMES_${lang.toUpperCase()}__['"\`]`, 'g'),
+ `[${lastNames.map(name => `"${name}"`).join(',')}]`
+ );
+
+ console.log('Transformed code:', code);
+
+ return {
+ code,
+ map: null
+ };
+ } catch (error) {
+ console.error(`Error loading dictionary files for ${lang}:`, error);
+ return null;
+ }
+ }
+ }
+ };
+}
\ No newline at end of file
diff --git a/browser-extensions/chrome/vite.config.js b/browser-extensions/chrome/vite.config.js
index 9a3b61baf..ef7d439fd 100644
--- a/browser-extensions/chrome/vite.config.js
+++ b/browser-extensions/chrome/vite.config.js
@@ -3,10 +3,12 @@ import react from '@vitejs/plugin-react';
import { viteStaticCopy } from 'vite-plugin-static-copy';
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';
+import dictionaryLoader from './vite-plugins/dictionary-loader';
export default defineConfig({
plugins: [
react(),
+ dictionaryLoader(),
viteStaticCopy({
targets: [
{