1 Commits

Author SHA1 Message Date
static
122970a6ea HMAC 계산을 Web Worker에서 처리하도록 변경 2026-01-12 12:47:37 +09:00
115 changed files with 2071 additions and 3359 deletions

View File

@@ -12,3 +12,4 @@ USER_CLIENT_CHALLENGE_EXPIRES=
SESSION_UPGRADE_CHALLENGE_EXPIRES= SESSION_UPGRADE_CHALLENGE_EXPIRES=
LIBRARY_PATH= LIBRARY_PATH=
THUMBNAILS_PATH= THUMBNAILS_PATH=
UPLOADS_PATH=

View File

@@ -1,45 +0,0 @@
name: Docker Image Build
on:
release:
types: [published]
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract Docker metadata
uses: docker/metadata-action@v5
id: meta
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=raw,value=latest
type=sha
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@@ -20,6 +20,7 @@ services:
- SESSION_UPGRADE_CHALLENGE_EXPIRES - SESSION_UPGRADE_CHALLENGE_EXPIRES
- LIBRARY_PATH=/app/data/library - LIBRARY_PATH=/app/data/library
- THUMBNAILS_PATH=/app/data/thumbnails - THUMBNAILS_PATH=/app/data/thumbnails
- UPLOADS_PATH=/app/data/uploads
# SvelteKit # SvelteKit
- ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For} - ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For}
- XFF_DEPTH=${TRUST_PROXY:-} - XFF_DEPTH=${TRUST_PROXY:-}

View File

@@ -1,7 +1,7 @@
{ {
"name": "arkvault", "name": "arkvault",
"private": true, "private": true,
"version": "0.9.1", "version": "0.8.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
@@ -16,56 +16,55 @@
"db:migrate": "kysely migrate" "db:migrate": "kysely migrate"
}, },
"devDependencies": { "devDependencies": {
"@eslint/compat": "^2.0.3", "@eslint/compat": "^2.0.1",
"@eslint/js": "^9.39.4", "@eslint/js": "^9.39.2",
"@iconify-json/material-symbols": "^1.2.61", "@iconify-json/material-symbols": "^1.2.51",
"@noble/hashes": "^2.0.1", "@noble/hashes": "^2.0.1",
"@sveltejs/adapter-node": "^5.5.4", "@sveltejs/adapter-node": "^5.4.0",
"@sveltejs/kit": "^2.53.4", "@sveltejs/kit": "^2.49.4",
"@sveltejs/vite-plugin-svelte": "^6.2.4", "@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tanstack/svelte-virtual": "^3.13.21", "@tanstack/svelte-virtual": "^3.13.18",
"@trpc/client": "^11.12.0", "@trpc/client": "^11.8.1",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
"@types/ms": "^0.7.34", "@types/ms": "^0.7.34",
"@types/node-schedule": "^2.1.8", "@types/node-schedule": "^2.1.8",
"@types/pg": "^8.18.0", "@types/pg": "^8.16.0",
"autoprefixer": "^10.4.27", "autoprefixer": "^10.4.23",
"axios": "^1.13.6", "axios": "^1.13.2",
"dexie": "^4.3.0", "dexie": "^4.2.1",
"es-hangul": "^2.3.8", "eslint": "^9.39.2",
"eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.15.2", "eslint-plugin-svelte": "^3.14.0",
"eslint-plugin-tailwindcss": "^3.18.2", "eslint-plugin-tailwindcss": "^3.18.2",
"exifreader": "^4.36.2", "exifreader": "^4.35.0",
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"globals": "^17.4.0", "globals": "^17.0.0",
"heic2any": "^0.0.4", "heic2any": "^0.0.4",
"kysely-ctl": "^0.20.0", "kysely-ctl": "^0.19.0",
"lru-cache": "^11.2.6", "lru-cache": "^11.2.4",
"mime": "^4.1.0", "mime": "^4.1.0",
"p-limit": "^7.3.0", "p-limit": "^7.2.0",
"prettier": "^3.8.1", "prettier": "^3.7.4",
"prettier-plugin-svelte": "^3.5.1", "prettier-plugin-svelte": "^3.4.1",
"prettier-plugin-tailwindcss": "^0.7.2", "prettier-plugin-tailwindcss": "^0.7.2",
"svelte": "^5.53.9", "svelte": "^5.46.1",
"svelte-check": "^4.4.5", "svelte-check": "^4.3.5",
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"typescript-eslint": "^8.57.0", "typescript-eslint": "^8.52.0",
"unplugin-icons": "^23.0.1", "unplugin-icons": "^22.5.0",
"vite": "^7.3.1" "vite": "^7.3.1"
}, },
"dependencies": { "dependencies": {
"@trpc/server": "^11.12.0", "@trpc/server": "^11.8.1",
"argon2": "^0.44.0", "argon2": "^0.44.0",
"kysely": "^0.28.11", "kysely": "^0.28.9",
"ms": "^2.1.3", "ms": "^2.1.3",
"node-schedule": "^2.1.1", "node-schedule": "^2.1.1",
"pg": "^8.20.0", "pg": "^8.16.3",
"superjson": "^2.2.6", "superjson": "^2.2.6",
"uuid": "^13.0.0", "uuid": "^13.0.0",
"zod": "^4.3.6" "zod": "^4.3.5"
}, },
"engines": { "engines": {
"node": "^22.0.0", "node": "^22.0.0",

1436
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,8 +7,8 @@ import {
cleanupExpiredSessions, cleanupExpiredSessions,
cleanupExpiredSessionUpgradeChallenges, cleanupExpiredSessionUpgradeChallenges,
} from "$lib/server/db/session"; } from "$lib/server/db/session";
import { authenticate, setAgentInfo } from "$lib/server/middlewares";
import { cleanupExpiredUploadSessions } from "$lib/server/services/upload"; import { cleanupExpiredUploadSessions } from "$lib/server/services/upload";
import { authenticate, setAgentInfo } from "$lib/server/middlewares";
export const init: ServerInit = async () => { export const init: ServerInit = async () => {
await migrateDB(); await migrateDB();

View File

@@ -1,53 +0,0 @@
<script lang="ts">
import type { Snippet } from "svelte";
import type { ClassValue } from "svelte/elements";
import IconClose from "~icons/material-symbols/close";
interface Props {
children: Snippet;
class?: ClassValue;
onclick?: () => void;
onRemoveClick?: () => void;
removable?: boolean;
selected?: boolean;
}
let {
children,
class: className,
onclick = () => (selected = !selected),
onRemoveClick,
removable = false,
selected = $bindable(false),
}: Props = $props();
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
onclick={onclick && (() => setTimeout(onclick, 100))}
class={[
"inline-flex cursor-pointer items-center gap-x-1 rounded-lg px-3 py-1.5 text-sm font-medium transition active:scale-95",
selected
? "bg-primary-500 text-white active:bg-primary-400"
: "bg-gray-100 text-gray-700 active:bg-gray-200",
className,
]}
>
<span>
{@render children()}
</span>
{#if removable && selected}
<button
onclick={(e) => {
e.stopPropagation();
if (onRemoveClick) {
setTimeout(onRemoveClick, 100);
}
}}
>
<IconClose />
</button>
{/if}
</div>

View File

@@ -6,22 +6,13 @@
interface Props { interface Props {
class?: ClassValue; class?: ClassValue;
count: number; count: number;
estimateItemHeight: (index: number) => number;
getItemKey?: (index: number) => string | number;
item: Snippet<[index: number]>; item: Snippet<[index: number]>;
itemHeight: (index: number) => number;
itemGap?: number; itemGap?: number;
placeholder?: Snippet; placeholder?: Snippet;
} }
let { let { class: className, count, item, itemHeight, itemGap, placeholder }: Props = $props();
class: className,
count,
estimateItemHeight,
getItemKey,
item,
itemGap,
placeholder,
}: Props = $props();
let element: HTMLElement | undefined = $state(); let element: HTMLElement | undefined = $state();
let scrollMargin = $state(0); let scrollMargin = $state(0);
@@ -29,9 +20,8 @@
let virtualizer = $derived( let virtualizer = $derived(
createWindowVirtualizer({ createWindowVirtualizer({
count, count,
estimateSize: estimateItemHeight, estimateSize: itemHeight,
gap: itemGap, gap: itemGap,
getItemKey: getItemKey,
scrollMargin, scrollMargin,
}), }),
); );

View File

@@ -49,7 +49,7 @@
</div> </div>
</div> </div>
<style lang="postcss"> <style>
#container:active:not(:has(#action-button:active)) { #container:active:not(:has(#action-button:active)) {
@apply bg-gray-100; @apply bg-gray-100;
} }

View File

@@ -2,8 +2,6 @@
import { getFileThumbnail } from "$lib/modules/file"; import { getFileThumbnail } from "$lib/modules/file";
import type { SummarizedFileInfo } from "$lib/modules/filesystem"; import type { SummarizedFileInfo } from "$lib/modules/filesystem";
import IconFavorite from "~icons/material-symbols/favorite";
interface Props { interface Props {
info: SummarizedFileInfo; info: SummarizedFileInfo;
onclick?: (file: SummarizedFileInfo) => void; onclick?: (file: SummarizedFileInfo) => void;
@@ -16,19 +14,11 @@
<button <button
onclick={onclick && (() => setTimeout(() => onclick(info), 100))} onclick={onclick && (() => setTimeout(() => onclick(info), 100))}
class="relative aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90" class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
> >
{#if $thumbnail} {#if $thumbnail}
<img src={$thumbnail} alt={info.name} class="h-full w-full object-cover" /> <img src={$thumbnail} alt={info.name} class="h-full w-full object-cover" />
{:else} {:else}
<div class="h-full w-full bg-gray-100"></div> <div class="h-full w-full bg-gray-100"></div>
{/if} {/if}
{#if info.isFavorite}
<div class={["absolute bottom-0.5 right-0.5"]}>
<IconFavorite
class="text-sm text-red-500"
style="filter: drop-shadow(0 0 1px white) drop-shadow(0 0 1px white)"
/>
</div>
{/if}
</button> </button>

View File

@@ -1,6 +1,5 @@
export { default as BottomSheet } from "./BottomSheet.svelte"; export { default as BottomSheet } from "./BottomSheet.svelte";
export * from "./buttons"; export * from "./buttons";
export { default as Chip } from "./Chip.svelte";
export * from "./divs"; export * from "./divs";
export * from "./inputs"; export * from "./inputs";
export { default as Modal } from "./Modal.svelte"; export { default as Modal } from "./Modal.svelte";

View File

@@ -28,7 +28,7 @@
</div> </div>
</div> </div>
<style lang="postcss"> <style>
input:focus, input:focus,
input:not(:placeholder-shown) { input:not(:placeholder-shown) {
@apply border-primary-300; @apply border-primary-300;

View File

@@ -10,9 +10,9 @@
class?: ClassValue; class?: ClassValue;
info: CategoryInfo; info: CategoryInfo;
onSubCategoryClick: (subCategory: SelectedCategory) => void; onSubCategoryClick: (subCategory: SelectedCategory) => void;
onSubCategoryCreateClick?: () => void; onSubCategoryCreateClick: () => void;
onSubCategoryMenuClick?: (category: SelectedCategory) => void; onSubCategoryMenuClick?: (category: SelectedCategory) => void;
subCategoryCreatePosition?: "top" | "bottom" | "none"; subCategoryCreatePosition?: "top" | "bottom";
subCategoryMenuIcon?: Component<SvelteHTMLElements["svg"]>; subCategoryMenuIcon?: Component<SvelteHTMLElements["svg"]>;
} }
@@ -22,7 +22,7 @@
onSubCategoryClick, onSubCategoryClick,
onSubCategoryCreateClick, onSubCategoryCreateClick,
onSubCategoryMenuClick, onSubCategoryMenuClick,
subCategoryCreatePosition = "none", subCategoryCreatePosition = "bottom",
subCategoryMenuIcon, subCategoryMenuIcon,
}: Props = $props(); }: Props = $props();
</script> </script>

View File

@@ -8,11 +8,10 @@
children?: Snippet; children?: Snippet;
class?: ClassValue; class?: ClassValue;
onBackClick?: () => void; onBackClick?: () => void;
showBackButton?: boolean;
title?: string; title?: string;
} }
let { children, class: className, onBackClick, showBackButton = true, title }: Props = $props(); let { children, class: className, onBackClick, title }: Props = $props();
</script> </script>
<div <div
@@ -21,16 +20,12 @@
className, className,
]} ]}
> >
<div class="w-[2.3rem] flex-shrink-0">
{#if showBackButton}
<button <button
onclick={onBackClick ?? (() => history.back())} onclick={onBackClick || (() => history.back())}
class="w-full rounded-full p-1 text-2xl active:bg-black active:bg-opacity-[0.04]" class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-black active:bg-opacity-[0.04]"
> >
<IconArrowBack /> <IconArrowBack class="text-2xl" />
</button> </button>
{/if}
</div>
{#if title} {#if title}
<p class="flex-grow truncate text-center text-lg font-semibold">{title}</p> <p class="flex-grow truncate text-center text-lg font-semibold">{title}</p>
{/if} {/if}

View File

@@ -5,11 +5,9 @@
import IconFolder from "~icons/material-symbols/folder"; import IconFolder from "~icons/material-symbols/folder";
import IconDriveFolderUpload from "~icons/material-symbols/drive-folder-upload"; import IconDriveFolderUpload from "~icons/material-symbols/drive-folder-upload";
import IconDraft from "~icons/material-symbols/draft"; import IconDraft from "~icons/material-symbols/draft";
import IconFavorite from "~icons/material-symbols/favorite";
interface Props { interface Props {
class?: ClassValue; class?: ClassValue;
isFavorite?: boolean;
name: string; name: string;
subtext?: string; subtext?: string;
textClass?: ClassValue; textClass?: ClassValue;
@@ -19,7 +17,6 @@
let { let {
class: className, class: className,
isFavorite = false,
name, name,
subtext, subtext,
textClass: textClassName, textClass: textClassName,
@@ -29,7 +26,7 @@
</script> </script>
{#snippet iconSnippet()} {#snippet iconSnippet()}
<div class="relative flex h-10 w-10 items-center justify-center text-xl"> <div class="flex h-10 w-10 items-center justify-center text-xl">
{#if thumbnail} {#if thumbnail}
<img src={thumbnail} alt={name} loading="lazy" class="aspect-square rounded object-cover" /> <img src={thumbnail} alt={name} loading="lazy" class="aspect-square rounded object-cover" />
{:else if type === "directory"} {:else if type === "directory"}
@@ -39,14 +36,6 @@
{:else} {:else}
<IconDraft class="text-blue-400" /> <IconDraft class="text-blue-400" />
{/if} {/if}
{#if isFavorite}
<div class={["absolute bottom-0 right-0", !thumbnail && "rounded-full bg-white p-0.5"]}>
<IconFavorite
class="text-xs text-red-500"
style="filter: drop-shadow(0 0 1px white) drop-shadow(0 0 1px white)"
/>
</div>
{/if}
</div> </div>
{/snippet} {/snippet}

View File

@@ -20,12 +20,7 @@ export const getFileCacheIndex = async () => {
}; };
export const storeFileCacheIndex = async (fileCacheIndex: FileCacheIndex) => { export const storeFileCacheIndex = async (fileCacheIndex: FileCacheIndex) => {
await cacheIndex.fileCache.put({ await cacheIndex.fileCache.put(fileCacheIndex);
fileId: fileCacheIndex.fileId,
cachedAt: fileCacheIndex.cachedAt,
lastRetrievedAt: fileCacheIndex.lastRetrievedAt,
size: fileCacheIndex.size,
});
}; };
export const deleteFileCacheIndex = async (fileId: number) => { export const deleteFileCacheIndex = async (fileId: number) => {

View File

@@ -4,7 +4,6 @@ interface DirectoryInfo {
id: number; id: number;
parentId: DirectoryId; parentId: DirectoryId;
name: string; name: string;
isFavorite: boolean;
} }
interface FileInfo { interface FileInfo {
@@ -15,7 +14,6 @@ interface FileInfo {
createdAt?: Date; createdAt?: Date;
lastModifiedAt: Date; lastModifiedAt: Date;
categoryIds?: number[]; categoryIds?: number[];
isFavorite: boolean;
} }
interface CategoryInfo { interface CategoryInfo {
@@ -48,23 +46,6 @@ filesystem
}); });
}); });
filesystem.version(4).upgrade(async (trx) => {
await Promise.all([
trx
.table("directory")
.toCollection()
.modify((directory) => {
directory.isFavorite = false;
}),
trx
.table("file")
.toCollection()
.modify((file) => {
file.isFavorite = false;
}),
]);
});
export const getDirectoryInfos = async (parentId: DirectoryId) => { export const getDirectoryInfos = async (parentId: DirectoryId) => {
return await filesystem.directory.where({ parentId }).toArray(); return await filesystem.directory.where({ parentId }).toArray();
}; };
@@ -74,11 +55,7 @@ export const getDirectoryInfo = async (id: number) => {
}; };
export const storeDirectoryInfo = async (directoryInfo: DirectoryInfo) => { export const storeDirectoryInfo = async (directoryInfo: DirectoryInfo) => {
await filesystem.directory.upsert(directoryInfo.id, { await filesystem.directory.upsert(directoryInfo.id, { ...directoryInfo });
parentId: directoryInfo.parentId,
name: directoryInfo.name,
isFavorite: directoryInfo.isFavorite,
});
}; };
export const deleteDirectoryInfo = async (id: number) => { export const deleteDirectoryInfo = async (id: number) => {
@@ -112,15 +89,7 @@ export const bulkGetFileInfos = async (ids: number[]) => {
}; };
export const storeFileInfo = async (fileInfo: FileInfo) => { export const storeFileInfo = async (fileInfo: FileInfo) => {
await filesystem.file.upsert(fileInfo.id, { await filesystem.file.upsert(fileInfo.id, { ...fileInfo });
parentId: fileInfo.parentId,
name: fileInfo.name,
contentType: fileInfo.contentType,
createdAt: fileInfo.createdAt,
lastModifiedAt: fileInfo.lastModifiedAt,
categoryIds: fileInfo.categoryIds,
isFavorite: fileInfo.isFavorite,
});
}; };
export const deleteFileInfo = async (id: number) => { export const deleteFileInfo = async (id: number) => {
@@ -147,12 +116,7 @@ export const getCategoryInfo = async (id: number) => {
}; };
export const storeCategoryInfo = async (categoryInfo: CategoryInfo) => { export const storeCategoryInfo = async (categoryInfo: CategoryInfo) => {
await filesystem.category.upsert(categoryInfo.id, { await filesystem.category.upsert(categoryInfo.id, { ...categoryInfo });
parentId: categoryInfo.parentId,
name: categoryInfo.name,
files: categoryInfo.files,
isFileRecursive: categoryInfo.isFileRecursive,
});
}; };
export const updateCategoryInfo = async (id: number, changes: { isFileRecursive?: boolean }) => { export const updateCategoryInfo = async (id: number, changes: { isFileRecursive?: boolean }) => {

View File

@@ -0,0 +1,30 @@
import { hmac } from "@noble/hashes/hmac.js";
import { sha256 } from "@noble/hashes/sha2.js";
interface ComputeMessage {
type: "compute";
file: File;
hmacSecret: ArrayBuffer;
}
type WorkerMessage = ComputeMessage;
self.onmessage = async (event: MessageEvent<WorkerMessage>) => {
const { type } = event.data;
if (type === "compute") {
const { file, hmacSecret } = event.data;
const h = hmac.create(sha256, new Uint8Array(hmacSecret));
const reader = file.stream().getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
h.update(value);
}
const result = h.digest();
self.postMessage({ type: "result", hmac: result }, { transfer: [result.buffer] });
}
};

View File

@@ -0,0 +1,25 @@
import HmacWorker from "./hmac.worker?worker";
export const computeFileHmac = async (file: File, hmacSecret: CryptoKey): Promise<Uint8Array> => {
const worker = new HmacWorker();
const hmacSecretRaw = await crypto.subtle.exportKey("raw", hmacSecret);
return new Promise((resolve, reject) => {
worker.onmessage = (event: MessageEvent<{ type: "result"; hmac: Uint8Array }>) => {
if (event.data.type === "result") {
resolve(event.data.hmac);
worker.terminate();
}
};
worker.onerror = (error) => {
reject(error);
worker.terminate();
};
worker.postMessage(
{ type: "compute", file, hmacSecret: hmacSecretRaw },
{ transfer: [hmacSecretRaw] },
);
});
};

View File

@@ -1,5 +1,5 @@
import HmacWorker from "$workers/hmac?worker"; import { hmac } from "@noble/hashes/hmac.js";
import type { ComputeMessage, ResultMessage } from "$workers/hmac"; import { sha256 } from "@noble/hashes/sha2.js";
export const digestMessage = async (message: BufferSource) => { export const digestMessage = async (message: BufferSource) => {
return await crypto.subtle.digest("SHA-256", message); return await crypto.subtle.digest("SHA-256", message);
@@ -18,24 +18,10 @@ export const generateHmacSecret = async () => {
}; };
}; };
export const signMessageHmac = async (message: Blob, hmacSecret: CryptoKey) => { export const createHmacStream = async (hmacSecret: CryptoKey) => {
const stream = message.stream(); const h = hmac.create(sha256, new Uint8Array(await crypto.subtle.exportKey("raw", hmacSecret)));
const hmacSecretRaw = new Uint8Array(await crypto.subtle.exportKey("raw", hmacSecret)); return {
const worker = new HmacWorker(); update: (data: Uint8Array) => h.update(data),
digest: () => h.digest(),
return new Promise<Uint8Array>((resolve, reject) => {
worker.onmessage = ({ data }: MessageEvent<ResultMessage>) => {
resolve(data.result);
worker.terminate();
}; };
worker.onerror = ({ error }) => {
reject(error);
worker.terminate();
};
worker.postMessage({ stream, key: hmacSecretRaw } satisfies ComputeMessage, {
transfer: [stream, hmacSecretRaw.buffer],
});
});
}; };

View File

@@ -1,6 +1,6 @@
import axios from "axios"; import axios from "axios";
import { limitFunction } from "p-limit"; import { limitFunction } from "p-limit";
import { ENCRYPTED_CHUNK_SIZE } from "$lib/constants"; import { CHUNK_SIZE, ENCRYPTION_OVERHEAD } from "$lib/constants";
import { decryptChunk, concatenateBuffers } from "$lib/modules/crypto"; import { decryptChunk, concatenateBuffers } from "$lib/modules/crypto";
export interface FileDownloadState { export interface FileDownloadState {
@@ -100,7 +100,7 @@ export const downloadFile = async (id: number, dataKey: CryptoKey, isLegacy: boo
return await decryptFile( return await decryptFile(
state, state,
fileEncrypted, fileEncrypted,
isLegacy ? fileEncrypted.byteLength : ENCRYPTED_CHUNK_SIZE, isLegacy ? fileEncrypted.byteLength : CHUNK_SIZE + ENCRYPTION_OVERHEAD,
dataKey, dataKey,
); );
} catch (e) { } catch (e) {

View File

@@ -1,7 +1,7 @@
import { LRUCache } from "lru-cache"; import { LRUCache } from "lru-cache";
import { writable, type Writable } from "svelte/store"; import { writable, type Writable } from "svelte/store";
import { browser } from "$app/environment"; import { browser } from "$app/environment";
import { decryptChunk } from "$lib/modules/crypto"; import { decryptData } from "$lib/modules/crypto";
import type { SummarizedFileInfo } from "$lib/modules/filesystem"; import type { SummarizedFileInfo } from "$lib/modules/filesystem";
import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs"; import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs";
import { getThumbnailUrl } from "$lib/modules/thumbnail"; import { getThumbnailUrl } from "$lib/modules/thumbnail";
@@ -20,7 +20,12 @@ const fetchFromServer = async (fileId: number, dataKey: CryptoKey) => {
const res = await fetch(`/api/file/${fileId}/thumbnail/download`); const res = await fetch(`/api/file/${fileId}/thumbnail/download`);
if (!res.ok) return null; if (!res.ok) return null;
const thumbnailBuffer = await decryptChunk(await res.arrayBuffer(), dataKey); const thumbnailEncrypted = await res.arrayBuffer();
const thumbnailBuffer = await decryptData(
thumbnailEncrypted.slice(12),
thumbnailEncrypted.slice(0, 12),
dataKey,
);
void writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer); void writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
return getThumbnailUrl(thumbnailBuffer); return getThumbnailUrl(thumbnailBuffer);

View File

@@ -2,15 +2,14 @@ import ExifReader from "exifreader";
import { limitFunction } from "p-limit"; import { limitFunction } from "p-limit";
import { CHUNK_SIZE } from "$lib/constants"; import { CHUNK_SIZE } from "$lib/constants";
import { encodeToBase64, generateDataKey, wrapDataKey, encryptString } from "$lib/modules/crypto"; import { encodeToBase64, generateDataKey, wrapDataKey, encryptString } from "$lib/modules/crypto";
import { signMessageHmac } from "$lib/modules/crypto"; import { computeFileHmac } from "$lib/modules/crypto/hmacWorker";
import { Scheduler } from "$lib/modules/scheduler";
import { generateThumbnail } from "$lib/modules/thumbnail"; import { generateThumbnail } from "$lib/modules/thumbnail";
import { uploadBlob } from "$lib/modules/upload"; import { uploadBlob } from "$lib/modules/upload";
import type { MasterKey, HmacSecret } from "$lib/stores"; import type { MasterKey, HmacSecret } from "$lib/stores";
import { Scheduler } from "$lib/utils";
import { trpc } from "$trpc/client"; import { trpc } from "$trpc/client";
export interface FileUploadState { export interface FileUploadState {
id: string;
name: string; name: string;
parentId: DirectoryId; parentId: DirectoryId;
status: status:
@@ -51,15 +50,9 @@ export const clearUploadedFiles = () => {
}; };
const requestDuplicateFileScan = limitFunction( const requestDuplicateFileScan = limitFunction(
async ( async (file: File, hmacSecret: HmacSecret, onDuplicate: () => Promise<boolean>) => {
state: FileUploadState, const hmacResult = await computeFileHmac(file, hmacSecret.secret);
file: File, const fileSigned = encodeToBase64(hmacResult);
hmacSecret: HmacSecret,
onDuplicate: () => Promise<boolean>,
) => {
state.status = "encryption-pending";
const fileSigned = encodeToBase64(await signMessageHmac(file, hmacSecret.secret));
const files = await trpc().file.listByHash.query({ const files = await trpc().file.listByHash.query({
hskVersion: hmacSecret.version, hskVersion: hmacSecret.version,
contentHmac: fileSigned, contentHmac: fileSigned,
@@ -105,21 +98,19 @@ const extractExifDateTime = (fileBuffer: ArrayBuffer) => {
return new Date(utcDate - offsetMs); return new Date(utcDate - offsetMs);
}; };
interface FileMetadata { const requestFileUpload2 = async (
state: FileUploadState,
file: Blob,
fileSigned: string,
fileMetadata: {
parentId: "root" | number; parentId: "root" | number;
name: string; name: string;
createdAt?: Date; createdAt?: Date;
lastModifiedAt: Date; lastModifiedAt: Date;
} },
const requestFileMetadataEncryption = limitFunction(
async (
state: FileUploadState,
file: Blob,
fileMetadata: FileMetadata,
masterKey: MasterKey, masterKey: MasterKey,
hmacSecret: HmacSecret, hmacSecret: HmacSecret,
) => { ) => {
state.status = "encrypting"; state.status = "encrypting";
const { dataKey, dataKeyVersion } = await generateDataKey(); const { dataKey, dataKeyVersion } = await generateDataKey();
@@ -128,8 +119,7 @@ const requestFileMetadataEncryption = limitFunction(
const [nameEncrypted, createdAtEncrypted, lastModifiedAtEncrypted, thumbnailBuffer] = const [nameEncrypted, createdAtEncrypted, lastModifiedAtEncrypted, thumbnailBuffer] =
await Promise.all([ await Promise.all([
encryptString(fileMetadata.name, dataKey), encryptString(fileMetadata.name, dataKey),
fileMetadata.createdAt && fileMetadata.createdAt && encryptString(fileMetadata.createdAt.getTime().toString(), dataKey),
encryptString(fileMetadata.createdAt.getTime().toString(), dataKey),
encryptString(fileMetadata.lastModifiedAt.getTime().toString(), dataKey), encryptString(fileMetadata.lastModifiedAt.getTime().toString(), dataKey),
generateThumbnail(file).then((blob) => blob?.arrayBuffer()), generateThumbnail(file).then((blob) => blob?.arrayBuffer()),
]); ]);
@@ -150,39 +140,21 @@ const requestFileMetadataEncryption = limitFunction(
lastModifiedAtIv: lastModifiedAtEncrypted.iv, lastModifiedAtIv: lastModifiedAtEncrypted.iv,
}); });
state.status = "upload-pending";
return { uploadId, thumbnailBuffer, dataKey, dataKeyVersion };
},
{ concurrency: 4 },
);
const requestFileUpload = limitFunction(
async (
state: FileUploadState,
uploadId: string,
file: Blob,
fileSigned: string,
thumbnailBuffer: ArrayBuffer | undefined,
dataKey: CryptoKey,
dataKeyVersion: Date,
) => {
state.status = "uploading"; state.status = "uploading";
const { encContentHash } = await uploadBlob(uploadId, file, dataKey, { await uploadBlob(uploadId, file, dataKey, {
onProgress(s) { onProgress(s) {
state.progress = s.progress; state.progress = s.progress;
state.rate = s.rate; state.rate = s.rateBps;
}, },
}); });
const { file: fileId } = await trpc().upload.completeFileUpload.mutate({ const { file: fileId } = await trpc().upload.completeFileUpload.mutate({
uploadId, uploadId,
contentHmac: fileSigned, contentHmac: fileSigned,
encContentHash,
}); });
if (thumbnailBuffer) { if (thumbnailBuffer) {
try {
const { uploadId } = await trpc().upload.startFileThumbnailUpload.mutate({ const { uploadId } = await trpc().upload.startFileThumbnailUpload.mutate({
file: fileId, file: fileId,
dekVersion: dataKeyVersion, dekVersion: dataKeyVersion,
@@ -191,16 +163,12 @@ const requestFileUpload = limitFunction(
await uploadBlob(uploadId, new Blob([thumbnailBuffer]), dataKey); await uploadBlob(uploadId, new Blob([thumbnailBuffer]), dataKey);
await trpc().upload.completeFileThumbnailUpload.mutate({ uploadId }); await trpc().upload.completeFileThumbnailUpload.mutate({ uploadId });
} catch (e) {
console.error(e);
}
} }
state.status = "uploaded"; state.status = "uploaded";
return { fileId };
}, return { fileId, thumbnailBuffer };
{ concurrency: 1 }, };
);
export const uploadFile = async ( export const uploadFile = async (
file: File, file: File,
@@ -210,7 +178,6 @@ export const uploadFile = async (
onDuplicate: () => Promise<boolean>, onDuplicate: () => Promise<boolean>,
) => { ) => {
uploadingFiles.push({ uploadingFiles.push({
id: crypto.randomUUID(),
name: file.name, name: file.name,
parentId, parentId,
status: "queued", status: "queued",
@@ -218,44 +185,51 @@ export const uploadFile = async (
const state = uploadingFiles.at(-1)!; const state = uploadingFiles.at(-1)!;
return await scheduler.schedule(file.size, async () => { return await scheduler.schedule(file.size, async () => {
try { state.status = "encryption-pending";
const { fileSigned } = await requestDuplicateFileScan(state, file, hmacSecret, onDuplicate);
try {
const { fileSigned } = await requestDuplicateFileScan(file, hmacSecret, onDuplicate);
if (!fileSigned) { if (!fileSigned) {
state.status = "canceled"; state.status = "canceled";
uploadingFiles = uploadingFiles.filter((file) => file !== state); uploadingFiles = uploadingFiles.filter((file) => file !== state);
return; return;
} }
let fileBuffer;
const fileType = getFileType(file); const fileType = getFileType(file);
const fileMetadata: FileMetadata = { if (fileType.startsWith("image/")) {
const fileBuffer = await file.arrayBuffer();
const fileCreatedAt = extractExifDateTime(fileBuffer);
const { fileId, thumbnailBuffer } = await requestFileUpload2(
state,
new Blob([fileBuffer], { type: fileType }),
fileSigned,
{
parentId, parentId,
name: file.name, name: file.name,
createdAt: fileCreatedAt,
lastModifiedAt: new Date(file.lastModified), lastModifiedAt: new Date(file.lastModified),
}; },
masterKey,
if (fileType.startsWith("image/")) { hmacSecret,
fileBuffer = await file.arrayBuffer();
fileMetadata.createdAt = extractExifDateTime(fileBuffer);
}
const blob = new Blob([file], { type: fileType });
const { uploadId, thumbnailBuffer, dataKey, dataKeyVersion } =
await requestFileMetadataEncryption(state, blob, fileMetadata, masterKey, hmacSecret);
const { fileId } = await requestFileUpload(
state,
uploadId,
blob,
fileSigned,
thumbnailBuffer,
dataKey,
dataKeyVersion,
); );
return { fileId, fileBuffer, thumbnailBuffer }; return { fileId, fileBuffer, thumbnailBuffer };
} else {
const { fileId, thumbnailBuffer } = await requestFileUpload2(
state,
file,
fileSigned,
{
parentId,
name: file.name,
lastModifiedAt: new Date(file.lastModified),
},
masterKey,
hmacSecret,
);
return { fileId, thumbnailBuffer };
}
} catch (e) { } catch (e) {
state.status = "error"; state.status = "error";
throw e; throw e;

View File

@@ -21,7 +21,6 @@ const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo>({
name: fileInfo.name, name: fileInfo.name,
createdAt: fileInfo.createdAt, createdAt: fileInfo.createdAt,
lastModifiedAt: fileInfo.lastModifiedAt, lastModifiedAt: fileInfo.lastModifiedAt,
isFavorite: fileInfo.isFavorite,
isRecursive: file.isRecursive, isRecursive: file.isRecursive,
} }
: undefined; : undefined;
@@ -65,7 +64,6 @@ const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo>({
id: file.id, id: file.id,
parentId: file.parent, parentId: file.parent,
contentType: file.contentType, contentType: file.contentType,
isFavorite: file.isFavorite,
isRecursive: file.isRecursive, isRecursive: file.isRecursive,
...(await decryptFileMetadata(file, masterKey)), ...(await decryptFileMetadata(file, masterKey)),
})), })),

View File

@@ -26,7 +26,6 @@ const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
name: directory.name, name: directory.name,
subDirectories, subDirectories,
files, files,
isFavorite: directory.isFavorite,
}; };
} }
}, },
@@ -39,7 +38,6 @@ const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
directory.subDirectories.map(async (directory) => ({ directory.subDirectories.map(async (directory) => ({
id: directory.id, id: directory.id,
parentId: id, parentId: id,
isFavorite: directory.isFavorite,
...(await decryptDirectoryMetadata(directory, masterKey)), ...(await decryptDirectoryMetadata(directory, masterKey)),
})), })),
), ),
@@ -48,7 +46,6 @@ const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
id: file.id, id: file.id,
parentId: id, parentId: id,
contentType: file.contentType, contentType: file.contentType,
isFavorite: file.isFavorite,
...(await decryptFileMetadata(file, masterKey)), ...(await decryptFileMetadata(file, masterKey)),
})), })),
), ),
@@ -62,7 +59,6 @@ const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
parentId: directory.metadata!.parent, parentId: directory.metadata!.parent,
subDirectories, subDirectories,
files, files,
isFavorite: directory.metadata!.isFavorite,
...metadata!, ...metadata!,
} }
: { id, subDirectories, files }, : { id, subDirectories, files },
@@ -101,34 +97,6 @@ const storeToIndexedDB = (info: DirectoryInfo) => {
return { ...info, exists: true as const }; return { ...info, exists: true as const };
}; };
export const getDirectoryInfo = ( export const getDirectoryInfo = (id: DirectoryId, masterKey: CryptoKey) => {
id: DirectoryId, return cache.get(id, masterKey);
masterKey: CryptoKey,
options?: {
serverResponse?: {
parent: DirectoryId;
dek: string;
dekVersion: Date;
name: string;
nameIv: string;
isFavorite: boolean;
};
},
) => {
return cache.get(id, masterKey, {
fetchFromServer:
options?.serverResponse &&
(async (cachedValue) => {
const metadata = await decryptDirectoryMetadata(options!.serverResponse!, masterKey);
return storeToIndexedDB({
subDirectories: [],
files: [],
...cachedValue,
id: id as number,
parentId: options!.serverResponse!.parent,
isFavorite: options!.serverResponse!.isFavorite,
...metadata,
});
}),
});
}; };

View File

@@ -27,7 +27,6 @@ const cache = new FilesystemCache<number, MaybeFileInfo>({
createdAt: file.createdAt, createdAt: file.createdAt,
lastModifiedAt: file.lastModifiedAt, lastModifiedAt: file.lastModifiedAt,
categories: categories?.filter((category) => !!category) ?? [], categories: categories?.filter((category) => !!category) ?? [],
isFavorite: file.isFavorite,
}; };
} }
}, },
@@ -56,7 +55,6 @@ const cache = new FilesystemCache<number, MaybeFileInfo>({
createdAt: metadata.createdAt, createdAt: metadata.createdAt,
lastModifiedAt: metadata.lastModifiedAt, lastModifiedAt: metadata.lastModifiedAt,
categories, categories,
isFavorite: file.isFavorite,
}); });
} catch (e) { } catch (e) {
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") { if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
@@ -122,7 +120,6 @@ const cache = new FilesystemCache<number, MaybeFileInfo>({
parentId: metadataRaw.parent, parentId: metadataRaw.parent,
contentType: metadataRaw.contentType, contentType: metadataRaw.contentType,
categories, categories,
isFavorite: metadataRaw.isFavorite,
...metadata, ...metadata,
}; };
}), }),
@@ -171,41 +168,8 @@ const bulkStoreToIndexedDB = (infos: FileInfo[]) => {
return infos.map((info) => [info.id, { ...info, exists: true }] as const); return infos.map((info) => [info.id, { ...info, exists: true }] as const);
}; };
export const getFileInfo = ( export const getFileInfo = (id: number, masterKey: CryptoKey) => {
id: number, return cache.get(id, masterKey);
masterKey: CryptoKey,
options?: {
serverResponse?: {
parent: DirectoryId;
dek: string;
dekVersion: Date;
contentType: string;
name: string;
nameIv: string;
createdAt?: string;
createdAtIv?: string;
lastModifiedAt: string;
lastModifiedAtIv: string;
isFavorite: boolean;
};
},
) => {
return cache.get(id, masterKey, {
fetchFromServer:
options?.serverResponse &&
(async (cachedValue) => {
const metadata = await decryptFileMetadata(options!.serverResponse!, masterKey);
return storeToIndexedDB({
categories: [],
...cachedValue,
id,
parentId: options!.serverResponse!.parent,
contentType: options!.serverResponse!.contentType,
isFavorite: options!.serverResponse!.isFavorite,
...metadata,
});
}),
});
}; };
export const bulkGetFileInfo = (ids: number[], masterKey: CryptoKey) => { export const bulkGetFileInfo = (ids: number[], masterKey: CryptoKey) => {

View File

@@ -16,11 +16,7 @@ export class FilesystemCache<K, V extends object> {
constructor(private readonly options: FilesystemCacheOptions<K, V>) {} constructor(private readonly options: FilesystemCacheOptions<K, V>) {}
get( get(key: K, masterKey: CryptoKey) {
key: K,
masterKey: CryptoKey,
options?: { fetchFromServer?: (cachedValue: V | undefined) => Promise<V> },
) {
return untrack(() => { return untrack(() => {
let state = this.map.get(key); let state = this.map.get(key);
if (state?.promise) return state.value ?? state.promise; if (state?.promise) return state.value ?? state.promise;
@@ -34,7 +30,7 @@ export class FilesystemCache<K, V extends object> {
} }
(state.value (state.value
? Promise.resolve($state.snapshot(state.value) as V) ? Promise.resolve(state.value)
: this.options.fetchFromIndexedDB(key).then((loadedInfo) => { : this.options.fetchFromIndexedDB(key).then((loadedInfo) => {
if (loadedInfo) { if (loadedInfo) {
state.value = loadedInfo; state.value = loadedInfo;
@@ -43,11 +39,7 @@ export class FilesystemCache<K, V extends object> {
return loadedInfo; return loadedInfo;
}) })
) )
.then( .then((cachedInfo) => this.options.fetchFromServer(key, cachedInfo, masterKey))
(cachedInfo) =>
options?.fetchFromServer?.(cachedInfo) ??
this.options.fetchFromServer(key, cachedInfo, masterKey),
)
.then((loadedInfo) => { .then((loadedInfo) => {
if (state.value) { if (state.value) {
Object.assign(state.value, loadedInfo); Object.assign(state.value, loadedInfo);

View File

@@ -1,23 +1,22 @@
export type DataKey = { key: CryptoKey; version: Date }; export type DataKey = { key: CryptoKey; version: Date };
type AllUndefined<T> = { [K in keyof T]?: undefined };
export interface LocalDirectoryInfo { interface LocalDirectoryInfo {
id: number; id: number;
parentId: DirectoryId; parentId: DirectoryId;
dataKey?: DataKey; dataKey?: DataKey;
name: string; name: string;
subDirectories: SubDirectoryInfo[]; subDirectories: SubDirectoryInfo[];
files: SummarizedFileInfo[]; files: SummarizedFileInfo[];
isFavorite: boolean;
} }
export interface RootDirectoryInfo { interface RootDirectoryInfo {
id: "root"; id: "root";
parentId?: undefined; parentId?: undefined;
dataKey?: undefined; dataKey?: undefined;
name?: undefined; name?: undefined;
subDirectories: SubDirectoryInfo[]; subDirectories: SubDirectoryInfo[];
files: SummarizedFileInfo[]; files: SummarizedFileInfo[];
isFavorite?: undefined;
} }
export type DirectoryInfo = LocalDirectoryInfo | RootDirectoryInfo; export type DirectoryInfo = LocalDirectoryInfo | RootDirectoryInfo;
@@ -37,7 +36,6 @@ export interface FileInfo {
createdAt?: Date; createdAt?: Date;
lastModifiedAt: Date; lastModifiedAt: Date;
categories: FileCategoryInfo[]; categories: FileCategoryInfo[];
isFavorite: boolean;
} }
export type MaybeFileInfo = export type MaybeFileInfo =
@@ -47,7 +45,7 @@ export type MaybeFileInfo =
export type SummarizedFileInfo = Omit<FileInfo, "categories">; export type SummarizedFileInfo = Omit<FileInfo, "categories">;
export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean }; export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean };
export interface LocalCategoryInfo { interface LocalCategoryInfo {
id: number; id: number;
parentId: DirectoryId; parentId: DirectoryId;
dataKey?: DataKey; dataKey?: DataKey;
@@ -57,7 +55,7 @@ export interface LocalCategoryInfo {
isFileRecursive: boolean; isFileRecursive: boolean;
} }
export interface RootCategoryInfo { interface RootCategoryInfo {
id: "root"; id: "root";
parentId?: undefined; parentId?: undefined;
dataKey?: undefined; dataKey?: undefined;

View File

@@ -12,3 +12,11 @@ export const parseRangeHeader = (value: string | null) => {
export const getContentRangeHeader = (range?: { start: number; end: number; total: number }) => { export const getContentRangeHeader = (range?: { start: number; end: number; total: number }) => {
return range && { "Content-Range": `bytes ${range.start}-${range.end}/${range.total}` }; return range && { "Content-Range": `bytes ${range.start}-${range.end}/${range.total}` };
}; };
export const parseContentDigestHeader = (value: string | null) => {
if (!value) return undefined;
const firstDigest = value.split(",")[0]!.trim();
const match = firstDigest.match(/^sha-256=:([A-Za-z0-9+/=]+):$/);
return match?.[1];
};

View File

@@ -1,91 +1,51 @@
import { sha256 } from "@noble/hashes/sha2.js";
import axios from "axios"; import axios from "axios";
import pLimit from "p-limit"; import pLimit from "p-limit";
import { ENCRYPTION_OVERHEAD, CHUNK_SIZE } from "$lib/constants"; import { ENCRYPTION_OVERHEAD, CHUNK_SIZE } from "$lib/constants";
import { encodeToBase64, encryptChunk } from "$lib/modules/crypto"; import { encryptChunk, digestMessage, encodeToBase64 } from "$lib/modules/crypto";
import { BoundedQueue } from "$lib/utils";
interface UploadStats { type UploadStats = {
progress: number; progress: number; // 0..1 (암호화 후 기준)
rate: number; rateBps: number; // bytes/sec
} uploadedBytes: number;
totalBytes: number;
interface EncryptedChunk { };
index: number;
data: ArrayBuffer;
}
const createSpeedMeter = (timeWindow = 3000, minInterval = 200, warmupPeriod = 500) => {
const samples: { t: number; b: number }[] = [];
let lastSpeed = 0;
let startTime: number | null = null;
return (bytesNow?: number) => {
if (bytesNow === undefined) return lastSpeed;
function createSpeedMeter(windowMs = 1500) {
const samples: Array<{ t: number; b: number }> = [];
return (bytesNow: number) => {
const now = performance.now(); const now = performance.now();
// Initialize start time on first call
if (startTime === null) {
startTime = now;
}
// Check if enough time has passed since the last sample
const lastSample = samples[samples.length - 1];
if (lastSample && now - lastSample.t < minInterval) {
return lastSpeed;
}
samples.push({ t: now, b: bytesNow }); samples.push({ t: now, b: bytesNow });
const cutoff = now - windowMs;
// Remove old samples outside the time window
const cutoff = now - timeWindow;
while (samples.length > 2 && samples[0]!.t < cutoff) samples.shift(); while (samples.length > 2 && samples[0]!.t < cutoff) samples.shift();
// Need at least 2 samples to calculate speed
if (samples.length < 2) {
return lastSpeed;
}
const first = samples[0]!; const first = samples[0]!;
const dt = now - first.t; const dt = now - first.t;
const db = bytesNow - first.b; const db = bytesNow - first.b;
return dt > 0 ? (db / dt) * 1000 : 0;
if (dt >= minInterval) {
const instantSpeed = (db / dt) * 1000;
// Apply EMA for smoother speed transitions
const alpha = 0.3;
const rawSpeed =
lastSpeed === 0 ? instantSpeed : alpha * instantSpeed + (1 - alpha) * lastSpeed;
// Apply warmup ramp to prevent initial overestimation
const elapsed = now - startTime;
const warmupWeight = Math.min(1, elapsed / warmupPeriod);
lastSpeed = rawSpeed * warmupWeight;
}
return lastSpeed;
}; };
}; }
const encryptChunkData = async (chunk: Blob, dataKey: CryptoKey): Promise<ArrayBuffer> => { const uploadChunk = async (
return await encryptChunk(await chunk.arrayBuffer(), dataKey);
};
const uploadEncryptedChunk = async (
uploadId: string, uploadId: string,
chunkIndex: number, chunkIndex: number,
encrypted: ArrayBuffer, chunk: Blob,
dataKey: CryptoKey,
onChunkProgress: (chunkIndex: number, loaded: number) => void, onChunkProgress: (chunkIndex: number, loaded: number) => void,
) => { ) => {
await axios.post(`/api/upload/${uploadId}/chunks/${chunkIndex + 1}`, encrypted, { const chunkEncrypted = await encryptChunk(await chunk.arrayBuffer(), dataKey);
headers: { "Content-Type": "application/octet-stream" }, const chunkEncryptedHash = encodeToBase64(await digestMessage(chunkEncrypted));
await axios.post(`/api/upload/${uploadId}/chunks/${chunkIndex}`, chunkEncrypted, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Digest": `sha-256=:${chunkEncryptedHash}:`,
},
onUploadProgress(e) { onUploadProgress(e) {
onChunkProgress(chunkIndex, e.loaded ?? 0); onChunkProgress(chunkIndex, e.loaded ?? 0);
}, },
}); });
onChunkProgress(chunkIndex, encrypted.byteLength); onChunkProgress(chunkIndex, chunkEncrypted.byteLength);
}; };
export const uploadBlob = async ( export const uploadBlob = async (
@@ -95,24 +55,21 @@ export const uploadBlob = async (
options?: { concurrency?: number; onProgress?: (s: UploadStats) => void }, options?: { concurrency?: number; onProgress?: (s: UploadStats) => void },
) => { ) => {
const onProgress = options?.onProgress; const onProgress = options?.onProgress;
const networkConcurrency = options?.concurrency ?? 4;
const maxQueueSize = 8;
const totalChunks = Math.ceil(blob.size / CHUNK_SIZE); const totalChunks = Math.ceil(blob.size / CHUNK_SIZE);
const totalBytes = blob.size + totalChunks * ENCRYPTION_OVERHEAD; const totalBytes = blob.size + totalChunks * ENCRYPTION_OVERHEAD;
const uploadedByChunk = new Array<number>(totalChunks).fill(0); const uploadedByChunk = new Array<number>(totalChunks).fill(0);
const speedMeter = createSpeedMeter(3000, 200); const speedMeter = createSpeedMeter(1500);
const hash = sha256.create();
const emit = () => { const emit = () => {
if (!onProgress) return; if (!onProgress) return;
const uploadedBytes = uploadedByChunk.reduce((a, b) => a + b, 0); const uploadedBytes = uploadedByChunk.reduce((a, b) => a + b, 0);
const rate = speedMeter(uploadedBytes); const rateBps = speedMeter(uploadedBytes);
const progress = Math.min(1, uploadedBytes / totalBytes); const progress = Math.min(1, uploadedBytes / totalBytes);
onProgress({ progress, rate }); onProgress({ progress, rateBps, uploadedBytes, totalBytes });
}; };
const onChunkProgress = (idx: number, loaded: number) => { const onChunkProgress = (idx: number, loaded: number) => {
@@ -120,58 +77,27 @@ export const uploadBlob = async (
emit(); emit();
}; };
const queue = new BoundedQueue<EncryptedChunk>(maxQueueSize); const limit = pLimit(options?.concurrency ?? 4);
let encryptionError: Error | null = null;
// Producer: encrypt chunks and push to queue await Promise.all(
const encryptionProducer = async () => { Array.from({ length: totalChunks }, (_, chunkIndex) =>
try { limit(() =>
for (let i = 0; i < totalChunks; i++) { uploadChunk(
const chunk = blob.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE); uploadId,
const data = await encryptChunkData(chunk, dataKey); chunkIndex,
hash.update(new Uint8Array(data)); blob.slice(chunkIndex * CHUNK_SIZE, (chunkIndex + 1) * CHUNK_SIZE),
await queue.push({ index: i, data }); dataKey,
} onChunkProgress,
} catch (e) { ),
encryptionError = e instanceof Error ? e : new Error(String(e)); ),
} finally { ),
queue.close(); );
}
};
// Consumer: upload chunks from queue with concurrency limit // 완료 보정
const uploadConsumer = async () => { onProgress?.({
const limit = pLimit(networkConcurrency); progress: 1,
const activeTasks = new Set<Promise<void>>(); rateBps: 0,
uploadedBytes: totalBytes,
while (true) { totalBytes,
const item = await queue.pop();
if (item === null) break;
if (encryptionError) throw encryptionError;
const task = limit(async () => {
try {
await uploadEncryptedChunk(uploadId, item.index, item.data, onChunkProgress);
} finally {
// @ts-ignore
item.data = null;
}
}); });
activeTasks.add(task);
task.finally(() => activeTasks.delete(task));
if (activeTasks.size >= networkConcurrency) {
await Promise.race(activeTasks);
}
}
await Promise.all(activeTasks);
};
// Run producer and consumer concurrently
await Promise.all([encryptionProducer(), uploadConsumer()]);
onProgress?.({ progress: 1, rate: speedMeter() });
return { encContentHash: encodeToBase64(hash.digest()) };
}; };

View File

@@ -1,278 +0,0 @@
import type { Selectable } from "kysely";
import { IntegrityError } from "./error";
import db from "./kysely";
import type { Ciphertext, DirectoryTable } from "./schema";
interface Directory {
id: number;
parentId: DirectoryId;
userId: number;
mekVersion: number;
encDek: string;
dekVersion: Date;
encName: Ciphertext;
isFavorite: boolean;
}
const toDirectory = (row: Selectable<DirectoryTable>): Directory => ({
id: row.id,
parentId: row.parent_id ?? "root",
userId: row.user_id,
mekVersion: row.master_encryption_key_version,
encDek: row.encrypted_data_encryption_key,
dekVersion: row.data_encryption_key_version,
encName: row.encrypted_name,
isFavorite: row.is_favorite,
});
export const registerDirectory = async (params: Omit<Directory, "id" | "isFavorite">) => {
await db.transaction().execute(async (trx) => {
const mek = await trx
.selectFrom("master_encryption_key")
.select("version")
.where("user_id", "=", params.userId)
.where("state", "=", "active")
.limit(1)
.forUpdate()
.executeTakeFirst();
if (mek?.version !== params.mekVersion) {
throw new IntegrityError("Inactive MEK version");
}
const { directoryId } = await trx
.insertInto("directory")
.values({
parent_id: params.parentId !== "root" ? params.parentId : null,
user_id: params.userId,
master_encryption_key_version: params.mekVersion,
encrypted_data_encryption_key: params.encDek,
data_encryption_key_version: params.dekVersion,
encrypted_name: params.encName,
})
.returning("id as directoryId")
.executeTakeFirstOrThrow();
await trx
.insertInto("directory_log")
.values({
directory_id: directoryId,
timestamp: new Date(),
action: "create",
new_name: params.encName,
})
.execute();
});
};
export const getAllDirectoriesByParent = async (userId: number, parentId: DirectoryId) => {
const directories = await db
.selectFrom("directory")
.selectAll()
.where("user_id", "=", userId)
.$if(parentId === "root", (qb) => qb.where("parent_id", "is", null))
.$if(parentId !== "root", (qb) => qb.where("parent_id", "=", parentId as number))
.execute();
return directories.map(toDirectory);
};
export const getAllFavoriteDirectories = async (userId: number) => {
const directories = await db
.selectFrom("directory")
.selectAll()
.where("user_id", "=", userId)
.where("is_favorite", "=", true)
.execute();
return directories.map(toDirectory);
};
export const getDirectory = async (userId: number, directoryId: number) => {
const directory = await db
.selectFrom("directory")
.selectAll()
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.limit(1)
.executeTakeFirst();
return directory ? toDirectory(directory) : null;
};
export const searchDirectories = async (
userId: number,
filters: {
parentId: DirectoryId;
inFavorites: boolean;
},
) => {
const directories = await db
.withRecursive("directory_tree", (db) =>
db
.selectFrom("directory")
.select("id")
.where("user_id", "=", userId)
.$if(filters.parentId === "root", (qb) => qb.where((eb) => eb.lit(false))) // directory_tree will be empty if parentId is "root"
.$if(filters.parentId !== "root", (qb) => qb.where("id", "=", filters.parentId as number))
.unionAll(
db
.selectFrom("directory as d")
.innerJoin("directory_tree as dt", "d.parent_id", "dt.id")
.select("d.id"),
),
)
.withRecursive("favorite_directory_tree", (db) =>
db
.selectFrom("directory")
.select("id")
.where("user_id", "=", userId)
.$if(!filters.inFavorites, (qb) => qb.where((eb) => eb.lit(false))) // favorite_directory_tree will be empty if inFavorites is false
.$if(filters.inFavorites, (qb) => qb.where("is_favorite", "=", true))
.unionAll((db) =>
db
.selectFrom("directory as d")
.innerJoin("favorite_directory_tree as dt", "d.parent_id", "dt.id")
.select("d.id"),
),
)
.selectFrom("directory")
.selectAll()
.where("user_id", "=", userId)
.$if(filters.parentId !== "root", (qb) =>
qb.where((eb) =>
eb.exists(eb.selectFrom("directory_tree as dt").whereRef("dt.id", "=", "parent_id")),
),
)
.$if(filters.inFavorites, (qb) =>
qb.where((eb) =>
eb.exists(
eb.selectFrom("favorite_directory_tree as dt").whereRef("dt.id", "=", "directory.id"),
),
),
)
.execute();
return directories.map(toDirectory);
};
export const setDirectoryEncName = async (
userId: number,
directoryId: number,
dekVersion: Date,
encName: Ciphertext,
) => {
await db.transaction().execute(async (trx) => {
const directory = await trx
.selectFrom("directory")
.select("data_encryption_key_version")
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!directory) {
throw new IntegrityError("Directory not found");
} else if (directory.data_encryption_key_version.getTime() !== dekVersion.getTime()) {
throw new IntegrityError("Invalid DEK version");
}
await trx
.updateTable("directory")
.set({ encrypted_name: encName })
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.execute();
await trx
.insertInto("directory_log")
.values({
directory_id: directoryId,
timestamp: new Date(),
action: "rename",
new_name: encName,
})
.execute();
});
};
export const setDirectoryFavorite = async (
userId: number,
directoryId: number,
isFavorite: boolean,
) => {
await db.transaction().execute(async (trx) => {
const directory = await trx
.selectFrom("directory")
.select("is_favorite")
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!directory) {
throw new IntegrityError("Directory not found");
} else if (directory.is_favorite === isFavorite) {
throw new IntegrityError(
isFavorite ? "Directory already favorited" : "Directory not favorited",
);
}
await trx
.updateTable("directory")
.set({ is_favorite: isFavorite })
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.execute();
await trx
.insertInto("directory_log")
.values({
directory_id: directoryId,
timestamp: new Date(),
action: isFavorite ? "add-to-favorites" : "remove-from-favorites",
})
.execute();
});
};
export const unregisterDirectory = async (userId: number, directoryId: number) => {
return await db
.transaction()
.setIsolationLevel("repeatable read") // TODO: Sufficient?
.execute(async (trx) => {
const unregisterFiles = async (parentId: number) => {
const files = await trx
.selectFrom("file")
.leftJoin("thumbnail", "file.id", "thumbnail.file_id")
.select(["file.id", "file.path", "thumbnail.path as thumbnailPath"])
.where("file.parent_id", "=", parentId)
.where("file.user_id", "=", userId)
.forUpdate("file")
.execute();
await trx
.deleteFrom("file")
.where("parent_id", "=", parentId)
.where("user_id", "=", userId)
.execute();
return files;
};
const unregisterDirectoryRecursively = async (
directoryId: number,
): Promise<{ id: number; path: string; thumbnailPath: string | null }[]> => {
const files = await unregisterFiles(directoryId);
const subDirectories = await trx
.selectFrom("directory")
.select("id")
.where("parent_id", "=", directoryId)
.where("user_id", "=", userId)
.execute();
const subDirectoryFilePaths = await Promise.all(
subDirectories.map(async ({ id }) => await unregisterDirectoryRecursively(id)),
);
const deleteRes = await trx
.deleteFrom("directory")
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.executeTakeFirst();
if (deleteRes.numDeletedRows === 0n) {
throw new IntegrityError("Directory not found");
}
return files.concat(...subDirectoryFilePaths);
};
return await unregisterDirectoryRecursively(directoryId);
});
};

View File

@@ -8,13 +8,10 @@ type IntegrityErrorMessages =
| "User client already exists" | "User client already exists"
// File // File
| "Directory not found" | "Directory not found"
| "Directory already favorited"
| "Directory not favorited"
| "File not found" | "File not found"
| "File is not legacy"
| "File not found in category" | "File not found in category"
| "File already added to category" | "File already added to category"
| "File already favorited"
| "File not favorited"
| "Invalid DEK version" | "Invalid DEK version"
// HSK // HSK
| "HSK already registered" | "HSK already registered"

View File

@@ -1,9 +1,19 @@
import { sql, type Selectable } from "kysely"; import { sql } from "kysely";
import { jsonArrayFrom } from "kysely/helpers/postgres"; import { jsonArrayFrom } from "kysely/helpers/postgres";
import pg from "pg"; import pg from "pg";
import { IntegrityError } from "./error"; import { IntegrityError } from "./error";
import db from "./kysely"; import db from "./kysely";
import type { Ciphertext, FileTable } from "./schema"; import type { Ciphertext } from "./schema";
interface Directory {
id: number;
parentId: DirectoryId;
userId: number;
mekVersion: number;
encDek: string;
dekVersion: Date;
encName: Ciphertext;
}
interface File { interface File {
id: number; id: number;
@@ -21,7 +31,6 @@ interface File {
encName: Ciphertext; encName: Ciphertext;
encCreatedAt: Ciphertext | null; encCreatedAt: Ciphertext | null;
encLastModifiedAt: Ciphertext; encLastModifiedAt: Ciphertext;
isFavorite: boolean;
} }
interface FileCategory { interface FileCategory {
@@ -33,26 +42,175 @@ interface FileCategory {
encName: Ciphertext; encName: Ciphertext;
} }
const toFile = (row: Selectable<FileTable>): File => ({ export const registerDirectory = async (params: Omit<Directory, "id">) => {
id: row.id, await db.transaction().execute(async (trx) => {
parentId: row.parent_id ?? "root", const mek = await trx
userId: row.user_id, .selectFrom("master_encryption_key")
path: row.path, .select("version")
mekVersion: row.master_encryption_key_version, .where("user_id", "=", params.userId)
encDek: row.encrypted_data_encryption_key, .where("state", "=", "active")
dekVersion: row.data_encryption_key_version, .limit(1)
hskVersion: row.hmac_secret_key_version, .forUpdate()
contentHmac: row.content_hmac, .executeTakeFirst();
contentType: row.content_type, if (mek?.version !== params.mekVersion) {
encContentIv: row.encrypted_content_iv, throw new IntegrityError("Inactive MEK version");
encContentHash: row.encrypted_content_hash, }
encName: row.encrypted_name,
encCreatedAt: row.encrypted_created_at,
encLastModifiedAt: row.encrypted_last_modified_at,
isFavorite: row.is_favorite,
});
export const registerFile = async (trx: typeof db, params: Omit<File, "id" | "isFavorite">) => { const { directoryId } = await trx
.insertInto("directory")
.values({
parent_id: params.parentId !== "root" ? params.parentId : null,
user_id: params.userId,
master_encryption_key_version: params.mekVersion,
encrypted_data_encryption_key: params.encDek,
data_encryption_key_version: params.dekVersion,
encrypted_name: params.encName,
})
.returning("id as directoryId")
.executeTakeFirstOrThrow();
await trx
.insertInto("directory_log")
.values({
directory_id: directoryId,
timestamp: new Date(),
action: "create",
new_name: params.encName,
})
.execute();
});
};
export const getAllDirectoriesByParent = async (userId: number, parentId: DirectoryId) => {
let query = db.selectFrom("directory").selectAll().where("user_id", "=", userId);
query =
parentId === "root"
? query.where("parent_id", "is", null)
: query.where("parent_id", "=", parentId);
const directories = await query.execute();
return directories.map(
(directory) =>
({
id: directory.id,
parentId: directory.parent_id ?? "root",
userId: directory.user_id,
mekVersion: directory.master_encryption_key_version,
encDek: directory.encrypted_data_encryption_key,
dekVersion: directory.data_encryption_key_version,
encName: directory.encrypted_name,
}) satisfies Directory,
);
};
export const getDirectory = async (userId: number, directoryId: number) => {
const directory = await db
.selectFrom("directory")
.selectAll()
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.limit(1)
.executeTakeFirst();
return directory
? ({
id: directory.id,
parentId: directory.parent_id ?? "root",
userId: directory.user_id,
mekVersion: directory.master_encryption_key_version,
encDek: directory.encrypted_data_encryption_key,
dekVersion: directory.data_encryption_key_version,
encName: directory.encrypted_name,
} satisfies Directory)
: null;
};
export const setDirectoryEncName = async (
userId: number,
directoryId: number,
dekVersion: Date,
encName: Ciphertext,
) => {
await db.transaction().execute(async (trx) => {
const directory = await trx
.selectFrom("directory")
.select("data_encryption_key_version")
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!directory) {
throw new IntegrityError("Directory not found");
} else if (directory.data_encryption_key_version.getTime() !== dekVersion.getTime()) {
throw new IntegrityError("Invalid DEK version");
}
await trx
.updateTable("directory")
.set({ encrypted_name: encName })
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.execute();
await trx
.insertInto("directory_log")
.values({
directory_id: directoryId,
timestamp: new Date(),
action: "rename",
new_name: encName,
})
.execute();
});
};
export const unregisterDirectory = async (userId: number, directoryId: number) => {
return await db
.transaction()
.setIsolationLevel("repeatable read") // TODO: Sufficient?
.execute(async (trx) => {
const unregisterFiles = async (parentId: number) => {
const files = await trx
.selectFrom("file")
.leftJoin("thumbnail", "file.id", "thumbnail.file_id")
.select(["file.id", "file.path", "thumbnail.path as thumbnailPath"])
.where("file.parent_id", "=", parentId)
.where("file.user_id", "=", userId)
.forUpdate("file")
.execute();
await trx
.deleteFrom("file")
.where("parent_id", "=", parentId)
.where("user_id", "=", userId)
.execute();
return files;
};
const unregisterDirectoryRecursively = async (
directoryId: number,
): Promise<{ id: number; path: string; thumbnailPath: string | null }[]> => {
const files = await unregisterFiles(directoryId);
const subDirectories = await trx
.selectFrom("directory")
.select("id")
.where("parent_id", "=", directoryId)
.where("user_id", "=", userId)
.execute();
const subDirectoryFilePaths = await Promise.all(
subDirectories.map(async ({ id }) => await unregisterDirectoryRecursively(id)),
);
const deleteRes = await trx
.deleteFrom("directory")
.where("id", "=", directoryId)
.where("user_id", "=", userId)
.executeTakeFirst();
if (deleteRes.numDeletedRows === 0n) {
throw new IntegrityError("Directory not found");
}
return files.concat(...subDirectoryFilePaths);
};
return await unregisterDirectoryRecursively(directoryId);
});
};
export const registerFile = async (trx: typeof db, params: Omit<File, "id">) => {
if ((params.hskVersion && !params.contentHmac) || (!params.hskVersion && params.contentHmac)) { if ((params.hskVersion && !params.contentHmac) || (!params.hskVersion && params.contentHmac)) {
throw new Error("Invalid arguments"); throw new Error("Invalid arguments");
} }
@@ -90,14 +248,32 @@ export const registerFile = async (trx: typeof db, params: Omit<File, "id" | "is
}; };
export const getAllFilesByParent = async (userId: number, parentId: DirectoryId) => { export const getAllFilesByParent = async (userId: number, parentId: DirectoryId) => {
const files = await db let query = db.selectFrom("file").selectAll().where("user_id", "=", userId);
.selectFrom("file") query =
.selectAll() parentId === "root"
.where("user_id", "=", userId) ? query.where("parent_id", "is", null)
.$if(parentId === "root", (qb) => qb.where("parent_id", "is", null)) : query.where("parent_id", "=", parentId);
.$if(parentId !== "root", (qb) => qb.where("parent_id", "=", parentId as number)) const files = await query.execute();
.execute(); return files.map(
return files.map(toFile); (file) =>
({
id: file.id,
parentId: file.parent_id ?? "root",
userId: file.user_id,
path: file.path,
mekVersion: file.master_encryption_key_version,
encDek: file.encrypted_data_encryption_key,
dekVersion: file.data_encryption_key_version,
hskVersion: file.hmac_secret_key_version,
contentHmac: file.content_hmac,
contentType: file.content_type,
encContentIv: file.encrypted_content_iv,
encContentHash: file.encrypted_content_hash,
encName: file.encrypted_name,
encCreatedAt: file.encrypted_created_at,
encLastModifiedAt: file.encrypted_last_modified_at,
}) satisfies File,
);
}; };
export const getAllFilesByCategory = async ( export const getAllFilesByCategory = async (
@@ -130,10 +306,27 @@ export const getAllFilesByCategory = async (
.orderBy("file_id") .orderBy("file_id")
.orderBy("depth") .orderBy("depth")
.execute(); .execute();
return files.map((file) => ({ return files.map(
...toFile(file), (file) =>
({
id: file.file_id,
parentId: file.parent_id ?? "root",
userId: file.user_id,
path: file.path,
mekVersion: file.master_encryption_key_version,
encDek: file.encrypted_data_encryption_key,
dekVersion: file.data_encryption_key_version,
hskVersion: file.hmac_secret_key_version,
contentHmac: file.content_hmac,
contentType: file.content_type,
encContentIv: file.encrypted_content_iv,
encContentHash: file.encrypted_content_hash,
encName: file.encrypted_name,
encCreatedAt: file.encrypted_created_at,
encLastModifiedAt: file.encrypted_last_modified_at,
isRecursive: file.depth > 0, isRecursive: file.depth > 0,
})); }) satisfies File & { isRecursive: boolean },
);
}; };
export const getAllFileIds = async (userId: number) => { export const getAllFileIds = async (userId: number) => {
@@ -141,28 +334,14 @@ export const getAllFileIds = async (userId: number) => {
return files.map(({ id }) => id); return files.map(({ id }) => id);
}; };
export const getFilesWithoutThumbnail = async (userId: number, limit: number = 100) => { export const getLegacyFileIds = async (userId: number) => {
const files = await db const files = await db
.selectFrom("file") .selectFrom("file")
.selectAll() .select("id")
.where("user_id", "=", userId) .where("user_id", "=", userId)
.where((eb) => .where("encrypted_content_iv", "is not", null)
eb.or([eb("content_type", "like", "image/%"), eb("content_type", "like", "video/%")]),
)
.where((eb) =>
eb.not(
eb.exists(
eb
.selectFrom("thumbnail")
.select("thumbnail.id")
.whereRef("thumbnail.file_id", "=", "file.id")
.limit(1),
),
),
)
.limit(limit)
.execute(); .execute();
return files.map(toFile); return files.map(({ id }) => id);
}; };
export const getAllFileIdsByContentHmac = async ( export const getAllFileIdsByContentHmac = async (
@@ -188,7 +367,25 @@ export const getFile = async (userId: number, fileId: number) => {
.where("user_id", "=", userId) .where("user_id", "=", userId)
.limit(1) .limit(1)
.executeTakeFirst(); .executeTakeFirst();
return file ? toFile(file) : null; return file
? ({
id: file.id,
parentId: file.parent_id ?? "root",
userId: file.user_id,
path: file.path,
mekVersion: file.master_encryption_key_version,
encDek: file.encrypted_data_encryption_key,
dekVersion: file.data_encryption_key_version,
hskVersion: file.hmac_secret_key_version,
contentHmac: file.content_hmac,
contentType: file.content_type,
encContentIv: file.encrypted_content_iv,
encContentHash: file.encrypted_content_hash,
encName: file.encrypted_name,
encCreatedAt: file.encrypted_created_at,
encLastModifiedAt: file.encrypted_last_modified_at,
} satisfies File)
: null;
}; };
export const getFilesWithCategories = async (userId: number, fileIds: number[]) => { export const getFilesWithCategories = async (userId: number, fileIds: number[]) => {
@@ -207,144 +404,34 @@ export const getFilesWithCategories = async (userId: number, fileIds: number[])
.where("id", "=", (eb) => eb.fn.any(eb.val(fileIds))) .where("id", "=", (eb) => eb.fn.any(eb.val(fileIds)))
.where("user_id", "=", userId) .where("user_id", "=", userId)
.execute(); .execute();
return files.map((file) => ({ return files.map(
...toFile(file), (file) =>
categories: file.categories.map(
(category) =>
({ ({
id: file.id,
parentId: file.parent_id ?? "root",
userId: file.user_id,
path: file.path,
mekVersion: file.master_encryption_key_version,
encDek: file.encrypted_data_encryption_key,
dekVersion: file.data_encryption_key_version,
hskVersion: file.hmac_secret_key_version,
contentHmac: file.content_hmac,
contentType: file.content_type,
encContentIv: file.encrypted_content_iv,
encContentHash: file.encrypted_content_hash,
encName: file.encrypted_name,
encCreatedAt: file.encrypted_created_at,
encLastModifiedAt: file.encrypted_last_modified_at,
categories: file.categories.map((category) => ({
id: category.id, id: category.id,
parentId: category.parent_id ?? "root", parentId: category.parent_id ?? "root",
mekVersion: category.master_encryption_key_version, mekVersion: category.master_encryption_key_version,
encDek: category.encrypted_data_encryption_key, encDek: category.encrypted_data_encryption_key,
dekVersion: new Date(category.data_encryption_key_version), dekVersion: new Date(category.data_encryption_key_version),
encName: category.encrypted_name, encName: category.encrypted_name,
}) satisfies FileCategory, })),
), }) satisfies File & { categories: FileCategory[] },
}));
};
export const getAllFavoriteFiles = async (userId: number) => {
const files = await db
.selectFrom("file")
.selectAll()
.where("user_id", "=", userId)
.where("is_favorite", "=", true)
.execute();
return files.map(toFile);
};
export const searchFiles = async (
userId: number,
filters: {
parentId: DirectoryId;
inFavorites: boolean;
includeCategoryIds: number[];
excludeCategoryIds: number[];
},
) => {
const baseQuery = db
.withRecursive("directory_tree", (db) =>
db
.selectFrom("directory")
.select("id")
.where("user_id", "=", userId)
.$if(filters.parentId === "root", (qb) => qb.where((eb) => eb.lit(false))) // directory_tree will be empty if parentId is "root"
.$if(filters.parentId !== "root", (qb) => qb.where("id", "=", filters.parentId as number))
.unionAll(
db
.selectFrom("directory as d")
.innerJoin("directory_tree as dt", "d.parent_id", "dt.id")
.select("d.id"),
),
)
.withRecursive("favorite_directory_tree", (db) =>
db
.selectFrom("directory")
.select("id")
.where("user_id", "=", userId)
.$if(!filters.inFavorites, (qb) => qb.where((eb) => eb.lit(false))) // favorite_directory_tree will be empty if inFavorites is false
.$if(filters.inFavorites, (qb) => qb.where("is_favorite", "=", true))
.unionAll((db) =>
db
.selectFrom("directory as d")
.innerJoin("favorite_directory_tree as dt", "d.parent_id", "dt.id")
.select("d.id"),
),
)
.withRecursive("include_category_tree", (db) =>
db
.selectFrom("category")
.select(["id", "id as root_id"])
.where("id", "=", (eb) => eb.fn.any(eb.val(filters.includeCategoryIds)))
.where("user_id", "=", userId)
.unionAll(
db
.selectFrom("category as c")
.innerJoin("include_category_tree as ct", "c.parent_id", "ct.id")
.select(["c.id", "ct.root_id"]),
),
)
.withRecursive("exclude_category_tree", (db) =>
db
.selectFrom("category")
.select("id")
.where("id", "=", (eb) => eb.fn.any(eb.val(filters.excludeCategoryIds)))
.where("user_id", "=", userId)
.unionAll((db) =>
db
.selectFrom("category as c")
.innerJoin("exclude_category_tree as ct", "c.parent_id", "ct.id")
.select("c.id"),
),
)
.selectFrom("file")
.selectAll("file")
.where("user_id", "=", userId)
.$if(filters.parentId !== "root", (qb) =>
qb.where((eb) =>
eb.exists(eb.selectFrom("directory_tree as dt").whereRef("dt.id", "=", "file.parent_id")),
),
)
.$if(filters.inFavorites, (qb) =>
qb.where((eb) =>
eb.or([
eb("is_favorite", "=", true),
eb.exists(
eb.selectFrom("favorite_directory_tree as dt").whereRef("dt.id", "=", "file.parent_id"),
),
]),
),
)
.$if(filters.excludeCategoryIds.length > 0, (qb) =>
qb.where((eb) =>
eb.not(
eb.exists(
eb
.selectFrom("file_category")
.innerJoin("exclude_category_tree", "category_id", "exclude_category_tree.id")
.whereRef("file_id", "=", "file.id"),
),
),
),
); );
const files =
filters.includeCategoryIds.length > 0
? await baseQuery
.innerJoin("file_category", "file.id", "file_category.file_id")
.innerJoin(
"include_category_tree",
"file_category.category_id",
"include_category_tree.id",
)
.groupBy("file.id")
.having(
(eb) => eb.fn.count("include_category_tree.root_id").distinct(),
"=",
filters.includeCategoryIds.length,
)
.execute()
: await baseQuery.execute();
return files.map(toFile);
}; };
export const setFileEncName = async ( export const setFileEncName = async (
@@ -405,6 +492,52 @@ export const unregisterFile = async (userId: number, fileId: number) => {
}); });
}; };
export const migrateFileContent = async (
trx: typeof db,
userId: number,
fileId: number,
newPath: string,
encContentHash: string,
) => {
const file = await trx
.selectFrom("file")
.select(["path", "encrypted_content_iv"])
.where("id", "=", fileId)
.where("user_id", "=", userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!file) {
throw new IntegrityError("File not found");
}
if (!file.encrypted_content_iv) {
throw new IntegrityError("File is not legacy");
}
await trx
.updateTable("file")
.set({
path: newPath,
encrypted_content_iv: null,
encrypted_content_hash: encContentHash,
})
.where("id", "=", fileId)
.where("user_id", "=", userId)
.execute();
await trx
.insertInto("file_log")
.values({
file_id: fileId,
timestamp: new Date(),
action: "migrate",
})
.execute();
return file.path;
};
export const addFileToCategory = async (fileId: number, categoryId: number) => { export const addFileToCategory = async (fileId: number, categoryId: number) => {
await db.transaction().execute(async (trx) => { await db.transaction().execute(async (trx) => {
try { try {
@@ -472,36 +605,3 @@ export const removeFileFromCategory = async (fileId: number, categoryId: number)
.execute(); .execute();
}); });
}; };
export const setFileFavorite = async (userId: number, fileId: number, isFavorite: boolean) => {
await db.transaction().execute(async (trx) => {
const file = await trx
.selectFrom("file")
.select("is_favorite")
.where("id", "=", fileId)
.where("user_id", "=", userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!file) {
throw new IntegrityError("File not found");
} else if (file.is_favorite === isFavorite) {
throw new IntegrityError(isFavorite ? "File already favorited" : "File not favorited");
}
await trx
.updateTable("file")
.set({ is_favorite: isFavorite })
.where("id", "=", fileId)
.where("user_id", "=", userId)
.execute();
await trx
.insertInto("file_log")
.values({
file_id: fileId,
timestamp: new Date(),
action: isFavorite ? "add-to-favorites" : "remove-from-favorites",
})
.execute();
});
};

View File

@@ -1,6 +1,5 @@
export * as CategoryRepo from "./category"; export * as CategoryRepo from "./category";
export * as ClientRepo from "./client"; export * as ClientRepo from "./client";
export * as DirectoryRepo from "./directory";
export * as FileRepo from "./file"; export * as FileRepo from "./file";
export * as HskRepo from "./hsk"; export * as HskRepo from "./hsk";
export * as MediaRepo from "./media"; export * as MediaRepo from "./media";

View File

@@ -83,3 +83,27 @@ export const getFileThumbnail = async (userId: number, fileId: number) => {
} satisfies FileThumbnail) } satisfies FileThumbnail)
: null; : null;
}; };
export const getMissingFileThumbnails = async (userId: number, limit: number = 100) => {
const files = await db
.selectFrom("file")
.select("id")
.where("user_id", "=", userId)
.where((eb) =>
eb.or([eb("content_type", "like", "image/%"), eb("content_type", "like", "video/%")]),
)
.where((eb) =>
eb.not(
eb.exists(
eb
.selectFrom("thumbnail")
.select("thumbnail.id")
.whereRef("thumbnail.file_id", "=", "file.id")
.limit(1),
),
),
)
.limit(limit)
.execute();
return files.map(({ id }) => id);
};

View File

@@ -71,7 +71,7 @@ export const getAllValidClientMeks = async (userId: number, clientId: number) =>
.selectAll() .selectAll()
.where("client_master_encryption_key.user_id", "=", userId) .where("client_master_encryption_key.user_id", "=", userId)
.where("client_master_encryption_key.client_id", "=", clientId) .where("client_master_encryption_key.client_id", "=", clientId)
.where("state", "in", ["active", "retired"]) .where((eb) => eb.or([eb("state", "=", "active"), eb("state", "=", "retired")]))
.execute(); .execute();
return clientMeks.map( return clientMeks.map(
({ user_id, client_id, version, state, encrypted_key, encrypted_key_signature }) => ({ user_id, client_id, version, state, encrypted_key, encrypted_key_signature }) =>

View File

@@ -135,7 +135,7 @@ export const up = async (db: Kysely<any>) => {
) )
.execute(); .execute();
// directory.ts // file.ts
await db.schema await db.schema
.createTable("directory") .createTable("directory")
.addColumn("id", "integer", (col) => col.primaryKey().generatedAlwaysAsIdentity()) .addColumn("id", "integer", (col) => col.primaryKey().generatedAlwaysAsIdentity())
@@ -162,8 +162,6 @@ export const up = async (db: Kysely<any>) => {
.addColumn("action", "text", (col) => col.notNull()) .addColumn("action", "text", (col) => col.notNull())
.addColumn("new_name", "json") .addColumn("new_name", "json")
.execute(); .execute();
// file.ts
await db.schema await db.schema
.createTable("file") .createTable("file")
.addColumn("id", "integer", (col) => col.primaryKey().generatedAlwaysAsIdentity()) .addColumn("id", "integer", (col) => col.primaryKey().generatedAlwaysAsIdentity())

View File

@@ -53,7 +53,9 @@ export const up = async (db: Kysely<any>) => {
export const down = async (db: Kysely<any>) => { export const down = async (db: Kysely<any>) => {
await db await db
.deleteFrom("file_log") .deleteFrom("file_log")
.where("action", "in", ["add-to-category", "remove-from-category"]) .where((eb) =>
eb.or([eb("action", "=", "add-to-category"), eb("action", "=", "remove-from-category")]),
)
.execute(); .execute();
await db.schema.dropTable("file_category").execute(); await db.schema.dropTable("file_category").execute();

View File

@@ -21,14 +21,8 @@ export const up = async (db: Kysely<any>) => {
.addColumn("type", "text", (col) => col.notNull()) .addColumn("type", "text", (col) => col.notNull())
.addColumn("user_id", "integer", (col) => col.references("user.id").notNull()) .addColumn("user_id", "integer", (col) => col.references("user.id").notNull())
.addColumn("path", "text", (col) => col.notNull()) .addColumn("path", "text", (col) => col.notNull())
.addColumn("bitmap", "bytea", (col) => col.notNull())
.addColumn("total_chunks", "integer", (col) => col.notNull()) .addColumn("total_chunks", "integer", (col) => col.notNull())
.addColumn("uploaded_chunks", "integer", (col) => .addColumn("uploaded_chunks", sql`integer[]`, (col) => col.notNull().defaultTo(sql`'{}'`))
col
.generatedAlwaysAs(sql`bit_count(bitmap)`)
.stored()
.notNull(),
)
.addColumn("expires_at", "timestamp(3)", (col) => col.notNull()) .addColumn("expires_at", "timestamp(3)", (col) => col.notNull())
.addColumn("parent_id", "integer", (col) => col.references("directory.id")) .addColumn("parent_id", "integer", (col) => col.references("directory.id"))
.addColumn("master_encryption_key_version", "integer") .addColumn("master_encryption_key_version", "integer")
@@ -52,18 +46,11 @@ export const up = async (db: Kysely<any>) => {
"hmac_secret_key", "hmac_secret_key",
["user_id", "version"], ["user_id", "version"],
) )
.addCheckConstraint(
"upload_session_ck01",
sql`length(bitmap) = ceil(total_chunks / 8.0)::integer`,
)
.addCheckConstraint("upload_session_ck02", sql`uploaded_chunks <= total_chunks`)
.execute(); .execute();
}; };
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const down = async (db: Kysely<any>) => { export const down = async (db: Kysely<any>) => {
await db.deleteFrom("file_log").where("action", "=", "migrate").execute();
await db.schema.dropTable("upload_session").execute(); await db.schema.dropTable("upload_session").execute();
await db.schema await db.schema
.alterTable("thumbnail") .alterTable("thumbnail")

View File

@@ -1,31 +0,0 @@
import { Kysely } from "kysely";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const up = async (db: Kysely<any>) => {
// directory.ts
await db.schema
.alterTable("directory")
.addColumn("is_favorite", "boolean", (col) => col.notNull().defaultTo(false))
.execute();
// file.ts
await db.schema
.alterTable("file")
.addColumn("is_favorite", "boolean", (col) => col.notNull().defaultTo(false))
.execute();
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const down = async (db: Kysely<any>) => {
await db
.deleteFrom("file_log")
.where("action", "in", ["add-to-favorites", "remove-from-favorites"])
.execute();
await db
.deleteFrom("directory_log")
.where("action", "in", ["add-to-favorites", "remove-from-favorites"])
.execute();
await db.schema.alterTable("file").dropColumn("is_favorite").execute();
await db.schema.alterTable("directory").dropColumn("is_favorite").execute();
};

View File

@@ -2,12 +2,10 @@ import * as Initial1737357000 from "./1737357000-Initial";
import * as AddFileCategory1737422340 from "./1737422340-AddFileCategory"; import * as AddFileCategory1737422340 from "./1737422340-AddFileCategory";
import * as AddThumbnail1738409340 from "./1738409340-AddThumbnail"; import * as AddThumbnail1738409340 from "./1738409340-AddThumbnail";
import * as AddChunkedUpload1768062380 from "./1768062380-AddChunkedUpload"; import * as AddChunkedUpload1768062380 from "./1768062380-AddChunkedUpload";
import * as AddFavorites1768643000 from "./1768643000-AddFavorites";
export default { export default {
"1737357000-Initial": Initial1737357000, "1737357000-Initial": Initial1737357000,
"1737422340-AddFileCategory": AddFileCategory1737422340, "1737422340-AddFileCategory": AddFileCategory1737422340,
"1738409340-AddThumbnail": AddThumbnail1738409340, "1738409340-AddThumbnail": AddThumbnail1738409340,
"1768062380-AddChunkedUpload": AddChunkedUpload1768062380, "1768062380-AddChunkedUpload": AddChunkedUpload1768062380,
"1768643000-AddFavorites": AddFavorites1768643000,
}; };

View File

@@ -1,7 +1,7 @@
import type { Generated } from "kysely"; import type { Generated } from "kysely";
import type { Ciphertext } from "./utils"; import type { Ciphertext } from "./utils";
export interface CategoryTable { interface CategoryTable {
id: Generated<number>; id: Generated<number>;
parent_id: number | null; parent_id: number | null;
user_id: number; user_id: number;
@@ -11,7 +11,7 @@ export interface CategoryTable {
encrypted_name: Ciphertext; encrypted_name: Ciphertext;
} }
export interface CategoryLogTable { interface CategoryLogTable {
id: Generated<number>; id: Generated<number>;
category_id: number; category_id: number;
timestamp: Date; timestamp: Date;

View File

@@ -1,6 +1,6 @@
import type { ColumnType, Generated } from "kysely"; import type { ColumnType, Generated } from "kysely";
export interface ClientTable { interface ClientTable {
id: Generated<number>; id: Generated<number>;
encryption_public_key: string; // Base64 encryption_public_key: string; // Base64
signature_public_key: string; // Base64 signature_public_key: string; // Base64
@@ -8,13 +8,13 @@ export interface ClientTable {
export type UserClientState = "challenging" | "pending" | "active"; export type UserClientState = "challenging" | "pending" | "active";
export interface UserClientTable { interface UserClientTable {
user_id: number; user_id: number;
client_id: number; client_id: number;
state: ColumnType<UserClientState, UserClientState | undefined>; state: ColumnType<UserClientState, UserClientState | undefined>;
} }
export interface UserClientChallengeTable { interface UserClientChallengeTable {
id: Generated<number>; id: Generated<number>;
user_id: number; user_id: number;
client_id: number; client_id: number;

View File

@@ -1,28 +0,0 @@
import type { ColumnType, Generated } from "kysely";
import type { Ciphertext } from "./utils";
export interface DirectoryTable {
id: Generated<number>;
parent_id: number | null;
user_id: number;
master_encryption_key_version: number;
encrypted_data_encryption_key: string; // Base64
data_encryption_key_version: Date;
encrypted_name: Ciphertext;
is_favorite: Generated<boolean>;
}
export interface DirectoryLogTable {
id: Generated<number>;
directory_id: number;
timestamp: ColumnType<Date, Date, never>;
action: "create" | "rename" | "add-to-favorites" | "remove-from-favorites";
new_name: Ciphertext | null;
}
declare module "./index" {
interface Database {
directory: DirectoryTable;
directory_log: DirectoryLogTable;
}
}

View File

@@ -1,7 +1,25 @@
import type { ColumnType, Generated } from "kysely"; import type { ColumnType, Generated } from "kysely";
import type { Ciphertext } from "./utils"; import type { Ciphertext } from "./utils";
export interface FileTable { interface DirectoryTable {
id: Generated<number>;
parent_id: number | null;
user_id: number;
master_encryption_key_version: number;
encrypted_data_encryption_key: string; // Base64
data_encryption_key_version: Date;
encrypted_name: Ciphertext;
}
interface DirectoryLogTable {
id: Generated<number>;
directory_id: number;
timestamp: ColumnType<Date, Date, never>;
action: "create" | "rename";
new_name: Ciphertext | null;
}
interface FileTable {
id: Generated<number>; id: Generated<number>;
parent_id: number | null; parent_id: number | null;
user_id: number; user_id: number;
@@ -17,32 +35,26 @@ export interface FileTable {
encrypted_name: Ciphertext; encrypted_name: Ciphertext;
encrypted_created_at: Ciphertext | null; encrypted_created_at: Ciphertext | null;
encrypted_last_modified_at: Ciphertext; encrypted_last_modified_at: Ciphertext;
is_favorite: Generated<boolean>;
} }
export interface FileLogTable { interface FileLogTable {
id: Generated<number>; id: Generated<number>;
file_id: number; file_id: number;
timestamp: ColumnType<Date, Date, never>; timestamp: ColumnType<Date, Date, never>;
action: action: "create" | "rename" | "migrate" | "add-to-category" | "remove-from-category";
| "create"
| "rename"
| "migrate"
| "add-to-category"
| "remove-from-category"
| "add-to-favorites"
| "remove-from-favorites";
new_name: Ciphertext | null; new_name: Ciphertext | null;
category_id: number | null; category_id: number | null;
} }
export interface FileCategoryTable { interface FileCategoryTable {
file_id: number; file_id: number;
category_id: number; category_id: number;
} }
declare module "./index" { declare module "./index" {
interface Database { interface Database {
directory: DirectoryTable;
directory_log: DirectoryLogTable;
file: FileTable; file: FileTable;
file_log: FileLogTable; file_log: FileLogTable;
file_category: FileCategoryTable; file_category: FileCategoryTable;

View File

@@ -2,7 +2,7 @@ import type { ColumnType, Generated } from "kysely";
export type HskState = "active"; export type HskState = "active";
export interface HskTable { interface HskTable {
user_id: number; user_id: number;
version: number; version: number;
state: HskState; state: HskState;
@@ -10,7 +10,7 @@ export interface HskTable {
encrypted_key: string; // Base64 encrypted_key: string; // Base64
} }
export interface HskLogTable { interface HskLogTable {
id: Generated<number>; id: Generated<number>;
user_id: number; user_id: number;
hmac_secret_key_version: number; hmac_secret_key_version: number;

View File

@@ -1,6 +1,5 @@
export * from "./category"; export * from "./category";
export * from "./client"; export * from "./client";
export * from "./directory";
export * from "./file"; export * from "./file";
export * from "./hsk"; export * from "./hsk";
export * from "./media"; export * from "./media";

View File

@@ -1,6 +1,6 @@
import type { Generated } from "kysely"; import type { Generated } from "kysely";
export interface ThumbnailTable { interface ThumbnailTable {
id: Generated<number>; id: Generated<number>;
directory_id: number | null; directory_id: number | null;
file_id: number | null; file_id: number | null;

View File

@@ -2,13 +2,13 @@ import type { ColumnType, Generated } from "kysely";
export type MekState = "active" | "retired" | "dead"; export type MekState = "active" | "retired" | "dead";
export interface MekTable { interface MekTable {
user_id: number; user_id: number;
version: number; version: number;
state: MekState; state: MekState;
} }
export interface MekLogTable { interface MekLogTable {
id: Generated<number>; id: Generated<number>;
user_id: number; user_id: number;
master_encryption_key_version: number; master_encryption_key_version: number;
@@ -17,7 +17,7 @@ export interface MekLogTable {
action_by: number | null; action_by: number | null;
} }
export interface ClientMekTable { interface ClientMekTable {
user_id: number; user_id: number;
client_id: number; client_id: number;
version: number; version: number;

View File

@@ -1,6 +1,6 @@
import type { ColumnType, Generated } from "kysely"; import type { ColumnType, Generated } from "kysely";
export interface SessionTable { interface SessionTable {
id: string; id: string;
user_id: number; user_id: number;
client_id: number | null; client_id: number | null;
@@ -10,7 +10,7 @@ export interface SessionTable {
last_used_by_agent: string | null; last_used_by_agent: string | null;
} }
export interface SessionUpgradeChallengeTable { interface SessionUpgradeChallengeTable {
id: Generated<number>; id: Generated<number>;
session_id: string; session_id: string;
client_id: number; client_id: number;

View File

@@ -1,16 +1,16 @@
import type { Generated } from "kysely"; import type { Generated } from "kysely";
import type { Ciphertext } from "./utils"; import type { Ciphertext } from "./utils";
export interface UploadSessionTable { interface UploadSessionTable {
id: string; id: string;
type: "file" | "thumbnail"; type: "file" | "thumbnail" | "migration";
user_id: number; user_id: number;
path: string; path: string;
bitmap: Buffer;
total_chunks: number; total_chunks: number;
uploaded_chunks: Generated<number>; uploaded_chunks: Generated<number[]>;
expires_at: Date; expires_at: Date;
// For file uploads
parent_id: number | null; parent_id: number | null;
master_encryption_key_version: number | null; master_encryption_key_version: number | null;
encrypted_data_encryption_key: string | null; // Base64 encrypted_data_encryption_key: string | null; // Base64
@@ -20,6 +20,8 @@ export interface UploadSessionTable {
encrypted_name: Ciphertext | null; encrypted_name: Ciphertext | null;
encrypted_created_at: Ciphertext | null; encrypted_created_at: Ciphertext | null;
encrypted_last_modified_at: Ciphertext | null; encrypted_last_modified_at: Ciphertext | null;
// For thumbnail uploads
file_id: number | null; file_id: number | null;
} }

View File

@@ -1,6 +1,6 @@
import type { Generated } from "kysely"; import type { Generated } from "kysely";
export interface UserTable { interface UserTable {
id: Generated<number>; id: Generated<number>;
email: string; email: string;
nickname: string; nickname: string;

View File

@@ -7,9 +7,8 @@ interface BaseUploadSession {
id: string; id: string;
userId: number; userId: number;
path: string; path: string;
bitmap: Buffer;
totalChunks: number; totalChunks: number;
uploadedChunks: number; uploadedChunks: number[];
expiresAt: Date; expiresAt: Date;
} }
@@ -32,8 +31,13 @@ interface ThumbnailUploadSession extends BaseUploadSession {
dekVersion: Date; dekVersion: Date;
} }
interface MigrationUploadSession extends BaseUploadSession {
type: "migration";
fileId: number;
}
export const createFileUploadSession = async ( export const createFileUploadSession = async (
params: Omit<FileUploadSession, "type" | "bitmap" | "uploadedChunks">, params: Omit<FileUploadSession, "type" | "uploadedChunks">,
) => { ) => {
await db.transaction().execute(async (trx) => { await db.transaction().execute(async (trx) => {
const mek = await trx const mek = await trx
@@ -69,7 +73,6 @@ export const createFileUploadSession = async (
type: "file", type: "file",
user_id: params.userId, user_id: params.userId,
path: params.path, path: params.path,
bitmap: Buffer.alloc(Math.ceil(params.totalChunks / 8)),
total_chunks: params.totalChunks, total_chunks: params.totalChunks,
expires_at: params.expiresAt, expires_at: params.expiresAt,
parent_id: params.parentId !== "root" ? params.parentId : null, parent_id: params.parentId !== "root" ? params.parentId : null,
@@ -87,7 +90,7 @@ export const createFileUploadSession = async (
}; };
export const createThumbnailUploadSession = async ( export const createThumbnailUploadSession = async (
params: Omit<ThumbnailUploadSession, "bitmap" | "uploadedChunks">, params: Omit<ThumbnailUploadSession, "type" | "uploadedChunks">,
) => { ) => {
await db.transaction().execute(async (trx) => { await db.transaction().execute(async (trx) => {
const file = await trx const file = await trx
@@ -108,10 +111,9 @@ export const createThumbnailUploadSession = async (
.insertInto("upload_session") .insertInto("upload_session")
.values({ .values({
id: params.id, id: params.id,
type: params.type, type: "thumbnail",
user_id: params.userId, user_id: params.userId,
path: params.path, path: params.path,
bitmap: Buffer.alloc(Math.ceil(params.totalChunks / 8)),
total_chunks: params.totalChunks, total_chunks: params.totalChunks,
expires_at: params.expiresAt, expires_at: params.expiresAt,
file_id: params.fileId, file_id: params.fileId,
@@ -121,6 +123,39 @@ export const createThumbnailUploadSession = async (
}); });
}; };
export const createMigrationUploadSession = async (
params: Omit<MigrationUploadSession, "type" | "uploadedChunks">,
) => {
await db.transaction().execute(async (trx) => {
const file = await trx
.selectFrom("file")
.select("encrypted_content_iv")
.where("id", "=", params.fileId)
.where("user_id", "=", params.userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!file) {
throw new IntegrityError("File not found");
} else if (!file.encrypted_content_iv) {
throw new IntegrityError("File is not legacy");
}
await trx
.insertInto("upload_session")
.values({
id: params.id,
type: "migration",
user_id: params.userId,
path: params.path,
total_chunks: params.totalChunks,
expires_at: params.expiresAt,
file_id: params.fileId,
})
.execute();
});
};
export const getUploadSession = async (sessionId: string, userId: number) => { export const getUploadSession = async (sessionId: string, userId: number) => {
const session = await db const session = await db
.selectFrom("upload_session") .selectFrom("upload_session")
@@ -138,7 +173,6 @@ export const getUploadSession = async (sessionId: string, userId: number) => {
id: session.id, id: session.id,
userId: session.user_id, userId: session.user_id,
path: session.path, path: session.path,
bitmap: session.bitmap,
totalChunks: session.total_chunks, totalChunks: session.total_chunks,
uploadedChunks: session.uploaded_chunks, uploadedChunks: session.uploaded_chunks,
expiresAt: session.expires_at, expiresAt: session.expires_at,
@@ -152,28 +186,36 @@ export const getUploadSession = async (sessionId: string, userId: number) => {
encCreatedAt: session.encrypted_created_at, encCreatedAt: session.encrypted_created_at,
encLastModifiedAt: session.encrypted_last_modified_at!, encLastModifiedAt: session.encrypted_last_modified_at!,
} satisfies FileUploadSession; } satisfies FileUploadSession;
} else { } else if (session.type === "thumbnail") {
return { return {
type: session.type, type: "thumbnail",
id: session.id, id: session.id,
userId: session.user_id, userId: session.user_id,
path: session.path, path: session.path,
bitmap: session.bitmap,
totalChunks: session.total_chunks, totalChunks: session.total_chunks,
uploadedChunks: session.uploaded_chunks, uploadedChunks: session.uploaded_chunks,
expiresAt: session.expires_at, expiresAt: session.expires_at,
fileId: session.file_id!, fileId: session.file_id!,
dekVersion: session.data_encryption_key_version!, dekVersion: session.data_encryption_key_version!,
} satisfies ThumbnailUploadSession; } satisfies ThumbnailUploadSession;
} else {
return {
type: "migration",
id: session.id,
userId: session.user_id,
path: session.path,
totalChunks: session.total_chunks,
uploadedChunks: session.uploaded_chunks,
expiresAt: session.expires_at,
fileId: session.file_id!,
} satisfies MigrationUploadSession;
} }
}; };
export const markChunkAsUploaded = async (sessionId: string, chunkIndex: number) => { export const markChunkAsUploaded = async (sessionId: string, chunkIndex: number) => {
await db await db
.updateTable("upload_session") .updateTable("upload_session")
.set({ .set({ uploaded_chunks: sql`array_append(uploaded_chunks, ${chunkIndex})` })
bitmap: sql`set_bit(${sql.ref("bitmap")}, ${chunkIndex - 1}, 1)`,
})
.where("id", "=", sessionId) .where("id", "=", sessionId)
.execute(); .execute();
}; };

View File

@@ -26,4 +26,5 @@ export default {
}, },
libraryPath: env.LIBRARY_PATH || "library", libraryPath: env.LIBRARY_PATH || "library",
thumbnailsPath: env.THUMBNAILS_PATH || "thumbnails", thumbnailsPath: env.THUMBNAILS_PATH || "thumbnails",
uploadsPath: env.UPLOADS_PATH || "uploads",
}; };

View File

@@ -1,4 +1,10 @@
import { unlink } from "fs/promises"; import { rm, unlink } from "fs/promises";
export const safeRecursiveRm = async (path: string | null | undefined) => {
if (path) {
await rm(path, { recursive: true }).catch(console.error);
}
};
export const safeUnlink = async (path: string | null | undefined) => { export const safeUnlink = async (path: string | null | undefined) => {
if (path) { if (path) {

View File

@@ -1,73 +1,19 @@
import { error } from "@sveltejs/kit"; import { error } from "@sveltejs/kit";
import { open } from "fs/promises"; import { createHash } from "crypto";
import { createWriteStream } from "fs";
import { Readable } from "stream"; import { Readable } from "stream";
import { ENCRYPTION_OVERHEAD, ENCRYPTED_CHUNK_SIZE } from "$lib/constants"; import { ENCRYPTION_OVERHEAD, ENCRYPTED_CHUNK_SIZE } from "$lib/constants";
import { UploadRepo } from "$lib/server/db"; import { UploadRepo } from "$lib/server/db";
import { safeUnlink } from "$lib/server/modules/filesystem"; import { safeRecursiveRm, safeUnlink } from "$lib/server/modules/filesystem";
const chunkLocks = new Set<string>(); const chunkLocks = new Set<string>();
const isChunkUploaded = (bitmap: Buffer, chunkIndex: number) => {
chunkIndex -= 1;
const byte = bitmap[Math.floor(chunkIndex / 8)];
return !!byte && (byte & (1 << (chunkIndex % 8))) !== 0; // Postgres sucks
};
const writeChunkAtOffset = async (
path: string,
encChunkStream: Readable,
chunkIndex: number,
isLastChunk: boolean,
) => {
const offset = (chunkIndex - 1) * ENCRYPTED_CHUNK_SIZE;
const file = await open(path, "r+");
let written = 0;
try {
for await (const chunk of encChunkStream) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
written += buffer.length;
if (written > ENCRYPTED_CHUNK_SIZE) {
throw new Error("Invalid chunk size");
}
let chunkOffset = 0;
while (chunkOffset < buffer.length) {
const { bytesWritten } = await file.write(
buffer,
chunkOffset,
buffer.length - chunkOffset,
offset + written - buffer.length + chunkOffset,
);
if (bytesWritten <= 0) {
throw new Error("Failed to write chunk");
}
chunkOffset += bytesWritten;
}
}
if (
(!isLastChunk && written !== ENCRYPTED_CHUNK_SIZE) ||
(isLastChunk && (written <= ENCRYPTION_OVERHEAD || written > ENCRYPTED_CHUNK_SIZE))
) {
throw new Error("Invalid chunk size");
}
if (isLastChunk) {
await file.truncate(offset + written);
}
return written;
} finally {
await file.close();
}
};
export const uploadChunk = async ( export const uploadChunk = async (
userId: number, userId: number,
sessionId: string, sessionId: string,
chunkIndex: number, chunkIndex: number,
encChunkStream: Readable, encChunkStream: Readable,
encChunkHash: string,
) => { ) => {
const lockKey = `${sessionId}/${chunkIndex}`; const lockKey = `${sessionId}/${chunkIndex}`;
if (chunkLocks.has(lockKey)) { if (chunkLocks.has(lockKey)) {
@@ -76,21 +22,52 @@ export const uploadChunk = async (
chunkLocks.add(lockKey); chunkLocks.add(lockKey);
} }
let filePath;
try { try {
const session = await UploadRepo.getUploadSession(sessionId, userId); const session = await UploadRepo.getUploadSession(sessionId, userId);
if (!session) { if (!session) {
error(404, "Invalid upload id"); error(404, "Invalid upload id");
} else if (chunkIndex > session.totalChunks) { } else if (chunkIndex >= session.totalChunks) {
error(400, "Invalid chunk index"); error(400, "Invalid chunk index");
} else if (isChunkUploaded(session.bitmap, chunkIndex)) { } else if (session.uploadedChunks.includes(chunkIndex)) {
error(409, "Chunk already uploaded"); error(409, "Chunk already uploaded");
} }
const isLastChunk = chunkIndex === session.totalChunks; const isLastChunk = chunkIndex === session.totalChunks - 1;
await writeChunkAtOffset(session.path, encChunkStream, chunkIndex, isLastChunk); filePath = `${session.path}/${chunkIndex}`;
const hashStream = createHash("sha256");
const writeStream = createWriteStream(filePath, { flags: "wx", mode: 0o600 });
let writtenBytes = 0;
for await (const chunk of encChunkStream) {
hashStream.update(chunk);
writeStream.write(chunk);
writtenBytes += chunk.length;
}
await new Promise<void>((resolve, reject) => {
writeStream.end((e: any) => (e ? reject(e) : resolve()));
});
if (hashStream.digest("base64") !== encChunkHash) {
throw new Error("Invalid checksum");
} else if (
(!isLastChunk && writtenBytes !== ENCRYPTED_CHUNK_SIZE) ||
(isLastChunk && (writtenBytes <= ENCRYPTION_OVERHEAD || writtenBytes > ENCRYPTED_CHUNK_SIZE))
) {
throw new Error("Invalid chunk size");
}
await UploadRepo.markChunkAsUploaded(sessionId, chunkIndex); await UploadRepo.markChunkAsUploaded(sessionId, chunkIndex);
} catch (e) { } catch (e) {
if (e instanceof Error && e.message === "Invalid chunk size") { await safeUnlink(filePath);
if (
e instanceof Error &&
(e.message === "Invalid checksum" || e.message === "Invalid chunk size")
) {
error(400, "Invalid request body"); error(400, "Invalid request body");
} }
throw e; throw e;
@@ -101,5 +78,5 @@ export const uploadChunk = async (
export const cleanupExpiredUploadSessions = async () => { export const cleanupExpiredUploadSessions = async () => {
const paths = await UploadRepo.cleanupExpiredUploadSessions(); const paths = await UploadRepo.cleanupExpiredUploadSessions();
await Promise.all(paths.map(safeUnlink)); await Promise.all(paths.map(safeRecursiveRm));
}; };

View File

@@ -1,4 +1,5 @@
import { getAllFileInfos } from "$lib/indexedDB/filesystem"; import { getAllFileInfos } from "$lib/indexedDB/filesystem";
import { encodeToBase64, digestMessage } from "$lib/modules/crypto";
import { import {
getFileCache, getFileCache,
storeFileCache, storeFileCache,
@@ -6,7 +7,6 @@ import {
downloadFile, downloadFile,
deleteFileThumbnailCache, deleteFileThumbnailCache,
} from "$lib/modules/file"; } from "$lib/modules/file";
import { uploadBlob } from "$lib/modules/upload";
import { trpc } from "$trpc/client"; import { trpc } from "$trpc/client";
export const requestFileDownload = async ( export const requestFileDownload = async (
@@ -24,24 +24,41 @@ export const requestFileDownload = async (
export const requestFileThumbnailUpload = async ( export const requestFileThumbnailUpload = async (
fileId: number, fileId: number,
thumbnail: Blob,
dataKey: CryptoKey,
dataKeyVersion: Date, dataKeyVersion: Date,
thumbnailEncrypted: { ciphertext: ArrayBuffer; iv: ArrayBuffer },
) => { ) => {
try {
const { uploadId } = await trpc().upload.startFileThumbnailUpload.mutate({ const { uploadId } = await trpc().upload.startFileThumbnailUpload.mutate({
file: fileId, file: fileId,
dekVersion: dataKeyVersion, dekVersion: dataKeyVersion,
}); });
await uploadBlob(uploadId, thumbnail, dataKey); // Prepend IV to ciphertext (consistent with file download format)
const ivAndCiphertext = new Uint8Array(
thumbnailEncrypted.iv.byteLength + thumbnailEncrypted.ciphertext.byteLength,
);
ivAndCiphertext.set(new Uint8Array(thumbnailEncrypted.iv), 0);
ivAndCiphertext.set(
new Uint8Array(thumbnailEncrypted.ciphertext),
thumbnailEncrypted.iv.byteLength,
);
const chunkHash = encodeToBase64(await digestMessage(ivAndCiphertext));
const response = await fetch(`/api/upload/${uploadId}/chunks/0`, {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"Content-Digest": `sha-256=:${chunkHash}:`,
},
body: ivAndCiphertext,
});
if (!response.ok) {
throw new Error(`Thumbnail upload failed: ${response.status} ${response.statusText}`);
}
await trpc().upload.completeFileThumbnailUpload.mutate({ uploadId }); await trpc().upload.completeFileThumbnailUpload.mutate({ uploadId });
return true; return response;
} catch {
// TODO: Error Handling
return false;
}
}; };
export const requestDeletedFilesCleanup = async () => { export const requestDeletedFilesCleanup = async () => {

View File

@@ -1 +0,0 @@
type AllUndefined<T> = { [K in keyof T]?: undefined };

View File

@@ -90,42 +90,4 @@ export class HybridPromise<T> implements PromiseLike<T> {
return HybridPromise.reject(e); return HybridPromise.reject(e);
} }
} }
static all<T extends readonly unknown[] | []>(
maybePromises: T,
): HybridPromise<{ -readonly [P in keyof T]: HybridAwaited<T[P]> }> {
const length = maybePromises.length;
if (length === 0) {
return HybridPromise.resolve([] as any);
}
const hps = Array.from(maybePromises).map((p) => HybridPromise.resolve(p));
if (hps.some((hp) => !hp.isSync())) {
return new HybridPromise({
mode: "async",
promise: Promise.all(hps.map((hp) => hp.toPromise())) as any,
});
}
try {
return HybridPromise.resolve(
Array.from(
hps.map((hp) => {
if (hp.state.mode === "sync") {
if (hp.state.status === "fulfilled") {
return hp.state.value;
} else {
throw hp.state.reason;
}
}
}),
) as any,
);
} catch (e) {
return HybridPromise.reject(e);
}
}
} }
export type HybridAwaited<T> =
T extends HybridPromise<infer U> ? U : T extends Promise<infer U> ? U : T;

View File

@@ -1,44 +0,0 @@
export class BoundedQueue<T> {
private isClosed = false;
private reservedCount = 0;
private items: T[] = [];
private waitersNotFull: (() => void)[] = [];
private waitersNotEmpty: (() => void)[] = [];
constructor(private readonly maxSize: number) {}
async push(item: T) {
if (this.isClosed) {
throw new Error("Queue closed");
}
while (this.reservedCount >= this.maxSize) {
await new Promise<void>((resolve) => this.waitersNotFull.push(resolve));
if (this.isClosed) throw new Error("Queue closed");
}
this.reservedCount++;
this.items.push(item);
this.waitersNotEmpty.shift()?.();
}
async pop() {
while (this.items.length === 0) {
if (this.isClosed) return null;
await new Promise<void>((resolve) => this.waitersNotEmpty.push(resolve));
}
const item = this.items.shift()!;
this.reservedCount--;
this.waitersNotFull.shift()?.();
return item;
}
close() {
this.isClosed = true;
while (this.waitersNotEmpty.length > 0) this.waitersNotEmpty.shift()!();
while (this.waitersNotFull.length > 0) this.waitersNotFull.shift()!();
}
}

View File

@@ -1,3 +0,0 @@
export * from "./BoundedQueue";
export * from "./HybridPromise";
export * from "./Scheduler";

View File

@@ -1,5 +1,4 @@
export * from "./concurrency";
export * from "./format"; export * from "./format";
export * from "./gotoStateful"; export * from "./gotoStateful";
export * from "./search"; export * from "./HybridPromise";
export * from "./sort"; export * from "./sort";

View File

@@ -1,28 +0,0 @@
import { disassemble, getChoseong } from "es-hangul";
const normalize = (s: string) => {
return s.normalize("NFC").toLowerCase().replace(/\s/g, "");
};
const extractHangul = (s: string) => {
return s.replace(/[^가-힣ㄱ-ㅎㅏ-ㅣ]/g, "");
};
const hangulSearch = (original: string, query: string) => {
original = extractHangul(original);
query = extractHangul(query);
if (!original || !query) return false;
return (
disassemble(original).includes(disassemble(query)) ||
getChoseong(original).includes(getChoseong(query))
);
};
export const searchString = (original: string, query: string) => {
original = normalize(original);
query = normalize(query);
if (!original || !query) return false;
return original.includes(query) || hangulSearch(original, query);
};

View File

@@ -18,7 +18,6 @@
requestThumbnailUpload, requestThumbnailUpload,
requestFileAdditionToCategory, requestFileAdditionToCategory,
requestVideoStream, requestVideoStream,
requestFavoriteToggle,
} from "./service"; } from "./service";
import TopBarMenu from "./TopBarMenu.svelte"; import TopBarMenu from "./TopBarMenu.svelte";
@@ -76,11 +75,6 @@
void getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME void getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
}; };
const toggleFavorite = async () => {
await requestFavoriteToggle(data.id, !!info?.isFavorite);
void getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
};
$effect(() => { $effect(() => {
HybridPromise.resolve(getFileInfo(data.id, $masterKeyStore?.get(1)?.key!)).then((result) => { HybridPromise.resolve(getFileInfo(data.id, $masterKeyStore?.get(1)?.key!)).then((result) => {
if (data.id === result.id) { if (data.id === result.id) {
@@ -150,22 +144,18 @@
<div onclick={(e) => e.stopPropagation()}> <div onclick={(e) => e.stopPropagation()}>
<button <button
onclick={() => (isMenuOpen = !isMenuOpen)} onclick={() => (isMenuOpen = !isMenuOpen)}
class="w-full rounded-full p-1 text-2xl active:bg-black active:bg-opacity-[0.04]" class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-black active:bg-opacity-[0.04]"
> >
<IconMoreVert /> <IconMoreVert class="text-2xl" />
</button> </button>
<TopBarMenu <TopBarMenu
bind:isOpen={isMenuOpen} bind:isOpen={isMenuOpen}
directoryId={["category", "gallery", "search", "favorite"].includes( directoryId={["category", "gallery"].includes(page.url.searchParams.get("from") ?? "")
page.url.searchParams.get("from") ?? "",
)
? info?.parentId ? info?.parentId
: undefined} : undefined}
{fileBlob} {fileBlob}
downloadUrl={videoStreamUrl} downloadUrl={videoStreamUrl}
filename={info?.name} filename={info?.name}
isFavorite={info?.isFavorite}
onToggleFavorite={toggleFavorite}
/> />
</div> </div>
</TopBar> </TopBar>

View File

@@ -5,8 +5,6 @@
import { fly } from "svelte/transition"; import { fly } from "svelte/transition";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import IconFavorite from "~icons/material-symbols/favorite";
import IconFavoriteOutline from "~icons/material-symbols/favorite-outline";
import IconFolderOpen from "~icons/material-symbols/folder-open"; import IconFolderOpen from "~icons/material-symbols/folder-open";
import IconCloudDownload from "~icons/material-symbols/cloud-download"; import IconCloudDownload from "~icons/material-symbols/cloud-download";
@@ -15,20 +13,10 @@
downloadUrl?: string; downloadUrl?: string;
fileBlob?: Blob; fileBlob?: Blob;
filename?: string; filename?: string;
isFavorite?: boolean;
isOpen: boolean; isOpen: boolean;
onToggleFavorite?: () => void;
} }
let { let { directoryId, downloadUrl, fileBlob, filename, isOpen = $bindable() }: Props = $props();
directoryId,
downloadUrl,
fileBlob,
filename,
isFavorite,
isOpen = $bindable(),
onToggleFavorite,
}: Props = $props();
const handleDownload = () => { const handleDownload = () => {
if (fileBlob && filename) { if (fileBlob && filename) {
@@ -46,7 +34,7 @@
{#if isOpen && (directoryId || downloadUrl || fileBlob)} {#if isOpen && (directoryId || downloadUrl || fileBlob)}
<div <div
class="absolute right-2 top-full z-20 min-w-44 space-y-1 rounded-lg bg-white px-1 py-2 shadow-2xl" class="absolute right-2 top-full z-20 space-y-1 rounded-lg bg-white px-1 py-2 shadow-2xl"
transition:fly={{ y: -8, duration: 200 }} transition:fly={{ y: -8, duration: 200 }}
> >
<p class="px-3 pt-2 text-sm font-semibold text-gray-600">더보기</p> <p class="px-3 pt-2 text-sm font-semibold text-gray-600">더보기</p>
@@ -66,13 +54,6 @@
</button> </button>
{/snippet} {/snippet}
{#if isFavorite !== undefined}
{@render menuButton(
isFavorite ? IconFavorite : IconFavoriteOutline,
isFavorite ? "즐겨찾기 해제" : "즐겨찾기",
onToggleFavorite ?? (() => {}),
)}
{/if}
{#if directoryId} {#if directoryId}
{@render menuButton(IconFolderOpen, "폴더에서 보기", () => {@render menuButton(IconFolderOpen, "폴더에서 보기", () =>
goto( goto(

View File

@@ -1,3 +1,4 @@
import { encryptData } from "$lib/modules/crypto";
import { storeFileThumbnailCache } from "$lib/modules/file"; import { storeFileThumbnailCache } from "$lib/modules/file";
import { prepareFileDecryption, getDecryptedFileUrl } from "$lib/serviceWorker"; import { prepareFileDecryption, getDecryptedFileUrl } from "$lib/serviceWorker";
import { requestFileThumbnailUpload } from "$lib/services/file"; import { requestFileThumbnailUpload } from "$lib/services/file";
@@ -32,10 +33,12 @@ export const requestThumbnailUpload = async (
dataKey: CryptoKey, dataKey: CryptoKey,
dataKeyVersion: Date, dataKeyVersion: Date,
) => { ) => {
const res = await requestFileThumbnailUpload(fileId, thumbnail, dataKey, dataKeyVersion); const thumbnailBuffer = await thumbnail.arrayBuffer();
if (!res) return false; const thumbnailEncrypted = await encryptData(thumbnailBuffer, dataKey);
const res = await requestFileThumbnailUpload(fileId, dataKeyVersion, thumbnailEncrypted);
if (!res.ok) return false;
void thumbnail.arrayBuffer().then((buffer) => storeFileThumbnailCache(fileId, buffer)); storeFileThumbnailCache(fileId, thumbnailBuffer); // Intended
return true; return true;
}; };
@@ -48,17 +51,3 @@ export const requestFileAdditionToCategory = async (fileId: number, categoryId:
return false; return false;
} }
}; };
export const requestFavoriteToggle = async (fileId: number, isFavorite: boolean) => {
try {
if (isFavorite) {
await trpc().favorites.removeFile.mutate({ id: fileId });
} else {
await trpc().favorites.addFile.mutate({ id: fileId });
}
return true;
} catch {
// TODO: Error Handling
return false;
}
};

View File

@@ -16,7 +16,7 @@
<TopBar /> <TopBar />
<FullscreenDiv> <FullscreenDiv>
<div class="space-y-2 pb-4"> <div class="space-y-2 pb-4">
{#each uploadingFiles as file (file.id)} {#each uploadingFiles as file}
<File state={file} /> <File state={file} />
{/each} {/each}
</div> </div>

View File

@@ -63,7 +63,7 @@
<FullscreenDiv> <FullscreenDiv>
<RowVirtualizer <RowVirtualizer
count={rows.length} count={rows.length}
estimateItemHeight={(index) => itemHeight={(index) =>
rows[index]!.type === "header" ? 28 : 181 + (rows[index]!.isLast ? 16 : 4)} rows[index]!.type === "header" ? 28 : 181 + (rows[index]!.isLast ? 16 : 4)}
class="flex flex-grow flex-col" class="flex flex-grow flex-col"
> >

View File

@@ -1,254 +0,0 @@
<script lang="ts">
import type { Snapshot } from "@sveltejs/kit";
import superjson, { type SuperJSONResult } from "superjson";
import { untrack } from "svelte";
import { slide } from "svelte/transition";
import { goto } from "$app/navigation";
import { Chip, FullscreenDiv, RowVirtualizer } from "$lib/components/atoms";
import {
getDirectoryInfo,
type LocalCategoryInfo,
type MaybeDirectoryInfo,
} from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import { HybridPromise, searchString, sortEntries } from "$lib/utils";
import Directory from "./Directory.svelte";
import File from "./File.svelte";
import SearchBar from "./SearchBar.svelte";
import SelectCategoryBottomSheet from "./SelectCategoryBottomSheet.svelte";
import { requestSearch, type SearchFilter, type SearchResult } from "./service";
let { data } = $props();
interface SearchFilters {
name: string;
includeImages: boolean;
includeVideos: boolean;
includeDirectories: boolean;
searchInFavorites: boolean;
searchInDirectory: boolean;
categories: SearchFilter["categories"];
}
let directoryInfo: MaybeDirectoryInfo | undefined = $state();
let filters: SearchFilters = $state({
name: "",
includeImages: false,
includeVideos: false,
includeDirectories: false,
searchInDirectory: false,
searchInFavorites: false,
categories: [],
});
let hasCategoryFilter = $derived(filters.categories.length > 0);
let hasAnyFilter = $derived(
hasCategoryFilter ||
filters.includeImages ||
filters.includeVideos ||
filters.includeDirectories ||
filters.name.trim().length > 0,
);
let isRestoredFromSnapshot = $state(false);
let serverResult: SearchResult | undefined = $state();
let result = $derived.by(() => {
if (!serverResult) return [];
const nameFilter = filters.name.trim();
const hasTypeFilter =
filters.includeImages || filters.includeVideos || filters.includeDirectories;
const directories =
!hasTypeFilter || filters.includeDirectories
? serverResult.directories.map((directory) => ({
type: "directory" as const,
...directory,
}))
: [];
const files =
!hasTypeFilter || filters.includeImages || filters.includeVideos
? serverResult.files
.filter(
({ contentType }) =>
!hasTypeFilter ||
(filters.includeImages && contentType.startsWith("image/")) ||
(filters.includeVideos && contentType.startsWith("video/")),
)
.map((file) => ({
type: "file" as const,
...file,
}))
: [];
return sortEntries(
[...directories, ...files].filter(
(entry) => !nameFilter || searchString(entry.name, nameFilter),
),
);
});
let isSelectCategoryBottomSheetOpen = $state(false);
let categorySelectMode: "include" | "exclude" = $state("include");
const openSelectCategoryBottomSheet = (mode: "include" | "exclude") => {
categorySelectMode = mode;
isSelectCategoryBottomSheetOpen = true;
};
const addCategoryFilter = (category: LocalCategoryInfo) => {
if (!filters.categories.some(({ info }) => info.id === category.id)) {
filters.categories.push({
info: category,
type: categorySelectMode,
});
isSelectCategoryBottomSheetOpen = false;
}
};
export const snapshot: Snapshot<{
filters: SearchFilters;
serverResult: SuperJSONResult;
}> = {
capture() {
return { filters, serverResult: superjson.serialize(serverResult) };
},
restore(value) {
filters = value.filters;
serverResult = superjson.deserialize(value.serverResult, { inPlace: true });
isRestoredFromSnapshot = true;
},
};
$effect.pre(() => {
if (data.directoryId) {
HybridPromise.resolve(getDirectoryInfo(data.directoryId, $masterKeyStore?.get(1)?.key!)).then(
(res) => {
directoryInfo = res;
filters.searchInDirectory = res.exists;
},
);
} else {
directoryInfo = undefined;
filters.searchInDirectory = false;
}
});
$effect.pre(() => {
filters.searchInFavorites = data.fromFavorites;
});
$effect(() => {
// Svelte sucks
hasAnyFilter;
filters.searchInDirectory;
filters.searchInFavorites;
filters.categories.length;
if (untrack(() => isRestoredFromSnapshot)) {
isRestoredFromSnapshot = false;
return;
}
if (hasAnyFilter) {
requestSearch(
{
ancestorId: filters.searchInDirectory ? data.directoryId! : "root",
inFavorites: filters.searchInFavorites,
categories: filters.categories,
},
$masterKeyStore?.get(1)?.key!,
).then((res) => {
serverResult = res;
});
}
});
</script>
<svelte:head>
<title>검색</title>
</svelte:head>
<SearchBar bind:value={filters.name} />
<FullscreenDiv class="bg-gray-100 !px-0">
<div class="flex flex-grow flex-col space-y-4">
<div class="space-y-2 bg-white p-4 !pt-0">
<div class="space-y-3">
<div class="flex flex-wrap gap-2">
<Chip bind:selected={filters.includeImages}>사진</Chip>
<Chip bind:selected={filters.includeVideos}>동영상</Chip>
{#if !hasCategoryFilter}
<Chip bind:selected={filters.includeDirectories}>폴더</Chip>
{/if}
<Chip bind:selected={filters.searchInFavorites}>즐겨찾기</Chip>
{#if directoryInfo?.exists}
<Chip bind:selected={filters.searchInDirectory}>
위치: {directoryInfo.name}
</Chip>
{/if}
</div>
{#if !filters.includeDirectories}
<div class="space-y-2" transition:slide={{ duration: 300 }}>
<p class="text-sm font-medium text-gray-600">카테고리</p>
<div class="flex flex-wrap gap-2">
{#each filters.categories as { info, type }, i (info.id)}
<Chip
selected
removable
onclick={() => {}}
onRemoveClick={() => filters.categories.splice(i, 1)}
>
{#if type === "include"}
포함:
{:else}
제외:
{/if}
{info.name}
</Chip>
{/each}
<Chip onclick={() => openSelectCategoryBottomSheet("include")}>+ 포함</Chip>
<Chip onclick={() => openSelectCategoryBottomSheet("exclude")}>- 제외</Chip>
</div>
</div>
{/if}
</div>
</div>
{#if hasAnyFilter}
<div class="flex flex-grow flex-col space-y-2 bg-white p-4">
<p class="text-lg font-bold text-gray-800">
검색 결과
{#if result.length > 0}
{" "}({result.length}개)
{/if}
</p>
{#if result.length > 0}
<RowVirtualizer
count={result.length}
getItemKey={(index) => `${result[index]!.type}-${result[index]!.id}`}
estimateItemHeight={() => 56}
itemGap={4}
>
{#snippet item(index)}
{@const info = result[index]!}
{#if info.type === "directory"}
<Directory {info} onclick={() => goto(`/directory/${info.id}?from=search`)} />
{:else}
<File {info} onclick={() => goto(`/file/${info.id}?from=search`)} />
{/if}
{/snippet}
</RowVirtualizer>
{:else}
<div class="flex flex-grow items-center justify-center py-8">
<p class="text-gray-500">검색 결과가 없어요.</p>
</div>
{/if}
</div>
{/if}
</div>
</FullscreenDiv>
<SelectCategoryBottomSheet
bind:isOpen={isSelectCategoryBottomSheetOpen}
mode={categorySelectMode}
onSelectCategoryClick={addCategoryFilter}
/>

View File

@@ -1,21 +0,0 @@
import { error } from "@sveltejs/kit";
import { z } from "zod";
import type { PageLoad } from "./$types";
export const load: PageLoad = ({ url }) => {
const directoryId = url.searchParams.get("directoryId");
const from = url.searchParams.get("from");
const zodRes = z
.object({
directoryId: z.coerce.number().int().positive().nullable(),
from: z.enum(["favorites"]).nullable(),
})
.safeParse({ directoryId, from });
if (!zodRes.success) error(400, "Invalid query parameters");
return {
directoryId: zodRes.data.directoryId,
fromFavorites: zodRes.data.from === "favorites",
};
};

View File

@@ -1,16 +0,0 @@
<script lang="ts">
import { ActionEntryButton } from "$lib/components/atoms";
import { DirectoryEntryLabel } from "$lib/components/molecules";
import type { SubDirectoryInfo } from "$lib/modules/filesystem";
interface Props {
info: SubDirectoryInfo;
onclick: () => void;
}
let { info, onclick }: Props = $props();
</script>
<ActionEntryButton class="h-14" {onclick}>
<DirectoryEntryLabel type="directory" name={info.name} isFavorite={info.isFavorite} />
</ActionEntryButton>

View File

@@ -1,26 +0,0 @@
<script lang="ts">
import { ActionEntryButton } from "$lib/components/atoms";
import { DirectoryEntryLabel } from "$lib/components/molecules";
import { getFileThumbnail } from "$lib/modules/file";
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
import { formatDateTime } from "$lib/utils";
interface Props {
info: SummarizedFileInfo;
onclick: () => void;
}
let { info, onclick }: Props = $props();
let thumbnail = $derived(getFileThumbnail(info));
</script>
<ActionEntryButton class="h-14" {onclick}>
<DirectoryEntryLabel
type="file"
thumbnail={$thumbnail}
name={info.name}
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
isFavorite={info.isFavorite}
/>
</ActionEntryButton>

View File

@@ -1,24 +0,0 @@
<script lang="ts">
import IconArrowBack from "~icons/material-symbols/arrow-back";
interface Props {
value: string;
}
let { value = $bindable() }: Props = $props();
</script>
<div class={"sticky top-0 z-10 flex items-center gap-x-2 px-2 py-3 backdrop-blur-2xl"}>
<button
onclick={() => history.back()}
class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-black active:bg-opacity-[0.04]"
>
<IconArrowBack class="text-2xl" />
</button>
<input
bind:value
type="text"
placeholder="검색"
class="mr-1 h-[2.3rem] min-w-0 flex-grow rounded-lg bg-gray-100 px-3 py-1.5 placeholder-gray-600 focus:outline-none"
/>
</div>

View File

@@ -1,54 +0,0 @@
<script lang="ts">
import { BottomDiv, BottomSheet, Button, FullscreenDiv } from "$lib/components/atoms";
import { SubCategories } from "$lib/components/molecules";
import {
getCategoryInfo,
type LocalCategoryInfo,
type MaybeCategoryInfo,
} from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import { HybridPromise } from "$lib/utils";
interface Props {
isOpen: boolean;
mode: "include" | "exclude";
onSelectCategoryClick: (category: LocalCategoryInfo) => void;
}
let { isOpen = $bindable(), mode, onSelectCategoryClick }: Props = $props();
let categoryInfo: MaybeCategoryInfo | undefined = $state();
$effect(() => {
if (isOpen) {
HybridPromise.resolve(getCategoryInfo("root", $masterKeyStore?.get(1)?.key!)).then(
(result) => (categoryInfo = result),
);
}
});
</script>
{#if categoryInfo?.exists}
<BottomSheet bind:isOpen class="flex flex-col">
<FullscreenDiv>
<SubCategories
class="py-4"
info={categoryInfo}
onSubCategoryClick={({ id }) =>
HybridPromise.resolve(getCategoryInfo(id, $masterKeyStore?.get(1)?.key!)).then(
(result) => (categoryInfo = result),
)}
/>
{#if categoryInfo.id !== "root"}
<BottomDiv>
<Button
onclick={() => onSelectCategoryClick(categoryInfo as LocalCategoryInfo)}
class="w-full"
>
{categoryInfo.name} 카테고리 {mode === "include" ? "꼭 포함하기" : "제외하기"}
</Button>
</BottomDiv>
{/if}
</FullscreenDiv>
</BottomSheet>
{/if}

View File

@@ -1,44 +0,0 @@
import {
getDirectoryInfo,
getFileInfo,
type LocalDirectoryInfo,
type FileInfo,
type LocalCategoryInfo,
} from "$lib/modules/filesystem";
import { HybridPromise } from "$lib/utils";
import { trpc } from "$trpc/client";
export interface SearchFilter {
ancestorId: DirectoryId;
inFavorites: boolean;
categories: { info: LocalCategoryInfo; type: "include" | "exclude" }[];
}
export interface SearchResult {
directories: LocalDirectoryInfo[];
files: FileInfo[];
}
export const requestSearch = async (filter: SearchFilter, masterKey: CryptoKey) => {
const { directories: directoriesRaw, files: filesRaw } = await trpc().search.search.query({
ancestor: filter.ancestorId,
inFavorites: filter.inFavorites,
includeCategories: filter.categories
.filter(({ type }) => type === "include")
.map(({ info }) => info.id),
excludeCategories: filter.categories
.filter(({ type }) => type === "exclude")
.map(({ info }) => info.id),
});
const [directories, files] = await HybridPromise.all([
HybridPromise.all(
directoriesRaw.map((directory) =>
getDirectoryInfo(directory.id, masterKey, { serverResponse: directory }),
),
),
HybridPromise.all(
filesRaw.map((file) => getFileInfo(file.id, masterKey, { serverResponse: file })),
),
]);
return { directories, files } as SearchResult;
};

View File

@@ -2,6 +2,6 @@ import { createCaller } from "$trpc/router.server";
import type { PageServerLoad } from "./$types"; import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async (event) => { export const load: PageServerLoad = async (event) => {
const favorites = await createCaller(event).favorites.get(); const files = await createCaller(event).file.listLegacy();
return { favorites }; return { files };
}; };

View File

@@ -0,0 +1,79 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { BottomDiv, Button, FullscreenDiv } from "$lib/components/atoms";
import { TopBar } from "$lib/components/molecules";
import { bulkGetFileInfo, type MaybeFileInfo } from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import { sortEntries } from "$lib/utils";
import File from "./File.svelte";
import { getMigrationState, clearMigrationStates, requestFileMigration } from "./service.svelte";
let { data } = $props();
let fileInfos: MaybeFileInfo[] = $state([]);
let files = $derived(
fileInfos
.map((info) => ({
info,
state: getMigrationState(info.id),
}))
.filter((file) => file.state?.status !== "completed"),
);
const migrateAllFiles = () => {
files.forEach(({ info }) => {
if (info.exists) {
requestFileMigration(info);
}
});
};
onMount(async () => {
fileInfos = sortEntries(
Array.from((await bulkGetFileInfo(data.files, $masterKeyStore?.get(1)?.key!)).values()),
);
});
$effect(() => clearMigrationStates);
</script>
<svelte:head>
<title>암호화 마이그레이션</title>
</svelte:head>
<TopBar title="암호화 마이그레이션" />
<FullscreenDiv>
{#if files.length > 0}
<div class="space-y-4 pb-4">
<p class="break-keep text-gray-800">
이전 버전의 ArkVault에서 업로드된 {files.length}개 파일을 다시 암호화할 수 있어요.
</p>
<div class="space-y-2">
{#each files as { info, state } (info.id)}
{#if info.exists}
<File
{info}
{state}
onclick={({ id }) => goto(`/file/${id}`)}
onMigrateClick={requestFileMigration}
/>
{/if}
{/each}
</div>
</div>
<BottomDiv>
<Button onclick={migrateAllFiles} class="w-full">모두 다시 암호화하기</Button>
</BottomDiv>
{:else}
<div class="flex flex-grow items-center justify-center">
<p class="text-gray-500">
{#if data.files.length === 0}
마이그레이션할 파일이 없어요.
{:else}
파일 목록을 불러오고 있어요.
{/if}
</p>
</div>
{/if}
</FullscreenDiv>

View File

@@ -0,0 +1,55 @@
<script module lang="ts">
const subtexts = {
queued: "대기 중",
"download-pending": "다운로드를 기다리는 중",
downloading: "다운로드하는 중",
"encryption-pending": "암호화를 기다리는 중",
encrypting: "암호화하는 중",
"upload-pending": "업로드를 기다리는 중",
completed: "완료",
error: "실패",
} as const;
</script>
<script lang="ts">
import { ActionEntryButton } from "$lib/components/atoms";
import { DirectoryEntryLabel } from "$lib/components/molecules";
import type { FileInfo } from "$lib/modules/filesystem";
import { formatDateTime, formatNetworkSpeed } from "$lib/utils";
import type { MigrationState } from "./service.svelte";
import IconSync from "~icons/material-symbols/sync";
type FileInfoWithExists = FileInfo & { exists: true };
interface Props {
info: FileInfoWithExists;
onclick: (file: FileInfo) => void;
onMigrateClick: (file: FileInfoWithExists) => void;
state: MigrationState | undefined;
}
let { info, onclick, onMigrateClick, state }: Props = $props();
let subtext = $derived.by(() => {
if (!state) {
return formatDateTime(info.createdAt ?? info.lastModifiedAt);
}
if (state.status === "uploading") {
const progress = Math.floor((state.progress ?? 0) * 100);
const speed = formatNetworkSpeed((state.rate ?? 0) * 8);
return `전송됨 ${progress}% · ${speed}`;
}
return subtexts[state.status] ?? state.status;
});
</script>
<ActionEntryButton
class="h-14"
onclick={() => onclick(info)}
actionButtonIcon={!state || state.status === "error" ? IconSync : undefined}
onActionButtonClick={() => onMigrateClick(info)}
actionButtonClass="text-gray-800"
>
<DirectoryEntryLabel type="file" name={info.name} {subtext} />
</ActionEntryButton>

View File

@@ -0,0 +1,107 @@
import { limitFunction } from "p-limit";
import { SvelteMap } from "svelte/reactivity";
import { CHUNK_SIZE } from "$lib/constants";
import type { FileInfo } from "$lib/modules/filesystem";
import { Scheduler } from "$lib/modules/scheduler";
import { uploadBlob } from "$lib/modules/upload";
import { requestFileDownload } from "$lib/services/file";
import { trpc } from "$trpc/client";
export type MigrationStatus =
| "queued"
| "download-pending"
| "downloading"
| "encryption-pending"
| "encrypting"
| "upload-pending"
| "uploading"
| "completed"
| "error";
export interface MigrationState {
status: MigrationStatus;
progress?: number;
rate?: number;
}
const scheduler = new Scheduler();
const states = new SvelteMap<number, MigrationState>();
const createState = (status: MigrationStatus): MigrationState => {
const state = $state({ status });
return state;
};
export const getMigrationState = (fileId: number) => {
return states.get(fileId);
};
export const clearMigrationStates = () => {
for (const [id, state] of states) {
if (state.status === "completed" || state.status === "error") {
states.delete(id);
}
}
};
const uploadMigrationChunks = limitFunction(
async (state: MigrationState, fileId: number, fileBuffer: ArrayBuffer, dataKey: CryptoKey) => {
state.status = "uploading";
const { uploadId } = await trpc().upload.startMigrationUpload.mutate({
file: fileId,
chunks: Math.ceil(fileBuffer.byteLength / CHUNK_SIZE),
});
await uploadBlob(uploadId, new Blob([fileBuffer]), dataKey, {
onProgress(s) {
state.progress = s.progress;
state.rate = s.rateBps;
},
});
await trpc().upload.completeMigrationUpload.mutate({ uploadId });
},
{ concurrency: 1 },
);
export const requestFileMigration = async (fileInfo: FileInfo) => {
let state = states.get(fileInfo.id);
if (state) {
if (state.status !== "error") return;
state.status = "queued";
state.progress = undefined;
state.rate = undefined;
} else {
state = createState("queued");
states.set(fileInfo.id, state);
}
try {
const dataKey = fileInfo.dataKey?.key;
if (!dataKey) {
throw new Error("Data key not available");
}
let fileBuffer: ArrayBuffer | undefined;
await scheduler.schedule(
async () => {
state.status = "download-pending";
state.status = "downloading";
fileBuffer = await requestFileDownload(fileInfo.id, dataKey, true);
return fileBuffer.byteLength;
},
async () => {
state.status = "encryption-pending";
await uploadMigrationChunks(state, fileInfo.id, fileBuffer!, dataKey);
state.status = "completed";
},
);
} catch (e) {
state.status = "error";
throw e;
}
};

View File

@@ -4,14 +4,13 @@
import { BottomDiv, Button, FullscreenDiv } from "$lib/components/atoms"; import { BottomDiv, Button, FullscreenDiv } from "$lib/components/atoms";
import { IconEntryButton, TopBar } from "$lib/components/molecules"; import { IconEntryButton, TopBar } from "$lib/components/molecules";
import { deleteAllFileThumbnailCaches } from "$lib/modules/file"; import { deleteAllFileThumbnailCaches } from "$lib/modules/file";
import type { MaybeFileInfo } from "$lib/modules/filesystem"; import { bulkGetFileInfo, type MaybeFileInfo } from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores"; import { masterKeyStore } from "$lib/stores";
import { sortEntries } from "$lib/utils"; import { sortEntries } from "$lib/utils";
import File from "./File.svelte"; import File from "./File.svelte";
import { import {
getThumbnailGenerationStatus, getThumbnailGenerationStatus,
clearThumbnailGenerationStatuses, clearThumbnailGenerationStatuses,
requestMissingThumbnailFiles,
requestThumbnailGeneration, requestThumbnailGeneration,
type GenerationStatus, type GenerationStatus,
} from "./service"; } from "./service";
@@ -43,7 +42,7 @@
onMount(async () => { onMount(async () => {
fileInfos = sortEntries( fileInfos = sortEntries(
await requestMissingThumbnailFiles(data.files, $masterKeyStore?.get(1)?.key!), Array.from((await bulkGetFileInfo(data.files, $masterKeyStore?.get(1)?.key!)).values()),
); );
}); });

View File

@@ -3,6 +3,7 @@
queued: "대기 중", queued: "대기 중",
"generation-pending": "준비 중", "generation-pending": "준비 중",
generating: "생성하는 중", generating: "생성하는 중",
"upload-pending": "업로드를 기다리는 중",
uploading: "업로드하는 중", uploading: "업로드하는 중",
error: "실패", error: "실패",
} as const; } as const;

View File

@@ -1,16 +1,17 @@
import { limitFunction } from "p-limit"; import { limitFunction } from "p-limit";
import { SvelteMap } from "svelte/reactivity"; import { SvelteMap } from "svelte/reactivity";
import { encryptData } from "$lib/modules/crypto";
import { storeFileThumbnailCache } from "$lib/modules/file"; import { storeFileThumbnailCache } from "$lib/modules/file";
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem"; import type { FileInfo } from "$lib/modules/filesystem";
import { generateThumbnail } from "$lib/modules/thumbnail"; import { Scheduler } from "$lib/modules/scheduler";
import { generateThumbnail as doGenerateThumbnail } from "$lib/modules/thumbnail";
import { requestFileDownload, requestFileThumbnailUpload } from "$lib/services/file"; import { requestFileDownload, requestFileThumbnailUpload } from "$lib/services/file";
import { HybridPromise, Scheduler } from "$lib/utils";
import type { RouterOutputs } from "$trpc/router.server";
export type GenerationStatus = export type GenerationStatus =
| "queued" | "queued"
| "generation-pending" | "generation-pending"
| "generating" | "generating"
| "upload-pending"
| "uploading" | "uploading"
| "uploaded" | "uploaded"
| "error"; | "error";
@@ -30,37 +31,33 @@ export const clearThumbnailGenerationStatuses = () => {
} }
}; };
export const requestMissingThumbnailFiles = async ( const generateThumbnail = limitFunction(
filesRaw: RouterOutputs["file"]["listWithoutThumbnail"], async (fileId: number, fileBuffer: ArrayBuffer, fileType: string, dataKey: CryptoKey) => {
masterKey: CryptoKey, statuses.set(fileId, "generating");
) => {
const files = await HybridPromise.all( const thumbnail = await doGenerateThumbnail(fileBuffer, fileType);
filesRaw.map((file) => getFileInfo(file.id, masterKey, { serverResponse: file })), if (!thumbnail) return null;
);
return files; const thumbnailBuffer = await thumbnail.arrayBuffer();
}; const thumbnailEncrypted = await encryptData(thumbnailBuffer, dataKey);
statuses.set(fileId, "upload-pending");
return { plaintext: thumbnailBuffer, ...thumbnailEncrypted };
},
{ concurrency: 4 },
);
const requestThumbnailUpload = limitFunction( const requestThumbnailUpload = limitFunction(
async (fileInfo: FileInfo, fileBuffer: ArrayBuffer) => { async (
statuses.set(fileInfo.id, "generating"); fileId: number,
dataKeyVersion: Date,
thumbnail: { plaintext: ArrayBuffer; ciphertext: ArrayBuffer; iv: ArrayBuffer },
) => {
statuses.set(fileId, "uploading");
const thumbnail = await generateThumbnail( const res = await requestFileThumbnailUpload(fileId, dataKeyVersion, thumbnail);
new Blob([fileBuffer], { type: fileInfo.contentType }), if (!res.ok) return false;
); statuses.set(fileId, "uploaded");
if (!thumbnail) return false; storeFileThumbnailCache(fileId, thumbnail.plaintext); // Intended
statuses.set(fileInfo.id, "uploading");
const res = await requestFileThumbnailUpload(
fileInfo.id,
thumbnail,
fileInfo.dataKey?.key!,
fileInfo.dataKey?.version!,
);
if (!res) return false;
statuses.set(fileInfo.id, "uploaded");
void thumbnail.arrayBuffer().then((buffer) => storeFileThumbnailCache(fileInfo.id, buffer));
return true; return true;
}, },
{ concurrency: 4 }, { concurrency: 4 },
@@ -84,7 +81,16 @@ export const requestThumbnailGeneration = async (fileInfo: FileInfo) => {
return file.byteLength; return file.byteLength;
}, },
async () => { async () => {
if (!(await requestThumbnailUpload(fileInfo, file!))) { const thumbnail = await generateThumbnail(
fileInfo.id,
file!,
fileInfo.contentType,
fileInfo.dataKey?.key!,
);
if (
!thumbnail ||
!(await requestThumbnailUpload(fileInfo.id, fileInfo.dataKey?.version!, thumbnail))
) {
statuses.set(fileInfo.id, "error"); statuses.set(fileInfo.id, "error");
} }
}, },

View File

@@ -12,7 +12,7 @@
const pages = [ const pages = [
{ path: "/home", label: "홈", icon: IconHome }, { path: "/home", label: "홈", icon: IconHome },
{ path: "/directory", label: "파일", icon: IconFolder }, { path: "/directory", label: "파일", icon: IconFolder },
{ path: "/favorites", label: "즐겨찾기", icon: IconFavorite }, { path: "/favorite", label: "즐겨찾기", icon: IconFavorite },
{ path: "/category", label: "카테고리", icon: IconCategory }, { path: "/category", label: "카테고리", icon: IconCategory },
{ path: "/menu", label: "전체", icon: IconMenu }, { path: "/menu", label: "전체", icon: IconMenu },
]; ];

View File

@@ -76,7 +76,7 @@
<div class="min-h-full bg-gray-100 pb-[5.5em]"> <div class="min-h-full bg-gray-100 pb-[5.5em]">
{#if info?.exists} {#if info?.exists}
<div class="space-y-4"> <div class="space-y-4">
<div class="space-y-2 bg-white p-4"> <div class="space-y-4 bg-white p-4">
{#if info.id !== "root"} {#if info.id !== "root"}
<p class="text-lg font-bold text-gray-800">하위 카테고리</p> <p class="text-lg font-bold text-gray-800">하위 카테고리</p>
{/if} {/if}
@@ -84,7 +84,6 @@
{info} {info}
onSubCategoryClick={({ id }) => goto(`/category/${id}`)} onSubCategoryClick={({ id }) => goto(`/category/${id}`)}
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)} onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
subCategoryCreatePosition="bottom"
onSubCategoryMenuClick={(subCategory) => { onSubCategoryMenuClick={(subCategory) => {
context.selectedCategory = subCategory; context.selectedCategory = subCategory;
isCategoryMenuBottomSheetOpen = true; isCategoryMenuBottomSheetOpen = true;
@@ -93,19 +92,14 @@
/> />
</div> </div>
{#if info.id !== "root"} {#if info.id !== "root"}
<div class="space-y-2 bg-white p-4"> <div class="space-y-4 bg-white p-4">
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<p class="text-lg font-bold text-gray-800">파일</p> <p class="text-lg font-bold text-gray-800">파일</p>
<CheckBox bind:checked={info.isFileRecursive}> <CheckBox bind:checked={info.isFileRecursive}>
<p class="font-medium">하위 카테고리의 파일</p> <p class="font-medium">하위 카테고리의 파일</p>
</CheckBox> </CheckBox>
</div> </div>
<RowVirtualizer <RowVirtualizer count={files.length} itemHeight={() => 48} itemGap={4}>
count={files.length}
getItemKey={(index) => files[index]!.details.id}
estimateItemHeight={() => 48}
itemGap={4}
>
{#snippet item(index)} {#snippet item(index)}
{@const { details } = files[index]!} {@const { details } = files[index]!}
<File <File

View File

@@ -3,7 +3,6 @@
import { DirectoryEntryLabel } from "$lib/components/molecules"; import { DirectoryEntryLabel } from "$lib/components/molecules";
import { getFileThumbnail } from "$lib/modules/file"; import { getFileThumbnail } from "$lib/modules/file";
import type { CategoryFileInfo } from "$lib/modules/filesystem"; import type { CategoryFileInfo } from "$lib/modules/filesystem";
import { formatDateTime } from "$lib/utils";
import type { SelectedFile } from "./service.svelte"; import type { SelectedFile } from "./service.svelte";
import IconClose from "~icons/material-symbols/close"; import IconClose from "~icons/material-symbols/close";
@@ -20,16 +19,10 @@
</script> </script>
<ActionEntryButton <ActionEntryButton
class="h-14" class="h-12"
onclick={() => onclick(info)} onclick={() => onclick(info)}
actionButtonIcon={onRemoveClick && IconClose} actionButtonIcon={onRemoveClick && IconClose}
onActionButtonClick={() => onRemoveClick?.(info)} onActionButtonClick={() => onRemoveClick?.(info)}
> >
<DirectoryEntryLabel <DirectoryEntryLabel type="file" thumbnail={$thumbnail} name={info.name} />
type="file"
thumbnail={$thumbnail}
name={info.name}
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
isFavorite={info.isFavorite}
/>
</ActionEntryButton> </ActionEntryButton>

View File

@@ -23,10 +23,8 @@
requestFileUpload, requestFileUpload,
requestEntryRename, requestEntryRename,
requestEntryDeletion, requestEntryDeletion,
requestFavoriteToggle,
} from "./service.svelte"; } from "./service.svelte";
import IconSearch from "~icons/material-symbols/search";
import IconAdd from "~icons/material-symbols/add"; import IconAdd from "~icons/material-symbols/add";
let { data } = $props(); let { data } = $props();
@@ -45,19 +43,8 @@
let isEntryRenameModalOpen = $state(false); let isEntryRenameModalOpen = $state(false);
let isEntryDeleteModalOpen = $state(false); let isEntryDeleteModalOpen = $state(false);
let showParentEntry = $derived( let isFromFilePage = $derived(page.url.searchParams.get("from") === "file");
["file", "search", "favorite"].includes(page.url.searchParams.get("from") ?? ""), let showTopBar = $derived(data.id !== "root" || isFromFilePage);
);
let showBackButton = $derived(data.id !== "root" || showParentEntry);
const onSearchClick = async () => {
const params = new URLSearchParams();
if (data.id !== "root") {
params.set("directoryId", data.id.toString());
}
const query = params.toString();
await goto(`/search${query ? `?${query}` : ""}`);
};
const uploadFile = () => { const uploadFile = () => {
const files = fileInput?.files; const files = fileInput?.files;
@@ -103,22 +90,17 @@
</script> </script>
<svelte:head> <svelte:head>
<title>파일</title> <title>파일</title>
</svelte:head> </svelte:head>
<input bind:this={fileInput} onchange={uploadFile} type="file" multiple class="hidden" /> <input bind:this={fileInput} onchange={uploadFile} type="file" multiple class="hidden" />
<div class="flex h-full flex-col"> <div class="flex h-full flex-col">
<TopBar title={info?.name ?? "내 파일"} {showBackButton} class="flex-shrink-0"> {#if showTopBar}
<button <TopBar title={info?.name} class="flex-shrink-0" />
onclick={onSearchClick} {/if}
class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-black active:bg-opacity-[0.04]"
>
<IconSearch class="text-2xl" />
</button>
</TopBar>
{#if info?.exists} {#if info?.exists}
<div class="flex flex-grow flex-col px-4 pb-4"> <div class={["flex flex-grow flex-col px-4 pb-4", !showTopBar && "pt-4"]}>
<div class="flex gap-x-2"> <div class="flex gap-x-2">
<UploadStatusCard onclick={() => goto("/file/uploads")} /> <UploadStatusCard onclick={() => goto("/file/uploads")} />
<DownloadStatusCard onclick={() => goto("/file/downloads")} /> <DownloadStatusCard onclick={() => goto("/file/downloads")} />
@@ -131,12 +113,12 @@
context.selectedEntry = entry; context.selectedEntry = entry;
isEntryMenuBottomSheetOpen = true; isEntryMenuBottomSheetOpen = true;
}} }}
showParentEntry={showParentEntry && data.id !== "root"} showParentEntry={isFromFilePage && info.parentId !== undefined}
onParentClick={() => onParentClick={() =>
goto( goto(
info!.parentId === "root" info!.parentId === "root"
? `/directory?from=${page.url.searchParams.get("from")}` ? "/directory?from=file"
: `/directory/${info!.parentId}?from=${page.url.searchParams.get("from")}`, : `/directory/${info!.parentId}?from=file`,
)} )}
/> />
{/key} {/key}
@@ -195,12 +177,6 @@
isEntryMenuBottomSheetOpen = false; isEntryMenuBottomSheetOpen = false;
isEntryDeleteModalOpen = true; isEntryDeleteModalOpen = true;
}} }}
onFavoriteClick={async () => {
if (await requestFavoriteToggle(context.selectedEntry!)) {
isEntryMenuBottomSheetOpen = false;
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
}
}}
/> />
<EntryRenameModal <EntryRenameModal
bind:isOpen={isEntryRenameModalOpen} bind:isOpen={isEntryRenameModalOpen}

View File

@@ -46,16 +46,7 @@
</script> </script>
{#if entries.length > 0} {#if entries.length > 0}
<RowVirtualizer <RowVirtualizer count={entries.length} itemHeight={() => 56} itemGap={4} class="pb-[4.5rem]">
count={entries.length}
getItemKey={(index) =>
entries[index]!.type !== "parent"
? `${entries[index]!.type}-${entries[index]!.details.id}`
: entries[index]!.type!}
estimateItemHeight={() => 56}
itemGap={4}
class="pb-[4.5rem]"
>
{#snippet item(index)} {#snippet item(index)}
{@const entry = entries[index]!} {@const entry = entries[index]!}
{#if entry.type === "parent"} {#if entry.type === "parent"}

View File

@@ -19,13 +19,7 @@
let thumbnail = $derived(getFileThumbnail(info)); let thumbnail = $derived(getFileThumbnail(info));
const action = (callback: typeof onclick) => { const action = (callback: typeof onclick) => {
callback({ callback({ type: "file", id: info.id, dataKey: info.dataKey, name: info.name });
type: "file",
id: info.id,
dataKey: info.dataKey,
name: info.name,
isFavorite: info.isFavorite,
});
}; };
</script> </script>
@@ -40,6 +34,5 @@
thumbnail={$thumbnail} thumbnail={$thumbnail}
name={info.name} name={info.name}
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)} subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
isFavorite={info.isFavorite}
/> />
</ActionEntryButton> </ActionEntryButton>

View File

@@ -15,13 +15,7 @@
let { info, onclick, onOpenMenuClick }: Props = $props(); let { info, onclick, onOpenMenuClick }: Props = $props();
const action = (callback: typeof onclick) => { const action = (callback: typeof onclick) => {
callback({ callback({ type: "directory", id: info.id, dataKey: info.dataKey, name: info.name });
type: "directory",
id: info.id,
dataKey: info.dataKey,
name: info.name,
isFavorite: info.isFavorite,
});
}; };
</script> </script>
@@ -31,5 +25,5 @@
actionButtonIcon={IconMoreVert} actionButtonIcon={IconMoreVert}
onActionButtonClick={() => action(onOpenMenuClick)} onActionButtonClick={() => action(onOpenMenuClick)}
> >
<DirectoryEntryLabel type="directory" name={info.name} isFavorite={info.isFavorite} /> <DirectoryEntryLabel type="directory" name={info.name} />
</ActionEntryButton> </ActionEntryButton>

View File

@@ -3,35 +3,24 @@
import { DirectoryEntryLabel, IconEntryButton } from "$lib/components/molecules"; import { DirectoryEntryLabel, IconEntryButton } from "$lib/components/molecules";
import { useContext } from "./service.svelte"; import { useContext } from "./service.svelte";
import IconFavorite from "~icons/material-symbols/favorite";
import IconFavoriteBorder from "~icons/material-symbols/favorite-outline";
import IconEdit from "~icons/material-symbols/edit"; import IconEdit from "~icons/material-symbols/edit";
import IconDelete from "~icons/material-symbols/delete"; import IconDelete from "~icons/material-symbols/delete";
interface Props { interface Props {
isOpen: boolean; isOpen: boolean;
onDeleteClick: () => void; onDeleteClick: () => void;
onFavoriteClick: () => void;
onRenameClick: () => void; onRenameClick: () => void;
} }
let { isOpen = $bindable(), onDeleteClick, onFavoriteClick, onRenameClick }: Props = $props(); let { isOpen = $bindable(), onDeleteClick, onRenameClick }: Props = $props();
let context = useContext(); let context = useContext();
</script> </script>
{#if context.selectedEntry} {#if context.selectedEntry}
{@const { name, type, isFavorite } = context.selectedEntry} {@const { name, type } = context.selectedEntry}
<BottomSheet bind:isOpen class="p-4"> <BottomSheet bind:isOpen class="p-4">
<DirectoryEntryLabel {type} {name} class="h-12 p-2" textClass="!font-semibold" /> <DirectoryEntryLabel {type} {name} class="h-12 p-2" textClass="!font-semibold" />
<div class="my-2 h-px w-full bg-gray-200"></div> <div class="my-2 h-px w-full bg-gray-200"></div>
<IconEntryButton
icon={isFavorite ? IconFavorite : IconFavoriteBorder}
onclick={onFavoriteClick}
class="h-12 w-full"
iconClass={isFavorite ? "text-red-500" : ""}
>
{isFavorite ? "즐겨찾기에서 해제하기" : "즐겨찾기에 추가하기"}
</IconEntryButton>
<IconEntryButton icon={IconEdit} onclick={onRenameClick} class="h-12 w-full"> <IconEntryButton icon={IconEdit} onclick={onRenameClick} class="h-12 w-full">
이름 바꾸기 이름 바꾸기
</IconEntryButton> </IconEntryButton>

View File

@@ -17,7 +17,6 @@ export interface SelectedEntry {
id: number; id: number;
dataKey: DataKey | undefined; dataKey: DataKey | undefined;
name: string; name: string;
isFavorite: boolean;
} }
export const createContext = () => { export const createContext = () => {
@@ -150,25 +149,3 @@ export const requestEntryDeletion = async (entry: SelectedEntry) => {
return false; return false;
} }
}; };
export const requestFavoriteToggle = async (entry: SelectedEntry) => {
try {
if (entry.type === "directory") {
if (entry.isFavorite) {
await trpc().favorites.removeDirectory.mutate({ id: entry.id });
} else {
await trpc().favorites.addDirectory.mutate({ id: entry.id });
}
} else {
if (entry.isFavorite) {
await trpc().favorites.removeFile.mutate({ id: entry.id });
} else {
await trpc().favorites.addFile.mutate({ id: entry.id });
}
}
return true;
} catch {
// TODO: Error Handling
return false;
}
};

View File

@@ -0,0 +1,3 @@
<div class="flex h-full items-center justify-center p-4">
<p class="text-gray-500">아직 개발 중이에요.</p>
</div>

View File

@@ -1,93 +0,0 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { RowVirtualizer } from "$lib/components/atoms";
import { TopBar } from "$lib/components/molecules";
import { masterKeyStore } from "$lib/stores";
import Directory from "./Directory.svelte";
import File from "./File.svelte";
import { requestFavoriteEntries, requestRemoveFavorite, type FavoriteEntry } from "./service";
import IconSearch from "~icons/material-symbols/search";
let { data } = $props();
let entries: FavoriteEntry[] = $state([]);
let isLoading = $state(true);
onMount(async () => {
const masterKey = $masterKeyStore?.get(1)?.key;
if (masterKey) {
entries = await requestFavoriteEntries(data.favorites, masterKey);
}
isLoading = false;
});
const handleRemove = async (entry: FavoriteEntry) => {
if (await requestRemoveFavorite(entry.type, entry.details.id)) {
entries = entries.filter(
(e) => !(e.type === entry.type && e.details.id === entry.details.id),
);
}
};
const handleClick = (entry: FavoriteEntry) => {
goto(
entry.type === "file"
? `/file/${entry.details.id}?from=favorite`
: `/directory/${entry.details.id}?from=favorite`,
);
};
</script>
<svelte:head>
<title>즐겨찾기</title>
</svelte:head>
<div class="flex h-full flex-col">
<TopBar title="즐겨찾기" showBackButton={false}>
<button
onclick={() => goto("/search?from=favorites")}
class="w-full rounded-full p-1 text-2xl active:bg-black active:bg-opacity-[0.04]"
>
<IconSearch />
</button>
</TopBar>
<div class="flex flex-grow flex-col px-4 pb-4">
{#if entries.length > 0}
<RowVirtualizer
count={entries.length}
getItemKey={(index) => `${entries[index]!.type}-${entries[index]!.details.id}`}
estimateItemHeight={() => 56}
itemGap={4}
>
{#snippet item(index)}
{@const entry = entries[index]!}
{#if entry.type === "directory"}
<Directory
info={entry.details}
onclick={() => handleClick(entry)}
onRemoveClick={() => handleRemove(entry)}
/>
{:else}
<File
info={entry.details}
onclick={() => handleClick(entry)}
onRemoveClick={() => handleRemove(entry)}
/>
{/if}
{/snippet}
</RowVirtualizer>
{:else}
<div class="flex flex-grow items-center justify-center">
<p class="text-gray-500">
{#if isLoading}
즐겨찾기 목록을 불러오고 있어요.
{:else}
즐겨찾기한 항목이 없어요.
{/if}
</p>
</div>
{/if}
</div>
</div>

View File

@@ -1,24 +0,0 @@
<script lang="ts">
import { ActionEntryButton } from "$lib/components/atoms";
import { DirectoryEntryLabel } from "$lib/components/molecules";
import type { SubDirectoryInfo } from "$lib/modules/filesystem";
import IconClose from "~icons/material-symbols/close";
interface Props {
info: SubDirectoryInfo;
onclick: () => void;
onRemoveClick: () => void;
}
let { info, onclick, onRemoveClick }: Props = $props();
</script>
<ActionEntryButton
class="h-14"
{onclick}
actionButtonIcon={IconClose}
onActionButtonClick={onRemoveClick}
>
<DirectoryEntryLabel type="directory" name={info.name} isFavorite />
</ActionEntryButton>

View File

@@ -1,34 +0,0 @@
<script lang="ts">
import { ActionEntryButton } from "$lib/components/atoms";
import { DirectoryEntryLabel } from "$lib/components/molecules";
import { getFileThumbnail } from "$lib/modules/file";
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
import { formatDateTime } from "$lib/utils";
import IconClose from "~icons/material-symbols/close";
interface Props {
info: SummarizedFileInfo;
onclick: () => void;
onRemoveClick: () => void;
}
let { info, onclick, onRemoveClick }: Props = $props();
let thumbnail = $derived(getFileThumbnail(info));
</script>
<ActionEntryButton
class="h-14"
{onclick}
actionButtonIcon={IconClose}
onActionButtonClick={onRemoveClick}
>
<DirectoryEntryLabel
type="file"
thumbnail={$thumbnail}
name={info.name}
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
isFavorite
/>
</ActionEntryButton>

View File

@@ -1,68 +0,0 @@
import {
getDirectoryInfo,
getFileInfo,
type SummarizedFileInfo,
type SubDirectoryInfo,
type LocalDirectoryInfo,
} from "$lib/modules/filesystem";
import { HybridPromise, sortEntries } from "$lib/utils";
import { trpc } from "$trpc/client";
import type { RouterOutputs } from "$trpc/router.server";
export type FavoriteEntry =
| { type: "directory"; name: string; details: SubDirectoryInfo }
| { type: "file"; name: string; details: SummarizedFileInfo };
export const requestFavoriteEntries = async (
favorites: RouterOutputs["favorites"]["get"],
masterKey: CryptoKey,
) => {
const [directories, files] = await HybridPromise.all([
HybridPromise.all(
favorites.directories.map((directory) =>
getDirectoryInfo(directory.id, masterKey, {
serverResponse: { ...directory, isFavorite: true },
}),
),
),
HybridPromise.all(
favorites.files.map((file) =>
getFileInfo(file.id, masterKey, { serverResponse: { ...file, isFavorite: true } }),
),
),
]);
return [
...sortEntries(
directories.map(
(directory): FavoriteEntry => ({
type: "directory",
name: directory.name!,
details: directory as LocalDirectoryInfo,
}),
),
),
...sortEntries(
files.map(
(file): FavoriteEntry => ({
type: "file",
name: file.name!,
details: file as SummarizedFileInfo,
}),
),
),
];
};
export const requestRemoveFavorite = async (type: "file" | "directory", id: number) => {
try {
if (type === "directory") {
await trpc().favorites.removeDirectory.mutate({ id });
} else {
await trpc().favorites.removeFile.mutate({ id });
}
return true;
} catch {
// TODO: Error Handling
return false;
}
};

View File

@@ -5,6 +5,7 @@
import IconStorage from "~icons/material-symbols/storage"; import IconStorage from "~icons/material-symbols/storage";
import IconImage from "~icons/material-symbols/image"; import IconImage from "~icons/material-symbols/image";
import IconLockReset from "~icons/material-symbols/lock-reset";
import IconPassword from "~icons/material-symbols/password"; import IconPassword from "~icons/material-symbols/password";
import IconLogout from "~icons/material-symbols/logout"; import IconLogout from "~icons/material-symbols/logout";
@@ -41,6 +42,13 @@
> >
썸네일 썸네일
</MenuEntryButton> </MenuEntryButton>
<MenuEntryButton
onclick={() => goto("/settings/migration")}
icon={IconLockReset}
iconColor="text-teal-500"
>
암호화 마이그레이션
</MenuEntryButton>
</div> </div>
<div class="space-y-2"> <div class="space-y-2">
<p class="font-semibold">보안</p> <p class="font-semibold">보안</p>

View File

@@ -1,7 +1,8 @@
import { error, text } from "@sveltejs/kit"; import { error, text } from "@sveltejs/kit";
import { Readable } from "stream"; import { Readable } from "stream";
import type { ReadableStream } from "stream/web"; import { ReadableStream } from "stream/web";
import { z } from "zod"; import { z } from "zod";
import { parseContentDigestHeader } from "$lib/modules/http";
import { authorize } from "$lib/server/modules/auth"; import { authorize } from "$lib/server/modules/auth";
import { uploadChunk } from "$lib/server/services/upload"; import { uploadChunk } from "$lib/server/services/upload";
import type { RequestHandler } from "./$types"; import type { RequestHandler } from "./$types";
@@ -12,13 +13,16 @@ export const POST: RequestHandler = async ({ locals, params, request }) => {
const zodRes = z const zodRes = z
.object({ .object({
id: z.uuidv4(), id: z.uuidv4(),
index: z.coerce.number().int().positive(), index: z.coerce.number().int().nonnegative(),
}) })
.safeParse(params); .safeParse(params);
if (!zodRes.success) error(400, "Invalid path parameters"); if (!zodRes.success) error(400, "Invalid path parameters");
const { id: sessionId, index: chunkIndex } = zodRes.data; const { id: sessionId, index: chunkIndex } = zodRes.data;
if (!request.body) { const encContentHash = parseContentDigestHeader(request.headers.get("Content-Digest"));
if (!encContentHash) {
error(400, "Invalid request headers");
} else if (!request.body) {
error(400, "Invalid request body"); error(400, "Invalid request body");
} }
@@ -27,6 +31,7 @@ export const POST: RequestHandler = async ({ locals, params, request }) => {
sessionId, sessionId,
chunkIndex, chunkIndex,
Readable.fromWeb(request.body as ReadableStream), Readable.fromWeb(request.body as ReadableStream),
encContentHash,
); );
return text("Chunk uploaded", { headers: { "Content-Type": "text/plain" } }); return text("Chunk uploaded", { headers: { "Content-Type": "text/plain" } });
}; };

View File

@@ -1 +0,0 @@
export * from "../lib/constants";

Some files were not shown because too many files have changed in this diff Show More