Compare commits

...
4 Commits
Author SHA1 Message Date
paula 04eaef2a59 Better csp 2026-10-29 22:04:28 -03:00
paula f7f34e1a57 Admin page 2026-10-29 21:42:26 -03:00
paula 07e61d9dd1 fuck you git 2026-10-29 20:44:34 -03:00
paula de1ad70068 File sharing 2026-10-29 20:44:26 -03:00
36 changed files with 965 additions and 72 deletions
+4 -5
View File
@@ -1,6 +1,5 @@
@import "tailwindcss";
/* Palette, shadows and font from Mozilla Send (__paula/send/tailwind.config.js), Send's -10..-90 scale mapped to 100..900 */
@theme {
--color-*: initial;
--color-white: #ffffff;
@@ -46,7 +45,7 @@
font-style: normal;
font-weight: 400;
font-display: optional;
src: url("./fonts/Inter-Regular.woff2") format("woff2");
src: url("/fonts/Inter-Regular.woff2") format("woff2");
}
@font-face {
@@ -54,7 +53,7 @@
font-style: normal;
font-weight: 500;
font-display: optional;
src: url("./fonts/Inter-Medium.woff2") format("woff2");
src: url("/fonts/Inter-Medium.woff2") format("woff2");
}
@font-face {
@@ -62,7 +61,7 @@
font-style: normal;
font-weight: 600;
font-display: optional;
src: url("./fonts/Inter-SemiBold.woff2") format("woff2");
src: url("/fonts/Inter-SemiBold.woff2") format("woff2");
}
@font-face {
@@ -70,5 +69,5 @@
font-style: normal;
font-weight: 700;
font-display: optional;
src: url("./fonts/Inter-Bold.woff2") format("woff2");
src: url("/fonts/Inter-Bold.woff2") format("woff2");
}
+20
View File
@@ -46,3 +46,23 @@ export function DownloadIcon(props: IconProps) {
</svg>
);
}
export function ShareIcon(props: IconProps) {
return (
<svg class={props.class} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M18 9a3 3 0 1 0-2.977-2.63l-6.94 3.47a3 3 0 1 0 0 4.319l6.94 3.47a3 3 0 1 0 .895-1.789l-6.94-3.47a3.03 3.03 0 0 0 0-.74l6.94-3.47C16.456 8.68 17.19 9 18 9z"
/>
</svg>
);
}
export function CopyIcon(props: IconProps) {
return (
<svg class={props.class} viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
<path d="M14.707 8.293l-3-3A1 1 0 0 0 11 5h-1V4a1 1 0 0 0-.293-.707l-3-3A1 1 0 0 0 6 0H3a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h3v3a2 2 0 0 0 2 2h5a2 2 0 0 0 2-2V9a1 1 0 0 0-.293-.707zM12.586 9H11V7.414zm-5-5H6V2.414zM6 7v2H3V2h2v2.5a.5.5 0 0 0 .5.5H8a2 2 0 0 0-2 2zm2 7V7h2v2.5a.5.5 0 0 0 .5.5H13v4z" />
</svg>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { useSignal, useSignalEffect } from "@preact/signals";
import { button_class } from "@/components/Button.tsx";
import type { MeResponse } from "@/src/admin.ts";
import { auth_headers, fetch_json } from "@/src/client.ts";
// Only shown to admins, the server checks again on every admin request
export default function AdminButton() {
const is_admin = useSignal(false);
useSignalEffect(() => {
const fn = async () => {
if (!localStorage.getItem("code")) {
return;
}
const result = await fetch_json<MeResponse>("/api/me", { headers: auth_headers() });
is_admin.value = result.ok && result.data.admin;
};
fn();
});
if (!is_admin.value) {
return null;
}
return <a href="/admin" class={button_class("link")}>Admin</a>;
}
+181
View File
@@ -0,0 +1,181 @@
import { useSignal, useSignalEffect } from "@preact/signals";
import Button from "@/components/Button.tsx";
import { CopyIcon } from "@/components/Icons.tsx";
import InputField from "@/components/InputField.tsx";
import Form from "@/islands/Form.tsx";
import type { AdminUserEntry, CreatedUser } from "@/src/admin.ts";
import { auth_headers, fetch_json } from "@/src/client.ts";
import { format_bytes } from "@/src/files.ts";
const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
interface CreatedNoticeProps {
user: CreatedUser;
}
function CreatedNotice(props: CreatedNoticeProps) {
const copied = useSignal(false);
const error = useSignal("");
async function copy() {
try {
await navigator.clipboard.writeText(props.user.code);
copied.value = true;
setTimeout(() => copied.value = false, 2000);
} catch {
error.value = "Couldn't copy the code, select it and copy it by hand";
}
}
return (
<div class="mt-6 rounded bg-primary-500/5 p-4 dark:bg-primary-400/10">
<p class="font-medium">Created {props.user.name}</p>
<p class="mt-1 text-sm text-gray-700 dark:text-gray-400">
Send them this code, it's how they log in. It won't be shown again.
</p>
<div class="mt-3 flex flex-row gap-2">
<InputField
type="text"
readOnly
value={props.user.code}
aria-label={`Login code for ${props.user.name}`}
class="h-10 min-w-0 font-mono text-sm"
onFocus={(event) => event.currentTarget.select()}
/>
<Button
variant="primary"
class="flex h-10 flex-none items-center gap-2 px-4 py-0 text-sm"
onClick={copy}
>
<CopyIcon class="size-4" />
{copied.value ? "Copied" : "Copy"}
</Button>
</div>
{error.value && <p role="alert" class="mt-2 text-sm text-error-600 dark:text-error-400">{error.value}</p>}
</div>
);
}
interface UserTableProps {
users: AdminUserEntry[];
}
function UserTable(props: UserTableProps) {
return (
<div class="overflow-x-auto">
<table class="w-full text-left">
<thead class="border-b border-gray-200 text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
<tr>
<th class="py-2 pr-4 font-medium">Name</th>
<th class="px-4 py-2 text-right font-medium">Files</th>
<th class="px-4 py-2 text-right font-medium">Storage</th>
<th class="py-2 pl-4 font-medium">Created</th>
</tr>
</thead>
<tbody>
{props.users.map((user) => (
<tr key={user.id} class="border-b border-gray-200 last:border-0 dark:border-gray-700">
<td class="py-3 pr-4">
<span class="font-medium break-all">{user.name}</span>
{user.admin && (
<span class="ml-2 rounded bg-primary-500/10 px-1.5 py-0.5 text-xs font-medium text-primary-600 dark:text-primary-400">
Admin
</span>
)}
{!user.has_key && (
<span class="ml-2 text-sm text-gray-500 dark:text-gray-400">Not set up yet</span>
)}
</td>
<td class="px-4 py-3 text-right tabular-nums">{user.file_count}</td>
<td class="px-4 py-3 text-right whitespace-nowrap tabular-nums">
{format_bytes(user.storage_used)}
</td>
<td class="py-3 pl-4 whitespace-nowrap">
{DATE_FORMAT.format(new Date(user.date_created))}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default function AdminPanel() {
const users = useSignal<AdminUserEntry[] | null>(null);
const load_error = useSignal("");
const created = useSignal<CreatedUser | null>(null);
// Changing it remounts the form, which clears it
const form_key = useSignal(0);
async function load() {
if (!localStorage.getItem("code")) {
load_error.value = "Log in to see this page";
return;
}
const result = await fetch_json<AdminUserEntry[]>("/api/admin/users", { headers: auth_headers() });
if (result.ok) {
users.value = result.data;
} else {
load_error.value = result.error;
}
}
function on_created(user: CreatedUser) {
created.value = user;
form_key.value++;
users.value = [
...users.value ?? [],
{
id: user.id,
name: user.name,
admin: user.admin,
date_created: new Date().toISOString(),
has_key: false,
file_count: 0,
storage_used: 0,
},
];
}
useSignalEffect(() => {
load();
});
if (!users.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-10">
<section>
<h1 class="pb-4 text-lg font-bold">
Users <span class="font-normal text-gray-500 dark:text-gray-400">({users.value.length})</span>
</h1>
<UserTable users={users.value} />
</section>
<section class="max-w-md">
<h2 class="pb-4 text-lg font-bold">Create a user</h2>
<Form<CreatedUser>
key={form_key.value}
action="/api/admin/users"
headers={auth_headers()}
on_success={on_created}
>
<div class="flex flex-col gap-4">
<InputField type="text" name="name" placeholder="Name" required maxLength={100} />
<label class="flex items-center gap-2">
<input type="checkbox" name="admin" class="size-4 accent-primary-600" />
Admin
</label>
<Button type="submit" variant="primary">Create user</Button>
</div>
</Form>
{created.value && <CreatedNotice user={created.value} />}
</section>
</div>
);
}
+2 -1
View File
@@ -9,6 +9,7 @@ interface FormProps<T> {
on_error?: (message: string) => void;
class?: string;
method?: string;
headers?: Record<string, string>;
children: ComponentChildren;
}
@@ -28,7 +29,7 @@ export default function Form<T = unknown>(props: FormProps<T>) {
submitting.value = true;
error.value = "";
const result = await post_json<T>(props.action, body, props.method);
const result = await post_json<T>(props.action, body, props.method, props.headers);
submitting.value = false;
if (result.ok) props.on_success(result.data);
+17 -4
View File
@@ -1,21 +1,34 @@
import { Signal, useSignal, useSignalEffect } from "@preact/signals";
import HubFileList, { type HubFile } from "@/islands/HubFileList.tsx";
import HubFileList, { type HubFile, type HubShare } from "@/islands/HubFileList.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 type { FileEntry, ShareEntry } 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";
import { open_share_secret, share_link } from "@/src/share_crypto.ts";
function has_files(event: DragEvent) {
return event.dataTransfer?.types.includes("Files") ?? false;
}
async function to_hub_share(master_key: CryptoKey, share: ShareEntry): Promise<HubShare | null> {
const link_secret = await open_share_secret(master_key, share.secret).catch(() => null);
return link_secret ? { link: share_link(share.id, link_secret) } : null;
}
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 };
return {
id: entry.id,
uploaded_at: entry.date_created,
stored_size: entry.size,
encrypted_metadata: entry.metadata,
metadata,
share: entry.share && await to_hub_share(master_key, entry.share),
};
}
interface HubProps {
@@ -161,7 +174,7 @@ export default function Hub(props: HubProps) {
/>
</div>
<div class="flex min-h-0 flex-col md:w-1/2">
<HubFileList files={files} />
<HubFileList files={files} master_key={master_key.value} />
</div>
</div>
);
+137 -15
View File
@@ -2,31 +2,75 @@ 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 { CloseIcon, CopyIcon, DownloadIcon, ShareIcon } from "@/components/Icons.tsx";
import InputField from "@/components/InputField.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";
import { delete_file, download_file, share_file, unshare_file } from "@/src/files_api.ts";
import { create_share, share_link } from "@/src/share_crypto.ts";
export interface HubShare {
// Has the link secret, so it only exists in this browser
link: string;
}
export interface HubFile {
id: string;
uploaded_at: string;
// Size of the encrypted file, shown when the metadata can't be read
stored_size: number;
// As stored on the server, needed to encrypt it again for a share link
encrypted_metadata: string;
// null when it can't be decrypted with this key
metadata: FileMetadata | null;
share: HubShare | null;
}
type FileAction = "download" | "delete" | "share" | "unshare";
const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
interface ShareLinkProps {
name: string;
link: string;
copied: boolean;
on_copy: (link: string) => void;
}
function ShareLink(props: ShareLinkProps) {
return (
<div class="mt-4 flex flex-row gap-2">
<InputField
type="text"
readOnly
value={props.link}
aria-label={`Share link for ${props.name}`}
class="h-10 min-w-0 text-sm"
onFocus={(event) => event.currentTarget.select()}
/>
<Button
variant="primary"
class="flex h-10 flex-none items-center gap-2 px-4 py-0 text-sm"
onClick={() => props.on_copy(props.link)}
>
<CopyIcon class="size-4" />
{props.copied ? "Copied" : "Copy"}
</Button>
</div>
);
}
interface HubFileListProps {
files: Signal<HubFile[]>;
master_key: CryptoKey;
}
export default function HubFileList(props: HubFileListProps) {
const busy = useSignal<{ id: string; action: "download" | "delete" } | null>(null);
const busy = useSignal<{ id: string; action: FileAction } | null>(null);
const copied = useSignal<string | null>(null);
const error = useSignal("");
async function run(file: HubFile, action: "download" | "delete", fn: () => Promise<void>) {
async function run(file: HubFile, action: FileAction, fn: () => Promise<void>) {
if (busy.value) {
return;
}
@@ -41,6 +85,29 @@ export default function HubFileList(props: HubFileListProps) {
}
}
function is_busy(file: HubFile, action: FileAction) {
return busy.value?.id === file.id && busy.value.action === action;
}
function set_share(file: HubFile, share: HubShare | null) {
props.files.value = props.files.value.map((other) => other.id === file.id ? { ...other, share } : other);
}
async function copy(file: HubFile, link: string) {
try {
await navigator.clipboard.writeText(link);
} catch {
error.value = "Couldn't copy the link, select it and copy it by hand";
return;
}
copied.value = file.id;
setTimeout(() => {
if (copied.value === file.id) {
copied.value = null;
}
}, 2000);
}
function download(file: HubFile) {
const metadata = file.metadata;
if (metadata) {
@@ -48,6 +115,32 @@ export default function HubFileList(props: HubFileListProps) {
}
}
function share(file: HubFile) {
run(file, "share", async () => {
const created = await create_share(props.master_key, file.encrypted_metadata);
const result = await share_file(file.id, created);
if (!result.ok) {
throw new Error(result.error);
}
const link = share_link(result.data.id, created.link_secret);
set_share(file, { link });
await copy(file, link);
});
}
function unshare(file: HubFile) {
if (!confirm(`Stop sharing "${file.metadata?.name ?? "this file"}"? The link will stop working.`)) {
return;
}
run(file, "unshare", async () => {
const result = await unshare_file(file.id);
if (!result.ok && result.status !== 404) {
throw new Error(result.error);
}
set_share(file, null);
});
}
function remove(file: HubFile) {
if (!confirm(`Delete "${file.metadata?.name ?? "this file"}"? This can't be undone.`)) {
return;
@@ -107,17 +200,46 @@ export default function HubFileList(props: HubFileListProps) {
{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>
<div class="flex flex-row flex-wrap items-center gap-x-6 gap-y-2">
<Button
variant="link"
class="flex items-center gap-2"
disabled={busy.value !== null}
onClick={() => download(file)}
>
<DownloadIcon class="h-4 w-3" />
{is_busy(file, "download") ? "Downloading..." : "Download"}
</Button>
{file.share
? (
<Button
variant="link"
disabled={busy.value !== null}
onClick={() => unshare(file)}
>
{is_busy(file, "unshare") ? "Removing link..." : "Stop sharing"}
</Button>
)
: (
<Button
variant="link"
class="flex items-center gap-2"
disabled={busy.value !== null}
onClick={() => share(file)}
>
<ShareIcon class="size-4" />
{is_busy(file, "share") ? "Creating link..." : "Share"}
</Button>
)}
</div>
{file.share && (
<ShareLink
name={file.metadata.name}
link={file.share.link}
copied={copied.value === file.id}
on_copy={(link) => copy(file, link)}
/>
)}
</>
)}
</li>
+85
View File
@@ -0,0 +1,85 @@
import { useSignal, useSignalEffect } from "@preact/signals";
import Button from "@/components/Button.tsx";
import FileInfo from "@/components/FileInfo.tsx";
import { DownloadIcon } from "@/components/Icons.tsx";
import type { FileMetadata } from "@/src/file_crypto.ts";
import { download_blob } from "@/src/files.ts";
import { download_shared_file, get_shared_file } from "@/src/files_api.ts";
import { decrypt_share_metadata } from "@/src/share_crypto.ts";
interface SharedDownloadProps {
share_id: string;
}
export default function SharedDownload(props: SharedDownloadProps) {
const metadata = useSignal<FileMetadata | null>(null);
const load_error = useSignal("");
const downloading = useSignal(false);
const error = useSignal("");
async function load() {
// The secret is after the #, so the browser never sends it to the server
const link_secret = location.hash.slice(1);
if (!link_secret) {
load_error.value = "This link is missing its key, make sure you copied all of it";
return;
}
const result = await get_shared_file(props.share_id);
if (!result.ok) {
load_error.value = result.error;
return;
}
try {
metadata.value = await decrypt_share_metadata(link_secret, result.data.metadata);
} catch (err) {
load_error.value = err instanceof Error ? err.message : String(err);
}
}
async function download() {
const file = metadata.value;
if (!file || downloading.value) {
return;
}
downloading.value = true;
error.value = "";
try {
download_blob(await download_shared_file(props.share_id, file), file.name);
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
downloading.value = false;
}
}
useSignalEffect(() => {
load();
});
if (!metadata.value) {
return load_error.value
? <p role="alert" class="py-8 text-center text-error-600 dark:text-error-400">{load_error.value}</p>
: <p class="py-8 text-center text-gray-800 dark:text-gray-400">Loading...</p>;
}
return (
<div class="mx-auto flex w-full max-w-md flex-col py-8">
<h1 class="text-3xl font-bold">Download a shared file</h1>
<div class="mt-8 rounded bg-white p-4 shadow-light dark:border dark:border-gray-700 dark:bg-gray-900">
<FileInfo name={metadata.value.name} size={metadata.value.size} />
</div>
<Button
variant="primary"
class="mt-6 flex items-center justify-center gap-2"
disabled={downloading.value}
onClick={download}
>
<DownloadIcon class="h-4 w-3" />
{downloading.value ? "Downloading..." : "Download"}
</Button>
{error.value && <p role="alert" class="mt-4 text-error-600 dark:text-error-400">{error.value}</p>}
</div>
);
}
+11
View File
@@ -1,8 +1,19 @@
import { App, csp, csrf, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
import { UPLOAD_CSP } from "@/src/storage.ts";
export const app = new App<State>();
// csp() overwrites any policy a route sets, so the stricter one for uploaded files is put back here
app.use(define.middleware(async (ctx) => {
const res = await ctx.next();
if (res.headers.get("Content-Disposition") === "attachment") {
res.headers.set("Content-Security-Policy", UPLOAD_CSP);
}
return res;
}));
// Vite's dev client injects CSS through <style> tags without a nonce
app.use(csrf(), csp({ useNonce: !import.meta.env.DEV }));
+4
View File
@@ -1,4 +1,5 @@
import { define } from "@/utils.ts";
import AdminButton from "@/islands/AdminButton.tsx";
export default define.page(function ({ Component }) {
return (
@@ -11,6 +12,9 @@ export default define.page(function ({ Component }) {
<body class="flex min-h-screen flex-col items-center bg-white font-sans text-gray-900 md:bg-gray-100 dark:bg-black dark:text-gray-100">
<header class="flex h-16 w-full flex-none flex-row items-center px-6 md:h-24 md:px-8">
<a href="/" class="text-2xl font-bold md:text-3xl">vces</a>
<div class="ml-auto">
<AdminButton />
</div>
</header>
<main class="flex w-full max-w-5xl md:m-auto md:w-[calc(100%-3rem)] md:flex-1 md:items-center md:py-8">
<section class="w-full bg-white p-6 md:min-h-[42rem] md:rounded-xl md:p-8 md:shadow-big dark:bg-gray-900 md:dark:border md:dark:border-gray-800">
+6
View File
@@ -0,0 +1,6 @@
import { define } from "@/utils.ts";
import AdminPanel from "@/islands/AdminPanel.tsx";
export default define.page(function () {
return <AdminPanel />;
});
+77
View File
@@ -0,0 +1,77 @@
import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import type { AdminUserEntry, CreatedUser } from "@/src/admin.ts";
import { authenticate, forbidden, unauthorized } from "@/src/auth.ts";
import { generate_code } from "@/src/crypto.ts";
import { db, type FileRow, type User } from "@/src/db.ts";
// Sent by the Form island, so the checkbox is "on" or missing
const CreateUserBody = z.object({
name: z.string().trim().min(1).max(100),
admin: z.literal("on").optional(),
});
async function authenticate_admin(req: Request) {
const user = await authenticate(req);
if (!user) {
return unauthorized();
}
if ((user as Partial<User>).admin !== true) {
return forbidden();
}
return undefined;
}
export const handler = define.handlers({
async GET(ctx) {
const denied = await authenticate_admin(ctx.req);
if (denied) {
return denied;
}
const files = await db.get_all_entries("files") as FileRow[];
const usage = new Map<string, { file_count: number; storage_used: number }>();
for (const file of files) {
const entry = usage.get(file.user_id) ?? { file_count: 0, storage_used: 0 };
entry.file_count++;
entry.storage_used += file.size;
usage.set(file.user_id, entry);
}
const users = await db.get_all_entries("users") as (User & { id: string; date_created: string })[];
return Response.json(
users.map((user): AdminUserEntry => ({
id: user.id,
name: user.name,
admin: user.admin,
date_created: user.date_created,
has_key: Boolean(user.key_check),
...(usage.get(user.id) ?? { file_count: 0, storage_used: 0 }),
})),
);
},
async POST(ctx) {
const denied = await authenticate_admin(ctx.req);
if (denied) {
return denied;
}
const body = CreateUserBody.safeParse(await ctx.req.json().catch(() => null));
if (!body.success) {
return Response.json({ error: "Enter a name" }, { status: 400 });
}
let code = generate_code();
while (await db.get_entry_by_index("users", "code", code)) {
code = generate_code();
}
const user = await db.create_entry("users", { name: body.data.name, code, admin: body.data.admin === "on" });
return Response.json(
{ id: user.id, name: user.name, admin: user.admin, code: user.code } satisfies CreatedUser,
{ status: 201 },
);
},
});
+7 -13
View File
@@ -1,7 +1,7 @@
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";
import { db, type FileRow, type ShareRow } from "@/src/db.ts";
import { delete_upload, upload_response } from "@/src/storage.ts";
const not_found = () => Response.json({ error: "File not found" }, { status: 404 });
@@ -17,17 +17,7 @@ export const handler = define.handlers({
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",
},
});
return await upload_response(file.storage_id) ?? not_found();
},
async DELETE(ctx) {
@@ -41,6 +31,10 @@ export const handler = define.handlers({
return not_found();
}
const shares = await db.get_entries_by_index("shares", "file_id", file.id) as ShareRow[];
for (const share of shares) {
await db.delete_entry("shares", share);
}
await db.delete_entry("files", file);
await delete_upload(file.storage_id);
return new Response(null, { status: 204 });
+62
View File
@@ -0,0 +1,62 @@
import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import { authenticate, unauthorized } from "@/src/auth.ts";
import { db, type FileRow, type ShareRow } from "@/src/db.ts";
import type { ShareEntry } from "@/src/files.ts";
const ShareBody = z.object({
metadata: z.base64().min(1).max(4096),
secret: z.base64().min(1).max(200),
});
const not_found = () => Response.json({ error: "File not found" }, { status: 404 });
export const handler = define.handlers({
// The body only has encrypted data, the link secret itself never reaches the server
async POST(ctx) {
const user = await authenticate(ctx.req);
if (!user) {
return unauthorized();
}
const body = ShareBody.safeParse(await ctx.req.json().catch(() => null));
if (!body.success) {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
const file = await db.get_entry("files", ctx.params.id) as FileRow | undefined;
if (!file || file.user_id !== user.id) {
return not_found();
}
if (await db.get_entry_by_index("shares", "file_id", file.id)) {
return Response.json({ error: "This file is already shared" }, { status: 409 });
}
const share = await db.create_entry("shares", {
user_id: user.id,
file_id: file.id,
metadata: body.data.metadata,
secret: body.data.secret,
});
return Response.json({ id: share.id, secret: share.secret } satisfies ShareEntry, { status: 201 });
},
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();
}
const shares = await db.get_entries_by_index("shares", "file_id", file.id) as ShareRow[];
for (const share of shares) {
await db.delete_entry("shares", share);
}
return new Response(null, { status: 204 });
},
});
+14 -7
View File
@@ -2,7 +2,7 @@ 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 { db, type FileRow, type ShareRow } 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";
@@ -19,13 +19,19 @@ export const handler = define.handlers({
}
const files = await db.get_entries_by_index("files", "user_id", user.id) as FileRow[];
const shares = await db.get_entries_by_index("shares", "user_id", user.id) as ShareRow[];
const share_by_file = new Map(shares.map((share) => [share.file_id, share]));
return Response.json(
files.map((file): FileEntry => ({
id: file.id,
date_created: file.date_created,
size: file.size,
metadata: file.metadata,
})).reverse(),
files.map((file): FileEntry => {
const share = share_by_file.get(file.id);
return {
id: file.id,
date_created: file.date_created,
size: file.size,
metadata: file.metadata,
share: share ? { id: share.id, secret: share.secret } : null,
};
}).reverse(),
);
},
@@ -67,6 +73,7 @@ export const handler = define.handlers({
date_created: file.date_created,
size: file.size,
metadata: file.metadata,
share: null,
} satisfies FileEntry,
{ status: 201 },
);
+16
View File
@@ -0,0 +1,16 @@
import { define } from "@/utils.ts";
import type { MeResponse } from "@/src/admin.ts";
import { authenticate, unauthorized } from "@/src/auth.ts";
import type { User } from "@/src/db.ts";
export const handler = define.handlers({
async GET(ctx) {
const user = await authenticate(ctx.req);
if (!user) {
return unauthorized();
}
const { name, admin } = user as Partial<User>;
return Response.json({ id: user.id, name: name ?? "", admin: admin === true } satisfies MeResponse);
},
});
+15
View File
@@ -0,0 +1,15 @@
import { define } from "@/utils.ts";
import type { SharedFileEntry } from "@/src/files.ts";
import { get_shared_file, share_not_found } from "@/src/shares.ts";
export const handler = define.handlers({
async GET(ctx) {
const shared = await get_shared_file(ctx.params.id);
if (!shared) {
return share_not_found();
}
return Response.json({ size: shared.file.size, metadata: shared.share.metadata } satisfies SharedFileEntry, {
headers: { "Cache-Control": "no-store" },
});
},
});
+14
View File
@@ -0,0 +1,14 @@
import { define } from "@/utils.ts";
import { get_shared_file, share_not_found } from "@/src/shares.ts";
import { upload_response } from "@/src/storage.ts";
export const handler = define.handlers({
// Streams the encrypted file, the recipient decrypts it with the secret in the link
async GET(ctx) {
const shared = await get_shared_file(ctx.params.id);
if (!shared) {
return share_not_found();
}
return await upload_response(shared.file.storage_id) ?? share_not_found();
},
});
+13
View File
@@ -0,0 +1,13 @@
import type { RouteConfig } from "fresh";
import { define } from "@/utils.ts";
import SharedDownload from "@/islands/SharedDownload.tsx";
// Share links look like /download/<id>/#<secret>, the trailing slash is optional
export const config: RouteConfig = {
routeOverride: "/download/:id{/}?",
};
export default define.page(function ({ params }) {
return <SharedDownload share_id={params.id} />;
});
+6
View File
@@ -0,0 +1,6 @@
import "@std/dotenv/load";
import * as server from "./_fresh/server.js";
Deno.serve(
{ port: Number(Deno.env.get("PORT") ?? 8000) },
server.default.fetch as unknown as Deno.ServeHandler<Deno.NetAddr>,
);
+24
View File
@@ -0,0 +1,24 @@
export interface MeResponse {
id: string;
name: string;
admin: boolean;
}
// What the admin users API returns, storage_used is the size of the encrypted files
export interface AdminUserEntry {
id: string;
name: string;
admin: boolean;
date_created: string;
has_key: boolean;
file_count: number;
storage_used: number;
}
// Only returned once, when the user is created
export interface CreatedUser {
id: string;
name: string;
admin: boolean;
code: string;
}
+4
View File
@@ -12,3 +12,7 @@ export async function authenticate(req: Request) {
export function unauthorized() {
return Response.json({ error: "Invalid code" }, { status: 401 });
}
export function forbidden() {
return Response.json({ error: "Only admins can do this" }, { status: 403 });
}
+12 -2
View File
@@ -22,10 +22,20 @@ export async function fetch_json<T>(url: string, init: RequestInit): Promise<Pos
return { ok: true, data: data as T };
}
export function post_json<T>(url: string, body: unknown, method = "POST"): Promise<PostJsonResult<T>> {
export function post_json<T>(
url: string,
body: unknown,
method = "POST",
headers: Record<string, string> = {},
): Promise<PostJsonResult<T>> {
return fetch_json<T>(url, {
method,
headers: { "Content-Type": "application/json" },
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
// The user's code from AskCode, sent as a bearer token
export function auth_headers() {
return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` };
}
+12
View File
@@ -21,15 +21,27 @@ export interface StoredFile extends Record<string, unknown> {
metadata: string;
}
export interface StoredShare extends Record<string, unknown> {
user_id: string;
file_id: string;
// The file metadata encrypted with the secret in the share link
metadata: string;
// The link secret encrypted with the owner's master key
secret: string;
}
// boksy's partial entry types lose the field types
export type FileRow = Model & StoredFile;
export type ShareRow = Model & StoredShare;
type Schema = {
users: User;
files: StoredFile;
shares: StoredShare;
};
export const db = await Database.open<Schema>(DATABASE_PATH ?? ":memory:", {
users: ["code"],
files: ["user_id"],
shares: ["user_id", "file_id"],
});
+27 -15
View File
@@ -29,26 +29,36 @@ function chunk_iv(index: number, last: boolean) {
return iv;
}
async function encrypt_metadata(master_key: CryptoKey, metadata: Record<string, unknown>) {
// Encrypts with a random IV, which goes in front of the ciphertext
export async function seal(key: CryptoKey, plaintext: Uint8Array<ArrayBuffer>, aad: Uint8Array<ArrayBuffer>) {
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);
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad }, key, plaintext);
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);
// Throws if it wasn't sealed with this key and aad
export async function unseal(key: CryptoKey, sealed: string, aad: Uint8Array<ArrayBuffer>) {
const bytes = from_base64(sealed);
const plaintext = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: bytes.slice(0, IV_LENGTH), additionalData: METADATA_AAD },
master_key,
{ name: "AES-GCM", iv: bytes.slice(0, IV_LENGTH), additionalData: aad },
key,
bytes.slice(IV_LENGTH),
);
return new Uint8Array(plaintext);
}
// Throws if the metadata wasn't encrypted with this master key
export async function decrypt_metadata(master_key: CryptoKey, metadata: string) {
return await parse_metadata(await unseal(master_key, metadata, METADATA_AAD));
}
// The file metadata decrypted as is, so it can be encrypted again for a share link
export function unseal_metadata(master_key: CryptoKey, metadata: string) {
return unseal(master_key, metadata, METADATA_AAD);
}
// Throws if the plaintext isn't valid metadata
export async function parse_metadata(plaintext: Uint8Array): Promise<FileMetadata> {
const data = JSON.parse(new TextDecoder().decode(plaintext));
if (
data.version !== METADATA_VERSION || typeof data.name !== "string" || typeof data.type !== "string" ||
@@ -70,14 +80,16 @@ export async function encrypt_file(
): 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, {
const plaintext = new TextEncoder().encode(JSON.stringify({
version: METADATA_VERSION,
name: file.name,
type: file.type,
size: file.size,
chunk_size: CHUNK_SIZE,
key: to_base64(raw_key),
});
}));
const metadata = await seal(master_key, plaintext, METADATA_AAD);
plaintext.fill(0);
raw_key.fill(0);
// Empty files still get one chunk, so the last chunk flag is always checked
+13
View File
@@ -19,10 +19,23 @@ export function download_blob(blob: Blob, file_name: string) {
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
export interface ShareEntry {
id: string;
// The link secret encrypted with the master key
secret: string;
}
// What the files API returns, size is of the encrypted file
export interface FileEntry {
id: string;
date_created: string;
size: number;
metadata: string;
share: ShareEntry | null;
}
// What the public shares API returns, metadata is encrypted with the link secret
export interface SharedFileEntry {
size: number;
metadata: string;
}
+32 -8
View File
@@ -1,10 +1,7 @@
import { fetch_json, type PostJsonResult } from "./client.ts";
import { auth_headers, 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") ?? ""}` };
}
import type { FileEntry, SharedFileEntry, ShareEntry } from "./files.ts";
import type { NewShare } from "./share_crypto.ts";
export function list_files() {
return fetch_json<FileEntry[]>("/api/files", { headers: auth_headers() });
@@ -59,11 +56,38 @@ export function upload_file(
}
// 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() });
async function download(url: string, metadata: FileMetadata, init?: RequestInit) {
const response = await fetch(url, init);
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);
}
export function download_file(id: string, metadata: FileMetadata) {
return download(`/api/files/${encodeURIComponent(id)}`, metadata, { headers: auth_headers() });
}
export function share_file(id: string, share: Pick<NewShare, "metadata" | "secret">) {
return fetch_json<ShareEntry>(`/api/files/${encodeURIComponent(id)}/share`, {
method: "POST",
headers: { ...auth_headers(), "Content-Type": "application/json" },
body: JSON.stringify({ metadata: share.metadata, secret: share.secret }),
});
}
export function unshare_file(id: string) {
return fetch_json<undefined>(`/api/files/${encodeURIComponent(id)}/share`, {
method: "DELETE",
headers: auth_headers(),
});
}
export function get_shared_file(share_id: string) {
return fetch_json<SharedFileEntry>(`/api/shares/${encodeURIComponent(share_id)}`, {});
}
export function download_shared_file(share_id: string, metadata: FileMetadata) {
return download(`/api/shares/${encodeURIComponent(share_id)}/file`, metadata);
}
+11 -2
View File
@@ -24,6 +24,15 @@ export function from_base64(text: string) {
return Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
}
export function to_base64url(bytes: Uint8Array) {
return to_base64(bytes).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
}
// Throws if the text isn't base64url
export function from_base64url(text: string) {
return from_base64(text.replaceAll("-", "+").replaceAll("_", "/"));
}
export function concat(a: Uint8Array, b: Uint8Array) {
const result = new Uint8Array(a.length + b.length);
result.set(a);
@@ -37,7 +46,7 @@ export function generate_master_key() {
export async function export_key_text(key: CryptoKey) {
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", key));
const base64url = to_base64(raw).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
const base64url = to_base64url(raw);
raw.fill(0);
return KEY_TEXT_PREFIX + base64url;
}
@@ -52,7 +61,7 @@ export async function import_key_text(text: string) {
let raw: Uint8Array<ArrayBuffer>;
try {
raw = from_base64(trimmed.slice(KEY_TEXT_PREFIX.length).replaceAll("-", "+").replaceAll("_", "/"));
raw = from_base64url(trimmed.slice(KEY_TEXT_PREFIX.length));
} catch {
throw not_a_key;
}
+74
View File
@@ -0,0 +1,74 @@
import { parse_metadata, seal, unseal, unseal_metadata } from "./file_crypto.ts";
import { from_base64url, to_base64url } from "./keys.ts";
const SECRET_LENGTH = 16;
const SHARE_KEY_INFO = new TextEncoder().encode("vces-share-key-v1");
const SHARE_METADATA_AAD = new TextEncoder().encode("vces-share-metadata-v1");
const SHARE_SECRET_AAD = new TextEncoder().encode("vces-share-secret-v1");
export interface NewShare {
// The file metadata encrypted with the link secret
metadata: string;
// The link secret encrypted with the master key, so the owner can copy the link again
secret: string;
// Goes after the # in the link, never sent to the server
link_secret: string;
}
async function derive_share_key(secret: Uint8Array<ArrayBuffer>) {
const base = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveKey"]);
return crypto.subtle.deriveKey(
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: SHARE_KEY_INFO },
base,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
// Throws if the file metadata wasn't encrypted with this master key
export async function create_share(master_key: CryptoKey, file_metadata: string): Promise<NewShare> {
const secret = crypto.getRandomValues(new Uint8Array(SECRET_LENGTH));
const plaintext = await unseal_metadata(master_key, file_metadata);
const metadata = await seal(await derive_share_key(secret), plaintext, SHARE_METADATA_AAD);
plaintext.fill(0);
const sealed_secret = await seal(master_key, secret, SHARE_SECRET_AAD);
const link_secret = to_base64url(secret);
secret.fill(0);
return { metadata, secret: sealed_secret, link_secret };
}
// Throws if the secret wasn't encrypted with this master key
export async function open_share_secret(master_key: CryptoKey, sealed_secret: string) {
const secret = await unseal(master_key, sealed_secret, SHARE_SECRET_AAD);
const link_secret = to_base64url(secret);
secret.fill(0);
return link_secret;
}
// Throws if the link secret is malformed or doesn't match the metadata
export async function decrypt_share_metadata(link_secret: string, metadata: string) {
const invalid = new Error("This link is invalid or incomplete");
let secret: Uint8Array<ArrayBuffer>;
try {
secret = from_base64url(link_secret);
} catch {
throw invalid;
}
if (secret.length !== SECRET_LENGTH) {
throw invalid;
}
const share_key = await derive_share_key(secret);
secret.fill(0);
try {
return await parse_metadata(await unseal(share_key, metadata, SHARE_METADATA_AAD));
} catch {
throw invalid;
}
}
export function share_link(share_id: string, link_secret: string) {
return `${location.origin}/download/${encodeURIComponent(share_id)}/#${link_secret}`;
}
+13
View File
@@ -0,0 +1,13 @@
import { db, type FileRow, type ShareRow } from "./db.ts";
export const share_not_found = () => Response.json({ error: "This link has expired or was removed" }, { status: 404 });
// Anyone with a share id can read these, everything here is useless without the secret in the link
export async function get_shared_file(share_id: string) {
const share = await db.get_entry("shares", share_id) as ShareRow | undefined;
if (!share) {
return undefined;
}
const file = await db.get_entry("files", share.file_id) as FileRow | undefined;
return file && { share, file };
}
+20
View File
@@ -4,6 +4,8 @@ import { FILE_UPLOAD_PATH } from "./server_constants.ts";
export class UploadTooLargeError extends Error {}
export const UPLOAD_CSP = "sandbox; default-src 'none'";
function upload_path(storage_id: string) {
if (!FILE_UPLOAD_PATH) {
throw new Error("FILE_UPLOAD_PATH isn't set");
@@ -43,6 +45,24 @@ export async function open_upload(storage_id: string) {
return await Deno.open(upload_path(storage_id), { read: true });
}
// Streams the encrypted file, undefined if it's missing from disk
export async function upload_response(storage_id: string) {
const stored = await open_upload(storage_id).catch(() => undefined);
if (!stored) {
return undefined;
}
// The body is whatever the uploader sent, so browsers must never render it on this origin
return new Response(stored.readable, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment",
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": UPLOAD_CSP,
"Cache-Control": "no-store",
},
});
}
export async function delete_upload(storage_id: string) {
try {
await Deno.remove(upload_path(storage_id));
+5
View File
@@ -4,4 +4,9 @@ import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [fresh(), tailwindcss()],
server: {
watch: {
ignored: ["**/__vces/**"],
},
},
});