mirror of
https://github.com/kmc7468/arkvault.git
synced 2026-02-04 16:16:55 +00:00
Compare commits
139 Commits
v0.3.0
...
d98be331ad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d98be331ad | ||
|
|
841c57e8fc | ||
|
|
182ec18a2b | ||
|
|
7b666cf692 | ||
|
|
26323c2d4d | ||
|
|
e4413ddbf6 | ||
|
|
b5522a4c6d | ||
|
|
1e57941f4c | ||
|
|
409ae09f4f | ||
|
|
cdb652cacf | ||
|
|
15b6a53710 | ||
|
|
174305ca1b | ||
|
|
0d13d3baef | ||
|
|
576d41da7f | ||
|
|
9eb67d5877 | ||
|
|
a9da8435cb | ||
|
|
3e98e3d591 | ||
|
|
27a46bcc2e | ||
|
|
a1f30ee154 | ||
|
|
6d02178c69 | ||
|
|
ed21a9cd31 | ||
|
|
b7a7536461 | ||
|
|
3eb7411438 | ||
|
|
c9d4b10356 | ||
|
|
d94d14cf83 | ||
|
|
3fc29cf8db | ||
|
|
b92b4a0b1b | ||
|
|
6d95059450 | ||
|
|
a08ddf2c09 | ||
|
|
208252f6b2 | ||
|
|
aa4a1a74ea | ||
|
|
640e12d2c3 | ||
|
|
7779910949 | ||
|
|
328baba395 | ||
|
|
4e91cdad95 | ||
|
|
9f53874d1d | ||
|
|
af20f6ec4e | ||
|
|
301216915e | ||
|
|
393bba45db | ||
|
|
3ebfcdaa7d | ||
|
|
89921ef1df | ||
|
|
4679b1d6bd | ||
|
|
0d35f0b607 | ||
|
|
1304cc3868 | ||
|
|
823ad7f59a | ||
|
|
01732037a6 | ||
|
|
381edce0c5 | ||
|
|
eda5ff7570 | ||
|
|
fa7ba451c3 | ||
|
|
eac81abe5a | ||
|
|
c47885d571 | ||
|
|
fa8c163347 | ||
|
|
6e14b45656 | ||
|
|
983cb2cc57 | ||
|
|
18660844e6 | ||
|
|
69b31ad9af | ||
|
|
2c7d085e6d | ||
|
|
a42ec28176 | ||
|
|
9b1e27c20b | ||
|
|
5d9042d149 | ||
|
|
40a87aa81f | ||
|
|
d3de06a7f9 | ||
|
|
c092545b58 | ||
|
|
e4cce6b8a0 | ||
|
|
8fefbc1bcb | ||
|
|
bcb969dc22 | ||
|
|
8975a0200d | ||
|
|
781642fed6 | ||
|
|
3a637b14b4 | ||
|
|
9e67920968 | ||
|
|
eaf2d7f202 | ||
|
|
c236242136 | ||
|
|
36d082e0f8 | ||
|
|
7b88679ff0 | ||
|
|
c9331ae5b7 | ||
|
|
13bac59824 | ||
|
|
2a5200fe9d | ||
|
|
451dd3c129 | ||
|
|
2105b66cc3 | ||
|
|
ad0f3ff950 | ||
|
|
36006a9b72 | ||
|
|
0a5ef2b970 | ||
|
|
23c82fee12 | ||
|
|
49f9c1e21f | ||
|
|
489f5daba8 | ||
|
|
43f0245ff9 | ||
|
|
183ce583b0 | ||
|
|
d2aca276ac | ||
|
|
b6edc2a8bc | ||
|
|
acb6e1ac6e | ||
|
|
7230810f3a | ||
|
|
df9831da8e | ||
|
|
cf51f2618e | ||
|
|
0f2c5f8b33 | ||
|
|
32ecf46341 | ||
|
|
c709a79266 | ||
|
|
0998d0662e | ||
|
|
7dba1cf4c6 | ||
|
|
cdbe5594f9 | ||
|
|
38a1c8d7e0 | ||
|
|
fea9cd729c | ||
|
|
1c09d93b41 | ||
|
|
a01137bbf9 | ||
|
|
3ee98166c6 | ||
|
|
fd10f13a4d | ||
|
|
ca67f5a81c | ||
|
|
b8b87877d2 | ||
|
|
606609d468 | ||
|
|
b48b9719ca | ||
|
|
a1fbea3e45 | ||
|
|
dd0a887576 | ||
|
|
f34764ffe0 | ||
|
|
8f8bad6d10 | ||
|
|
368868910d | ||
|
|
4c0d668cc1 | ||
|
|
a2402f37a0 | ||
|
|
dbe2262d07 | ||
|
|
88d4757cf7 | ||
|
|
efe2782db0 | ||
|
|
2993593770 | ||
|
|
f66421a5dc | ||
|
|
2a2d01b50e | ||
|
|
698d2455ff | ||
|
|
d0f1e06525 | ||
|
|
9419e5e2b4 | ||
|
|
eed60bb4a1 | ||
|
|
803110606b | ||
|
|
ce329891ae | ||
|
|
a3c169f706 | ||
|
|
63eacbb1b3 | ||
|
|
3da3be3b73 | ||
|
|
0002b4e5f2 | ||
|
|
6018b03523 | ||
|
|
5517d9f811 | ||
|
|
53bc426487 | ||
|
|
10eba78444 | ||
|
|
2af3caf3b9 | ||
|
|
2b303f9197 | ||
|
|
e1262506c4 |
@@ -1,5 +1,6 @@
|
|||||||
.git
|
.git
|
||||||
node_modules
|
node_modules
|
||||||
|
/Makefile
|
||||||
|
|
||||||
# Output
|
# Output
|
||||||
.output
|
.output
|
||||||
@@ -10,13 +11,15 @@ node_modules
|
|||||||
/build
|
/build
|
||||||
/data
|
/data
|
||||||
/library
|
/library
|
||||||
|
/thumbnails
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
# VSCode
|
# Editors
|
||||||
/.vscode
|
/.vscode
|
||||||
|
/.idea
|
||||||
|
|
||||||
# Env
|
# Env
|
||||||
.env
|
.env
|
||||||
@@ -27,6 +30,3 @@ Thumbs.db
|
|||||||
# Vite
|
# Vite
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
vite.config.ts.timestamp-*
|
vite.config.ts.timestamp-*
|
||||||
|
|
||||||
# SQLite
|
|
||||||
*.db
|
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
# Required environment variables
|
# Required environment variables
|
||||||
|
DATABASE_PASSWORD=
|
||||||
SESSION_SECRET=
|
SESSION_SECRET=
|
||||||
|
|
||||||
# Optional environment variables
|
# Optional environment variables
|
||||||
DATABASE_URL=
|
DATABASE_HOST=
|
||||||
|
DATABASE_PORT=
|
||||||
|
DATABASE_USER=
|
||||||
|
DATABASE_NAME=
|
||||||
SESSION_EXPIRES=
|
SESSION_EXPIRES=
|
||||||
USER_CLIENT_CHALLENGE_EXPIRES=
|
USER_CLIENT_CHALLENGE_EXPIRES=
|
||||||
SESSION_UPGRADE_CHALLENGE_EXPIRES=
|
SESSION_UPGRADE_CHALLENGE_EXPIRES=
|
||||||
LIBRARY_PATH=
|
LIBRARY_PATH=
|
||||||
|
THUMBNAILS_PATH=
|
||||||
|
|||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -9,13 +9,15 @@ node_modules
|
|||||||
/build
|
/build
|
||||||
/data
|
/data
|
||||||
/library
|
/library
|
||||||
|
/thumbnails
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
# VSCode
|
# Editors
|
||||||
/.vscode
|
/.vscode
|
||||||
|
/.idea
|
||||||
|
|
||||||
# Env
|
# Env
|
||||||
.env
|
.env
|
||||||
@@ -26,6 +28,3 @@ Thumbs.db
|
|||||||
# Vite
|
# Vite
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
vite.config.ts.timestamp-*
|
vite.config.ts.timestamp-*
|
||||||
|
|
||||||
# SQLite
|
|
||||||
*.db
|
|
||||||
|
|||||||
@@ -3,8 +3,5 @@ package-lock.json
|
|||||||
pnpm-lock.yaml
|
pnpm-lock.yaml
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
# Output
|
|
||||||
/drizzle
|
|
||||||
|
|
||||||
# Documents
|
# Documents
|
||||||
*.md
|
*.md
|
||||||
|
|||||||
11
Dockerfile
11
Dockerfile
@@ -2,7 +2,7 @@
|
|||||||
FROM node:22-alpine AS base
|
FROM node:22-alpine AS base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
RUN npm install -g pnpm@9
|
RUN npm install -g pnpm@10
|
||||||
COPY pnpm-lock.yaml .
|
COPY pnpm-lock.yaml .
|
||||||
|
|
||||||
# Build Stage
|
# Build Stage
|
||||||
@@ -10,10 +10,9 @@ FROM base AS build
|
|||||||
RUN pnpm fetch
|
RUN pnpm fetch
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN pnpm install --offline
|
RUN pnpm install --offline && \
|
||||||
RUN pnpm build
|
pnpm build && \
|
||||||
|
sed -i "s/http\.createServer()/http.createServer({ requestTimeout: 0 })/g" ./build/index.js
|
||||||
RUN sed -i "s/http\.createServer()/http.createServer({ requestTimeout: 0 })/g" ./build/index.js
|
|
||||||
|
|
||||||
# Deploy Stage
|
# Deploy Stage
|
||||||
FROM base
|
FROM base
|
||||||
@@ -23,9 +22,7 @@ COPY package.json .
|
|||||||
RUN pnpm install --offline --prod
|
RUN pnpm install --offline --prod
|
||||||
|
|
||||||
COPY --from=build /app/build ./build
|
COPY --from=build /app/build ./build
|
||||||
COPY drizzle ./drizzle
|
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
ENV BODY_SIZE_LIMIT=Infinity
|
ENV BODY_SIZE_LIMIT=Infinity
|
||||||
|
|
||||||
CMD ["node", "./build/index.js"]
|
CMD ["node", "./build/index.js"]
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ vim .env # 아래를 참고하여 환경 변수를 설정해 주세요.
|
|||||||
docker compose up --build -d
|
docker compose up --build -d
|
||||||
```
|
```
|
||||||
|
|
||||||
모든 데이터는 `./data` 디렉터리에 저장될 거예요.
|
모든 데이터는 `./data` 디렉터리에 아래에 저장될 거예요.
|
||||||
|
|
||||||
### Environment Variables
|
### Environment Variables
|
||||||
|
|
||||||
@@ -31,7 +31,8 @@ docker compose up --build -d
|
|||||||
|
|
||||||
|이름|필수|기본값|설명|
|
|이름|필수|기본값|설명|
|
||||||
|:-|:-:|:-:|:-|
|
|:-|:-:|:-:|:-|
|
||||||
|`SESSION_SECRET`|Y||Session ID의 서명을 위해 사용돼요. 안전한 값으로 설정해 주세요.|
|
|`DATABASE_PASSWORD`|Y||데이터베이스에 접근하기 위해 필요한 비밀번호예요. 안전한 값으로 설정해 주세요.|
|
||||||
|
|`SESSION_SECRET`|Y||Session ID의 서명에 사용되는 비밀번호예요. 안전한 값으로 설정해 주세요.|
|
||||||
|`SESSION_EXPIRES`||`14d`|Session의 유효 시간이에요. Session은 마지막으로 사용된 후 설정된 유효 시간이 지나면 자동으로 삭제돼요.|
|
|`SESSION_EXPIRES`||`14d`|Session의 유효 시간이에요. Session은 마지막으로 사용된 후 설정된 유효 시간이 지나면 자동으로 삭제돼요.|
|
||||||
|`USER_CLIENT_CHALLENGE_EXPIRES`||`5m`|암호 키를 서버에 처음 등록할 때 사용되는 챌린지의 유효 시간이에요.|
|
|`USER_CLIENT_CHALLENGE_EXPIRES`||`5m`|암호 키를 서버에 처음 등록할 때 사용되는 챌린지의 유효 시간이에요.|
|
||||||
|`SESSION_UPGRADE_CHALLENGE_EXPIRES`||`5m`|암호 키와 함께 로그인할 때 사용되는 챌린지의 유효 시간이에요.|
|
|`SESSION_UPGRADE_CHALLENGE_EXPIRES`||`5m`|암호 키와 함께 로그인할 때 사용되는 챌린지의 유효 시간이에요.|
|
||||||
|
|||||||
15
docker-compose.dev.yaml
Normal file
15
docker-compose.dev.yaml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
services:
|
||||||
|
database:
|
||||||
|
image: postgres:17
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
- database:/var/lib/postgresql/data
|
||||||
|
environment:
|
||||||
|
- POSTGRES_USER=${DATABASE_USER:-}
|
||||||
|
- POSTGRES_PASSWORD=${DATABASE_PASSWORD:?} # Required
|
||||||
|
- POSTGRES_DB=${DATABASE_NAME:-}
|
||||||
|
ports:
|
||||||
|
- ${DATABASE_PORT:-5432}:5432
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
database:
|
||||||
@@ -2,20 +2,42 @@ services:
|
|||||||
server:
|
server:
|
||||||
build: .
|
build: .
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
database:
|
||||||
|
condition: service_healthy
|
||||||
user: ${CONTAINER_UID:-0}:${CONTAINER_GID:-0}
|
user: ${CONTAINER_UID:-0}:${CONTAINER_GID:-0}
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/app/data
|
- ./data/library:/app/data/library
|
||||||
|
- ./data/thumbnails:/app/data/thumbnails
|
||||||
environment:
|
environment:
|
||||||
# ArkVault
|
# ArkVault
|
||||||
- DATABASE_URL=/app/data/database.sqlite
|
- DATABASE_HOST=database
|
||||||
|
- DATABASE_USER=arkvault
|
||||||
|
- DATABASE_PASSWORD=${DATABASE_PASSWORD:?} # Required
|
||||||
- SESSION_SECRET=${SESSION_SECRET:?} # Required
|
- SESSION_SECRET=${SESSION_SECRET:?} # Required
|
||||||
- SESSION_EXPIRES
|
- SESSION_EXPIRES
|
||||||
- USER_CLIENT_CHALLENGE_EXPIRES
|
- USER_CLIENT_CHALLENGE_EXPIRES
|
||||||
- SESSION_UPGRADE_CHALLENGE_EXPIRES
|
- SESSION_UPGRADE_CHALLENGE_EXPIRES
|
||||||
- LIBRARY_PATH=/app/data/library
|
- LIBRARY_PATH=/app/data/library
|
||||||
|
- THUMBNAILS_PATH=/app/data/thumbnails
|
||||||
# SvelteKit
|
# SvelteKit
|
||||||
- ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For}
|
- ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For}
|
||||||
- XFF_DEPTH=${TRUST_PROXY:-}
|
- XFF_DEPTH=${TRUST_PROXY:-}
|
||||||
- NODE_ENV=${NODE_ENV:-production}
|
- NODE_ENV=${NODE_ENV:-production}
|
||||||
ports:
|
ports:
|
||||||
- ${PORT:-80}:3000
|
- ${PORT:-80}:3000
|
||||||
|
|
||||||
|
database:
|
||||||
|
image: postgres:17-alpine
|
||||||
|
restart: unless-stopped
|
||||||
|
user: ${CONTAINER_UID:-0}:${CONTAINER_GID:-0}
|
||||||
|
volumes:
|
||||||
|
- ./data/database:/var/lib/postgresql/data
|
||||||
|
environment:
|
||||||
|
- POSTGRES_USER=arkvault
|
||||||
|
- POSTGRES_PASSWORD=${DATABASE_PASSWORD:?}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
import { defineConfig } from "drizzle-kit";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
schema: "./src/lib/server/db/schema",
|
|
||||||
|
|
||||||
dbCredentials: {
|
|
||||||
url: process.env.DATABASE_URL || "local.db",
|
|
||||||
},
|
|
||||||
|
|
||||||
verbose: true,
|
|
||||||
strict: true,
|
|
||||||
dialect: "sqlite",
|
|
||||||
});
|
|
||||||
@@ -1,175 +0,0 @@
|
|||||||
CREATE TABLE `client` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`encryption_public_key` text NOT NULL,
|
|
||||||
`signature_public_key` text NOT NULL
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `user_client` (
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`client_id` integer NOT NULL,
|
|
||||||
`state` text DEFAULT 'challenging' NOT NULL,
|
|
||||||
PRIMARY KEY(`client_id`, `user_id`),
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`client_id`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `user_client_challenge` (
|
|
||||||
`id` integer PRIMARY KEY NOT NULL,
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`client_id` integer NOT NULL,
|
|
||||||
`answer` text NOT NULL,
|
|
||||||
`allowed_ip` text NOT NULL,
|
|
||||||
`expires_at` integer NOT NULL,
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`client_id`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`client_id`) REFERENCES `user_client`(`user_id`,`client_id`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `directory` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`parent_id` integer,
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`master_encryption_key_version` integer NOT NULL,
|
|
||||||
`encrypted_data_encryption_key` text NOT NULL,
|
|
||||||
`data_encryption_key_version` integer NOT NULL,
|
|
||||||
`encrypted_name` text NOT NULL,
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`parent_id`) REFERENCES `directory`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`master_encryption_key_version`) REFERENCES `master_encryption_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `directory_log` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`directory_id` integer NOT NULL,
|
|
||||||
`timestamp` integer NOT NULL,
|
|
||||||
`action` text NOT NULL,
|
|
||||||
`new_name` text,
|
|
||||||
FOREIGN KEY (`directory_id`) REFERENCES `directory`(`id`) ON UPDATE no action ON DELETE cascade
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `file` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`parent_id` integer,
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`path` text NOT NULL,
|
|
||||||
`master_encryption_key_version` integer NOT NULL,
|
|
||||||
`encrypted_data_encryption_key` text NOT NULL,
|
|
||||||
`data_encryption_key_version` integer NOT NULL,
|
|
||||||
`hmac_secret_key_version` integer,
|
|
||||||
`content_hmac` text,
|
|
||||||
`content_type` text NOT NULL,
|
|
||||||
`encrypted_content_iv` text NOT NULL,
|
|
||||||
`encrypted_name` text NOT NULL,
|
|
||||||
FOREIGN KEY (`parent_id`) REFERENCES `directory`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`master_encryption_key_version`) REFERENCES `master_encryption_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`hmac_secret_key_version`) REFERENCES `hmac_secret_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `file_log` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`file_id` integer NOT NULL,
|
|
||||||
`timestamp` integer NOT NULL,
|
|
||||||
`action` text NOT NULL,
|
|
||||||
`new_name` text,
|
|
||||||
FOREIGN KEY (`file_id`) REFERENCES `file`(`id`) ON UPDATE no action ON DELETE cascade
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `hmac_secret_key` (
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`version` integer NOT NULL,
|
|
||||||
`state` text NOT NULL,
|
|
||||||
`master_encryption_key_version` integer NOT NULL,
|
|
||||||
`encrypted_key` text NOT NULL,
|
|
||||||
PRIMARY KEY(`user_id`, `version`),
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`master_encryption_key_version`) REFERENCES `master_encryption_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `hmac_secret_key_log` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`hmac_secret_key_version` integer NOT NULL,
|
|
||||||
`timestamp` integer NOT NULL,
|
|
||||||
`action` text NOT NULL,
|
|
||||||
`action_by` integer,
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`action_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`hmac_secret_key_version`) REFERENCES `hmac_secret_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `client_master_encryption_key` (
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`client_id` integer NOT NULL,
|
|
||||||
`version` integer NOT NULL,
|
|
||||||
`encrypted_key` text NOT NULL,
|
|
||||||
`encrypted_key_signature` text NOT NULL,
|
|
||||||
PRIMARY KEY(`client_id`, `user_id`, `version`),
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`client_id`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`version`) REFERENCES `master_encryption_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `master_encryption_key` (
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`version` integer NOT NULL,
|
|
||||||
`state` text NOT NULL,
|
|
||||||
`retired_at` integer,
|
|
||||||
PRIMARY KEY(`user_id`, `version`),
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `master_encryption_key_log` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`master_encryption_key_version` integer NOT NULL,
|
|
||||||
`timestamp` integer NOT NULL,
|
|
||||||
`action` text NOT NULL,
|
|
||||||
`action_by` integer,
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`action_by`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`user_id`,`master_encryption_key_version`) REFERENCES `master_encryption_key`(`user_id`,`version`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `session` (
|
|
||||||
`id` text PRIMARY KEY NOT NULL,
|
|
||||||
`user_id` integer NOT NULL,
|
|
||||||
`client_id` integer,
|
|
||||||
`created_at` integer NOT NULL,
|
|
||||||
`last_used_at` integer NOT NULL,
|
|
||||||
`last_used_by_ip` text,
|
|
||||||
`last_used_by_user_agent` text,
|
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`client_id`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `session_upgrade_challenge` (
|
|
||||||
`id` integer PRIMARY KEY NOT NULL,
|
|
||||||
`session_id` text NOT NULL,
|
|
||||||
`client_id` integer NOT NULL,
|
|
||||||
`answer` text NOT NULL,
|
|
||||||
`allowed_ip` text NOT NULL,
|
|
||||||
`expires_at` integer NOT NULL,
|
|
||||||
FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`client_id`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `user` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`email` text NOT NULL,
|
|
||||||
`password` text NOT NULL,
|
|
||||||
`nickname` text NOT NULL
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `client_encryption_public_key_unique` ON `client` (`encryption_public_key`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `client_signature_public_key_unique` ON `client` (`signature_public_key`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `client_encryption_public_key_signature_public_key_unique` ON `client` (`encryption_public_key`,`signature_public_key`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `user_client_challenge_answer_unique` ON `user_client_challenge` (`answer`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `directory_encrypted_data_encryption_key_unique` ON `directory` (`encrypted_data_encryption_key`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `file_path_unique` ON `file` (`path`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `file_encrypted_data_encryption_key_unique` ON `file` (`encrypted_data_encryption_key`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `hmac_secret_key_encrypted_key_unique` ON `hmac_secret_key` (`encrypted_key`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `session_user_id_client_id_unique` ON `session` (`user_id`,`client_id`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `session_upgrade_challenge_session_id_unique` ON `session_upgrade_challenge` (`session_id`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `session_upgrade_challenge_answer_unique` ON `session_upgrade_challenge` (`answer`);--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE `file` ADD `encrypted_created_at` text;--> statement-breakpoint
|
|
||||||
ALTER TABLE `file` ADD `encrypted_last_modified_at` text NOT NULL;
|
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"version": "7",
|
|
||||||
"dialect": "sqlite",
|
|
||||||
"entries": [
|
|
||||||
{
|
|
||||||
"idx": 0,
|
|
||||||
"version": "6",
|
|
||||||
"when": 1736704436996,
|
|
||||||
"tag": "0000_unknown_stark_industries",
|
|
||||||
"breakpoints": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idx": 1,
|
|
||||||
"version": "6",
|
|
||||||
"when": 1736720831242,
|
|
||||||
"tag": "0001_blushing_alice",
|
|
||||||
"breakpoints": true
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,24 @@
|
|||||||
import prettier from "eslint-config-prettier";
|
|
||||||
import js from "@eslint/js";
|
|
||||||
import { includeIgnoreFile } from "@eslint/compat";
|
import { includeIgnoreFile } from "@eslint/compat";
|
||||||
|
import js from "@eslint/js";
|
||||||
|
import { defineConfig } from "eslint/config";
|
||||||
|
import prettier from "eslint-config-prettier";
|
||||||
import svelte from "eslint-plugin-svelte";
|
import svelte from "eslint-plugin-svelte";
|
||||||
import tailwind from "eslint-plugin-tailwindcss";
|
import tailwind from "eslint-plugin-tailwindcss";
|
||||||
import globals from "globals";
|
import globals from "globals";
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import ts from "typescript-eslint";
|
import ts from "typescript-eslint";
|
||||||
|
import { fileURLToPath } from "url";
|
||||||
|
import svelteConfig from "./svelte.config.js";
|
||||||
|
|
||||||
const gitignorePath = fileURLToPath(new URL("./.gitignore", import.meta.url));
|
const gitignorePath = fileURLToPath(new URL("./.gitignore", import.meta.url));
|
||||||
|
|
||||||
export default ts.config(
|
export default defineConfig(
|
||||||
includeIgnoreFile(gitignorePath),
|
includeIgnoreFile(gitignorePath),
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
...ts.configs.recommended,
|
...ts.configs.recommended,
|
||||||
...svelte.configs["flat/recommended"],
|
...svelte.configs.recommended,
|
||||||
...tailwind.configs["flat/recommended"],
|
...tailwind.configs["flat/recommended"],
|
||||||
prettier,
|
prettier,
|
||||||
...svelte.configs["flat/prettier"],
|
...svelte.configs.prettier,
|
||||||
{
|
{
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
globals: {
|
globals: {
|
||||||
@@ -23,13 +26,18 @@ export default ts.config(
|
|||||||
...globals.node,
|
...globals.node,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
rules: {
|
||||||
|
"no-undef": "off",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
files: ["**/*.svelte"],
|
files: ["**/*.svelte", "**/*.svelte.ts", "**/*.svelte.js"],
|
||||||
|
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
parserOptions: {
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
extraFileExtensions: [".svelte"],
|
||||||
parser: ts.parser,
|
parser: ts.parser,
|
||||||
|
svelteConfig,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
18
kysely.config.ts
Normal file
18
kysely.config.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig } from "kysely-ctl";
|
||||||
|
import { Pool } from "pg";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
dialect: "pg",
|
||||||
|
dialectConfig: {
|
||||||
|
pool: new Pool({
|
||||||
|
host: process.env.DATABASE_HOST,
|
||||||
|
port: process.env.DATABASE_PORT ? parseInt(process.env.DATABASE_PORT) : undefined,
|
||||||
|
user: process.env.DATABASE_USER,
|
||||||
|
password: process.env.DATABASE_PASSWORD,
|
||||||
|
database: process.env.DATABASE_NAME,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
migrations: {
|
||||||
|
migrationFolder: "./src/lib/server/db/migrations",
|
||||||
|
},
|
||||||
|
});
|
||||||
86
package.json
86
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "arkvault",
|
"name": "arkvault",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.2.0",
|
"version": "0.6.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
@@ -11,58 +11,62 @@
|
|||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"lint": "prettier --check . && eslint .",
|
"lint": "prettier --check . && eslint .",
|
||||||
"db:push": "drizzle-kit push",
|
"db:up": "docker compose -f docker-compose.dev.yaml -p arkvault-dev up -d",
|
||||||
"db:generate": "drizzle-kit generate",
|
"db:down": "docker compose -f docker-compose.dev.yaml -p arkvault-dev down",
|
||||||
"db:migrate": "drizzle-kit migrate",
|
"db:migrate": "kysely migrate"
|
||||||
"db:studio": "drizzle-kit studio"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/compat": "^1.2.4",
|
"@eslint/compat": "^2.0.0",
|
||||||
"@iconify-json/material-symbols": "^1.2.12",
|
"@iconify-json/material-symbols": "^1.2.50",
|
||||||
"@sveltejs/adapter-node": "^5.2.11",
|
"@sveltejs/adapter-node": "^5.4.0",
|
||||||
"@sveltejs/kit": "^2.15.2",
|
"@sveltejs/kit": "^2.49.2",
|
||||||
"@sveltejs/vite-plugin-svelte": "^4.0.4",
|
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
||||||
"@types/better-sqlite3": "^7.6.12",
|
"@tanstack/svelte-virtual": "^3.13.13",
|
||||||
|
"@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.7",
|
"@types/node-schedule": "^2.1.8",
|
||||||
"autoprefixer": "^10.4.20",
|
"@types/pg": "^8.16.0",
|
||||||
"axios": "^1.7.9",
|
"autoprefixer": "^10.4.23",
|
||||||
"dexie": "^4.0.10",
|
"axios": "^1.13.2",
|
||||||
"drizzle-kit": "^0.22.8",
|
"dexie": "^4.2.1",
|
||||||
"eslint": "^9.17.0",
|
"eslint": "^9.39.2",
|
||||||
"eslint-config-prettier": "^9.1.0",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-svelte": "^2.46.1",
|
"eslint-plugin-svelte": "^3.13.1",
|
||||||
"eslint-plugin-tailwindcss": "^3.17.5",
|
"eslint-plugin-tailwindcss": "^3.18.2",
|
||||||
"exifreader": "^4.26.0",
|
"exifreader": "^4.33.1",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"globals": "^15.14.0",
|
"globals": "^16.5.0",
|
||||||
"heic2any": "^0.0.4",
|
"heic2any": "^0.0.4",
|
||||||
"mime": "^4.0.6",
|
"kysely-ctl": "^0.19.0",
|
||||||
"p-limit": "^6.2.0",
|
"lru-cache": "^11.2.4",
|
||||||
"prettier": "^3.4.2",
|
"mime": "^4.1.0",
|
||||||
"prettier-plugin-svelte": "^3.3.2",
|
"p-limit": "^7.2.0",
|
||||||
"prettier-plugin-tailwindcss": "^0.6.9",
|
"prettier": "^3.7.4",
|
||||||
"svelte": "^5.17.1",
|
"prettier-plugin-svelte": "^3.4.1",
|
||||||
"svelte-check": "^4.1.3",
|
"prettier-plugin-tailwindcss": "^0.7.2",
|
||||||
"tailwindcss": "^3.4.17",
|
"svelte": "^5.46.1",
|
||||||
"typescript": "^5.7.3",
|
"svelte-check": "^4.3.5",
|
||||||
"typescript-eslint": "^8.19.1",
|
"tailwindcss": "^3.4.19",
|
||||||
"unplugin-icons": "^0.22.0",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^5.4.11"
|
"typescript-eslint": "^8.50.1",
|
||||||
|
"unplugin-icons": "^22.5.0",
|
||||||
|
"vite": "^7.3.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/busboy": "^3.1.1",
|
"@fastify/busboy": "^3.2.0",
|
||||||
"argon2": "^0.41.1",
|
"@trpc/server": "^11.8.1",
|
||||||
"better-sqlite3": "^11.7.2",
|
"argon2": "^0.44.0",
|
||||||
"drizzle-orm": "^0.33.0",
|
"kysely": "^0.28.9",
|
||||||
"ms": "^2.1.3",
|
"ms": "^2.1.3",
|
||||||
"node-schedule": "^2.1.1",
|
"node-schedule": "^2.1.1",
|
||||||
"uuid": "^11.0.4",
|
"pg": "^8.16.3",
|
||||||
"zod": "^3.24.1"
|
"superjson": "^2.2.6",
|
||||||
|
"uuid": "^13.0.0",
|
||||||
|
"zod": "^4.2.1"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^22.0.0",
|
"node": "^22.0.0",
|
||||||
"pnpm": "^9.0.0"
|
"pnpm": "^10.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3702
pnpm-lock.yaml
generated
3702
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="ko">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||||
|
|||||||
@@ -4,6 +4,15 @@ import { prepareFileCache } from "$lib/modules/file";
|
|||||||
import { prepareOpfs } from "$lib/modules/opfs";
|
import { prepareOpfs } from "$lib/modules/opfs";
|
||||||
import { clientKeyStore, masterKeyStore, hmacSecretStore } from "$lib/stores";
|
import { clientKeyStore, masterKeyStore, hmacSecretStore } from "$lib/stores";
|
||||||
|
|
||||||
|
const requestPersistentStorage = async () => {
|
||||||
|
const isPersistent = await navigator.storage.persist();
|
||||||
|
if (isPersistent) {
|
||||||
|
console.log("[ArkVault] Persistent storage granted.");
|
||||||
|
} else {
|
||||||
|
console.warn("[ArkVault] Persistent storage not granted.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const prepareClientKeyStore = async () => {
|
const prepareClientKeyStore = async () => {
|
||||||
const [encryptKey, decryptKey, signKey, verifyKey] = await Promise.all([
|
const [encryptKey, decryptKey, signKey, verifyKey] = await Promise.all([
|
||||||
getClientKey("encrypt"),
|
getClientKey("encrypt"),
|
||||||
@@ -32,6 +41,7 @@ const prepareHmacSecretStore = async () => {
|
|||||||
|
|
||||||
export const init: ClientInit = async () => {
|
export const init: ClientInit = async () => {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
|
requestPersistentStorage(),
|
||||||
prepareFileCache(),
|
prepareFileCache(),
|
||||||
prepareClientKeyStore(),
|
prepareClientKeyStore(),
|
||||||
prepareMasterKeyStore(),
|
prepareMasterKeyStore(),
|
||||||
|
|||||||
@@ -2,15 +2,15 @@ import type { ServerInit } from "@sveltejs/kit";
|
|||||||
import { sequence } from "@sveltejs/kit/hooks";
|
import { sequence } from "@sveltejs/kit/hooks";
|
||||||
import schedule from "node-schedule";
|
import schedule from "node-schedule";
|
||||||
import { cleanupExpiredUserClientChallenges } from "$lib/server/db/client";
|
import { cleanupExpiredUserClientChallenges } from "$lib/server/db/client";
|
||||||
import { migrateDB } from "$lib/server/db/drizzle";
|
import { migrateDB } from "$lib/server/db/kysely";
|
||||||
import {
|
import {
|
||||||
cleanupExpiredSessions,
|
cleanupExpiredSessions,
|
||||||
cleanupExpiredSessionUpgradeChallenges,
|
cleanupExpiredSessionUpgradeChallenges,
|
||||||
} from "$lib/server/db/session";
|
} from "$lib/server/db/session";
|
||||||
import { authenticate, setAgentInfo } from "$lib/server/middlewares";
|
import { authenticate, setAgentInfo } from "$lib/server/middlewares";
|
||||||
|
|
||||||
export const init: ServerInit = () => {
|
export const init: ServerInit = async () => {
|
||||||
migrateDB();
|
await migrateDB();
|
||||||
|
|
||||||
schedule.scheduleJob("0 * * * *", () => {
|
schedule.scheduleJob("0 * * * *", () => {
|
||||||
cleanupExpiredUserClientChallenges();
|
cleanupExpiredUserClientChallenges();
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Snippet } from "svelte";
|
|
||||||
import { fade, fly } from "svelte/transition";
|
|
||||||
import { AdaptiveDiv } from "$lib/components/divs";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
children: Snippet;
|
|
||||||
onclose?: () => void;
|
|
||||||
isOpen: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { children, onclose, isOpen = $bindable() }: Props = $props();
|
|
||||||
|
|
||||||
const closeBottomSheet = $derived(
|
|
||||||
onclose ||
|
|
||||||
(() => {
|
|
||||||
isOpen = false;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#if isOpen}
|
|
||||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
|
||||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
|
||||||
<div onclick={closeBottomSheet} class="fixed inset-0 z-10 flex items-end justify-center">
|
|
||||||
<div class="absolute inset-0 bg-black bg-opacity-50" transition:fade={{ duration: 100 }}></div>
|
|
||||||
<div class="z-20 w-full">
|
|
||||||
<AdaptiveDiv>
|
|
||||||
<div
|
|
||||||
onclick={(e) => e.stopPropagation()}
|
|
||||||
class="flex max-h-[70vh] min-h-[30vh] rounded-t-2xl bg-white px-4"
|
|
||||||
transition:fly={{ y: 100, duration: 200 }}
|
|
||||||
>
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
</AdaptiveDiv>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Snippet } from "svelte";
|
|
||||||
import { fade } from "svelte/transition";
|
|
||||||
import { AdaptiveDiv } from "$lib/components/divs";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
children: Snippet;
|
|
||||||
onclose?: () => void;
|
|
||||||
isOpen: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { children, onclose, isOpen = $bindable() }: Props = $props();
|
|
||||||
|
|
||||||
const closeModal = $derived(
|
|
||||||
onclose ||
|
|
||||||
(() => {
|
|
||||||
isOpen = false;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#if isOpen}
|
|
||||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
|
||||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
|
||||||
<div
|
|
||||||
onclick={closeModal}
|
|
||||||
class="fixed inset-0 z-10 bg-black bg-opacity-50"
|
|
||||||
transition:fade={{ duration: 100 }}
|
|
||||||
>
|
|
||||||
<AdaptiveDiv>
|
|
||||||
<div class="flex h-full items-center justify-center px-4">
|
|
||||||
<div onclick={(e) => e.stopPropagation()} class="rounded-2xl bg-white p-4">
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</AdaptiveDiv>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Snippet } from "svelte";
|
|
||||||
|
|
||||||
import IconArrowBack from "~icons/material-symbols/arrow-back";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
children?: Snippet;
|
|
||||||
onback?: () => void;
|
|
||||||
title?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { children, onback, title }: Props = $props();
|
|
||||||
|
|
||||||
const back = $derived(() => {
|
|
||||||
setTimeout(onback || (() => history.back()), 100);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="sticky top-0 z-10 flex flex-shrink-0 items-center justify-between bg-white py-4">
|
|
||||||
<button onclick={back} class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-gray-100">
|
|
||||||
<IconArrowBack class="text-2xl" />
|
|
||||||
</button>
|
|
||||||
{#if title}
|
|
||||||
<p class="flex-grow truncate px-2 text-center text-lg font-semibold">{title}</p>
|
|
||||||
{/if}
|
|
||||||
<div class="w-[2.3rem] flex-shrink-0">
|
|
||||||
{#if children}
|
|
||||||
{@render children?.()}
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
40
src/lib/components/atoms/BottomSheet.svelte
Normal file
40
src/lib/components/atoms/BottomSheet.svelte
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
import { fade, fly } from "svelte/transition";
|
||||||
|
import { AdaptiveDiv } from "$lib/components/atoms";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
isOpen: boolean;
|
||||||
|
onclose?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className, isOpen = $bindable(), onclose }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if isOpen}
|
||||||
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div
|
||||||
|
onclick={onclose || (() => (isOpen = false))}
|
||||||
|
class="fixed inset-0 z-10 flex items-end justify-center"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="absolute inset-0 bg-black bg-opacity-50"
|
||||||
|
transition:fade|global={{ duration: 100 }}
|
||||||
|
></div>
|
||||||
|
<AdaptiveDiv class="z-10 w-full">
|
||||||
|
<div
|
||||||
|
onclick={(e) => e.stopPropagation()}
|
||||||
|
class="flex max-h-[70vh] min-h-[30vh] flex-col rounded-t-2xl bg-white"
|
||||||
|
transition:fly|global={{ y: 100, duration: 200 }}
|
||||||
|
>
|
||||||
|
<div class={["flex-grow overflow-y-auto", className]}>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AdaptiveDiv>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
31
src/lib/components/atoms/Modal.svelte
Normal file
31
src/lib/components/atoms/Modal.svelte
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
import { fade } from "svelte/transition";
|
||||||
|
import { AdaptiveDiv } from "$lib/components/atoms";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
isOpen: boolean;
|
||||||
|
onclose?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className, isOpen = $bindable(), onclose }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if isOpen}
|
||||||
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div
|
||||||
|
onclick={onclose || (() => (isOpen = false))}
|
||||||
|
class="fixed inset-0 z-10 bg-black bg-opacity-50"
|
||||||
|
transition:fade|global={{ duration: 100 }}
|
||||||
|
>
|
||||||
|
<AdaptiveDiv class="flex h-full items-center justify-center px-4">
|
||||||
|
<div onclick={(e) => e.stopPropagation()} class={["rounded-2xl bg-white p-4", className]}>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
</AdaptiveDiv>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
58
src/lib/components/atoms/RowVirtualizer.svelte
Normal file
58
src/lib/components/atoms/RowVirtualizer.svelte
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { createWindowVirtualizer } from "@tanstack/svelte-virtual";
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class?: ClassValue;
|
||||||
|
count: number;
|
||||||
|
item: Snippet<[index: number]>;
|
||||||
|
itemHeight: (index: number) => number;
|
||||||
|
placeholder?: Snippet;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { class: className, count, item, itemHeight, placeholder }: Props = $props();
|
||||||
|
|
||||||
|
let element: HTMLElement | undefined = $state();
|
||||||
|
let scrollMargin = $state(0);
|
||||||
|
|
||||||
|
let virtualizer = $derived(
|
||||||
|
createWindowVirtualizer({
|
||||||
|
count,
|
||||||
|
estimateSize: itemHeight,
|
||||||
|
scrollMargin,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const measureItem = (node: HTMLElement) => {
|
||||||
|
$effect(() => $virtualizer.measureElement(node));
|
||||||
|
};
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!element) return;
|
||||||
|
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
scrollMargin = element!.getBoundingClientRect().top + window.scrollY;
|
||||||
|
});
|
||||||
|
observer.observe(element.parentElement!);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div bind:this={element} class={["relative", className]}>
|
||||||
|
<div style:height="{$virtualizer.getTotalSize()}px">
|
||||||
|
{#each $virtualizer.getVirtualItems() as virtualItem (virtualItem.key)}
|
||||||
|
<div
|
||||||
|
class="absolute left-0 top-0 w-full"
|
||||||
|
style:transform="translateY({virtualItem.start - scrollMargin}px)"
|
||||||
|
data-index={virtualItem.index}
|
||||||
|
use:measureItem
|
||||||
|
>
|
||||||
|
{@render item(virtualItem.index)}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{#if placeholder && $virtualizer.getVirtualItems().length === 0}
|
||||||
|
{@render placeholder()}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
59
src/lib/components/atoms/buttons/ActionEntryButton.svelte
Normal file
59
src/lib/components/atoms/buttons/ActionEntryButton.svelte
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component, Snippet } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
actionButtonClass?: ClassValue;
|
||||||
|
actionButtonIcon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
onActionButtonClick?: () => void;
|
||||||
|
onclick?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
actionButtonIcon: ActionButtonIcon,
|
||||||
|
actionButtonClass: actionButtonClassName,
|
||||||
|
children,
|
||||||
|
class: className,
|
||||||
|
onActionButtonClick,
|
||||||
|
onclick,
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
|
<div
|
||||||
|
id="container"
|
||||||
|
onclick={onclick && (() => setTimeout(onclick, 100))}
|
||||||
|
class={["rounded-xl", className]}
|
||||||
|
>
|
||||||
|
<div id="children" class="flex h-full items-center gap-x-4 p-2 transition">
|
||||||
|
<div class="flex-grow overflow-x-hidden">
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
{#if ActionButtonIcon}
|
||||||
|
<button
|
||||||
|
id="action-button"
|
||||||
|
onclick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (onActionButtonClick) {
|
||||||
|
setTimeout(onActionButtonClick, 100);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
class={["flex-shrink-0 rounded-full p-1 text-lg active:bg-gray-100", actionButtonClassName]}
|
||||||
|
>
|
||||||
|
<ActionButtonIcon />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
#container:active:not(:has(#action-button:active)) {
|
||||||
|
@apply bg-gray-100;
|
||||||
|
}
|
||||||
|
#children:active:not(:has(#action-button:active)) {
|
||||||
|
@apply scale-95;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
38
src/lib/components/atoms/buttons/Button.svelte
Normal file
38
src/lib/components/atoms/buttons/Button.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
color?: "primary" | "gray";
|
||||||
|
onclick?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className, color = "primary", onclick }: Props = $props();
|
||||||
|
|
||||||
|
let bgColor = $derived(
|
||||||
|
{
|
||||||
|
primary: "bg-primary-600 active:bg-primary-500",
|
||||||
|
gray: "bg-gray-300 active:bg-gray-400",
|
||||||
|
}[color],
|
||||||
|
);
|
||||||
|
let textColor = $derived(
|
||||||
|
{
|
||||||
|
primary: "text-white",
|
||||||
|
gray: "text-gray-800",
|
||||||
|
}[color],
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onclick={onclick && (() => setTimeout(onclick, 100))}
|
||||||
|
class={[
|
||||||
|
"h-12 min-w-fit rounded-xl p-3 font-medium transition active:scale-95",
|
||||||
|
bgColor,
|
||||||
|
textColor,
|
||||||
|
className,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{@render children()}
|
||||||
|
</button>
|
||||||
26
src/lib/components/atoms/buttons/EntryButton.svelte
Normal file
26
src/lib/components/atoms/buttons/EntryButton.svelte
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
import IconChevronRight from "~icons/material-symbols/chevron-right";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
onclick?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className, onclick }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onclick={onclick && (() => setTimeout(onclick, 100))}
|
||||||
|
class={["rounded-xl active:bg-gray-100", className]}
|
||||||
|
>
|
||||||
|
<div class="flex h-full items-center gap-x-4 p-2 transition active:scale-95">
|
||||||
|
<div class="flex-grow">
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
<IconChevronRight class="flex-shrink-0 text-xl text-gray-800" />
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
34
src/lib/components/atoms/buttons/FileThumbnailButton.svelte
Normal file
34
src/lib/components/atoms/buttons/FileThumbnailButton.svelte
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { browser } from "$app/environment";
|
||||||
|
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||||
|
import { requestFileThumbnailDownload } from "$lib/services/file";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
info: SummarizedFileInfo;
|
||||||
|
onclick?: (file: SummarizedFileInfo) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { info, onclick }: Props = $props();
|
||||||
|
|
||||||
|
let showThumbnail = $derived(
|
||||||
|
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
||||||
|
);
|
||||||
|
let thumbnailPromise = $derived(
|
||||||
|
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onclick={onclick && (() => setTimeout(() => onclick(info), 100))}
|
||||||
|
class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
|
||||||
|
>
|
||||||
|
{#await thumbnailPromise}
|
||||||
|
<div class="h-full w-full bg-gray-100"></div>
|
||||||
|
{:then thumbnail}
|
||||||
|
{#if thumbnail}
|
||||||
|
<img src={thumbnail} alt={info.name} class="h-full w-full object-cover" />
|
||||||
|
{:else}
|
||||||
|
<div class="h-full w-full bg-gray-100"></div>
|
||||||
|
{/if}
|
||||||
|
{/await}
|
||||||
|
</button>
|
||||||
27
src/lib/components/atoms/buttons/FloatingButton.svelte
Normal file
27
src/lib/components/atoms/buttons/FloatingButton.svelte
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
import { AdaptiveDiv } from "$lib/components/atoms";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class: ClassValue;
|
||||||
|
icon: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
onclick?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { class: className, icon: Icon, onclick }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="pointer-events-none fixed inset-0">
|
||||||
|
<AdaptiveDiv class="relative h-full">
|
||||||
|
<button
|
||||||
|
onclick={onclick && (() => setTimeout(onclick, 100))}
|
||||||
|
class={[
|
||||||
|
"pointer-events-auto absolute flex h-14 w-14 items-center justify-center rounded-full bg-gray-300 text-xl shadow-lg transition active:scale-95 active:bg-gray-400",
|
||||||
|
className,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Icon />
|
||||||
|
</button>
|
||||||
|
</AdaptiveDiv>
|
||||||
|
</div>
|
||||||
@@ -10,14 +10,10 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onclick={() => {
|
onclick={onclick && (() => setTimeout(onclick, 100))}
|
||||||
setTimeout(() => {
|
|
||||||
onclick?.();
|
|
||||||
}, 100);
|
|
||||||
}}
|
|
||||||
class="text-sm font-medium text-gray-800 underline underline-offset-2 active:rounded-xl active:bg-gray-100"
|
class="text-sm font-medium text-gray-800 underline underline-offset-2 active:rounded-xl active:bg-gray-100"
|
||||||
>
|
>
|
||||||
<div class="h-full w-full p-1 transition active:scale-95">
|
<div class="h-full p-1 transition active:scale-95">
|
||||||
{@render children?.()}
|
{@render children()}
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
|
export { default as ActionEntryButton } from "./ActionEntryButton.svelte";
|
||||||
export { default as Button } from "./Button.svelte";
|
export { default as Button } from "./Button.svelte";
|
||||||
export { default as EntryButton } from "./EntryButton.svelte";
|
export { default as EntryButton } from "./EntryButton.svelte";
|
||||||
|
export { default as FileThumbnailButton } from "./FileThumbnailButton.svelte";
|
||||||
export { default as FloatingButton } from "./FloatingButton.svelte";
|
export { default as FloatingButton } from "./FloatingButton.svelte";
|
||||||
export { default as TextButton } from "./TextButton.svelte";
|
export { default as TextButton } from "./TextButton.svelte";
|
||||||
15
src/lib/components/atoms/divs/AdaptiveDiv.svelte
Normal file
15
src/lib/components/atoms/divs/AdaptiveDiv.svelte
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={["mx-auto max-w-screen-md", className]}>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
15
src/lib/components/atoms/divs/BottomDiv.svelte
Normal file
15
src/lib/components/atoms/divs/BottomDiv.svelte
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={["sticky bottom-0 bg-white pb-4", className]}>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
15
src/lib/components/atoms/divs/FullscreenDiv.svelte
Normal file
15
src/lib/components/atoms/divs/FullscreenDiv.svelte
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={["flex flex-grow flex-col justify-between px-4", className]}>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
export { default as AdaptiveDiv } from "./AdaptiveDiv.svelte";
|
export { default as AdaptiveDiv } from "./AdaptiveDiv.svelte";
|
||||||
export { default as BottomDiv } from "./BottomDiv.svelte";
|
export { default as BottomDiv } from "./BottomDiv.svelte";
|
||||||
export { default as TitleDiv } from "./TitleDiv.svelte";
|
export { default as FullscreenDiv } from "./FullscreenDiv.svelte";
|
||||||
6
src/lib/components/atoms/index.ts
Normal file
6
src/lib/components/atoms/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export { default as BottomSheet } from "./BottomSheet.svelte";
|
||||||
|
export * from "./buttons";
|
||||||
|
export * from "./divs";
|
||||||
|
export * from "./inputs";
|
||||||
|
export { default as Modal } from "./Modal.svelte";
|
||||||
|
export { default as RowVirtualizer } from "./RowVirtualizer.svelte";
|
||||||
23
src/lib/components/atoms/inputs/CheckBox.svelte
Normal file
23
src/lib/components/atoms/inputs/CheckBox.svelte
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
|
||||||
|
import IconCheckCircle from "~icons/material-symbols/check-circle";
|
||||||
|
import IconCheckCircleOutline from "~icons/material-symbols/check-circle-outline";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
checked?: boolean;
|
||||||
|
children: Snippet;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { checked = $bindable(false), children }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<label class="flex items-center gap-x-1">
|
||||||
|
<input bind:checked type="checkbox" class="hidden" />
|
||||||
|
{@render children()}
|
||||||
|
{#if checked}
|
||||||
|
<IconCheckCircle class="text-primary-600" />
|
||||||
|
{:else}
|
||||||
|
<IconCheckCircleOutline class="text-gray-300" />
|
||||||
|
{/if}
|
||||||
|
</label>
|
||||||
40
src/lib/components/atoms/inputs/TextInput.svelte
Normal file
40
src/lib/components/atoms/inputs/TextInput.svelte
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class?: ClassValue;
|
||||||
|
placeholder: string;
|
||||||
|
type?: "text" | "password";
|
||||||
|
value?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { class: className, placeholder, type = "text", value = $bindable("") }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={className}>
|
||||||
|
<div class="relative mt-5">
|
||||||
|
<input
|
||||||
|
bind:value
|
||||||
|
{type}
|
||||||
|
placeholder=""
|
||||||
|
class="w-full border-b-2 border-gray-300 py-1 text-xl outline-none transition duration-300 ease-in-out"
|
||||||
|
/>
|
||||||
|
<!-- svelte-ignore a11y_label_has_associated_control -->
|
||||||
|
<label
|
||||||
|
class="pointer-events-none absolute left-0 top-1/2 -translate-y-1/2 transform text-xl text-gray-400 transition-all duration-300 ease-in-out"
|
||||||
|
>
|
||||||
|
{placeholder}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
input:focus,
|
||||||
|
input:not(:placeholder-shown) {
|
||||||
|
@apply border-primary-300;
|
||||||
|
}
|
||||||
|
input:focus + label,
|
||||||
|
input:not(:placeholder-shown) + label {
|
||||||
|
@apply top-0 -translate-y-full text-sm text-primary-400;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1 +1,2 @@
|
|||||||
|
export { default as CheckBox } from "./CheckBox.svelte";
|
||||||
export { default as TextInput } from "./TextInput.svelte";
|
export { default as TextInput } from "./TextInput.svelte";
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Snippet } from "svelte";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
children: Snippet;
|
|
||||||
color?: "primary" | "gray";
|
|
||||||
onclick?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { children, color = "primary", onclick }: Props = $props();
|
|
||||||
|
|
||||||
const bgColorStyle = $derived(
|
|
||||||
{
|
|
||||||
primary: "bg-primary-600 active:bg-primary-500",
|
|
||||||
gray: "bg-gray-300 active:bg-gray-400",
|
|
||||||
}[color],
|
|
||||||
);
|
|
||||||
const fontColorStyle = $derived(
|
|
||||||
{
|
|
||||||
primary: "text-white",
|
|
||||||
gray: "text-gray-800",
|
|
||||||
}[color],
|
|
||||||
);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onclick={() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
onclick?.();
|
|
||||||
}, 100);
|
|
||||||
}}
|
|
||||||
class="{bgColorStyle} {fontColorStyle} h-12 w-full min-w-fit rounded-xl font-medium"
|
|
||||||
>
|
|
||||||
<div class="h-full w-full p-3 transition active:scale-95">
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Snippet } from "svelte";
|
|
||||||
|
|
||||||
import IconChevronRight from "~icons/material-symbols/chevron-right";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
children: Snippet;
|
|
||||||
onclick?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { children, onclick }: Props = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onclick={() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
onclick?.();
|
|
||||||
}, 100);
|
|
||||||
}}
|
|
||||||
class="w-full rounded-xl active:bg-gray-100"
|
|
||||||
>
|
|
||||||
<div class="flex w-full justify-between p-2 transition active:scale-95">
|
|
||||||
<div>
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center justify-center">
|
|
||||||
<IconChevronRight class="text-xl text-gray-800" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Component } from "svelte";
|
|
||||||
import type { SvelteHTMLElements } from "svelte/elements";
|
|
||||||
import { AdaptiveDiv } from "$lib/components/divs";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
icon: Component<SvelteHTMLElements["svg"]>;
|
|
||||||
offset?: string;
|
|
||||||
onclick?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { icon: Icon, offset = "bottom-20", onclick }: Props = $props();
|
|
||||||
|
|
||||||
const click = () => {
|
|
||||||
setTimeout(() => {
|
|
||||||
onclick?.();
|
|
||||||
}, 100);
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="pointer-events-none fixed inset-0">
|
|
||||||
<div class="absolute w-full {offset}">
|
|
||||||
<AdaptiveDiv>
|
|
||||||
<div class="relative">
|
|
||||||
<div class="absolute bottom-4 right-4">
|
|
||||||
<button
|
|
||||||
onclick={click}
|
|
||||||
class="pointer-events-auto flex h-14 w-14 items-center justify-center rounded-full bg-gray-300 shadow-lg transition active:scale-95 active:bg-gray-400"
|
|
||||||
>
|
|
||||||
<Icon class="text-xl" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</AdaptiveDiv>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
let { children } = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="mx-auto h-full w-full max-w-screen-md">
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
let { children } = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="sticky bottom-0 flex flex-col items-center gap-y-2 bg-white pb-4">
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Component, Snippet } from "svelte";
|
|
||||||
import type { SvelteHTMLElements } from "svelte/elements";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
children: Snippet;
|
|
||||||
icon?: Component<SvelteHTMLElements["svg"]>;
|
|
||||||
topPadding?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { topPadding = true, children, icon: Icon }: Props = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<div class="box-content flex min-h-[10vh] items-center {topPadding ? 'pt-4' : ''}">
|
|
||||||
{#if Icon}
|
|
||||||
<Icon class="text-5xl text-gray-600" />
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{@render children?.()}
|
|
||||||
</div>
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export { default as BottomSheet } from "./BottomSheet.svelte";
|
|
||||||
export { default as Modal } from "./Modal.svelte";
|
|
||||||
export { default as TopBar } from "./TopBar.svelte";
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
interface Props {
|
|
||||||
placeholder: string;
|
|
||||||
type?: "text" | "password";
|
|
||||||
value?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { placeholder, type = "text", value = $bindable("") }: Props = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="relative mt-5">
|
|
||||||
<input
|
|
||||||
bind:value
|
|
||||||
{type}
|
|
||||||
placeholder=""
|
|
||||||
class="w-full border-b-2 border-gray-300 py-1 text-xl outline-none transition duration-300 ease-in-out"
|
|
||||||
/>
|
|
||||||
<!-- svelte-ignore a11y_label_has_associated_control -->
|
|
||||||
<label
|
|
||||||
class="absolute left-0 top-1/2 -translate-y-1/2 transform text-xl text-gray-400 transition-all duration-300 ease-in-out"
|
|
||||||
>
|
|
||||||
{placeholder}
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
input:focus,
|
|
||||||
input:not(:placeholder-shown) {
|
|
||||||
@apply border-primary-300;
|
|
||||||
}
|
|
||||||
input:focus + label,
|
|
||||||
input:not(:placeholder-shown) + label {
|
|
||||||
@apply top-0 -translate-y-full text-sm text-primary-400;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
57
src/lib/components/molecules/ActionModal.svelte
Normal file
57
src/lib/components/molecules/ActionModal.svelte
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<script module lang="ts">
|
||||||
|
export type ConfirmHandler = () => void | Promise<void> | boolean | Promise<boolean>;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import { Button, Modal } from "$lib/components/atoms";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
cancelText?: string;
|
||||||
|
children: Snippet;
|
||||||
|
confirmText: string;
|
||||||
|
isOpen: boolean;
|
||||||
|
onbeforeclose?: () => void;
|
||||||
|
oncancel?: () => void;
|
||||||
|
onConfirmClick: ConfirmHandler;
|
||||||
|
title: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
cancelText = "닫기",
|
||||||
|
children,
|
||||||
|
confirmText,
|
||||||
|
isOpen = $bindable(),
|
||||||
|
onbeforeclose,
|
||||||
|
oncancel,
|
||||||
|
onConfirmClick,
|
||||||
|
title,
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
const closeModal = () => {
|
||||||
|
onbeforeclose?.();
|
||||||
|
isOpen = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelAction = () => {
|
||||||
|
oncancel?.();
|
||||||
|
closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmAction = async () => {
|
||||||
|
if ((await onConfirmClick()) !== false) {
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Modal bind:isOpen onclose={cancelAction} class="space-y-4">
|
||||||
|
<div class="flex flex-col gap-y-2 break-keep">
|
||||||
|
<p class="text-xl font-bold">{title}</p>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-x-2">
|
||||||
|
<Button color="gray" onclick={cancelAction} class="flex-1">{cancelText}</Button>
|
||||||
|
<Button onclick={confirmAction} class="flex-1">{confirmText}</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
33
src/lib/components/molecules/Categories/Categories.svelte
Normal file
33
src/lib/components/molecules/Categories/Categories.svelte
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component } from "svelte";
|
||||||
|
import type { SvelteHTMLElements } from "svelte/elements";
|
||||||
|
import type { SubCategoryInfo } from "$lib/modules/filesystem";
|
||||||
|
import { SortBy, sortEntries } from "$lib/utils";
|
||||||
|
import Category from "./Category.svelte";
|
||||||
|
import type { SelectedCategory } from "./service";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
categories: SubCategoryInfo[];
|
||||||
|
categoryMenuIcon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
onCategoryClick: (category: SelectedCategory) => void;
|
||||||
|
onCategoryMenuClick?: (category: SelectedCategory) => void;
|
||||||
|
sortBy?: SortBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { categories, categoryMenuIcon, onCategoryClick, onCategoryMenuClick }: Props = $props();
|
||||||
|
|
||||||
|
let categoriesWithName = $derived(sortEntries(structuredClone($state.snapshot(categories))));
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if categoriesWithName.length > 0}
|
||||||
|
<div class="space-y-1">
|
||||||
|
{#each categoriesWithName as category}
|
||||||
|
<Category
|
||||||
|
info={category}
|
||||||
|
menuIcon={categoryMenuIcon}
|
||||||
|
onclick={onCategoryClick}
|
||||||
|
onMenuClick={onCategoryMenuClick}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
26
src/lib/components/molecules/Categories/Category.svelte
Normal file
26
src/lib/components/molecules/Categories/Category.svelte
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component } from "svelte";
|
||||||
|
import type { SvelteHTMLElements } from "svelte/elements";
|
||||||
|
import { ActionEntryButton } from "$lib/components/atoms";
|
||||||
|
import { CategoryLabel } from "$lib/components/molecules";
|
||||||
|
import type { SubCategoryInfo } from "$lib/modules/filesystem";
|
||||||
|
import type { SelectedCategory } from "./service";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
info: SubCategoryInfo;
|
||||||
|
menuIcon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
onclick: (category: SelectedCategory) => void;
|
||||||
|
onMenuClick?: (category: SelectedCategory) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { info, menuIcon, onclick, onMenuClick }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<ActionEntryButton
|
||||||
|
class="h-12"
|
||||||
|
onclick={() => onclick(info)}
|
||||||
|
actionButtonIcon={menuIcon}
|
||||||
|
onActionButtonClick={() => onMenuClick?.(info)}
|
||||||
|
>
|
||||||
|
<CategoryLabel name={info.name} />
|
||||||
|
</ActionEntryButton>
|
||||||
2
src/lib/components/molecules/Categories/index.ts
Normal file
2
src/lib/components/molecules/Categories/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./Categories.svelte";
|
||||||
|
export * from "./service";
|
||||||
7
src/lib/components/molecules/Categories/service.ts
Normal file
7
src/lib/components/molecules/Categories/service.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { DataKey } from "$lib/modules/filesystem";
|
||||||
|
|
||||||
|
export interface SelectedCategory {
|
||||||
|
id: number;
|
||||||
|
dataKey?: DataKey;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
30
src/lib/components/molecules/IconEntryButton.svelte
Normal file
30
src/lib/components/molecules/IconEntryButton.svelte
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component, Snippet } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
import { EntryButton } from "$lib/components/atoms";
|
||||||
|
import { IconLabel } from "$lib/components/molecules";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
icon: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
iconClass?: ClassValue;
|
||||||
|
onclick?: () => void;
|
||||||
|
textClass?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
children,
|
||||||
|
class: className,
|
||||||
|
icon,
|
||||||
|
iconClass: iconClassName,
|
||||||
|
onclick,
|
||||||
|
textClass: textClassName,
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<EntryButton {onclick} class={className}>
|
||||||
|
<IconLabel {icon} class="h-full" iconClass={iconClassName} textClass={textClassName}>
|
||||||
|
{@render children()}
|
||||||
|
</IconLabel>
|
||||||
|
</EntryButton>
|
||||||
55
src/lib/components/molecules/SubCategories.svelte
Normal file
55
src/lib/components/molecules/SubCategories.svelte
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
import { Categories, IconEntryButton, type SelectedCategory } from "$lib/components/molecules";
|
||||||
|
import type { CategoryInfo } from "$lib/modules/filesystem";
|
||||||
|
|
||||||
|
import IconAddCircle from "~icons/material-symbols/add-circle";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class?: ClassValue;
|
||||||
|
info: CategoryInfo;
|
||||||
|
onSubCategoryClick: (subCategory: SelectedCategory) => void;
|
||||||
|
onSubCategoryCreateClick: () => void;
|
||||||
|
onSubCategoryMenuClick?: (category: SelectedCategory) => void;
|
||||||
|
subCategoryCreatePosition?: "top" | "bottom";
|
||||||
|
subCategoryMenuIcon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
class: className,
|
||||||
|
info,
|
||||||
|
onSubCategoryClick,
|
||||||
|
onSubCategoryCreateClick,
|
||||||
|
onSubCategoryMenuClick,
|
||||||
|
subCategoryCreatePosition = "bottom",
|
||||||
|
subCategoryMenuIcon,
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={["space-y-1", className]}>
|
||||||
|
{#snippet subCategoryCreate()}
|
||||||
|
<IconEntryButton
|
||||||
|
icon={IconAddCircle}
|
||||||
|
onclick={onSubCategoryCreateClick}
|
||||||
|
class="h-12 w-full"
|
||||||
|
iconClass="text-gray-600"
|
||||||
|
textClass="text-gray-700"
|
||||||
|
>
|
||||||
|
카테고리 추가하기
|
||||||
|
</IconEntryButton>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
{#if subCategoryCreatePosition === "top"}
|
||||||
|
{@render subCategoryCreate()}
|
||||||
|
{/if}
|
||||||
|
<Categories
|
||||||
|
categories={info.subCategories}
|
||||||
|
categoryMenuIcon={subCategoryMenuIcon}
|
||||||
|
onCategoryClick={onSubCategoryClick}
|
||||||
|
onCategoryMenuClick={onSubCategoryMenuClick}
|
||||||
|
/>
|
||||||
|
{#if subCategoryCreatePosition === "bottom"}
|
||||||
|
{@render subCategoryCreate()}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
43
src/lib/components/molecules/TitledDiv.svelte
Normal file
43
src/lib/components/molecules/TitledDiv.svelte
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component, Snippet } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
import { TitleLabel } from "$lib/components/molecules";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children?: Snippet;
|
||||||
|
childrenClass?: ClassValue;
|
||||||
|
class?: ClassValue;
|
||||||
|
description?: Snippet;
|
||||||
|
icon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
title: Snippet;
|
||||||
|
titleClass?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
children,
|
||||||
|
childrenClass: childrenClassName,
|
||||||
|
class: className,
|
||||||
|
description,
|
||||||
|
icon,
|
||||||
|
title,
|
||||||
|
titleClass: titleClassName,
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={["space-y-4 py-4", className]}>
|
||||||
|
<div class="space-y-2 break-keep">
|
||||||
|
<TitleLabel {icon} textClass={titleClassName}>
|
||||||
|
{@render title()}
|
||||||
|
</TitleLabel>
|
||||||
|
{#if description}
|
||||||
|
<p>
|
||||||
|
{@render description()}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if children}
|
||||||
|
<div class={childrenClassName}>
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
37
src/lib/components/molecules/TopBar.svelte
Normal file
37
src/lib/components/molecules/TopBar.svelte
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
|
||||||
|
import IconArrowBack from "~icons/material-symbols/arrow-back";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children?: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
onBackClick?: () => void;
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className, onBackClick, title }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class={[
|
||||||
|
"sticky top-0 z-10 flex items-center justify-between gap-x-2 px-2 py-3 backdrop-blur-2xl",
|
||||||
|
className,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onclick={onBackClick || (() => 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>
|
||||||
|
{#if title}
|
||||||
|
<p class="flex-grow truncate text-center text-lg font-semibold">{title}</p>
|
||||||
|
{/if}
|
||||||
|
<div class="w-[2.3rem] flex-shrink-0">
|
||||||
|
{#if children}
|
||||||
|
{@render children()}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
9
src/lib/components/molecules/index.ts
Normal file
9
src/lib/components/molecules/index.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export * from "./ActionModal.svelte";
|
||||||
|
export { default as ActionModal } from "./ActionModal.svelte";
|
||||||
|
export * from "./Categories";
|
||||||
|
export { default as Categories } from "./Categories";
|
||||||
|
export { default as IconEntryButton } from "./IconEntryButton.svelte";
|
||||||
|
export * from "./labels";
|
||||||
|
export { default as SubCategories } from "./SubCategories.svelte";
|
||||||
|
export { default as TitledDiv } from "./TitledDiv.svelte";
|
||||||
|
export { default as TopBar } from "./TopBar.svelte";
|
||||||
28
src/lib/components/molecules/labels/CategoryLabel.svelte
Normal file
28
src/lib/components/molecules/labels/CategoryLabel.svelte
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
import { IconLabel } from "$lib/components/molecules";
|
||||||
|
|
||||||
|
import IconCategory from "~icons/material-symbols/category";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class?: ClassValue;
|
||||||
|
name: string;
|
||||||
|
subtext?: string;
|
||||||
|
textClass?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { class: className, name, subtext, textClass: textClassName }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet subtextSnippet()}
|
||||||
|
{subtext}
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<IconLabel
|
||||||
|
icon={IconCategory}
|
||||||
|
subtext={subtext ? subtextSnippet : undefined}
|
||||||
|
class={className}
|
||||||
|
textClass={textClassName}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</IconLabel>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { ClassValue } from "svelte/elements";
|
||||||
|
import { IconLabel } from "$lib/components/molecules";
|
||||||
|
|
||||||
|
import IconFolder from "~icons/material-symbols/folder";
|
||||||
|
import IconDriveFolderUpload from "~icons/material-symbols/drive-folder-upload";
|
||||||
|
import IconDraft from "~icons/material-symbols/draft";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class?: ClassValue;
|
||||||
|
name: string;
|
||||||
|
subtext?: string;
|
||||||
|
textClass?: ClassValue;
|
||||||
|
thumbnail?: string;
|
||||||
|
type: "directory" | "parent-directory" | "file";
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
class: className,
|
||||||
|
name,
|
||||||
|
subtext,
|
||||||
|
textClass: textClassName,
|
||||||
|
thumbnail,
|
||||||
|
type,
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet iconSnippet()}
|
||||||
|
<div class="flex h-10 w-10 items-center justify-center text-xl">
|
||||||
|
{#if thumbnail}
|
||||||
|
<img src={thumbnail} alt={name} loading="lazy" class="aspect-square rounded object-cover" />
|
||||||
|
{:else if type === "directory"}
|
||||||
|
<IconFolder />
|
||||||
|
{:else if type === "parent-directory"}
|
||||||
|
<IconDriveFolderUpload class="text-yellow-500" />
|
||||||
|
{:else}
|
||||||
|
<IconDraft class="text-blue-400" />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
{#snippet subtextSnippet()}
|
||||||
|
{subtext}
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<IconLabel
|
||||||
|
{iconSnippet}
|
||||||
|
subtext={subtext ? subtextSnippet : undefined}
|
||||||
|
class={className}
|
||||||
|
textClass={textClassName}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</IconLabel>
|
||||||
46
src/lib/components/molecules/labels/IconLabel.svelte
Normal file
46
src/lib/components/molecules/labels/IconLabel.svelte
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component, Snippet } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
icon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
iconClass?: ClassValue;
|
||||||
|
iconSnippet?: Snippet;
|
||||||
|
subtext?: Snippet;
|
||||||
|
textClass?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
children,
|
||||||
|
class: className,
|
||||||
|
icon: Icon,
|
||||||
|
iconClass: iconClassName,
|
||||||
|
iconSnippet,
|
||||||
|
subtext,
|
||||||
|
textClass: textClassName,
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={["flex items-center gap-x-4", className]}>
|
||||||
|
{#if iconSnippet}
|
||||||
|
<div class={["flex-shrink-0", iconClassName]}>
|
||||||
|
{@render iconSnippet()}
|
||||||
|
</div>
|
||||||
|
{:else if Icon}
|
||||||
|
<div class={["flex-shrink-0 text-lg", iconClassName]}>
|
||||||
|
<Icon />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="flex flex-grow flex-col overflow-x-hidden text-left">
|
||||||
|
<p class={["truncate font-medium", textClassName]}>
|
||||||
|
{@render children()}
|
||||||
|
</p>
|
||||||
|
{#if subtext}
|
||||||
|
<p class="truncate text-xs text-gray-800">
|
||||||
|
{@render subtext()}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
24
src/lib/components/molecules/labels/TitleLabel.svelte
Normal file
24
src/lib/components/molecules/labels/TitleLabel.svelte
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component, Snippet } from "svelte";
|
||||||
|
import type { ClassValue, SvelteHTMLElements } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: Snippet;
|
||||||
|
class?: ClassValue;
|
||||||
|
icon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
textClass?: ClassValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { children, class: className, icon: Icon, textClass: textClassName }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={className}>
|
||||||
|
<div class="flex min-h-[10vh] items-center">
|
||||||
|
{#if Icon}
|
||||||
|
<Icon class="text-5xl text-gray-600" />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<p class={["text-3xl font-bold", textClassName]}>
|
||||||
|
{@render children()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
4
src/lib/components/molecules/labels/index.ts
Normal file
4
src/lib/components/molecules/labels/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export { default as CategoryLabel } from "./CategoryLabel.svelte";
|
||||||
|
export { default as DirectoryEntryLabel } from "./DirectoryEntryLabel.svelte";
|
||||||
|
export { default as IconLabel } from "./IconLabel.svelte";
|
||||||
|
export { default as TitleLabel } from "./TitleLabel.svelte";
|
||||||
81
src/lib/components/organisms/Category/Category.svelte
Normal file
81
src/lib/components/organisms/Category/Category.svelte
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { CheckBox, RowVirtualizer } from "$lib/components/atoms";
|
||||||
|
import { SubCategories, type SelectedCategory } from "$lib/components/molecules";
|
||||||
|
import type { CategoryInfo } from "$lib/modules/filesystem";
|
||||||
|
import { sortEntries } from "$lib/utils";
|
||||||
|
import File from "./File.svelte";
|
||||||
|
import type { SelectedFile } from "./service";
|
||||||
|
|
||||||
|
import IconMoreVert from "~icons/material-symbols/more-vert";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
info: CategoryInfo;
|
||||||
|
isFileRecursive: boolean | undefined;
|
||||||
|
onFileClick: (file: SelectedFile) => void;
|
||||||
|
onFileRemoveClick: (file: SelectedFile) => void;
|
||||||
|
onSubCategoryClick: (subCategory: SelectedCategory) => void;
|
||||||
|
onSubCategoryCreateClick: () => void;
|
||||||
|
onSubCategoryMenuClick: (subCategory: SelectedCategory) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
info,
|
||||||
|
onFileClick,
|
||||||
|
onFileRemoveClick,
|
||||||
|
onSubCategoryClick,
|
||||||
|
onSubCategoryCreateClick,
|
||||||
|
onSubCategoryMenuClick,
|
||||||
|
isFileRecursive = $bindable(),
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
let files = $derived(
|
||||||
|
sortEntries(
|
||||||
|
info.files
|
||||||
|
?.map((file) => ({ name: file.name, details: file }))
|
||||||
|
.filter(({ details }) => isFileRecursive || !details.isRecursive) ?? [],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div class="space-y-4 bg-white p-4">
|
||||||
|
{#if info.id !== "root"}
|
||||||
|
<p class="text-lg font-bold text-gray-800">하위 카테고리</p>
|
||||||
|
{/if}
|
||||||
|
<SubCategories
|
||||||
|
{info}
|
||||||
|
{onSubCategoryClick}
|
||||||
|
{onSubCategoryCreateClick}
|
||||||
|
{onSubCategoryMenuClick}
|
||||||
|
subCategoryMenuIcon={IconMoreVert}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{#if info.id !== "root"}
|
||||||
|
<div class="space-y-4 bg-white p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<p class="text-lg font-bold text-gray-800">파일</p>
|
||||||
|
<CheckBox bind:checked={isFileRecursive}>
|
||||||
|
<p class="font-medium">하위 카테고리의 파일</p>
|
||||||
|
</CheckBox>
|
||||||
|
</div>
|
||||||
|
<RowVirtualizer
|
||||||
|
count={files.length}
|
||||||
|
itemHeight={(index) => 48 + (index + 1 < files.length ? 4 : 0)}
|
||||||
|
>
|
||||||
|
{#snippet item(index)}
|
||||||
|
{@const { details } = files[index]!}
|
||||||
|
<div class={[index + 1 < files.length && "pb-1"]}>
|
||||||
|
<File
|
||||||
|
info={details}
|
||||||
|
onclick={onFileClick}
|
||||||
|
onRemoveClick={!details.isRecursive ? onFileRemoveClick : undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
{#snippet placeholder()}
|
||||||
|
<p class="text-center text-gray-500">이 카테고리에 추가된 파일이 없어요.</p>
|
||||||
|
{/snippet}
|
||||||
|
</RowVirtualizer>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
38
src/lib/components/organisms/Category/File.svelte
Normal file
38
src/lib/components/organisms/Category/File.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { browser } from "$app/environment";
|
||||||
|
import { ActionEntryButton } from "$lib/components/atoms";
|
||||||
|
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||||
|
import type { CategoryFileInfo } from "$lib/modules/filesystem";
|
||||||
|
import { requestFileThumbnailDownload } from "$lib/services/file";
|
||||||
|
import type { SelectedFile } from "./service";
|
||||||
|
|
||||||
|
import IconClose from "~icons/material-symbols/close";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
info: CategoryFileInfo;
|
||||||
|
onclick: (file: SelectedFile) => void;
|
||||||
|
onRemoveClick?: (file: SelectedFile) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { info, onclick, onRemoveClick }: Props = $props();
|
||||||
|
|
||||||
|
let showThumbnail = $derived(
|
||||||
|
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
||||||
|
);
|
||||||
|
let thumbnailPromise = $derived(
|
||||||
|
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<ActionEntryButton
|
||||||
|
class="h-12"
|
||||||
|
onclick={() => onclick(info)}
|
||||||
|
actionButtonIcon={onRemoveClick && IconClose}
|
||||||
|
onActionButtonClick={() => onRemoveClick?.(info)}
|
||||||
|
>
|
||||||
|
{#await thumbnailPromise}
|
||||||
|
<DirectoryEntryLabel type="file" name={info.name} />
|
||||||
|
{:then thumbnail}
|
||||||
|
<DirectoryEntryLabel type="file" thumbnail={thumbnail ?? undefined} name={info.name} />
|
||||||
|
{/await}
|
||||||
|
</ActionEntryButton>
|
||||||
2
src/lib/components/organisms/Category/index.ts
Normal file
2
src/lib/components/organisms/Category/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./Category.svelte";
|
||||||
|
export * from "./service";
|
||||||
4
src/lib/components/organisms/Category/service.ts
Normal file
4
src/lib/components/organisms/Category/service.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export interface SelectedFile {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
82
src/lib/components/organisms/Gallery.svelte
Normal file
82
src/lib/components/organisms/Gallery.svelte
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { FileThumbnailButton, RowVirtualizer } from "$lib/components/atoms";
|
||||||
|
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||||
|
import { formatDate, formatDateSortable, SortBy, sortEntries } from "$lib/utils";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
files: SummarizedFileInfo[];
|
||||||
|
onFileClick?: (file: SummarizedFileInfo) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { files, onFileClick }: Props = $props();
|
||||||
|
|
||||||
|
type Row =
|
||||||
|
| { type: "header"; label: string }
|
||||||
|
| { type: "items"; files: SummarizedFileInfo[]; isLast: boolean };
|
||||||
|
|
||||||
|
let rows = $derived.by(() => {
|
||||||
|
const groups = Map.groupBy(
|
||||||
|
files.filter(
|
||||||
|
(file) => file.contentType.startsWith("image/") || file.contentType.startsWith("video/"),
|
||||||
|
),
|
||||||
|
(file) => formatDateSortable(file.createdAt ?? file.lastModifiedAt),
|
||||||
|
);
|
||||||
|
return Array.from(groups.entries())
|
||||||
|
.sort(([dateA], [dateB]) => dateB.localeCompare(dateA))
|
||||||
|
.flatMap(([_, entries]) => {
|
||||||
|
const sortedEntries = [...entries];
|
||||||
|
sortEntries(sortedEntries, SortBy.DATE_DESC);
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
type: "header",
|
||||||
|
label: formatDate(sortedEntries[0]!.createdAt ?? sortedEntries[0]!.lastModifiedAt),
|
||||||
|
},
|
||||||
|
...Array.from({ length: Math.ceil(sortedEntries.length / 4) }, (_, i) => {
|
||||||
|
const start = i * 4;
|
||||||
|
const end = start + 4;
|
||||||
|
return {
|
||||||
|
type: "items" as const,
|
||||||
|
files: sortedEntries.slice(start, end),
|
||||||
|
isLast: end >= sortedEntries.length,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
] satisfies Row[];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<RowVirtualizer
|
||||||
|
count={rows.length}
|
||||||
|
itemHeight={(index) =>
|
||||||
|
rows[index]!.type === "header"
|
||||||
|
? 28
|
||||||
|
: Math.ceil(rows[index]!.files.length / 4) * 181 +
|
||||||
|
(Math.ceil(rows[index]!.files.length / 4) - 1) * 4 +
|
||||||
|
16}
|
||||||
|
class="flex flex-grow flex-col"
|
||||||
|
>
|
||||||
|
{#snippet item(index)}
|
||||||
|
{@const row = rows[index]!}
|
||||||
|
{#if row.type === "header"}
|
||||||
|
<p class="pb-2 text-sm font-medium">{row.label}</p>
|
||||||
|
{:else}
|
||||||
|
<div class={["grid grid-cols-4 gap-x-1", row.isLast ? "pb-4" : "pb-1"]}>
|
||||||
|
{#each row.files as file}
|
||||||
|
<FileThumbnailButton info={file} onclick={onFileClick} />
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
{#snippet placeholder()}
|
||||||
|
<div class="flex h-full flex-grow items-center justify-center">
|
||||||
|
<p class="text-gray-500">
|
||||||
|
{#if files.length === 0}
|
||||||
|
업로드된 파일이 없어요.
|
||||||
|
{:else}
|
||||||
|
사진 또는 동영상이 없어요.
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</RowVirtualizer>
|
||||||
4
src/lib/components/organisms/index.ts
Normal file
4
src/lib/components/organisms/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export * from "./Category";
|
||||||
|
export { default as Category } from "./Category";
|
||||||
|
export { default as Gallery } from "./Gallery.svelte";
|
||||||
|
export * from "./modals";
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { TextInputModal } from "$lib/components/organisms";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
isOpen: boolean;
|
||||||
|
onCreateClick: (name: string) => Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { isOpen = $bindable(), onCreateClick }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<TextInputModal
|
||||||
|
bind:isOpen
|
||||||
|
title="새 카테고리"
|
||||||
|
placeholder="카테고리 이름"
|
||||||
|
submitText="만들기"
|
||||||
|
onSubmitClick={onCreateClick}
|
||||||
|
/>
|
||||||
22
src/lib/components/organisms/modals/ForceLoginModal.svelte
Normal file
22
src/lib/components/organisms/modals/ForceLoginModal.svelte
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { ActionModal } from "$lib/components/molecules";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
isOpen: boolean;
|
||||||
|
oncancel?: () => void;
|
||||||
|
onLoginClick: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { isOpen = $bindable(), oncancel, onLoginClick }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<ActionModal
|
||||||
|
bind:isOpen
|
||||||
|
title="다른 디바이스에 이미 로그인되어 있어요."
|
||||||
|
cancelText="아니요"
|
||||||
|
{oncancel}
|
||||||
|
confirmText="네"
|
||||||
|
onConfirmClick={onLoginClick}
|
||||||
|
>
|
||||||
|
<p>다른 디바이스에서는 로그아웃하고, 이 디바이스에서 로그인할까요?</p>
|
||||||
|
</ActionModal>
|
||||||
22
src/lib/components/organisms/modals/RenameModal.svelte
Normal file
22
src/lib/components/organisms/modals/RenameModal.svelte
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { TextInputModal } from "$lib/components/organisms";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
isOpen: boolean;
|
||||||
|
onbeforeclose?: () => void;
|
||||||
|
onRenameClick: (newName: string) => Promise<boolean>;
|
||||||
|
originalName: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { isOpen = $bindable(), onbeforeclose, onRenameClick, originalName }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<TextInputModal
|
||||||
|
bind:isOpen
|
||||||
|
{onbeforeclose}
|
||||||
|
title="이름 바꾸기"
|
||||||
|
placeholder="이름"
|
||||||
|
defaultValue={originalName}
|
||||||
|
submitText="바꾸기"
|
||||||
|
onSubmitClick={onRenameClick}
|
||||||
|
/>
|
||||||
42
src/lib/components/organisms/modals/TextInputModal.svelte
Normal file
42
src/lib/components/organisms/modals/TextInputModal.svelte
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { TextInput } from "$lib/components/atoms";
|
||||||
|
import { ActionModal, type ConfirmHandler } from "$lib/components/molecules";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
defaultValue?: string;
|
||||||
|
isOpen: boolean;
|
||||||
|
onbeforeclose?: () => void;
|
||||||
|
onSubmitClick: (value: string) => ReturnType<ConfirmHandler>;
|
||||||
|
placeholder: string;
|
||||||
|
submitText: string;
|
||||||
|
title: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
defaultValue = "",
|
||||||
|
isOpen = $bindable(),
|
||||||
|
onbeforeclose,
|
||||||
|
onSubmitClick,
|
||||||
|
placeholder,
|
||||||
|
submitText,
|
||||||
|
title,
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
let value = $state("");
|
||||||
|
|
||||||
|
$effect.pre(() => {
|
||||||
|
if (isOpen) {
|
||||||
|
value = defaultValue;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<ActionModal
|
||||||
|
bind:isOpen
|
||||||
|
{onbeforeclose}
|
||||||
|
{title}
|
||||||
|
confirmText={submitText}
|
||||||
|
onConfirmClick={() => onSubmitClick(value)}
|
||||||
|
>
|
||||||
|
<TextInput bind:value {placeholder} class="mb-3" />
|
||||||
|
</ActionModal>
|
||||||
4
src/lib/components/organisms/modals/index.ts
Normal file
4
src/lib/components/organisms/modals/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export { default as CategoryCreateModal } from "./CategoryCreateModal.svelte";
|
||||||
|
export { default as ForceLoginModal } from "./ForceLoginModal.svelte";
|
||||||
|
export { default as RenameModal } from "./RenameModal.svelte";
|
||||||
|
export { default as TextInputModal } from "./TextInputModal.svelte";
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
export const callGetApi = async (input: RequestInfo, fetchInternal = fetch) => {
|
|
||||||
return await fetchInternal(input);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const callPostApi = async <T>(input: RequestInfo, payload?: T, fetchInternal = fetch) => {
|
|
||||||
return await fetchInternal(input, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: payload ? JSON.stringify(payload) : undefined,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export * from "./callApi";
|
|
||||||
export * from "./gotoStateful";
|
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
import { Dexie, type EntityTable } from "dexie";
|
import { Dexie, type EntityTable } from "dexie";
|
||||||
|
|
||||||
export type DirectoryId = "root" | number;
|
|
||||||
|
|
||||||
interface DirectoryInfo {
|
interface DirectoryInfo {
|
||||||
id: number;
|
id: number;
|
||||||
parentId: DirectoryId;
|
parentId: DirectoryId;
|
||||||
@@ -15,17 +13,38 @@ interface FileInfo {
|
|||||||
contentType: string;
|
contentType: string;
|
||||||
createdAt?: Date;
|
createdAt?: Date;
|
||||||
lastModifiedAt: Date;
|
lastModifiedAt: Date;
|
||||||
|
categoryIds: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CategoryInfo {
|
||||||
|
id: number;
|
||||||
|
parentId: CategoryId;
|
||||||
|
name: string;
|
||||||
|
files: { id: number; isRecursive: boolean }[];
|
||||||
|
isFileRecursive: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filesystem = new Dexie("filesystem") as Dexie & {
|
const filesystem = new Dexie("filesystem") as Dexie & {
|
||||||
directory: EntityTable<DirectoryInfo, "id">;
|
directory: EntityTable<DirectoryInfo, "id">;
|
||||||
file: EntityTable<FileInfo, "id">;
|
file: EntityTable<FileInfo, "id">;
|
||||||
|
category: EntityTable<CategoryInfo, "id">;
|
||||||
};
|
};
|
||||||
|
|
||||||
filesystem.version(1).stores({
|
filesystem
|
||||||
|
.version(3)
|
||||||
|
.stores({
|
||||||
directory: "id, parentId",
|
directory: "id, parentId",
|
||||||
file: "id, parentId",
|
file: "id, parentId",
|
||||||
});
|
category: "id, parentId",
|
||||||
|
})
|
||||||
|
.upgrade(async (trx) => {
|
||||||
|
await trx
|
||||||
|
.table("category")
|
||||||
|
.toCollection()
|
||||||
|
.modify((category) => {
|
||||||
|
category.isFileRecursive = 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();
|
||||||
@@ -43,6 +62,10 @@ export const deleteDirectoryInfo = async (id: number) => {
|
|||||||
await filesystem.directory.delete(id);
|
await filesystem.directory.delete(id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getAllFileInfos = async () => {
|
||||||
|
return await filesystem.file.toArray();
|
||||||
|
};
|
||||||
|
|
||||||
export const getFileInfos = async (parentId: DirectoryId) => {
|
export const getFileInfos = async (parentId: DirectoryId) => {
|
||||||
return await filesystem.file.where({ parentId }).toArray();
|
return await filesystem.file.where({ parentId }).toArray();
|
||||||
};
|
};
|
||||||
@@ -51,6 +74,10 @@ export const getFileInfo = async (id: number) => {
|
|||||||
return await filesystem.file.get(id);
|
return await filesystem.file.get(id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const bulkGetFileInfos = async (ids: number[]) => {
|
||||||
|
return await filesystem.file.bulkGet(ids);
|
||||||
|
};
|
||||||
|
|
||||||
export const storeFileInfo = async (fileInfo: FileInfo) => {
|
export const storeFileInfo = async (fileInfo: FileInfo) => {
|
||||||
await filesystem.file.put(fileInfo);
|
await filesystem.file.put(fileInfo);
|
||||||
};
|
};
|
||||||
@@ -59,13 +86,33 @@ export const deleteFileInfo = async (id: number) => {
|
|||||||
await filesystem.file.delete(id);
|
await filesystem.file.delete(id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getCategoryInfos = async (parentId: CategoryId) => {
|
||||||
|
return await filesystem.category.where({ parentId }).toArray();
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCategoryInfo = async (id: number) => {
|
||||||
|
return await filesystem.category.get(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const storeCategoryInfo = async (categoryInfo: CategoryInfo) => {
|
||||||
|
await filesystem.category.put(categoryInfo);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateCategoryInfo = async (id: number, changes: { isFileRecursive?: boolean }) => {
|
||||||
|
await filesystem.category.update(id, changes);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteCategoryInfo = async (id: number) => {
|
||||||
|
await filesystem.category.delete(id);
|
||||||
|
};
|
||||||
|
|
||||||
export const cleanupDanglingInfos = async () => {
|
export const cleanupDanglingInfos = async () => {
|
||||||
const validDirectoryIds: number[] = [];
|
const validDirectoryIds: number[] = [];
|
||||||
const validFileIds: number[] = [];
|
const validFileIds: number[] = [];
|
||||||
const queue: DirectoryId[] = ["root"];
|
const directoryQueue: DirectoryId[] = ["root"];
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const directoryId = queue.shift();
|
const directoryId = directoryQueue.shift();
|
||||||
if (!directoryId) break;
|
if (!directoryId) break;
|
||||||
|
|
||||||
const [subDirectories, files] = await Promise.all([
|
const [subDirectories, files] = await Promise.all([
|
||||||
@@ -74,13 +121,28 @@ export const cleanupDanglingInfos = async () => {
|
|||||||
]);
|
]);
|
||||||
subDirectories.forEach(({ id }) => {
|
subDirectories.forEach(({ id }) => {
|
||||||
validDirectoryIds.push(id);
|
validDirectoryIds.push(id);
|
||||||
queue.push(id);
|
directoryQueue.push(id);
|
||||||
});
|
});
|
||||||
files.forEach(({ id }) => validFileIds.push(id));
|
files.forEach(({ id }) => validFileIds.push(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const validCategoryIds: number[] = [];
|
||||||
|
const categoryQueue: CategoryId[] = ["root"];
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const categoryId = categoryQueue.shift();
|
||||||
|
if (!categoryId) break;
|
||||||
|
|
||||||
|
const subCategories = await filesystem.category.where({ parentId: categoryId }).toArray();
|
||||||
|
subCategories.forEach(({ id }) => {
|
||||||
|
validCategoryIds.push(id);
|
||||||
|
categoryQueue.push(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
filesystem.directory.where("id").noneOf(validDirectoryIds).delete(),
|
filesystem.directory.where("id").noneOf(validDirectoryIds).delete(),
|
||||||
filesystem.file.where("id").noneOf(validFileIds).delete(),
|
filesystem.file.where("id").noneOf(validFileIds).delete(),
|
||||||
|
filesystem.category.where("id").noneOf(validCategoryIds).delete(),
|
||||||
]);
|
]);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -46,6 +46,56 @@ export const exportRSAKeyToBase64 = async (key: CryptoKey) => {
|
|||||||
return encodeToBase64((await exportRSAKey(key)).key);
|
return encodeToBase64((await exportRSAKey(key)).key);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const importEncryptionKeyPairFromBase64 = async (
|
||||||
|
encryptKeyBase64: string,
|
||||||
|
decryptKeyBase64: string,
|
||||||
|
) => {
|
||||||
|
const algorithm: RsaHashedImportParams = {
|
||||||
|
name: "RSA-OAEP",
|
||||||
|
hash: "SHA-256",
|
||||||
|
};
|
||||||
|
const encryptKey = await window.crypto.subtle.importKey(
|
||||||
|
"spki",
|
||||||
|
decodeFromBase64(encryptKeyBase64),
|
||||||
|
algorithm,
|
||||||
|
true,
|
||||||
|
["encrypt", "wrapKey"],
|
||||||
|
);
|
||||||
|
const decryptKey = await window.crypto.subtle.importKey(
|
||||||
|
"pkcs8",
|
||||||
|
decodeFromBase64(decryptKeyBase64),
|
||||||
|
algorithm,
|
||||||
|
true,
|
||||||
|
["decrypt", "unwrapKey"],
|
||||||
|
);
|
||||||
|
return { encryptKey, decryptKey };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const importSigningKeyPairFromBase64 = async (
|
||||||
|
signKeyBase64: string,
|
||||||
|
verifyKeyBase64: string,
|
||||||
|
) => {
|
||||||
|
const algorithm: RsaHashedImportParams = {
|
||||||
|
name: "RSA-PSS",
|
||||||
|
hash: "SHA-256",
|
||||||
|
};
|
||||||
|
const signKey = await window.crypto.subtle.importKey(
|
||||||
|
"pkcs8",
|
||||||
|
decodeFromBase64(signKeyBase64),
|
||||||
|
algorithm,
|
||||||
|
true,
|
||||||
|
["sign"],
|
||||||
|
);
|
||||||
|
const verifyKey = await window.crypto.subtle.importKey(
|
||||||
|
"spki",
|
||||||
|
decodeFromBase64(verifyKeyBase64),
|
||||||
|
algorithm,
|
||||||
|
true,
|
||||||
|
["verify"],
|
||||||
|
);
|
||||||
|
return { signKey, verifyKey };
|
||||||
|
};
|
||||||
|
|
||||||
export const makeRSAKeyNonextractable = async (key: CryptoKey) => {
|
export const makeRSAKeyNonextractable = async (key: CryptoKey) => {
|
||||||
const { key: exportedKey, format } = await exportRSAKey(key);
|
const { key: exportedKey, format } = await exportRSAKey(key);
|
||||||
return await window.crypto.subtle.importKey(
|
return await window.crypto.subtle.importKey(
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
|
import { LRUCache } from "lru-cache";
|
||||||
import {
|
import {
|
||||||
getFileCacheIndex as getFileCacheIndexFromIndexedDB,
|
getFileCacheIndex as getFileCacheIndexFromIndexedDB,
|
||||||
storeFileCacheIndex,
|
storeFileCacheIndex,
|
||||||
deleteFileCacheIndex,
|
deleteFileCacheIndex,
|
||||||
type FileCacheIndex,
|
type FileCacheIndex,
|
||||||
} from "$lib/indexedDB";
|
} from "$lib/indexedDB";
|
||||||
import { readFile, writeFile, deleteFile } from "$lib/modules/opfs";
|
import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs";
|
||||||
|
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
||||||
|
|
||||||
const fileCacheIndex = new Map<number, FileCacheIndex>();
|
const fileCacheIndex = new Map<number, FileCacheIndex>();
|
||||||
|
const loadedThumbnails = new LRUCache<number, string>({ max: 100 });
|
||||||
|
|
||||||
export const prepareFileCache = async () => {
|
export const prepareFileCache = async () => {
|
||||||
for (const cache of await getFileCacheIndexFromIndexedDB()) {
|
for (const cache of await getFileCacheIndexFromIndexedDB()) {
|
||||||
@@ -48,3 +51,30 @@ export const deleteFileCache = async (fileId: number) => {
|
|||||||
await deleteFile(`/cache/${fileId}`);
|
await deleteFile(`/cache/${fileId}`);
|
||||||
await deleteFileCacheIndex(fileId);
|
await deleteFileCacheIndex(fileId);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getFileThumbnailCache = async (fileId: number) => {
|
||||||
|
const thumbnail = loadedThumbnails.get(fileId);
|
||||||
|
if (thumbnail) return thumbnail;
|
||||||
|
|
||||||
|
const thumbnailBuffer = await readFile(`/thumbnail/file/${fileId}`);
|
||||||
|
if (!thumbnailBuffer) return null;
|
||||||
|
|
||||||
|
const thumbnailUrl = getThumbnailUrl(thumbnailBuffer);
|
||||||
|
loadedThumbnails.set(fileId, thumbnailUrl);
|
||||||
|
return thumbnailUrl;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const storeFileThumbnailCache = async (fileId: number, thumbnailBuffer: ArrayBuffer) => {
|
||||||
|
await writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
|
||||||
|
loadedThumbnails.set(fileId, getThumbnailUrl(thumbnailBuffer));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteFileThumbnailCache = async (fileId: number) => {
|
||||||
|
loadedThumbnails.delete(fileId);
|
||||||
|
await deleteFile(`/thumbnail/file/${fileId}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteAllFileThumbnailCaches = async () => {
|
||||||
|
loadedThumbnails.clear();
|
||||||
|
await deleteDirectory("/thumbnail/file");
|
||||||
|
};
|
||||||
|
|||||||
95
src/lib/modules/file/download.svelte.ts
Normal file
95
src/lib/modules/file/download.svelte.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { limitFunction } from "p-limit";
|
||||||
|
import { decryptData } from "$lib/modules/crypto";
|
||||||
|
|
||||||
|
export interface FileDownloadState {
|
||||||
|
id: number;
|
||||||
|
status:
|
||||||
|
| "download-pending"
|
||||||
|
| "downloading"
|
||||||
|
| "decryption-pending"
|
||||||
|
| "decrypting"
|
||||||
|
| "decrypted"
|
||||||
|
| "canceled"
|
||||||
|
| "error";
|
||||||
|
progress?: number;
|
||||||
|
rate?: number;
|
||||||
|
estimated?: number;
|
||||||
|
result?: ArrayBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LiveFileDownloadState = FileDownloadState & {
|
||||||
|
status: "download-pending" | "downloading" | "decryption-pending" | "decrypting";
|
||||||
|
};
|
||||||
|
|
||||||
|
let downloadingFiles: FileDownloadState[] = $state([]);
|
||||||
|
|
||||||
|
export const isFileDownloading = (
|
||||||
|
status: FileDownloadState["status"],
|
||||||
|
): status is LiveFileDownloadState["status"] =>
|
||||||
|
["download-pending", "downloading", "decryption-pending", "decrypting"].includes(status);
|
||||||
|
|
||||||
|
export const getFileDownloadState = (fileId: number) => {
|
||||||
|
return downloadingFiles.find((file) => file.id === fileId && isFileDownloading(file.status));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getDownloadingFiles = () => {
|
||||||
|
return downloadingFiles.filter((file) => isFileDownloading(file.status));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const clearDownloadedFiles = () => {
|
||||||
|
downloadingFiles = downloadingFiles.filter((file) => isFileDownloading(file.status));
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestFileDownload = limitFunction(
|
||||||
|
async (state: FileDownloadState, id: number) => {
|
||||||
|
state.status = "downloading";
|
||||||
|
|
||||||
|
const res = await axios.get(`/api/file/${id}/download`, {
|
||||||
|
responseType: "arraybuffer",
|
||||||
|
onDownloadProgress: ({ progress, rate, estimated }) => {
|
||||||
|
state.progress = progress;
|
||||||
|
state.rate = rate;
|
||||||
|
state.estimated = estimated;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const fileEncrypted: ArrayBuffer = res.data;
|
||||||
|
|
||||||
|
state.status = "decryption-pending";
|
||||||
|
return fileEncrypted;
|
||||||
|
},
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const decryptFile = limitFunction(
|
||||||
|
async (
|
||||||
|
state: FileDownloadState,
|
||||||
|
fileEncrypted: ArrayBuffer,
|
||||||
|
fileEncryptedIv: string,
|
||||||
|
dataKey: CryptoKey,
|
||||||
|
) => {
|
||||||
|
state.status = "decrypting";
|
||||||
|
|
||||||
|
const fileBuffer = await decryptData(fileEncrypted, fileEncryptedIv, dataKey);
|
||||||
|
|
||||||
|
state.status = "decrypted";
|
||||||
|
state.result = fileBuffer;
|
||||||
|
return fileBuffer;
|
||||||
|
},
|
||||||
|
{ concurrency: 4 },
|
||||||
|
);
|
||||||
|
|
||||||
|
export const downloadFile = async (id: number, fileEncryptedIv: string, dataKey: CryptoKey) => {
|
||||||
|
downloadingFiles.push({
|
||||||
|
id,
|
||||||
|
status: "download-pending",
|
||||||
|
});
|
||||||
|
const state = downloadingFiles.at(-1)!;
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await decryptFile(state, await requestFileDownload(state, id), fileEncryptedIv, dataKey);
|
||||||
|
} catch (e) {
|
||||||
|
state.status = "error";
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import axios from "axios";
|
|
||||||
import { limitFunction } from "p-limit";
|
|
||||||
import { writable, type Writable } from "svelte/store";
|
|
||||||
import { decryptData } from "$lib/modules/crypto";
|
|
||||||
import { fileDownloadStatusStore, type FileDownloadStatus } from "$lib/stores";
|
|
||||||
|
|
||||||
const requestFileDownload = limitFunction(
|
|
||||||
async (status: Writable<FileDownloadStatus>, id: number) => {
|
|
||||||
status.update((value) => {
|
|
||||||
value.status = "downloading";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await axios.get(`/api/file/${id}/download`, {
|
|
||||||
responseType: "arraybuffer",
|
|
||||||
onDownloadProgress: ({ progress, rate, estimated }) => {
|
|
||||||
status.update((value) => {
|
|
||||||
value.progress = progress;
|
|
||||||
value.rate = rate;
|
|
||||||
value.estimated = estimated;
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const fileEncrypted: ArrayBuffer = res.data;
|
|
||||||
|
|
||||||
status.update((value) => {
|
|
||||||
value.status = "decryption-pending";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
return fileEncrypted;
|
|
||||||
},
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
|
|
||||||
const decryptFile = limitFunction(
|
|
||||||
async (
|
|
||||||
status: Writable<FileDownloadStatus>,
|
|
||||||
fileEncrypted: ArrayBuffer,
|
|
||||||
fileEncryptedIv: string,
|
|
||||||
dataKey: CryptoKey,
|
|
||||||
) => {
|
|
||||||
status.update((value) => {
|
|
||||||
value.status = "decrypting";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
const fileBuffer = await decryptData(fileEncrypted, fileEncryptedIv, dataKey);
|
|
||||||
|
|
||||||
status.update((value) => {
|
|
||||||
value.status = "decrypted";
|
|
||||||
value.result = fileBuffer;
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
return fileBuffer;
|
|
||||||
},
|
|
||||||
{ concurrency: 4 },
|
|
||||||
);
|
|
||||||
|
|
||||||
export const downloadFile = async (id: number, fileEncryptedIv: string, dataKey: CryptoKey) => {
|
|
||||||
const status = writable<FileDownloadStatus>({
|
|
||||||
id,
|
|
||||||
status: "download-pending",
|
|
||||||
});
|
|
||||||
fileDownloadStatusStore.update((value) => {
|
|
||||||
value.push(status);
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await decryptFile(
|
|
||||||
status,
|
|
||||||
await requestFileDownload(status, id),
|
|
||||||
fileEncryptedIv,
|
|
||||||
dataKey,
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
status.update((value) => {
|
|
||||||
value.status = "error";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
export * from "./cache";
|
export * from "./cache";
|
||||||
export * from "./download";
|
export * from "./download.svelte";
|
||||||
export * from "./upload";
|
export * from "./upload.svelte";
|
||||||
|
|||||||
@@ -1,38 +1,69 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import ExifReader from "exifreader";
|
import ExifReader from "exifreader";
|
||||||
import { limitFunction } from "p-limit";
|
import { limitFunction } from "p-limit";
|
||||||
import { writable, type Writable } from "svelte/store";
|
|
||||||
import {
|
import {
|
||||||
encodeToBase64,
|
encodeToBase64,
|
||||||
generateDataKey,
|
generateDataKey,
|
||||||
wrapDataKey,
|
wrapDataKey,
|
||||||
encryptData,
|
encryptData,
|
||||||
encryptString,
|
encryptString,
|
||||||
|
digestMessage,
|
||||||
signMessageHmac,
|
signMessageHmac,
|
||||||
} from "$lib/modules/crypto";
|
} from "$lib/modules/crypto";
|
||||||
|
import { generateThumbnail } from "$lib/modules/thumbnail";
|
||||||
import type {
|
import type {
|
||||||
DuplicateFileScanRequest,
|
FileThumbnailUploadRequest,
|
||||||
DuplicateFileScanResponse,
|
|
||||||
FileUploadRequest,
|
FileUploadRequest,
|
||||||
|
FileUploadResponse,
|
||||||
} from "$lib/server/schemas";
|
} from "$lib/server/schemas";
|
||||||
import {
|
import type { MasterKey, HmacSecret } from "$lib/stores";
|
||||||
fileUploadStatusStore,
|
import { trpc } from "$trpc/client";
|
||||||
type MasterKey,
|
|
||||||
type HmacSecret,
|
export interface FileUploadState {
|
||||||
type FileUploadStatus,
|
name: string;
|
||||||
} from "$lib/stores";
|
parentId: DirectoryId;
|
||||||
|
status:
|
||||||
|
| "encryption-pending"
|
||||||
|
| "encrypting"
|
||||||
|
| "upload-pending"
|
||||||
|
| "uploading"
|
||||||
|
| "uploaded"
|
||||||
|
| "canceled"
|
||||||
|
| "error";
|
||||||
|
progress?: number;
|
||||||
|
rate?: number;
|
||||||
|
estimated?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LiveFileUploadState = FileUploadState & {
|
||||||
|
status: "encryption-pending" | "encrypting" | "upload-pending" | "uploading";
|
||||||
|
};
|
||||||
|
|
||||||
|
let uploadingFiles: FileUploadState[] = $state([]);
|
||||||
|
|
||||||
|
const isFileUploading = (status: FileUploadState["status"]) =>
|
||||||
|
["encryption-pending", "encrypting", "upload-pending", "uploading"].includes(status);
|
||||||
|
|
||||||
|
export const getUploadingFiles = (parentId?: DirectoryId) => {
|
||||||
|
return uploadingFiles.filter(
|
||||||
|
(file): file is LiveFileUploadState =>
|
||||||
|
(parentId === undefined || file.parentId === parentId) && isFileUploading(file.status),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const clearUploadedFiles = () => {
|
||||||
|
uploadingFiles = uploadingFiles.filter((file) => isFileUploading(file.status));
|
||||||
|
};
|
||||||
|
|
||||||
const requestDuplicateFileScan = limitFunction(
|
const requestDuplicateFileScan = limitFunction(
|
||||||
async (file: File, hmacSecret: HmacSecret, onDuplicate: () => Promise<boolean>) => {
|
async (file: File, hmacSecret: HmacSecret, onDuplicate: () => Promise<boolean>) => {
|
||||||
const fileBuffer = await file.arrayBuffer();
|
const fileBuffer = await file.arrayBuffer();
|
||||||
const fileSigned = encodeToBase64(await signMessageHmac(fileBuffer, hmacSecret.secret));
|
const fileSigned = encodeToBase64(await signMessageHmac(fileBuffer, hmacSecret.secret));
|
||||||
|
|
||||||
const res = await axios.post("/api/file/scanDuplicates", {
|
const files = await trpc().file.listByHash.query({
|
||||||
hskVersion: hmacSecret.version,
|
hskVersion: hmacSecret.version,
|
||||||
contentHmac: fileSigned,
|
contentHmac: fileSigned,
|
||||||
} satisfies DuplicateFileScanRequest);
|
});
|
||||||
const { files }: DuplicateFileScanResponse = res.data;
|
|
||||||
|
|
||||||
if (files.length === 0 || (await onDuplicate())) {
|
if (files.length === 0 || (await onDuplicate())) {
|
||||||
return { fileBuffer, fileSigned };
|
return { fileBuffer, fileSigned };
|
||||||
} else {
|
} else {
|
||||||
@@ -75,16 +106,8 @@ const extractExifDateTime = (fileBuffer: ArrayBuffer) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const encryptFile = limitFunction(
|
const encryptFile = limitFunction(
|
||||||
async (
|
async (state: FileUploadState, file: File, fileBuffer: ArrayBuffer, masterKey: MasterKey) => {
|
||||||
status: Writable<FileUploadStatus>,
|
state.status = "encrypting";
|
||||||
file: File,
|
|
||||||
fileBuffer: ArrayBuffer,
|
|
||||||
masterKey: MasterKey,
|
|
||||||
) => {
|
|
||||||
status.update((value) => {
|
|
||||||
value.status = "encrypting";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
const fileType = getFileType(file);
|
const fileType = getFileType(file);
|
||||||
|
|
||||||
@@ -97,51 +120,59 @@ const encryptFile = limitFunction(
|
|||||||
const dataKeyWrapped = await wrapDataKey(dataKey, masterKey.key);
|
const dataKeyWrapped = await wrapDataKey(dataKey, masterKey.key);
|
||||||
|
|
||||||
const fileEncrypted = await encryptData(fileBuffer, dataKey);
|
const fileEncrypted = await encryptData(fileBuffer, dataKey);
|
||||||
|
const fileEncryptedHash = encodeToBase64(await digestMessage(fileEncrypted.ciphertext));
|
||||||
|
|
||||||
const nameEncrypted = await encryptString(file.name, dataKey);
|
const nameEncrypted = await encryptString(file.name, dataKey);
|
||||||
const createdAtEncrypted =
|
const createdAtEncrypted =
|
||||||
createdAt && (await encryptString(createdAt.getTime().toString(), dataKey));
|
createdAt && (await encryptString(createdAt.getTime().toString(), dataKey));
|
||||||
const lastModifiedAtEncrypted = await encryptString(file.lastModified.toString(), dataKey);
|
const lastModifiedAtEncrypted = await encryptString(file.lastModified.toString(), dataKey);
|
||||||
|
|
||||||
status.update((value) => {
|
const thumbnail = await generateThumbnail(fileBuffer, fileType);
|
||||||
value.status = "upload-pending";
|
const thumbnailBuffer = await thumbnail?.arrayBuffer();
|
||||||
return value;
|
const thumbnailEncrypted = thumbnailBuffer && (await encryptData(thumbnailBuffer, dataKey));
|
||||||
});
|
|
||||||
|
state.status = "upload-pending";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
dataKeyWrapped,
|
dataKeyWrapped,
|
||||||
dataKeyVersion,
|
dataKeyVersion,
|
||||||
fileEncrypted,
|
|
||||||
fileType,
|
fileType,
|
||||||
|
fileEncrypted,
|
||||||
|
fileEncryptedHash,
|
||||||
nameEncrypted,
|
nameEncrypted,
|
||||||
createdAtEncrypted,
|
createdAtEncrypted,
|
||||||
lastModifiedAtEncrypted,
|
lastModifiedAtEncrypted,
|
||||||
|
thumbnail: thumbnailEncrypted && { plaintext: thumbnailBuffer, ...thumbnailEncrypted },
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
{ concurrency: 4 },
|
{ concurrency: 4 },
|
||||||
);
|
);
|
||||||
|
|
||||||
const requestFileUpload = limitFunction(
|
const requestFileUpload = limitFunction(
|
||||||
async (status: Writable<FileUploadStatus>, form: FormData) => {
|
async (state: FileUploadState, form: FormData, thumbnailForm: FormData | null) => {
|
||||||
status.update((value) => {
|
state.status = "uploading";
|
||||||
value.status = "uploading";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
await axios.post("/api/file/upload", form, {
|
const res = await axios.post("/api/file/upload", form, {
|
||||||
onUploadProgress: ({ progress, rate, estimated }) => {
|
onUploadProgress: ({ progress, rate, estimated }) => {
|
||||||
status.update((value) => {
|
state.progress = progress;
|
||||||
value.progress = progress;
|
state.rate = rate;
|
||||||
value.rate = rate;
|
state.estimated = estimated;
|
||||||
value.estimated = estimated;
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const { file }: FileUploadResponse = res.data;
|
||||||
|
|
||||||
status.update((value) => {
|
if (thumbnailForm) {
|
||||||
value.status = "uploaded";
|
try {
|
||||||
return value;
|
await axios.post(`/api/file/${file}/thumbnail/upload`, thumbnailForm);
|
||||||
});
|
} catch (e) {
|
||||||
|
// TODO
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
state.status = "uploaded";
|
||||||
|
|
||||||
|
return { fileId: file };
|
||||||
},
|
},
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
);
|
);
|
||||||
@@ -152,16 +183,15 @@ export const uploadFile = async (
|
|||||||
hmacSecret: HmacSecret,
|
hmacSecret: HmacSecret,
|
||||||
masterKey: MasterKey,
|
masterKey: MasterKey,
|
||||||
onDuplicate: () => Promise<boolean>,
|
onDuplicate: () => Promise<boolean>,
|
||||||
) => {
|
): Promise<
|
||||||
const status = writable<FileUploadStatus>({
|
{ fileId: number; fileBuffer: ArrayBuffer; thumbnailBuffer?: ArrayBuffer } | undefined
|
||||||
|
> => {
|
||||||
|
uploadingFiles.push({
|
||||||
name: file.name,
|
name: file.name,
|
||||||
parentId,
|
parentId,
|
||||||
status: "encryption-pending",
|
status: "encryption-pending",
|
||||||
});
|
});
|
||||||
fileUploadStatusStore.update((value) => {
|
const state = uploadingFiles.at(-1)!;
|
||||||
value.push(status);
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { fileBuffer, fileSigned } = await requestDuplicateFileScan(
|
const { fileBuffer, fileSigned } = await requestDuplicateFileScan(
|
||||||
@@ -170,26 +200,22 @@ export const uploadFile = async (
|
|||||||
onDuplicate,
|
onDuplicate,
|
||||||
);
|
);
|
||||||
if (!fileBuffer || !fileSigned) {
|
if (!fileBuffer || !fileSigned) {
|
||||||
status.update((value) => {
|
state.status = "canceled";
|
||||||
value.status = "canceled";
|
uploadingFiles = uploadingFiles.filter((file) => file !== state);
|
||||||
return value;
|
return undefined;
|
||||||
});
|
|
||||||
fileUploadStatusStore.update((value) => {
|
|
||||||
value = value.filter((v) => v !== status);
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
dataKeyWrapped,
|
dataKeyWrapped,
|
||||||
dataKeyVersion,
|
dataKeyVersion,
|
||||||
fileEncrypted,
|
|
||||||
fileType,
|
fileType,
|
||||||
|
fileEncrypted,
|
||||||
|
fileEncryptedHash,
|
||||||
nameEncrypted,
|
nameEncrypted,
|
||||||
createdAtEncrypted,
|
createdAtEncrypted,
|
||||||
lastModifiedAtEncrypted,
|
lastModifiedAtEncrypted,
|
||||||
} = await encryptFile(status, file, fileBuffer, masterKey);
|
thumbnail,
|
||||||
|
} = await encryptFile(state, file, fileBuffer, masterKey);
|
||||||
|
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.set(
|
form.set(
|
||||||
@@ -209,17 +235,28 @@ export const uploadFile = async (
|
|||||||
createdAtIv: createdAtEncrypted?.iv,
|
createdAtIv: createdAtEncrypted?.iv,
|
||||||
lastModifiedAt: lastModifiedAtEncrypted.ciphertext,
|
lastModifiedAt: lastModifiedAtEncrypted.ciphertext,
|
||||||
lastModifiedAtIv: lastModifiedAtEncrypted.iv,
|
lastModifiedAtIv: lastModifiedAtEncrypted.iv,
|
||||||
} as FileUploadRequest),
|
} satisfies FileUploadRequest),
|
||||||
);
|
);
|
||||||
form.set("content", new Blob([fileEncrypted.ciphertext]));
|
form.set("content", new Blob([fileEncrypted.ciphertext]));
|
||||||
|
form.set("checksum", fileEncryptedHash);
|
||||||
|
|
||||||
await requestFileUpload(status, form);
|
let thumbnailForm = null;
|
||||||
return true;
|
if (thumbnail) {
|
||||||
|
thumbnailForm = new FormData();
|
||||||
|
thumbnailForm.set(
|
||||||
|
"metadata",
|
||||||
|
JSON.stringify({
|
||||||
|
dekVersion: dataKeyVersion.toISOString(),
|
||||||
|
contentIv: thumbnail.iv,
|
||||||
|
} satisfies FileThumbnailUploadRequest),
|
||||||
|
);
|
||||||
|
thumbnailForm.set("content", new Blob([thumbnail.ciphertext]));
|
||||||
|
}
|
||||||
|
|
||||||
|
const { fileId } = await requestFileUpload(state, form, thumbnailForm);
|
||||||
|
return { fileId, fileBuffer, thumbnailBuffer: thumbnail?.plaintext };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
status.update((value) => {
|
state.status = "error";
|
||||||
value.status = "error";
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,206 +0,0 @@
|
|||||||
import { get, writable, type Writable } from "svelte/store";
|
|
||||||
import { callGetApi } from "$lib/hooks";
|
|
||||||
import {
|
|
||||||
getDirectoryInfos as getDirectoryInfosFromIndexedDB,
|
|
||||||
getDirectoryInfo as getDirectoryInfoFromIndexedDB,
|
|
||||||
storeDirectoryInfo,
|
|
||||||
deleteDirectoryInfo,
|
|
||||||
getFileInfos as getFileInfosFromIndexedDB,
|
|
||||||
getFileInfo as getFileInfoFromIndexedDB,
|
|
||||||
storeFileInfo,
|
|
||||||
deleteFileInfo,
|
|
||||||
type DirectoryId,
|
|
||||||
} from "$lib/indexedDB";
|
|
||||||
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
|
||||||
import type { DirectoryInfoResponse, FileInfoResponse } from "$lib/server/schemas";
|
|
||||||
|
|
||||||
export type DirectoryInfo =
|
|
||||||
| {
|
|
||||||
id: "root";
|
|
||||||
dataKey?: undefined;
|
|
||||||
dataKeyVersion?: undefined;
|
|
||||||
name?: undefined;
|
|
||||||
subDirectoryIds: number[];
|
|
||||||
fileIds: number[];
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
id: number;
|
|
||||||
dataKey?: CryptoKey;
|
|
||||||
dataKeyVersion?: Date;
|
|
||||||
name: string;
|
|
||||||
subDirectoryIds: number[];
|
|
||||||
fileIds: number[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface FileInfo {
|
|
||||||
id: number;
|
|
||||||
dataKey?: CryptoKey;
|
|
||||||
dataKeyVersion?: Date;
|
|
||||||
contentType: string;
|
|
||||||
contentIv?: string;
|
|
||||||
name: string;
|
|
||||||
createdAt?: Date;
|
|
||||||
lastModifiedAt: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
const directoryInfoStore = new Map<DirectoryId, Writable<DirectoryInfo | null>>();
|
|
||||||
const fileInfoStore = new Map<number, Writable<FileInfo | null>>();
|
|
||||||
|
|
||||||
const fetchDirectoryInfoFromIndexedDB = async (
|
|
||||||
id: DirectoryId,
|
|
||||||
info: Writable<DirectoryInfo | null>,
|
|
||||||
) => {
|
|
||||||
if (get(info)) return;
|
|
||||||
|
|
||||||
const [directory, subDirectories, files] = await Promise.all([
|
|
||||||
id !== "root" ? getDirectoryInfoFromIndexedDB(id) : undefined,
|
|
||||||
getDirectoryInfosFromIndexedDB(id),
|
|
||||||
getFileInfosFromIndexedDB(id),
|
|
||||||
]);
|
|
||||||
const subDirectoryIds = subDirectories.map(({ id }) => id);
|
|
||||||
const fileIds = files.map(({ id }) => id);
|
|
||||||
|
|
||||||
if (id === "root") {
|
|
||||||
info.set({ id, subDirectoryIds, fileIds });
|
|
||||||
} else {
|
|
||||||
if (!directory) return;
|
|
||||||
info.set({ id, name: directory.name, subDirectoryIds, fileIds });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchDirectoryInfoFromServer = async (
|
|
||||||
id: DirectoryId,
|
|
||||||
info: Writable<DirectoryInfo | null>,
|
|
||||||
masterKey: CryptoKey,
|
|
||||||
) => {
|
|
||||||
const res = await callGetApi(`/api/directory/${id}`);
|
|
||||||
if (res.status === 404) {
|
|
||||||
info.set(null);
|
|
||||||
await deleteDirectoryInfo(id as number);
|
|
||||||
} else if (!res.ok) {
|
|
||||||
throw new Error("Failed to fetch directory information");
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
metadata,
|
|
||||||
subDirectories: subDirectoryIds,
|
|
||||||
files: fileIds,
|
|
||||||
}: DirectoryInfoResponse = await res.json();
|
|
||||||
|
|
||||||
if (id === "root") {
|
|
||||||
info.set({ id, subDirectoryIds, fileIds });
|
|
||||||
} else {
|
|
||||||
const { dataKey } = await unwrapDataKey(metadata!.dek, masterKey);
|
|
||||||
const name = await decryptString(metadata!.name, metadata!.nameIv, dataKey);
|
|
||||||
|
|
||||||
info.set({
|
|
||||||
id,
|
|
||||||
dataKey,
|
|
||||||
dataKeyVersion: new Date(metadata!.dekVersion),
|
|
||||||
name,
|
|
||||||
subDirectoryIds,
|
|
||||||
fileIds,
|
|
||||||
});
|
|
||||||
await storeDirectoryInfo({ id, parentId: metadata!.parent, name });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchDirectoryInfo = async (
|
|
||||||
id: DirectoryId,
|
|
||||||
info: Writable<DirectoryInfo | null>,
|
|
||||||
masterKey: CryptoKey,
|
|
||||||
) => {
|
|
||||||
await fetchDirectoryInfoFromIndexedDB(id, info);
|
|
||||||
await fetchDirectoryInfoFromServer(id, info, masterKey);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getDirectoryInfo = (id: DirectoryId, masterKey: CryptoKey) => {
|
|
||||||
// TODO: MEK rotation
|
|
||||||
|
|
||||||
let info = directoryInfoStore.get(id);
|
|
||||||
if (!info) {
|
|
||||||
info = writable(null);
|
|
||||||
directoryInfoStore.set(id, info);
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchDirectoryInfo(id, info, masterKey);
|
|
||||||
return info;
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchFileInfoFromIndexedDB = async (id: number, info: Writable<FileInfo | null>) => {
|
|
||||||
if (get(info)) return;
|
|
||||||
|
|
||||||
const file = await getFileInfoFromIndexedDB(id);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
info.set(file);
|
|
||||||
};
|
|
||||||
|
|
||||||
const decryptDate = async (ciphertext: string, iv: string, dataKey: CryptoKey) => {
|
|
||||||
return new Date(parseInt(await decryptString(ciphertext, iv, dataKey), 10));
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchFileInfoFromServer = async (
|
|
||||||
id: number,
|
|
||||||
info: Writable<FileInfo | null>,
|
|
||||||
masterKey: CryptoKey,
|
|
||||||
) => {
|
|
||||||
const res = await callGetApi(`/api/file/${id}`);
|
|
||||||
if (res.status === 404) {
|
|
||||||
info.set(null);
|
|
||||||
await deleteFileInfo(id);
|
|
||||||
} else if (!res.ok) {
|
|
||||||
throw new Error("Failed to fetch file information");
|
|
||||||
}
|
|
||||||
|
|
||||||
const metadata: FileInfoResponse = await res.json();
|
|
||||||
const { dataKey } = await unwrapDataKey(metadata.dek, masterKey);
|
|
||||||
|
|
||||||
const name = await decryptString(metadata.name, metadata.nameIv, dataKey);
|
|
||||||
const createdAt =
|
|
||||||
metadata.createdAt && metadata.createdAtIv
|
|
||||||
? await decryptDate(metadata.createdAt, metadata.createdAtIv, dataKey)
|
|
||||||
: undefined;
|
|
||||||
const lastModifiedAt = await decryptDate(
|
|
||||||
metadata.lastModifiedAt,
|
|
||||||
metadata.lastModifiedAtIv,
|
|
||||||
dataKey,
|
|
||||||
);
|
|
||||||
|
|
||||||
info.set({
|
|
||||||
id,
|
|
||||||
dataKey,
|
|
||||||
dataKeyVersion: new Date(metadata.dekVersion),
|
|
||||||
contentType: metadata.contentType,
|
|
||||||
contentIv: metadata.contentIv,
|
|
||||||
name,
|
|
||||||
createdAt,
|
|
||||||
lastModifiedAt,
|
|
||||||
});
|
|
||||||
await storeFileInfo({
|
|
||||||
id,
|
|
||||||
parentId: metadata.parent,
|
|
||||||
name,
|
|
||||||
contentType: metadata.contentType,
|
|
||||||
createdAt,
|
|
||||||
lastModifiedAt,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchFileInfo = async (id: number, info: Writable<FileInfo | null>, masterKey: CryptoKey) => {
|
|
||||||
await fetchFileInfoFromIndexedDB(id, info);
|
|
||||||
await fetchFileInfoFromServer(id, info, masterKey);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileInfo = (fileId: number, masterKey: CryptoKey) => {
|
|
||||||
// TODO: MEK rotation
|
|
||||||
|
|
||||||
let info = fileInfoStore.get(fileId);
|
|
||||||
if (!info) {
|
|
||||||
info = writable(null);
|
|
||||||
fileInfoStore.set(fileId, info);
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchFileInfo(fileId, info, masterKey);
|
|
||||||
return info;
|
|
||||||
};
|
|
||||||
113
src/lib/modules/filesystem/category.ts
Normal file
113
src/lib/modules/filesystem/category.ts
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import * as IndexedDB from "$lib/indexedDB";
|
||||||
|
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||||
|
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
||||||
|
import type { MaybeCategoryInfo } from "./types";
|
||||||
|
|
||||||
|
const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo, Partial<MaybeCategoryInfo>>();
|
||||||
|
|
||||||
|
const fetchFromIndexedDB = async (id: CategoryId) => {
|
||||||
|
const [category, subCategories] = await Promise.all([
|
||||||
|
id !== "root" ? IndexedDB.getCategoryInfo(id) : undefined,
|
||||||
|
IndexedDB.getCategoryInfos(id),
|
||||||
|
]);
|
||||||
|
const files = category
|
||||||
|
? await Promise.all(
|
||||||
|
category.files.map(async (file) => {
|
||||||
|
const fileInfo = await IndexedDB.getFileInfo(file.id);
|
||||||
|
return fileInfo
|
||||||
|
? {
|
||||||
|
id: file.id,
|
||||||
|
contentType: fileInfo.contentType,
|
||||||
|
name: fileInfo.name,
|
||||||
|
createdAt: fileInfo.createdAt,
|
||||||
|
lastModifiedAt: fileInfo.lastModifiedAt,
|
||||||
|
isRecursive: file.isRecursive,
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (id === "root") {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
subCategories,
|
||||||
|
};
|
||||||
|
} else if (category) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
name: category.name,
|
||||||
|
subCategories,
|
||||||
|
files: files!.filter((file) => !!file),
|
||||||
|
isFileRecursive: category.isFileRecursive,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchFromServer = async (id: CategoryId, masterKey: CryptoKey) => {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
metadata,
|
||||||
|
subCategories: subCategoriesRaw,
|
||||||
|
files: filesRaw,
|
||||||
|
} = await trpc().category.get.query({ id });
|
||||||
|
const [subCategories, files] = await Promise.all([
|
||||||
|
Promise.all(
|
||||||
|
subCategoriesRaw.map(async (category) => ({
|
||||||
|
id: category.id,
|
||||||
|
...(await decryptCategoryMetadata(category, masterKey)),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
filesRaw
|
||||||
|
? Promise.all(
|
||||||
|
filesRaw.map(async (file) => ({
|
||||||
|
id: file.id,
|
||||||
|
contentType: file.contentType,
|
||||||
|
isRecursive: file.isRecursive,
|
||||||
|
...(await decryptFileMetadata(file, masterKey)),
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
: undefined,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (id === "root") {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
subCategories,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
subCategories,
|
||||||
|
files,
|
||||||
|
...(await decryptCategoryMetadata(metadata!, masterKey)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
|
await IndexedDB.deleteCategoryInfo(id as number);
|
||||||
|
return { id, exists: false as const };
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCategoryInfo = async (id: CategoryId, masterKey: CryptoKey) => {
|
||||||
|
return await cache.get(id, async (isInitial, resolve) => {
|
||||||
|
if (isInitial) {
|
||||||
|
const info = await fetchFromIndexedDB(id);
|
||||||
|
if (info) {
|
||||||
|
resolve(info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const info = await fetchFromServer(id, masterKey);
|
||||||
|
if (info) {
|
||||||
|
resolve(info);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
91
src/lib/modules/filesystem/directory.ts
Normal file
91
src/lib/modules/filesystem/directory.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import * as IndexedDB from "$lib/indexedDB";
|
||||||
|
import { monotonicResolve } from "$lib/utils";
|
||||||
|
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||||
|
import { FilesystemCache, decryptDirectoryMetadata, decryptFileMetadata } from "./internal.svelte";
|
||||||
|
import type { MaybeDirectoryInfo } from "./types";
|
||||||
|
|
||||||
|
const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>();
|
||||||
|
|
||||||
|
const fetchFromIndexedDB = async (id: DirectoryId) => {
|
||||||
|
const [directory, subDirectories, files] = await Promise.all([
|
||||||
|
id !== "root" ? IndexedDB.getDirectoryInfo(id) : undefined,
|
||||||
|
IndexedDB.getDirectoryInfos(id),
|
||||||
|
IndexedDB.getFileInfos(id),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (id === "root") {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
subDirectories,
|
||||||
|
files,
|
||||||
|
};
|
||||||
|
} else if (directory) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
parentId: directory.parentId,
|
||||||
|
name: directory.name,
|
||||||
|
subDirectories,
|
||||||
|
files,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchFromServer = async (id: DirectoryId, masterKey: CryptoKey) => {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
metadata,
|
||||||
|
subDirectories: subDirectoriesRaw,
|
||||||
|
files: filesRaw,
|
||||||
|
} = await trpc().directory.get.query({ id });
|
||||||
|
const [subDirectories, files] = await Promise.all([
|
||||||
|
Promise.all(
|
||||||
|
subDirectoriesRaw.map(async (directory) => ({
|
||||||
|
id: directory.id,
|
||||||
|
...(await decryptDirectoryMetadata(directory, masterKey)),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
Promise.all(
|
||||||
|
filesRaw.map(async (file) => ({
|
||||||
|
id: file.id,
|
||||||
|
contentType: file.contentType,
|
||||||
|
...(await decryptFileMetadata(file, masterKey)),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (id === "root") {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
subDirectories,
|
||||||
|
files,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
parentId: metadata!.parent,
|
||||||
|
subDirectories,
|
||||||
|
files,
|
||||||
|
...(await decryptDirectoryMetadata(metadata!, masterKey)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
|
await IndexedDB.deleteDirectoryInfo(id as number);
|
||||||
|
return { id, exists: false as const };
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getDirectoryInfo = async (id: DirectoryId, masterKey: CryptoKey) => {
|
||||||
|
return await cache.get(id, (isInitial, resolve) =>
|
||||||
|
monotonicResolve(
|
||||||
|
[isInitial && fetchFromIndexedDB(id), fetchFromServer(id, masterKey)],
|
||||||
|
resolve,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
151
src/lib/modules/filesystem/file.ts
Normal file
151
src/lib/modules/filesystem/file.ts
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
import * as IndexedDB from "$lib/indexedDB";
|
||||||
|
import { monotonicResolve } from "$lib/utils";
|
||||||
|
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||||
|
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
||||||
|
import type { MaybeFileInfo } from "./types";
|
||||||
|
|
||||||
|
const cache = new FilesystemCache<number, MaybeFileInfo>();
|
||||||
|
|
||||||
|
const fetchFromIndexedDB = async (id: number) => {
|
||||||
|
const file = await IndexedDB.getFileInfo(id);
|
||||||
|
const categories = file
|
||||||
|
? await Promise.all(
|
||||||
|
file.categoryIds.map(async (categoryId) => {
|
||||||
|
const category = await IndexedDB.getCategoryInfo(categoryId);
|
||||||
|
return category ? { id: category.id, name: category.name } : undefined;
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (file) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
parentId: file.parentId,
|
||||||
|
contentType: file.contentType,
|
||||||
|
name: file.name,
|
||||||
|
createdAt: file.createdAt,
|
||||||
|
lastModifiedAt: file.lastModifiedAt,
|
||||||
|
categories: categories!.filter((category) => !!category),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const bulkFetchFromIndexedDB = async (ids: number[]) => {
|
||||||
|
const files = await IndexedDB.bulkGetFileInfos(ids);
|
||||||
|
const categories = await Promise.all(
|
||||||
|
files.map(async (file) =>
|
||||||
|
file
|
||||||
|
? await Promise.all(
|
||||||
|
file.categoryIds.map(async (categoryId) => {
|
||||||
|
const category = await IndexedDB.getCategoryInfo(categoryId);
|
||||||
|
return category ? { id: category.id, name: category.name } : undefined;
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
: undefined,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return new Map(
|
||||||
|
files
|
||||||
|
.map((file, index) =>
|
||||||
|
file
|
||||||
|
? ([
|
||||||
|
file.id,
|
||||||
|
{
|
||||||
|
...file,
|
||||||
|
exists: true,
|
||||||
|
categories: categories[index]!.filter((category) => !!category),
|
||||||
|
},
|
||||||
|
] as const)
|
||||||
|
: undefined,
|
||||||
|
)
|
||||||
|
.filter((file) => !!file),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchFromServer = async (id: number, masterKey: CryptoKey) => {
|
||||||
|
try {
|
||||||
|
const { categories: categoriesRaw, ...metadata } = await trpc().file.get.query({ id });
|
||||||
|
const [categories] = await Promise.all([
|
||||||
|
Promise.all(
|
||||||
|
categoriesRaw.map(async (category) => ({
|
||||||
|
id: category.id,
|
||||||
|
...(await decryptCategoryMetadata(category, masterKey)),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
exists: true as const,
|
||||||
|
parentId: metadata.parent,
|
||||||
|
contentType: metadata.contentType,
|
||||||
|
contentIv: metadata.contentIv,
|
||||||
|
categories,
|
||||||
|
...(await decryptFileMetadata(metadata, masterKey)),
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
|
await IndexedDB.deleteFileInfo(id);
|
||||||
|
return { id, exists: false as const };
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const bulkFetchFromServer = async (ids: number[], masterKey: CryptoKey) => {
|
||||||
|
const filesRaw = await trpc().file.bulkGet.query({ ids });
|
||||||
|
const files = await Promise.all(
|
||||||
|
filesRaw.map(async (file) => {
|
||||||
|
const categories = await Promise.all(
|
||||||
|
file.categories.map(async (category) => ({
|
||||||
|
id: category.id,
|
||||||
|
...(await decryptCategoryMetadata(category, masterKey)),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
id: file.id,
|
||||||
|
exists: true as const,
|
||||||
|
parentId: file.parent,
|
||||||
|
contentType: file.contentType,
|
||||||
|
contentIv: file.contentIv,
|
||||||
|
categories,
|
||||||
|
...(await decryptFileMetadata(file, masterKey)),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const existingIds = new Set(filesRaw.map(({ id }) => id));
|
||||||
|
return new Map<number, MaybeFileInfo>([
|
||||||
|
...files.map((file) => [file.id, file] as const),
|
||||||
|
...ids.filter((id) => !existingIds.has(id)).map((id) => [id, { id, exists: false }] as const),
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getFileInfo = async (id: number, masterKey: CryptoKey) => {
|
||||||
|
return await cache.get(id, (isInitial, resolve) =>
|
||||||
|
monotonicResolve(
|
||||||
|
[isInitial && fetchFromIndexedDB(id), fetchFromServer(id, masterKey)],
|
||||||
|
resolve,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const bulkGetFileInfo = async (ids: number[], masterKey: CryptoKey) => {
|
||||||
|
return await cache.bulkGet(new Set(ids), (keys, resolve) =>
|
||||||
|
monotonicResolve(
|
||||||
|
[
|
||||||
|
bulkFetchFromIndexedDB(
|
||||||
|
Array.from(
|
||||||
|
keys
|
||||||
|
.entries()
|
||||||
|
.filter(([, isInitial]) => isInitial)
|
||||||
|
.map(([key]) => key),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
bulkFetchFromServer(Array.from(keys.keys()), masterKey),
|
||||||
|
],
|
||||||
|
resolve,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
4
src/lib/modules/filesystem/index.ts
Normal file
4
src/lib/modules/filesystem/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export * from "./category";
|
||||||
|
export * from "./directory";
|
||||||
|
export * from "./file";
|
||||||
|
export * from "./types";
|
||||||
130
src/lib/modules/filesystem/internal.svelte.ts
Normal file
130
src/lib/modules/filesystem/internal.svelte.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
||||||
|
|
||||||
|
export class FilesystemCache<K, V extends RV, RV = V> {
|
||||||
|
private map = new Map<K, V | Promise<V>>();
|
||||||
|
|
||||||
|
get(key: K, loader: (isInitial: boolean, resolve: (value: RV | undefined) => void) => void) {
|
||||||
|
const info = this.map.get(key);
|
||||||
|
if (info instanceof Promise) {
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { promise, resolve } = Promise.withResolvers<V>();
|
||||||
|
if (!info) {
|
||||||
|
this.map.set(key, promise);
|
||||||
|
}
|
||||||
|
|
||||||
|
loader(!info, (loadedInfo) => {
|
||||||
|
if (!loadedInfo) return;
|
||||||
|
|
||||||
|
const info = this.map.get(key)!;
|
||||||
|
if (info instanceof Promise) {
|
||||||
|
const state = $state(loadedInfo);
|
||||||
|
this.map.set(key, state as V);
|
||||||
|
resolve(state as V);
|
||||||
|
} else {
|
||||||
|
Object.assign(info, loadedInfo);
|
||||||
|
resolve(info);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return info ?? promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
async bulkGet(
|
||||||
|
keys: Set<K>,
|
||||||
|
loader: (keys: Map<K, boolean>, resolve: (values: Map<K, RV>) => void) => void,
|
||||||
|
) {
|
||||||
|
const states = new Map<K, V>();
|
||||||
|
const promises = new Map<K, Promise<V>>();
|
||||||
|
const resolvers = new Map<K, (value: V) => void>();
|
||||||
|
|
||||||
|
keys.forEach((key) => {
|
||||||
|
const info = this.map.get(key);
|
||||||
|
if (info instanceof Promise) {
|
||||||
|
promises.set(key, info);
|
||||||
|
} else if (info) {
|
||||||
|
states.set(key, info);
|
||||||
|
} else {
|
||||||
|
const { promise, resolve } = Promise.withResolvers<V>();
|
||||||
|
this.map.set(key, promise);
|
||||||
|
promises.set(key, promise);
|
||||||
|
resolvers.set(key, resolve);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
loader(
|
||||||
|
new Map([
|
||||||
|
...states.keys().map((key) => [key, false] as const),
|
||||||
|
...resolvers.keys().map((key) => [key, true] as const),
|
||||||
|
]),
|
||||||
|
(loadedInfos) =>
|
||||||
|
loadedInfos.forEach((loadedInfo, key) => {
|
||||||
|
const info = this.map.get(key)!;
|
||||||
|
const resolve = resolvers.get(key);
|
||||||
|
if (info instanceof Promise) {
|
||||||
|
const state = $state(loadedInfo);
|
||||||
|
this.map.set(key, state as V);
|
||||||
|
resolve?.(state as V);
|
||||||
|
} else {
|
||||||
|
Object.assign(info, loadedInfo);
|
||||||
|
resolve?.(info);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const newStates = await Promise.all(
|
||||||
|
promises.entries().map(async ([key, promise]) => [key, await promise] as const),
|
||||||
|
);
|
||||||
|
return new Map([...states, ...newStates]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const decryptDirectoryMetadata = async (
|
||||||
|
metadata: { dek: string; dekVersion: Date; name: string; nameIv: string },
|
||||||
|
masterKey: CryptoKey,
|
||||||
|
) => {
|
||||||
|
const { dataKey } = await unwrapDataKey(metadata.dek, masterKey);
|
||||||
|
const name = await decryptString(metadata.name, metadata.nameIv, dataKey);
|
||||||
|
|
||||||
|
return {
|
||||||
|
dataKey: { key: dataKey, version: metadata.dekVersion },
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const decryptDate = async (ciphertext: string, iv: string, dataKey: CryptoKey) => {
|
||||||
|
return new Date(parseInt(await decryptString(ciphertext, iv, dataKey), 10));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const decryptFileMetadata = async (
|
||||||
|
metadata: {
|
||||||
|
dek: string;
|
||||||
|
dekVersion: Date;
|
||||||
|
name: string;
|
||||||
|
nameIv: string;
|
||||||
|
createdAt?: string;
|
||||||
|
createdAtIv?: string;
|
||||||
|
lastModifiedAt: string;
|
||||||
|
lastModifiedAtIv: string;
|
||||||
|
},
|
||||||
|
masterKey: CryptoKey,
|
||||||
|
) => {
|
||||||
|
const { dataKey } = await unwrapDataKey(metadata.dek, masterKey);
|
||||||
|
const [name, createdAt, lastModifiedAt] = await Promise.all([
|
||||||
|
decryptString(metadata.name, metadata.nameIv, dataKey),
|
||||||
|
metadata.createdAt
|
||||||
|
? decryptDate(metadata.createdAt, metadata.createdAtIv!, dataKey)
|
||||||
|
: undefined,
|
||||||
|
decryptDate(metadata.lastModifiedAt, metadata.lastModifiedAtIv, dataKey),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
dataKey: { key: dataKey, version: metadata.dekVersion },
|
||||||
|
name,
|
||||||
|
createdAt,
|
||||||
|
lastModifiedAt,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const decryptCategoryMetadata = decryptDirectoryMetadata;
|
||||||
71
src/lib/modules/filesystem/types.ts
Normal file
71
src/lib/modules/filesystem/types.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
export type DataKey = { key: CryptoKey; version: Date };
|
||||||
|
type AllUndefined<T> = { [K in keyof T]?: undefined };
|
||||||
|
|
||||||
|
interface LocalDirectoryInfo {
|
||||||
|
id: number;
|
||||||
|
parentId: DirectoryId;
|
||||||
|
dataKey?: DataKey;
|
||||||
|
name: string;
|
||||||
|
subDirectories: SubDirectoryInfo[];
|
||||||
|
files: SummarizedFileInfo[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RootDirectoryInfo {
|
||||||
|
id: "root";
|
||||||
|
parentId?: undefined;
|
||||||
|
dataKey?: undefined;
|
||||||
|
name?: undefined;
|
||||||
|
subDirectories: SubDirectoryInfo[];
|
||||||
|
files: SummarizedFileInfo[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DirectoryInfo = LocalDirectoryInfo | RootDirectoryInfo;
|
||||||
|
export type SubDirectoryInfo = Omit<LocalDirectoryInfo, "parentId" | "subDirectories" | "files">;
|
||||||
|
export type MaybeDirectoryInfo =
|
||||||
|
| (DirectoryInfo & { exists: true })
|
||||||
|
| ({ id: DirectoryId; exists: false } & AllUndefined<Omit<DirectoryInfo, "id">>);
|
||||||
|
|
||||||
|
export interface FileInfo {
|
||||||
|
id: number;
|
||||||
|
parentId: DirectoryId;
|
||||||
|
dataKey?: DataKey;
|
||||||
|
contentType: string;
|
||||||
|
contentIv?: string;
|
||||||
|
name: string;
|
||||||
|
createdAt?: Date;
|
||||||
|
lastModifiedAt: Date;
|
||||||
|
categories: { id: number; name: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SummarizedFileInfo = Omit<FileInfo, "parentId" | "contentIv" | "categories">;
|
||||||
|
export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean };
|
||||||
|
export type MaybeFileInfo =
|
||||||
|
| (FileInfo & { exists: true })
|
||||||
|
| ({ id: number; exists: false } & AllUndefined<Omit<FileInfo, "id">>);
|
||||||
|
|
||||||
|
interface LocalCategoryInfo {
|
||||||
|
id: number;
|
||||||
|
dataKey?: DataKey;
|
||||||
|
name: string;
|
||||||
|
subCategories: SubCategoryInfo[];
|
||||||
|
files: CategoryFileInfo[];
|
||||||
|
isFileRecursive: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RootCategoryInfo {
|
||||||
|
id: "root";
|
||||||
|
dataKey?: undefined;
|
||||||
|
name?: undefined;
|
||||||
|
subCategories: SubCategoryInfo[];
|
||||||
|
files?: undefined;
|
||||||
|
isFileRecursive?: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CategoryInfo = LocalCategoryInfo | RootCategoryInfo;
|
||||||
|
export type SubCategoryInfo = Omit<
|
||||||
|
LocalCategoryInfo,
|
||||||
|
"subCategories" | "files" | "isFileRecursive"
|
||||||
|
>;
|
||||||
|
export type MaybeCategoryInfo =
|
||||||
|
| (CategoryInfo & { exists: true })
|
||||||
|
| ({ id: CategoryId; exists: false } & AllUndefined<Omit<CategoryInfo, "id">>);
|
||||||
65
src/lib/modules/key.ts
Normal file
65
src/lib/modules/key.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { storeClientKey } from "$lib/indexedDB";
|
||||||
|
import type { ClientKeys } from "$lib/stores";
|
||||||
|
|
||||||
|
const serializedClientKeysSchema = z.intersection(
|
||||||
|
z.object({
|
||||||
|
generator: z.literal("ArkVault"),
|
||||||
|
exportedAt: z.iso.datetime(),
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
version: z.literal(1),
|
||||||
|
encryptKey: z.base64().nonempty(),
|
||||||
|
decryptKey: z.base64().nonempty(),
|
||||||
|
signKey: z.base64().nonempty(),
|
||||||
|
verifyKey: z.base64().nonempty(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
type SerializedClientKeys = z.infer<typeof serializedClientKeysSchema>;
|
||||||
|
|
||||||
|
type DeserializedClientKeys = {
|
||||||
|
encryptKeyBase64: string;
|
||||||
|
decryptKeyBase64: string;
|
||||||
|
signKeyBase64: string;
|
||||||
|
verifyKeyBase64: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const serializeClientKeys = ({
|
||||||
|
encryptKeyBase64,
|
||||||
|
decryptKeyBase64,
|
||||||
|
signKeyBase64,
|
||||||
|
verifyKeyBase64,
|
||||||
|
}: DeserializedClientKeys) => {
|
||||||
|
return JSON.stringify({
|
||||||
|
version: 1,
|
||||||
|
generator: "ArkVault",
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
encryptKey: encryptKeyBase64,
|
||||||
|
decryptKey: decryptKeyBase64,
|
||||||
|
signKey: signKeyBase64,
|
||||||
|
verifyKey: verifyKeyBase64,
|
||||||
|
} satisfies SerializedClientKeys);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deserializeClientKeys = (serialized: string) => {
|
||||||
|
const zodRes = serializedClientKeysSchema.safeParse(JSON.parse(serialized));
|
||||||
|
if (zodRes.success) {
|
||||||
|
return {
|
||||||
|
encryptKeyBase64: zodRes.data.encryptKey,
|
||||||
|
decryptKeyBase64: zodRes.data.decryptKey,
|
||||||
|
signKeyBase64: zodRes.data.signKey,
|
||||||
|
verifyKeyBase64: zodRes.data.verifyKey,
|
||||||
|
} satisfies DeserializedClientKeys;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const storeClientKeys = async (clientKeys: ClientKeys) => {
|
||||||
|
await Promise.all([
|
||||||
|
storeClientKey(clientKeys.encryptKey, "encrypt"),
|
||||||
|
storeClientKey(clientKeys.decryptKey, "decrypt"),
|
||||||
|
storeClientKey(clientKeys.signKey, "sign"),
|
||||||
|
storeClientKey(clientKeys.verifyKey, "verify"),
|
||||||
|
]);
|
||||||
|
};
|
||||||
@@ -59,3 +59,39 @@ export const deleteFile = async (path: string) => {
|
|||||||
|
|
||||||
await parentHandle.removeEntry(filename);
|
await parentHandle.removeEntry(filename);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getDirectoryHandle = async (path: string) => {
|
||||||
|
if (!rootHandle) {
|
||||||
|
throw new Error("OPFS not prepared");
|
||||||
|
} else if (path[0] !== "/") {
|
||||||
|
throw new Error("Path must be absolute");
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = path.split("/");
|
||||||
|
if (parts.length <= 1) {
|
||||||
|
throw new Error("Invalid path");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let directoryHandle = rootHandle;
|
||||||
|
let parentHandle;
|
||||||
|
for (const part of parts.slice(1)) {
|
||||||
|
if (!part) continue;
|
||||||
|
parentHandle = directoryHandle;
|
||||||
|
directoryHandle = await directoryHandle.getDirectoryHandle(part);
|
||||||
|
}
|
||||||
|
return { directoryHandle, parentHandle };
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof DOMException && e.name === "NotFoundError") {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteDirectory = async (path: string) => {
|
||||||
|
const { directoryHandle, parentHandle } = await getDirectoryHandle(path);
|
||||||
|
if (!parentHandle) return;
|
||||||
|
|
||||||
|
await parentHandle.removeEntry(directoryHandle.name, { recursive: true });
|
||||||
|
};
|
||||||
|
|||||||
127
src/lib/modules/thumbnail.ts
Normal file
127
src/lib/modules/thumbnail.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import { encodeToBase64 } from "$lib/modules/crypto";
|
||||||
|
|
||||||
|
const scaleSize = (width: number, height: number, targetSize: number) => {
|
||||||
|
if (width <= targetSize || height <= targetSize) {
|
||||||
|
return { width, height };
|
||||||
|
}
|
||||||
|
|
||||||
|
const scale = targetSize / Math.min(width, height);
|
||||||
|
return {
|
||||||
|
width: Math.round(width * scale),
|
||||||
|
height: Math.round(height * scale),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const capture = (
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
drawer: (context: CanvasRenderingContext2D, width: number, height: number) => void,
|
||||||
|
targetSize = 250,
|
||||||
|
) => {
|
||||||
|
return new Promise<Blob>((resolve, reject) => {
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
const { width: scaledWidth, height: scaledHeight } = scaleSize(width, height, targetSize);
|
||||||
|
|
||||||
|
canvas.width = scaledWidth;
|
||||||
|
canvas.height = scaledHeight;
|
||||||
|
|
||||||
|
const context = canvas.getContext("2d");
|
||||||
|
if (!context) {
|
||||||
|
return reject(new Error("Failed to generate thumbnail"));
|
||||||
|
}
|
||||||
|
|
||||||
|
drawer(context, scaledWidth, scaledHeight);
|
||||||
|
canvas.toBlob((blob) => {
|
||||||
|
if (blob && blob.type === "image/webp") {
|
||||||
|
resolve(blob);
|
||||||
|
} else {
|
||||||
|
reject(new Error("Failed to generate thumbnail"));
|
||||||
|
}
|
||||||
|
}, "image/webp");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const generateImageThumbnail = (imageUrl: string) => {
|
||||||
|
return new Promise<Blob>((resolve, reject) => {
|
||||||
|
const image = new Image();
|
||||||
|
image.onload = () => {
|
||||||
|
capture(image.width, image.height, (context, width, height) => {
|
||||||
|
context.drawImage(image, 0, 0, width, height);
|
||||||
|
})
|
||||||
|
.then(resolve)
|
||||||
|
.catch(reject);
|
||||||
|
};
|
||||||
|
image.onerror = reject;
|
||||||
|
|
||||||
|
image.src = imageUrl;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const captureVideoThumbnail = (video: HTMLVideoElement) => {
|
||||||
|
return capture(video.videoWidth, video.videoHeight, (context, width, height) => {
|
||||||
|
context.drawImage(video, 0, 0, width, height);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const generateVideoThumbnail = (videoUrl: string, time = 0) => {
|
||||||
|
return new Promise<Blob>((resolve, reject) => {
|
||||||
|
const video = document.createElement("video");
|
||||||
|
video.onloadedmetadata = () => {
|
||||||
|
if (video.videoWidth === 0 || video.videoHeight === 0) {
|
||||||
|
return reject();
|
||||||
|
}
|
||||||
|
|
||||||
|
const callbackId = video.requestVideoFrameCallback(() => {
|
||||||
|
captureVideoThumbnail(video).then(resolve).catch(reject);
|
||||||
|
video.cancelVideoFrameCallback(callbackId);
|
||||||
|
});
|
||||||
|
video.currentTime = Math.min(time, video.duration);
|
||||||
|
};
|
||||||
|
video.onerror = reject;
|
||||||
|
|
||||||
|
video.muted = true;
|
||||||
|
video.playsInline = true;
|
||||||
|
video.src = videoUrl;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const generateThumbnail = async (fileBuffer: ArrayBuffer, fileType: string) => {
|
||||||
|
let url;
|
||||||
|
try {
|
||||||
|
if (fileType.startsWith("image/")) {
|
||||||
|
const fileBlob = new Blob([fileBuffer], { type: fileType });
|
||||||
|
url = URL.createObjectURL(fileBlob);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await generateImageThumbnail(url);
|
||||||
|
} catch {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
url = undefined;
|
||||||
|
|
||||||
|
if (fileType === "image/heic") {
|
||||||
|
const { default: heic2any } = await import("heic2any");
|
||||||
|
url = URL.createObjectURL(
|
||||||
|
(await heic2any({ blob: fileBlob, toType: "image/png" })) as Blob,
|
||||||
|
);
|
||||||
|
return await generateImageThumbnail(url);
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (fileType.startsWith("video/")) {
|
||||||
|
url = URL.createObjectURL(new Blob([fileBuffer], { type: fileType }));
|
||||||
|
return await generateVideoThumbnail(url);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
if (url) {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getThumbnailUrl = (thumbnailBuffer: ArrayBuffer) => {
|
||||||
|
return `data:image/webp;base64,${encodeToBase64(thumbnailBuffer)}`;
|
||||||
|
};
|
||||||
145
src/lib/server/db/category.ts
Normal file
145
src/lib/server/db/category.ts
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
import { IntegrityError } from "./error";
|
||||||
|
import db from "./kysely";
|
||||||
|
import type { Ciphertext } from "./schema";
|
||||||
|
|
||||||
|
interface Category {
|
||||||
|
id: number;
|
||||||
|
parentId: CategoryId;
|
||||||
|
userId: number;
|
||||||
|
mekVersion: number;
|
||||||
|
encDek: string;
|
||||||
|
dekVersion: Date;
|
||||||
|
encName: Ciphertext;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NewCategory = Omit<Category, "id">;
|
||||||
|
|
||||||
|
export const registerCategory = async (params: NewCategory) => {
|
||||||
|
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 { categoryId } = await trx
|
||||||
|
.insertInto("category")
|
||||||
|
.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 categoryId")
|
||||||
|
.executeTakeFirstOrThrow();
|
||||||
|
await trx
|
||||||
|
.insertInto("category_log")
|
||||||
|
.values({
|
||||||
|
category_id: categoryId,
|
||||||
|
timestamp: new Date(),
|
||||||
|
action: "create",
|
||||||
|
new_name: params.encName,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAllCategoriesByParent = async (userId: number, parentId: CategoryId) => {
|
||||||
|
let query = db.selectFrom("category").selectAll().where("user_id", "=", userId);
|
||||||
|
query =
|
||||||
|
parentId === "root"
|
||||||
|
? query.where("parent_id", "is", null)
|
||||||
|
: query.where("parent_id", "=", parentId);
|
||||||
|
const categories = await query.execute();
|
||||||
|
return categories.map(
|
||||||
|
(category) =>
|
||||||
|
({
|
||||||
|
id: category.id,
|
||||||
|
parentId: category.parent_id ?? "root",
|
||||||
|
userId: category.user_id,
|
||||||
|
mekVersion: category.master_encryption_key_version,
|
||||||
|
encDek: category.encrypted_data_encryption_key,
|
||||||
|
dekVersion: category.data_encryption_key_version,
|
||||||
|
encName: category.encrypted_name,
|
||||||
|
}) satisfies Category,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCategory = async (userId: number, categoryId: number) => {
|
||||||
|
const category = await db
|
||||||
|
.selectFrom("category")
|
||||||
|
.selectAll()
|
||||||
|
.where("id", "=", categoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
return category
|
||||||
|
? ({
|
||||||
|
id: category.id,
|
||||||
|
parentId: category.parent_id ?? "root",
|
||||||
|
userId: category.user_id,
|
||||||
|
mekVersion: category.master_encryption_key_version,
|
||||||
|
encDek: category.encrypted_data_encryption_key,
|
||||||
|
dekVersion: category.data_encryption_key_version,
|
||||||
|
encName: category.encrypted_name,
|
||||||
|
} satisfies Category)
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const setCategoryEncName = async (
|
||||||
|
userId: number,
|
||||||
|
categoryId: number,
|
||||||
|
dekVersion: Date,
|
||||||
|
encName: Ciphertext,
|
||||||
|
) => {
|
||||||
|
await db.transaction().execute(async (trx) => {
|
||||||
|
const category = await trx
|
||||||
|
.selectFrom("category")
|
||||||
|
.select("data_encryption_key_version")
|
||||||
|
.where("id", "=", categoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.limit(1)
|
||||||
|
.forUpdate()
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (!category) {
|
||||||
|
throw new IntegrityError("Category not found");
|
||||||
|
} else if (category.data_encryption_key_version.getTime() !== dekVersion.getTime()) {
|
||||||
|
throw new IntegrityError("Invalid DEK version");
|
||||||
|
}
|
||||||
|
|
||||||
|
await trx
|
||||||
|
.updateTable("category")
|
||||||
|
.set({ encrypted_name: encName })
|
||||||
|
.where("id", "=", categoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.execute();
|
||||||
|
await trx
|
||||||
|
.insertInto("category_log")
|
||||||
|
.values({
|
||||||
|
category_id: categoryId,
|
||||||
|
timestamp: new Date(),
|
||||||
|
action: "rename",
|
||||||
|
new_name: encName,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const unregisterCategory = async (userId: number, categoryId: number) => {
|
||||||
|
const res = await db
|
||||||
|
.deleteFrom("category")
|
||||||
|
.where("id", "=", categoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (res.numDeletedRows === 0n) {
|
||||||
|
throw new IntegrityError("Category not found");
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,106 +1,158 @@
|
|||||||
import { SqliteError } from "better-sqlite3";
|
import pg from "pg";
|
||||||
import { and, or, eq, gt, lte } from "drizzle-orm";
|
|
||||||
import db from "./drizzle";
|
|
||||||
import { IntegrityError } from "./error";
|
import { IntegrityError } from "./error";
|
||||||
import { client, userClient, userClientChallenge } from "./schema";
|
import db from "./kysely";
|
||||||
|
import type { UserClientState } from "./schema";
|
||||||
|
|
||||||
|
interface Client {
|
||||||
|
id: number;
|
||||||
|
encPubKey: string;
|
||||||
|
sigPubKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserClient {
|
||||||
|
userId: number;
|
||||||
|
clientId: number;
|
||||||
|
state: UserClientState;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserClientWithDetails extends UserClient {
|
||||||
|
encPubKey: string;
|
||||||
|
sigPubKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
export const createClient = async (encPubKey: string, sigPubKey: string, userId: number) => {
|
export const createClient = async (encPubKey: string, sigPubKey: string, userId: number) => {
|
||||||
return await db.transaction(
|
return await db
|
||||||
async (tx) => {
|
.transaction()
|
||||||
const clients = await tx
|
.setIsolationLevel("serializable")
|
||||||
.select({ id: client.id })
|
.execute(async (trx) => {
|
||||||
.from(client)
|
const client = await trx
|
||||||
.where(or(eq(client.encPubKey, sigPubKey), eq(client.sigPubKey, encPubKey)))
|
.selectFrom("client")
|
||||||
.limit(1);
|
.where((eb) =>
|
||||||
if (clients.length !== 0) {
|
eb.or([
|
||||||
|
eb("encryption_public_key", "=", encPubKey),
|
||||||
|
eb("encryption_public_key", "=", sigPubKey),
|
||||||
|
eb("signature_public_key", "=", encPubKey),
|
||||||
|
eb("signature_public_key", "=", sigPubKey),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (client) {
|
||||||
throw new IntegrityError("Public key(s) already registered");
|
throw new IntegrityError("Public key(s) already registered");
|
||||||
}
|
}
|
||||||
|
|
||||||
const newClients = await tx
|
const { clientId } = await trx
|
||||||
.insert(client)
|
.insertInto("client")
|
||||||
.values({ encPubKey, sigPubKey })
|
.values({ encryption_public_key: encPubKey, signature_public_key: sigPubKey })
|
||||||
.returning({ id: client.id });
|
.returning("id as clientId")
|
||||||
const { id: clientId } = newClients[0]!;
|
.executeTakeFirstOrThrow();
|
||||||
await tx.insert(userClient).values({ userId, clientId });
|
await trx
|
||||||
|
.insertInto("user_client")
|
||||||
return clientId;
|
.values({ user_id: userId, client_id: clientId })
|
||||||
},
|
.execute();
|
||||||
{ behavior: "exclusive" },
|
return { id: clientId };
|
||||||
);
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getClient = async (clientId: number) => {
|
export const getClient = async (clientId: number) => {
|
||||||
const clients = await db.select().from(client).where(eq(client.id, clientId)).limit(1);
|
const client = await db
|
||||||
return clients[0] ?? null;
|
.selectFrom("client")
|
||||||
|
.selectAll()
|
||||||
|
.where("id", "=", clientId)
|
||||||
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
return client
|
||||||
|
? ({
|
||||||
|
id: client.id,
|
||||||
|
encPubKey: client.encryption_public_key,
|
||||||
|
sigPubKey: client.signature_public_key,
|
||||||
|
} satisfies Client)
|
||||||
|
: null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getClientByPubKeys = async (encPubKey: string, sigPubKey: string) => {
|
export const getClientByPubKeys = async (encPubKey: string, sigPubKey: string) => {
|
||||||
const clients = await db
|
const client = await db
|
||||||
.select()
|
.selectFrom("client")
|
||||||
.from(client)
|
.selectAll()
|
||||||
.where(and(eq(client.encPubKey, encPubKey), eq(client.sigPubKey, sigPubKey)))
|
.where("encryption_public_key", "=", encPubKey)
|
||||||
.limit(1);
|
.where("signature_public_key", "=", sigPubKey)
|
||||||
return clients[0] ?? null;
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
return client
|
||||||
|
? ({
|
||||||
|
id: client.id,
|
||||||
|
encPubKey: client.encryption_public_key,
|
||||||
|
sigPubKey: client.signature_public_key,
|
||||||
|
} satisfies Client)
|
||||||
|
: null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createUserClient = async (userId: number, clientId: number) => {
|
export const createUserClient = async (userId: number, clientId: number) => {
|
||||||
try {
|
try {
|
||||||
await db.insert(userClient).values({ userId, clientId });
|
await db.insertInto("user_client").values({ user_id: userId, client_id: clientId }).execute();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof SqliteError && e.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
|
if (e instanceof pg.DatabaseError && e.code === "23505") {
|
||||||
throw new IntegrityError("User client already exists");
|
throw new IntegrityError("User client already exists");
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllUserClients = async (userId: number) => {
|
|
||||||
return await db.select().from(userClient).where(eq(userClient.userId, userId));
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getUserClient = async (userId: number, clientId: number) => {
|
export const getUserClient = async (userId: number, clientId: number) => {
|
||||||
const userClients = await db
|
const userClient = await db
|
||||||
.select()
|
.selectFrom("user_client")
|
||||||
.from(userClient)
|
.selectAll()
|
||||||
.where(and(eq(userClient.userId, userId), eq(userClient.clientId, clientId)))
|
.where("user_id", "=", userId)
|
||||||
.limit(1);
|
.where("client_id", "=", clientId)
|
||||||
return userClients[0] ?? null;
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
return userClient
|
||||||
|
? ({
|
||||||
|
userId: userClient.user_id,
|
||||||
|
clientId: userClient.client_id,
|
||||||
|
state: userClient.state,
|
||||||
|
} satisfies UserClient)
|
||||||
|
: null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getUserClientWithDetails = async (userId: number, clientId: number) => {
|
export const getUserClientWithDetails = async (userId: number, clientId: number) => {
|
||||||
const userClients = await db
|
const userClient = await db
|
||||||
.select()
|
.selectFrom("user_client")
|
||||||
.from(userClient)
|
.innerJoin("client", "user_client.client_id", "client.id")
|
||||||
.innerJoin(client, eq(userClient.clientId, client.id))
|
.selectAll()
|
||||||
.where(and(eq(userClient.userId, userId), eq(userClient.clientId, clientId)))
|
.where("user_id", "=", userId)
|
||||||
.limit(1);
|
.where("client_id", "=", clientId)
|
||||||
return userClients[0] ?? null;
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
return userClient
|
||||||
|
? ({
|
||||||
|
userId: userClient.user_id,
|
||||||
|
clientId: userClient.client_id,
|
||||||
|
state: userClient.state,
|
||||||
|
encPubKey: userClient.encryption_public_key,
|
||||||
|
sigPubKey: userClient.signature_public_key,
|
||||||
|
} satisfies UserClientWithDetails)
|
||||||
|
: null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const setUserClientStateToPending = async (userId: number, clientId: number) => {
|
export const setUserClientStateToPending = async (userId: number, clientId: number) => {
|
||||||
await db
|
await db
|
||||||
.update(userClient)
|
.updateTable("user_client")
|
||||||
.set({ state: "pending" })
|
.set({ state: "pending" })
|
||||||
.where(
|
.where("user_id", "=", userId)
|
||||||
and(
|
.where("client_id", "=", clientId)
|
||||||
eq(userClient.userId, userId),
|
.where("state", "=", "challenging")
|
||||||
eq(userClient.clientId, clientId),
|
.execute();
|
||||||
eq(userClient.state, "challenging"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const setUserClientStateToActive = async (userId: number, clientId: number) => {
|
export const setUserClientStateToActive = async (userId: number, clientId: number) => {
|
||||||
await db
|
await db
|
||||||
.update(userClient)
|
.updateTable("user_client")
|
||||||
.set({ state: "active" })
|
.set({ state: "active" })
|
||||||
.where(
|
.where("user_id", "=", userId)
|
||||||
and(
|
.where("client_id", "=", clientId)
|
||||||
eq(userClient.userId, userId),
|
.where("state", "=", "pending")
|
||||||
eq(userClient.clientId, clientId),
|
.execute();
|
||||||
eq(userClient.state, "pending"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const registerUserClientChallenge = async (
|
export const registerUserClientChallenge = async (
|
||||||
@@ -110,30 +162,36 @@ export const registerUserClientChallenge = async (
|
|||||||
allowedIp: string,
|
allowedIp: string,
|
||||||
expiresAt: Date,
|
expiresAt: Date,
|
||||||
) => {
|
) => {
|
||||||
await db.insert(userClientChallenge).values({
|
const { id } = await db
|
||||||
userId,
|
.insertInto("user_client_challenge")
|
||||||
clientId,
|
.values({
|
||||||
|
user_id: userId,
|
||||||
|
client_id: clientId,
|
||||||
answer,
|
answer,
|
||||||
allowedIp,
|
allowed_ip: allowedIp,
|
||||||
expiresAt,
|
expires_at: expiresAt,
|
||||||
});
|
})
|
||||||
|
.returning("id")
|
||||||
|
.executeTakeFirstOrThrow();
|
||||||
|
return { id };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const consumeUserClientChallenge = async (userId: number, answer: string, ip: string) => {
|
export const consumeUserClientChallenge = async (
|
||||||
const challenges = await db
|
challengeId: number,
|
||||||
.delete(userClientChallenge)
|
userId: number,
|
||||||
.where(
|
ip: string,
|
||||||
and(
|
) => {
|
||||||
eq(userClientChallenge.userId, userId),
|
const challenge = await db
|
||||||
eq(userClientChallenge.answer, answer),
|
.deleteFrom("user_client_challenge")
|
||||||
eq(userClientChallenge.allowedIp, ip),
|
.where("id", "=", challengeId)
|
||||||
gt(userClientChallenge.expiresAt, new Date()),
|
.where("user_id", "=", userId)
|
||||||
),
|
.where("allowed_ip", "=", ip)
|
||||||
)
|
.where("expires_at", ">", new Date())
|
||||||
.returning({ clientId: userClientChallenge.clientId });
|
.returning(["client_id", "answer"])
|
||||||
return challenges[0] ?? null;
|
.executeTakeFirst();
|
||||||
|
return challenge ? { clientId: challenge.client_id, answer: challenge.answer } : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cleanupExpiredUserClientChallenges = async () => {
|
export const cleanupExpiredUserClientChallenges = async () => {
|
||||||
await db.delete(userClientChallenge).where(lte(userClientChallenge.expiresAt, new Date()));
|
await db.deleteFrom("user_client_challenge").where("expires_at", "<=", new Date()).execute();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
import Database from "better-sqlite3";
|
|
||||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
|
||||||
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
|
|
||||||
import env from "$lib/server/loadenv";
|
|
||||||
|
|
||||||
const client = new Database(env.databaseUrl);
|
|
||||||
const db = drizzle(client);
|
|
||||||
|
|
||||||
export const migrateDB = () => {
|
|
||||||
if (process.env.NODE_ENV === "production") {
|
|
||||||
migrate(db, { migrationsFolder: "./drizzle" });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default db;
|
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
type IntegrityErrorMessages =
|
type IntegrityErrorMessages =
|
||||||
|
// Category
|
||||||
|
| "Category not found"
|
||||||
// Challenge
|
// Challenge
|
||||||
| "Challenge already registered"
|
| "Challenge already registered"
|
||||||
// Client
|
// Client
|
||||||
@@ -7,6 +9,8 @@ type IntegrityErrorMessages =
|
|||||||
// File
|
// File
|
||||||
| "Directory not found"
|
| "Directory not found"
|
||||||
| "File not found"
|
| "File not found"
|
||||||
|
| "File not found in category"
|
||||||
|
| "File already added to category"
|
||||||
| "Invalid DEK version"
|
| "Invalid DEK version"
|
||||||
// HSK
|
// HSK
|
||||||
| "HSK already registered"
|
| "HSK already registered"
|
||||||
|
|||||||
@@ -1,21 +1,24 @@
|
|||||||
import { and, eq, isNull } from "drizzle-orm";
|
import { sql } from "kysely";
|
||||||
import db from "./drizzle";
|
import { jsonArrayFrom } from "kysely/helpers/postgres";
|
||||||
|
import pg from "pg";
|
||||||
import { IntegrityError } from "./error";
|
import { IntegrityError } from "./error";
|
||||||
import { directory, directoryLog, file, fileLog, hsk, mek } from "./schema";
|
import db from "./kysely";
|
||||||
|
import type { Ciphertext } from "./schema";
|
||||||
|
|
||||||
type DirectoryId = "root" | number;
|
interface Directory {
|
||||||
|
id: number;
|
||||||
export interface NewDirectoryParams {
|
|
||||||
parentId: DirectoryId;
|
parentId: DirectoryId;
|
||||||
userId: number;
|
userId: number;
|
||||||
mekVersion: number;
|
mekVersion: number;
|
||||||
encDek: string;
|
encDek: string;
|
||||||
dekVersion: Date;
|
dekVersion: Date;
|
||||||
encName: string;
|
encName: Ciphertext;
|
||||||
encNameIv: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NewFileParams {
|
export type NewDirectory = Omit<Directory, "id">;
|
||||||
|
|
||||||
|
interface File {
|
||||||
|
id: number;
|
||||||
parentId: DirectoryId;
|
parentId: DirectoryId;
|
||||||
userId: number;
|
userId: number;
|
||||||
path: string;
|
path: string;
|
||||||
@@ -26,286 +29,552 @@ export interface NewFileParams {
|
|||||||
contentHmac: string | null;
|
contentHmac: string | null;
|
||||||
contentType: string;
|
contentType: string;
|
||||||
encContentIv: string;
|
encContentIv: string;
|
||||||
encName: string;
|
encContentHash: string;
|
||||||
encNameIv: string;
|
encName: Ciphertext;
|
||||||
encCreatedAt: string | null;
|
encCreatedAt: Ciphertext | null;
|
||||||
encCreatedAtIv: string | null;
|
encLastModifiedAt: Ciphertext;
|
||||||
encLastModifiedAt: string;
|
|
||||||
encLastModifiedAtIv: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const registerDirectory = async (params: NewDirectoryParams) => {
|
export type NewFile = Omit<File, "id">;
|
||||||
await db.transaction(
|
|
||||||
async (tx) => {
|
interface FileCategory {
|
||||||
const meks = await tx
|
id: number;
|
||||||
.select({ version: mek.version })
|
mekVersion: number;
|
||||||
.from(mek)
|
encDek: string;
|
||||||
.where(and(eq(mek.userId, params.userId), eq(mek.state, "active")))
|
dekVersion: Date;
|
||||||
.limit(1);
|
encName: Ciphertext;
|
||||||
if (meks[0]?.version !== params.mekVersion) {
|
}
|
||||||
|
|
||||||
|
export const registerDirectory = async (params: NewDirectory) => {
|
||||||
|
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");
|
throw new IntegrityError("Inactive MEK version");
|
||||||
}
|
}
|
||||||
|
|
||||||
const newDirectories = await tx
|
const { directoryId } = await trx
|
||||||
.insert(directory)
|
.insertInto("directory")
|
||||||
.values({
|
.values({
|
||||||
parentId: params.parentId === "root" ? null : params.parentId,
|
parent_id: params.parentId !== "root" ? params.parentId : null,
|
||||||
userId: params.userId,
|
user_id: params.userId,
|
||||||
mekVersion: params.mekVersion,
|
master_encryption_key_version: params.mekVersion,
|
||||||
encDek: params.encDek,
|
encrypted_data_encryption_key: params.encDek,
|
||||||
dekVersion: params.dekVersion,
|
data_encryption_key_version: params.dekVersion,
|
||||||
encName: { ciphertext: params.encName, iv: params.encNameIv },
|
encrypted_name: params.encName,
|
||||||
})
|
})
|
||||||
.returning({ id: directory.id });
|
.returning("id as directoryId")
|
||||||
const { id: directoryId } = newDirectories[0]!;
|
.executeTakeFirstOrThrow();
|
||||||
await tx.insert(directoryLog).values({
|
await trx
|
||||||
directoryId,
|
.insertInto("directory_log")
|
||||||
|
.values({
|
||||||
|
directory_id: directoryId,
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
action: "create",
|
action: "create",
|
||||||
newName: { ciphertext: params.encName, iv: params.encNameIv },
|
new_name: params.encName,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
});
|
});
|
||||||
},
|
|
||||||
{ behavior: "exclusive" },
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllDirectoriesByParent = async (userId: number, parentId: DirectoryId) => {
|
export const getAllDirectoriesByParent = async (userId: number, parentId: DirectoryId) => {
|
||||||
return await db
|
let query = db.selectFrom("directory").selectAll().where("user_id", "=", userId);
|
||||||
.select()
|
query =
|
||||||
.from(directory)
|
parentId === "root"
|
||||||
.where(
|
? query.where("parent_id", "is", null)
|
||||||
and(
|
: query.where("parent_id", "=", parentId);
|
||||||
eq(directory.userId, userId),
|
const directories = await query.execute();
|
||||||
parentId === "root" ? isNull(directory.parentId) : eq(directory.parentId, parentId),
|
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) => {
|
export const getDirectory = async (userId: number, directoryId: number) => {
|
||||||
const res = await db
|
const directory = await db
|
||||||
.select()
|
.selectFrom("directory")
|
||||||
.from(directory)
|
.selectAll()
|
||||||
.where(and(eq(directory.userId, userId), eq(directory.id, directoryId)))
|
.where("id", "=", directoryId)
|
||||||
.limit(1);
|
.where("user_id", "=", userId)
|
||||||
return res[0] ?? null;
|
.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 (
|
export const setDirectoryEncName = async (
|
||||||
userId: number,
|
userId: number,
|
||||||
directoryId: number,
|
directoryId: number,
|
||||||
dekVersion: Date,
|
dekVersion: Date,
|
||||||
encName: string,
|
encName: Ciphertext,
|
||||||
encNameIv: string,
|
|
||||||
) => {
|
) => {
|
||||||
await db.transaction(
|
await db.transaction().execute(async (trx) => {
|
||||||
async (tx) => {
|
const directory = await trx
|
||||||
const directories = await tx
|
.selectFrom("directory")
|
||||||
.select({ version: directory.dekVersion })
|
.select("data_encryption_key_version")
|
||||||
.from(directory)
|
.where("id", "=", directoryId)
|
||||||
.where(and(eq(directory.userId, userId), eq(directory.id, directoryId)))
|
.where("user_id", "=", userId)
|
||||||
.limit(1);
|
.limit(1)
|
||||||
if (!directories[0]) {
|
.forUpdate()
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (!directory) {
|
||||||
throw new IntegrityError("Directory not found");
|
throw new IntegrityError("Directory not found");
|
||||||
} else if (directories[0].version.getTime() !== dekVersion.getTime()) {
|
} else if (directory.data_encryption_key_version.getTime() !== dekVersion.getTime()) {
|
||||||
throw new IntegrityError("Invalid DEK version");
|
throw new IntegrityError("Invalid DEK version");
|
||||||
}
|
}
|
||||||
|
|
||||||
await tx
|
await trx
|
||||||
.update(directory)
|
.updateTable("directory")
|
||||||
.set({ encName: { ciphertext: encName, iv: encNameIv } })
|
.set({ encrypted_name: encName })
|
||||||
.where(and(eq(directory.userId, userId), eq(directory.id, directoryId)));
|
.where("id", "=", directoryId)
|
||||||
await tx.insert(directoryLog).values({
|
.where("user_id", "=", userId)
|
||||||
directoryId,
|
.execute();
|
||||||
|
await trx
|
||||||
|
.insertInto("directory_log")
|
||||||
|
.values({
|
||||||
|
directory_id: directoryId,
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
action: "rename",
|
action: "rename",
|
||||||
newName: { ciphertext: encName, iv: encNameIv },
|
new_name: encName,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
});
|
});
|
||||||
},
|
|
||||||
{ behavior: "exclusive" },
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const unregisterDirectory = async (userId: number, directoryId: number) => {
|
export const unregisterDirectory = async (userId: number, directoryId: number) => {
|
||||||
return await db.transaction(
|
return await db
|
||||||
async (tx) => {
|
.transaction()
|
||||||
|
.setIsolationLevel("repeatable read") // TODO: Sufficient?
|
||||||
|
.execute(async (trx) => {
|
||||||
const unregisterFiles = async (parentId: number) => {
|
const unregisterFiles = async (parentId: number) => {
|
||||||
return await tx
|
const files = await trx
|
||||||
.delete(file)
|
.selectFrom("file")
|
||||||
.where(and(eq(file.userId, userId), eq(file.parentId, parentId)))
|
.leftJoin("thumbnail", "file.id", "thumbnail.file_id")
|
||||||
.returning({ id: file.id, path: file.path });
|
.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 (
|
const unregisterDirectoryRecursively = async (
|
||||||
directoryId: number,
|
directoryId: number,
|
||||||
): Promise<{ id: number; path: string }[]> => {
|
): Promise<{ id: number; path: string; thumbnailPath: string | null }[]> => {
|
||||||
const files = await unregisterFiles(directoryId);
|
const files = await unregisterFiles(directoryId);
|
||||||
const subDirectories = await tx
|
const subDirectories = await trx
|
||||||
.select({ id: directory.id })
|
.selectFrom("directory")
|
||||||
.from(directory)
|
.select("id")
|
||||||
.where(and(eq(directory.userId, userId), eq(directory.parentId, directoryId)));
|
.where("parent_id", "=", directoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.execute();
|
||||||
const subDirectoryFilePaths = await Promise.all(
|
const subDirectoryFilePaths = await Promise.all(
|
||||||
subDirectories.map(async ({ id }) => await unregisterDirectoryRecursively(id)),
|
subDirectories.map(async ({ id }) => await unregisterDirectoryRecursively(id)),
|
||||||
);
|
);
|
||||||
|
|
||||||
const deleteRes = await tx.delete(directory).where(eq(directory.id, directoryId));
|
const deleteRes = await trx
|
||||||
if (deleteRes.changes === 0) {
|
.deleteFrom("directory")
|
||||||
|
.where("id", "=", directoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (deleteRes.numDeletedRows === 0n) {
|
||||||
throw new IntegrityError("Directory not found");
|
throw new IntegrityError("Directory not found");
|
||||||
}
|
}
|
||||||
return files.concat(...subDirectoryFilePaths);
|
return files.concat(...subDirectoryFilePaths);
|
||||||
};
|
};
|
||||||
return await unregisterDirectoryRecursively(directoryId);
|
return await unregisterDirectoryRecursively(directoryId);
|
||||||
},
|
});
|
||||||
{ behavior: "exclusive" },
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const registerFile = async (params: NewFileParams) => {
|
export const registerFile = async (params: NewFile) => {
|
||||||
if (
|
if ((params.hskVersion && !params.contentHmac) || (!params.hskVersion && params.contentHmac)) {
|
||||||
(params.hskVersion && !params.contentHmac) ||
|
|
||||||
(!params.hskVersion && params.contentHmac) ||
|
|
||||||
(params.encCreatedAt && !params.encCreatedAtIv) ||
|
|
||||||
(!params.encCreatedAt && params.encCreatedAtIv)
|
|
||||||
) {
|
|
||||||
throw new Error("Invalid arguments");
|
throw new Error("Invalid arguments");
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.transaction(
|
return await db.transaction().execute(async (trx) => {
|
||||||
async (tx) => {
|
const mek = await trx
|
||||||
const meks = await tx
|
.selectFrom("master_encryption_key")
|
||||||
.select({ version: mek.version })
|
.select("version")
|
||||||
.from(mek)
|
.where("user_id", "=", params.userId)
|
||||||
.where(and(eq(mek.userId, params.userId), eq(mek.state, "active")))
|
.where("state", "=", "active")
|
||||||
.limit(1);
|
.limit(1)
|
||||||
if (meks[0]?.version !== params.mekVersion) {
|
.forUpdate()
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (mek?.version !== params.mekVersion) {
|
||||||
throw new IntegrityError("Inactive MEK version");
|
throw new IntegrityError("Inactive MEK version");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (params.hskVersion) {
|
if (params.hskVersion) {
|
||||||
const hsks = await tx
|
const hsk = await trx
|
||||||
.select({ version: hsk.version })
|
.selectFrom("hmac_secret_key")
|
||||||
.from(hsk)
|
.select("version")
|
||||||
.where(and(eq(hsk.userId, params.userId), eq(hsk.state, "active")))
|
.where("user_id", "=", params.userId)
|
||||||
.limit(1);
|
.where("state", "=", "active")
|
||||||
if (hsks[0]?.version !== params.hskVersion) {
|
.limit(1)
|
||||||
|
.forUpdate()
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (hsk?.version !== params.hskVersion) {
|
||||||
throw new IntegrityError("Inactive HSK version");
|
throw new IntegrityError("Inactive HSK version");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const newFiles = await tx
|
const { fileId } = await trx
|
||||||
.insert(file)
|
.insertInto("file")
|
||||||
.values({
|
.values({
|
||||||
|
parent_id: params.parentId !== "root" ? params.parentId : null,
|
||||||
|
user_id: params.userId,
|
||||||
path: params.path,
|
path: params.path,
|
||||||
parentId: params.parentId === "root" ? null : params.parentId,
|
master_encryption_key_version: params.mekVersion,
|
||||||
userId: params.userId,
|
encrypted_data_encryption_key: params.encDek,
|
||||||
mekVersion: params.mekVersion,
|
data_encryption_key_version: params.dekVersion,
|
||||||
hskVersion: params.hskVersion,
|
hmac_secret_key_version: params.hskVersion,
|
||||||
contentHmac: params.contentHmac,
|
content_hmac: params.contentHmac,
|
||||||
contentType: params.contentType,
|
content_type: params.contentType,
|
||||||
encDek: params.encDek,
|
encrypted_content_iv: params.encContentIv,
|
||||||
dekVersion: params.dekVersion,
|
encrypted_content_hash: params.encContentHash,
|
||||||
encContentIv: params.encContentIv,
|
encrypted_name: params.encName,
|
||||||
encName: { ciphertext: params.encName, iv: params.encNameIv },
|
encrypted_created_at: params.encCreatedAt,
|
||||||
encCreatedAt:
|
encrypted_last_modified_at: params.encLastModifiedAt,
|
||||||
params.encCreatedAt && params.encCreatedAtIv
|
|
||||||
? { ciphertext: params.encCreatedAt, iv: params.encCreatedAtIv }
|
|
||||||
: null,
|
|
||||||
encLastModifiedAt: {
|
|
||||||
ciphertext: params.encLastModifiedAt,
|
|
||||||
iv: params.encLastModifiedAtIv,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
.returning({ id: file.id });
|
.returning("id as fileId")
|
||||||
const { id: fileId } = newFiles[0]!;
|
.executeTakeFirstOrThrow();
|
||||||
await tx.insert(fileLog).values({
|
await trx
|
||||||
fileId,
|
.insertInto("file_log")
|
||||||
|
.values({
|
||||||
|
file_id: fileId,
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
action: "create",
|
action: "create",
|
||||||
newName: { ciphertext: params.encName, iv: params.encNameIv },
|
new_name: params.encName,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
|
return { id: fileId };
|
||||||
});
|
});
|
||||||
},
|
|
||||||
{ behavior: "exclusive" },
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllFilesByParent = async (userId: number, parentId: DirectoryId) => {
|
export const getAllFilesByParent = async (userId: number, parentId: DirectoryId) => {
|
||||||
return await db
|
let query = db.selectFrom("file").selectAll().where("user_id", "=", userId);
|
||||||
.select()
|
query =
|
||||||
.from(file)
|
parentId === "root"
|
||||||
.where(
|
? query.where("parent_id", "is", null)
|
||||||
and(
|
: query.where("parent_id", "=", parentId);
|
||||||
eq(file.userId, userId),
|
const files = await query.execute();
|
||||||
parentId === "root" ? isNull(file.parentId) : eq(file.parentId, parentId),
|
return files.map(
|
||||||
),
|
(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 (
|
||||||
|
userId: number,
|
||||||
|
categoryId: number,
|
||||||
|
recurse: boolean,
|
||||||
|
) => {
|
||||||
|
const files = await db
|
||||||
|
.withRecursive("category_tree", (db) =>
|
||||||
|
db
|
||||||
|
.selectFrom("category")
|
||||||
|
.select(["id", sql<number>`0`.as("depth")])
|
||||||
|
.where("id", "=", categoryId)
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.$if(recurse, (qb) =>
|
||||||
|
qb.unionAll((db) =>
|
||||||
|
db
|
||||||
|
.selectFrom("category")
|
||||||
|
.innerJoin("category_tree", "category.parent_id", "category_tree.id")
|
||||||
|
.select(["category.id", sql<number>`depth + 1`.as("depth")]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.selectFrom("category_tree")
|
||||||
|
.innerJoin("file_category", "category_tree.id", "file_category.category_id")
|
||||||
|
.innerJoin("file", "file_category.file_id", "file.id")
|
||||||
|
.select(["file_id", "depth"])
|
||||||
|
.selectAll("file")
|
||||||
|
.distinctOn("file_id")
|
||||||
|
.orderBy("file_id")
|
||||||
|
.orderBy("depth")
|
||||||
|
.execute();
|
||||||
|
return files.map(
|
||||||
|
(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,
|
||||||
|
}) satisfies File & { isRecursive: boolean },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAllFileIds = async (userId: number) => {
|
||||||
|
const files = await db.selectFrom("file").select("id").where("user_id", "=", userId).execute();
|
||||||
|
return files.map(({ id }) => id);
|
||||||
|
};
|
||||||
|
|
||||||
export const getAllFileIdsByContentHmac = async (
|
export const getAllFileIdsByContentHmac = async (
|
||||||
userId: number,
|
userId: number,
|
||||||
hskVersion: number,
|
hskVersion: number,
|
||||||
contentHmac: string,
|
contentHmac: string,
|
||||||
) => {
|
) => {
|
||||||
return await db
|
const files = await db
|
||||||
.select({ id: file.id })
|
.selectFrom("file")
|
||||||
.from(file)
|
.select("id")
|
||||||
.where(
|
.where("user_id", "=", userId)
|
||||||
and(
|
.where("hmac_secret_key_version", "=", hskVersion)
|
||||||
eq(file.userId, userId),
|
.where("content_hmac", "=", contentHmac)
|
||||||
eq(file.hskVersion, hskVersion),
|
.execute();
|
||||||
eq(file.contentHmac, contentHmac),
|
return files.map(({ id }) => id);
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getFile = async (userId: number, fileId: number) => {
|
export const getFile = async (userId: number, fileId: number) => {
|
||||||
const res = await db
|
const file = await db
|
||||||
.select()
|
.selectFrom("file")
|
||||||
.from(file)
|
.selectAll()
|
||||||
.where(and(eq(file.userId, userId), eq(file.id, fileId)))
|
.where("id", "=", fileId)
|
||||||
.limit(1);
|
.where("user_id", "=", userId)
|
||||||
return res[0] ?? null;
|
.limit(1)
|
||||||
|
.executeTakeFirst();
|
||||||
|
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[]) => {
|
||||||
|
const files = await db
|
||||||
|
.selectFrom("file")
|
||||||
|
.selectAll()
|
||||||
|
.select((eb) =>
|
||||||
|
jsonArrayFrom(
|
||||||
|
eb
|
||||||
|
.selectFrom("file_category")
|
||||||
|
.innerJoin("category", "file_category.category_id", "category.id")
|
||||||
|
.where("file_category.file_id", "=", eb.ref("file.id"))
|
||||||
|
.selectAll("category"),
|
||||||
|
).as("categories"),
|
||||||
|
)
|
||||||
|
.where("id", "=", (eb) => eb.fn.any(eb.val(fileIds)))
|
||||||
|
.where("user_id", "=", userId)
|
||||||
|
.execute();
|
||||||
|
return files.map(
|
||||||
|
(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,
|
||||||
|
categories: file.categories.map((category) => ({
|
||||||
|
id: category.id,
|
||||||
|
mekVersion: category.master_encryption_key_version,
|
||||||
|
encDek: category.encrypted_data_encryption_key,
|
||||||
|
dekVersion: new Date(category.data_encryption_key_version),
|
||||||
|
encName: category.encrypted_name,
|
||||||
|
})),
|
||||||
|
}) satisfies File & { categories: FileCategory[] },
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const setFileEncName = async (
|
export const setFileEncName = async (
|
||||||
userId: number,
|
userId: number,
|
||||||
fileId: number,
|
fileId: number,
|
||||||
dekVersion: Date,
|
dekVersion: Date,
|
||||||
encName: string,
|
encName: Ciphertext,
|
||||||
encNameIv: string,
|
|
||||||
) => {
|
) => {
|
||||||
await db.transaction(
|
await db.transaction().execute(async (trx) => {
|
||||||
async (tx) => {
|
const file = await trx
|
||||||
const files = await tx
|
.selectFrom("file")
|
||||||
.select({ version: file.dekVersion })
|
.select("data_encryption_key_version")
|
||||||
.from(file)
|
.where("id", "=", fileId)
|
||||||
.where(and(eq(file.userId, userId), eq(file.id, fileId)))
|
.where("user_id", "=", userId)
|
||||||
.limit(1);
|
.limit(1)
|
||||||
if (!files[0]) {
|
.forUpdate()
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (!file) {
|
||||||
throw new IntegrityError("File not found");
|
throw new IntegrityError("File not found");
|
||||||
} else if (files[0].version.getTime() !== dekVersion.getTime()) {
|
} else if (file.data_encryption_key_version.getTime() !== dekVersion.getTime()) {
|
||||||
throw new IntegrityError("Invalid DEK version");
|
throw new IntegrityError("Invalid DEK version");
|
||||||
}
|
}
|
||||||
|
|
||||||
await tx
|
await trx
|
||||||
.update(file)
|
.updateTable("file")
|
||||||
.set({ encName: { ciphertext: encName, iv: encNameIv } })
|
.set({ encrypted_name: encName })
|
||||||
.where(and(eq(file.userId, userId), eq(file.id, fileId)));
|
.where("id", "=", fileId)
|
||||||
await tx.insert(fileLog).values({
|
.where("user_id", "=", userId)
|
||||||
fileId,
|
.execute();
|
||||||
|
await trx
|
||||||
|
.insertInto("file_log")
|
||||||
|
.values({
|
||||||
|
file_id: fileId,
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
action: "rename",
|
action: "rename",
|
||||||
newName: { ciphertext: encName, iv: encNameIv },
|
new_name: encName,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
});
|
});
|
||||||
},
|
|
||||||
{ behavior: "exclusive" },
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const unregisterFile = async (userId: number, fileId: number) => {
|
export const unregisterFile = async (userId: number, fileId: number) => {
|
||||||
const files = await db
|
return await db.transaction().execute(async (trx) => {
|
||||||
.delete(file)
|
const file = await trx
|
||||||
.where(and(eq(file.userId, userId), eq(file.id, fileId)))
|
.selectFrom("file")
|
||||||
.returning({ path: file.path });
|
.leftJoin("thumbnail", "file.id", "thumbnail.file_id")
|
||||||
if (!files[0]) {
|
.select(["file.path", "thumbnail.path as thumbnailPath"])
|
||||||
|
.where("file.id", "=", fileId)
|
||||||
|
.where("file.user_id", "=", userId)
|
||||||
|
.forUpdate("file")
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (!file) {
|
||||||
throw new IntegrityError("File not found");
|
throw new IntegrityError("File not found");
|
||||||
}
|
}
|
||||||
return files[0].path;
|
|
||||||
|
await trx.deleteFrom("file").where("id", "=", fileId).execute();
|
||||||
|
return file;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const addFileToCategory = async (fileId: number, categoryId: number) => {
|
||||||
|
await db.transaction().execute(async (trx) => {
|
||||||
|
try {
|
||||||
|
await trx
|
||||||
|
.insertInto("file_category")
|
||||||
|
.values({ file_id: fileId, category_id: categoryId })
|
||||||
|
.execute();
|
||||||
|
await trx
|
||||||
|
.insertInto("file_log")
|
||||||
|
.values({
|
||||||
|
file_id: fileId,
|
||||||
|
timestamp: new Date(),
|
||||||
|
action: "add-to-category",
|
||||||
|
category_id: categoryId,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof pg.DatabaseError && e.code === "23505") {
|
||||||
|
throw new IntegrityError("File already added to category");
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAllFileCategories = async (fileId: number) => {
|
||||||
|
const categories = await db
|
||||||
|
.selectFrom("file_category")
|
||||||
|
.innerJoin("category", "file_category.category_id", "category.id")
|
||||||
|
.selectAll("category")
|
||||||
|
.where("file_id", "=", fileId)
|
||||||
|
.execute();
|
||||||
|
return categories.map(
|
||||||
|
(category) =>
|
||||||
|
({
|
||||||
|
id: category.id,
|
||||||
|
mekVersion: category.master_encryption_key_version,
|
||||||
|
encDek: category.encrypted_data_encryption_key,
|
||||||
|
dekVersion: category.data_encryption_key_version,
|
||||||
|
encName: category.encrypted_name,
|
||||||
|
}) satisfies FileCategory,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const removeFileFromCategory = async (fileId: number, categoryId: number) => {
|
||||||
|
await db.transaction().execute(async (trx) => {
|
||||||
|
const res = await trx
|
||||||
|
.deleteFrom("file_category")
|
||||||
|
.where("file_id", "=", fileId)
|
||||||
|
.where("category_id", "=", categoryId)
|
||||||
|
.executeTakeFirst();
|
||||||
|
if (res.numDeletedRows === 0n) {
|
||||||
|
throw new IntegrityError("File not found in category");
|
||||||
|
}
|
||||||
|
|
||||||
|
await trx
|
||||||
|
.insertInto("file_log")
|
||||||
|
.values({
|
||||||
|
file_id: fileId,
|
||||||
|
timestamp: new Date(),
|
||||||
|
action: "remove-from-category",
|
||||||
|
category_id: categoryId,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user