From de1ad700687e2864848a6f3cb870aadc8ca4cef1 Mon Sep 17 00:00:00 2001 From: Paula Date: Thu, 29 Oct 2026 20:44:26 -0300 Subject: [PATCH] File sharing --- components/Icons.tsx | 20 +++++ islands/Hub.tsx | 21 ++++- islands/HubFileList.tsx | 152 +++++++++++++++++++++++++++++---- islands/SharedDownload.tsx | 88 +++++++++++++++++++ routes/api/files/[id].ts | 20 ++--- routes/api/files/[id]/share.ts | 62 ++++++++++++++ routes/api/files/index.ts | 21 +++-- routes/api/shares/[id].ts | 15 ++++ routes/api/shares/[id]/file.ts | 14 +++ routes/download/[id].tsx | 13 +++ src/db.ts | 12 +++ src/file_crypto.ts | 42 +++++---- src/files.ts | 13 +++ src/files_api.ts | 34 +++++++- src/keys.ts | 13 ++- src/share_crypto.ts | 74 ++++++++++++++++ src/shares.ts | 13 +++ src/storage.ts | 14 +++ 18 files changed, 582 insertions(+), 59 deletions(-) create mode 100644 islands/SharedDownload.tsx create mode 100644 routes/api/files/[id]/share.ts create mode 100644 routes/api/shares/[id].ts create mode 100644 routes/api/shares/[id]/file.ts create mode 100644 routes/download/[id].tsx create mode 100644 src/share_crypto.ts create mode 100644 src/shares.ts diff --git a/components/Icons.tsx b/components/Icons.tsx index 96ae1e4..bf76ee2 100644 --- a/components/Icons.tsx +++ b/components/Icons.tsx @@ -46,3 +46,23 @@ export function DownloadIcon(props: IconProps) { ); } + +export function ShareIcon(props: IconProps) { + return ( + + ); +} + +export function CopyIcon(props: IconProps) { + return ( + + ); +} diff --git a/islands/Hub.tsx b/islands/Hub.tsx index 8219415..d2526c1 100644 --- a/islands/Hub.tsx +++ b/islands/Hub.tsx @@ -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 { + 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 { 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) { />
- +
); diff --git a/islands/HubFileList.tsx b/islands/HubFileList.tsx index 6e5afba..2f2ce2e 100644 --- a/islands/HubFileList.tsx +++ b/islands/HubFileList.tsx @@ -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 ( +
+ event.currentTarget.select()} + /> + +
+ ); +} + interface HubFileListProps { files: Signal; + 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(null); const error = useSignal(""); - async function run(file: HubFile, action: "download" | "delete", fn: () => Promise) { + async function run(file: HubFile, action: FileAction, fn: () => Promise) { 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 && ( <>
- +
+ + {file.share + ? ( + + ) + : ( + + )} +
+ {file.share && ( + copy(file, link)} + /> + )} )} diff --git a/islands/SharedDownload.tsx b/islands/SharedDownload.tsx new file mode 100644 index 0000000..231a15e --- /dev/null +++ b/islands/SharedDownload.tsx @@ -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(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 + ? + :

Loading...

; + } + + return ( +
+

Download a shared file

+

+ It's decrypted in this browser, the server never sees what's inside. +

+
+ +
+ + {error.value && } +
+ ); +} diff --git a/routes/api/files/[id].ts b/routes/api/files/[id].ts index 911dc6c..d89b275 100644 --- a/routes/api/files/[id].ts +++ b/routes/api/files/[id].ts @@ -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 }); diff --git a/routes/api/files/[id]/share.ts b/routes/api/files/[id]/share.ts new file mode 100644 index 0000000..17ff1fd --- /dev/null +++ b/routes/api/files/[id]/share.ts @@ -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 }); + }, +}); diff --git a/routes/api/files/index.ts b/routes/api/files/index.ts index 8dd0038..2aac4fc 100644 --- a/routes/api/files/index.ts +++ b/routes/api/files/index.ts @@ -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 }, ); diff --git a/routes/api/shares/[id].ts b/routes/api/shares/[id].ts new file mode 100644 index 0000000..72360f2 --- /dev/null +++ b/routes/api/shares/[id].ts @@ -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" }, + }); + }, +}); diff --git a/routes/api/shares/[id]/file.ts b/routes/api/shares/[id]/file.ts new file mode 100644 index 0000000..cb89227 --- /dev/null +++ b/routes/api/shares/[id]/file.ts @@ -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(); + }, +}); diff --git a/routes/download/[id].tsx b/routes/download/[id].tsx new file mode 100644 index 0000000..17ee6d3 --- /dev/null +++ b/routes/download/[id].tsx @@ -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//#, the trailing slash is optional +export const config: RouteConfig = { + routeOverride: "/download/:id{/}?", +}; + +export default define.page(function ({ params }) { + return ; +}); diff --git a/src/db.ts b/src/db.ts index aa39647..bb3d03e 100644 --- a/src/db.ts +++ b/src/db.ts @@ -21,15 +21,27 @@ export interface StoredFile extends Record { metadata: string; } +export interface StoredShare extends Record { + 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(DATABASE_PATH ?? ":memory:", { users: ["code"], files: ["user_id"], + shares: ["user_id", "file_id"], }); diff --git a/src/file_crypto.ts b/src/file_crypto.ts index 0032c20..24e69a7 100644 --- a/src/file_crypto.ts +++ b/src/file_crypto.ts @@ -29,26 +29,36 @@ function chunk_iv(index: number, last: boolean) { return iv; } -async function encrypt_metadata(master_key: CryptoKey, metadata: Record) { +// Encrypts with a random IV, which goes in front of the ciphertext +export async function seal(key: CryptoKey, plaintext: Uint8Array, aad: Uint8Array) { 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 { - 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) { + 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 { 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 { 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 diff --git a/src/files.ts b/src/files.ts index 88b2b4b..6397470 100644 --- a/src/files.ts +++ b/src/files.ts @@ -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; } diff --git a/src/files_api.ts b/src/files_api.ts index 38d5a77..db00a9f 100644 --- a/src/files_api.ts +++ b/src/files_api.ts @@ -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) { + return fetch_json(`/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(`/api/files/${encodeURIComponent(id)}/share`, { + method: "DELETE", + headers: auth_headers(), + }); +} + +export function get_shared_file(share_id: string) { + return fetch_json(`/api/shares/${encodeURIComponent(share_id)}`, {}); +} + +export function download_shared_file(share_id: string, metadata: FileMetadata) { + return download(`/api/shares/${encodeURIComponent(share_id)}/file`, metadata); +} diff --git a/src/keys.ts b/src/keys.ts index e9acf14..7a06f5e 100644 --- a/src/keys.ts +++ b/src/keys.ts @@ -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; 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; } diff --git a/src/share_crypto.ts b/src/share_crypto.ts new file mode 100644 index 0000000..7162a04 --- /dev/null +++ b/src/share_crypto.ts @@ -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) { + 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 { + 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; + 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}`; +} diff --git a/src/shares.ts b/src/shares.ts new file mode 100644 index 0000000..568a193 --- /dev/null +++ b/src/shares.ts @@ -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 }; +} diff --git a/src/storage.ts b/src/storage.ts index 2356b86..efb65ec 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -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));