mirror of
https://github.com/kmc7468/arkvault.git
synced 2026-02-04 16:16:55 +00:00
Compare commits
1 Commits
a4912c8952
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a198e5f6dc |
@@ -1,6 +1,5 @@
|
|||||||
.git
|
.git
|
||||||
node_modules
|
node_modules
|
||||||
/Makefile
|
|
||||||
|
|
||||||
# Output
|
# Output
|
||||||
.output
|
.output
|
||||||
@@ -11,16 +10,13 @@ node_modules
|
|||||||
/build
|
/build
|
||||||
/data
|
/data
|
||||||
/library
|
/library
|
||||||
/thumbnails
|
|
||||||
/uploads
|
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
# Editors
|
# VSCode
|
||||||
/.vscode
|
/.vscode
|
||||||
/.idea
|
|
||||||
|
|
||||||
# Env
|
# Env
|
||||||
.env
|
.env
|
||||||
@@ -31,3 +27,6 @@ Thumbs.db
|
|||||||
# Vite
|
# Vite
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
vite.config.ts.timestamp-*
|
vite.config.ts.timestamp-*
|
||||||
|
|
||||||
|
# SQLite
|
||||||
|
*.db
|
||||||
|
|||||||
15
.env.example
15
.env.example
@@ -1,15 +1,10 @@
|
|||||||
# Required environment variables
|
# Required environment variables
|
||||||
DATABASE_PASSWORD=
|
JWT_SECRET=
|
||||||
SESSION_SECRET=
|
|
||||||
|
|
||||||
# Optional environment variables
|
# Optional environment variables
|
||||||
DATABASE_HOST=
|
DATABASE_URL=
|
||||||
DATABASE_PORT=
|
JWT_ACCESS_TOKEN_EXPIRES=
|
||||||
DATABASE_USER=
|
JWT_REFRESH_TOKEN_EXPIRES=
|
||||||
DATABASE_NAME=
|
|
||||||
SESSION_EXPIRES=
|
|
||||||
USER_CLIENT_CHALLENGE_EXPIRES=
|
USER_CLIENT_CHALLENGE_EXPIRES=
|
||||||
SESSION_UPGRADE_CHALLENGE_EXPIRES=
|
TOKEN_UPGRADE_CHALLENGE_EXPIRES=
|
||||||
LIBRARY_PATH=
|
LIBRARY_PATH=
|
||||||
THUMBNAILS_PATH=
|
|
||||||
UPLOADS_PATH=
|
|
||||||
|
|||||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -9,16 +9,13 @@ node_modules
|
|||||||
/build
|
/build
|
||||||
/data
|
/data
|
||||||
/library
|
/library
|
||||||
/thumbnails
|
|
||||||
/uploads
|
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
# Editors
|
# VSCode
|
||||||
/.vscode
|
/.vscode
|
||||||
/.idea
|
|
||||||
|
|
||||||
# Env
|
# Env
|
||||||
.env
|
.env
|
||||||
@@ -29,3 +26,6 @@ Thumbs.db
|
|||||||
# Vite
|
# Vite
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
vite.config.ts.timestamp-*
|
vite.config.ts.timestamp-*
|
||||||
|
|
||||||
|
# SQLite
|
||||||
|
*.db
|
||||||
|
|||||||
@@ -3,5 +3,8 @@ package-lock.json
|
|||||||
pnpm-lock.yaml
|
pnpm-lock.yaml
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
|
# Output
|
||||||
|
/drizzle
|
||||||
|
|
||||||
# Documents
|
# Documents
|
||||||
*.md
|
*.md
|
||||||
|
|||||||
11
Dockerfile
11
Dockerfile
@@ -1,8 +1,8 @@
|
|||||||
# Base Image
|
# Base Image
|
||||||
FROM node:22-alpine AS base
|
FROM node:18-alpine AS base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
RUN npm install -g pnpm@10
|
RUN npm install -g pnpm@8
|
||||||
COPY pnpm-lock.yaml .
|
COPY pnpm-lock.yaml .
|
||||||
|
|
||||||
# Build Stage
|
# Build Stage
|
||||||
@@ -10,9 +10,8 @@ FROM base AS build
|
|||||||
RUN pnpm fetch
|
RUN pnpm fetch
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN pnpm install --offline && \
|
RUN pnpm install --offline
|
||||||
pnpm build && \
|
RUN pnpm build
|
||||||
sed -i "s/http\.createServer()/http.createServer({ requestTimeout: 0 })/g" ./build/index.js
|
|
||||||
|
|
||||||
# Deploy Stage
|
# Deploy Stage
|
||||||
FROM base
|
FROM base
|
||||||
@@ -22,7 +21,9 @@ 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"]
|
||||||
|
|||||||
12
README.md
12
README.md
@@ -23,19 +23,19 @@ vim .env # 아래를 참고하여 환경 변수를 설정해 주세요.
|
|||||||
docker compose up --build -d
|
docker compose up --build -d
|
||||||
```
|
```
|
||||||
|
|
||||||
모든 데이터는 `./data` 디렉터리에 아래에 저장될 거예요.
|
모든 데이터는 `./data` 디렉터리에 저장될 거예요.
|
||||||
|
|
||||||
### Environment Variables
|
### Environment Variables
|
||||||
|
|
||||||
필수 환경 변수가 아닌 경우, 설정해야 하는 특별한 이유가 없다면 기본값을 사용하는 것이 좋아요.
|
필수 환경 변수가 아닌 경우, 설정해야 하는 특별한 이유가 없다면 기본값을 사용하는 것이 좋아요.
|
||||||
|
|
||||||
|이름|필수|기본값|설명|
|
|이름|필수|기본값|설명|
|
||||||
|:-|:-:|:-:|:-|
|
|-:|:-:|:-:|:-|
|
||||||
|`DATABASE_PASSWORD`|Y||데이터베이스에 접근하기 위해 필요한 비밀번호예요. 안전한 값으로 설정해 주세요.|
|
|`JWT_SECRET`|Y||JWT의 서명을 위해 사용돼요. 안전한 값으로 설정해 주세요.|
|
||||||
|`SESSION_SECRET`|Y||Session ID의 서명에 사용되는 비밀번호예요. 안전한 값으로 설정해 주세요.|
|
|`JWT_ACCESS_TOKEN_EXPIRES`||`5m`|Access Token의 유효 시간이에요.|
|
||||||
|`SESSION_EXPIRES`||`14d`|Session의 유효 시간이에요. Session은 마지막으로 사용된 후 설정된 유효 시간이 지나면 자동으로 삭제돼요.|
|
|`JWT_REFRESH_TOKEN_EXPIRES`||`14d`|Refresh Token의 유효 시간이에요.|
|
||||||
|`USER_CLIENT_CHALLENGE_EXPIRES`||`5m`|암호 키를 서버에 처음 등록할 때 사용되는 챌린지의 유효 시간이에요.|
|
|`USER_CLIENT_CHALLENGE_EXPIRES`||`5m`|암호 키를 서버에 처음 등록할 때 사용되는 챌린지의 유효 시간이에요.|
|
||||||
|`SESSION_UPGRADE_CHALLENGE_EXPIRES`||`5m`|암호 키와 함께 로그인할 때 사용되는 챌린지의 유효 시간이에요.|
|
|`TOKEN_UPGRADE_CHALLENGE_EXPIRES`||`5m`|암호 키와 함께 로그인할 때 사용되는 챌린지의 유효 시간이에요.|
|
||||||
|`TRUST_PROXY`|||신뢰할 수 있는 리버스 프록시의 수예요. 설정할 경우 1 이상의 정수로 설정해 주세요. 프록시에서 `X-Forwarded-For` HTTP 헤더를 올바르게 설정하도록 구성해 주세요.|
|
|`TRUST_PROXY`|||신뢰할 수 있는 리버스 프록시의 수예요. 설정할 경우 1 이상의 정수로 설정해 주세요. 프록시에서 `X-Forwarded-For` HTTP 헤더를 올바르게 설정하도록 구성해 주세요.|
|
||||||
|`NODE_ENV`||`production`|ArkVault의 사용 용도예요. `production`인 경우, 컨테이너가 실행될 때마다 DB 마이그레이션이 자동으로 실행돼요.|
|
|`NODE_ENV`||`production`|ArkVault의 사용 용도예요. `production`인 경우, 컨테이너가 실행될 때마다 DB 마이그레이션이 자동으로 실행돼요.|
|
||||||
|`PORT`||`80`|ArkVault 서버의 포트예요.|
|
|`PORT`||`80`|ArkVault 서버의 포트예요.|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
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,44 +2,21 @@ 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/library:/app/data/library
|
- ./data:/app/data
|
||||||
- ./data/thumbnails:/app/data/thumbnails
|
|
||||||
- ./data/uploads:/app/data/uploads
|
|
||||||
environment:
|
environment:
|
||||||
# ArkVault
|
# ArkVault
|
||||||
- DATABASE_HOST=database
|
- DATABASE_URL=/app/data/database.sqlite
|
||||||
- DATABASE_USER=arkvault
|
- JWT_SECRET=${JWT_SECRET:?} # Required
|
||||||
- DATABASE_PASSWORD=${DATABASE_PASSWORD:?} # Required
|
- JWT_ACCESS_TOKEN_EXPIRES
|
||||||
- SESSION_SECRET=${SESSION_SECRET:?} # Required
|
- JWT_REFRESH_TOKEN_EXPIRES
|
||||||
- SESSION_EXPIRES
|
|
||||||
- USER_CLIENT_CHALLENGE_EXPIRES
|
- USER_CLIENT_CHALLENGE_EXPIRES
|
||||||
- SESSION_UPGRADE_CHALLENGE_EXPIRES
|
- TOKEN_UPGRADE_CHALLENGE_EXPIRES
|
||||||
- LIBRARY_PATH=/app/data/library
|
- LIBRARY_PATH=/app/data/library
|
||||||
- THUMBNAILS_PATH=/app/data/thumbnails
|
|
||||||
- UPLOADS_PATH=/app/data/uploads
|
|
||||||
# SvelteKit
|
# SvelteKit
|
||||||
- ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For}
|
- ADDRESS_HEADER=${TRUST_PROXY:+X-Forwarded-For}
|
||||||
- XFF_DEPTH=${TRUST_PROXY:-}
|
- XFF_DEPTH=${TRUST_PROXY:-}
|
||||||
- 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
|
|
||||||
|
|||||||
13
drizzle.config.ts
Normal file
13
drizzle.config.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
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",
|
||||||
|
});
|
||||||
119
drizzle/0000_handy_captain_marvel.sql
Normal file
119
drizzle/0000_handy_captain_marvel.sql
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
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,
|
||||||
|
`challenge` text NOT NULL,
|
||||||
|
`allowed_ip` text NOT NULL,
|
||||||
|
`expires_at` integer NOT NULL,
|
||||||
|
`is_used` integer DEFAULT false 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
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE `directory` (
|
||||||
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
|
`created_at` integer 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 `file` (
|
||||||
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
|
`path` text NOT NULL,
|
||||||
|
`parent_id` integer,
|
||||||
|
`created_at` integer NOT NULL,
|
||||||
|
`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,
|
||||||
|
`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
|
||||||
|
);
|
||||||
|
--> 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,
|
||||||
|
`created_by` integer NOT NULL,
|
||||||
|
`created_at` 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,
|
||||||
|
FOREIGN KEY (`created_by`) REFERENCES `client`(`id`) ON UPDATE no action ON DELETE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE `refresh_token` (
|
||||||
|
`id` text PRIMARY KEY NOT NULL,
|
||||||
|
`user_id` integer NOT NULL,
|
||||||
|
`client_id` integer,
|
||||||
|
`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
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE `token_upgrade_challenge` (
|
||||||
|
`id` integer PRIMARY KEY NOT NULL,
|
||||||
|
`refresh_token_id` text NOT NULL,
|
||||||
|
`client_id` integer NOT NULL,
|
||||||
|
`challenge` text NOT NULL,
|
||||||
|
`allowed_ip` text NOT NULL,
|
||||||
|
`expires_at` integer NOT NULL,
|
||||||
|
`is_used` integer DEFAULT false NOT NULL,
|
||||||
|
FOREIGN KEY (`refresh_token_id`) REFERENCES `refresh_token`(`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
|
||||||
|
);
|
||||||
|
--> 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_challenge_unique` ON `user_client_challenge` (`challenge`);--> 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 `refresh_token_user_id_client_id_unique` ON `refresh_token` (`user_id`,`client_id`);--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX `token_upgrade_challenge_challenge_unique` ON `token_upgrade_challenge` (`challenge`);--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);
|
||||||
874
drizzle/meta/0000_snapshot.json
Normal file
874
drizzle/meta/0000_snapshot.json
Normal file
@@ -0,0 +1,874 @@
|
|||||||
|
{
|
||||||
|
"version": "6",
|
||||||
|
"dialect": "sqlite",
|
||||||
|
"id": "929c6bca-d0c0-4899-afc6-a0a498226f28",
|
||||||
|
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"tables": {
|
||||||
|
"client": {
|
||||||
|
"name": "client",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": true
|
||||||
|
},
|
||||||
|
"encryption_public_key": {
|
||||||
|
"name": "encryption_public_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"signature_public_key": {
|
||||||
|
"name": "signature_public_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"client_encryption_public_key_unique": {
|
||||||
|
"name": "client_encryption_public_key_unique",
|
||||||
|
"columns": [
|
||||||
|
"encryption_public_key"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
},
|
||||||
|
"client_signature_public_key_unique": {
|
||||||
|
"name": "client_signature_public_key_unique",
|
||||||
|
"columns": [
|
||||||
|
"signature_public_key"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
},
|
||||||
|
"client_encryption_public_key_signature_public_key_unique": {
|
||||||
|
"name": "client_encryption_public_key_signature_public_key_unique",
|
||||||
|
"columns": [
|
||||||
|
"encryption_public_key",
|
||||||
|
"signature_public_key"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"user_client": {
|
||||||
|
"name": "user_client",
|
||||||
|
"columns": {
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"client_id": {
|
||||||
|
"name": "client_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"state": {
|
||||||
|
"name": "state",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": "'challenging'"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"user_client_user_id_user_id_fk": {
|
||||||
|
"name": "user_client_user_id_user_id_fk",
|
||||||
|
"tableFrom": "user_client",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"user_client_client_id_client_id_fk": {
|
||||||
|
"name": "user_client_client_id_client_id_fk",
|
||||||
|
"tableFrom": "user_client",
|
||||||
|
"tableTo": "client",
|
||||||
|
"columnsFrom": [
|
||||||
|
"client_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {
|
||||||
|
"user_client_user_id_client_id_pk": {
|
||||||
|
"columns": [
|
||||||
|
"client_id",
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"name": "user_client_user_id_client_id_pk"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"user_client_challenge": {
|
||||||
|
"name": "user_client_challenge",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"client_id": {
|
||||||
|
"name": "client_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"challenge": {
|
||||||
|
"name": "challenge",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"allowed_ip": {
|
||||||
|
"name": "allowed_ip",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"expires_at": {
|
||||||
|
"name": "expires_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"is_used": {
|
||||||
|
"name": "is_used",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"user_client_challenge_challenge_unique": {
|
||||||
|
"name": "user_client_challenge_challenge_unique",
|
||||||
|
"columns": [
|
||||||
|
"challenge"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"user_client_challenge_user_id_user_id_fk": {
|
||||||
|
"name": "user_client_challenge_user_id_user_id_fk",
|
||||||
|
"tableFrom": "user_client_challenge",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"user_client_challenge_client_id_client_id_fk": {
|
||||||
|
"name": "user_client_challenge_client_id_client_id_fk",
|
||||||
|
"tableFrom": "user_client_challenge",
|
||||||
|
"tableTo": "client",
|
||||||
|
"columnsFrom": [
|
||||||
|
"client_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"directory": {
|
||||||
|
"name": "directory",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": true
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"parent_id": {
|
||||||
|
"name": "parent_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"master_encryption_key_version": {
|
||||||
|
"name": "master_encryption_key_version",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_data_encryption_key": {
|
||||||
|
"name": "encrypted_data_encryption_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"data_encryption_key_version": {
|
||||||
|
"name": "data_encryption_key_version",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_name": {
|
||||||
|
"name": "encrypted_name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"directory_encrypted_data_encryption_key_unique": {
|
||||||
|
"name": "directory_encrypted_data_encryption_key_unique",
|
||||||
|
"columns": [
|
||||||
|
"encrypted_data_encryption_key"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"directory_user_id_user_id_fk": {
|
||||||
|
"name": "directory_user_id_user_id_fk",
|
||||||
|
"tableFrom": "directory",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"directory_parent_id_directory_id_fk": {
|
||||||
|
"name": "directory_parent_id_directory_id_fk",
|
||||||
|
"tableFrom": "directory",
|
||||||
|
"tableTo": "directory",
|
||||||
|
"columnsFrom": [
|
||||||
|
"parent_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"directory_user_id_master_encryption_key_version_master_encryption_key_user_id_version_fk": {
|
||||||
|
"name": "directory_user_id_master_encryption_key_version_master_encryption_key_user_id_version_fk",
|
||||||
|
"tableFrom": "directory",
|
||||||
|
"tableTo": "master_encryption_key",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id",
|
||||||
|
"master_encryption_key_version"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"user_id",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"file": {
|
||||||
|
"name": "file",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": true
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"name": "path",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"parent_id": {
|
||||||
|
"name": "parent_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"master_encryption_key_version": {
|
||||||
|
"name": "master_encryption_key_version",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_data_encryption_key": {
|
||||||
|
"name": "encrypted_data_encryption_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"data_encryption_key_version": {
|
||||||
|
"name": "data_encryption_key_version",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"content_type": {
|
||||||
|
"name": "content_type",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_content_iv": {
|
||||||
|
"name": "encrypted_content_iv",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_name": {
|
||||||
|
"name": "encrypted_name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"file_path_unique": {
|
||||||
|
"name": "file_path_unique",
|
||||||
|
"columns": [
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
},
|
||||||
|
"file_encrypted_data_encryption_key_unique": {
|
||||||
|
"name": "file_encrypted_data_encryption_key_unique",
|
||||||
|
"columns": [
|
||||||
|
"encrypted_data_encryption_key"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"file_parent_id_directory_id_fk": {
|
||||||
|
"name": "file_parent_id_directory_id_fk",
|
||||||
|
"tableFrom": "file",
|
||||||
|
"tableTo": "directory",
|
||||||
|
"columnsFrom": [
|
||||||
|
"parent_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"file_user_id_user_id_fk": {
|
||||||
|
"name": "file_user_id_user_id_fk",
|
||||||
|
"tableFrom": "file",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"file_user_id_master_encryption_key_version_master_encryption_key_user_id_version_fk": {
|
||||||
|
"name": "file_user_id_master_encryption_key_version_master_encryption_key_user_id_version_fk",
|
||||||
|
"tableFrom": "file",
|
||||||
|
"tableTo": "master_encryption_key",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id",
|
||||||
|
"master_encryption_key_version"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"user_id",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"client_master_encryption_key": {
|
||||||
|
"name": "client_master_encryption_key",
|
||||||
|
"columns": {
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"client_id": {
|
||||||
|
"name": "client_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"name": "version",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_key": {
|
||||||
|
"name": "encrypted_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"encrypted_key_signature": {
|
||||||
|
"name": "encrypted_key_signature",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"client_master_encryption_key_user_id_user_id_fk": {
|
||||||
|
"name": "client_master_encryption_key_user_id_user_id_fk",
|
||||||
|
"tableFrom": "client_master_encryption_key",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"client_master_encryption_key_client_id_client_id_fk": {
|
||||||
|
"name": "client_master_encryption_key_client_id_client_id_fk",
|
||||||
|
"tableFrom": "client_master_encryption_key",
|
||||||
|
"tableTo": "client",
|
||||||
|
"columnsFrom": [
|
||||||
|
"client_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"client_master_encryption_key_user_id_version_master_encryption_key_user_id_version_fk": {
|
||||||
|
"name": "client_master_encryption_key_user_id_version_master_encryption_key_user_id_version_fk",
|
||||||
|
"tableFrom": "client_master_encryption_key",
|
||||||
|
"tableTo": "master_encryption_key",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"user_id",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {
|
||||||
|
"client_master_encryption_key_user_id_client_id_version_pk": {
|
||||||
|
"columns": [
|
||||||
|
"client_id",
|
||||||
|
"user_id",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"name": "client_master_encryption_key_user_id_client_id_version_pk"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"master_encryption_key": {
|
||||||
|
"name": "master_encryption_key",
|
||||||
|
"columns": {
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"name": "version",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"created_by": {
|
||||||
|
"name": "created_by",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"state": {
|
||||||
|
"name": "state",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"retired_at": {
|
||||||
|
"name": "retired_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"master_encryption_key_user_id_user_id_fk": {
|
||||||
|
"name": "master_encryption_key_user_id_user_id_fk",
|
||||||
|
"tableFrom": "master_encryption_key",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"master_encryption_key_created_by_client_id_fk": {
|
||||||
|
"name": "master_encryption_key_created_by_client_id_fk",
|
||||||
|
"tableFrom": "master_encryption_key",
|
||||||
|
"tableTo": "client",
|
||||||
|
"columnsFrom": [
|
||||||
|
"created_by"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {
|
||||||
|
"master_encryption_key_user_id_version_pk": {
|
||||||
|
"columns": [
|
||||||
|
"user_id",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"name": "master_encryption_key_user_id_version_pk"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"refresh_token": {
|
||||||
|
"name": "refresh_token",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"client_id": {
|
||||||
|
"name": "client_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"expires_at": {
|
||||||
|
"name": "expires_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"refresh_token_user_id_client_id_unique": {
|
||||||
|
"name": "refresh_token_user_id_client_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"user_id",
|
||||||
|
"client_id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"refresh_token_user_id_user_id_fk": {
|
||||||
|
"name": "refresh_token_user_id_user_id_fk",
|
||||||
|
"tableFrom": "refresh_token",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"refresh_token_client_id_client_id_fk": {
|
||||||
|
"name": "refresh_token_client_id_client_id_fk",
|
||||||
|
"tableFrom": "refresh_token",
|
||||||
|
"tableTo": "client",
|
||||||
|
"columnsFrom": [
|
||||||
|
"client_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"token_upgrade_challenge": {
|
||||||
|
"name": "token_upgrade_challenge",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"refresh_token_id": {
|
||||||
|
"name": "refresh_token_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"client_id": {
|
||||||
|
"name": "client_id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"challenge": {
|
||||||
|
"name": "challenge",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"allowed_ip": {
|
||||||
|
"name": "allowed_ip",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"expires_at": {
|
||||||
|
"name": "expires_at",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"is_used": {
|
||||||
|
"name": "is_used",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"token_upgrade_challenge_challenge_unique": {
|
||||||
|
"name": "token_upgrade_challenge_challenge_unique",
|
||||||
|
"columns": [
|
||||||
|
"challenge"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"token_upgrade_challenge_refresh_token_id_refresh_token_id_fk": {
|
||||||
|
"name": "token_upgrade_challenge_refresh_token_id_refresh_token_id_fk",
|
||||||
|
"tableFrom": "token_upgrade_challenge",
|
||||||
|
"tableTo": "refresh_token",
|
||||||
|
"columnsFrom": [
|
||||||
|
"refresh_token_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"token_upgrade_challenge_client_id_client_id_fk": {
|
||||||
|
"name": "token_upgrade_challenge_client_id_client_id_fk",
|
||||||
|
"tableFrom": "token_upgrade_challenge",
|
||||||
|
"tableTo": "client",
|
||||||
|
"columnsFrom": [
|
||||||
|
"client_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"name": "user",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": true
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"name": "email",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"name": "password",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"user_email_unique": {
|
||||||
|
"name": "user_email_unique",
|
||||||
|
"columns": [
|
||||||
|
"email"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {},
|
||||||
|
"_meta": {
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {},
|
||||||
|
"columns": {}
|
||||||
|
},
|
||||||
|
"internal": {
|
||||||
|
"indexes": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
13
drizzle/meta/_journal.json
Normal file
13
drizzle/meta/_journal.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "sqlite",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"idx": 0,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1736170919561,
|
||||||
|
"tag": "0000_handy_captain_marvel",
|
||||||
|
"breakpoints": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,24 +1,21 @@
|
|||||||
import { includeIgnoreFile } from "@eslint/compat";
|
|
||||||
import js from "@eslint/js";
|
|
||||||
import { defineConfig } from "eslint/config";
|
|
||||||
import prettier from "eslint-config-prettier";
|
import prettier from "eslint-config-prettier";
|
||||||
|
import js from "@eslint/js";
|
||||||
|
import { includeIgnoreFile } from "@eslint/compat";
|
||||||
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 defineConfig(
|
export default ts.config(
|
||||||
includeIgnoreFile(gitignorePath),
|
includeIgnoreFile(gitignorePath),
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
...ts.configs.recommended,
|
...ts.configs.recommended,
|
||||||
...svelte.configs.recommended,
|
...svelte.configs["flat/recommended"],
|
||||||
...tailwind.configs["flat/recommended"],
|
...tailwind.configs["flat/recommended"],
|
||||||
prettier,
|
prettier,
|
||||||
...svelte.configs.prettier,
|
...svelte.configs["flat/prettier"],
|
||||||
{
|
{
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
globals: {
|
globals: {
|
||||||
@@ -26,18 +23,13 @@ export default defineConfig(
|
|||||||
...globals.node,
|
...globals.node,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
rules: {
|
|
||||||
"no-undef": "off",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
files: ["**/*.svelte", "**/*.svelte.ts", "**/*.svelte.js"],
|
files: ["**/*.svelte"],
|
||||||
|
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
parserOptions: {
|
parserOptions: {
|
||||||
projectService: true,
|
|
||||||
extraFileExtensions: [".svelte"],
|
|
||||||
parser: ts.parser,
|
parser: ts.parser,
|
||||||
svelteConfig,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
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",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
87
package.json
87
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "arkvault",
|
"name": "arkvault",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.8.0",
|
"version": "0.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
@@ -11,63 +11,52 @@
|
|||||||
"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:up": "docker compose -f docker-compose.dev.yaml -p arkvault-dev up -d",
|
"db:push": "drizzle-kit push",
|
||||||
"db:down": "docker compose -f docker-compose.dev.yaml -p arkvault-dev down",
|
"db:generate": "drizzle-kit generate",
|
||||||
"db:migrate": "kysely migrate"
|
"db:migrate": "drizzle-kit migrate",
|
||||||
|
"db:studio": "drizzle-kit studio"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/compat": "^2.0.1",
|
"@eslint/compat": "^1.2.3",
|
||||||
"@eslint/js": "^9.39.2",
|
"@iconify-json/material-symbols": "^1.2.12",
|
||||||
"@iconify-json/material-symbols": "^1.2.51",
|
"@sveltejs/adapter-node": "^5.2.9",
|
||||||
"@noble/hashes": "^2.0.1",
|
"@sveltejs/kit": "^2.0.0",
|
||||||
"@sveltejs/adapter-node": "^5.4.0",
|
"@sveltejs/vite-plugin-svelte": "^4.0.0",
|
||||||
"@sveltejs/kit": "^2.49.4",
|
"@types/better-sqlite3": "^7.6.11",
|
||||||
"@sveltejs/vite-plugin-svelte": "^6.2.4",
|
|
||||||
"@tanstack/svelte-virtual": "^3.13.18",
|
|
||||||
"@trpc/client": "^11.8.1",
|
|
||||||
"@types/file-saver": "^2.0.7",
|
"@types/file-saver": "^2.0.7",
|
||||||
|
"@types/jsonwebtoken": "^9.0.7",
|
||||||
"@types/ms": "^0.7.34",
|
"@types/ms": "^0.7.34",
|
||||||
"@types/node-schedule": "^2.1.8",
|
"@types/node-schedule": "^2.1.7",
|
||||||
"@types/pg": "^8.16.0",
|
"autoprefixer": "^10.4.20",
|
||||||
"autoprefixer": "^10.4.23",
|
"dexie": "^4.0.10",
|
||||||
"axios": "^1.13.2",
|
"drizzle-kit": "^0.22.0",
|
||||||
"dexie": "^4.2.1",
|
"eslint": "^9.7.0",
|
||||||
"eslint": "^9.39.2",
|
"eslint-config-prettier": "^9.1.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-plugin-svelte": "^2.36.0",
|
||||||
"eslint-plugin-svelte": "^3.14.0",
|
"eslint-plugin-tailwindcss": "^3.17.5",
|
||||||
"eslint-plugin-tailwindcss": "^3.18.2",
|
|
||||||
"exifreader": "^4.35.0",
|
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"globals": "^17.0.0",
|
"globals": "^15.0.0",
|
||||||
"heic2any": "^0.0.4",
|
"heic2any": "^0.0.4",
|
||||||
"kysely-ctl": "^0.19.0",
|
"mime": "^4.0.6",
|
||||||
"lru-cache": "^11.2.4",
|
"prettier": "^3.3.2",
|
||||||
"mime": "^4.1.0",
|
"prettier-plugin-svelte": "^3.2.6",
|
||||||
"p-limit": "^7.2.0",
|
"prettier-plugin-tailwindcss": "^0.6.5",
|
||||||
"prettier": "^3.7.4",
|
"svelte": "^5.0.0",
|
||||||
"prettier-plugin-svelte": "^3.4.1",
|
"svelte-check": "^4.0.0",
|
||||||
"prettier-plugin-tailwindcss": "^0.7.2",
|
"tailwindcss": "^3.4.9",
|
||||||
"svelte": "^5.46.1",
|
"typescript": "^5.0.0",
|
||||||
"svelte-check": "^4.3.5",
|
"typescript-eslint": "^8.0.0",
|
||||||
"tailwindcss": "^3.4.19",
|
"unplugin-icons": "^0.22.0",
|
||||||
"typescript": "^5.9.3",
|
"vite": "^5.4.11"
|
||||||
"typescript-eslint": "^8.52.0",
|
|
||||||
"unplugin-icons": "^22.5.0",
|
|
||||||
"vite": "^7.3.1"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@trpc/server": "^11.8.1",
|
"argon2": "^0.41.1",
|
||||||
"argon2": "^0.44.0",
|
"better-sqlite3": "^11.1.2",
|
||||||
"kysely": "^0.28.9",
|
"drizzle-orm": "^0.33.0",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
"ms": "^2.1.3",
|
"ms": "^2.1.3",
|
||||||
"node-schedule": "^2.1.1",
|
"node-schedule": "^2.1.1",
|
||||||
"pg": "^8.16.3",
|
"uuid": "^11.0.3",
|
||||||
"superjson": "^2.2.6",
|
"zod": "^3.24.1"
|
||||||
"uuid": "^13.0.0",
|
|
||||||
"zod": "^4.3.5"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "^22.0.0",
|
|
||||||
"pnpm": "^10.0.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
5621
pnpm-lock.yaml
generated
5621
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
14
src/app.d.ts
vendored
14
src/app.d.ts
vendored
@@ -5,15 +5,11 @@ import "unplugin-icons/types/svelte";
|
|||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
namespace App {
|
namespace App {
|
||||||
interface Locals {
|
// interface Error {}
|
||||||
ip: string;
|
// interface Locals {}
|
||||||
userAgent: string;
|
// interface PageData {}
|
||||||
session?: {
|
// interface PageState {}
|
||||||
id: string;
|
// interface Platform {}
|
||||||
userId: number;
|
|
||||||
clientId?: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="ko">
|
<html lang="en">
|
||||||
<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" />
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
import type { ClientInit } from "@sveltejs/kit";
|
import type { ClientInit } from "@sveltejs/kit";
|
||||||
import { cleanupDanglingInfos, getClientKey, getMasterKeys, getHmacSecrets } from "$lib/indexedDB";
|
import { getClientKey, getMasterKeys } from "$lib/indexedDB";
|
||||||
import { prepareFileCache } from "$lib/modules/file";
|
import { clientKeyStore, masterKeyStore } 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([
|
||||||
@@ -31,21 +21,6 @@ const prepareMasterKeyStore = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const prepareHmacSecretStore = async () => {
|
|
||||||
const hmacSecrets = await getHmacSecrets();
|
|
||||||
if (hmacSecrets.length > 0) {
|
|
||||||
hmacSecretStore.set(new Map(hmacSecrets.map((hmacSecret) => [hmacSecret.version, hmacSecret])));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const init: ClientInit = async () => {
|
export const init: ClientInit = async () => {
|
||||||
await Promise.all([
|
await Promise.all([prepareClientKeyStore(), prepareMasterKeyStore()]);
|
||||||
requestPersistentStorage(),
|
|
||||||
prepareFileCache(),
|
|
||||||
prepareClientKeyStore(),
|
|
||||||
prepareMasterKeyStore(),
|
|
||||||
prepareHmacSecretStore(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
cleanupDanglingInfos(); // Intended
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,24 +1,34 @@
|
|||||||
import type { ServerInit } from "@sveltejs/kit";
|
import { redirect, type ServerInit, type Handle } from "@sveltejs/kit";
|
||||||
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/kysely";
|
import { migrateDB } from "$lib/server/db/drizzle";
|
||||||
import {
|
import {
|
||||||
cleanupExpiredSessions,
|
cleanupExpiredRefreshTokens,
|
||||||
cleanupExpiredSessionUpgradeChallenges,
|
cleanupExpiredTokenUpgradeChallenges,
|
||||||
} from "$lib/server/db/session";
|
} from "$lib/server/db/token";
|
||||||
import { authenticate, setAgentInfo } from "$lib/server/middlewares";
|
|
||||||
import { cleanupExpiredUploadSessions } from "$lib/server/services/upload";
|
|
||||||
|
|
||||||
export const init: ServerInit = async () => {
|
export const init: ServerInit = () => {
|
||||||
await migrateDB();
|
migrateDB();
|
||||||
|
|
||||||
schedule.scheduleJob("0 * * * *", () => {
|
schedule.scheduleJob("0 * * * *", () => {
|
||||||
cleanupExpiredUserClientChallenges();
|
cleanupExpiredUserClientChallenges();
|
||||||
cleanupExpiredSessions();
|
cleanupExpiredRefreshTokens();
|
||||||
cleanupExpiredSessionUpgradeChallenges();
|
cleanupExpiredTokenUpgradeChallenges();
|
||||||
cleanupExpiredUploadSessions();
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const handle = sequence(setAgentInfo, authenticate);
|
export const handle: Handle = async ({ event, resolve }) => {
|
||||||
|
if (["/api", "/auth"].some((path) => event.url.pathname.startsWith(path))) {
|
||||||
|
return await resolve(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
const accessToken = event.cookies.get("accessToken");
|
||||||
|
if (accessToken) {
|
||||||
|
return await resolve(event);
|
||||||
|
} else {
|
||||||
|
redirect(
|
||||||
|
302,
|
||||||
|
"/auth/login?redirect=" + encodeURIComponent(event.url.pathname + event.url.search),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|||||||
39
src/lib/components/BottomSheet.svelte
Normal file
39
src/lib/components/BottomSheet.svelte
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
<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}
|
||||||
38
src/lib/components/Modal.svelte
Normal file
38
src/lib/components/Modal.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<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}
|
||||||
31
src/lib/components/TopBar.svelte
Normal file
31
src/lib/components/TopBar.svelte
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<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>
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
<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}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
<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}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
<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;
|
|
||||||
itemGap?: number;
|
|
||||||
placeholder?: Snippet;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { class: className, count, item, itemHeight, itemGap, placeholder }: Props = $props();
|
|
||||||
|
|
||||||
let element: HTMLElement | undefined = $state();
|
|
||||||
let scrollMargin = $state(0);
|
|
||||||
|
|
||||||
let virtualizer = $derived(
|
|
||||||
createWindowVirtualizer({
|
|
||||||
count,
|
|
||||||
estimateSize: itemHeight,
|
|
||||||
gap: itemGap,
|
|
||||||
scrollMargin,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const measureItem = (node: HTMLElement) => {
|
|
||||||
$effect(() => $virtualizer.measureElement(node));
|
|
||||||
};
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (!element) return;
|
|
||||||
|
|
||||||
const observer = new ResizeObserver(() => {
|
|
||||||
scrollMargin = Math.round(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 && count === 0}
|
|
||||||
{@render placeholder()}
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { getFileThumbnail } from "$lib/modules/file";
|
|
||||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
info: SummarizedFileInfo;
|
|
||||||
onclick?: (file: SummarizedFileInfo) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { info, onclick }: Props = $props();
|
|
||||||
|
|
||||||
let thumbnail = $derived(getFileThumbnail(info));
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onclick={onclick && (() => setTimeout(() => onclick(info), 100))}
|
|
||||||
class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
|
|
||||||
>
|
|
||||||
{#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}
|
|
||||||
</button>
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<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,6 +0,0 @@
|
|||||||
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";
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
<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>
|
|
||||||
37
src/lib/components/buttons/Button.svelte
Normal file
37
src/lib/components/buttons/Button.svelte
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<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 rounded-xl font-medium"
|
||||||
|
>
|
||||||
|
<div class="h-full w-full p-3 transition active:scale-95">
|
||||||
|
{@render children?.()}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
30
src/lib/components/buttons/EntryButton.svelte
Normal file
30
src/lib/components/buttons/EntryButton.svelte
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<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>
|
||||||
36
src/lib/components/buttons/FloatingButton.svelte
Normal file
36
src/lib/components/buttons/FloatingButton.svelte
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<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>
|
||||||
@@ -10,10 +10,14 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onclick={onclick && (() => setTimeout(onclick, 100))}
|
onclick={() => {
|
||||||
|
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 p-1 transition active:scale-95">
|
<div class="h-full w-full p-1 transition active:scale-95">
|
||||||
{@render children()}
|
{@render children?.()}
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
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";
|
||||||
7
src/lib/components/divs/AdaptiveDiv.svelte
Normal file
7
src/lib/components/divs/AdaptiveDiv.svelte
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
let { children } = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="mx-auto h-full w-full max-w-screen-md">
|
||||||
|
{@render children?.()}
|
||||||
|
</div>
|
||||||
7
src/lib/components/divs/BottomDiv.svelte
Normal file
7
src/lib/components/divs/BottomDiv.svelte
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<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>
|
||||||
20
src/lib/components/divs/TitleDiv.svelte
Normal file
20
src/lib/components/divs/TitleDiv.svelte
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Component, Snippet } from "svelte";
|
||||||
|
import type { SvelteHTMLElements } from "svelte/elements";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
icon?: Component<SvelteHTMLElements["svg"]>;
|
||||||
|
children: Snippet;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { icon: Icon, children }: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div class="box-content flex min-h-[10vh] items-center pt-4">
|
||||||
|
{#if Icon}
|
||||||
|
<Icon class="text-5xl text-gray-600" />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{@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 FullscreenDiv } from "./FullscreenDiv.svelte";
|
export { default as TitleDiv } from "./TitleDiv.svelte";
|
||||||
3
src/lib/components/index.ts
Normal file
3
src/lib/components/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export { default as BottomSheet } from "./BottomSheet.svelte";
|
||||||
|
export { default as Modal } from "./Modal.svelte";
|
||||||
|
export { default as TopBar } from "./TopBar.svelte";
|
||||||
35
src/lib/components/inputs/TextInput.svelte
Normal file
35
src/lib/components/inputs/TextInput.svelte
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<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>
|
||||||
@@ -1,2 +1 @@
|
|||||||
export { default as CheckBox } from "./CheckBox.svelte";
|
|
||||||
export { default as TextInput } from "./TextInput.svelte";
|
export { default as TextInput } from "./TextInput.svelte";
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
<script module lang="ts">
|
|
||||||
import type { DataKey } from "$lib/modules/filesystem";
|
|
||||||
|
|
||||||
export interface SelectedCategory {
|
|
||||||
id: number;
|
|
||||||
dataKey?: DataKey;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<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 { sortEntries } from "$lib/utils";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
categories: SubCategoryInfo[];
|
|
||||||
categoryMenuIcon?: Component<SvelteHTMLElements["svg"]>;
|
|
||||||
onCategoryClick: (category: SelectedCategory) => void;
|
|
||||||
onCategoryMenuClick?: (category: SelectedCategory) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { categories, categoryMenuIcon, onCategoryClick, onCategoryMenuClick }: Props = $props();
|
|
||||||
|
|
||||||
let categoriesWithName = $derived(sortEntries([...categories]));
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#if categoriesWithName.length > 0}
|
|
||||||
<div class="space-y-1">
|
|
||||||
{#each categoriesWithName as category (category.id)}
|
|
||||||
<ActionEntryButton
|
|
||||||
class="h-12"
|
|
||||||
onclick={() => onCategoryClick(category)}
|
|
||||||
actionButtonIcon={categoryMenuIcon}
|
|
||||||
onActionButtonClick={() => onCategoryMenuClick?.(category)}
|
|
||||||
>
|
|
||||||
<CategoryLabel name={category.name} />
|
|
||||||
</ActionEntryButton>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
export * from "./ActionModal.svelte";
|
|
||||||
export { default as ActionModal } from "./ActionModal.svelte";
|
|
||||||
export * from "./Categories.svelte";
|
|
||||||
export { default as Categories } from "./Categories.svelte";
|
|
||||||
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";
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
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";
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export * from "./modals";
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<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}
|
|
||||||
/>
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<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}
|
|
||||||
/>
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
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,2 +0,0 @@
|
|||||||
export * from "./serviceWorker";
|
|
||||||
export * from "./upload";
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export const DECRYPTED_FILE_URL_PREFIX = "/_internal/decryptedFile/";
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
export const AES_GCM_IV_SIZE = 12;
|
|
||||||
export const AES_GCM_TAG_SIZE = 16;
|
|
||||||
export const ENCRYPTION_OVERHEAD = AES_GCM_IV_SIZE + AES_GCM_TAG_SIZE;
|
|
||||||
|
|
||||||
export const CHUNK_SIZE = 4 * 1024 * 1024; // 4 MiB
|
|
||||||
export const ENCRYPTED_CHUNK_SIZE = CHUNK_SIZE + ENCRYPTION_OVERHEAD;
|
|
||||||
35
src/lib/hooks/callApi.ts
Normal file
35
src/lib/hooks/callApi.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
export const refreshToken = async (fetchInternal = fetch) => {
|
||||||
|
return await fetchInternal("/api/auth/refreshToken", { method: "POST" });
|
||||||
|
};
|
||||||
|
|
||||||
|
const callApi = async (input: RequestInfo, init?: RequestInit, fetchInternal = fetch) => {
|
||||||
|
let res = await fetchInternal(input, init);
|
||||||
|
if (res.status === 401) {
|
||||||
|
res = await refreshToken();
|
||||||
|
if (!res.ok) {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
res = await fetchInternal(input, init);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const callGetApi = async (input: RequestInfo, fetchInternal?: typeof fetch) => {
|
||||||
|
return await callApi(input, undefined, fetchInternal);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const callPostApi = async <T>(
|
||||||
|
input: RequestInfo,
|
||||||
|
payload?: T,
|
||||||
|
fetchInternal?: typeof fetch,
|
||||||
|
) => {
|
||||||
|
return await callApi(
|
||||||
|
input,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: payload ? JSON.stringify(payload) : undefined,
|
||||||
|
},
|
||||||
|
fetchInternal,
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -11,7 +11,6 @@ interface KeyExportState {
|
|||||||
verifyKeyBase64: string;
|
verifyKeyBase64: string;
|
||||||
|
|
||||||
masterKeyWrapped: string;
|
masterKeyWrapped: string;
|
||||||
hmacSecretWrapped: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const useAutoNull = <T>(value: T | null) => {
|
const useAutoNull = <T>(value: T | null) => {
|
||||||
2
src/lib/hooks/index.ts
Normal file
2
src/lib/hooks/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./callApi";
|
||||||
|
export * from "./gotoStateful";
|
||||||
@@ -7,28 +7,22 @@ interface ClientKey {
|
|||||||
key: CryptoKey;
|
key: CryptoKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MasterKeyState = "active" | "retired";
|
||||||
|
|
||||||
interface MasterKey {
|
interface MasterKey {
|
||||||
version: number;
|
version: number;
|
||||||
state: "active" | "retired";
|
state: MasterKeyState;
|
||||||
key: CryptoKey;
|
key: CryptoKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface HmacSecret {
|
|
||||||
version: number;
|
|
||||||
state: "active";
|
|
||||||
secret: CryptoKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
const keyStore = new Dexie("keyStore") as Dexie & {
|
const keyStore = new Dexie("keyStore") as Dexie & {
|
||||||
clientKey: EntityTable<ClientKey, "usage">;
|
clientKey: EntityTable<ClientKey, "usage">;
|
||||||
masterKey: EntityTable<MasterKey, "version">;
|
masterKey: EntityTable<MasterKey, "version">;
|
||||||
hmacSecret: EntityTable<HmacSecret, "version">;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
keyStore.version(1).stores({
|
keyStore.version(1).stores({
|
||||||
clientKey: "usage",
|
clientKey: "usage",
|
||||||
masterKey: "version",
|
masterKey: "version",
|
||||||
hmacSecret: "version",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getClientKey = async (usage: ClientKeyUsage) => {
|
export const getClientKey = async (usage: ClientKeyUsage) => {
|
||||||
@@ -68,14 +62,3 @@ export const storeMasterKeys = async (keys: MasterKey[]) => {
|
|||||||
}
|
}
|
||||||
await keyStore.masterKey.bulkPut(keys);
|
await keyStore.masterKey.bulkPut(keys);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getHmacSecrets = async () => {
|
|
||||||
return (await keyStore.hmacSecret.toArray()).filter(({ secret }) => secret.extractable);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeHmacSecrets = async (secrets: HmacSecret[]) => {
|
|
||||||
if (secrets.some(({ secret }) => !secret.extractable)) {
|
|
||||||
throw new Error("Hmac secrets must be extractable");
|
|
||||||
}
|
|
||||||
await keyStore.hmacSecret.bulkPut(secrets);
|
|
||||||
};
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import { Dexie, type EntityTable } from "dexie";
|
|
||||||
|
|
||||||
export interface FileCacheIndex {
|
|
||||||
fileId: number;
|
|
||||||
cachedAt: Date;
|
|
||||||
lastRetrievedAt: Date;
|
|
||||||
size: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cacheIndex = new Dexie("cacheIndex") as Dexie & {
|
|
||||||
fileCache: EntityTable<FileCacheIndex, "fileId">;
|
|
||||||
};
|
|
||||||
|
|
||||||
cacheIndex.version(1).stores({
|
|
||||||
fileCache: "fileId",
|
|
||||||
});
|
|
||||||
|
|
||||||
export const getFileCacheIndex = async () => {
|
|
||||||
return await cacheIndex.fileCache.toArray();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeFileCacheIndex = async (fileCacheIndex: FileCacheIndex) => {
|
|
||||||
await cacheIndex.fileCache.put(fileCacheIndex);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteFileCacheIndex = async (fileId: number) => {
|
|
||||||
await cacheIndex.fileCache.delete(fileId);
|
|
||||||
};
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
import { Dexie, type EntityTable } from "dexie";
|
|
||||||
|
|
||||||
interface DirectoryInfo {
|
|
||||||
id: number;
|
|
||||||
parentId: DirectoryId;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FileInfo {
|
|
||||||
id: number;
|
|
||||||
parentId: DirectoryId;
|
|
||||||
name: string;
|
|
||||||
contentType: string;
|
|
||||||
createdAt?: 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 & {
|
|
||||||
directory: EntityTable<DirectoryInfo, "id">;
|
|
||||||
file: EntityTable<FileInfo, "id">;
|
|
||||||
category: EntityTable<CategoryInfo, "id">;
|
|
||||||
};
|
|
||||||
|
|
||||||
filesystem
|
|
||||||
.version(3)
|
|
||||||
.stores({
|
|
||||||
directory: "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) => {
|
|
||||||
return await filesystem.directory.where({ parentId }).toArray();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getDirectoryInfo = async (id: number) => {
|
|
||||||
return await filesystem.directory.get(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeDirectoryInfo = async (directoryInfo: DirectoryInfo) => {
|
|
||||||
await filesystem.directory.upsert(directoryInfo.id, { ...directoryInfo });
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteDirectoryInfo = async (id: number) => {
|
|
||||||
await filesystem.directory.delete(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteDanglingDirectoryInfos = async (
|
|
||||||
parentId: DirectoryId,
|
|
||||||
validIds: Set<number>,
|
|
||||||
) => {
|
|
||||||
await filesystem.directory
|
|
||||||
.where({ parentId })
|
|
||||||
.and((directory) => !validIds.has(directory.id))
|
|
||||||
.delete();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAllFileInfos = async () => {
|
|
||||||
return await filesystem.file.toArray();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileInfos = async (parentId: DirectoryId) => {
|
|
||||||
return await filesystem.file.where({ parentId }).toArray();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileInfo = async (id: number) => {
|
|
||||||
return await filesystem.file.get(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const bulkGetFileInfos = async (ids: number[]) => {
|
|
||||||
return await filesystem.file.bulkGet(ids);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeFileInfo = async (fileInfo: FileInfo) => {
|
|
||||||
await filesystem.file.upsert(fileInfo.id, { ...fileInfo });
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteFileInfo = async (id: number) => {
|
|
||||||
await filesystem.file.delete(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const bulkDeleteFileInfos = async (ids: number[]) => {
|
|
||||||
await filesystem.file.bulkDelete(ids);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteDanglingFileInfos = async (parentId: DirectoryId, validIds: Set<number>) => {
|
|
||||||
await filesystem.file
|
|
||||||
.where({ parentId })
|
|
||||||
.and((file) => !validIds.has(file.id))
|
|
||||||
.delete();
|
|
||||||
};
|
|
||||||
|
|
||||||
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.upsert(categoryInfo.id, { ...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 deleteDanglingCategoryInfos = async (parentId: CategoryId, validIds: Set<number>) => {
|
|
||||||
await filesystem.category
|
|
||||||
.where({ parentId })
|
|
||||||
.and((category) => !validIds.has(category.id))
|
|
||||||
.delete();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const cleanupDanglingInfos = async () => {
|
|
||||||
const validDirectoryIds: number[] = [];
|
|
||||||
const validFileIds: number[] = [];
|
|
||||||
const directoryQueue: DirectoryId[] = ["root"];
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const directoryId = directoryQueue.shift();
|
|
||||||
if (!directoryId) break;
|
|
||||||
|
|
||||||
const [subDirectories, files] = await Promise.all([
|
|
||||||
filesystem.directory.where({ parentId: directoryId }).toArray(),
|
|
||||||
filesystem.file.where({ parentId: directoryId }).toArray(),
|
|
||||||
]);
|
|
||||||
subDirectories.forEach(({ id }) => {
|
|
||||||
validDirectoryIds.push(id);
|
|
||||||
directoryQueue.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([
|
|
||||||
filesystem.directory.where("id").noneOf(validDirectoryIds).delete(),
|
|
||||||
filesystem.file.where("id").noneOf(validFileIds).delete(),
|
|
||||||
filesystem.category.where("id").noneOf(validCategoryIds).delete(),
|
|
||||||
]);
|
|
||||||
};
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export * from "./cacheIndex";
|
|
||||||
export * from "./filesystem";
|
|
||||||
export * from "./keyStore";
|
|
||||||
@@ -1,15 +1,8 @@
|
|||||||
import { AES_GCM_IV_SIZE } from "$lib/constants";
|
import { encodeString, decodeString, encodeToBase64, decodeFromBase64 } from "./util";
|
||||||
import {
|
|
||||||
encodeString,
|
|
||||||
decodeString,
|
|
||||||
encodeToBase64,
|
|
||||||
decodeFromBase64,
|
|
||||||
concatenateBuffers,
|
|
||||||
} from "./utils";
|
|
||||||
|
|
||||||
export const generateMasterKey = async () => {
|
export const generateMasterKey = async () => {
|
||||||
return {
|
return {
|
||||||
masterKey: await crypto.subtle.generateKey(
|
masterKey: await window.crypto.subtle.generateKey(
|
||||||
{
|
{
|
||||||
name: "AES-KW",
|
name: "AES-KW",
|
||||||
length: 256,
|
length: 256,
|
||||||
@@ -22,7 +15,7 @@ export const generateMasterKey = async () => {
|
|||||||
|
|
||||||
export const generateDataKey = async () => {
|
export const generateDataKey = async () => {
|
||||||
return {
|
return {
|
||||||
dataKey: await crypto.subtle.generateKey(
|
dataKey: await window.crypto.subtle.generateKey(
|
||||||
{
|
{
|
||||||
name: "AES-GCM",
|
name: "AES-GCM",
|
||||||
length: 256,
|
length: 256,
|
||||||
@@ -35,9 +28,9 @@ export const generateDataKey = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const makeAESKeyNonextractable = async (key: CryptoKey) => {
|
export const makeAESKeyNonextractable = async (key: CryptoKey) => {
|
||||||
return await crypto.subtle.importKey(
|
return await window.crypto.subtle.importKey(
|
||||||
"raw",
|
"raw",
|
||||||
await crypto.subtle.exportKey("raw", key),
|
await window.crypto.subtle.exportKey("raw", key),
|
||||||
key.algorithm,
|
key.algorithm,
|
||||||
false,
|
false,
|
||||||
key.usages,
|
key.usages,
|
||||||
@@ -45,12 +38,12 @@ export const makeAESKeyNonextractable = async (key: CryptoKey) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const wrapDataKey = async (dataKey: CryptoKey, masterKey: CryptoKey) => {
|
export const wrapDataKey = async (dataKey: CryptoKey, masterKey: CryptoKey) => {
|
||||||
return encodeToBase64(await crypto.subtle.wrapKey("raw", dataKey, masterKey, "AES-KW"));
|
return encodeToBase64(await window.crypto.subtle.wrapKey("raw", dataKey, masterKey, "AES-KW"));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const unwrapDataKey = async (dataKeyWrapped: string, masterKey: CryptoKey) => {
|
export const unwrapDataKey = async (dataKeyWrapped: string, masterKey: CryptoKey) => {
|
||||||
return {
|
return {
|
||||||
dataKey: await crypto.subtle.unwrapKey(
|
dataKey: await window.crypto.subtle.unwrapKey(
|
||||||
"raw",
|
"raw",
|
||||||
decodeFromBase64(dataKeyWrapped),
|
decodeFromBase64(dataKeyWrapped),
|
||||||
masterKey,
|
masterKey,
|
||||||
@@ -62,30 +55,9 @@ export const unwrapDataKey = async (dataKeyWrapped: string, masterKey: CryptoKey
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const wrapHmacSecret = async (hmacSecret: CryptoKey, masterKey: CryptoKey) => {
|
|
||||||
return encodeToBase64(await crypto.subtle.wrapKey("raw", hmacSecret, masterKey, "AES-KW"));
|
|
||||||
};
|
|
||||||
|
|
||||||
export const unwrapHmacSecret = async (hmacSecretWrapped: string, masterKey: CryptoKey) => {
|
|
||||||
return {
|
|
||||||
hmacSecret: await crypto.subtle.unwrapKey(
|
|
||||||
"raw",
|
|
||||||
decodeFromBase64(hmacSecretWrapped),
|
|
||||||
masterKey,
|
|
||||||
"AES-KW",
|
|
||||||
{
|
|
||||||
name: "HMAC",
|
|
||||||
hash: "SHA-256",
|
|
||||||
} satisfies HmacImportParams,
|
|
||||||
true, // Extractable
|
|
||||||
["sign", "verify"],
|
|
||||||
),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const encryptData = async (data: BufferSource, dataKey: CryptoKey) => {
|
export const encryptData = async (data: BufferSource, dataKey: CryptoKey) => {
|
||||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||||
const ciphertext = await crypto.subtle.encrypt(
|
const ciphertext = await window.crypto.subtle.encrypt(
|
||||||
{
|
{
|
||||||
name: "AES-GCM",
|
name: "AES-GCM",
|
||||||
iv,
|
iv,
|
||||||
@@ -93,18 +65,14 @@ export const encryptData = async (data: BufferSource, dataKey: CryptoKey) => {
|
|||||||
dataKey,
|
dataKey,
|
||||||
data,
|
data,
|
||||||
);
|
);
|
||||||
return { ciphertext, iv: iv.buffer };
|
return { ciphertext, iv: encodeToBase64(iv.buffer) };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const decryptData = async (
|
export const decryptData = async (ciphertext: BufferSource, iv: string, dataKey: CryptoKey) => {
|
||||||
ciphertext: BufferSource,
|
return await window.crypto.subtle.decrypt(
|
||||||
iv: string | BufferSource,
|
|
||||||
dataKey: CryptoKey,
|
|
||||||
) => {
|
|
||||||
return await crypto.subtle.decrypt(
|
|
||||||
{
|
{
|
||||||
name: "AES-GCM",
|
name: "AES-GCM",
|
||||||
iv: typeof iv === "string" ? decodeFromBase64(iv) : iv,
|
iv: decodeFromBase64(iv),
|
||||||
} satisfies AesGcmParams,
|
} satisfies AesGcmParams,
|
||||||
dataKey,
|
dataKey,
|
||||||
ciphertext,
|
ciphertext,
|
||||||
@@ -113,22 +81,9 @@ export const decryptData = async (
|
|||||||
|
|
||||||
export const encryptString = async (plaintext: string, dataKey: CryptoKey) => {
|
export const encryptString = async (plaintext: string, dataKey: CryptoKey) => {
|
||||||
const { ciphertext, iv } = await encryptData(encodeString(plaintext), dataKey);
|
const { ciphertext, iv } = await encryptData(encodeString(plaintext), dataKey);
|
||||||
return { ciphertext: encodeToBase64(ciphertext), iv: encodeToBase64(iv) };
|
return { ciphertext: encodeToBase64(ciphertext), iv };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const decryptString = async (ciphertext: string, iv: string, dataKey: CryptoKey) => {
|
export const decryptString = async (ciphertext: string, iv: string, dataKey: CryptoKey) => {
|
||||||
return decodeString(await decryptData(decodeFromBase64(ciphertext), iv, dataKey));
|
return decodeString(await decryptData(decodeFromBase64(ciphertext), iv, dataKey));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const encryptChunk = async (chunk: ArrayBuffer, dataKey: CryptoKey) => {
|
|
||||||
const { ciphertext, iv } = await encryptData(chunk, dataKey);
|
|
||||||
return concatenateBuffers(iv, ciphertext).buffer;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const decryptChunk = async (encryptedChunk: ArrayBuffer, dataKey: CryptoKey) => {
|
|
||||||
return await decryptData(
|
|
||||||
encryptedChunk.slice(AES_GCM_IV_SIZE),
|
|
||||||
encryptedChunk.slice(0, AES_GCM_IV_SIZE),
|
|
||||||
dataKey,
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export * from "./aes";
|
export * from "./aes";
|
||||||
export * from "./rsa";
|
export * from "./rsa";
|
||||||
export * from "./sha";
|
export * from "./sha";
|
||||||
export * from "./utils";
|
export * from "./util";
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { encodeString, encodeToBase64, decodeFromBase64 } from "./utils";
|
import { encodeString, encodeToBase64, decodeFromBase64 } from "./util";
|
||||||
|
|
||||||
export const generateEncryptionKeyPair = async () => {
|
export const generateEncryptionKeyPair = async () => {
|
||||||
const keyPair = await crypto.subtle.generateKey(
|
const keyPair = await window.crypto.subtle.generateKey(
|
||||||
{
|
{
|
||||||
name: "RSA-OAEP",
|
name: "RSA-OAEP",
|
||||||
modulusLength: 4096,
|
modulusLength: 4096,
|
||||||
@@ -18,7 +18,7 @@ export const generateEncryptionKeyPair = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const generateSigningKeyPair = async () => {
|
export const generateSigningKeyPair = async () => {
|
||||||
const keyPair = await crypto.subtle.generateKey(
|
const keyPair = await window.crypto.subtle.generateKey(
|
||||||
{
|
{
|
||||||
name: "RSA-PSS",
|
name: "RSA-PSS",
|
||||||
modulusLength: 4096,
|
modulusLength: 4096,
|
||||||
@@ -37,7 +37,7 @@ export const generateSigningKeyPair = async () => {
|
|||||||
export const exportRSAKey = async (key: CryptoKey) => {
|
export const exportRSAKey = async (key: CryptoKey) => {
|
||||||
const format = key.type === "public" ? ("spki" as const) : ("pkcs8" as const);
|
const format = key.type === "public" ? ("spki" as const) : ("pkcs8" as const);
|
||||||
return {
|
return {
|
||||||
key: await crypto.subtle.exportKey(format, key),
|
key: await window.crypto.subtle.exportKey(format, key),
|
||||||
format,
|
format,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -46,63 +46,19 @@ 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 crypto.subtle.importKey(
|
|
||||||
"spki",
|
|
||||||
decodeFromBase64(encryptKeyBase64),
|
|
||||||
algorithm,
|
|
||||||
true,
|
|
||||||
["encrypt", "wrapKey"],
|
|
||||||
);
|
|
||||||
const decryptKey = await 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 crypto.subtle.importKey(
|
|
||||||
"pkcs8",
|
|
||||||
decodeFromBase64(signKeyBase64),
|
|
||||||
algorithm,
|
|
||||||
true,
|
|
||||||
["sign"],
|
|
||||||
);
|
|
||||||
const verifyKey = await 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 crypto.subtle.importKey(format, exportedKey, key.algorithm, false, key.usages);
|
return await window.crypto.subtle.importKey(
|
||||||
|
format,
|
||||||
|
exportedKey,
|
||||||
|
key.algorithm,
|
||||||
|
false,
|
||||||
|
key.usages,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const decryptChallenge = async (challenge: string, decryptKey: CryptoKey) => {
|
export const decryptChallenge = async (challenge: string, decryptKey: CryptoKey) => {
|
||||||
return await crypto.subtle.decrypt(
|
return await window.crypto.subtle.decrypt(
|
||||||
{
|
{
|
||||||
name: "RSA-OAEP",
|
name: "RSA-OAEP",
|
||||||
} satisfies RsaOaepParams,
|
} satisfies RsaOaepParams,
|
||||||
@@ -113,7 +69,7 @@ export const decryptChallenge = async (challenge: string, decryptKey: CryptoKey)
|
|||||||
|
|
||||||
export const wrapMasterKey = async (masterKey: CryptoKey, encryptKey: CryptoKey) => {
|
export const wrapMasterKey = async (masterKey: CryptoKey, encryptKey: CryptoKey) => {
|
||||||
return encodeToBase64(
|
return encodeToBase64(
|
||||||
await crypto.subtle.wrapKey("raw", masterKey, encryptKey, {
|
await window.crypto.subtle.wrapKey("raw", masterKey, encryptKey, {
|
||||||
name: "RSA-OAEP",
|
name: "RSA-OAEP",
|
||||||
} satisfies RsaOaepParams),
|
} satisfies RsaOaepParams),
|
||||||
);
|
);
|
||||||
@@ -125,7 +81,7 @@ export const unwrapMasterKey = async (
|
|||||||
extractable = false,
|
extractable = false,
|
||||||
) => {
|
) => {
|
||||||
return {
|
return {
|
||||||
masterKey: await crypto.subtle.unwrapKey(
|
masterKey: await window.crypto.subtle.unwrapKey(
|
||||||
"raw",
|
"raw",
|
||||||
decodeFromBase64(masterKeyWrapped),
|
decodeFromBase64(masterKeyWrapped),
|
||||||
decryptKey,
|
decryptKey,
|
||||||
@@ -139,8 +95,8 @@ export const unwrapMasterKey = async (
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const signMessageRSA = async (message: BufferSource, signKey: CryptoKey) => {
|
export const signMessage = async (message: BufferSource, signKey: CryptoKey) => {
|
||||||
return await crypto.subtle.sign(
|
return await window.crypto.subtle.sign(
|
||||||
{
|
{
|
||||||
name: "RSA-PSS",
|
name: "RSA-PSS",
|
||||||
saltLength: 32, // SHA-256
|
saltLength: 32, // SHA-256
|
||||||
@@ -150,12 +106,12 @@ export const signMessageRSA = async (message: BufferSource, signKey: CryptoKey)
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const verifySignatureRSA = async (
|
export const verifySignature = async (
|
||||||
message: BufferSource,
|
message: BufferSource,
|
||||||
signature: BufferSource,
|
signature: BufferSource,
|
||||||
verifyKey: CryptoKey,
|
verifyKey: CryptoKey,
|
||||||
) => {
|
) => {
|
||||||
return await crypto.subtle.verify(
|
return await window.crypto.subtle.verify(
|
||||||
{
|
{
|
||||||
name: "RSA-PSS",
|
name: "RSA-PSS",
|
||||||
saltLength: 32, // SHA-256
|
saltLength: 32, // SHA-256
|
||||||
@@ -175,7 +131,7 @@ export const signMasterKeyWrapped = async (
|
|||||||
version: masterKeyVersion,
|
version: masterKeyVersion,
|
||||||
key: masterKeyWrapped,
|
key: masterKeyWrapped,
|
||||||
});
|
});
|
||||||
return encodeToBase64(await signMessageRSA(encodeString(serialized), signKey));
|
return encodeToBase64(await signMessage(encodeString(serialized), signKey));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const verifyMasterKeyWrapped = async (
|
export const verifyMasterKeyWrapped = async (
|
||||||
@@ -188,7 +144,7 @@ export const verifyMasterKeyWrapped = async (
|
|||||||
version: masterKeyVersion,
|
version: masterKeyVersion,
|
||||||
key: masterKeyWrapped,
|
key: masterKeyWrapped,
|
||||||
});
|
});
|
||||||
return await verifySignatureRSA(
|
return await verifySignature(
|
||||||
encodeString(serialized),
|
encodeString(serialized),
|
||||||
decodeFromBase64(masterKeyWrappedSig),
|
decodeFromBase64(masterKeyWrappedSig),
|
||||||
verifyKey,
|
verifyKey,
|
||||||
|
|||||||
@@ -1,41 +1,3 @@
|
|||||||
import HmacWorker from "$workers/hmac?worker";
|
|
||||||
import type { ComputeMessage, ResultMessage } from "$workers/hmac";
|
|
||||||
|
|
||||||
export const digestMessage = async (message: BufferSource) => {
|
export const digestMessage = async (message: BufferSource) => {
|
||||||
return await crypto.subtle.digest("SHA-256", message);
|
return await window.crypto.subtle.digest("SHA-256", message);
|
||||||
};
|
|
||||||
|
|
||||||
export const generateHmacSecret = async () => {
|
|
||||||
return {
|
|
||||||
hmacSecret: await crypto.subtle.generateKey(
|
|
||||||
{
|
|
||||||
name: "HMAC",
|
|
||||||
hash: "SHA-256",
|
|
||||||
} satisfies HmacKeyGenParams,
|
|
||||||
true,
|
|
||||||
["sign", "verify"],
|
|
||||||
),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const signMessageHmac = async (message: Blob, hmacSecret: CryptoKey) => {
|
|
||||||
const stream = message.stream();
|
|
||||||
const hmacSecretRaw = new Uint8Array(await crypto.subtle.exportKey("raw", hmacSecret));
|
|
||||||
const worker = new HmacWorker();
|
|
||||||
|
|
||||||
return new Promise<Uint8Array>((resolve, reject) => {
|
|
||||||
worker.onmessage = ({ data }: MessageEvent<ResultMessage>) => {
|
|
||||||
resolve(data.result);
|
|
||||||
worker.terminate();
|
|
||||||
};
|
|
||||||
|
|
||||||
worker.onerror = ({ error }) => {
|
|
||||||
reject(error);
|
|
||||||
worker.terminate();
|
|
||||||
};
|
|
||||||
|
|
||||||
worker.postMessage({ stream, key: hmacSecretRaw } satisfies ComputeMessage, {
|
|
||||||
transfer: [stream, hmacSecretRaw.buffer],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ export const decodeString = (data: ArrayBuffer) => {
|
|||||||
return textDecoder.decode(data);
|
return textDecoder.decode(data);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const encodeToBase64 = (data: ArrayBuffer | Uint8Array) => {
|
export const encodeToBase64 = (data: ArrayBuffer) => {
|
||||||
return btoa(String.fromCharCode(...(data instanceof ArrayBuffer ? new Uint8Array(data) : data)));
|
return btoa(String.fromCharCode(...new Uint8Array(data)));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const decodeFromBase64 = (data: string) => {
|
export const decodeFromBase64 = (data: string) => {
|
||||||
89
src/lib/modules/file.ts
Normal file
89
src/lib/modules/file.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import { writable, type Writable } from "svelte/store";
|
||||||
|
import { callGetApi } from "$lib/hooks";
|
||||||
|
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
||||||
|
import type { DirectoryInfoResponse, FileInfoResponse } from "$lib/server/schemas";
|
||||||
|
import {
|
||||||
|
directoryInfoStore,
|
||||||
|
fileInfoStore,
|
||||||
|
type DirectoryInfo,
|
||||||
|
type FileInfo,
|
||||||
|
} from "$lib/stores/file";
|
||||||
|
|
||||||
|
const fetchDirectoryInfo = async (
|
||||||
|
directoryId: "root" | number,
|
||||||
|
masterKey: CryptoKey,
|
||||||
|
infoStore: Writable<DirectoryInfo | null>,
|
||||||
|
) => {
|
||||||
|
const res = await callGetApi(`/api/directory/${directoryId}`);
|
||||||
|
if (!res.ok) throw new Error("Failed to fetch directory information");
|
||||||
|
const { metadata, subDirectories, files }: DirectoryInfoResponse = await res.json();
|
||||||
|
|
||||||
|
let newInfo: DirectoryInfo;
|
||||||
|
if (directoryId === "root") {
|
||||||
|
newInfo = {
|
||||||
|
id: "root",
|
||||||
|
subDirectoryIds: subDirectories,
|
||||||
|
fileIds: files,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const { dataKey } = await unwrapDataKey(metadata!.dek, masterKey);
|
||||||
|
newInfo = {
|
||||||
|
id: directoryId,
|
||||||
|
dataKey,
|
||||||
|
dataKeyVersion: new Date(metadata!.dekVersion),
|
||||||
|
name: await decryptString(metadata!.name, metadata!.nameIv, dataKey),
|
||||||
|
subDirectoryIds: subDirectories,
|
||||||
|
fileIds: files,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
infoStore.update(() => newInfo);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getDirectoryInfo = (directoryId: "root" | number, masterKey: CryptoKey) => {
|
||||||
|
// TODO: MEK rotation
|
||||||
|
|
||||||
|
let info = directoryInfoStore.get(directoryId);
|
||||||
|
if (!info) {
|
||||||
|
info = writable(null);
|
||||||
|
directoryInfoStore.set(directoryId, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchDirectoryInfo(directoryId, masterKey, info);
|
||||||
|
return info;
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchFileInfo = async (
|
||||||
|
fileId: number,
|
||||||
|
masterKey: CryptoKey,
|
||||||
|
infoStore: Writable<FileInfo | null>,
|
||||||
|
) => {
|
||||||
|
const res = await callGetApi(`/api/file/${fileId}`);
|
||||||
|
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 newInfo: FileInfo = {
|
||||||
|
id: fileId,
|
||||||
|
dataKey,
|
||||||
|
dataKeyVersion: new Date(metadata.dekVersion),
|
||||||
|
contentType: metadata.contentType,
|
||||||
|
contentIv: metadata.contentIv,
|
||||||
|
name: await decryptString(metadata.name, metadata.nameIv, dataKey),
|
||||||
|
};
|
||||||
|
|
||||||
|
infoStore.update(() => newInfo);
|
||||||
|
};
|
||||||
|
|
||||||
|
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, masterKey, info);
|
||||||
|
return info;
|
||||||
|
};
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import {
|
|
||||||
getFileCacheIndex as getFileCacheIndexFromIndexedDB,
|
|
||||||
storeFileCacheIndex,
|
|
||||||
deleteFileCacheIndex,
|
|
||||||
type FileCacheIndex,
|
|
||||||
} from "$lib/indexedDB";
|
|
||||||
import { readFile, writeFile, deleteFile } from "$lib/modules/opfs";
|
|
||||||
|
|
||||||
const fileCacheIndex = new Map<number, FileCacheIndex>();
|
|
||||||
|
|
||||||
export const prepareFileCache = async () => {
|
|
||||||
for (const cache of await getFileCacheIndexFromIndexedDB()) {
|
|
||||||
fileCacheIndex.set(cache.fileId, cache);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileCacheIndex = () => {
|
|
||||||
return Array.from(fileCacheIndex.values());
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileCache = async (fileId: number) => {
|
|
||||||
const cacheIndex = fileCacheIndex.get(fileId);
|
|
||||||
if (!cacheIndex) return null;
|
|
||||||
|
|
||||||
cacheIndex.lastRetrievedAt = new Date();
|
|
||||||
storeFileCacheIndex(cacheIndex); // Intended
|
|
||||||
return await readFile(`/cache/${fileId}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeFileCache = async (fileId: number, fileBuffer: ArrayBuffer) => {
|
|
||||||
const now = new Date();
|
|
||||||
await writeFile(`/cache/${fileId}`, fileBuffer);
|
|
||||||
|
|
||||||
const cacheIndex: FileCacheIndex = {
|
|
||||||
fileId,
|
|
||||||
cachedAt: now,
|
|
||||||
lastRetrievedAt: now,
|
|
||||||
size: fileBuffer.byteLength,
|
|
||||||
};
|
|
||||||
fileCacheIndex.set(fileId, cacheIndex);
|
|
||||||
await storeFileCacheIndex(cacheIndex);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteFileCache = async (fileId: number) => {
|
|
||||||
if (!fileCacheIndex.has(fileId)) return;
|
|
||||||
|
|
||||||
fileCacheIndex.delete(fileId);
|
|
||||||
await deleteFile(`/cache/${fileId}`);
|
|
||||||
await deleteFileCacheIndex(fileId);
|
|
||||||
};
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
import axios from "axios";
|
|
||||||
import { limitFunction } from "p-limit";
|
|
||||||
import { ENCRYPTED_CHUNK_SIZE } from "$lib/constants";
|
|
||||||
import { decryptChunk, concatenateBuffers } 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,
|
|
||||||
encryptedChunkSize: number,
|
|
||||||
dataKey: CryptoKey,
|
|
||||||
) => {
|
|
||||||
state.status = "decrypting";
|
|
||||||
|
|
||||||
const chunks: ArrayBuffer[] = [];
|
|
||||||
let offset = 0;
|
|
||||||
|
|
||||||
while (offset < fileEncrypted.byteLength) {
|
|
||||||
const nextOffset = Math.min(offset + encryptedChunkSize, fileEncrypted.byteLength);
|
|
||||||
chunks.push(await decryptChunk(fileEncrypted.slice(offset, nextOffset), dataKey));
|
|
||||||
offset = nextOffset;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileBuffer = concatenateBuffers(...chunks).buffer;
|
|
||||||
state.status = "decrypted";
|
|
||||||
state.result = fileBuffer;
|
|
||||||
return fileBuffer;
|
|
||||||
},
|
|
||||||
{ concurrency: 4 },
|
|
||||||
);
|
|
||||||
|
|
||||||
export const downloadFile = async (id: number, dataKey: CryptoKey, isLegacy: boolean) => {
|
|
||||||
downloadingFiles.push({
|
|
||||||
id,
|
|
||||||
status: "download-pending",
|
|
||||||
});
|
|
||||||
const state = downloadingFiles.at(-1)!;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const fileEncrypted = await requestFileDownload(state, id);
|
|
||||||
return await decryptFile(
|
|
||||||
state,
|
|
||||||
fileEncrypted,
|
|
||||||
isLegacy ? fileEncrypted.byteLength : ENCRYPTED_CHUNK_SIZE,
|
|
||||||
dataKey,
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
state.status = "error";
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
export * from "./cache";
|
|
||||||
export * from "./download.svelte";
|
|
||||||
export * from "./thumbnail";
|
|
||||||
export * from "./upload.svelte";
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
import { LRUCache } from "lru-cache";
|
|
||||||
import { writable, type Writable } from "svelte/store";
|
|
||||||
import { browser } from "$app/environment";
|
|
||||||
import { decryptChunk } from "$lib/modules/crypto";
|
|
||||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
|
||||||
import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs";
|
|
||||||
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
|
||||||
|
|
||||||
const loadedThumbnails = new LRUCache<number, Writable<string>>({ max: 100 });
|
|
||||||
const loadingThumbnails = new Map<number, Writable<string | undefined>>();
|
|
||||||
|
|
||||||
const fetchFromOpfs = async (fileId: number) => {
|
|
||||||
const thumbnailBuffer = await readFile(`/thumbnail/file/${fileId}`);
|
|
||||||
if (thumbnailBuffer) {
|
|
||||||
return getThumbnailUrl(thumbnailBuffer);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchFromServer = async (fileId: number, dataKey: CryptoKey) => {
|
|
||||||
const res = await fetch(`/api/file/${fileId}/thumbnail/download`);
|
|
||||||
if (!res.ok) return null;
|
|
||||||
|
|
||||||
const thumbnailBuffer = await decryptChunk(await res.arrayBuffer(), dataKey);
|
|
||||||
|
|
||||||
void writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
|
|
||||||
return getThumbnailUrl(thumbnailBuffer);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileThumbnail = (file: SummarizedFileInfo) => {
|
|
||||||
if (
|
|
||||||
!browser ||
|
|
||||||
!(file.contentType.startsWith("image/") || file.contentType.startsWith("video/"))
|
|
||||||
) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const thumbnail = loadedThumbnails.get(file.id);
|
|
||||||
if (thumbnail) return thumbnail;
|
|
||||||
|
|
||||||
let loadingThumbnail = loadingThumbnails.get(file.id);
|
|
||||||
if (loadingThumbnail) return loadingThumbnail;
|
|
||||||
|
|
||||||
loadingThumbnail = writable(undefined);
|
|
||||||
loadingThumbnails.set(file.id, loadingThumbnail);
|
|
||||||
|
|
||||||
fetchFromOpfs(file.id)
|
|
||||||
.then((thumbnail) => thumbnail ?? (file.dataKey && fetchFromServer(file.id, file.dataKey.key)))
|
|
||||||
.then((thumbnail) => {
|
|
||||||
if (thumbnail) {
|
|
||||||
loadingThumbnail.set(thumbnail);
|
|
||||||
loadedThumbnails.set(file.id, loadingThumbnail as Writable<string>);
|
|
||||||
}
|
|
||||||
loadingThumbnails.delete(file.id);
|
|
||||||
});
|
|
||||||
return loadingThumbnail;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeFileThumbnailCache = async (fileId: number, thumbnailBuffer: ArrayBuffer) => {
|
|
||||||
await writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
|
|
||||||
|
|
||||||
const oldThumbnail = loadedThumbnails.get(fileId);
|
|
||||||
if (oldThumbnail) {
|
|
||||||
oldThumbnail.set(getThumbnailUrl(thumbnailBuffer));
|
|
||||||
} else {
|
|
||||||
loadedThumbnails.set(fileId, writable(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`);
|
|
||||||
};
|
|
||||||
@@ -1,261 +0,0 @@
|
|||||||
import ExifReader from "exifreader";
|
|
||||||
import { limitFunction } from "p-limit";
|
|
||||||
import { CHUNK_SIZE } from "$lib/constants";
|
|
||||||
import { encodeToBase64, generateDataKey, wrapDataKey, encryptString } from "$lib/modules/crypto";
|
|
||||||
import { signMessageHmac } from "$lib/modules/crypto";
|
|
||||||
import { Scheduler } from "$lib/modules/scheduler";
|
|
||||||
import { generateThumbnail } from "$lib/modules/thumbnail";
|
|
||||||
import { uploadBlob } from "$lib/modules/upload";
|
|
||||||
import type { MasterKey, HmacSecret } from "$lib/stores";
|
|
||||||
import { trpc } from "$trpc/client";
|
|
||||||
|
|
||||||
export interface FileUploadState {
|
|
||||||
name: string;
|
|
||||||
parentId: DirectoryId;
|
|
||||||
status:
|
|
||||||
| "queued"
|
|
||||||
| "encryption-pending"
|
|
||||||
| "encrypting"
|
|
||||||
| "upload-pending"
|
|
||||||
| "uploading"
|
|
||||||
| "uploaded"
|
|
||||||
| "canceled"
|
|
||||||
| "error";
|
|
||||||
progress?: number;
|
|
||||||
rate?: number;
|
|
||||||
estimated?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type LiveFileUploadState = FileUploadState & {
|
|
||||||
status: "queued" | "encryption-pending" | "encrypting" | "upload-pending" | "uploading";
|
|
||||||
};
|
|
||||||
|
|
||||||
const scheduler = new Scheduler<
|
|
||||||
{ fileId: number; fileBuffer?: ArrayBuffer; thumbnailBuffer?: ArrayBuffer } | undefined
|
|
||||||
>();
|
|
||||||
let uploadingFiles: FileUploadState[] = $state([]);
|
|
||||||
|
|
||||||
const isFileUploading = (status: FileUploadState["status"]) =>
|
|
||||||
["queued", "encryption-pending", "encrypting", "upload-pending", "uploading"].includes(status);
|
|
||||||
|
|
||||||
export const getUploadingFiles = (parentId?: DirectoryId) => {
|
|
||||||
return uploadingFiles.filter(
|
|
||||||
(file) =>
|
|
||||||
(parentId === undefined || file.parentId === parentId) && isFileUploading(file.status),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const clearUploadedFiles = () => {
|
|
||||||
uploadingFiles = uploadingFiles.filter((file) => isFileUploading(file.status));
|
|
||||||
};
|
|
||||||
|
|
||||||
const requestDuplicateFileScan = limitFunction(
|
|
||||||
async (
|
|
||||||
state: FileUploadState,
|
|
||||||
file: File,
|
|
||||||
hmacSecret: HmacSecret,
|
|
||||||
onDuplicate: () => Promise<boolean>,
|
|
||||||
) => {
|
|
||||||
state.status = "encryption-pending";
|
|
||||||
|
|
||||||
const fileSigned = encodeToBase64(await signMessageHmac(file, hmacSecret.secret));
|
|
||||||
const files = await trpc().file.listByHash.query({
|
|
||||||
hskVersion: hmacSecret.version,
|
|
||||||
contentHmac: fileSigned,
|
|
||||||
});
|
|
||||||
if (files.length === 0 || (await onDuplicate())) {
|
|
||||||
return { fileSigned };
|
|
||||||
} else {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
|
|
||||||
const getFileType = (file: File) => {
|
|
||||||
if (file.type) return file.type;
|
|
||||||
if (file.name.endsWith(".heic")) return "image/heic";
|
|
||||||
throw new Error("Unknown file type");
|
|
||||||
};
|
|
||||||
|
|
||||||
const extractExifDateTime = (fileBuffer: ArrayBuffer) => {
|
|
||||||
const exif = ExifReader.load(fileBuffer);
|
|
||||||
const dateTimeOriginal = exif["DateTimeOriginal"]?.description;
|
|
||||||
const offsetTimeOriginal = exif["OffsetTimeOriginal"]?.description;
|
|
||||||
if (!dateTimeOriginal) return undefined;
|
|
||||||
|
|
||||||
const [date, time] = dateTimeOriginal.split(" ");
|
|
||||||
if (!date || !time) return undefined;
|
|
||||||
|
|
||||||
const [year, month, day] = date.split(":").map(Number);
|
|
||||||
const [hour, minute, second] = time.split(":").map(Number);
|
|
||||||
if (!year || !month || !day || !hour || !minute || !second) return undefined;
|
|
||||||
|
|
||||||
if (!offsetTimeOriginal) {
|
|
||||||
// No timezone information.. Assume local timezone
|
|
||||||
return new Date(year, month - 1, day, hour, minute, second);
|
|
||||||
}
|
|
||||||
|
|
||||||
const offsetSign = offsetTimeOriginal[0] === "+" ? 1 : -1;
|
|
||||||
const [offsetHour, offsetMinute] = offsetTimeOriginal.slice(1).split(":").map(Number);
|
|
||||||
|
|
||||||
const utcDate = Date.UTC(year, month - 1, day, hour, minute, second);
|
|
||||||
const offsetMs = offsetSign * ((offsetHour ?? 0) * 60 + (offsetMinute ?? 0)) * 60 * 1000;
|
|
||||||
return new Date(utcDate - offsetMs);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface FileMetadata {
|
|
||||||
parentId: "root" | number;
|
|
||||||
name: string;
|
|
||||||
createdAt?: Date;
|
|
||||||
lastModifiedAt: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestFileMetadataEncryption = limitFunction(
|
|
||||||
async (
|
|
||||||
state: FileUploadState,
|
|
||||||
file: Blob,
|
|
||||||
fileMetadata: FileMetadata,
|
|
||||||
masterKey: MasterKey,
|
|
||||||
hmacSecret: HmacSecret,
|
|
||||||
) => {
|
|
||||||
state.status = "encrypting";
|
|
||||||
|
|
||||||
const { dataKey, dataKeyVersion } = await generateDataKey();
|
|
||||||
const dataKeyWrapped = await wrapDataKey(dataKey, masterKey.key);
|
|
||||||
|
|
||||||
const [nameEncrypted, createdAtEncrypted, lastModifiedAtEncrypted, thumbnailBuffer] =
|
|
||||||
await Promise.all([
|
|
||||||
encryptString(fileMetadata.name, dataKey),
|
|
||||||
fileMetadata.createdAt &&
|
|
||||||
encryptString(fileMetadata.createdAt.getTime().toString(), dataKey),
|
|
||||||
encryptString(fileMetadata.lastModifiedAt.getTime().toString(), dataKey),
|
|
||||||
generateThumbnail(file).then((blob) => blob?.arrayBuffer()),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const { uploadId } = await trpc().upload.startFileUpload.mutate({
|
|
||||||
chunks: Math.ceil(file.size / CHUNK_SIZE),
|
|
||||||
parent: fileMetadata.parentId,
|
|
||||||
mekVersion: masterKey.version,
|
|
||||||
dek: dataKeyWrapped,
|
|
||||||
dekVersion: dataKeyVersion,
|
|
||||||
hskVersion: hmacSecret.version,
|
|
||||||
contentType: file.type,
|
|
||||||
name: nameEncrypted.ciphertext,
|
|
||||||
nameIv: nameEncrypted.iv,
|
|
||||||
createdAt: createdAtEncrypted?.ciphertext,
|
|
||||||
createdAtIv: createdAtEncrypted?.iv,
|
|
||||||
lastModifiedAt: lastModifiedAtEncrypted.ciphertext,
|
|
||||||
lastModifiedAtIv: lastModifiedAtEncrypted.iv,
|
|
||||||
});
|
|
||||||
|
|
||||||
state.status = "upload-pending";
|
|
||||||
return { uploadId, thumbnailBuffer, dataKey, dataKeyVersion };
|
|
||||||
},
|
|
||||||
{ concurrency: 4 },
|
|
||||||
);
|
|
||||||
|
|
||||||
const requestFileUpload = limitFunction(
|
|
||||||
async (
|
|
||||||
state: FileUploadState,
|
|
||||||
uploadId: string,
|
|
||||||
file: Blob,
|
|
||||||
fileSigned: string,
|
|
||||||
thumbnailBuffer: ArrayBuffer | undefined,
|
|
||||||
dataKey: CryptoKey,
|
|
||||||
dataKeyVersion: Date,
|
|
||||||
) => {
|
|
||||||
state.status = "uploading";
|
|
||||||
|
|
||||||
await uploadBlob(uploadId, file, dataKey, {
|
|
||||||
onProgress(s) {
|
|
||||||
state.progress = s.progress;
|
|
||||||
state.rate = s.rate;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const { file: fileId } = await trpc().upload.completeFileUpload.mutate({
|
|
||||||
uploadId,
|
|
||||||
contentHmac: fileSigned,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (thumbnailBuffer) {
|
|
||||||
try {
|
|
||||||
const { uploadId } = await trpc().upload.startFileThumbnailUpload.mutate({
|
|
||||||
file: fileId,
|
|
||||||
dekVersion: dataKeyVersion,
|
|
||||||
});
|
|
||||||
|
|
||||||
await uploadBlob(uploadId, new Blob([thumbnailBuffer]), dataKey);
|
|
||||||
|
|
||||||
await trpc().upload.completeFileThumbnailUpload.mutate({ uploadId });
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
state.status = "uploaded";
|
|
||||||
return { fileId };
|
|
||||||
},
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
|
|
||||||
export const uploadFile = async (
|
|
||||||
file: File,
|
|
||||||
parentId: "root" | number,
|
|
||||||
masterKey: MasterKey,
|
|
||||||
hmacSecret: HmacSecret,
|
|
||||||
onDuplicate: () => Promise<boolean>,
|
|
||||||
) => {
|
|
||||||
uploadingFiles.push({
|
|
||||||
name: file.name,
|
|
||||||
parentId,
|
|
||||||
status: "queued",
|
|
||||||
});
|
|
||||||
const state = uploadingFiles.at(-1)!;
|
|
||||||
|
|
||||||
return await scheduler.schedule(file.size, async () => {
|
|
||||||
try {
|
|
||||||
const { fileSigned } = await requestDuplicateFileScan(state, file, hmacSecret, onDuplicate);
|
|
||||||
|
|
||||||
if (!fileSigned) {
|
|
||||||
state.status = "canceled";
|
|
||||||
uploadingFiles = uploadingFiles.filter((file) => file !== state);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let fileBuffer;
|
|
||||||
const fileType = getFileType(file);
|
|
||||||
const fileMetadata: FileMetadata = {
|
|
||||||
parentId,
|
|
||||||
name: file.name,
|
|
||||||
lastModifiedAt: new Date(file.lastModified),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (fileType.startsWith("image/")) {
|
|
||||||
fileBuffer = await file.arrayBuffer();
|
|
||||||
fileMetadata.createdAt = extractExifDateTime(fileBuffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
const blob = new Blob([file], { type: fileType });
|
|
||||||
|
|
||||||
const { uploadId, thumbnailBuffer, dataKey, dataKeyVersion } =
|
|
||||||
await requestFileMetadataEncryption(state, blob, fileMetadata, masterKey, hmacSecret);
|
|
||||||
|
|
||||||
const { fileId } = await requestFileUpload(
|
|
||||||
state,
|
|
||||||
uploadId,
|
|
||||||
blob,
|
|
||||||
fileSigned,
|
|
||||||
thumbnailBuffer,
|
|
||||||
dataKey,
|
|
||||||
dataKeyVersion,
|
|
||||||
);
|
|
||||||
|
|
||||||
return { fileId, fileBuffer, thumbnailBuffer };
|
|
||||||
} catch (e) {
|
|
||||||
state.status = "error";
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
import * as IndexedDB from "$lib/indexedDB";
|
|
||||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
|
||||||
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
|
||||||
import type { CategoryInfo, MaybeCategoryInfo } from "./types";
|
|
||||||
|
|
||||||
const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo>({
|
|
||||||
async fetchFromIndexedDB(id) {
|
|
||||||
const [category, subCategories] = await Promise.all([
|
|
||||||
id !== "root" ? IndexedDB.getCategoryInfo(id) : undefined,
|
|
||||||
IndexedDB.getCategoryInfos(id),
|
|
||||||
]);
|
|
||||||
const files = category?.files
|
|
||||||
? await Promise.all(
|
|
||||||
category.files.map(async (file) => {
|
|
||||||
const fileInfo = await IndexedDB.getFileInfo(file.id);
|
|
||||||
return fileInfo
|
|
||||||
? {
|
|
||||||
id: file.id,
|
|
||||||
parentId: fileInfo.parentId,
|
|
||||||
contentType: fileInfo.contentType,
|
|
||||||
name: fileInfo.name,
|
|
||||||
createdAt: fileInfo.createdAt,
|
|
||||||
lastModifiedAt: fileInfo.lastModifiedAt,
|
|
||||||
isRecursive: file.isRecursive,
|
|
||||||
}
|
|
||||||
: undefined;
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (id === "root") {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true,
|
|
||||||
subCategories,
|
|
||||||
};
|
|
||||||
} else if (category) {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true,
|
|
||||||
parentId: category.parentId,
|
|
||||||
name: category.name,
|
|
||||||
subCategories,
|
|
||||||
files: files?.filter((file) => !!file) ?? [],
|
|
||||||
isFileRecursive: category.isFileRecursive ?? false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
async fetchFromServer(id, cachedInfo, masterKey) {
|
|
||||||
try {
|
|
||||||
const category = await trpc().category.get.query({ id, recurse: true });
|
|
||||||
const [subCategories, files, metadata] = await Promise.all([
|
|
||||||
Promise.all(
|
|
||||||
category.subCategories.map(async (category) => ({
|
|
||||||
id: category.id,
|
|
||||||
parentId: id,
|
|
||||||
...(await decryptCategoryMetadata(category, masterKey)),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
category.files &&
|
|
||||||
Promise.all(
|
|
||||||
category.files.map(async (file) => ({
|
|
||||||
id: file.id,
|
|
||||||
parentId: file.parent,
|
|
||||||
contentType: file.contentType,
|
|
||||||
isRecursive: file.isRecursive,
|
|
||||||
...(await decryptFileMetadata(file, masterKey)),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
category.metadata && decryptCategoryMetadata(category.metadata, masterKey),
|
|
||||||
]);
|
|
||||||
|
|
||||||
return storeToIndexedDB(
|
|
||||||
id !== "root"
|
|
||||||
? {
|
|
||||||
id,
|
|
||||||
parentId: category.metadata!.parent,
|
|
||||||
subCategories,
|
|
||||||
files: files!,
|
|
||||||
isFileRecursive: cachedInfo?.isFileRecursive ?? false,
|
|
||||||
...metadata!,
|
|
||||||
}
|
|
||||||
: { id, subCategories },
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
|
||||||
await IndexedDB.deleteCategoryInfo(id as number);
|
|
||||||
return { id, exists: false };
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const storeToIndexedDB = (info: CategoryInfo) => {
|
|
||||||
if (info.id !== "root") {
|
|
||||||
void IndexedDB.storeCategoryInfo(info);
|
|
||||||
|
|
||||||
// TODO: Bulk Upsert
|
|
||||||
new Map(info.files.map((file) => [file.id, file])).forEach((file) => {
|
|
||||||
void IndexedDB.storeFileInfo(file);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Bulk Upsert
|
|
||||||
info.subCategories.forEach((category) => {
|
|
||||||
void IndexedDB.storeCategoryInfo(category);
|
|
||||||
});
|
|
||||||
|
|
||||||
void IndexedDB.deleteDanglingCategoryInfos(
|
|
||||||
info.id,
|
|
||||||
new Set(info.subCategories.map(({ id }) => id)),
|
|
||||||
);
|
|
||||||
|
|
||||||
return { ...info, exists: true as const };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getCategoryInfo = (id: CategoryId, masterKey: CryptoKey) => {
|
|
||||||
return cache.get(id, masterKey);
|
|
||||||
};
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
import * as IndexedDB from "$lib/indexedDB";
|
|
||||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
|
||||||
import { FilesystemCache, decryptDirectoryMetadata, decryptFileMetadata } from "./internal.svelte";
|
|
||||||
import type { DirectoryInfo, MaybeDirectoryInfo } from "./types";
|
|
||||||
|
|
||||||
const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
|
|
||||||
async fetchFromIndexedDB(id) {
|
|
||||||
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,
|
|
||||||
subDirectories,
|
|
||||||
files,
|
|
||||||
};
|
|
||||||
} else if (directory) {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true,
|
|
||||||
parentId: directory.parentId,
|
|
||||||
name: directory.name,
|
|
||||||
subDirectories,
|
|
||||||
files,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
async fetchFromServer(id, _cachedInfo, masterKey) {
|
|
||||||
try {
|
|
||||||
const directory = await trpc().directory.get.query({ id });
|
|
||||||
const [subDirectories, files, metadata] = await Promise.all([
|
|
||||||
Promise.all(
|
|
||||||
directory.subDirectories.map(async (directory) => ({
|
|
||||||
id: directory.id,
|
|
||||||
parentId: id,
|
|
||||||
...(await decryptDirectoryMetadata(directory, masterKey)),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
Promise.all(
|
|
||||||
directory.files.map(async (file) => ({
|
|
||||||
id: file.id,
|
|
||||||
parentId: id,
|
|
||||||
contentType: file.contentType,
|
|
||||||
...(await decryptFileMetadata(file, masterKey)),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
directory.metadata && decryptDirectoryMetadata(directory.metadata, masterKey),
|
|
||||||
]);
|
|
||||||
|
|
||||||
return storeToIndexedDB(
|
|
||||||
id !== "root"
|
|
||||||
? {
|
|
||||||
id,
|
|
||||||
parentId: directory.metadata!.parent,
|
|
||||||
subDirectories,
|
|
||||||
files,
|
|
||||||
...metadata!,
|
|
||||||
}
|
|
||||||
: { id, subDirectories, files },
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
|
||||||
await IndexedDB.deleteDirectoryInfo(id as number);
|
|
||||||
return { id, exists: false as const };
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const storeToIndexedDB = (info: DirectoryInfo) => {
|
|
||||||
if (info.id !== "root") {
|
|
||||||
void IndexedDB.storeDirectoryInfo(info);
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Bulk Upsert
|
|
||||||
info.subDirectories.forEach((subDirectory) => {
|
|
||||||
void IndexedDB.storeDirectoryInfo(subDirectory);
|
|
||||||
});
|
|
||||||
|
|
||||||
// TODO: Bulk Upsert
|
|
||||||
info.files.forEach((file) => {
|
|
||||||
void IndexedDB.storeFileInfo(file);
|
|
||||||
});
|
|
||||||
|
|
||||||
void IndexedDB.deleteDanglingDirectoryInfos(
|
|
||||||
info.id,
|
|
||||||
new Set(info.subDirectories.map(({ id }) => id)),
|
|
||||||
);
|
|
||||||
void IndexedDB.deleteDanglingFileInfos(info.id, new Set(info.files.map(({ id }) => id)));
|
|
||||||
|
|
||||||
return { ...info, exists: true as const };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getDirectoryInfo = (id: DirectoryId, masterKey: CryptoKey) => {
|
|
||||||
return cache.get(id, masterKey);
|
|
||||||
};
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
import * as IndexedDB from "$lib/indexedDB";
|
|
||||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
|
||||||
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
|
||||||
import type { FileInfo, MaybeFileInfo } from "./types";
|
|
||||||
|
|
||||||
const cache = new FilesystemCache<number, MaybeFileInfo>({
|
|
||||||
async fetchFromIndexedDB(id) {
|
|
||||||
const file = await IndexedDB.getFileInfo(id);
|
|
||||||
const categories = file?.categoryIds
|
|
||||||
? await Promise.all(
|
|
||||||
file.categoryIds.map(async (categoryId) => {
|
|
||||||
const category = await IndexedDB.getCategoryInfo(categoryId);
|
|
||||||
return category
|
|
||||||
? { id: category.id, parentId: category.parentId, name: category.name }
|
|
||||||
: undefined;
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (file) {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true,
|
|
||||||
parentId: file.parentId,
|
|
||||||
contentType: file.contentType,
|
|
||||||
name: file.name,
|
|
||||||
createdAt: file.createdAt,
|
|
||||||
lastModifiedAt: file.lastModifiedAt,
|
|
||||||
categories: categories?.filter((category) => !!category) ?? [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
async fetchFromServer(id, _cachedInfo, masterKey) {
|
|
||||||
try {
|
|
||||||
const file = await trpc().file.get.query({ id });
|
|
||||||
const [categories, metadata] = await Promise.all([
|
|
||||||
Promise.all(
|
|
||||||
file.categories.map(async (category) => ({
|
|
||||||
id: category.id,
|
|
||||||
parentId: category.parent,
|
|
||||||
...(await decryptCategoryMetadata(category, masterKey)),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
decryptFileMetadata(file, masterKey),
|
|
||||||
]);
|
|
||||||
|
|
||||||
return storeToIndexedDB({
|
|
||||||
id,
|
|
||||||
isLegacy: file.isLegacy,
|
|
||||||
parentId: file.parent,
|
|
||||||
dataKey: metadata.dataKey,
|
|
||||||
contentType: file.contentType,
|
|
||||||
name: metadata.name,
|
|
||||||
createdAt: metadata.createdAt,
|
|
||||||
lastModifiedAt: metadata.lastModifiedAt,
|
|
||||||
categories,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
|
||||||
await IndexedDB.deleteFileInfo(id);
|
|
||||||
return { id, exists: false as const };
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
async bulkFetchFromIndexedDB(ids) {
|
|
||||||
const files = await IndexedDB.bulkGetFileInfos([...ids]);
|
|
||||||
const categories = await Promise.all(
|
|
||||||
files.map(async (file) =>
|
|
||||||
file?.categoryIds
|
|
||||||
? await Promise.all(
|
|
||||||
file.categoryIds.map(async (categoryId) => {
|
|
||||||
const category = await IndexedDB.getCategoryInfo(categoryId);
|
|
||||||
return category
|
|
||||||
? { id: category.id, parentId: category.parentId, name: category.name }
|
|
||||||
: undefined;
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return new Map(
|
|
||||||
files
|
|
||||||
.filter((file) => !!file)
|
|
||||||
.map((file, index) => [
|
|
||||||
file.id,
|
|
||||||
{
|
|
||||||
...file,
|
|
||||||
exists: true,
|
|
||||||
categories: categories[index]?.filter((category) => !!category) ?? [],
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
|
|
||||||
async bulkFetchFromServer(ids, masterKey) {
|
|
||||||
const idsArray = [...ids.keys()];
|
|
||||||
|
|
||||||
const filesRaw = await trpc().file.bulkGet.query({ ids: idsArray });
|
|
||||||
const files = await Promise.all(
|
|
||||||
filesRaw.map(async ({ id, categories: categoriesRaw, ...metadataRaw }) => {
|
|
||||||
const [categories, metadata] = await Promise.all([
|
|
||||||
Promise.all(
|
|
||||||
categoriesRaw.map(async (category) => ({
|
|
||||||
id: category.id,
|
|
||||||
parentId: category.parent,
|
|
||||||
...(await decryptCategoryMetadata(category, masterKey)),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
decryptFileMetadata(metadataRaw, masterKey),
|
|
||||||
]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true as const,
|
|
||||||
isLegacy: metadataRaw.isLegacy,
|
|
||||||
parentId: metadataRaw.parent,
|
|
||||||
contentType: metadataRaw.contentType,
|
|
||||||
categories,
|
|
||||||
...metadata,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const existingIds = new Set(filesRaw.map(({ id }) => id));
|
|
||||||
const deletedIds = idsArray.filter((id) => !existingIds.has(id));
|
|
||||||
|
|
||||||
void IndexedDB.bulkDeleteFileInfos(deletedIds);
|
|
||||||
return new Map<number, MaybeFileInfo>([
|
|
||||||
...bulkStoreToIndexedDB(files),
|
|
||||||
...deletedIds.map((id) => [id, { id, exists: false }] as const),
|
|
||||||
]);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const storeToIndexedDB = (info: FileInfo) => {
|
|
||||||
void IndexedDB.storeFileInfo({
|
|
||||||
...info,
|
|
||||||
categoryIds: info.categories.map(({ id }) => id),
|
|
||||||
});
|
|
||||||
|
|
||||||
info.categories.forEach((category) => {
|
|
||||||
void IndexedDB.storeCategoryInfo(category);
|
|
||||||
});
|
|
||||||
|
|
||||||
return { ...info, exists: true as const };
|
|
||||||
};
|
|
||||||
|
|
||||||
const bulkStoreToIndexedDB = (infos: FileInfo[]) => {
|
|
||||||
// TODO: Bulk Upsert
|
|
||||||
infos.forEach((info) => {
|
|
||||||
void IndexedDB.storeFileInfo({
|
|
||||||
...info,
|
|
||||||
categoryIds: info.categories.map(({ id }) => id),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// TODO: Bulk Upsert
|
|
||||||
new Map(
|
|
||||||
infos.flatMap(({ categories }) => categories).map((category) => [category.id, category]),
|
|
||||||
).forEach((category) => {
|
|
||||||
void IndexedDB.storeCategoryInfo(category);
|
|
||||||
});
|
|
||||||
|
|
||||||
return infos.map((info) => [info.id, { ...info, exists: true }] as const);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFileInfo = (id: number, masterKey: CryptoKey) => {
|
|
||||||
return cache.get(id, masterKey);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const bulkGetFileInfo = (ids: number[], masterKey: CryptoKey) => {
|
|
||||||
return cache.bulkGet(new Set(ids), masterKey);
|
|
||||||
};
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
export * from "./category";
|
|
||||||
export * from "./directory";
|
|
||||||
export * from "./file";
|
|
||||||
export * from "./types";
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
import { untrack } from "svelte";
|
|
||||||
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
|
||||||
|
|
||||||
interface FilesystemCacheOptions<K, V> {
|
|
||||||
fetchFromIndexedDB: (key: K) => Promise<V | undefined>;
|
|
||||||
fetchFromServer: (key: K, cachedValue: V | undefined, masterKey: CryptoKey) => Promise<V>;
|
|
||||||
bulkFetchFromIndexedDB?: (keys: Set<K>) => Promise<Map<K, V>>;
|
|
||||||
bulkFetchFromServer?: (
|
|
||||||
keys: Map<K, { cachedValue: V | undefined }>,
|
|
||||||
masterKey: CryptoKey,
|
|
||||||
) => Promise<Map<K, V>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class FilesystemCache<K, V extends object> {
|
|
||||||
private map = new Map<K, { value?: V; promise?: Promise<V> }>();
|
|
||||||
|
|
||||||
constructor(private readonly options: FilesystemCacheOptions<K, V>) {}
|
|
||||||
|
|
||||||
get(key: K, masterKey: CryptoKey) {
|
|
||||||
return untrack(() => {
|
|
||||||
let state = this.map.get(key);
|
|
||||||
if (state?.promise) return state.value ?? state.promise;
|
|
||||||
|
|
||||||
const { promise: newPromise, resolve } = Promise.withResolvers<V>();
|
|
||||||
|
|
||||||
if (!state) {
|
|
||||||
const newState = $state({});
|
|
||||||
state = newState;
|
|
||||||
this.map.set(key, newState);
|
|
||||||
}
|
|
||||||
|
|
||||||
(state.value
|
|
||||||
? Promise.resolve(state.value)
|
|
||||||
: this.options.fetchFromIndexedDB(key).then((loadedInfo) => {
|
|
||||||
if (loadedInfo) {
|
|
||||||
state.value = loadedInfo;
|
|
||||||
resolve(state.value);
|
|
||||||
}
|
|
||||||
return loadedInfo;
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.then((cachedInfo) => this.options.fetchFromServer(key, cachedInfo, masterKey))
|
|
||||||
.then((loadedInfo) => {
|
|
||||||
if (state.value) {
|
|
||||||
Object.assign(state.value, loadedInfo);
|
|
||||||
} else {
|
|
||||||
state.value = loadedInfo;
|
|
||||||
}
|
|
||||||
resolve(state.value);
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
state.promise = undefined;
|
|
||||||
});
|
|
||||||
|
|
||||||
state.promise = newPromise;
|
|
||||||
return state.value ?? newPromise;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
bulkGet(keys: Set<K>, masterKey: CryptoKey) {
|
|
||||||
return untrack(() => {
|
|
||||||
const newPromises = new Map(
|
|
||||||
keys
|
|
||||||
.keys()
|
|
||||||
.filter((key) => this.map.get(key)?.promise === undefined)
|
|
||||||
.map((key) => [key, Promise.withResolvers<V>()]),
|
|
||||||
);
|
|
||||||
newPromises.forEach(({ promise }, key) => {
|
|
||||||
const state = this.map.get(key);
|
|
||||||
if (state) {
|
|
||||||
state.promise = promise;
|
|
||||||
} else {
|
|
||||||
const newState = $state({ promise });
|
|
||||||
this.map.set(key, newState);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const resolve = (loadedInfos: Map<K, V>) => {
|
|
||||||
loadedInfos.forEach((loadedInfo, key) => {
|
|
||||||
const state = this.map.get(key)!;
|
|
||||||
if (state.value) {
|
|
||||||
Object.assign(state.value, loadedInfo);
|
|
||||||
} else {
|
|
||||||
state.value = loadedInfo;
|
|
||||||
}
|
|
||||||
newPromises.get(key)!.resolve(state.value);
|
|
||||||
});
|
|
||||||
return loadedInfos;
|
|
||||||
};
|
|
||||||
|
|
||||||
this.options.bulkFetchFromIndexedDB!(
|
|
||||||
new Set(newPromises.keys().filter((key) => this.map.get(key)!.value === undefined)),
|
|
||||||
)
|
|
||||||
.then(resolve)
|
|
||||||
.then(() =>
|
|
||||||
this.options.bulkFetchFromServer!(
|
|
||||||
new Map(
|
|
||||||
newPromises.keys().map((key) => [key, { cachedValue: this.map.get(key)!.value }]),
|
|
||||||
),
|
|
||||||
masterKey,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.then(resolve)
|
|
||||||
.finally(() => {
|
|
||||||
newPromises.forEach((_, key) => {
|
|
||||||
this.map.get(key)!.promise = undefined;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const bottleneckPromises = Array.from(
|
|
||||||
keys
|
|
||||||
.keys()
|
|
||||||
.filter((key) => this.map.get(key)!.value === undefined)
|
|
||||||
.map((key) => this.map.get(key)!.promise!),
|
|
||||||
);
|
|
||||||
const makeResult = () =>
|
|
||||||
new Map(keys.keys().map((key) => [key, this.map.get(key)!.value!] as const));
|
|
||||||
return bottleneckPromises.length > 0
|
|
||||||
? Promise.all(bottleneckPromises).then(makeResult)
|
|
||||||
: makeResult();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
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 MaybeDirectoryInfo =
|
|
||||||
| (DirectoryInfo & { exists: true })
|
|
||||||
| ({ id: DirectoryId; exists: false } & AllUndefined<Omit<DirectoryInfo, "id">>);
|
|
||||||
|
|
||||||
export type SubDirectoryInfo = Omit<LocalDirectoryInfo, "subDirectories" | "files">;
|
|
||||||
|
|
||||||
export interface FileInfo {
|
|
||||||
id: number;
|
|
||||||
isLegacy?: boolean;
|
|
||||||
parentId: DirectoryId;
|
|
||||||
dataKey?: DataKey;
|
|
||||||
contentType: string;
|
|
||||||
name: string;
|
|
||||||
createdAt?: Date;
|
|
||||||
lastModifiedAt: Date;
|
|
||||||
categories: FileCategoryInfo[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type MaybeFileInfo =
|
|
||||||
| (FileInfo & { exists: true })
|
|
||||||
| ({ id: number; exists: false } & AllUndefined<Omit<FileInfo, "id">>);
|
|
||||||
|
|
||||||
export type SummarizedFileInfo = Omit<FileInfo, "categories">;
|
|
||||||
export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean };
|
|
||||||
|
|
||||||
interface LocalCategoryInfo {
|
|
||||||
id: number;
|
|
||||||
parentId: DirectoryId;
|
|
||||||
dataKey?: DataKey;
|
|
||||||
name: string;
|
|
||||||
subCategories: SubCategoryInfo[];
|
|
||||||
files: CategoryFileInfo[];
|
|
||||||
isFileRecursive: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RootCategoryInfo {
|
|
||||||
id: "root";
|
|
||||||
parentId?: undefined;
|
|
||||||
dataKey?: undefined;
|
|
||||||
name?: undefined;
|
|
||||||
subCategories: SubCategoryInfo[];
|
|
||||||
files?: undefined;
|
|
||||||
isFileRecursive?: undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type CategoryInfo = LocalCategoryInfo | RootCategoryInfo;
|
|
||||||
export type MaybeCategoryInfo =
|
|
||||||
| (CategoryInfo & { exists: true })
|
|
||||||
| ({ id: CategoryId; exists: false } & AllUndefined<Omit<CategoryInfo, "id">>);
|
|
||||||
|
|
||||||
export type SubCategoryInfo = Omit<
|
|
||||||
LocalCategoryInfo,
|
|
||||||
"subCategories" | "files" | "isFileRecursive"
|
|
||||||
>;
|
|
||||||
export type FileCategoryInfo = Omit<SubCategoryInfo, "dataKey">;
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
export const parseRangeHeader = (value: string | null) => {
|
|
||||||
if (!value) return undefined;
|
|
||||||
|
|
||||||
const firstRange = value.split(",")[0]!.trim();
|
|
||||||
const parts = firstRange.replace(/bytes=/, "").split("-");
|
|
||||||
return {
|
|
||||||
start: parts[0] ? parseInt(parts[0], 10) : undefined,
|
|
||||||
end: parts[1] ? parseInt(parts[1], 10) : undefined,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getContentRangeHeader = (range?: { start: number; end: number; total: number }) => {
|
|
||||||
return range && { "Content-Range": `bytes ${range.start}-${range.end}/${range.total}` };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const parseContentDigestHeader = (value: string | null) => {
|
|
||||||
if (!value) return undefined;
|
|
||||||
|
|
||||||
const firstDigest = value.split(",")[0]!.trim();
|
|
||||||
const match = firstDigest.match(/^sha-256=:([A-Za-z0-9+/=]+):$/);
|
|
||||||
return match?.[1];
|
|
||||||
};
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
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"),
|
|
||||||
]);
|
|
||||||
};
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
const getFileHandle = async (path: string, create = true) => {
|
|
||||||
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 = await navigator.storage.getDirectory();
|
|
||||||
for (const part of parts.slice(0, -1)) {
|
|
||||||
if (!part) continue;
|
|
||||||
directoryHandle = await directoryHandle.getDirectoryHandle(part, { create });
|
|
||||||
}
|
|
||||||
|
|
||||||
const filename = parts[parts.length - 1]!;
|
|
||||||
const fileHandle = await directoryHandle.getFileHandle(filename, { create });
|
|
||||||
return { parentHandle: directoryHandle, filename, fileHandle };
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof DOMException && e.name === "NotFoundError") {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFile = async (path: string) => {
|
|
||||||
const { fileHandle } = await getFileHandle(path, false);
|
|
||||||
if (!fileHandle) return null;
|
|
||||||
|
|
||||||
return await fileHandle.getFile();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const readFile = async (path: string) => {
|
|
||||||
return (await getFile(path))?.arrayBuffer() ?? null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const writeFile = async (path: string, data: ArrayBuffer) => {
|
|
||||||
const { fileHandle } = await getFileHandle(path);
|
|
||||||
const writable = await fileHandle!.createWritable();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await writable.write(data);
|
|
||||||
} finally {
|
|
||||||
await writable.close();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteFile = async (path: string) => {
|
|
||||||
const { parentHandle, filename } = await getFileHandle(path, false);
|
|
||||||
if (!parentHandle) return;
|
|
||||||
|
|
||||||
await parentHandle.removeEntry(filename);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getDirectoryHandle = async (path: string) => {
|
|
||||||
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 = await navigator.storage.getDirectory();
|
|
||||||
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 });
|
|
||||||
};
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
export class Scheduler<T = void> {
|
|
||||||
private isEstimating = false;
|
|
||||||
private memoryUsage = 0;
|
|
||||||
private queue: (() => void)[] = [];
|
|
||||||
|
|
||||||
constructor(public readonly memoryLimit = 100 * 1024 * 1024 /* 100 MiB */) {}
|
|
||||||
|
|
||||||
private next() {
|
|
||||||
if (!this.isEstimating && this.memoryUsage < this.memoryLimit) {
|
|
||||||
const resolve = this.queue.shift();
|
|
||||||
if (resolve) {
|
|
||||||
this.isEstimating = true;
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async schedule(
|
|
||||||
estimateMemoryUsage: number | (() => number | Promise<number>),
|
|
||||||
task: () => Promise<T>,
|
|
||||||
) {
|
|
||||||
if (this.isEstimating || this.memoryUsage >= this.memoryLimit) {
|
|
||||||
await new Promise<void>((resolve) => {
|
|
||||||
this.queue.push(resolve);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
this.isEstimating = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
let taskMemoryUsage = 0;
|
|
||||||
|
|
||||||
try {
|
|
||||||
taskMemoryUsage =
|
|
||||||
typeof estimateMemoryUsage === "number" ? estimateMemoryUsage : await estimateMemoryUsage();
|
|
||||||
this.memoryUsage += taskMemoryUsage;
|
|
||||||
} finally {
|
|
||||||
this.isEstimating = false;
|
|
||||||
this.next();
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await task();
|
|
||||||
} finally {
|
|
||||||
this.memoryUsage -= taskMemoryUsage;
|
|
||||||
this.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
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 (blob: Blob) => {
|
|
||||||
let url;
|
|
||||||
try {
|
|
||||||
if (blob.type.startsWith("image/")) {
|
|
||||||
url = URL.createObjectURL(blob);
|
|
||||||
try {
|
|
||||||
return await generateImageThumbnail(url);
|
|
||||||
} catch {
|
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
url = undefined;
|
|
||||||
|
|
||||||
if (blob.type === "image/heic") {
|
|
||||||
const { default: heic2any } = await import("heic2any");
|
|
||||||
url = URL.createObjectURL((await heic2any({ blob, toType: "image/png" })) as Blob);
|
|
||||||
return await generateImageThumbnail(url);
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (blob.type.startsWith("video/")) {
|
|
||||||
url = URL.createObjectURL(blob);
|
|
||||||
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)}`;
|
|
||||||
};
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
import axios from "axios";
|
|
||||||
import pLimit from "p-limit";
|
|
||||||
import { ENCRYPTION_OVERHEAD, CHUNK_SIZE } from "$lib/constants";
|
|
||||||
import { encryptChunk, digestMessage, encodeToBase64 } from "$lib/modules/crypto";
|
|
||||||
|
|
||||||
interface UploadStats {
|
|
||||||
progress: number;
|
|
||||||
rate: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const createSpeedMeter = (timeWindow = 1500) => {
|
|
||||||
const samples: { t: number; b: number }[] = [];
|
|
||||||
let lastSpeed = 0;
|
|
||||||
|
|
||||||
return (bytesNow?: number) => {
|
|
||||||
if (!bytesNow) return lastSpeed;
|
|
||||||
|
|
||||||
const now = performance.now();
|
|
||||||
samples.push({ t: now, b: bytesNow });
|
|
||||||
|
|
||||||
const cutoff = now - timeWindow;
|
|
||||||
while (samples.length > 2 && samples[0]!.t < cutoff) samples.shift();
|
|
||||||
|
|
||||||
const first = samples[0]!;
|
|
||||||
const dt = now - first.t;
|
|
||||||
const db = bytesNow - first.b;
|
|
||||||
|
|
||||||
lastSpeed = dt > 0 ? (db / dt) * 1000 : 0;
|
|
||||||
return lastSpeed;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const uploadChunk = async (
|
|
||||||
uploadId: string,
|
|
||||||
chunkIndex: number,
|
|
||||||
chunk: Blob,
|
|
||||||
dataKey: CryptoKey,
|
|
||||||
onChunkProgress: (chunkIndex: number, loaded: number) => void,
|
|
||||||
) => {
|
|
||||||
const chunkEncrypted = await encryptChunk(await chunk.arrayBuffer(), dataKey);
|
|
||||||
const chunkEncryptedHash = encodeToBase64(await digestMessage(chunkEncrypted));
|
|
||||||
|
|
||||||
await axios.post(`/api/upload/${uploadId}/chunks/${chunkIndex}`, chunkEncrypted, {
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/octet-stream",
|
|
||||||
"Content-Digest": `sha-256=:${chunkEncryptedHash}:`,
|
|
||||||
},
|
|
||||||
onUploadProgress(e) {
|
|
||||||
onChunkProgress(chunkIndex, e.loaded ?? 0);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
onChunkProgress(chunkIndex, chunkEncrypted.byteLength);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const uploadBlob = async (
|
|
||||||
uploadId: string,
|
|
||||||
blob: Blob,
|
|
||||||
dataKey: CryptoKey,
|
|
||||||
options?: { concurrency?: number; onProgress?: (s: UploadStats) => void },
|
|
||||||
) => {
|
|
||||||
const onProgress = options?.onProgress;
|
|
||||||
|
|
||||||
const totalChunks = Math.ceil(blob.size / CHUNK_SIZE);
|
|
||||||
const totalBytes = blob.size + totalChunks * ENCRYPTION_OVERHEAD;
|
|
||||||
|
|
||||||
const uploadedByChunk = new Array<number>(totalChunks).fill(0);
|
|
||||||
const speedMeter = createSpeedMeter(1500);
|
|
||||||
|
|
||||||
const emit = () => {
|
|
||||||
if (!onProgress) return;
|
|
||||||
|
|
||||||
const uploadedBytes = uploadedByChunk.reduce((a, b) => a + b, 0);
|
|
||||||
const rate = speedMeter(uploadedBytes);
|
|
||||||
const progress = Math.min(1, uploadedBytes / totalBytes);
|
|
||||||
|
|
||||||
onProgress({ progress, rate });
|
|
||||||
};
|
|
||||||
|
|
||||||
const onChunkProgress = (idx: number, loaded: number) => {
|
|
||||||
uploadedByChunk[idx] = loaded;
|
|
||||||
emit();
|
|
||||||
};
|
|
||||||
|
|
||||||
const limit = pLimit(options?.concurrency ?? 4);
|
|
||||||
|
|
||||||
await Promise.all(
|
|
||||||
Array.from({ length: totalChunks }, (_, i) =>
|
|
||||||
limit(() =>
|
|
||||||
uploadChunk(
|
|
||||||
uploadId,
|
|
||||||
i + 1,
|
|
||||||
blob.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE),
|
|
||||||
dataKey,
|
|
||||||
onChunkProgress,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
onProgress?.({ progress: 1, rate: speedMeter() });
|
|
||||||
};
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user