client-index.ts
Raw
1import { encrypt } from "./crypto";
2import { getMode, setupModeRadios } from "./shared";
3
4async function uploadFile() {
5 (
6 document.getElementById("upload-dialog") as HTMLDialogElement | null
7 )?.showModal();
8 const passwordInput = document.getElementById(
9 "password",
10 ) as HTMLInputElement | null;
11 const fileInput = document.getElementById("file") as HTMLInputElement | null;
12 const filenameInput = document.getElementById(
13 "filename",
14 ) as HTMLInputElement | null;
15 const encryptedInput = document.getElementById(
16 "encrypted",
17 ) as HTMLInputElement | null;
18 const form = document.getElementById("uploadForm") as HTMLFormElement | null;
19
20 if (
21 !passwordInput ||
22 !fileInput ||
23 !filenameInput ||
24 !encryptedInput ||
25 !form
26 ) {
27 console.error("Missing required elements.");
28 console.error(
29 passwordInput,
30 fileInput,
31 filenameInput,
32 encryptedInput,
33 form,
34 );
35 return;
36 }
37
38 const password = passwordInput.value;
39 if (!password) {
40 form.submit();
41 return;
42 }
43
44 const file = fileInput.files?.[0];
45 if (!file) {
46 return;
47 }
48
49 const content = await file.arrayBuffer();
50 const encryptedContent = await encrypt(new Uint8Array(content), password);
51
52 const myFile = new File([encryptedContent as BlobPart], file.name);
53 const dataTransfer = new DataTransfer();
54 dataTransfer.items.add(myFile);
55
56 fileInput.files = dataTransfer.files;
57 encryptedInput.checked = true;
58 console.log("encryption done");
59 form.submit();
60}
61
62// Decides per submit whether to encrypt in the browser (client mode) or let the
63// form POST normally so the server encrypts (server mode / no password).
64function onUploadSubmit(): boolean {
65 const passwordInput = document.getElementById(
66 "password",
67 ) as HTMLInputElement | null;
68 if (getMode("encrypt_mode") === "client" && passwordInput?.value) {
69 uploadFile();
70 return false;
71 }
72 return true;
73}
74
75// reset() first: it reverts controls to their HTML defaults (incl. the radios),
76// so apply the saved mode preference afterwards.
77(document.getElementById("uploadForm") as HTMLFormElement | null)?.reset();
78setupModeRadios("encrypt_mode");
79Object.assign(window, { uploadFile });
80Object.assign(window, { onUploadSubmit });
81//disable bfcache, otherwise dialog will stay open when navigating back
82window.addEventListener("unload", () => {});
83window.addEventListener("beforeunload", () => {});
84