Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
581 lines (508 loc) · 16.6 KB
/
Copy pathmain.js
File metadata and controls
581 lines (508 loc) · 16.6 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
// Extremely simple client-side PGP encryptor using OpenPGP.js
// All operations happen in the browser; no data is sent to a server.
let defaultPublicKeyArmored = "";
let uploadedPublicKeyArmored = "";
let uploadedPrivateKeyArmored = "";
const PASSPHRASE_STORAGE_KEY = "pgpLitePrivatePassphrase";
function setStatus(message, kind) {
const statusElement = document.getElementById("statusMessage");
statusElement.textContent = message;
statusElement.classList.remove("status--ok", "status--error");
if (kind === "ok") {
statusElement.classList.add("status--ok");
} else if (kind === "error") {
statusElement.classList.add("status--error");
}
}
function usePublicKeySource() {
const keyModeSelect = document.getElementById("keyModeSelect");
if (keyModeSelect && keyModeSelect.value !== "uploaded") {
keyModeSelect.value = "uploaded";
}
}
async function handleKeyUpload(event) {
const input = event.target;
const infoElement = document.getElementById("uploadedKeyInfo");
if (!input.files || input.files.length === 0) {
uploadedPublicKeyArmored = "";
infoElement.textContent = "No public key file selected yet.";
return;
}
const file = input.files[0];
try {
const text = await file.text();
if (!text.includes("BEGIN PGP PUBLIC KEY BLOCK")) {
uploadedPublicKeyArmored = "";
infoElement.textContent = "File does not look like a PGP public key.";
return;
}
uploadedPublicKeyArmored = text;
infoElement.textContent = `Loaded key from: ${file.name}`;
usePublicKeySource();
} catch (error) {
uploadedPublicKeyArmored = "";
infoElement.textContent = "Failed to read key file.";
}
}
function handleKeyPaste(event) {
const text = event.target.value;
const infoElement = document.getElementById("uploadedKeyInfo");
if (!text.trim()) {
uploadedPublicKeyArmored = "";
infoElement.textContent = "No public key pasted yet.";
return;
}
if (!text.includes("BEGIN PGP PUBLIC KEY BLOCK")) {
uploadedPublicKeyArmored = "";
infoElement.textContent = "Pasted text does not look like a PGP public key.";
return;
}
uploadedPublicKeyArmored = text;
infoElement.textContent = "Loaded pasted public key.";
usePublicKeySource();
}
async function handlePrivateKeyUpload(event) {
const input = event.target;
const infoElement = document.getElementById("uploadedPrivateKeyInfo");
if (!input.files || input.files.length === 0) {
uploadedPrivateKeyArmored = "";
infoElement.textContent = "No private key file selected yet.";
return;
}
const file = input.files[0];
try {
const text = await file.text();
if (!text.includes("BEGIN PGP PRIVATE KEY BLOCK")) {
uploadedPrivateKeyArmored = "";
infoElement.textContent = "File does not look like a PGP private key.";
return;
}
uploadedPrivateKeyArmored = text;
infoElement.textContent = `Loaded private key from: ${file.name}`;
} catch (error) {
uploadedPrivateKeyArmored = "";
infoElement.textContent = "Failed to read private key file.";
}
}
function handlePrivateKeyPaste(event) {
const text = event.target.value;
const infoElement = document.getElementById("uploadedPrivateKeyInfo");
if (!text.trim()) {
uploadedPrivateKeyArmored = "";
infoElement.textContent = "No private key pasted yet.";
return;
}
if (!text.includes("BEGIN PGP PRIVATE KEY BLOCK")) {
uploadedPrivateKeyArmored = "";
infoElement.textContent =
"Pasted text does not look like a PGP private key.";
return;
}
uploadedPrivateKeyArmored = text;
infoElement.textContent = "Loaded pasted private key.";
}
// Switching between the "Upload file" and "Paste key" panes clears whichever
// input is being left so only one source is ever active for a key.
function wireUpInputToggle(toggleElement, onPaneChange) {
const options = Array.from(
toggleElement.querySelectorAll(".input-toggle__option"),
);
options.forEach((option) => {
option.addEventListener("click", () => {
if (option.classList.contains("is-active")) {
return;
}
options.forEach((other) => {
const isActive = other === option;
other.classList.toggle("is-active", isActive);
other.setAttribute("aria-selected", isActive ? "true" : "false");
const pane = document.getElementById(other.dataset.pane);
if (pane) {
pane.hidden = !isActive;
}
});
onPaneChange(option.dataset.pane);
});
});
}
async function encryptCurrentText() {
if (typeof window.openpgp === "undefined") {
setStatus("OpenPGP.js failed to load.", "error");
return;
}
const plaintextElement = document.getElementById("plaintextInput");
const keyModeSelect = document.getElementById("keyModeSelect");
const plaintext = plaintextElement.value;
if (!plaintext.trim()) {
setStatus("Please enter some text to encrypt.", "error");
return;
}
const useUploaded = keyModeSelect.value === "uploaded";
let armoredKey = "";
if (useUploaded) {
if (!uploadedPublicKeyArmored) {
setStatus(
"You chose your own public key, but none is provided yet.",
"error",
);
return;
}
armoredKey = uploadedPublicKeyArmored;
} else {
if (!defaultPublicKeyArmored) {
setStatus(
"No default public key is loaded. Provide your own public key instead.",
"error",
);
return;
}
armoredKey = defaultPublicKeyArmored;
}
setStatus("Encrypting...", "");
try {
const publicKey = await window.openpgp.readKey({ armoredKey });
const message = await window.openpgp.createMessage({ text: plaintext });
const encrypted = await window.openpgp.encrypt({
message,
encryptionKeys: publicKey,
});
plaintextElement.value = encrypted;
setStatus("Encryption complete.", "ok");
updateActionButtonsBasedOnText();
} catch (error) {
setStatus("Failed to encrypt. Check that the public key is valid.", "error");
}
}
async function decryptCurrentText() {
if (typeof window.openpgp === "undefined") {
setStatus("OpenPGP.js failed to load.", "error");
return;
}
const textElement = document.getElementById("plaintextInput");
const passphraseElement = document.getElementById("privateKeyPassphrase");
const ciphertext = textElement.value;
if (!ciphertext.trim()) {
setStatus("Please paste an encrypted PGP message to decrypt.", "error");
return;
}
if (!uploadedPrivateKeyArmored) {
setStatus("Provide a private key before decrypting.", "error");
return;
}
setStatus("Decrypting...", "");
try {
const privateKey = await window.openpgp.readPrivateKey({
armoredKey: uploadedPrivateKeyArmored,
});
const passphrase = passphraseElement.value;
let decryptionKey = privateKey;
if (passphrase.trim()) {
try {
decryptionKey = await window.openpgp.decryptKey({
privateKey,
passphrase,
});
} catch (error) {
setStatus("Failed to unlock private key. Check your passphrase.", "error");
return;
}
}
const message = await window.openpgp.readMessage({
armoredMessage: ciphertext,
});
const decrypted = await window.openpgp.decrypt({
message,
decryptionKeys: decryptionKey,
});
textElement.value = decrypted.data;
setStatus("Decryption complete.", "ok");
updateActionButtonsBasedOnText();
} catch (error) {
setStatus(
"Failed to decrypt. Check that the private key, passphrase, and message match.",
"error",
);
}
}
async function copyCiphertext() {
const textElement = document.getElementById("plaintextInput");
const value = textElement.value;
if (!value.trim()) {
setStatus("Nothing to copy yet.", "error");
return;
}
try {
await navigator.clipboard.writeText(value);
setStatus("Text copied to clipboard.", "ok");
} catch (error) {
setStatus("Could not access clipboard. Copy manually.", "error");
}
}
function sanitizeForFilename(value) {
const trimmed = value.trim();
if (!trimmed) {
return "key";
}
return trimmed
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64);
}
function downloadTextFile(filename, text) {
const blob = new Blob([text], { type: "application/pgp-keys" });
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
}
async function generateAndDownloadKeypair() {
const statusElement = document.getElementById("keyGenStatus");
const setKeyGenStatus = (message, kind) => {
if (!statusElement) {
return;
}
statusElement.textContent = message;
statusElement.classList.remove("status--ok", "status--error");
if (kind === "ok") {
statusElement.classList.add("status--ok");
} else if (kind === "error") {
statusElement.classList.add("status--error");
}
};
if (typeof window.openpgp === "undefined") {
setKeyGenStatus("OpenPGP.js failed to load.", "error");
return;
}
const nameInput = document.getElementById("keyGenName");
const emailInput = document.getElementById("keyGenEmail");
const passphraseInput = document.getElementById("keyGenPassphrase");
const name = nameInput.value.trim();
const email = emailInput.value.trim();
const passphrase = passphraseInput.value;
if (!name && !email) {
setKeyGenStatus("Enter a name or email to generate a keypair.", "error");
return;
}
setKeyGenStatus("Generating keypair...", "");
try {
const userIDs =
name || email
? [
{
name: name || undefined,
email: email || undefined,
},
]
: [];
const generated = await window.openpgp.generateKey({
type: "rsa",
rsaBits: 4096,
userIDs,
passphrase: passphrase || undefined,
});
const baseName = sanitizeForFilename(email || name || "key");
downloadTextFile(`${baseName}-public.asc`, generated.publicKey);
downloadTextFile(`${baseName}-private.asc`, generated.privateKey);
setKeyGenStatus("Keypair generated and downloads started.", "ok");
} catch (error) {
setKeyGenStatus("Failed to generate keypair.", "error");
}
}
function syncStoredPassphrase() {
const passphraseElement = document.getElementById("privateKeyPassphrase");
const rememberCheckbox = document.getElementById("rememberPassphraseCheckbox");
if (!passphraseElement || !rememberCheckbox) {
return;
}
try {
if (rememberCheckbox.checked && passphraseElement.value) {
window.localStorage.setItem(
PASSPHRASE_STORAGE_KEY,
passphraseElement.value,
);
} else {
window.localStorage.removeItem(PASSPHRASE_STORAGE_KEY);
}
} catch (error) {
// Ignore localStorage errors (e.g., disabled or unavailable).
}
}
function isLikelyPgpMessage(text) {
if (!text) {
return false;
}
const trimmedStart = text.replace(/^\s+/, "");
return trimmedStart.startsWith("-----BEGIN PGP") && trimmedStart.includes("-----END PGP");
}
function updateActionButtonsBasedOnText() {
const plaintextElement = document.getElementById("plaintextInput");
const actionButton = document.getElementById("actionButton");
const copyButton = document.getElementById("copyButton");
if (!plaintextElement || !actionButton) {
return;
}
const text = plaintextElement.value;
const looksLikePgp = isLikelyPgpMessage(text);
if (looksLikePgp) {
actionButton.textContent = "Decrypt";
actionButton.classList.add("button--primary");
actionButton.classList.remove("button--ghost");
if (copyButton) {
copyButton.textContent = "Copy text";
}
} else {
actionButton.textContent = "Encrypt";
actionButton.classList.add("button--primary");
actionButton.classList.remove("button--ghost");
if (copyButton) {
copyButton.textContent = "Copy text";
}
}
}
async function loadDefaultPublicKey() {
try {
const response = await fetch("default-public-key.asc", {
cache: "no-store",
});
if (!response.ok) {
setStatus(
"No default public key file found. Provide your own public key instead.",
"error",
);
return;
}
const text = await response.text();
if (!text.includes("BEGIN PGP PUBLIC KEY BLOCK")) {
setStatus(
"Default public key file is not a valid PGP public key.",
"error",
);
return;
}
defaultPublicKeyArmored = text;
const previewElement = document.getElementById("defaultKeyPreview");
if (previewElement) {
previewElement.textContent = defaultPublicKeyArmored;
}
} catch (error) {
setStatus(
"Could not load default public key file. Provide your own public key instead.",
"error",
);
}
}
function wireUpEvents() {
const fileInput = document.getElementById("publicKeyFile");
const privateKeyFileInput = document.getElementById("privateKeyFile");
const actionButton = document.getElementById("actionButton");
const copyButton = document.getElementById("copyButton");
const plaintextElement = document.getElementById("plaintextInput");
const passphraseElement = document.getElementById("privateKeyPassphrase");
const rememberCheckbox = document.getElementById("rememberPassphraseCheckbox");
const generateKeypairButton = document.getElementById(
"generateKeypairButton",
);
const publicKeyTextarea = document.getElementById("publicKeyText");
const privateKeyTextarea = document.getElementById("privateKeyText");
const publicKeyToggle = document.querySelector(
'.input-toggle[aria-label="Public key input method"]',
);
const privateKeyToggle = document.querySelector(
'.input-toggle[aria-label="Private key input method"]',
);
fileInput.addEventListener("change", handleKeyUpload);
privateKeyFileInput.addEventListener("change", handlePrivateKeyUpload);
if (publicKeyTextarea) {
publicKeyTextarea.addEventListener("input", handleKeyPaste);
}
if (privateKeyTextarea) {
privateKeyTextarea.addEventListener("input", handlePrivateKeyPaste);
}
if (publicKeyToggle) {
wireUpInputToggle(publicKeyToggle, (activePane) => {
uploadedPublicKeyArmored = "";
fileInput.value = "";
if (publicKeyTextarea) {
publicKeyTextarea.value = "";
}
document.getElementById("uploadedKeyInfo").textContent =
activePane === "publicKeyPastePane"
? "No public key pasted yet."
: "No public key file selected yet.";
if (activePane === "publicKeyPastePane" && publicKeyTextarea) {
publicKeyTextarea.focus();
}
});
}
if (privateKeyToggle) {
wireUpInputToggle(privateKeyToggle, (activePane) => {
uploadedPrivateKeyArmored = "";
privateKeyFileInput.value = "";
if (privateKeyTextarea) {
privateKeyTextarea.value = "";
}
document.getElementById("uploadedPrivateKeyInfo").textContent =
activePane === "privateKeyPastePane"
? "No private key pasted yet."
: "No private key file selected yet.";
if (activePane === "privateKeyPastePane" && privateKeyTextarea) {
privateKeyTextarea.focus();
}
});
}
actionButton.addEventListener("click", () => {
const text = plaintextElement ? plaintextElement.value : "";
const looksLikePgp = isLikelyPgpMessage(text);
if (looksLikePgp) {
void decryptCurrentText();
} else {
void encryptCurrentText();
}
});
copyButton.addEventListener("click", () => {
void copyCiphertext();
});
plaintextElement.addEventListener("input", () => {
updateActionButtonsBasedOnText();
});
if (passphraseElement) {
passphraseElement.addEventListener("input", () => {
syncStoredPassphrase();
});
}
if (rememberCheckbox) {
rememberCheckbox.addEventListener("change", () => {
syncStoredPassphrase();
});
}
if (generateKeypairButton) {
generateKeypairButton.addEventListener("click", () => {
void generateAndDownloadKeypair();
});
}
}
document.addEventListener("DOMContentLoaded", () => {
void loadDefaultPublicKey();
wireUpEvents();
try {
const storedPassphrase = window.localStorage.getItem(
PASSPHRASE_STORAGE_KEY,
);
const passphraseElement = document.getElementById("privateKeyPassphrase");
const rememberCheckbox = document.getElementById(
"rememberPassphraseCheckbox",
);
if (storedPassphrase && passphraseElement && rememberCheckbox) {
passphraseElement.value = storedPassphrase;
rememberCheckbox.checked = true;
}
} catch (error) {
// Ignore localStorage errors (e.g., disabled or unavailable).
}
updateActionButtonsBasedOnText();
});