diff --git a/.env.example b/.env.example index f2f6f4d..f37b417 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,3 @@ DATABASE_PATH="__vces/vces.db" -FILE_UPLOAD_PATH="__vces/uploads" \ No newline at end of file +FILE_UPLOAD_PATH="__vces/uploads" +MAX_UPLOAD_SIZE=1073741824 diff --git a/deno.json b/deno.json index 44c4bdd..e06275a 100644 --- a/deno.json +++ b/deno.json @@ -24,6 +24,7 @@ "@paulaboks/boksy": "jsr:@paulaboks/boksy@^0.4.2", "@std/cli": "jsr:@std/cli@^1.0.32", "@std/dotenv": "jsr:@std/dotenv@^0.225.8", + "@std/path": "jsr:@std/path@^1.1.6", "@std/ulid": "jsr:@std/ulid@^1.0.0", "@zod/zod": "jsr:@zod/zod@^4.6.7", "fresh": "jsr:@fresh/core@^2.3.3", diff --git a/deno.lock b/deno.lock index 3709f52..dbe9e10 100644 --- a/deno.lock +++ b/deno.lock @@ -31,6 +31,7 @@ "jsr:@std/path@^1.1.1": "1.1.6", "jsr:@std/path@^1.1.2": "1.1.6", "jsr:@std/path@^1.1.5": "1.1.6", + "jsr:@std/path@^1.1.6": "1.1.6", "jsr:@std/semver@^1.0.6": "1.0.8", "jsr:@std/ulid@1": "1.0.0", "jsr:@std/uuid@^1.0.9": "1.1.1", @@ -1518,6 +1519,7 @@ "jsr:@paulaboks/boksy@~0.4.2", "jsr:@std/cli@^1.0.32", "jsr:@std/dotenv@~0.225.8", + "jsr:@std/path@^1.1.6", "jsr:@std/ulid@1", "jsr:@zod/zod@^4.6.7", "npm:@preact/signals@^2.9.0", diff --git a/islands/Hub.tsx b/islands/Hub.tsx index fa94e62..8219415 100644 --- a/islands/Hub.tsx +++ b/islands/Hub.tsx @@ -1,35 +1,113 @@ -import { useSignal, useSignalEffect } from "@preact/signals"; +import { Signal, useSignal, useSignalEffect } from "@preact/signals"; import HubFileList, { type HubFile } from "@/islands/HubFileList.tsx"; -import HubUpload from "@/islands/HubUpload.tsx"; +import HubUpload, { type UploadState } from "@/islands/HubUpload.tsx"; +import { post_json } from "@/src/client.ts"; +import { decrypt_metadata, encrypt_file } from "@/src/file_crypto.ts"; +import type { FileEntry } from "@/src/files.ts"; +import { list_files, upload_file } from "@/src/files_api.ts"; +import { load_master_key } from "@/src/key_store.ts"; +import { type GetKeyResponse, verify_key_check } from "@/src/keys.ts"; function has_files(event: DragEvent) { return event.dataTransfer?.types.includes("Files") ?? false; } -export default function Hub() { +async function to_hub_file(master_key: CryptoKey, entry: FileEntry): Promise { + const metadata = await decrypt_metadata(master_key, entry.metadata).catch(() => null); + return { id: entry.id, uploaded_at: entry.date_created, stored_size: entry.size, metadata }; +} + +interface HubProps { + page: Signal; +} + +export default function Hub(props: HubProps) { + const master_key = useSignal(null); + const load_error = useSignal(""); const pending = useSignal([]); const files = useSignal([]); + const upload_state = useSignal(null); + const upload_error = useSignal(""); const dragging = useSignal(false); - function add_files(new_files: File[]) { - pending.value = [...pending.value, ...new_files]; + async function load() { + const code = localStorage.getItem("code"); + if (!code) { + props.page.value = "askcode"; + return; + } + + const account = await post_json("/api/get_key", { code }); + if (!account.ok) { + load_error.value = account.error; + return; + } + const key = await load_master_key(account.data.user_id).catch(() => undefined); + const key_check = account.data.key_check; + if (!key || !key_check || !(await verify_key_check(key, key_check))) { + props.page.value = "keysnew"; + return; + } + + const list = await list_files(); + if (!list.ok) { + load_error.value = list.error; + return; + } + files.value = await Promise.all(list.data.map((entry) => to_hub_file(key, entry))); + master_key.value = key; } - // TODO: encrypt with the master key and upload, the list only lives in memory until the API exists - function upload() { - const uploaded_at = Date.now(); - const uploaded = pending.value.map((file): HubFile => ({ - id: crypto.randomUUID(), - name: file.name, - size: file.size, - uploaded_at, - blob: file, - })); - files.value = [...uploaded.reverse(), ...files.value]; - pending.value = []; + function add_files(new_files: File[]) { + if (!upload_state.value) { + upload_error.value = ""; + pending.value = [...pending.value, ...new_files]; + } } + async function upload() { + const key = master_key.value; + if (!key || upload_state.value) { + return; + } + + const queue = pending.value; + const controller = new AbortController(); + upload_error.value = ""; + for (const [index, file] of queue.entries()) { + const state = { file, index, count: queue.length, progress: null, controller }; + upload_state.value = state; + try { + const encrypted = await encrypt_file(key, file); + if (controller.signal.aborted) { + break; + } + + const result = await upload_file(encrypted, (ratio) => { + upload_state.value = { ...state, progress: ratio }; + }, controller.signal); + if (!result.ok) { + if (!controller.signal.aborted) { + upload_error.value = `Couldn't upload ${file.name}: ${result.error}`; + } + break; + } + + files.value = [await to_hub_file(key, result.data), ...files.value]; + pending.value = pending.value.filter((pending_file) => pending_file !== file); + } catch (err) { + upload_error.value = `Couldn't upload ${file.name}: ${err instanceof Error ? err.message : err}`; + break; + } + } + upload_state.value = null; + } + + useSignalEffect(() => { + load(); + }); + // Files can be dropped anywhere on the page, not only on the upload area useSignalEffect(() => { function drag_over(event: DragEvent) { @@ -64,10 +142,23 @@ export default function Hub() { }; }); + if (!master_key.value) { + return load_error.value + ? + :

Loading...

; + } + return ( -
+
- +
diff --git a/islands/HubFileList.tsx b/islands/HubFileList.tsx index ec2b258..6e5afba 100644 --- a/islands/HubFileList.tsx +++ b/islands/HubFileList.tsx @@ -1,17 +1,19 @@ -import { Signal } from "@preact/signals"; +import { Signal, useSignal } from "@preact/signals"; import Button from "@/components/Button.tsx"; import FileInfo from "@/components/FileInfo.tsx"; import { CloseIcon, DownloadIcon } from "@/components/Icons.tsx"; +import type { FileMetadata } from "@/src/file_crypto.ts"; import { download_blob } from "@/src/files.ts"; +import { delete_file, download_file } from "@/src/files_api.ts"; export interface HubFile { id: string; - name: string; - size: number; - uploaded_at: number; - // TODO: replace with fetching and decrypting from the server once uploads exist - blob: Blob; + uploaded_at: string; + // Size of the encrypted file, shown when the metadata can't be read + stored_size: number; + // null when it can't be decrypted with this key + metadata: FileMetadata | null; } const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); @@ -21,8 +23,42 @@ interface HubFileListProps { } export default function HubFileList(props: HubFileListProps) { + const busy = useSignal<{ id: string; action: "download" | "delete" } | null>(null); + const error = useSignal(""); + + async function run(file: HubFile, action: "download" | "delete", fn: () => Promise) { + if (busy.value) { + return; + } + busy.value = { id: file.id, action }; + error.value = ""; + try { + await fn(); + } catch (err) { + error.value = err instanceof Error ? err.message : String(err); + } finally { + busy.value = null; + } + } + + function download(file: HubFile) { + const metadata = file.metadata; + if (metadata) { + run(file, "download", async () => download_blob(await download_file(file.id, metadata), metadata.name)); + } + } + function remove(file: HubFile) { - props.files.value = props.files.value.filter((other) => other.id !== file.id); + if (!confirm(`Delete "${file.metadata?.name ?? "this file"}"? This can't be undone.`)) { + return; + } + run(file, "delete", async () => { + const result = await delete_file(file.id); + if (!result.ok && result.status !== 404) { + throw new Error(result.error); + } + props.files.value = props.files.value.filter((other) => other.id !== file.id); + }); } if (props.files.value.length === 0) { @@ -42,6 +78,7 @@ export default function HubFileList(props: HubFileListProps) { Your files{" "} ({props.files.value.length}) + {error.value && }
    {props.files.value.map((file) => (
  • remove(file)} > } /> -
    - + {file.metadata && ( + <> +
    + + + )}
  • ))}
diff --git a/islands/HubUpload.tsx b/islands/HubUpload.tsx index 34143f2..a59b613 100644 --- a/islands/HubUpload.tsx +++ b/islands/HubUpload.tsx @@ -24,8 +24,45 @@ function FilePicker(props: FilePickerProps) { return ; } +export interface UploadState { + file: File; + index: number; + count: number; + // null while the file is being encrypted + progress: number | null; + controller: AbortController; +} + +interface UploadingProps { + state: UploadState; +} + +function Uploading({ state }: UploadingProps) { + const percent = Math.round((state.progress ?? 0) * 100); + return ( +
+ 1 ? `${state.index + 1} of ${state.count}` : undefined} + /> +

+ {state.progress === null ? "Encrypting..." : `Uploading ${percent}%`} +

+ + +
+ ); +} + interface HubUploadProps { pending: Signal; + upload_state: UploadState | null; + error: string; dragging: boolean; on_add: (files: File[]) => void; on_upload: () => void; @@ -38,6 +75,12 @@ export default function HubUpload(props: HubUploadProps) { props.pending.value = props.pending.value.filter((pending_file) => pending_file !== file); } + if (props.upload_state) { + return ; + } + + const error = props.error && ; + if (props.pending.value.length === 0) { return ( ); } @@ -100,6 +144,7 @@ export default function HubUpload(props: HubUploadProps) {

+ {error}
); } diff --git a/islands/MainIsland.tsx b/islands/MainIsland.tsx index 12b9450..0f8a7b6 100644 --- a/islands/MainIsland.tsx +++ b/islands/MainIsland.tsx @@ -12,7 +12,7 @@ export default function MainIsland() { } else if (page.value === "keysnew") { return ; } else if (page.value === "hub") { - return ; + return ; } else { return "Error"; } diff --git a/routes/api/files/[id].ts b/routes/api/files/[id].ts new file mode 100644 index 0000000..911dc6c --- /dev/null +++ b/routes/api/files/[id].ts @@ -0,0 +1,48 @@ +import { define } from "@/utils.ts"; +import { authenticate, unauthorized } from "@/src/auth.ts"; +import { db, type FileRow } from "@/src/db.ts"; +import { delete_upload, open_upload } from "@/src/storage.ts"; + +const not_found = () => Response.json({ error: "File not found" }, { status: 404 }); + +export const handler = define.handlers({ + // Streams the encrypted file, the client decrypts it + async GET(ctx) { + const user = await authenticate(ctx.req); + if (!user) { + return unauthorized(); + } + + const file = await db.get_entry("files", ctx.params.id) as FileRow | undefined; + if (!file || file.user_id !== user.id) { + return not_found(); + } + + const stored = await open_upload(file.storage_id).catch(() => undefined); + if (!stored) { + return not_found(); + } + return new Response(stored.readable, { + headers: { + "Content-Type": "application/octet-stream", + "Cache-Control": "no-store", + }, + }); + }, + + async DELETE(ctx) { + const user = await authenticate(ctx.req); + if (!user) { + return unauthorized(); + } + + const file = await db.get_entry("files", ctx.params.id) as FileRow | undefined; + if (!file || file.user_id !== user.id) { + return not_found(); + } + + await db.delete_entry("files", file); + await delete_upload(file.storage_id); + return new Response(null, { status: 204 }); + }, +}); diff --git a/routes/api/files/index.ts b/routes/api/files/index.ts new file mode 100644 index 0000000..8dd0038 --- /dev/null +++ b/routes/api/files/index.ts @@ -0,0 +1,78 @@ +import { z } from "@zod/zod"; + +import { define } from "@/utils.ts"; +import { authenticate, unauthorized } from "@/src/auth.ts"; +import { db, type FileRow } from "@/src/db.ts"; +import type { FileEntry } from "@/src/files.ts"; +import { MAX_UPLOAD_SIZE } from "@/src/server_constants.ts"; +import { delete_upload, save_upload, UploadTooLargeError } from "@/src/storage.ts"; + +const Metadata = z.base64().min(1).max(4096); + +const too_large = () => Response.json({ error: "The file is too large" }, { status: 413 }); + +export const handler = define.handlers({ + async GET(ctx) { + const user = await authenticate(ctx.req); + if (!user) { + return unauthorized(); + } + + const files = await db.get_entries_by_index("files", "user_id", user.id) as FileRow[]; + return Response.json( + files.map((file): FileEntry => ({ + id: file.id, + date_created: file.date_created, + size: file.size, + metadata: file.metadata, + })).reverse(), + ); + }, + + // The body is the encrypted file, its encrypted metadata goes in the X-File-Metadata header + async POST(ctx) { + const user = await authenticate(ctx.req); + if (!user) { + return unauthorized(); + } + + const metadata = Metadata.safeParse(ctx.req.headers.get("X-File-Metadata")); + if (!metadata.success || !ctx.req.body) { + return Response.json({ error: "Invalid request" }, { status: 400 }); + } + if (Number(ctx.req.headers.get("Content-Length")) > MAX_UPLOAD_SIZE) { + return too_large(); + } + + let saved; + try { + saved = await save_upload(ctx.req.body, MAX_UPLOAD_SIZE); + } catch (err) { + if (err instanceof UploadTooLargeError) { + return too_large(); + } + throw err; + } + + try { + const file = await db.create_entry("files", { + user_id: user.id, + storage_id: saved.storage_id, + size: saved.size, + metadata: metadata.data, + }); + return Response.json( + { + id: file.id, + date_created: file.date_created, + size: file.size, + metadata: file.metadata, + } satisfies FileEntry, + { status: 201 }, + ); + } catch (err) { + await delete_upload(saved.storage_id); + throw err; + } + }, +}); diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..53ba417 --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,14 @@ +import { db } from "./db.ts"; + +// Reads the user's code from an "Authorization: Bearer " header +export async function authenticate(req: Request) { + const code = req.headers.get("Authorization")?.match(/^Bearer (\S+)$/)?.[1]; + if (!code) { + return undefined; + } + return await db.get_entry_by_index("users", "code", code); +} + +export function unauthorized() { + return Response.json({ error: "Invalid code" }, { status: 401 }); +} diff --git a/src/client.ts b/src/client.ts index 97e853d..19a0d7e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -3,14 +3,10 @@ export type PostJsonResult = // status is 0 when the request never reached the server | { ok: false; status: number; error: string }; -export async function post_json(url: string, body: unknown, method = "POST"): Promise> { +export async function fetch_json(url: string, init: RequestInit): Promise> { let response: Response; try { - response = await fetch(url, { - method, - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); + response = await fetch(url, init); } catch (err) { return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) }; } @@ -25,3 +21,11 @@ export async function post_json(url: string, body: unknown, method = "POST"): } return { ok: true, data: data as T }; } + +export function post_json(url: string, body: unknown, method = "POST"): Promise> { + return fetch_json(url, { + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} diff --git a/src/db.ts b/src/db.ts index e05e94a..aa39647 100644 --- a/src/db.ts +++ b/src/db.ts @@ -1,4 +1,4 @@ -import { Database } from "@paulaboks/boksy"; +import { Database, type Model } from "@paulaboks/boksy"; import { DATABASE_PATH } from "@/src/server_constants.ts"; import type { PassphraseBackup } from "@/src/keys.ts"; @@ -11,10 +11,25 @@ export interface User extends Record { passphrase_backup?: PassphraseBackup; } +export interface StoredFile extends Record { + user_id: string; + // Name of the encrypted file inside FILE_UPLOAD_PATH + storage_id: string; + // Size of the encrypted file + size: number; + // Encrypted by the client, holds the name, type and file key + metadata: string; +} + +// boksy's partial entry types lose the field types +export type FileRow = Model & StoredFile; + type Schema = { users: User; + files: StoredFile; }; export const db = await Database.open(DATABASE_PATH ?? ":memory:", { users: ["code"], + files: ["user_id"], }); diff --git a/src/file_crypto.ts b/src/file_crypto.ts new file mode 100644 index 0000000..0032c20 --- /dev/null +++ b/src/file_crypto.ts @@ -0,0 +1,156 @@ +import { concat, from_base64, to_base64 } from "./keys.ts"; + +// Plaintext bytes per encrypted chunk, every chunk gets its own 16 byte tag +const CHUNK_SIZE = 1024 * 1024; +const TAG_LENGTH = 16; +const IV_LENGTH = 12; +const METADATA_VERSION = 1; +const METADATA_AAD = new TextEncoder().encode("vces-file-metadata-v1"); + +export interface FileMetadata { + name: string; + type: string; + size: number; + chunk_size: number; + key: CryptoKey; +} + +export interface EncryptedFile { + metadata: string; + body: Blob; +} + +// Each file has its own key, so the chunk index works as the IV. The last byte marks the final chunk +// so a truncated file fails to decrypt +function chunk_iv(index: number, last: boolean) { + const iv = new Uint8Array(IV_LENGTH); + new DataView(iv.buffer).setUint32(7, index); + iv[11] = last ? 1 : 0; + return iv; +} + +async function encrypt_metadata(master_key: CryptoKey, metadata: Record) { + const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH)); + const plaintext = new TextEncoder().encode(JSON.stringify(metadata)); + const ciphertext = await crypto.subtle.encrypt( + { name: "AES-GCM", iv, additionalData: METADATA_AAD }, + master_key, + plaintext, + ); + plaintext.fill(0); + return to_base64(concat(iv, new Uint8Array(ciphertext))); +} + +// Throws if the metadata wasn't encrypted with this master key +export async function decrypt_metadata(master_key: CryptoKey, metadata: string): Promise { + const bytes = from_base64(metadata); + const plaintext = await crypto.subtle.decrypt( + { name: "AES-GCM", iv: bytes.slice(0, IV_LENGTH), additionalData: METADATA_AAD }, + master_key, + bytes.slice(IV_LENGTH), + ); + const data = JSON.parse(new TextDecoder().decode(plaintext)); + if ( + data.version !== METADATA_VERSION || typeof data.name !== "string" || typeof data.type !== "string" || + !Number.isSafeInteger(data.size) || !Number.isSafeInteger(data.chunk_size) || typeof data.key !== "string" + ) { + throw new Error("Unsupported file metadata"); + } + + const raw_key = from_base64(data.key); + const key = await crypto.subtle.importKey("raw", raw_key, "AES-GCM", false, ["decrypt"]); + raw_key.fill(0); + return { name: data.name, type: data.type, size: data.size, chunk_size: data.chunk_size, key }; +} + +export async function encrypt_file( + master_key: CryptoKey, + file: File, + on_progress?: (ratio: number) => void, +): Promise { + const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"]); + const raw_key = new Uint8Array(await crypto.subtle.exportKey("raw", key)); + const metadata = await encrypt_metadata(master_key, { + version: METADATA_VERSION, + name: file.name, + type: file.type, + size: file.size, + chunk_size: CHUNK_SIZE, + key: to_base64(raw_key), + }); + raw_key.fill(0); + + // Empty files still get one chunk, so the last chunk flag is always checked + const parts: ArrayBuffer[] = []; + for (let index = 0, start = 0;; index++, start += CHUNK_SIZE) { + const end = Math.min(start + CHUNK_SIZE, file.size); + const last = end >= file.size; + const plaintext = await file.slice(start, end).arrayBuffer(); + parts.push(await crypto.subtle.encrypt({ name: "AES-GCM", iv: chunk_iv(index, last) }, key, plaintext)); + on_progress?.(file.size ? end / file.size : 1); + if (last) { + break; + } + } + + return { metadata, body: new Blob(parts, { type: "application/octet-stream" }) }; +} + +function join(chunks: Uint8Array[], length: number) { + const joined = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + joined.set(chunk, offset); + offset += chunk.length; + } + return joined; +} + +// Throws if the file was modified, truncated or doesn't match its metadata +export async function decrypt_file(metadata: FileMetadata, body: ReadableStream): Promise { + const encrypted_chunk_size = metadata.chunk_size + TAG_LENGTH; + const parts: ArrayBuffer[] = []; + let index = 0; + let size = 0; + + async function decrypt_chunk(chunk: Uint8Array, last: boolean) { + try { + const plaintext = await crypto.subtle.decrypt( + { name: "AES-GCM", iv: chunk_iv(index, last) }, + metadata.key, + chunk, + ); + parts.push(plaintext); + size += plaintext.byteLength; + index++; + } catch { + throw new Error("The file is damaged or was tampered with"); + } + } + + // A chunk is only known to be the last one once the stream ends, so the final one is held back + let pending: Uint8Array[] = []; + let pending_length = 0; + for await (const value of body) { + pending.push(value); + pending_length += value.length; + if (pending_length <= encrypted_chunk_size) { + continue; + } + + const joined = join(pending, pending_length); + let offset = 0; + while (joined.length - offset > encrypted_chunk_size) { + await decrypt_chunk(joined.subarray(offset, offset + encrypted_chunk_size), false); + offset += encrypted_chunk_size; + } + pending = [joined.subarray(offset)]; + pending_length = joined.length - offset; + } + await decrypt_chunk(join(pending, pending_length), true); + + if (size !== metadata.size) { + throw new Error("The file is damaged or was tampered with"); + } + return new Blob(parts, { type: metadata.type }); +} diff --git a/src/files.ts b/src/files.ts index 296c406..88b2b4b 100644 --- a/src/files.ts +++ b/src/files.ts @@ -18,3 +18,11 @@ export function download_blob(blob: Blob, file_name: string) { // Revoking right away can cancel the download in some browsers setTimeout(() => URL.revokeObjectURL(url), 60_000); } + +// What the files API returns, size is of the encrypted file +export interface FileEntry { + id: string; + date_created: string; + size: number; + metadata: string; +} diff --git a/src/files_api.ts b/src/files_api.ts new file mode 100644 index 0000000..38d5a77 --- /dev/null +++ b/src/files_api.ts @@ -0,0 +1,69 @@ +import { fetch_json, type PostJsonResult } from "./client.ts"; +import { decrypt_file, type EncryptedFile, type FileMetadata } from "./file_crypto.ts"; +import type { FileEntry } from "./files.ts"; + +function auth_headers() { + return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` }; +} + +export function list_files() { + return fetch_json("/api/files", { headers: auth_headers() }); +} + +export function delete_file(id: string) { + return fetch_json(`/api/files/${encodeURIComponent(id)}`, { method: "DELETE", headers: auth_headers() }); +} + +// Uses XMLHttpRequest since fetch can't report upload progress +export function upload_file( + file: EncryptedFile, + on_progress: (ratio: number) => void, + signal: AbortSignal, +): Promise> { + return new Promise((resolve) => { + if (signal.aborted) { + resolve({ ok: false, status: 0, error: "Upload cancelled" }); + return; + } + + const request = new XMLHttpRequest(); + request.open("POST", "/api/files"); + for (const [name, value] of Object.entries(auth_headers())) { + request.setRequestHeader(name, value); + } + request.setRequestHeader("X-File-Metadata", file.metadata); + request.responseType = "json"; + + request.upload.onprogress = (event) => { + if (event.lengthComputable) { + on_progress(event.loaded / event.total); + } + }; + request.onload = () => { + if (request.status >= 200 && request.status < 300) { + resolve({ ok: true, data: request.response }); + } else { + resolve({ + ok: false, + status: request.status, + error: request.response?.error ?? `Request failed with status ${request.status}`, + }); + } + }; + request.onerror = () => resolve({ ok: false, status: 0, error: "Couldn't reach the server" }); + request.onabort = () => resolve({ ok: false, status: 0, error: "Upload cancelled" }); + signal.addEventListener("abort", () => request.abort(), { once: true }); + + request.send(file.body); + }); +} + +// Throws if the request fails or the file can't be decrypted +export async function download_file(id: string, metadata: FileMetadata) { + const response = await fetch(`/api/files/${encodeURIComponent(id)}`, { headers: auth_headers() }); + if (!response.ok || !response.body) { + const data = await response.json().catch(() => undefined); + throw new Error(data?.error ?? `Request failed with status ${response.status}`); + } + return await decrypt_file(metadata, response.body); +} diff --git a/src/keys.ts b/src/keys.ts index 277bc2c..e9acf14 100644 --- a/src/keys.ts +++ b/src/keys.ts @@ -16,15 +16,15 @@ const PBKDF2_ITERATIONS = 600_000; const IV_LENGTH = 12; const MASTER_KEY_USAGES: KeyUsage[] = ["encrypt", "decrypt", "wrapKey", "unwrapKey"]; -function to_base64(bytes: Uint8Array) { +export function to_base64(bytes: Uint8Array) { return btoa(String.fromCharCode(...bytes)); } -function from_base64(text: string) { +export function from_base64(text: string) { return Uint8Array.from(atob(text), (char) => char.charCodeAt(0)); } -function concat(a: Uint8Array, b: Uint8Array) { +export function concat(a: Uint8Array, b: Uint8Array) { const result = new Uint8Array(a.length + b.length); result.set(a); result.set(b, a.length); diff --git a/src/server_constants.ts b/src/server_constants.ts index e7fa63b..b37c41f 100644 --- a/src/server_constants.ts +++ b/src/server_constants.ts @@ -1,2 +1,4 @@ export const DATABASE_PATH = Deno.env.get("DATABASE_PATH"); export const FILE_UPLOAD_PATH = Deno.env.get("FILE_UPLOAD_PATH"); +// In bytes, defaults to 1 GiB +export const MAX_UPLOAD_SIZE = Number(Deno.env.get("MAX_UPLOAD_SIZE") ?? 1024 ** 3); diff --git a/src/storage.ts b/src/storage.ts new file mode 100644 index 0000000..2356b86 --- /dev/null +++ b/src/storage.ts @@ -0,0 +1,54 @@ +import { dirname, join } from "@std/path"; + +import { FILE_UPLOAD_PATH } from "./server_constants.ts"; + +export class UploadTooLargeError extends Error {} + +function upload_path(storage_id: string) { + if (!FILE_UPLOAD_PATH) { + throw new Error("FILE_UPLOAD_PATH isn't set"); + } + return join(FILE_UPLOAD_PATH, storage_id); +} + +// Throws UploadTooLargeError once more than max_size bytes arrive, nothing is left on disk on failure +export async function save_upload(body: ReadableStream, max_size: number) { + const storage_id = crypto.randomUUID(); + const path = upload_path(storage_id); + await Deno.mkdir(dirname(path), { recursive: true }); + + let size = 0; + const limit = new TransformStream({ + transform(chunk, controller) { + size += chunk.byteLength; + if (size > max_size) { + controller.error(new UploadTooLargeError()); + } else { + controller.enqueue(chunk); + } + }, + }); + + const file = await Deno.open(path, { write: true, createNew: true }); + try { + await body.pipeThrough(limit).pipeTo(file.writable); + } catch (err) { + await delete_upload(storage_id); + throw err; + } + return { storage_id, size }; +} + +export async function open_upload(storage_id: string) { + return await Deno.open(upload_path(storage_id), { read: true }); +} + +export async function delete_upload(storage_id: string) { + try { + await Deno.remove(upload_path(storage_id)); + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + } +}