-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
678 lines (616 loc) · 29.7 KB
/
Copy pathapp.js
File metadata and controls
678 lines (616 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
const STORAGE_KEY = 'private-test-account:last-identity';
const THEME_STORAGE_KEY = 'private-test-account:theme';
const APP_URL = 'https://fake-identity-chi.vercel.app/';
const RANDOM_USER_URL = 'https://randomuser.me/api/';
const FAKER_API_URL = 'https://fakerapi.it/api/v2/persons';
const IDENTITY_LOCALES = ['us', 'gb', 'ca', 'au', 'de', 'fr'];
const PASSWORD_CHARSET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+=';
const EMAIL_PROVIDERS = {
mailgw: {
id: 'mailgw',
name: 'Mail.gw',
kind: 'api',
baseUrl: 'https://api.mail.gw',
help: 'Mail.gw is the default browser-compatible provider with an in-app inbox.'
},
mailtm: {
id: 'mailtm',
name: 'Mail.tm',
kind: 'api',
baseUrl: 'https://api.mail.tm',
help: 'Mail.tm is free and uses the same account/token API, but browser access can be blocked by its CORS policy.'
},
tenminutemail: {
id: 'tenminutemail',
name: '10MinuteMail',
kind: 'web',
website: 'https://10minutemail.com/',
help: '10MinuteMail is web-only: open its site to receive a short-lived inbox. It does not expose a public inbox API.'
}
};
let currentData = {};
let activeMailProvider = 'mailgw';
let mailToken = null;
let mailPollingInterval = null;
const els = {
generateBtn: document.getElementById('generateBtn'),
copyAllBtn: document.getElementById('copyAllBtn'),
bookmarkletCode: document.getElementById('bookmarkletCode'),
copyBookmarkletBtn: document.getElementById('copyBookmarkletBtn'),
bookmarkletLink: document.getElementById('bookmarkletLink'),
themeToggle: document.getElementById('themeToggle'),
themeToggleText: document.querySelector('.theme-toggle-text'),
createMailBtn: document.getElementById('createMailBtn'),
generatePasswordBtn: document.getElementById('generatePasswordBtn'),
passwordLength: document.getElementById('passwordLength'),
mailProviderSelect: document.getElementById('mailProviderSelect'),
openProviderBtn: document.getElementById('openProviderBtn'),
providerHelp: document.getElementById('providerHelp'),
localeSelect: document.getElementById('localeSelect'),
clearDataBtn: document.getElementById('clearDataBtn'),
identityStatus: document.getElementById('identityStatus'),
mailStatus: document.getElementById('mailStatus'),
userAvatar: document.getElementById('userAvatar'),
fullName: document.getElementById('fullName'),
username: document.getElementById('username'),
gender: document.getElementById('gender'),
dob: document.getElementById('dob'),
address: document.getElementById('address'),
email: document.getElementById('email'),
liveEmail: document.getElementById('liveEmail'),
mailPassword: document.getElementById('mailPassword'),
accountPassword: document.getElementById('accountPassword'),
passwordStrength: document.getElementById('passwordStrength'),
passwordStrengthBar: document.getElementById('passwordStrengthBar'),
passwordStrengthTrack: document.querySelector('.strength-track'),
passwordEntropy: document.getElementById('passwordEntropy'),
passwordComposition: document.getElementById('passwordComposition'),
passwordStrengthHelp: document.getElementById('passwordStrengthHelp'),
phone: document.getElementById('phone'),
tabEmail: document.getElementById('tabEmail'),
tabSms: document.getElementById('tabSms'),
emailInbox: document.getElementById('emailInbox'),
smsInbox: document.getElementById('smsInbox'),
ccNumber: document.getElementById('ccNumber'),
ccExp: document.getElementById('ccExp'),
ccCvv: document.getElementById('ccCvv'),
ccNumberVis: document.getElementById('ccNumberVis'),
ccNameVis: document.getElementById('ccNameVis'),
ccExpVis: document.getElementById('ccExpVis'),
ccCvvVis: document.getElementById('ccCvvVis'),
toast: document.getElementById('toast'),
toastMsg: document.getElementById('toastMsg')
};
els.generateBtn.addEventListener('click', generateIdentity);
els.copyAllBtn.addEventListener('click', copyAllJson);
els.copyBookmarkletBtn?.addEventListener('click', copyBookmarklet);
initializeBookmarklet();
els.themeToggle?.addEventListener('click', toggleTheme);
applyTheme(localStorage.getItem(THEME_STORAGE_KEY) || 'dark');
els.createMailBtn.addEventListener('click', createLiveMail);
els.generatePasswordBtn?.addEventListener('click', generateAccountPassword);
els.mailProviderSelect?.addEventListener('change', handleProviderChange);
els.openProviderBtn?.addEventListener('click', openSelectedProvider);
els.clearDataBtn?.addEventListener('click', clearSavedData);
updateProviderUI();
els.tabEmail.addEventListener('click', () => switchInbox('email'));
els.tabSms.addEventListener('click', () => switchInbox('sms'));
document.querySelectorAll('[data-copy]').forEach((button) => {
button.addEventListener('click', () => {
const id = button.dataset.copy;
const value = els[id]?.innerText?.trim();
if (value && value !== '--') copyToClipboard(value, `${id} copied`);
});
});
async function generateIdentity() {
setButtonLoading(els.generateBtn, true);
setStatus(els.identityStatus, 'loading', 'Identity service: loading');
try {
const locale = IDENTITY_LOCALES.includes(els.localeSelect.value) ? els.localeSelect.value : 'us';
const person = await fetchIdentity(locale);
const firstName = person.firstName || 'Test';
const lastName = person.lastName || 'User';
const username = makeUsername(firstName, lastName, person.username);
currentData = {
firstName,
lastName,
fullName: `${firstName} ${lastName}`,
username,
gender: person.gender || 'unspecified',
dob: person.dob || '1990-01-01',
address: person.address || 'Synthetic address for testing',
email: person.email || `${username}@example.com`,
phone: makeTestPhone(locale),
password: generatePassword(getSelectedPasswordLength()),
locale,
source: person.source || 'Random User API',
card: getTestCard(),
generatedAt: new Date().toISOString()
};
saveCurrentData();
updateUI();
setStatus(els.identityStatus, 'success', `Identity service: ${currentData.source}`);
showToast('Synthetic identity generated');
} catch (error) {
console.error('Identity generation failed:', error);
setStatus(els.identityStatus, 'error', 'Identity service: unavailable');
showToast('Could not generate identity', true);
} finally {
setButtonLoading(els.generateBtn, false);
}
}
async function fetchIdentity(locale) {
try {
const params = new URLSearchParams({
nat: locale,
inc: 'name,gender,dob,location,email,login',
noinfo: ''
});
const response = await fetchWithTimeout(`${RANDOM_USER_URL}?${params}`, {}, 10000);
if (!response.ok) throw new Error(`Random User returned ${response.status}`);
const payload = await response.json();
const user = payload.results?.[0];
if (!user?.name) throw new Error('Random User returned no user');
return {
firstName: user.name.first,
lastName: user.name.last,
username: user.login?.username,
gender: user.gender,
dob: user.dob?.date ? formatDate(user.dob.date) : undefined,
address: formatRandomUserAddress(user.location),
email: user.email,
source: 'Random User API'
};
} catch (randomUserError) {
console.warn('Random User unavailable; trying FakerAPI.', randomUserError);
try {
const params = new URLSearchParams({ _quantity: '1', _locale: `${locale === 'us' ? 'en_US' : locale === 'gb' ? 'en_GB' : locale === 'ca' ? 'en_CA' : locale === 'au' ? 'en_AU' : locale === 'de' ? 'de_DE' : 'fr_FR'}` });
const response = await fetchWithTimeout(`${FAKER_API_URL}?${params}`, {}, 10000);
if (!response.ok) throw new Error(`FakerAPI returned ${response.status}`);
const payload = await response.json();
const person = payload.data?.[0];
if (!person?.firstname) throw new Error('FakerAPI returned no person');
return {
firstName: person.firstname,
lastName: person.lastname,
gender: person.gender,
dob: person.birthday,
address: formatFakerAddress(person.address),
email: person.email,
source: 'FakerAPI'
};
} catch (fakerError) {
console.warn('FakerAPI unavailable; using local synthetic fallback.', fakerError);
return localIdentityFallback(locale);
}
}
}
function localIdentityFallback(locale) {
const firstNames = ['Alex', 'Jordan', 'Taylor', 'Morgan', 'Casey', 'Riley', 'Avery', 'Quinn'];
const lastNames = ['Carter', 'Hayes', 'Parker', 'Reed', 'Morgan', 'Brooks', 'Mason', 'Ellis'];
const firstName = randomItem(firstNames);
const lastName = randomItem(lastNames);
const number = Math.floor(100 + Math.random() * 900);
return {
firstName,
lastName,
gender: 'unspecified',
dob: `${1985 + Math.floor(Math.random() * 16)}-${String(1 + Math.floor(Math.random() * 12)).padStart(2, '0')}-${String(1 + Math.floor(Math.random() * 28)).padStart(2, '0')}`,
address: `${number} Test Street, Test City, ${locale.toUpperCase()}`,
email: `${firstName.toLowerCase()}.${lastName.toLowerCase()}${number}@example.com`,
source: 'Local fallback'
};
}
function makeUsername(firstName, lastName, supplied) {
const base = (supplied || `${firstName}${lastName}`).toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 18) || 'testuser';
return `${base}${Math.floor(100 + Math.random() * 900)}`;
}
function makeTestPhone(locale) {
if (locale === 'gb') return `+44 7700 900${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`;
if (locale === 'au') return `+61 491 570 ${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`;
return `+1 202-555-01${String(Math.floor(Math.random() * 100)).padStart(2, '0')}`;
}
function getTestCard() {
return { number: '4242424242424242', expiry: '12/34', cvv: '123', type: 'Visa test card' };
}
function updateUI() {
const hasIdentity = Boolean(currentData.fullName);
els.fullName.innerText = currentData.fullName || '--';
els.username.innerText = currentData.username || '--';
els.gender.innerText = titleCase(currentData.gender || '--');
els.dob.innerText = currentData.dob || '--';
els.address.innerText = currentData.address || '--';
els.email.innerText = currentData.email || '--';
const liveEmail = currentData.liveEmail;
els.liveEmail.innerText = liveEmail?.address || (liveEmail?.provider === 'tenminutemail' ? 'Use 10MinuteMail website' : '--');
els.mailPassword.innerText = liveEmail?.password || (liveEmail?.provider === 'tenminutemail' ? 'Not applicable' : '--');
els.accountPassword.innerText = currentData.password || '--';
updatePasswordStrength(currentData.password || '');
els.phone.innerText = currentData.phone || '--';
const card = currentData.card || getTestCard();
const formattedCard = card.number.match(/.{1,4}/g).join(' ');
els.ccNumber.innerText = formattedCard;
els.ccExp.innerText = card.expiry;
els.ccCvv.innerText = card.cvv;
els.ccNumberVis.innerText = formattedCard;
els.ccNameVis.innerText = hasIdentity ? currentData.fullName.toUpperCase() : 'TEST USER';
els.ccExpVis.innerText = card.expiry;
els.ccCvvVis.innerText = card.cvv;
els.userAvatar.innerHTML = `<span>${escapeHtml((currentData.firstName || '?').charAt(0).toUpperCase())}</span>`;
document.querySelectorAll('.data-value').forEach((element) => element.classList.toggle('empty-state', element.innerText === '--'));
}
async function createLiveMail() {
if (!currentData.fullName) {
showToast('Generate an identity first', true);
return;
}
const provider = getSelectedProvider();
stopMailPolling();
mailToken = null;
if (provider.kind === 'web') {
currentData.liveEmail = { provider: provider.id, website: provider.website };
saveCurrentData();
updateUI();
setStatus(els.mailStatus, 'success', `${provider.name}: website ready`);
renderInboxMessage(`${provider.name} opens in a new tab`, 'This provider is web-only and does not expose a public inbox API for this app.');
openSelectedProvider();
showToast(`${provider.name} opened`);
return;
}
setButtonLoading(els.createMailBtn, true);
setStatus(els.mailStatus, 'loading', `${provider.name}: creating inbox`);
try {
const domainsResponse = await fetchWithTimeout(`${provider.baseUrl}/domains?page=1`, {}, 10000);
if (!domainsResponse.ok) throw new Error(`${provider.name} domains returned ${domainsResponse.status}`);
const domainsPayload = await domainsResponse.json();
const domain = domainsPayload['hydra:member']?.find((item) => item.isActive !== false)?.domain;
if (!domain) throw new Error(`${provider.name} returned no active domain`);
let account;
let lastError;
for (let attempt = 0; attempt < 3; attempt += 1) {
const address = `${currentData.username.toLowerCase()}${attempt ? Math.floor(1000 + Math.random() * 9000) : ''}@${domain}`;
const password = generatePassword();
try {
const accountResponse = await fetchWithTimeout(`${provider.baseUrl}/accounts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address, password })
}, 10000);
if (!accountResponse.ok) throw new Error(`${provider.name} account returned ${accountResponse.status}`);
account = { address, password, provider: provider.id };
break;
} catch (error) {
lastError = error;
}
}
if (!account) throw lastError || new Error(`Could not create ${provider.name} account`);
const tokenResponse = await fetchWithTimeout(`${provider.baseUrl}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(account)
}, 10000);
if (!tokenResponse.ok) throw new Error(`${provider.name} token returned ${tokenResponse.status}`);
const tokenPayload = await tokenResponse.json();
if (!tokenPayload.token) throw new Error(`${provider.name} returned no token`);
activeMailProvider = provider.id;
mailToken = tokenPayload.token;
currentData.liveEmail = account;
saveCurrentData();
updateUI();
setStatus(els.mailStatus, 'success', `${provider.name}: connected`);
renderInboxMessage('Inbox created. Waiting for incoming email…', `${provider.name} is ready for permitted testing.`);
await fetchEmails();
mailPollingInterval = setInterval(fetchEmails, 8000);
showToast(`${provider.name} inbox created`);
} catch (error) {
console.error(`${provider.name} inbox creation failed:`, error);
setStatus(els.mailStatus, 'error', `${provider.name}: unavailable`);
renderInboxMessage('Inbox could not be created', `${provider.name} may be rate-limited, blocked by browser CORS, or temporarily unavailable.`);
showToast(`${provider.name} unavailable`, true);
} finally {
setButtonLoading(els.createMailBtn, false);
}
}
function getSelectedProvider() {
return EMAIL_PROVIDERS[activeMailProvider] || EMAIL_PROVIDERS.mailgw;
}
function updateProviderUI() {
const provider = getSelectedProvider();
if (els.mailProviderSelect) els.mailProviderSelect.value = provider.id;
if (els.providerHelp) els.providerHelp.innerText = provider.help;
if (els.openProviderBtn) els.openProviderBtn.style.display = provider.kind === 'web' ? 'inline-flex' : 'none';
const buttonText = els.createMailBtn?.querySelector('.btn-text');
if (buttonText) buttonText.innerHTML = provider.kind === 'web' ? `<i class="ph ph-arrow-square-out"></i> Open ${provider.name}` : `<i class="ph ph-envelope-simple"></i> Create ${provider.name} Inbox`;
}
function handleProviderChange() {
const selected = els.mailProviderSelect?.value;
if (!EMAIL_PROVIDERS[selected]) return;
activeMailProvider = selected;
stopMailPolling();
mailToken = null;
if (currentData.liveEmail?.provider !== selected) {
delete currentData.liveEmail;
saveCurrentData();
updateUI();
}
updateProviderUI();
setStatus(els.mailStatus, 'idle', `${getSelectedProvider().name}: ready`);
renderInboxMessage('Choose an inbox action', getSelectedProvider().help);
}
function openSelectedProvider() {
const provider = getSelectedProvider();
if (provider.kind === 'web') window.open(provider.website, '_blank', 'noopener,noreferrer');
}
async function restoreSavedData() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null');
if (!saved?.fullName) return false;
currentData = saved;
if (!currentData.password) {
currentData.password = generatePassword(getSelectedPasswordLength());
saveCurrentData();
}
activeMailProvider = EMAIL_PROVIDERS[saved.liveEmail?.provider]?.id || 'mailgw';
updateProviderUI();
updateUI();
setStatus(els.identityStatus, 'success', `Identity service: ${saved.source || 'restored locally'}`);
const provider = getSelectedProvider();
if (provider.kind === 'api' && saved.liveEmail?.address && saved.liveEmail?.password) {
try {
const response = await fetchWithTimeout(`${provider.baseUrl}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(saved.liveEmail)
}, 8000);
if (!response.ok) throw new Error(`${provider.name} token returned ${response.status}`);
const payload = await response.json();
mailToken = payload.token;
setStatus(els.mailStatus, 'success', `${provider.name}: reconnected`);
await fetchEmails();
mailPollingInterval = setInterval(fetchEmails, 8000);
} catch (error) {
console.warn(`Could not reconnect ${provider.name}:`, error);
setStatus(els.mailStatus, 'error', `${provider.name}: reconnect failed`);
}
} else if (provider.kind === 'web' && saved.liveEmail?.website) {
setStatus(els.mailStatus, 'success', `${provider.name}: website ready`);
}
return true;
} catch (error) {
console.warn('Could not restore saved data:', error);
return false;
}
}
async function fetchEmails() {
if (!mailToken) return;
const provider = getSelectedProvider();
try {
const response = await fetchWithTimeout(`${provider.baseUrl}/messages?page=1`, {
headers: { Authorization: `Bearer ${mailToken}` }
}, 8000);
if (!response.ok) return;
const payload = await response.json();
const messages = payload['hydra:member'] || [];
if (!messages.length) return;
els.emailInbox.innerHTML = messages.map((message) => `
<article class="message-card">
<div class="message-subject">${escapeHtml(message.subject || '(No subject)')}</div>
<div class="message-meta">From: ${escapeHtml(message.from?.address || 'unknown sender')} · ${escapeHtml(formatDateTime(message.createdAt))}</div>
<div class="message-intro">${escapeHtml(message.intro || `Open this message in your ${provider.name} account for the full content.`)}</div>
</article>
`).join('');
} catch (error) {
console.warn(`${provider.name} email polling failed:`, error);
}
}
function renderInboxMessage(title, detail) {
els.emailInbox.innerHTML = `<div class="empty-state inbox-empty"><i class="ph ph-envelope-open" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i><strong>${escapeHtml(title)}</strong><p>${escapeHtml(detail)}</p></div>`;
}
function switchInbox(tab) {
const emailActive = tab === 'email';
els.tabEmail.classList.toggle('active', emailActive);
els.tabSms.classList.toggle('active', !emailActive);
els.emailInbox.style.display = emailActive ? 'block' : 'none';
els.smsInbox.style.display = emailActive ? 'none' : 'block';
}
function clearSavedData() {
stopMailPolling();
currentData = {};
activeMailProvider = 'mailgw';
mailToken = null;
localStorage.removeItem(STORAGE_KEY);
updateProviderUI();
updatePasswordStrength('');
document.querySelectorAll('.data-value').forEach((element) => {
element.innerText = '--';
element.classList.add('empty-state');
});
els.fullName.innerText = '--';
els.userAvatar.innerHTML = '<span>?</span>';
els.emailInbox.innerHTML = '<div class="empty-state inbox-empty"><i class="ph ph-envelope" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i><p>Create a disposable inbox to receive permitted test emails.</p></div>';
setStatus(els.identityStatus, 'idle', 'Identity service: ready');
setStatus(els.mailStatus, 'idle', 'Disposable email: ready');
showToast('Local data cleared');
}
function saveCurrentData() {
if (currentData.fullName) localStorage.setItem(STORAGE_KEY, JSON.stringify(currentData));
}
function stopMailPolling() {
if (mailPollingInterval) clearInterval(mailPollingInterval);
mailPollingInterval = null;
}
function setButtonLoading(button, isLoading) {
button.classList.toggle('loading', isLoading);
button.disabled = isLoading;
}
function setStatus(element, state, text) {
element.className = `status-pill status-${state}`;
element.innerHTML = `<span class="status-dot"></span> ${escapeHtml(text)}`;
}
function fetchWithTimeout(url, options = {}, timeout = 10000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
return fetch(url, { ...options, signal: controller.signal }).finally(() => clearTimeout(timer));
}
function formatRandomUserAddress(location = {}) {
const street = location.street ? `${location.street.number} ${location.street.name}` : 'Synthetic address';
return [street, location.city, location.state, location.country, location.postcode].filter(Boolean).join(', ');
}
function formatFakerAddress(address = {}) {
return [address.street, address.city, address.country, address.zipcode].filter(Boolean).join(', ') || 'Synthetic address for testing';
}
function formatDate(value) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? String(value).slice(0, 10) : date.toISOString().slice(0, 10);
}
function formatDateTime(value) {
if (!value) return 'unknown time';
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
function titleCase(value) {
return String(value).replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function randomItem(items) {
return items[Math.floor(Math.random() * items.length)];
}
function initializeBookmarklet() {
const launcherUrl = new URL(APP_URL);
launcherUrl.searchParams.set('launcher', 'bookmarklet');
const encodedUrl = JSON.stringify(launcherUrl.toString());
const bookmarklet = `javascript:(()=>{window.open(${encodedUrl},'_blank','noopener,noreferrer')})()`;
if (els.bookmarkletCode) els.bookmarkletCode.value = bookmarklet;
if (els.bookmarkletLink) els.bookmarkletLink.href = bookmarklet;
}
function copyBookmarklet() {
const code = els.bookmarkletCode?.value;
if (code) copyToClipboard(code, 'Bookmarklet copied');
}
function applyTheme(theme) {
const nextTheme = theme === 'light' ? 'light' : 'dark';
document.body.dataset.theme = nextTheme;
const darkModeActive = nextTheme === 'dark';
if (els.themeToggle) {
els.themeToggle.setAttribute('aria-pressed', String(darkModeActive));
els.themeToggle.setAttribute('aria-label', `Switch to ${darkModeActive ? 'light' : 'dark'} mode`);
}
if (els.themeToggleText) els.themeToggleText.innerText = darkModeActive ? 'Light mode' : 'Dark mode';
const icon = els.themeToggle?.querySelector('i');
if (icon) icon.className = darkModeActive ? 'ph ph-sun' : 'ph ph-moon';
}
function toggleTheme() {
const nextTheme = document.body.dataset.theme === 'dark' ? 'light' : 'dark';
applyTheme(nextTheme);
localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
showToast(`${nextTheme === 'dark' ? 'Dark' : 'Light'} mode enabled`);
}
function getSelectedPasswordLength() {
const length = Number.parseInt(els.passwordLength?.value, 10);
return [12, 16, 20, 24, 32].includes(length) ? length : 16;
}
function generatePassword(length = 16) {
const chars = PASSWORD_CHARSET;
const values = new Uint32Array(length);
if (window.crypto?.getRandomValues) {
window.crypto.getRandomValues(values);
return Array.from(values, (value) => chars[value % chars.length]).join('');
}
return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
}
function generateAccountPassword() {
if (!currentData.fullName) {
showToast('Generate an identity first', true);
return;
}
currentData.password = generatePassword(getSelectedPasswordLength());
saveCurrentData();
updateUI();
showToast('Password generated locally');
}
function updatePasswordStrength(password) {
if (!els.passwordStrength || !els.passwordStrengthBar || !els.passwordStrengthTrack) return;
if (!password) {
els.passwordStrength.innerText = '--';
els.passwordStrengthBar.style.width = '0%';
els.passwordStrengthTrack.setAttribute('aria-valuenow', '0');
els.passwordEntropy.innerText = 'Estimated entropy: --';
els.passwordComposition.innerText = 'Composition: --';
els.passwordStrengthHelp.innerText = 'Generate a password to see an estimated strength score.';
els.passwordStrengthBar.className = 'strength-bar';
return;
}
const result = calculatePasswordStrength(password);
els.passwordStrength.innerText = result.label;
els.passwordStrengthBar.style.width = `${result.percent}%`;
els.passwordStrengthBar.className = `strength-bar strength-${result.level}`;
els.passwordStrengthTrack.setAttribute('aria-valuenow', String(result.score));
els.passwordEntropy.innerText = `Estimated entropy: ${result.entropy.toFixed(1)} bits`;
els.passwordComposition.innerText = `Composition: ${result.composition}`;
els.passwordStrengthHelp.innerText = result.help;
}
function calculatePasswordStrength(password) {
const categories = [
{ label: 'lowercase', pattern: /[a-z]/, poolSize: 24 },
{ label: 'uppercase', pattern: /[A-Z]/, poolSize: 24 },
{ label: 'numbers', pattern: /[0-9]/, poolSize: 8 },
{ label: 'symbols', pattern: /[^A-Za-z0-9]/, poolSize: 12 }
];
const present = categories.filter((category) => category.pattern.test(password)).map((category) => category.label);
const poolSize = categories.filter((category) => present.includes(category.label)).reduce((total, category) => total + category.poolSize, 0);
const entropy = password.length * Math.log2(Math.max(poolSize, 1));
const score = entropy < 40 ? 1 : entropy < 60 ? 2 : entropy < 80 ? 3 : 4;
const levels = { 1: 'weak', 2: 'fair', 3: 'strong', 4: 'very-strong' };
const labels = { 1: 'Weak', 2: 'Fair', 3: 'Strong', 4: 'Very strong' };
const helps = {
1: 'Use a longer password with multiple character types.',
2: 'Add length and another character type for a stronger password.',
3: 'Good for synthetic testing; use a password manager for real accounts.',
4: 'High estimated entropy. Never reuse this password for important accounts.'
};
return {
entropy,
score,
level: levels[score],
label: labels[score],
percent: score * 25,
composition: present.length ? present.join(', ') : 'none',
help: helps[score]
};
}
function copyAllJson() {
if (!currentData.fullName) {
showToast('Nothing to copy yet', true);
return;
}
copyToClipboard(JSON.stringify(currentData, null, 2), 'JSON copied');
}
function copyToClipboard(text, message) {
if (navigator.clipboard?.writeText) {
navigator.clipboard.writeText(text).then(() => showToast(message)).catch(() => showToast('Copy failed', true));
return;
}
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
showToast(message);
}
function showToast(message, isError = false) {
els.toastMsg.innerText = message;
const icon = els.toast.querySelector('i');
icon.className = isError ? 'ph ph-warning-circle' : 'ph ph-check-circle';
icon.style.color = isError ? '#ef4444' : 'var(--success)';
els.toast.classList.add('show');
window.clearTimeout(showToast.timeout);
showToast.timeout = window.setTimeout(() => els.toast.classList.remove('show'), 3000);
}
function escapeHtml(value) {
return String(value ?? '').replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }[character]));
}
window.addEventListener('beforeunload', stopMailPolling);
(async function init() {
const restored = await restoreSavedData();
if (!restored) await generateIdentity();
})();