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 form.submit();
59}
60
61// Decides per submit whether to encrypt in the browser (client mode) or let the
62// form POST normally so the server encrypts (server mode / no password).
63function onUploadSubmit(): boolean {
64 const passwordInput = document.getElementById(
65 "password",
66 ) as HTMLInputElement | null;
67 if (getMode("encrypt_mode") === "client" && passwordInput?.value) {
68 uploadFile();
69 return false;
70 }
71 return true;
72}
73
74// reset() first: it reverts controls to their HTML defaults (incl. the radios),
75// so apply the saved mode preference afterwards.
76(document.getElementById("uploadForm") as HTMLFormElement | null)?.reset();
77setupModeRadios("encrypt_mode");
78Object.assign(window, { uploadFile });
79Object.assign(window, { onUploadSubmit });
80//disable bfcache, otherwise dialog will stay open when navigating back
81window.addEventListener("unload", () => {});
82window.addEventListener("beforeunload", () => {});
83