-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
312 lines (286 loc) Β· 10.5 KB
/
Copy pathscript.js
File metadata and controls
312 lines (286 loc) Β· 10.5 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
// GenPassX β script v2 with entropy, localStorage, per-password download & accessibility
// Elements
const lengthRange = document.getElementById("lengthRange");
const lengthValue = document.getElementById("lengthValue");
const generateBtn = document.getElementById("generateBtn");
const downloadAllBtn = document.getElementById("downloadAll");
const clearBtn = document.getElementById("clearBtn");
const themeToggle = document.getElementById("themeToggle");
const autoRegenerate = document.getElementById("autoRegenerate");
const showPasswords = document.getElementById("showPasswords");
const passwordInputs = document.querySelectorAll(".password-input");
const copyButtons = document.querySelectorAll(".copy-btn");
const regenButtons = document.querySelectorAll(".regen-btn");
const downloadButtons = document.querySelectorAll(".download-btn");
const bitsEls = document.querySelectorAll(".entropy .bits");
const strTextEls = document.querySelectorAll(".str-text");
const historyList = document.getElementById("historyList");
const meterBar = document.querySelector(".meter-bar");
const globalEntropy = document.getElementById("globalEntropy");
const globalStrength = document.getElementById("globalStrength");
// Options
const uppercase = document.getElementById("uppercase");
const lowercase = document.getElementById("lowercase");
const numbers = document.getElementById("numbers");
const symbols = document.getElementById("symbols");
// state & constants
const HISTORY_KEY = "genpassx_history_v2";
const AUTO_INTERVAL = 5000; // ms
lengthRange.addEventListener("input", () => {
lengthValue.textContent = lengthRange.value;
});
// Utility: build charset and pool size
function getCharset() {
let charset = "";
if (uppercase.checked) charset += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (lowercase.checked) charset += "abcdefghijklmnopqrstuvwxyz";
if (numbers.checked) charset += "0123456789";
if (symbols.checked) charset += "!@#$%^&*()_+-=[]{};:,.<>?/|";
// remove duplicates and return as array
return Array.from(new Set(charset.split("")));
}
// Generate password picking random chars
function generatePassword(len = +lengthRange.value) {
const chars = getCharset();
if (!chars.length) return "";
let pwd = "";
for (let i = 0; i < len; i++) {
pwd += chars[Math.floor(Math.random() * chars.length)];
}
const stats = calcEntropy(pwd, chars.length);
return { pwd, stats };
}
// Calculate entropy (bits) and determine a simple strength label
function calcEntropy(password, poolSize) {
// bits = length * log2(poolSize)
// If poolSize not passed (for per-password estimation), compute from present categories
if (!poolSize) {
const pools = [
/[A-Z]/.test(password) ? 26 : 0,
/[a-z]/.test(password) ? 26 : 0,
/[0-9]/.test(password) ? 10 : 0,
/[^A-Za-z0-9]/.test(password) ? 32 : 0,
];
poolSize = pools.reduce((a, b) => a + b, 0) || 1;
}
const bits = +(password.length * Math.log2(poolSize)).toFixed(2);
// strength buckets (very rough)
let strength = "Weak";
if (bits >= 80) strength = "Excellent";
else if (bits >= 60) strength = "Strong";
else if (bits >= 40) strength = "Good";
else if (bits >= 24) strength = "Fair";
return { bits, strength };
}
// update UI for a password card
function setPasswordCard(index, pwdObj) {
const input = passwordInputs[index];
const bitsEl = bitsEls[index];
const strText = strTextEls[index];
input.value = pwdObj.pwd;
const { bits, strength } = pwdObj.stats;
bitsEl.textContent = bits;
strText.textContent = strength;
// update global meter using the first card's metrics (visual)
updateGlobalMeter(bits, strength);
// save to history
pushHistory({ password: pwdObj.pwd, bits, strength, ts: Date.now() });
}
function updateGlobalMeter(bits, strength) {
const maxBits = 128; // for visual scale
const pct = Math.min(1, bits / maxBits);
meterBar.style.transform = `scaleX(${pct})`;
meterBar.style.opacity = 0.95;
globalEntropy.textContent = bits;
globalStrength.textContent = strength;
meterBar.setAttribute("aria-valuenow", bits);
}
// Copy helper
async function copyToClipboard(text, btn) {
try {
await navigator.clipboard.writeText(text);
btn.textContent = "β
";
setTimeout(() => (btn.textContent = "π"), 1000);
} catch (e) {
// fallback select
const ta = document.createElement("textarea");
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
btn.textContent = "β
";
setTimeout(() => (btn.textContent = "π"), 1000);
}
}
// Download helper
function downloadText(filename, content) {
const blob = new Blob([content], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
/* ---------- History (localStorage) ---------- */
function loadHistory() {
try {
const raw = localStorage.getItem(HISTORY_KEY);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function saveHistory(arr) {
localStorage.setItem(HISTORY_KEY, JSON.stringify(arr));
}
function pushHistory(entry) {
// keep latest 50
const hist = loadHistory();
hist.unshift(entry);
while (hist.length > 50) hist.pop();
saveHistory(hist);
renderHistory();
}
function renderHistory() {
const hist = loadHistory();
historyList.innerHTML = "";
if (!hist.length) {
const li = document.createElement("li");
li.className = "history-item";
li.innerHTML = `<div class="left" style="color:var(--muted)">No saved passwords yet β generated items appear here (masked).</div>`;
historyList.appendChild(li);
return;
}
hist.forEach((h, idx) => {
const li = document.createElement("li");
li.className = "history-item";
// masked preview (first/last 2 chars)
const pw = h.password || "";
const masked = pw.length > 4 ? pw.slice(0,2) + "β¦" + pw.slice(-2) : "β’".repeat(Math.max(1,pw.length));
const time = new Date(h.ts).toLocaleString();
li.innerHTML = `
<div class="left">
<div><strong>${masked}</strong> <span style="color:var(--muted);font-size:0.8rem">Β· ${h.bits} bits Β· ${h.strength}</span></div>
<div style="color:var(--muted);font-size:0.8rem">${time}</div>
</div>
<div class="right">
<button class="reveal-h" title="Reveal" aria-label="Reveal password">π</button>
<button class="copy-h" title="Copy" aria-label="Copy password">π</button>
<button class="dl-h" title="Download" aria-label="Download password">β¬οΈ</button>
<button class="del-h" title="Delete" aria-label="Delete history item">π</button>
</div>
`;
// attach handlers
li.querySelector(".reveal-h").addEventListener("click", () => {
alert(`Password (full):\n\n${pw}`);
});
li.querySelector(".copy-h").addEventListener("click", () => copyToClipboard(pw, li.querySelector(".copy-h")));
li.querySelector(".dl-h").addEventListener("click", () => downloadText(`GenPassX_pwd_${idx+1}.txt`, pw));
li.querySelector(".del-h").addEventListener("click", () => {
const arr = loadHistory();
arr.splice(idx,1);
saveHistory(arr);
renderHistory();
});
historyList.appendChild(li);
});
}
/* ---------- Events ---------- */
// Generate for all cards
function generateAllCards() {
// For each password-input, create a pwd and set UI
passwordInputs.forEach((input, i) => {
const { pwd, stats } = generatePassword().pwd ? generatePassword() : { pwd: "", stats: { bits: 0, strength: "Weak" } };
// note: generatePassword returns {pwd, stats}
const res = typeof pwd === "object" ? pwd : { pwd, stats }; // compat
// fix: call once
const generated = generatePassword();
setPasswordCard(i, generated);
});
}
generateBtn.addEventListener("click", () => {
// only accept when at least one charset selected
if (getCharset().length === 0) {
alert("Please enable at least one character set (uppercase/lowercase/numbers/symbols).");
return;
}
// populate each card
passwordInputs.forEach((input, idx) => {
const { pwd, stats } = generatePassword();
setPasswordCard(idx, { pwd, stats });
});
});
// per-card regen / copy / download wiring
regenButtons.forEach((btn, idx) => {
btn.addEventListener("click", () => {
const { pwd, stats } = generatePassword();
setPasswordCard(idx, { pwd, stats });
});
});
copyButtons.forEach((btn, idx) => {
btn.addEventListener("click", () => {
const val = passwordInputs[idx].value;
if (!val) return;
copyToClipboard(val, btn);
});
});
downloadButtons.forEach((btn, idx) => {
btn.addEventListener("click", () => {
const val = passwordInputs[idx].value;
if (!val) return;
downloadText(`GenPassX_password_${idx+1}.txt`, val);
});
});
// show/hide toggle
showPasswords.addEventListener("change", () => {
const type = showPasswords.checked ? "text" : "password";
passwordInputs.forEach(inp => inp.type = type);
});
// download all (only non-empty ones)
downloadAllBtn.addEventListener("click", () => {
const lines = Array.from(passwordInputs).map((inp, i) => {
const v = inp.value || "";
return `Password ${i+1}: ${v}`;
}).filter(Boolean);
if (!lines.length) { alert("No passwords to download."); return; }
downloadText("GenPassX_Passwords.txt", lines.join("\n"));
});
// clear
clearBtn.addEventListener("click", () => {
passwordInputs.forEach(inp => inp.value = "");
// reset meter
updateGlobalMeter(0, "β");
});
// theme toggle
themeToggle.addEventListener("click", () => {
const isLight = document.body.classList.toggle("light");
themeToggle.setAttribute("aria-pressed", String(isLight));
themeToggle.textContent = isLight ? "βοΈ" : "π";
});
// Auto regenerate
let autoTimer = null;
autoRegenerate.addEventListener("change", () => {
if (autoRegenerate.checked) {
// safety: ensure charset exists
if (getCharset().length === 0) { alert("Please enable at least one character set for auto-regenerate."); autoRegenerate.checked = false; return; }
autoTimer = setInterval(() => {
if (autoRegenerate.checked) {
generateBtn.click();
}
}, AUTO_INTERVAL);
} else {
if (autoTimer) clearInterval(autoTimer);
}
});
/* ---------- Initialization ---------- */
(function init() {
lengthValue.textContent = lengthRange.value;
renderHistory();
// initial empty meter
updateGlobalMeter(0, "β");
// keyboard accessible: space/enter on generate button triggers click (browsers do this by default for buttons)
})();