File uploading
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
DATABASE_PATH="__vces/vces.db"
|
||||
FILE_UPLOAD_PATH="__vces/uploads"
|
||||
MAX_UPLOAD_SIZE=1073741824
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
+110
-19
@@ -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<HubFile> {
|
||||
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<string>;
|
||||
}
|
||||
|
||||
export default function Hub(props: HubProps) {
|
||||
const master_key = useSignal<CryptoKey | null>(null);
|
||||
const load_error = useSignal("");
|
||||
const pending = useSignal<File[]>([]);
|
||||
const files = useSignal<HubFile[]>([]);
|
||||
const upload_state = useSignal<UploadState | null>(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<GetKeyResponse>("/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
|
||||
? <p role="alert" class="text-center text-error-600 dark:text-error-400">{load_error.value}</p>
|
||||
: <p class="text-center text-gray-800 dark:text-gray-400">Loading...</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="flex flex-col gap-6 md:h-[38rem] md:flex-row md:gap-8">
|
||||
<div class="flex flex-col gap-6 md:h-152 md:flex-row md:gap-8">
|
||||
<div class="flex min-h-0 flex-col md:w-1/2">
|
||||
<HubUpload pending={pending} dragging={dragging.value} on_add={add_files} on_upload={upload} />
|
||||
<HubUpload
|
||||
pending={pending}
|
||||
upload_state={upload_state.value}
|
||||
error={upload_error.value}
|
||||
dragging={dragging.value}
|
||||
on_add={add_files}
|
||||
on_upload={upload}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex min-h-0 flex-col md:w-1/2">
|
||||
<HubFileList files={files} />
|
||||
|
||||
+67
-20
@@ -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<void>) {
|
||||
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{" "}
|
||||
<span class="font-normal text-gray-500 dark:text-gray-400">({props.files.value.length})</span>
|
||||
</h1>
|
||||
{error.value && <p role="alert" class="pb-2 text-error-600 dark:text-error-400">{error.value}</p>}
|
||||
<ul class="-mx-2 flex min-h-0 flex-col gap-4 overflow-y-auto p-2">
|
||||
{props.files.value.map((file) => (
|
||||
<li
|
||||
@@ -49,30 +86,40 @@ export default function HubFileList(props: HubFileListProps) {
|
||||
class="flex flex-col rounded bg-white p-4 shadow-light dark:border dark:border-gray-700 dark:bg-gray-900"
|
||||
>
|
||||
<FileInfo
|
||||
name={file.name}
|
||||
size={file.size}
|
||||
detail={DATE_FORMAT.format(file.uploaded_at)}
|
||||
name={file.metadata?.name ?? "Unreadable file"}
|
||||
size={file.metadata?.size ?? file.stored_size}
|
||||
detail={file.metadata
|
||||
? DATE_FORMAT.format(new Date(file.uploaded_at))
|
||||
: "Can't be decrypted with your key"}
|
||||
action={
|
||||
<Button
|
||||
variant="link"
|
||||
class="flex-none self-start p-1 text-gray-500 hover:text-gray-700 focus:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 dark:focus:text-gray-200"
|
||||
title="Delete"
|
||||
aria-label={`Delete ${file.name}`}
|
||||
aria-label={`Delete ${file.metadata?.name ?? "unreadable file"}`}
|
||||
disabled={busy.value !== null}
|
||||
onClick={() => remove(file)}
|
||||
>
|
||||
<CloseIcon class="size-3.5" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<hr class="my-4 w-full border-gray-200 dark:border-gray-700" />
|
||||
<Button
|
||||
variant="link"
|
||||
class="flex items-center gap-2 self-start"
|
||||
onClick={() => download_blob(file.blob, file.name)}
|
||||
>
|
||||
<DownloadIcon class="h-4 w-3" />
|
||||
Download
|
||||
</Button>
|
||||
{file.metadata && (
|
||||
<>
|
||||
<hr class="my-4 w-full border-gray-200 dark:border-gray-700" />
|
||||
<Button
|
||||
variant="link"
|
||||
class="flex items-center gap-2 self-start"
|
||||
disabled={busy.value !== null}
|
||||
onClick={() => download(file)}
|
||||
>
|
||||
<DownloadIcon class="h-4 w-3" />
|
||||
{busy.value?.id === file.id && busy.value.action === "download"
|
||||
? "Downloading..."
|
||||
: "Download"}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -24,8 +24,45 @@ function FilePicker(props: FilePickerProps) {
|
||||
return <input type="file" multiple class="sr-only" onChange={change} />;
|
||||
}
|
||||
|
||||
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 (
|
||||
<div class="flex w-full flex-col rounded bg-white p-4 shadow-light dark:border dark:border-gray-700 dark:bg-gray-900">
|
||||
<FileInfo
|
||||
name={state.file.name}
|
||||
size={state.file.size}
|
||||
detail={state.count > 1 ? `${state.index + 1} of ${state.count}` : undefined}
|
||||
/>
|
||||
<p class="mt-4 text-sm font-medium text-primary-600 dark:text-primary-400">
|
||||
{state.progress === null ? "Encrypting..." : `Uploading ${percent}%`}
|
||||
</p>
|
||||
<progress
|
||||
class="my-3 h-1 w-full appearance-none overflow-hidden rounded bg-gray-200 dark:bg-gray-700 [&::-moz-progress-bar]:bg-primary-500 [&::-webkit-progress-bar]:bg-gray-200 dark:[&::-webkit-progress-bar]:bg-gray-700 [&::-webkit-progress-value]:bg-primary-500"
|
||||
max={100}
|
||||
value={state.progress === null ? undefined : percent}
|
||||
/>
|
||||
<Button variant="link" class="self-end" onClick={() => state.controller.abort()}>Cancel</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface HubUploadProps {
|
||||
pending: Signal<File[]>;
|
||||
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 <Uploading state={props.upload_state} />;
|
||||
}
|
||||
|
||||
const error = props.error && <p role="alert" class="mt-4 text-error-600 dark:text-error-400">{props.error}</p>;
|
||||
|
||||
if (props.pending.value.length === 0) {
|
||||
return (
|
||||
<label
|
||||
@@ -54,6 +97,7 @@ export default function HubUpload(props: HubUploadProps) {
|
||||
<p class="mx-12 my-6 max-w-sm text-center text-sm leading-loose text-gray-500 dark:text-gray-400">
|
||||
Files are encrypted in this browser before they're uploaded, the server never sees what's inside.
|
||||
</p>
|
||||
{error}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -100,6 +144,7 @@ export default function HubUpload(props: HubUploadProps) {
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="primary" class="mt-4 flex-none" onClick={props.on_upload}>Upload</Button>
|
||||
{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ export default function MainIsland() {
|
||||
} else if (page.value === "keysnew") {
|
||||
return <KeysNew page={page} />;
|
||||
} else if (page.value === "hub") {
|
||||
return <Hub />;
|
||||
return <Hub page={page} />;
|
||||
} else {
|
||||
return "Error";
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
},
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
},
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { db } from "./db.ts";
|
||||
|
||||
// Reads the user's code from an "Authorization: Bearer <code>" 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 });
|
||||
}
|
||||
+10
-6
@@ -3,14 +3,10 @@ export type PostJsonResult<T> =
|
||||
// status is 0 when the request never reached the server
|
||||
| { ok: false; status: number; error: string };
|
||||
|
||||
export async function post_json<T>(url: string, body: unknown, method = "POST"): Promise<PostJsonResult<T>> {
|
||||
export async function fetch_json<T>(url: string, init: RequestInit): Promise<PostJsonResult<T>> {
|
||||
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<T>(url: string, body: unknown, method = "POST"):
|
||||
}
|
||||
return { ok: true, data: data as T };
|
||||
}
|
||||
|
||||
export function post_json<T>(url: string, body: unknown, method = "POST"): Promise<PostJsonResult<T>> {
|
||||
return fetch_json<T>(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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<string, unknown> {
|
||||
passphrase_backup?: PassphraseBackup;
|
||||
}
|
||||
|
||||
export interface StoredFile extends Record<string, unknown> {
|
||||
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<Schema>(DATABASE_PATH ?? ":memory:", {
|
||||
users: ["code"],
|
||||
files: ["user_id"],
|
||||
});
|
||||
|
||||
@@ -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<string, unknown>) {
|
||||
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<FileMetadata> {
|
||||
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<EncryptedFile> {
|
||||
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<Uint8Array>): Promise<Blob> {
|
||||
const encrypted_chunk_size = metadata.chunk_size + TAG_LENGTH;
|
||||
const parts: ArrayBuffer[] = [];
|
||||
let index = 0;
|
||||
let size = 0;
|
||||
|
||||
async function decrypt_chunk(chunk: Uint8Array<ArrayBuffer>, 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 });
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<FileEntry[]>("/api/files", { headers: auth_headers() });
|
||||
}
|
||||
|
||||
export function delete_file(id: string) {
|
||||
return fetch_json<undefined>(`/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<PostJsonResult<FileEntry>> {
|
||||
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);
|
||||
}
|
||||
+3
-3
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Uint8Array>, 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<Uint8Array, Uint8Array>({
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user