3 Commits

29 changed files with 876 additions and 1346 deletions

View File

@@ -13,7 +13,6 @@ node_modules
/library
/thumbnails
/uploads
/log
# OS
.DS_Store

View File

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

1
.gitignore vendored
View File

@@ -11,7 +11,6 @@ node_modules
/library
/thumbnails
/uploads
/log
# OS
.DS_Store

View File

@@ -9,8 +9,6 @@ services:
volumes:
- ./data/library:/app/data/library
- ./data/thumbnails:/app/data/thumbnails
- ./data/uploads:/app/data/uploads
- ./data/log:/app/data/log
environment:
# ArkVault
- DATABASE_HOST=database
@@ -22,8 +20,6 @@ services:
- SESSION_UPGRADE_CHALLENGE_EXPIRES
- LIBRARY_PATH=/app/data/library
- THUMBNAILS_PATH=/app/data/thumbnails
- UPLOADS_PATH=/app/data/uploads
- LOG_DIR=/app/data/log
# SvelteKit
- ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For}
- XFF_DEPTH=${TRUST_PROXY:-}

View File

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

1386
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,3 @@ export const ENCRYPTION_OVERHEAD = AES_GCM_IV_SIZE + AES_GCM_TAG_SIZE;
export const CHUNK_SIZE = 4 * 1024 * 1024; // 4 MiB
export const ENCRYPTED_CHUNK_SIZE = CHUNK_SIZE + ENCRYPTION_OVERHEAD;
export const MAX_FILE_SIZE = 512 * 1024 * 1024; // 512 MiB
export const MAX_CHUNKS = Math.ceil(MAX_FILE_SIZE / CHUNK_SIZE); // 128 chunks

View File

@@ -168,7 +168,7 @@ const requestFileUpload = limitFunction(
) => {
state.status = "uploading";
await uploadBlob(uploadId, file, dataKey, {
const { encContentHash } = await uploadBlob(uploadId, file, dataKey, {
onProgress(s) {
state.progress = s.progress;
state.rate = s.rate;
@@ -178,6 +178,7 @@ const requestFileUpload = limitFunction(
const { file: fileId } = await trpc().upload.completeFileUpload.mutate({
uploadId,
contentHmac: fileSigned,
encContentHash,
});
if (thumbnailBuffer) {

View File

@@ -12,11 +12,3 @@ export const parseRangeHeader = (value: string | null) => {
export const getContentRangeHeader = (range?: { start: number; end: number; total: number }) => {
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,7 +1,8 @@
import { sha256 } from "@noble/hashes/sha2.js";
import axios from "axios";
import pLimit from "p-limit";
import { ENCRYPTION_OVERHEAD, CHUNK_SIZE } from "$lib/constants";
import { encryptChunk, digestMessage, encodeToBase64 } from "$lib/modules/crypto";
import { encodeToBase64, encryptChunk } from "$lib/modules/crypto";
import { BoundedQueue } from "$lib/utils";
interface UploadStats {
@@ -12,7 +13,6 @@ interface UploadStats {
interface EncryptedChunk {
index: number;
data: ArrayBuffer;
hash: string;
}
const createSpeedMeter = (timeWindow = 3000, minInterval = 200, warmupPeriod = 500) => {
@@ -68,27 +68,18 @@ const createSpeedMeter = (timeWindow = 3000, minInterval = 200, warmupPeriod = 5
};
};
const encryptChunkData = async (
chunk: Blob,
dataKey: CryptoKey,
): Promise<{ data: ArrayBuffer; hash: string }> => {
const encrypted = await encryptChunk(await chunk.arrayBuffer(), dataKey);
const hash = encodeToBase64(await digestMessage(encrypted));
return { data: encrypted, hash };
const encryptChunkData = async (chunk: Blob, dataKey: CryptoKey): Promise<ArrayBuffer> => {
return await encryptChunk(await chunk.arrayBuffer(), dataKey);
};
const uploadEncryptedChunk = async (
uploadId: string,
chunkIndex: number,
encrypted: ArrayBuffer,
hash: string,
onChunkProgress: (chunkIndex: number, loaded: number) => void,
) => {
await axios.post(`/api/upload/${uploadId}/chunks/${chunkIndex + 1}`, encrypted, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Digest": `sha-256=:${hash}:`,
},
headers: { "Content-Type": "application/octet-stream" },
onUploadProgress(e) {
onChunkProgress(chunkIndex, e.loaded ?? 0);
},
@@ -112,6 +103,7 @@ export const uploadBlob = async (
const uploadedByChunk = new Array<number>(totalChunks).fill(0);
const speedMeter = createSpeedMeter(3000, 200);
const hash = sha256.create();
const emit = () => {
if (!onProgress) return;
@@ -136,8 +128,9 @@ export const uploadBlob = async (
try {
for (let i = 0; i < totalChunks; i++) {
const chunk = blob.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
const { data, hash } = await encryptChunkData(chunk, dataKey);
await queue.push({ index: i, data, hash });
const data = await encryptChunkData(chunk, dataKey);
hash.update(new Uint8Array(data));
await queue.push({ index: i, data });
}
} catch (e) {
encryptionError = e instanceof Error ? e : new Error(String(e));
@@ -158,7 +151,7 @@ export const uploadBlob = async (
const task = limit(async () => {
try {
await uploadEncryptedChunk(uploadId, item.index, item.data, item.hash, onChunkProgress);
await uploadEncryptedChunk(uploadId, item.index, item.data, onChunkProgress);
} finally {
// @ts-ignore
item.data = null;
@@ -180,4 +173,5 @@ export const uploadBlob = async (
await Promise.all([encryptionProducer(), uploadConsumer()]);
onProgress?.({ progress: 1, rate: speedMeter() });
return { encContentHash: encodeToBase64(hash.digest()) };
};

View File

@@ -11,7 +11,6 @@ type IntegrityErrorMessages =
| "Directory already favorited"
| "Directory not favorited"
| "File not found"
| "File is not legacy"
| "File not found in category"
| "File already added to category"
| "File already favorited"

View File

@@ -141,17 +141,6 @@ export const getAllFileIds = async (userId: number) => {
return files.map(({ id }) => id);
};
export const getLegacyFiles = async (userId: number, limit: number = 100) => {
const files = await db
.selectFrom("file")
.selectAll()
.where("user_id", "=", userId)
.where("encrypted_content_iv", "is not", null)
.limit(limit)
.execute();
return files.map(toFile);
};
export const getFilesWithoutThumbnail = async (userId: number, limit: number = 100) => {
const files = await db
.selectFrom("file")
@@ -416,51 +405,6 @@ export const unregisterFile = async (userId: number, fileId: number) => {
});
};
export const migrateFileContent = async (
trx: typeof db,
userId: number,
fileId: number,
newPath: string,
dekVersion: Date,
encContentHash: string,
) => {
const file = await trx
.selectFrom("file")
.select(["path", "data_encryption_key_version", "encrypted_content_iv"])
.where("id", "=", fileId)
.where("user_id", "=", userId)
.limit(1)
.forUpdate()
.executeTakeFirst();
if (!file) {
throw new IntegrityError("File not found");
} else if (file.data_encryption_key_version.getTime() !== dekVersion.getTime()) {
throw new IntegrityError("Invalid DEK version");
} else 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 { oldPath: file.path };
};
export const addFileToCategory = async (fileId: number, categoryId: number) => {
await db.transaction().execute(async (trx) => {
try {

View File

@@ -3,7 +3,7 @@ import type { Ciphertext } from "./utils";
export interface UploadSessionTable {
id: string;
type: "file" | "thumbnail" | "migration";
type: "file" | "thumbnail";
user_id: number;
path: string;
bitmap: Buffer;

View File

@@ -26,8 +26,8 @@ interface FileUploadSession extends BaseUploadSession {
encLastModifiedAt: Ciphertext;
}
interface ThumbnailOrMigrationUploadSession extends BaseUploadSession {
type: "thumbnail" | "migration";
interface ThumbnailUploadSession extends BaseUploadSession {
type: "thumbnail";
fileId: number;
dekVersion: Date;
}
@@ -86,8 +86,8 @@ export const createFileUploadSession = async (
});
};
export const createThumbnailOrMigrationUploadSession = async (
params: Omit<ThumbnailOrMigrationUploadSession, "bitmap" | "uploadedChunks">,
export const createThumbnailUploadSession = async (
params: Omit<ThumbnailUploadSession, "bitmap" | "uploadedChunks">,
) => {
await db.transaction().execute(async (trx) => {
const file = await trx
@@ -164,7 +164,7 @@ export const getUploadSession = async (sessionId: string, userId: number) => {
expiresAt: session.expires_at,
fileId: session.file_id!,
dekVersion: session.data_encryption_key_version!,
} satisfies ThumbnailOrMigrationUploadSession;
} satisfies ThumbnailUploadSession;
}
};

View File

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

View File

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

View File

@@ -1,37 +0,0 @@
import { appendFileSync, existsSync, mkdirSync } from "fs";
import { env } from "$env/dynamic/private";
const LOG_DIR = env.LOG_DIR || "log";
const getLogFilePath = () => {
const date = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
return `${LOG_DIR}/arkvault-${date}.log`;
};
const ensureLogDir = () => {
if (!existsSync(LOG_DIR)) {
mkdirSync(LOG_DIR, { recursive: true });
}
};
const formatLogLine = (type: string, data: Record<string, unknown>) => {
const timestamp = new Date().toISOString();
return JSON.stringify({ timestamp, type, ...data });
};
export const demoLogger = {
log: (type: string, data: Record<string, unknown>) => {
const line = formatLogLine(type, data);
// Output to stdout
console.log(line);
// Output to file
try {
ensureLogDir();
appendFileSync(getLogFilePath(), line + "\n", { encoding: "utf-8" });
} catch (e) {
console.error("Failed to write to log file:", e);
}
},
};

View File

@@ -1,10 +1,9 @@
import { error } from "@sveltejs/kit";
import { createHash } from "crypto";
import { createWriteStream } from "fs";
import { open } from "fs/promises";
import { Readable } from "stream";
import { ENCRYPTION_OVERHEAD, ENCRYPTED_CHUNK_SIZE } from "$lib/constants";
import { UploadRepo } from "$lib/server/db";
import { safeRecursiveRm, safeUnlink } from "$lib/server/modules/filesystem";
import { safeUnlink } from "$lib/server/modules/filesystem";
const chunkLocks = new Set<string>();
@@ -14,12 +13,61 @@ const isChunkUploaded = (bitmap: Buffer, chunkIndex: number) => {
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 (
userId: number,
sessionId: string,
chunkIndex: number,
encChunkStream: Readable,
encChunkHash: string,
) => {
const lockKey = `${sessionId}/${chunkIndex}`;
if (chunkLocks.has(lockKey)) {
@@ -28,8 +76,6 @@ export const uploadChunk = async (
chunkLocks.add(lockKey);
}
let filePath;
try {
const session = await UploadRepo.getUploadSession(sessionId, userId);
if (!session) {
@@ -41,39 +87,10 @@ export const uploadChunk = async (
}
const isLastChunk = chunkIndex === session.totalChunks;
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 writeChunkAtOffset(session.path, encChunkStream, chunkIndex, isLastChunk);
await UploadRepo.markChunkAsUploaded(sessionId, chunkIndex);
} catch (e) {
await safeUnlink(filePath);
if (
e instanceof Error &&
(e.message === "Invalid checksum" || e.message === "Invalid chunk size")
) {
if (e instanceof Error && e.message === "Invalid chunk size") {
error(400, "Invalid request body");
}
throw e;
@@ -84,5 +101,5 @@ export const uploadChunk = async (
export const cleanupExpiredUploadSessions = async () => {
const paths = await UploadRepo.cleanupExpiredUploadSessions();
await Promise.all(paths.map(safeRecursiveRm));
await Promise.all(paths.map(safeUnlink));
};

View File

@@ -14,8 +14,8 @@
let { data } = $props();
let email = $state("arkvault-demo@minchan.me");
let password = $state("arkvault-demo");
let email = $state("");
let password = $state("");
let isForceLoginModalOpen = $state(false);

View File

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

View File

@@ -1,82 +0,0 @@
<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 type { MaybeFileInfo } from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import { sortEntries } from "$lib/utils";
import File from "./File.svelte";
import {
getMigrationState,
clearMigrationStates,
requestLegacyFiles,
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 !== "uploaded"),
);
const migrateAllFiles = () => {
files.forEach(({ info }) => {
if (info.exists) {
requestFileMigration(info);
}
});
};
onMount(async () => {
fileInfos = sortEntries(await requestLegacyFiles(data.files, $masterKeyStore?.get(1)?.key!));
});
$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

@@ -1,52 +0,0 @@
<script module lang="ts">
const subtexts = {
queued: "대기 중",
downloading: "다운로드하는 중",
"upload-pending": "업로드를 기다리는 중",
uploaded: "",
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

@@ -1,116 +0,0 @@
import { limitFunction } from "p-limit";
import { SvelteMap } from "svelte/reactivity";
import { CHUNK_SIZE } from "$lib/constants";
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem";
import { uploadBlob } from "$lib/modules/upload";
import { requestFileDownload } from "$lib/services/file";
import { HybridPromise, Scheduler } from "$lib/utils";
import { trpc } from "$trpc/client";
import type { RouterOutputs } from "$trpc/router.server";
export type MigrationStatus =
| "queued"
| "downloading"
| "upload-pending"
| "uploading"
| "uploaded"
| "error";
export interface MigrationState {
status: MigrationStatus;
progress?: number;
rate?: number;
}
const scheduler = new Scheduler();
const states = new SvelteMap<number, MigrationState>();
export const requestLegacyFiles = async (
filesRaw: RouterOutputs["file"]["listLegacy"],
masterKey: CryptoKey,
) => {
const files = await HybridPromise.all(
filesRaw.map((file) => getFileInfo(file.id, masterKey, { serverResponse: file })),
);
return files;
};
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 === "uploaded" || state.status === "error") {
states.delete(id);
}
}
};
const requestFileUpload = limitFunction(
async (
state: MigrationState,
fileId: number,
fileBuffer: ArrayBuffer,
dataKey: CryptoKey,
dataKeyVersion: Date,
) => {
state.status = "uploading";
const { uploadId } = await trpc().upload.startMigrationUpload.mutate({
file: fileId,
chunks: Math.ceil(fileBuffer.byteLength / CHUNK_SIZE),
dekVersion: dataKeyVersion,
});
await uploadBlob(uploadId, new Blob([fileBuffer]), dataKey, {
onProgress(s) {
state.progress = s.progress;
state.rate = s.rate;
},
});
await trpc().upload.completeMigrationUpload.mutate({ uploadId });
state.status = "uploaded";
},
{ 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;
if (!dataKey) {
throw new Error("Data key not available");
}
let fileBuffer: ArrayBuffer | undefined;
await scheduler.schedule(
async () => {
state.status = "downloading";
fileBuffer = await requestFileDownload(fileInfo.id, dataKey.key, true);
return fileBuffer.byteLength;
},
() => requestFileUpload(state, fileInfo.id, fileBuffer!, dataKey.key, dataKey.version),
);
} catch (e) {
state.status = "error";
throw e;
}
};

View File

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

View File

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

View File

@@ -5,7 +5,6 @@ import { ClientRepo, SessionRepo, UserRepo, IntegrityError } from "$lib/server/d
import env from "$lib/server/loadenv";
import { cookieOptions } from "$lib/server/modules/auth";
import { generateChallenge, verifySignature, issueSessionId } from "$lib/server/modules/crypto";
import { demoLogger } from "$lib/server/modules/logger";
import { router, publicProcedure, roleProcedure } from "../init.server";
const authRouter = router({
@@ -25,10 +24,6 @@ const authRouter = router({
const { sessionId, sessionIdSigned } = await issueSessionId(32, env.session.secret);
await SessionRepo.createSession(user.id, sessionId, ctx.locals.ip, ctx.locals.userAgent);
ctx.cookies.set("sessionId", sessionIdSigned, cookieOptions);
if (input.email === "arkvault-demo@minchan.me") {
demoLogger.log("demo:login", { ip: ctx.locals.ip, sessionId });
}
}),
logout: roleProcedure["any"].mutation(async ({ ctx }) => {
@@ -43,8 +38,22 @@ const authRouter = router({
newPassword: z.string().nonempty(),
}),
)
.mutation(() => {
throw new TRPCError({ code: "NOT_IMPLEMENTED" });
.mutation(async ({ ctx, input }) => {
if (input.oldPassword === input.newPassword) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Same passwords" });
} else if (input.newPassword.length < 8) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Too short password" });
}
const user = await UserRepo.getUser(ctx.session.userId);
if (!user) {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Invalid session id" });
} else if (!(await argon2.verify(user.password, input.oldPassword))) {
throw new TRPCError({ code: "FORBIDDEN", message: "Invalid password" });
}
await UserRepo.setUserPassword(ctx.session.userId, await argon2.hash(input.newPassword));
await SessionRepo.deleteAllOtherSessions(ctx.session.userId, ctx.session.sessionId);
}),
upgrade: roleProcedure["notClient"]

View File

@@ -3,7 +3,6 @@ import { z } from "zod";
import { DirectoryIdSchema } from "$lib/schemas";
import { DirectoryRepo, FileRepo, IntegrityError } from "$lib/server/db";
import { safeUnlink } from "$lib/server/modules/filesystem";
import { demoLogger } from "$lib/server/modules/logger";
import { router, roleProcedure } from "../init.server";
const directoryRouter = router({
@@ -135,7 +134,6 @@ const directoryRouter = router({
const files = await DirectoryRepo.unregisterDirectory(ctx.session.userId, input.id);
return {
deletedFiles: files.map((file) => {
demoLogger.log("file:delete", { ip: ctx.locals.ip, fileId: file.id, recursive: true });
safeUnlink(file.path); // Intended
safeUnlink(file.thumbnailPath); // Intended
return file.id;

View File

@@ -2,7 +2,6 @@ import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { FileRepo, MediaRepo, IntegrityError } from "$lib/server/db";
import { safeUnlink } from "$lib/server/modules/filesystem";
import { demoLogger } from "$lib/server/modules/logger";
import { router, roleProcedure } from "../init.server";
const fileRouter = router({
@@ -119,26 +118,6 @@ const fileRouter = router({
}));
}),
listLegacy: roleProcedure["activeClient"].query(async ({ ctx }) => {
const files = await FileRepo.getLegacyFiles(ctx.session.userId);
return files.map((file) => ({
id: file.id,
isLegacy: true,
parent: file.parentId,
mekVersion: file.mekVersion,
dek: file.encDek,
dekVersion: file.dekVersion,
contentType: file.contentType,
name: file.encName.ciphertext,
nameIv: file.encName.iv,
createdAt: file.encCreatedAt?.ciphertext,
createdAtIv: file.encCreatedAt?.iv,
lastModifiedAt: file.encLastModifiedAt.ciphertext,
lastModifiedAtIv: file.encLastModifiedAt.iv,
isFavorite: file.isFavorite,
}));
}),
rename: roleProcedure["activeClient"]
.input(
z.object({
@@ -175,7 +154,6 @@ const fileRouter = router({
.mutation(async ({ ctx, input }) => {
try {
const { path, thumbnailPath } = await FileRepo.unregisterFile(ctx.session.userId, input.id);
demoLogger.log("file:delete", { ip: ctx.locals.ip, fileId: input.id });
safeUnlink(path); // Intended
safeUnlink(thumbnailPath); // Intended
} catch (e) {

View File

@@ -1,28 +1,39 @@
import { TRPCError } from "@trpc/server";
import { createHash } from "crypto";
import { createReadStream, createWriteStream } from "fs";
import { copyFile, mkdir } from "fs/promises";
import { createReadStream } from "fs";
import { mkdir, open } from "fs/promises";
import mime from "mime";
import { dirname } from "path";
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
import { MAX_CHUNKS } from "$lib/constants";
import { DirectoryIdSchema } from "$lib/schemas";
import { FileRepo, MediaRepo, UploadRepo, IntegrityError } from "$lib/server/db";
import db from "$lib/server/db/kysely";
import env from "$lib/server/loadenv";
import { safeRecursiveRm, safeUnlink } from "$lib/server/modules/filesystem";
import { demoLogger } from "$lib/server/modules/logger";
import { safeUnlink } from "$lib/server/modules/filesystem";
import { router, roleProcedure } from "../init.server";
const UPLOADS_EXPIRES = 24 * 3600 * 1000; // 24 hours
const sessionLocks = new Set<string>();
const generateSessionId = async () => {
const reserveUploadPath = async (path: string) => {
await mkdir(dirname(path), { recursive: true });
const file = await open(path, "wx", 0o600);
await file.close();
};
const generateFileUploadSession = async (userId: number) => {
const id = uuidv4();
const path = `${env.uploadsPath}/${id}`;
await mkdir(path, { recursive: true });
const path = `${env.libraryPath}/${userId}/${uuidv4()}`;
await reserveUploadPath(path);
return { id, path };
};
const generateThumbnailUploadSession = async (userId: number) => {
const id = uuidv4();
const path = `${env.thumbnailsPath}/${userId}/${id}`;
await reserveUploadPath(path);
return { id, path };
};
@@ -30,7 +41,7 @@ const uploadRouter = router({
startFileUpload: roleProcedure["activeClient"]
.input(
z.object({
chunks: z.int().positive().max(MAX_CHUNKS),
chunks: z.int().positive(),
parent: DirectoryIdSchema,
mekVersion: z.int().positive(),
dek: z.base64().nonempty(),
@@ -56,7 +67,7 @@ const uploadRouter = router({
throw new TRPCError({ code: "BAD_REQUEST", message: "Invalid DEK version" });
}
const { id, path } = await generateSessionId();
const { id, path } = await generateFileUploadSession(ctx.session.userId);
try {
await UploadRepo.createFileUploadSession({
@@ -78,10 +89,9 @@ const uploadRouter = router({
: null,
encLastModifiedAt: { ciphertext: input.lastModifiedAt, iv: input.lastModifiedAtIv },
});
demoLogger.log("upload:start", { ip: ctx.locals.ip, uploadId: id });
return { uploadId: id };
} catch (e) {
await safeRecursiveRm(path);
await safeUnlink(path);
if (e instanceof IntegrityError) {
if (e.message === "Inactive MEK version") {
@@ -99,6 +109,7 @@ const uploadRouter = router({
z.object({
uploadId: z.uuidv4(),
contentHmac: z.base64().nonempty().optional(),
encContentHash: z.base64().nonempty(),
}),
)
.mutation(async ({ ctx, input }) => {
@@ -109,8 +120,6 @@ const uploadRouter = router({
sessionLocks.add(uploadId);
}
let filePath = "";
try {
const session = await UploadRepo.getUploadSession(uploadId, ctx.session.userId);
if (session?.type !== "file") {
@@ -124,29 +133,24 @@ const uploadRouter = router({
throw new TRPCError({ code: "BAD_REQUEST", message: "Upload not completed" });
}
filePath = `${env.libraryPath}/${ctx.session.userId}/${uuidv4()}`;
await mkdir(dirname(filePath), { recursive: true });
const hashStream = createHash("sha256");
const writeStream = createWriteStream(filePath, { flags: "wx", mode: 0o600 });
for (let i = 1; i <= session.totalChunks; i++) {
for await (const chunk of createReadStream(`${session.path}/${i}`)) {
for await (const chunk of createReadStream(session.path)) {
hashStream.update(chunk);
writeStream.write(chunk);
}
}
await new Promise<void>((resolve, reject) => {
writeStream.end((e: any) => (e ? reject(e) : resolve()));
});
const hash = hashStream.digest("base64");
if (hash !== input.encContentHash) {
await UploadRepo.deleteUploadSession(db, uploadId);
await safeUnlink(session.path);
throw new TRPCError({ code: "CONFLICT", message: "Uploaded file corrupted" });
}
const fileId = await db.transaction().execute(async (trx) => {
const { id: fileId } = await FileRepo.registerFile(trx, {
...session,
userId: ctx.session.userId,
path: filePath,
path: session.path,
contentHmac: input.contentHmac ?? null,
encContentHash: hash,
encContentIv: null,
@@ -155,12 +159,7 @@ const uploadRouter = router({
return fileId;
});
await safeRecursiveRm(session.path);
demoLogger.log("upload:complete", { ip: ctx.locals.ip, uploadId, fileId });
return { file: fileId };
} catch (e) {
await safeUnlink(filePath);
throw e;
} finally {
sessionLocks.delete(uploadId);
}
@@ -174,10 +173,10 @@ const uploadRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
const { id, path } = await generateSessionId();
const { id, path } = await generateThumbnailUploadSession(ctx.session.userId);
try {
await UploadRepo.createThumbnailOrMigrationUploadSession({
await UploadRepo.createThumbnailUploadSession({
id,
type: "thumbnail",
userId: ctx.session.userId,
@@ -187,10 +186,9 @@ const uploadRouter = router({
fileId: input.file,
dekVersion: input.dekVersion,
});
demoLogger.log("thumbnail:start", { ip: ctx.locals.ip, uploadId: id });
return { uploadId: id };
} catch (e) {
await safeRecursiveRm(path);
await safeUnlink(path);
if (e instanceof IntegrityError) {
if (e.message === "File not found") {
@@ -217,8 +215,6 @@ const uploadRouter = router({
sessionLocks.add(uploadId);
}
let thumbnailPath = "";
try {
const session = await UploadRepo.getUploadSession(uploadId, ctx.session.userId);
if (session?.type !== "thumbnail") {
@@ -227,31 +223,20 @@ const uploadRouter = router({
throw new TRPCError({ code: "BAD_REQUEST", message: "Upload not completed" });
}
thumbnailPath = `${env.thumbnailsPath}/${ctx.session.userId}/${uploadId}`;
await mkdir(dirname(thumbnailPath), { recursive: true });
await copyFile(`${session.path}/1`, thumbnailPath);
const oldThumbnailPath = await db.transaction().execute(async (trx) => {
const oldPath = await MediaRepo.updateFileThumbnail(
trx,
ctx.session.userId,
session.fileId,
session.dekVersion,
thumbnailPath,
session.path,
null,
);
await UploadRepo.deleteUploadSession(trx, uploadId);
return oldPath;
});
demoLogger.log("thumbnail:complete", {
ip: ctx.locals.ip,
uploadId,
fileId: session.fileId,
});
await Promise.all([safeUnlink(oldThumbnailPath), safeRecursiveRm(session.path)]);
await safeUnlink(oldThumbnailPath);
} catch (e) {
await safeUnlink(thumbnailPath);
if (e instanceof IntegrityError && e.message === "Invalid DEK version") {
// DEK rotated after this upload started
throw new TRPCError({ code: "CONFLICT", message: e.message });
@@ -261,112 +246,6 @@ const uploadRouter = router({
sessionLocks.delete(uploadId);
}
}),
startMigrationUpload: roleProcedure["activeClient"]
.input(
z.object({
file: z.int().positive(),
chunks: z.int().positive(),
dekVersion: z.date(),
}),
)
.mutation(async ({ ctx, input }) => {
const { id, path } = await generateSessionId();
try {
await UploadRepo.createThumbnailOrMigrationUploadSession({
id,
type: "migration",
userId: ctx.session.userId,
path,
totalChunks: input.chunks,
expiresAt: new Date(Date.now() + UPLOADS_EXPIRES),
fileId: input.file,
dekVersion: input.dekVersion,
});
return { uploadId: id };
} catch (e) {
await safeRecursiveRm(path);
if (e instanceof IntegrityError) {
if (e.message === "File not found") {
throw new TRPCError({ code: "NOT_FOUND", message: "Invalid file id" });
} else if (e.message === "File is not legacy") {
throw new TRPCError({ code: "BAD_REQUEST", message: e.message });
}
}
throw e;
}
}),
completeMigrationUpload: roleProcedure["activeClient"]
.input(
z.object({
uploadId: z.uuidv4(),
}),
)
.mutation(async ({ ctx, input }) => {
const { uploadId } = input;
if (sessionLocks.has(uploadId)) {
throw new TRPCError({ code: "CONFLICT", message: "Completion already in progress" });
} else {
sessionLocks.add(uploadId);
}
let filePath = "";
try {
const session = await UploadRepo.getUploadSession(uploadId, ctx.session.userId);
if (session?.type !== "migration") {
throw new TRPCError({ code: "NOT_FOUND", message: "Invalid upload id" });
} else if (session.uploadedChunks < session.totalChunks) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Upload not completed" });
}
filePath = `${env.libraryPath}/${ctx.session.userId}/${uuidv4()}`;
await mkdir(dirname(filePath), { recursive: true });
const hashStream = createHash("sha256");
const writeStream = createWriteStream(filePath, { flags: "wx", mode: 0o600 });
for (let i = 1; i <= session.totalChunks; i++) {
for await (const chunk of createReadStream(`${session.path}/${i}`)) {
hashStream.update(chunk);
writeStream.write(chunk);
}
}
await new Promise<void>((resolve, reject) => {
writeStream.end((e: any) => (e ? reject(e) : resolve()));
});
const hash = hashStream.digest("base64");
const oldPath = await db.transaction().execute(async (trx) => {
const { oldPath } = await FileRepo.migrateFileContent(
trx,
ctx.session.userId,
session.fileId,
filePath,
session.dekVersion!,
hash,
);
await UploadRepo.deleteUploadSession(trx, uploadId);
return oldPath;
});
await Promise.all([safeUnlink(oldPath), safeRecursiveRm(session.path)]);
} catch (e) {
await safeUnlink(filePath);
if (e instanceof IntegrityError && e.message === "File is not legacy") {
// File migrated after this upload started
throw new TRPCError({ code: "CONFLICT", message: e.message });
}
throw e;
} finally {
sessionLocks.delete(uploadId);
}
}),
});
export default uploadRouter;