File sharing
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
+17
-4
@@ -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>
|
||||
);
|
||||
|
||||
+130
-8
@@ -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" />
|
||||
<div class="flex flex-row flex-wrap items-center gap-x-6 gap-y-2">
|
||||
<Button
|
||||
variant="link"
|
||||
class="flex items-center gap-2 self-start"
|
||||
class="flex items-center gap-2"
|
||||
disabled={busy.value !== null}
|
||||
onClick={() => download(file)}
|
||||
>
|
||||
<DownloadIcon class="h-4 w-3" />
|
||||
{busy.value?.id === file.id && busy.value.action === "download"
|
||||
? "Downloading..."
|
||||
: "Download"}
|
||||
{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>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
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>
|
||||
<p class="mt-2 leading-loose text-gray-800 dark:text-gray-400">
|
||||
It's decrypted in this browser, the server never sees what's inside.
|
||||
</p>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -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 });
|
||||
},
|
||||
});
|
||||
@@ -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 => ({
|
||||
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,
|
||||
})).reverse(),
|
||||
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 },
|
||||
);
|
||||
|
||||
@@ -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" },
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -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();
|
||||
},
|
||||
});
|
||||
@@ -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} />;
|
||||
});
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+31
-3
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
import type { FileEntry, SharedFileEntry, ShareEntry } from "./files.ts";
|
||||
import type { NewShare } from "./share_crypto.ts";
|
||||
|
||||
function auth_headers() {
|
||||
return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` };
|
||||
@@ -59,11 +60,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
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -43,6 +43,20 @@ 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;
|
||||
}
|
||||
return new Response(stored.readable, {
|
||||
headers: {
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function delete_upload(storage_id: string) {
|
||||
try {
|
||||
await Deno.remove(upload_path(storage_id));
|
||||
|
||||
Reference in New Issue
Block a user