Compare commits
No commits in common. "develop" and "feature/opnsense" have entirely different histories.
develop
...
feature/op
@ -1,33 +0,0 @@
|
||||
node_modules
|
||||
|
||||
# Output
|
||||
.output
|
||||
.vercel
|
||||
/.svelte-kit
|
||||
/build
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.test
|
||||
|
||||
# Vite
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
|
||||
# SQLite
|
||||
*.db
|
||||
|
||||
# Git
|
||||
/.git
|
||||
|
||||
# IntelliJ
|
||||
/.idea
|
||||
|
||||
# Bruno (API Docs)
|
||||
/bruno
|
@ -1,10 +0,0 @@
|
||||
[*]
|
||||
charset = utf-8
|
||||
insert_final_newline = true
|
||||
end_of_line = lf
|
||||
|
||||
indent_style = tab
|
||||
indent_size = 2
|
||||
max_line_length = 100
|
||||
quote_type = single
|
||||
trim_trailing_whitespace = true
|
21
.env.example
21
.env.example
@ -1,19 +1,10 @@
|
||||
DATABASE_URL=file:local.db
|
||||
AUTH_DOMAIN=auth.lab.cazzzer.com
|
||||
AUTH_CLIENT_ID=
|
||||
AUTH_CLIENT_SECRET=
|
||||
AUTH_REDIRECT_URI=http://localhost:5173/auth/authentik/callback
|
||||
|
||||
PUBLIC_AUTH_AUTHENTIK_ENABLE=1
|
||||
AUTH_AUTHENTIK_REQUIRE_INVITE=0
|
||||
AUTH_AUTHENTIK_DOMAIN=auth.lab.cazzzer.com
|
||||
AUTH_AUTHENTIK_CLIENT_ID=
|
||||
AUTH_AUTHENTIK_CLIENT_SECRET=
|
||||
|
||||
PUBLIC_AUTH_GOOGLE_ENABLE=1
|
||||
AUTH_GOOGLE_REQUIRE_INVITE=1
|
||||
AUTH_GOOGLE_CLIENT_ID=
|
||||
AUTH_GOOGLE_CLIENT_SECRET=
|
||||
|
||||
AUTH_INVITE_TOKEN=GUjdsz9aREFTEBYDrA3AajUE8oVys2xW
|
||||
|
||||
OPNSENSE_API_URL=https://opnsense.cazzzer.com
|
||||
OPNSENSE_API_URL=https://opnsense.home
|
||||
OPNSENSE_API_KEY=
|
||||
OPNSENSE_API_SECRET=
|
||||
OPNSENSE_WG_IFNAME=wg2
|
||||
@ -25,5 +16,3 @@ IP_MAX_INDEX=100
|
||||
VPN_ENDPOINT=vpn.lab.cazzzer.com:51820
|
||||
VPN_DNS=10.18.11.1,fd00:10:18:11::1
|
||||
MAX_CLIENTS_PER_USER=20
|
||||
|
||||
ORIGIN=http://localhost:5173
|
||||
|
1
.gitattributes
vendored
1
.gitattributes
vendored
@ -1 +0,0 @@
|
||||
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
6
.idea/bun.xml
generated
6
.idea/bun.xml
generated
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="BunSettings">
|
||||
<option name="bunPath" value="bun" />
|
||||
</component>
|
||||
</project>
|
4
.idea/codeStyles/Project.xml
generated
4
.idea/codeStyles/Project.xml
generated
@ -9,7 +9,7 @@
|
||||
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
|
||||
<option name="USE_DOUBLE_QUOTES" value="false" />
|
||||
<option name="FORCE_QUOTE_STYlE" value="true" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
|
||||
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
|
||||
<option name="SPACES_WITHIN_IMPORTS" value="true" />
|
||||
</JSCodeStyleSettings>
|
||||
@ -120,7 +120,7 @@
|
||||
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
|
||||
<option name="USE_DOUBLE_QUOTES" value="false" />
|
||||
<option name="FORCE_QUOTE_STYlE" value="true" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
|
||||
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
|
||||
<option name="SPACES_WITHIN_IMPORTS" value="true" />
|
||||
</TypeScriptCodeStyleSettings>
|
||||
|
2
.idea/modules.xml
generated
2
.idea/modules.xml
generated
@ -2,7 +2,7 @@
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/vpgen.iml" filepath="$PROJECT_DIR$/.idea/vpgen.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/vpgen-sv5.iml" filepath="$PROJECT_DIR$/.idea/vpgen-sv5.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
0
.idea/vpgen.iml → .idea/vpgen-sv5.iml
generated
0
.idea/vpgen.iml → .idea/vpgen-sv5.iml
generated
@ -1,15 +0,0 @@
|
||||
when:
|
||||
- event: [push]
|
||||
steps:
|
||||
- name: build
|
||||
image: woodpeckerci/plugin-kaniko
|
||||
settings:
|
||||
registry: gitea.cazzzer.com
|
||||
repo: ${CI_REPO,,}
|
||||
# replace '/' in branch name
|
||||
tags: ${CI_COMMIT_BRANCH/\//-}
|
||||
cache: true
|
||||
username:
|
||||
from_secret: registry-username
|
||||
password:
|
||||
from_secret: registry-password
|
@ -1,7 +0,0 @@
|
||||
// Folder-specific settings
|
||||
//
|
||||
// For a full list of overridable settings, and general information on folder-specific settings,
|
||||
// see the documentation: https://zed.dev/docs/configuring-zed#settings-files
|
||||
{
|
||||
"formatter": "prettier"
|
||||
}
|
45
Dockerfile
45
Dockerfile
@ -1,45 +0,0 @@
|
||||
# use the official Bun image
|
||||
# see all versions at https://hub.docker.com/r/oven/bun/tags
|
||||
FROM oven/bun:1-alpine AS base
|
||||
WORKDIR /app
|
||||
COPY package.json bun.lock /app/
|
||||
|
||||
# install dependencies into temp directory
|
||||
# this will cache them and speed up future builds
|
||||
FROM base AS install
|
||||
RUN mkdir -p /temp/dev
|
||||
COPY package.json bun.lock /temp/dev/
|
||||
RUN cd /temp/dev && bun install --frozen-lockfile
|
||||
|
||||
# install with --production (exclude devDependencies)
|
||||
RUN mkdir -p /temp/prod
|
||||
COPY package.json bun.lock /temp/prod/
|
||||
RUN cd /temp/prod && bun install --frozen-lockfile --production --ignore-scripts
|
||||
|
||||
# copy node_modules from temp directory
|
||||
# then copy all (non-ignored) project files into the image
|
||||
FROM base AS builder
|
||||
COPY --from=install /temp/dev/node_modules /app/node_modules
|
||||
COPY . /app
|
||||
RUN bun run build
|
||||
|
||||
FROM base
|
||||
# Metadata
|
||||
LABEL org.opencontainers.image.title="VPGen"
|
||||
LABEL org.opencontainers.image.description="A VPN config generator built with SvelteKit."
|
||||
LABEL org.opencontainers.image.url="https://gitea.cazzzer.com/CaZzzer/vpgen"
|
||||
LABEL org.opencontainers.image.source="https://gitea.cazzzer.com/CaZzzer/vpgen"
|
||||
LABEL org.opencontainers.image.version="0.1"
|
||||
|
||||
COPY ./entrypoint.sh /entrypoint.sh
|
||||
COPY --from=install /temp/prod/node_modules /app/node_modules
|
||||
COPY --from=builder /app/build /app/build
|
||||
COPY --from=builder /app/drizzle /app/drizzle
|
||||
COPY --from=builder /app/drizzle.config.ts /app/
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
# entrypoint for drizzle migrations
|
||||
ENTRYPOINT ["sh", "/entrypoint.sh"]
|
||||
|
||||
CMD ["bun", "./build"]
|
55
README.md
55
README.md
@ -1,29 +1,38 @@
|
||||
# VPGen
|
||||
# sv
|
||||
|
||||
One-click WireGuard config generator, work in progress.
|
||||
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
|
||||
|
||||
## Why?
|
||||
## Creating a project
|
||||
|
||||
Make it easier to share VPN access with friends/family,
|
||||
making use of existing networking infrastructure.
|
||||
If you're seeing this, you've probably already done this step. Congrats!
|
||||
|
||||
## How?
|
||||
```bash
|
||||
# create a new project in the current directory
|
||||
npx sv create
|
||||
|
||||
Currently, the supported backend is [OPNsense](https://opnsense.org/).
|
||||
VPGen just creates WireGuard clients on the configured interface via the OPNsense API.
|
||||
|
||||
Future plans include supporting other API backends (e.g. [Netmaker](https://github.com/gravitl/netmaker))
|
||||
and [wg-quick](https://www.wireguard.com/quickstart/) for standalone setups.
|
||||
|
||||
## Development
|
||||
|
||||
Development uses bun.
|
||||
An additional prepare step is needed to set up typia for type validation.
|
||||
|
||||
For example .env settings, see [.env.example](.env.example)
|
||||
|
||||
```shell
|
||||
bun install
|
||||
bun run prepare
|
||||
bun run dev
|
||||
# create a new project in my-app
|
||||
npx sv create my-app
|
||||
```
|
||||
|
||||
## Developing
|
||||
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
|
||||
# or start the server and open the app in a new browser tab
|
||||
npm run dev -- --open
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To create a production version of your app:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
|
||||
|
@ -1,25 +0,0 @@
|
||||
meta {
|
||||
name: Delete Client
|
||||
type: http
|
||||
seq: 11
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{base}}/api/wireguard/client/delClient/:clientUuid
|
||||
body: none
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
params:path {
|
||||
clientUuid: d484d381-4d6f-4444-8e9d-9cda7b5b2243
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"current": 1,
|
||||
"rowCount": 7,
|
||||
"sort": {},
|
||||
"servers": ["{{serverUuid}}"],
|
||||
"searchPhrase": "{{searchPhrase}}"
|
||||
}
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
{
|
||||
"$schema": "https://next.shadcn-svelte.com/schema.json",
|
||||
"$schema": "https://shadcn-svelte.com/schema.json",
|
||||
"style": "default",
|
||||
"tailwind": {
|
||||
"config": "tailwind.config.ts",
|
||||
@ -8,10 +8,7 @@
|
||||
},
|
||||
"aliases": {
|
||||
"components": "$lib/components",
|
||||
"utils": "$lib/utils",
|
||||
"ui": "$lib/components/ui",
|
||||
"hooks": "$lib/hooks"
|
||||
"utils": "$lib/utils"
|
||||
},
|
||||
"typescript": true,
|
||||
"registry": "https://next.shadcn-svelte.com/registry"
|
||||
}
|
||||
"typescript": true
|
||||
}
|
@ -1,22 +1,10 @@
|
||||
CREATE TABLE `devices` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`opnsense_id` text,
|
||||
`public_key` text NOT NULL,
|
||||
`private_key` text,
|
||||
`pre_shared_key` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `devices_public_key_unique` ON `devices` (`public_key`);--> statement-breakpoint
|
||||
CREATE TABLE `ip_allocations` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`device_id` integer,
|
||||
FOREIGN KEY (`device_id`) REFERENCES `devices`(`id`) ON UPDATE no action ON DELETE set null
|
||||
`client_id` integer,
|
||||
FOREIGN KEY (`client_id`) REFERENCES `wg_clients`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `ip_allocations_device_id_unique` ON `ip_allocations` (`device_id`);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `ip_allocations_client_id_unique` ON `ip_allocations` (`client_id`);--> statement-breakpoint
|
||||
CREATE TABLE `sessions` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
@ -29,3 +17,16 @@ CREATE TABLE `users` (
|
||||
`username` text NOT NULL,
|
||||
`name` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `wg_clients` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`opnsense_id` text,
|
||||
`public_key` text NOT NULL,
|
||||
`private_key` text,
|
||||
`pre_shared_key` text,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `wg_clients_public_key_unique` ON `wg_clients` (`public_key`);
|
@ -1 +0,0 @@
|
||||
ALTER TABLE `users` ADD `auth_source` text DEFAULT 'authentik' NOT NULL;
|
@ -1 +0,0 @@
|
||||
ALTER TABLE `devices` DROP COLUMN `opnsense_id`;
|
@ -1,90 +1,9 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "48b7ce55-58f1-4b97-a144-ca733576dba6",
|
||||
"id": "29e6fd88-fa47-4f79-ad83-c52538bc36a6",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"tables": {
|
||||
"devices": {
|
||||
"name": "devices",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"opnsense_id": {
|
||||
"name": "opnsense_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"public_key": {
|
||||
"name": "public_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"private_key": {
|
||||
"name": "private_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"pre_shared_key": {
|
||||
"name": "pre_shared_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"devices_public_key_unique": {
|
||||
"name": "devices_public_key_unique",
|
||||
"columns": [
|
||||
"public_key"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"devices_user_id_users_id_fk": {
|
||||
"name": "devices_user_id_users_id_fk",
|
||||
"tableFrom": "devices",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"ip_allocations": {
|
||||
"name": "ip_allocations",
|
||||
"columns": {
|
||||
@ -95,8 +14,8 @@
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"device_id": {
|
||||
"name": "device_id",
|
||||
"client_id": {
|
||||
"name": "client_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
@ -104,21 +23,21 @@
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ip_allocations_device_id_unique": {
|
||||
"name": "ip_allocations_device_id_unique",
|
||||
"ip_allocations_client_id_unique": {
|
||||
"name": "ip_allocations_client_id_unique",
|
||||
"columns": [
|
||||
"device_id"
|
||||
"client_id"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ip_allocations_device_id_devices_id_fk": {
|
||||
"name": "ip_allocations_device_id_devices_id_fk",
|
||||
"ip_allocations_client_id_wg_clients_id_fk": {
|
||||
"name": "ip_allocations_client_id_wg_clients_id_fk",
|
||||
"tableFrom": "ip_allocations",
|
||||
"tableTo": "devices",
|
||||
"tableTo": "wg_clients",
|
||||
"columnsFrom": [
|
||||
"device_id"
|
||||
"client_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
@ -206,6 +125,87 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"wg_clients": {
|
||||
"name": "wg_clients",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"opnsense_id": {
|
||||
"name": "opnsense_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"public_key": {
|
||||
"name": "public_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"private_key": {
|
||||
"name": "private_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"pre_shared_key": {
|
||||
"name": "pre_shared_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"wg_clients_public_key_unique": {
|
||||
"name": "wg_clients_public_key_unique",
|
||||
"columns": [
|
||||
"public_key"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"wg_clients_user_id_users_id_fk": {
|
||||
"name": "wg_clients_user_id_users_id_fk",
|
||||
"tableFrom": "wg_clients",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
|
@ -1,229 +0,0 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "cc1fa973-1e9c-4bd6-b082-d7cf36f7342c",
|
||||
"prevId": "48b7ce55-58f1-4b97-a144-ca733576dba6",
|
||||
"tables": {
|
||||
"devices": {
|
||||
"name": "devices",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"opnsense_id": {
|
||||
"name": "opnsense_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"public_key": {
|
||||
"name": "public_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"private_key": {
|
||||
"name": "private_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"pre_shared_key": {
|
||||
"name": "pre_shared_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"devices_public_key_unique": {
|
||||
"name": "devices_public_key_unique",
|
||||
"columns": [
|
||||
"public_key"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"devices_user_id_users_id_fk": {
|
||||
"name": "devices_user_id_users_id_fk",
|
||||
"tableFrom": "devices",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"ip_allocations": {
|
||||
"name": "ip_allocations",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"device_id": {
|
||||
"name": "device_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ip_allocations_device_id_unique": {
|
||||
"name": "ip_allocations_device_id_unique",
|
||||
"columns": [
|
||||
"device_id"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ip_allocations_device_id_devices_id_fk": {
|
||||
"name": "ip_allocations_device_id_devices_id_fk",
|
||||
"tableFrom": "ip_allocations",
|
||||
"tableTo": "devices",
|
||||
"columnsFrom": [
|
||||
"device_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"sessions": {
|
||||
"name": "sessions",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"sessions_user_id_users_id_fk": {
|
||||
"name": "sessions_user_id_users_id_fk",
|
||||
"tableFrom": "sessions",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"users": {
|
||||
"name": "users",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"auth_source": {
|
||||
"name": "auth_source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'authentik'"
|
||||
},
|
||||
"username": {
|
||||
"name": "username",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
@ -1,222 +0,0 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "0b364191-58d0-46a3-8372-4a30b0b88d85",
|
||||
"prevId": "cc1fa973-1e9c-4bd6-b082-d7cf36f7342c",
|
||||
"tables": {
|
||||
"devices": {
|
||||
"name": "devices",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"public_key": {
|
||||
"name": "public_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"private_key": {
|
||||
"name": "private_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"pre_shared_key": {
|
||||
"name": "pre_shared_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"devices_public_key_unique": {
|
||||
"name": "devices_public_key_unique",
|
||||
"columns": [
|
||||
"public_key"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"devices_user_id_users_id_fk": {
|
||||
"name": "devices_user_id_users_id_fk",
|
||||
"tableFrom": "devices",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"ip_allocations": {
|
||||
"name": "ip_allocations",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"device_id": {
|
||||
"name": "device_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ip_allocations_device_id_unique": {
|
||||
"name": "ip_allocations_device_id_unique",
|
||||
"columns": [
|
||||
"device_id"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ip_allocations_device_id_devices_id_fk": {
|
||||
"name": "ip_allocations_device_id_devices_id_fk",
|
||||
"tableFrom": "ip_allocations",
|
||||
"tableTo": "devices",
|
||||
"columnsFrom": [
|
||||
"device_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"sessions": {
|
||||
"name": "sessions",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"sessions_user_id_users_id_fk": {
|
||||
"name": "sessions_user_id_users_id_fk",
|
||||
"tableFrom": "sessions",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"users": {
|
||||
"name": "users",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"auth_source": {
|
||||
"name": "auth_source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'authentik'"
|
||||
},
|
||||
"username": {
|
||||
"name": "username",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
@ -5,22 +5,8 @@
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "6",
|
||||
"when": 1736295566569,
|
||||
"tag": "0000_fair_tarantula",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "6",
|
||||
"when": 1741936760967,
|
||||
"tag": "0001_equal_unicorn",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "6",
|
||||
"when": 1743389268079,
|
||||
"tag": "0002_minor_black_panther",
|
||||
"when": 1735028333867,
|
||||
"tag": "0000_young_wong",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
@ -1,8 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Run database migrations
|
||||
bun run db:migrate
|
||||
|
||||
# Execute the CMD passed to the container
|
||||
exec "$@"
|
73
package.json
73
package.json
@ -1,7 +1,6 @@
|
||||
{
|
||||
"name": "vpgen",
|
||||
"name": "vpgen-sv5",
|
||||
"version": "0.0.1",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
@ -15,52 +14,46 @@
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"db:seed": "bun run ./src/lib/server/db/seed.ts",
|
||||
"prepare": "ts-patch install"
|
||||
"db:seed": "bun run ./src/lib/server/db/seed.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lucide/svelte": "^0.487.0",
|
||||
"@oslojs/crypto": "^1.0.1",
|
||||
"@oslojs/encoding": "^1.1.0",
|
||||
"@ryoppippi/unplugin-typia": "npm:@jsr/ryoppippi__unplugin-typia",
|
||||
"@sveltejs/adapter-auto": "^3.3.1",
|
||||
"@sveltejs/adapter-node": "^5.2.12",
|
||||
"@sveltejs/kit": "^2.20.7",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||
"@sveltejs/adapter-auto": "^3.0.0",
|
||||
"@sveltejs/kit": "^2.0.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^4.0.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tailwindcss/forms": "^0.5.10",
|
||||
"@tailwindcss/typography": "^0.5.16",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/eslint": "^9.6.1",
|
||||
"@tailwindcss/forms": "^0.5.9",
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@types/better-sqlite3": "^7.6.11",
|
||||
"@types/eslint": "^9.6.0",
|
||||
"@types/qrcode-svg": "^1.1.5",
|
||||
"arctic": "^2.3.4",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"bits-ui": "^1.3.19",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"bits-ui": "^0.21.16",
|
||||
"clsx": "^2.1.1",
|
||||
"eslint": "^9.25.1",
|
||||
"drizzle-kit": "^0.30.1",
|
||||
"eslint": "^9.7.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-svelte": "^2.46.1",
|
||||
"globals": "^15.15.0",
|
||||
"ip-address": "^10.0.1",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-svelte": "^3.3.3",
|
||||
"prettier-plugin-tailwindcss": "^0.6.11",
|
||||
"qrcode-svg": "^1.1.0",
|
||||
"svelte": "^5.28.1",
|
||||
"svelte-check": "^4.1.6",
|
||||
"tailwind-merge": "^2.6.0",
|
||||
"tailwind-variants": "^0.3.1",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"ts-patch": "^3.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.31.0",
|
||||
"typia": "^8.2.0",
|
||||
"vite": "^6.3.2"
|
||||
"eslint-plugin-svelte": "^2.36.0",
|
||||
"globals": "^15.0.0",
|
||||
"prettier": "^3.3.2",
|
||||
"prettier-plugin-svelte": "^3.2.6",
|
||||
"prettier-plugin-tailwindcss": "^0.6.5",
|
||||
"svelte": "^5.0.0",
|
||||
"svelte-check": "^4.0.0",
|
||||
"tailwind-merge": "^2.5.4",
|
||||
"tailwind-variants": "^0.2.1",
|
||||
"tailwindcss": "^3.4.9",
|
||||
"typescript": "^5.0.0",
|
||||
"typescript-eslint": "^8.0.0",
|
||||
"vite": "^5.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@libsql/client": "^0.14.0",
|
||||
"drizzle-kit": "^0.30.6",
|
||||
"drizzle-orm": "^0.38.4"
|
||||
"@oslojs/crypto": "^1.0.1",
|
||||
"@oslojs/encoding": "^1.1.0",
|
||||
"arctic": "^2.2.1",
|
||||
"drizzle-orm": "^0.38.2",
|
||||
"ip-address": "^10.0.1",
|
||||
"lucide-svelte": "^0.454.0",
|
||||
"qrcode-svg": "^1.1.0"
|
||||
}
|
||||
}
|
||||
|
135
src/app.css
135
src/app.css
@ -3,110 +3,79 @@
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 90%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
:root {
|
||||
--background: 0 0% 90%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
|
||||
--popover: 0 0% 90%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
--popover: 0 0% 90%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
|
||||
--card: 0 0% 90%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
--card: 0 0% 90%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
|
||||
--primary: 222.2 47.4% 11.2%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--primary: 222.2 47.4% 11.2%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
|
||||
--secondary: 210 26% 86%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
--secondary: 210 26% 86%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--accent: 210 26% 86%;
|
||||
--accent-light: 210 26% 86%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
--accent: 210 26% 86%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--destructive: 0 72.2% 50.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--destructive: 0 72.2% 50.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
|
||||
--ring: 222.2 84% 4.9%;
|
||||
--ring: 222.2 84% 4.9%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
--sidebar-background: 0 0% 98%;
|
||||
--sidebar-foreground: 240 5.3% 26.1%;
|
||||
--sidebar-primary: 240 5.9% 10%;
|
||||
--sidebar-primary-foreground: 0 0% 98%;
|
||||
--sidebar-accent: 240 4.8% 95.9%;
|
||||
--sidebar-accent-foreground: 240 5.9% 10%;
|
||||
--sidebar-border: 220 13% 91%;
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 90%;
|
||||
|
||||
--surface: 210 26% 76%;
|
||||
}
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 90%;
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 90%;
|
||||
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 90%;
|
||||
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 90%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 90%;
|
||||
--primary: 210 40% 90%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 90%;
|
||||
|
||||
--primary: 210 40% 90%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 90%;
|
||||
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 90%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 90%;
|
||||
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 90%;
|
||||
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 90%;
|
||||
|
||||
--ring: 212.7 26.8% 83.9%;
|
||||
|
||||
--sidebar-background: 240 5.9% 10%;
|
||||
--sidebar-foreground: 240 4.8% 95.9%;
|
||||
--sidebar-primary: 224.3 76.3% 48%;
|
||||
--sidebar-primary-foreground: 0 0% 100%;
|
||||
--sidebar-accent: 240 3.7% 15.9%;
|
||||
--sidebar-accent-foreground: 240 4.8% 95.9%;
|
||||
--sidebar-border: 240 3.7% 15.9%;
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
|
||||
--surface: 217.2 40.6% 11.5%;
|
||||
}
|
||||
}
|
||||
--ring: 212.7 26.8% 83.9%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
ol > li {
|
||||
@apply flex flex-wrap gap-x-2;
|
||||
counter-increment: counterName;
|
||||
}
|
||||
ol > li:before {
|
||||
content: counter(counterName) '.';
|
||||
}
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
@ -6,10 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body
|
||||
data-sveltekit-preload-data="hover"
|
||||
class="flex min-h-screen flex-col items-center gap-8 p-4 max-sm:px-2"
|
||||
>
|
||||
%sveltekit.body%
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div class="flex flex-col min-h-screen">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,10 +1,7 @@
|
||||
import { type Handle, redirect } from '@sveltejs/kit';
|
||||
import { sequence } from '@sveltejs/kit/hooks';
|
||||
import { dev } from '$app/environment';
|
||||
import * as auth from '$lib/server/auth';
|
||||
import wgProvider from '$lib/server/wg-provider';
|
||||
|
||||
await wgProvider.init();
|
||||
import { sequence } from '@sveltejs/kit/hooks';
|
||||
|
||||
const handleAuth: Handle = async ({ event, resolve }) => {
|
||||
const sessionId = event.cookies.get(auth.sessionCookieName);
|
||||
@ -38,7 +35,7 @@ const authRequired = [
|
||||
/^\/api/,
|
||||
/^\/user/,
|
||||
/^\/connections/,
|
||||
/^\/devices/,
|
||||
/^\/clients/,
|
||||
];
|
||||
const handleProtectedPaths: Handle = ({ event, resolve }) => {
|
||||
const isProtected = authRequired.some((re) => re.test(event.url.pathname));
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 4.6 KiB |
@ -1,13 +0,0 @@
|
||||
<svg width="40" height="40" viewBox="10 10 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_710_6221)">
|
||||
<path d="M29.6 20.2273C29.6 19.5182 29.5364 18.8364 29.4182 18.1818H20V22.05H25.3818C25.15 23.3 24.4455 24.3591 23.3864 25.0682V27.5773H26.6182C28.5091 25.8364 29.6 23.2727 29.6 20.2273Z" fill="#4285F4"/>
|
||||
<path d="M20 30C22.7 30 24.9636 29.1045 26.6181 27.5773L23.3863 25.0682C22.4909 25.6682 21.3454 26.0227 20 26.0227C17.3954 26.0227 15.1909 24.2636 14.4045 21.9H11.0636V24.4909C12.7091 27.7591 16.0909 30 20 30Z" fill="#34A853"/>
|
||||
<path d="M14.4045 21.9C14.2045 21.3 14.0909 20.6591 14.0909 20C14.0909 19.3409 14.2045 18.7 14.4045 18.1V15.5091H11.0636C10.3864 16.8591 10 18.3864 10 20C10 21.6136 10.3864 23.1409 11.0636 24.4909L14.4045 21.9Z" fill="#FBBC04"/>
|
||||
<path d="M20 13.9773C21.4681 13.9773 22.7863 14.4818 23.8227 15.4727L26.6909 12.6045C24.9591 10.9909 22.6954 10 20 10C16.0909 10 12.7091 12.2409 11.0636 15.5091L14.4045 18.1C15.1909 15.7364 17.3954 13.9773 20 13.9773Z" fill="#E94235"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_710_6221">
|
||||
<rect width="20" height="20" fill="white" transform="translate(10 10)"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
Before Width: | Height: | Size: 1.1 KiB |
BIN
src/lib/assets/guide-android.mp4
(Stored with Git LFS)
BIN
src/lib/assets/guide-android.mp4
(Stored with Git LFS)
Binary file not shown.
@ -1,9 +0,0 @@
|
||||
import { envToBool } from '$lib/utils';
|
||||
import { env } from '$env/dynamic/public';
|
||||
|
||||
export type AuthProvider = 'authentik' | 'google';
|
||||
|
||||
export const enabledAuthProviders: Record<AuthProvider, boolean> = {
|
||||
authentik: envToBool(env.PUBLIC_AUTH_AUTHENTIK_ENABLE),
|
||||
google: envToBool(env.PUBLIC_AUTH_GOOGLE_ENABLE),
|
||||
};
|
33
src/lib/clients.ts
Normal file
33
src/lib/clients.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import type { ClientDetails } from '$lib/types/clients';
|
||||
|
||||
/**
|
||||
* Convert client details to WireGuard configuration.
|
||||
*
|
||||
* ```conf
|
||||
* [Interface]
|
||||
* PrivateKey = wPa07zR0H4wYoc1ljfeiqlSbR8Z28pPc6jplwE7zPms=
|
||||
* Address = 10.18.11.100/32,fd00::1/128
|
||||
* DNS = 10.18.11.1,fd00::0
|
||||
*
|
||||
* [Peer]
|
||||
* PublicKey = BJ5faPVJsDP4CCxNYilmKnwlQXOtXEOJjqIwb4U/CgM=
|
||||
* PresharedKey = uhZUVqXKF0oayP0BS6yPu6Gepgh68Nz9prtbE5Cuok0=
|
||||
* Endpoint = vpn.lab.cazzzer.com:51820
|
||||
* AllowedIPs = 0.0.0.0/0,::/0
|
||||
* ```
|
||||
* @param client
|
||||
*/
|
||||
export function clientDetailsToConfig(client: ClientDetails): string {
|
||||
return `\
|
||||
[Interface]
|
||||
PrivateKey = ${client.privateKey}
|
||||
Address = ${client.ips.join(', ')}
|
||||
DNS = ${client.vpnDns}
|
||||
|
||||
[Peer]
|
||||
PublicKey = ${client.vpnPublicKey}
|
||||
PresharedKey = ${client.preSharedKey}
|
||||
Endpoint = ${client.vpnEndpoint}
|
||||
AllowedIPs = 0.0.0.0/0,::/0
|
||||
`;
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { LucideLoaderCircle } from '@lucide/svelte';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
|
||||
interface Props {
|
||||
providerName: string;
|
||||
displayName: string;
|
||||
iconSrc: string;
|
||||
inviteToken?: string;
|
||||
}
|
||||
let { providerName, displayName, inviteToken, iconSrc }: Props = $props();
|
||||
|
||||
let submitted = $state(false);
|
||||
</script>
|
||||
|
||||
<form method="get" onsubmit={() => (submitted = true)} action="/auth/{providerName}">
|
||||
{#if inviteToken}
|
||||
<input type="hidden" value={inviteToken} name="invite" />
|
||||
{/if}
|
||||
<Button type="submit" disabled={submitted}>
|
||||
{#if submitted}
|
||||
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<img class="mr-2 h-4 w-4" alt="{displayName} Logo" src={iconSrc} />
|
||||
{/if}
|
||||
Sign {inviteToken ? 'up' : 'in'} with {displayName}
|
||||
</Button>
|
||||
</form>
|
@ -1,26 +1,22 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '$lib/utils.js';
|
||||
import googleIcon from '$lib/assets/google.svg';
|
||||
import { enabledAuthProviders } from '$lib/auth';
|
||||
import AuthButton from './auth-button.svelte';
|
||||
import { LucideLoaderCircle } from 'lucide-svelte';
|
||||
import { Button } from "$lib/components/ui/button";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
interface Props {
|
||||
inviteToken?: string;
|
||||
class?: string;
|
||||
}
|
||||
let { inviteToken, class: className }: Props = $props();
|
||||
let { class: className, ...rest }: {class: string | undefined | null, rest: { [p: string]: unknown }} = $props();
|
||||
|
||||
let isLoading = $state(false);
|
||||
</script>
|
||||
|
||||
<div class={cn('flex gap-6', className)}>
|
||||
{#if enabledAuthProviders.authentik}
|
||||
<AuthButton
|
||||
providerName="authentik"
|
||||
displayName="Authentik"
|
||||
iconSrc="https://auth.cazzzer.com/static/dist/assets/icons/icon.svg"
|
||||
{inviteToken}
|
||||
/>
|
||||
{/if}
|
||||
{#if enabledAuthProviders.google}
|
||||
<AuthButton providerName="google" displayName="Google" iconSrc={googleIcon} {inviteToken} />
|
||||
{/if}
|
||||
<div class={cn("grid gap-6", className)} {...rest}>
|
||||
<form method="get" action="/auth/authentik">
|
||||
<Button type="submit" onclick={() => {isLoading=true}}>
|
||||
{#if isLoading}
|
||||
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<img class="mr-2 h-4 w-4" alt="Authentik Logo" src="https://auth.cazzzer.com/static/dist/assets/icons/icon.svg" />
|
||||
{/if}
|
||||
Sign in with Authentik
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
@ -1,74 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { LucideClipboardCopy, LucideDownload } from '@lucide/svelte';
|
||||
|
||||
const {
|
||||
data,
|
||||
filename,
|
||||
copy,
|
||||
download,
|
||||
}: {
|
||||
data: string;
|
||||
filename?: string;
|
||||
copy?: boolean;
|
||||
download?: boolean;
|
||||
} = $props();
|
||||
|
||||
let wasCopied = $state(false);
|
||||
|
||||
const roundedPre = copy || download ? 'rounded-b-lg' : 'rounded-lg';
|
||||
|
||||
async function copyToClipboard() {
|
||||
await navigator.clipboard.writeText(data);
|
||||
wasCopied = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex max-w-full flex-grow flex-col rounded-lg bg-accent">
|
||||
{#if copy || download}
|
||||
<!--Copy and download buttons-->
|
||||
<div class="b flex flex-wrap items-center justify-between gap-4 rounded-t-lg p-2">
|
||||
Configuration
|
||||
<div class="flex gap-2">
|
||||
{#if copy}
|
||||
<Button
|
||||
class="action-button group"
|
||||
onclick={copyToClipboard}
|
||||
onmouseleave={() => (wasCopied = false)}
|
||||
>
|
||||
<LucideClipboardCopy />
|
||||
<span class="group-hover:block">
|
||||
{wasCopied ? 'Copied' : 'Copy to clipboard'}
|
||||
</span>
|
||||
</Button>
|
||||
{/if}
|
||||
|
||||
{#if download}
|
||||
<a
|
||||
class="contents"
|
||||
href={`data:application/octet-stream;charset=utf-8,${encodeURIComponent(data)}`}
|
||||
download={filename}
|
||||
>
|
||||
<Button class="action-button group">
|
||||
<LucideDownload />
|
||||
<span class="group-hover:block">Download</span>
|
||||
</Button>
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="bg-surface flex items-start overflow-x-auto {roundedPre} p-2">
|
||||
<pre><code>{data}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
:global(.action-button) {
|
||||
@apply relative size-auto p-2;
|
||||
}
|
||||
|
||||
:global(.action-button > span) {
|
||||
@apply absolute bottom-full mb-3 hidden rounded-lg bg-muted p-2 text-xs text-foreground;
|
||||
}
|
||||
</style>
|
@ -1,7 +0,0 @@
|
||||
import Root from "./code-snippet.svelte";
|
||||
|
||||
export {
|
||||
Root,
|
||||
//
|
||||
Root as CodeSnippet,
|
||||
};
|
@ -1,5 +0,0 @@
|
||||
import WireguardGuide from "./wireguard-guide.svelte";
|
||||
|
||||
export {
|
||||
WireguardGuide
|
||||
};
|
@ -1,85 +0,0 @@
|
||||
<script lang="ts">
|
||||
import * as Tabs from '$lib/components/ui/tabs';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import getItOnGooglePlay from '$lib/assets/GetItOnGooglePlay_Badge_Web_color_English.png';
|
||||
import guideVideoAndroid from '$lib/assets/guide-android.mp4';
|
||||
</script>
|
||||
|
||||
<Tabs.Root value="android">
|
||||
<Tabs.List class="grid w-full grid-cols-3">
|
||||
<Tabs.Trigger value="android">Android</Tabs.Trigger>
|
||||
<Tabs.Trigger value="windows">Windows</Tabs.Trigger>
|
||||
<Tabs.Trigger value="other">Other</Tabs.Trigger>
|
||||
</Tabs.List>
|
||||
<Tabs.Content value="android">
|
||||
<Card.Root>
|
||||
<Card.Header class="max-sm:px-4 max-sm:pt-4">
|
||||
<Card.Title>WireGuard on Android</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content class="max-sm:p-4">
|
||||
<ol class="flex flex-col gap-2">
|
||||
<li>
|
||||
<div class="flex flex-col gap-2">
|
||||
Install the WireGuard app
|
||||
<a
|
||||
class="contents"
|
||||
href="https://play.google.com/store/apps/details?id=com.wireguard.android"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<img class="size-min" alt="Get it on google play" src={getItOnGooglePlay} />
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div class="flex flex-col gap-2">
|
||||
<p>Download the configuration file and import it</p>
|
||||
<aside>Alternatively, you can scan the QR code with the WireGuard app</aside>
|
||||
<video autoplay loop controls muted preload="metadata" class="max-h-screen">
|
||||
<source src={guideVideoAndroid} type="video/mp4" />
|
||||
</video>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</Tabs.Content>
|
||||
<Tabs.Content value="windows">
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>WireGuard on Windows</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<p>
|
||||
<a
|
||||
class="underline"
|
||||
href="https://download.wireguard.com/windows-client/wireguard-installer.exe"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Download WireGuard
|
||||
</a>
|
||||
</p>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</Tabs.Content>
|
||||
<Tabs.Content value="other">
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>WireGuard on Other Platforms</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<p>
|
||||
You can download the WireGuard client from the <a
|
||||
class="underline"
|
||||
href="https://www.wireguard.com/install/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
official website
|
||||
</a>.
|
||||
</p>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</Tabs.Content>
|
||||
</Tabs.Root>
|
@ -1,50 +1,18 @@
|
||||
<script lang="ts" module>
|
||||
import { type VariantProps, tv } from "tailwind-variants";
|
||||
|
||||
export const badgeVariants = tv({
|
||||
base: "focus:ring-ring inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground hover:bg-primary/80 border-transparent",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80 border-transparent",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/80 border-transparent",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
});
|
||||
|
||||
export type BadgeVariant = VariantProps<typeof badgeVariants>["variant"];
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAnchorAttributes } from "svelte/elements";
|
||||
import { type Variant, badgeVariants } from "./index.js";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
href,
|
||||
class: className,
|
||||
variant = "default",
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAnchorAttributes> & {
|
||||
variant?: BadgeVariant;
|
||||
} = $props();
|
||||
let className: string | undefined | null = undefined;
|
||||
export let href: string | undefined = undefined;
|
||||
export let variant: Variant = "default";
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<svelte:element
|
||||
this={href ? "a" : "span"}
|
||||
bind:this={ref}
|
||||
{href}
|
||||
class={cn(badgeVariants({ variant }), className)}
|
||||
{...restProps}
|
||||
class={cn(badgeVariants({ variant, className }))}
|
||||
{...$$restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
<slot />
|
||||
</svelte:element>
|
||||
|
@ -1,2 +1,21 @@
|
||||
import { type VariantProps, tv } from "tailwind-variants";
|
||||
export { default as Badge } from "./badge.svelte";
|
||||
export { badgeVariants, type BadgeVariant } from "./badge.svelte";
|
||||
|
||||
export const badgeVariants = tv({
|
||||
base: "focus:ring-ring inline-flex select-none items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/80 border-transparent",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80 border-transparent",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/80 border-transparent",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
});
|
||||
|
||||
export type Variant = VariantProps<typeof badgeVariants>["variant"];
|
||||
|
@ -1,74 +1,25 @@
|
||||
<script lang="ts" module>
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAnchorAttributes, HTMLButtonAttributes } from "svelte/elements";
|
||||
import { type VariantProps, tv } from "tailwind-variants";
|
||||
|
||||
export const buttonVariants = tv({
|
||||
base: "ring-offset-background focus-visible:ring-ring inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border-input bg-background hover:bg-accent hover:text-accent-foreground border",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
});
|
||||
|
||||
export type ButtonVariant = VariantProps<typeof buttonVariants>["variant"];
|
||||
export type ButtonSize = VariantProps<typeof buttonVariants>["size"];
|
||||
|
||||
export type ButtonProps = WithElementRef<HTMLButtonAttributes> &
|
||||
WithElementRef<HTMLAnchorAttributes> & {
|
||||
variant?: ButtonVariant;
|
||||
size?: ButtonSize;
|
||||
};
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { Button as ButtonPrimitive } from "bits-ui";
|
||||
import { type Events, type Props, buttonVariants } from "./index.js";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
class: className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
ref = $bindable(null),
|
||||
href = undefined,
|
||||
type = "button",
|
||||
children,
|
||||
...restProps
|
||||
}: ButtonProps = $props();
|
||||
type $$Props = Props;
|
||||
type $$Events = Events;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export let variant: $$Props["variant"] = "default";
|
||||
export let size: $$Props["size"] = "default";
|
||||
export let builders: $$Props["builders"] = [];
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
{#if href}
|
||||
<a
|
||||
bind:this={ref}
|
||||
class={cn(buttonVariants({ variant, size }), className)}
|
||||
{href}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</a>
|
||||
{:else}
|
||||
<button
|
||||
bind:this={ref}
|
||||
class={cn(buttonVariants({ variant, size }), className)}
|
||||
{type}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</button>
|
||||
{/if}
|
||||
<ButtonPrimitive.Root
|
||||
{builders}
|
||||
class={cn(buttonVariants({ variant, size, className }))}
|
||||
type="button"
|
||||
{...$$restProps}
|
||||
on:click
|
||||
on:keydown
|
||||
>
|
||||
<slot />
|
||||
</ButtonPrimitive.Root>
|
||||
|
@ -1,17 +1,49 @@
|
||||
import Root, {
|
||||
type ButtonProps,
|
||||
type ButtonSize,
|
||||
type ButtonVariant,
|
||||
buttonVariants,
|
||||
} from "./button.svelte";
|
||||
import { type VariantProps, tv } from "tailwind-variants";
|
||||
import type { Button as ButtonPrimitive } from "bits-ui";
|
||||
import Root from "./button.svelte";
|
||||
|
||||
const buttonVariants = tv({
|
||||
base: "ring-offset-background focus-visible:ring-ring inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border-input bg-background hover:bg-accent hover:text-accent-foreground border",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
});
|
||||
|
||||
type Variant = VariantProps<typeof buttonVariants>["variant"];
|
||||
type Size = VariantProps<typeof buttonVariants>["size"];
|
||||
|
||||
type Props = ButtonPrimitive.Props & {
|
||||
variant?: Variant;
|
||||
size?: Size;
|
||||
};
|
||||
|
||||
type Events = ButtonPrimitive.Events;
|
||||
|
||||
export {
|
||||
Root,
|
||||
type ButtonProps as Props,
|
||||
type Props,
|
||||
type Events,
|
||||
//
|
||||
Root as Button,
|
||||
type Props as ButtonProps,
|
||||
type Events as ButtonEvents,
|
||||
buttonVariants,
|
||||
type ButtonProps,
|
||||
type ButtonSize,
|
||||
type ButtonVariant,
|
||||
};
|
||||
|
@ -1,16 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div bind:this={ref} class={cn("p-6", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,16 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLParagraphElement>> = $props();
|
||||
</script>
|
||||
|
||||
<p bind:this={ref} class={cn("text-muted-foreground text-sm", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
</p>
|
@ -1,16 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div bind:this={ref} class={cn("flex items-center p-6 pt-0", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,16 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div bind:this={ref} class={cn("flex flex-col space-y-1.5 p-6 pb-0", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,25 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
level = 3,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
|
||||
level?: 1 | 2 | 3 | 4 | 5 | 6;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
role="heading"
|
||||
aria-level={level}
|
||||
bind:this={ref}
|
||||
class={cn("text-2xl font-semibold leading-none tracking-tight", className)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,20 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={ref}
|
||||
class={cn("bg-card text-card-foreground rounded-lg border shadow-sm", className)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,22 +0,0 @@
|
||||
import Root from "./card.svelte";
|
||||
import Content from "./card-content.svelte";
|
||||
import Description from "./card-description.svelte";
|
||||
import Footer from "./card-footer.svelte";
|
||||
import Header from "./card-header.svelte";
|
||||
import Title from "./card-title.svelte";
|
||||
|
||||
export {
|
||||
Root,
|
||||
Content,
|
||||
Description,
|
||||
Footer,
|
||||
Header,
|
||||
Title,
|
||||
//
|
||||
Root as Card,
|
||||
Content as CardContent,
|
||||
Description as CardDescription,
|
||||
Footer as CardFooter,
|
||||
Header as CardHeader,
|
||||
Title as CardTitle,
|
||||
};
|
@ -1,35 +1,35 @@
|
||||
<script lang="ts">
|
||||
import { Checkbox as CheckboxPrimitive, type WithoutChildrenOrChild } from "bits-ui";
|
||||
import Check from "@lucide/svelte/icons/check";
|
||||
import Minus from "@lucide/svelte/icons/minus";
|
||||
import { Checkbox as CheckboxPrimitive } from "bits-ui";
|
||||
import Check from "lucide-svelte/icons/check";
|
||||
import Minus from "lucide-svelte/icons/minus";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
checked = $bindable(false),
|
||||
indeterminate = $bindable(false),
|
||||
class: className,
|
||||
...restProps
|
||||
}: WithoutChildrenOrChild<CheckboxPrimitive.RootProps> = $props();
|
||||
type $$Props = CheckboxPrimitive.Props;
|
||||
type $$Events = CheckboxPrimitive.Events;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export let checked: $$Props["checked"] = false;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<CheckboxPrimitive.Root
|
||||
bind:ref
|
||||
class={cn(
|
||||
"border-primary ring-offset-background focus-visible:ring-ring data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground peer box-content size-4 shrink-0 rounded-sm border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50",
|
||||
"border-primary ring-offset-background focus-visible:ring-ring data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground peer box-content h-4 w-4 shrink-0 rounded-sm border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50",
|
||||
className
|
||||
)}
|
||||
bind:checked
|
||||
bind:indeterminate
|
||||
{...restProps}
|
||||
{...$$restProps}
|
||||
on:click
|
||||
>
|
||||
{#snippet children({ checked, indeterminate })}
|
||||
<div class="flex size-4 items-center justify-center text-current">
|
||||
{#if indeterminate}
|
||||
<Minus class="size-3.5" />
|
||||
{:else}
|
||||
<Check class={cn("size-3.5", !checked && "text-transparent")} />
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
<CheckboxPrimitive.Indicator
|
||||
class={cn("flex h-4 w-4 items-center justify-center text-current")}
|
||||
let:isChecked
|
||||
let:isIndeterminate
|
||||
>
|
||||
{#if isChecked}
|
||||
<Check class="h-3.5 w-3.5" />
|
||||
{:else if isIndeterminate}
|
||||
<Minus class="h-3.5 w-3.5" />
|
||||
{/if}
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
|
@ -1,38 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Dialog as DialogPrimitive, type WithoutChildrenOrChild } from "bits-ui";
|
||||
import X from "@lucide/svelte/icons/x";
|
||||
import type { Snippet } from "svelte";
|
||||
import * as Dialog from "./index.js";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
portalProps,
|
||||
children,
|
||||
...restProps
|
||||
}: WithoutChildrenOrChild<DialogPrimitive.ContentProps> & {
|
||||
portalProps?: DialogPrimitive.PortalProps;
|
||||
children: Snippet;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<Dialog.Portal {...portalProps}>
|
||||
<Dialog.Overlay />
|
||||
<DialogPrimitive.Content
|
||||
bind:ref
|
||||
class={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] bg-background fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
<DialogPrimitive.Close
|
||||
class="ring-offset-background focus:ring-ring absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none"
|
||||
>
|
||||
<X class="size-4" />
|
||||
<span class="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</Dialog.Portal>
|
@ -1,16 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Dialog as DialogPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: DialogPrimitive.DescriptionProps = $props();
|
||||
</script>
|
||||
|
||||
<DialogPrimitive.Description
|
||||
bind:ref
|
||||
class={cn("text-muted-foreground text-sm", className)}
|
||||
{...restProps}
|
||||
/>
|
@ -1,20 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={ref}
|
||||
class={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,20 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={ref}
|
||||
class={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</div>
|
@ -1,19 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Dialog as DialogPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: DialogPrimitive.OverlayProps = $props();
|
||||
</script>
|
||||
|
||||
<DialogPrimitive.Overlay
|
||||
bind:ref
|
||||
class={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
/>
|
@ -1,16 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Dialog as DialogPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: DialogPrimitive.TitleProps = $props();
|
||||
</script>
|
||||
|
||||
<DialogPrimitive.Title
|
||||
bind:ref
|
||||
class={cn("text-lg font-semibold leading-none tracking-tight", className)}
|
||||
{...restProps}
|
||||
/>
|
@ -1,37 +0,0 @@
|
||||
import { Dialog as DialogPrimitive } from "bits-ui";
|
||||
|
||||
import Title from "./dialog-title.svelte";
|
||||
import Footer from "./dialog-footer.svelte";
|
||||
import Header from "./dialog-header.svelte";
|
||||
import Overlay from "./dialog-overlay.svelte";
|
||||
import Content from "./dialog-content.svelte";
|
||||
import Description from "./dialog-description.svelte";
|
||||
|
||||
const Root = DialogPrimitive.Root;
|
||||
const Trigger = DialogPrimitive.Trigger;
|
||||
const Close = DialogPrimitive.Close;
|
||||
const Portal = DialogPrimitive.Portal;
|
||||
|
||||
export {
|
||||
Root,
|
||||
Title,
|
||||
Portal,
|
||||
Footer,
|
||||
Header,
|
||||
Trigger,
|
||||
Overlay,
|
||||
Content,
|
||||
Description,
|
||||
Close,
|
||||
//
|
||||
Root as Dialog,
|
||||
Title as DialogTitle,
|
||||
Portal as DialogPortal,
|
||||
Footer as DialogFooter,
|
||||
Header as DialogHeader,
|
||||
Trigger as DialogTrigger,
|
||||
Overlay as DialogOverlay,
|
||||
Content as DialogContent,
|
||||
Description as DialogDescription,
|
||||
Close as DialogClose,
|
||||
};
|
@ -1,5 +1,27 @@
|
||||
import Root from "./input.svelte";
|
||||
|
||||
export type FormInputEvent<T extends Event = Event> = T & {
|
||||
currentTarget: EventTarget & HTMLInputElement;
|
||||
};
|
||||
export type InputEvents = {
|
||||
blur: FormInputEvent<FocusEvent>;
|
||||
change: FormInputEvent<Event>;
|
||||
click: FormInputEvent<MouseEvent>;
|
||||
focus: FormInputEvent<FocusEvent>;
|
||||
focusin: FormInputEvent<FocusEvent>;
|
||||
focusout: FormInputEvent<FocusEvent>;
|
||||
keydown: FormInputEvent<KeyboardEvent>;
|
||||
keypress: FormInputEvent<KeyboardEvent>;
|
||||
keyup: FormInputEvent<KeyboardEvent>;
|
||||
mouseover: FormInputEvent<MouseEvent>;
|
||||
mouseenter: FormInputEvent<MouseEvent>;
|
||||
mouseleave: FormInputEvent<MouseEvent>;
|
||||
mousemove: FormInputEvent<MouseEvent>;
|
||||
paste: FormInputEvent<ClipboardEvent>;
|
||||
input: FormInputEvent<InputEvent>;
|
||||
wheel: FormInputEvent<WheelEvent>;
|
||||
};
|
||||
|
||||
export {
|
||||
Root,
|
||||
//
|
||||
|
@ -1,46 +1,42 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLInputAttributes, HTMLInputTypeAttribute } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import type { HTMLInputAttributes } from "svelte/elements";
|
||||
import type { InputEvents } from "./index.js";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
type InputType = Exclude<HTMLInputTypeAttribute, "file">;
|
||||
type $$Props = HTMLInputAttributes;
|
||||
type $$Events = InputEvents;
|
||||
|
||||
type Props = WithElementRef<
|
||||
Omit<HTMLInputAttributes, "type"> &
|
||||
({ type: "file"; files?: FileList } | { type?: InputType; files?: undefined })
|
||||
>;
|
||||
let className: $$Props["class"] = undefined;
|
||||
export let value: $$Props["value"] = undefined;
|
||||
export { className as class };
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
value = $bindable(),
|
||||
type,
|
||||
files = $bindable(),
|
||||
class: className,
|
||||
...restProps
|
||||
}: Props = $props();
|
||||
// Workaround for https://github.com/sveltejs/svelte/issues/9305
|
||||
// Fixed in Svelte 5, but not backported to 4.x.
|
||||
export let readonly: $$Props["readonly"] = undefined;
|
||||
</script>
|
||||
|
||||
{#if type === "file"}
|
||||
<input
|
||||
bind:this={ref}
|
||||
class={cn(
|
||||
"border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
type="file"
|
||||
bind:files
|
||||
bind:value
|
||||
{...restProps}
|
||||
/>
|
||||
{:else}
|
||||
<input
|
||||
bind:this={ref}
|
||||
class={cn(
|
||||
"border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{type}
|
||||
bind:value
|
||||
{...restProps}
|
||||
/>
|
||||
{/if}
|
||||
<input
|
||||
class={cn(
|
||||
"border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
bind:value
|
||||
{readonly}
|
||||
on:blur
|
||||
on:change
|
||||
on:click
|
||||
on:focus
|
||||
on:focusin
|
||||
on:focusout
|
||||
on:keydown
|
||||
on:keypress
|
||||
on:keyup
|
||||
on:mouseover
|
||||
on:mouseenter
|
||||
on:mouseleave
|
||||
on:mousemove
|
||||
on:paste
|
||||
on:input
|
||||
on:wheel|passive
|
||||
{...$$restProps}
|
||||
/>
|
||||
|
@ -2,18 +2,20 @@
|
||||
import { Label as LabelPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: LabelPrimitive.RootProps = $props();
|
||||
type $$Props = LabelPrimitive.Props;
|
||||
type $$Events = LabelPrimitive.Events;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<LabelPrimitive.Root
|
||||
bind:ref
|
||||
class={cn(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
/>
|
||||
{...$$restProps}
|
||||
on:mousedown
|
||||
>
|
||||
<slot />
|
||||
</LabelPrimitive.Root>
|
||||
|
@ -1,16 +1,13 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
|
||||
type $$Props = HTMLAttributes<HTMLTableSectionElement>;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<tbody bind:this={ref} class={cn("[&_tr:last-child]:border-0", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
<tbody class={cn("[&_tr:last-child]:border-0", className)} {...$$restProps}>
|
||||
<slot />
|
||||
</tbody>
|
||||
|
@ -1,16 +1,13 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
|
||||
type $$Props = HTMLAttributes<HTMLTableCaptionElement>;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<caption bind:this={ref} class={cn("text-muted-foreground mt-4 text-sm", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
<caption class={cn("text-muted-foreground mt-4 text-sm", className)} {...$$restProps}>
|
||||
<slot />
|
||||
</caption>
|
||||
|
@ -1,20 +1,18 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLTdAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLTdAttributes> = $props();
|
||||
type $$Props = HTMLTdAttributes;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<td
|
||||
bind:this={ref}
|
||||
class={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
||||
{...restProps}
|
||||
{...$$restProps}
|
||||
on:click
|
||||
on:keydown
|
||||
>
|
||||
{@render children?.()}
|
||||
<slot />
|
||||
</td>
|
||||
|
@ -1,16 +1,13 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
|
||||
type $$Props = HTMLAttributes<HTMLTableSectionElement>;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<tfoot bind:this={ref} class={cn("bg-muted/50 font-medium", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
<tfoot class={cn("bg-muted/50 text-primary-foreground font-medium", className)} {...$$restProps}>
|
||||
<slot />
|
||||
</tfoot>
|
||||
|
@ -1,23 +1,19 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLThAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLThAttributes> = $props();
|
||||
type $$Props = HTMLThAttributes;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<th
|
||||
bind:this={ref}
|
||||
class={cn(
|
||||
"text-muted-foreground h-12 px-4 text-left align-middle font-medium [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
{...$$restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
<slot />
|
||||
</th>
|
||||
|
@ -1,16 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
|
||||
type $$Props = HTMLAttributes<HTMLTableSectionElement>;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<thead bind:this={ref} class={cn("[&_tr]:border-b", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
|
||||
<thead class={cn("[&_tr]:border-b", className)} {...$$restProps} on:click on:keydown>
|
||||
<slot />
|
||||
</thead>
|
||||
|
@ -1,23 +1,23 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLTableRowElement>> = $props();
|
||||
type $$Props = HTMLAttributes<HTMLTableRowElement> & {
|
||||
"data-state"?: unknown;
|
||||
};
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<tr
|
||||
bind:this={ref}
|
||||
class={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
{...$$restProps}
|
||||
on:click
|
||||
on:keydown
|
||||
>
|
||||
{@render children?.()}
|
||||
<slot />
|
||||
</tr>
|
||||
|
@ -1,18 +1,15 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLTableAttributes } from "svelte/elements";
|
||||
import type { WithElementRef } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLTableAttributes> = $props();
|
||||
type $$Props = HTMLTableAttributes;
|
||||
|
||||
let className: $$Props["class"] = undefined;
|
||||
export { className as class };
|
||||
</script>
|
||||
|
||||
<div class="relative w-full overflow-auto">
|
||||
<table bind:this={ref} class={cn("w-full caption-bottom text-sm", className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
<table class={cn("w-full caption-bottom text-sm", className)} {...$$restProps}>
|
||||
<slot />
|
||||
</table>
|
||||
</div>
|
||||
|
@ -1,18 +0,0 @@
|
||||
import { Tabs as TabsPrimitive } from "bits-ui";
|
||||
import Content from "./tabs-content.svelte";
|
||||
import List from "./tabs-list.svelte";
|
||||
import Trigger from "./tabs-trigger.svelte";
|
||||
|
||||
const Root = TabsPrimitive.Root;
|
||||
|
||||
export {
|
||||
Root,
|
||||
Content,
|
||||
List,
|
||||
Trigger,
|
||||
//
|
||||
Root as Tabs,
|
||||
Content as TabsContent,
|
||||
List as TabsList,
|
||||
Trigger as TabsTrigger,
|
||||
};
|
@ -1,19 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Tabs as TabsPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: TabsPrimitive.ContentProps = $props();
|
||||
</script>
|
||||
|
||||
<TabsPrimitive.Content
|
||||
bind:ref
|
||||
class={cn(
|
||||
"ring-offset-background focus-visible:ring-ring mt-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
/>
|
@ -1,19 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Tabs as TabsPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: TabsPrimitive.ListProps = $props();
|
||||
</script>
|
||||
|
||||
<TabsPrimitive.List
|
||||
bind:ref
|
||||
class={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-10 items-center justify-center rounded-md p-1",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
/>
|
@ -1,19 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Tabs as TabsPrimitive } from "bits-ui";
|
||||
import { cn } from "$lib/utils.js";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
...restProps
|
||||
}: TabsPrimitive.TriggerProps = $props();
|
||||
</script>
|
||||
|
||||
<TabsPrimitive.Trigger
|
||||
bind:ref
|
||||
class={cn(
|
||||
"ring-offset-background focus-visible:ring-ring data-[state=active]:bg-background data-[state=active]:text-foreground inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
/>
|
@ -1,10 +0,0 @@
|
||||
export type ConnectionDetails = {
|
||||
deviceId: number;
|
||||
deviceName: string;
|
||||
devicePublicKey: string;
|
||||
deviceIps: string[];
|
||||
endpoint: string;
|
||||
transferRx: number;
|
||||
transferTx: number;
|
||||
latestHandshake: number;
|
||||
};
|
@ -1,43 +0,0 @@
|
||||
/**
|
||||
* Convert device details to WireGuard configuration.
|
||||
*
|
||||
* ```conf
|
||||
* [Interface]
|
||||
* PrivateKey = wPa07zR0H4wYoc1ljfeiqlSbR8Z28pPc6jplwE7zPms=
|
||||
* Address = 10.18.11.100/32,fd00::1/128
|
||||
* DNS = 10.18.11.1,fd00::0
|
||||
*
|
||||
* [Peer]
|
||||
* PublicKey = BJ5faPVJsDP4CCxNYilmKnwlQXOtXEOJjqIwb4U/CgM=
|
||||
* PresharedKey = uhZUVqXKF0oayP0BS6yPu6Gepgh68Nz9prtbE5Cuok0=
|
||||
* Endpoint = vpn.lab.cazzzer.com:51820
|
||||
* AllowedIPs = 0.0.0.0/0,::/0
|
||||
* ```
|
||||
* @param device
|
||||
*/
|
||||
export function deviceDetailsToConfig(device: DeviceDetails): string {
|
||||
return `\
|
||||
[Interface]
|
||||
PrivateKey = ${device.privateKey}
|
||||
Address = ${device.ips.join(', ')}
|
||||
DNS = ${device.vpnDns}
|
||||
|
||||
[Peer]
|
||||
PublicKey = ${device.vpnPublicKey}
|
||||
PresharedKey = ${device.preSharedKey}
|
||||
Endpoint = ${device.vpnEndpoint}
|
||||
AllowedIPs = 0.0.0.0/0,::/0
|
||||
`;
|
||||
}
|
||||
|
||||
export type DeviceDetails = {
|
||||
id: number;
|
||||
name: string;
|
||||
publicKey: string;
|
||||
privateKey: string | null;
|
||||
preSharedKey: string | null;
|
||||
ips: string[];
|
||||
vpnPublicKey: string;
|
||||
vpnEndpoint: string;
|
||||
vpnDns: string;
|
||||
};
|
@ -3,9 +3,8 @@ import { sha256 } from '@oslojs/crypto/sha2';
|
||||
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from '@oslojs/encoding';
|
||||
import { db } from '$lib/server/db';
|
||||
import * as table from '$lib/server/db/schema';
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { dev } from '$app/environment';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
const DAY_IN_MS = 1000 * 60 * 60 * 24;
|
||||
|
||||
@ -22,14 +21,14 @@ export async function createSession(userId: string): Promise<table.Session> {
|
||||
const session: table.Session = {
|
||||
id: sessionId,
|
||||
userId,
|
||||
expiresAt: new Date(Date.now() + DAY_IN_MS * 30),
|
||||
expiresAt: new Date(Date.now() + DAY_IN_MS * 30)
|
||||
};
|
||||
await db.insert(table.sessions).values(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
export function setSessionTokenCookie(cookies: Cookies, sessionId: string, expiresAt: Date) {
|
||||
cookies.set(sessionCookieName, sessionId, {
|
||||
export function setSessionTokenCookie(event: RequestEvent, sessionId: string, expiresAt: Date) {
|
||||
event.cookies.set(sessionCookieName, sessionId, {
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
httpOnly: true,
|
||||
@ -42,21 +41,16 @@ export async function invalidateSession(sessionId: string): Promise<void> {
|
||||
await db.delete(table.sessions).where(eq(table.sessions.id, sessionId));
|
||||
}
|
||||
|
||||
export function deleteSessionTokenCookie(cookies: Cookies) {
|
||||
cookies.delete(sessionCookieName, { path: '/' });
|
||||
export function deleteSessionTokenCookie(event: RequestEvent) {
|
||||
event.cookies.delete(sessionCookieName, { path: '/' });
|
||||
}
|
||||
|
||||
export async function validateSession(sessionId: string) {
|
||||
const [result] = await db
|
||||
.select({
|
||||
// Adjust user table here to tweak returned data
|
||||
user: {
|
||||
id: table.users.id,
|
||||
authSource: table.users.authSource,
|
||||
username: table.users.username,
|
||||
name: table.users.name,
|
||||
},
|
||||
session: table.sessions,
|
||||
user: { id: table.users.id, username: table.users.username, name: table.users.name },
|
||||
session: table.sessions
|
||||
})
|
||||
.from(table.sessions)
|
||||
.innerJoin(table.users, eq(table.sessions.userId, table.users.id))
|
||||
@ -85,8 +79,4 @@ export async function validateSession(sessionId: string) {
|
||||
return { session, user };
|
||||
}
|
||||
|
||||
export function isValidInviteToken(inviteToken: string) {
|
||||
return inviteToken === env.AUTH_INVITE_TOKEN;
|
||||
}
|
||||
|
||||
export type SessionValidationResult = Awaited<ReturnType<typeof validateSession>>;
|
||||
|
227
src/lib/server/clients.ts
Normal file
227
src/lib/server/clients.ts
Normal file
@ -0,0 +1,227 @@
|
||||
import type { User } from '$lib/server/db/schema';
|
||||
import { db } from '$lib/server/db';
|
||||
import { wgClients, ipAllocations } from '$lib/server/db/schema';
|
||||
import { opnsenseAuth, opnsenseUrl, serverPublicKey, serverUuid } from '$lib/server/opnsense';
|
||||
import { Address4, Address6 } from 'ip-address';
|
||||
import {
|
||||
IP_MAX_INDEX,
|
||||
IPV4_STARTING_ADDR,
|
||||
IPV6_CLIENT_PREFIX_SIZE,
|
||||
IPV6_STARTING_ADDR,
|
||||
MAX_CLIENTS_PER_USER,
|
||||
VPN_DNS,
|
||||
VPN_ENDPOINT,
|
||||
} from '$env/static/private';
|
||||
import { and, count, eq, isNull } from 'drizzle-orm';
|
||||
import { err, ok, type Result } from '$lib/types';
|
||||
import type { ClientDetails } from '$lib/types/clients';
|
||||
|
||||
export async function findClients(userId: string) {
|
||||
return db.query.wgClients.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
publicKey: true,
|
||||
privateKey: true,
|
||||
preSharedKey: true,
|
||||
},
|
||||
with: {
|
||||
ipAllocation: true,
|
||||
},
|
||||
where: eq(wgClients.userId, userId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function findClient(userId: string, clientId: number) {
|
||||
return db.query.wgClients.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
publicKey: true,
|
||||
privateKey: true,
|
||||
preSharedKey: true,
|
||||
},
|
||||
with: {
|
||||
ipAllocation: true,
|
||||
},
|
||||
where: and(eq(wgClients.userId, userId), eq(wgClients.id, clientId)),
|
||||
});
|
||||
}
|
||||
|
||||
export function mapClientToDetails(
|
||||
client: Awaited<ReturnType<typeof findClients>>[0],
|
||||
): ClientDetails {
|
||||
const ips = getIpsFromIndex(client.ipAllocation.id);
|
||||
return {
|
||||
id: client.id,
|
||||
name: client.name,
|
||||
publicKey: client.publicKey,
|
||||
privateKey: client.privateKey,
|
||||
preSharedKey: client.preSharedKey,
|
||||
ips,
|
||||
vpnPublicKey: serverPublicKey,
|
||||
vpnEndpoint: VPN_ENDPOINT,
|
||||
vpnDns: VPN_DNS,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createClient(params: {
|
||||
name: string;
|
||||
user: User;
|
||||
}): Promise<Result<null, [400 | 500, string]>> {
|
||||
// check if user exceeds the limit of clients
|
||||
const [{ clientCount }] = await db
|
||||
.select({ clientCount: count() })
|
||||
.from(wgClients)
|
||||
.where(eq(wgClients.userId, params.user.id));
|
||||
if (clientCount >= parseInt(MAX_CLIENTS_PER_USER))
|
||||
return err([400, 'Maximum number of clients reached'] as [400, string]);
|
||||
|
||||
// this is going to be quite long
|
||||
// 1. fetch params for new client from opnsense api
|
||||
// 2.1 get an allocation for the client
|
||||
// 2.2. insert new client into db
|
||||
// 2.3. update the allocation with the client id
|
||||
// 3. create the client in opnsense
|
||||
// 4. reconfigure opnsense to enable the new client
|
||||
const error = await db.transaction(async (tx) => {
|
||||
const [keys, availableAllocation, lastAllocation] = await Promise.all([
|
||||
// fetch params for new client from opnsense api
|
||||
getKeys(),
|
||||
// find first unallocated IP
|
||||
await tx.query.ipAllocations.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
where: isNull(ipAllocations.clientId),
|
||||
}),
|
||||
// find last allocation to check if we have any IPs left
|
||||
await tx.query.ipAllocations.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
orderBy: (ipAllocations, { desc }) => desc(ipAllocations.id),
|
||||
}),
|
||||
]);
|
||||
|
||||
// check for existing allocation or if we have any IPs left
|
||||
if (!availableAllocation && lastAllocation && lastAllocation.id >= parseInt(IP_MAX_INDEX)) {
|
||||
return err([500, 'No more IP addresses available'] as [500, string]);
|
||||
}
|
||||
|
||||
// use existing allocation or create a new one
|
||||
const ipAllocationId =
|
||||
availableAllocation?.id ??
|
||||
(await tx.insert(ipAllocations).values({}).returning({ id: ipAllocations.id }))[0].id;
|
||||
|
||||
// transaction savepoint after creating a new IP allocation
|
||||
// TODO: not sure if this is needed
|
||||
return await tx.transaction(async (tx2) => {
|
||||
// create new client in db
|
||||
const [newClient] = await tx2
|
||||
.insert(wgClients)
|
||||
.values({
|
||||
userId: params.user.id,
|
||||
name: params.name,
|
||||
publicKey: keys.pubkey,
|
||||
privateKey: keys.privkey,
|
||||
preSharedKey: keys.psk,
|
||||
})
|
||||
.returning({ id: wgClients.id });
|
||||
|
||||
// update IP allocation with client ID
|
||||
await tx2
|
||||
.update(ipAllocations)
|
||||
.set({ clientId: newClient.id })
|
||||
.where(eq(ipAllocations.id, ipAllocationId));
|
||||
|
||||
// create client in opnsense
|
||||
const opnsenseRes = await opnsenseCreateClient({
|
||||
username: params.user.username,
|
||||
pubkey: keys.pubkey,
|
||||
psk: keys.psk,
|
||||
allowedIps: getIpsFromIndex(ipAllocationId).join(','),
|
||||
});
|
||||
const opnsenseResJson = await opnsenseRes.json();
|
||||
if (opnsenseResJson['result'] !== 'saved') {
|
||||
tx2.rollback();
|
||||
console.error(`Error creating client in OPNsense: \n${opnsenseResJson}`);
|
||||
return err([500, 'Error creating client in OPNsense'] as [500, string]);
|
||||
}
|
||||
|
||||
// reconfigure opnsense
|
||||
await opnsenseReconfigure();
|
||||
});
|
||||
});
|
||||
if (error) return error;
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
async function getKeys() {
|
||||
// fetch key pair from opnsense
|
||||
const options: RequestInit = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
};
|
||||
const resKeyPair = await fetch(`${opnsenseUrl}/api/wireguard/server/key_pair`, options);
|
||||
const resPsk = await fetch(`${opnsenseUrl}/api/wireguard/client/psk`, options);
|
||||
const keyPair = await resKeyPair.json();
|
||||
const psk = await resPsk.json();
|
||||
return {
|
||||
pubkey: keyPair['pubkey'] as string,
|
||||
privkey: keyPair['privkey'] as string,
|
||||
psk: psk['psk'] as string,
|
||||
};
|
||||
}
|
||||
|
||||
export function getIpsFromIndex(ipIndex: number) {
|
||||
ipIndex -= 1; // 1-indexed in the db
|
||||
const v4StartingAddr = new Address4(IPV4_STARTING_ADDR);
|
||||
const v6StartingAddr = new Address6(IPV6_STARTING_ADDR);
|
||||
const v4Allowed = Address4.fromBigInt(v4StartingAddr.bigInt() + BigInt(ipIndex));
|
||||
const v6Offset = BigInt(ipIndex) << (128n - BigInt(IPV6_CLIENT_PREFIX_SIZE));
|
||||
const v6Allowed = Address6.fromBigInt(v6StartingAddr.bigInt() + v6Offset);
|
||||
const v6AllowedShort = v6Allowed.parsedAddress.join(':');
|
||||
|
||||
return [v4Allowed.address + '/32', v6AllowedShort + '/' + IPV6_CLIENT_PREFIX_SIZE];
|
||||
}
|
||||
|
||||
async function opnsenseCreateClient(params: {
|
||||
username: string;
|
||||
pubkey: string;
|
||||
psk: string;
|
||||
allowedIps: string;
|
||||
}) {
|
||||
return fetch(`${opnsenseUrl}/api/wireguard/client/addClientBuilder`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
configbuilder: {
|
||||
enabled: '1',
|
||||
name: `vpgen-${params.username}`,
|
||||
pubkey: params.pubkey,
|
||||
psk: params.psk,
|
||||
tunneladdress: params.allowedIps,
|
||||
server: serverUuid,
|
||||
endpoint: VPN_ENDPOINT,
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function opnsenseReconfigure() {
|
||||
return fetch(`${opnsenseUrl}/api/wireguard/service/reconfigure`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
import { drizzle } from 'drizzle-orm/libsql';
|
||||
import * as schema from './schema';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { DATABASE_URL } from '$env/static/private';
|
||||
|
||||
export const db= drizzle(env.DATABASE_URL, { schema });
|
||||
export const db= drizzle(DATABASE_URL, { schema });
|
||||
|
@ -3,13 +3,12 @@ import { relations } from 'drizzle-orm';
|
||||
|
||||
export const users = sqliteTable('users', {
|
||||
id: text('id').primaryKey(),
|
||||
authSource: text('auth_source').notNull().default('authentik'),
|
||||
username: text('username').notNull(),
|
||||
name: text('name').notNull(),
|
||||
});
|
||||
|
||||
export const usersRelations = relations(users, ({ many }) => ({
|
||||
devices: many(devices),
|
||||
wgClients: many(wgClients),
|
||||
}));
|
||||
|
||||
export const sessions = sqliteTable('sessions', {
|
||||
@ -23,21 +22,23 @@ export const sessions = sqliteTable('sessions', {
|
||||
export const ipAllocations = sqliteTable('ip_allocations', {
|
||||
// for now, id will be the same as the ipIndex
|
||||
id: integer('id').primaryKey({ autoIncrement: true }),
|
||||
// deviceId is nullable because allocations can remain after the device is deleted
|
||||
// unique for now, only allowing one allocation per device
|
||||
deviceId: integer('device_id')
|
||||
// clientId is nullable because allocations can remain after the client is deleted
|
||||
// unique for now, only allowing one allocation per client
|
||||
clientId: integer('client_id')
|
||||
.unique()
|
||||
.references(() => devices.id, { onDelete: 'set null' }),
|
||||
.references(() => wgClients.id, { onDelete: 'set null' }),
|
||||
});
|
||||
|
||||
export const devices = sqliteTable('devices', {
|
||||
export const wgClients = sqliteTable('wg_clients', {
|
||||
id: integer().primaryKey({ autoIncrement: true }),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
name: text('name').notNull(),
|
||||
// questioning whether this should be nullable
|
||||
opnsenseId: text('opnsense_id'),
|
||||
publicKey: text('public_key').notNull().unique(),
|
||||
// nullable for the possibility of a user supplying their own private key
|
||||
// nullable for the possibility of a client supplying their own private key
|
||||
privateKey: text('private_key'),
|
||||
// nullable for the possibility of no psk
|
||||
preSharedKey: text('pre_shared_key'),
|
||||
@ -47,18 +48,18 @@ export const devices = sqliteTable('devices', {
|
||||
// allowedIps: text('allowed_ips').notNull(),
|
||||
});
|
||||
|
||||
export const devicesRelations = relations(devices, ({ one }) => ({
|
||||
export const wgClientsRelations = relations(wgClients, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [devices.userId],
|
||||
fields: [wgClients.userId],
|
||||
references: [users.id],
|
||||
}),
|
||||
ipAllocation: one(ipAllocations, {
|
||||
fields: [devices.id],
|
||||
references: [ipAllocations.deviceId],
|
||||
fields: [wgClients.id],
|
||||
references: [ipAllocations.clientId],
|
||||
}),
|
||||
}));
|
||||
|
||||
export type Device = typeof devices.$inferSelect;
|
||||
export type WgClient = typeof wgClients.$inferSelect;
|
||||
|
||||
export type Session = typeof sessions.$inferSelect;
|
||||
|
||||
|
@ -1,8 +1,8 @@
|
||||
import { ipAllocations, users, devices } from './schema';
|
||||
import { ipAllocations, users, wgClients } from './schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import assert from 'node:assert';
|
||||
import { drizzle } from 'drizzle-orm/libsql';
|
||||
import * as schema from './schema';
|
||||
import * as schema from '$lib/server/db/schema';
|
||||
|
||||
assert(process.env.DATABASE_URL, 'DATABASE_URL is not set');
|
||||
const db = drizzle(process.env.DATABASE_URL, { schema });
|
||||
@ -11,10 +11,10 @@ async function seed() {
|
||||
const user = await db.query.users.findFirst({ where: eq(users.username, 'CaZzzer') });
|
||||
assert(user, 'User not found');
|
||||
|
||||
const newDevices: typeof devices.$inferInsert[] = [
|
||||
const clients: typeof wgClients.$inferInsert[] = [
|
||||
{
|
||||
userId: user.id,
|
||||
name: 'Device1',
|
||||
name: 'Client1',
|
||||
publicKey: 'BJ5faPVJsDP4CCxNYilmKnwlQXOtXEOJjqIwb4U/CgM=',
|
||||
privateKey: 'KKqsHDu30WCSrVsyzMkOKbE3saQ+wlx0sBwGs61UGXk=',
|
||||
preSharedKey: '0LWopbrISXBNHUxr+WOhCSAg+0hD8j3TLmpyzHkBHCQ=',
|
||||
@ -22,10 +22,10 @@ async function seed() {
|
||||
// allowedIps: '10.18.11.101/32,fd00::1/112',
|
||||
},
|
||||
];
|
||||
const returned = await db.insert(devices).values(newDevices).returning({ insertedId: devices.id });
|
||||
const returned = await db.insert(wgClients).values(clients).returning({ insertedId: wgClients.id });
|
||||
|
||||
const ipAllocation: typeof ipAllocations.$inferInsert = {
|
||||
deviceId: returned[0].insertedId,
|
||||
clientId: returned[0].insertedId,
|
||||
};
|
||||
await db.insert(ipAllocations).values(ipAllocation);
|
||||
}
|
||||
|
@ -1,94 +0,0 @@
|
||||
import { devices, ipAllocations, type User } from '$lib/server/db/schema';
|
||||
import { err, ok, type Result } from '$lib/types';
|
||||
import { db } from '$lib/server/db';
|
||||
import { count, eq, isNull } from 'drizzle-orm';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getIpsFromIndex } from './utils';
|
||||
import wgProvider from '$lib/server/wg-provider';
|
||||
|
||||
export async function createDevice(params: {
|
||||
name: string;
|
||||
user: User;
|
||||
}): Promise<Result<number, [400 | 500, string]>> {
|
||||
// check if user exceeds the limit of devices
|
||||
const [{ deviceCount }] = await db
|
||||
.select({ deviceCount: count() })
|
||||
.from(devices)
|
||||
.where(eq(devices.userId, params.user.id));
|
||||
if (deviceCount >= parseInt(env.MAX_CLIENTS_PER_USER))
|
||||
return err([400, 'Maximum number of devices reached'] as [400, string]);
|
||||
|
||||
// 1. fetch params for new device from provider
|
||||
// 2.1 get an allocation for the device
|
||||
// 2.2. insert new device into db
|
||||
// 2.3. update the allocation with the device id
|
||||
// 3. create the client in provider
|
||||
return await db.transaction(async (tx) => {
|
||||
const [keysResult, availableAllocation, lastAllocation] = await Promise.all([
|
||||
// fetch params for new device from provider
|
||||
wgProvider.generateKeys(),
|
||||
// find first unallocated IP
|
||||
await tx.query.ipAllocations.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
where: isNull(ipAllocations.deviceId),
|
||||
}),
|
||||
// find last allocation to check if we have any IPs left
|
||||
await tx.query.ipAllocations.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
orderBy: (ipAllocations, { desc }) => desc(ipAllocations.id),
|
||||
}),
|
||||
]);
|
||||
|
||||
if (keysResult?._tag === 'err') return err([500, 'Failed to get keys']);
|
||||
const keys = keysResult.value;
|
||||
|
||||
// check for existing allocation or if we have any IPs left
|
||||
if (!availableAllocation && lastAllocation && lastAllocation.id >= parseInt(env.IP_MAX_INDEX)) {
|
||||
return err([500, 'No more IP addresses available']);
|
||||
}
|
||||
|
||||
// use existing allocation or create a new one
|
||||
const ipAllocationId =
|
||||
availableAllocation?.id ??
|
||||
(await tx.insert(ipAllocations).values({}).returning({ id: ipAllocations.id }))[0].id;
|
||||
|
||||
// transaction savepoint after creating a new IP allocation
|
||||
// TODO: not sure if this is needed
|
||||
return await tx.transaction(async (tx2) => {
|
||||
// create new device in db
|
||||
const [newDevice] = await tx2
|
||||
.insert(devices)
|
||||
.values({
|
||||
userId: params.user.id,
|
||||
name: params.name,
|
||||
publicKey: keys.publicKey,
|
||||
privateKey: keys.privateKey,
|
||||
preSharedKey: keys.preSharedKey,
|
||||
})
|
||||
.returning({ id: devices.id });
|
||||
|
||||
// update IP allocation with device ID
|
||||
await tx2
|
||||
.update(ipAllocations)
|
||||
.set({ deviceId: newDevice.id })
|
||||
.where(eq(ipAllocations.id, ipAllocationId));
|
||||
|
||||
// create client in provider
|
||||
const providerRes = await wgProvider.createClient({
|
||||
user: params.user,
|
||||
publicKey: keys.publicKey,
|
||||
preSharedKey: keys.preSharedKey,
|
||||
allowedIps: getIpsFromIndex(ipAllocationId).join(','),
|
||||
});
|
||||
if (providerRes._tag === 'err') {
|
||||
tx2.rollback();
|
||||
return err([500, 'Failed to create client in provider']);
|
||||
}
|
||||
return ok(newDevice.id);
|
||||
});
|
||||
});
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { db } from '$lib/server/db';
|
||||
import { devices } from '$lib/server/db/schema';
|
||||
import { err, ok, type Result } from '$lib/types';
|
||||
import wgProvider from '$lib/server/wg-provider';
|
||||
|
||||
export async function deleteDevice(
|
||||
userId: string,
|
||||
deviceId: number,
|
||||
): Promise<Result<null, [400 | 500, string]>> {
|
||||
const device = await db.query.devices.findFirst({
|
||||
columns: {
|
||||
publicKey: true,
|
||||
},
|
||||
where: and(eq(devices.userId, userId), eq(devices.id, deviceId)),
|
||||
});
|
||||
if (!device) return err([400, 'Device not found']);
|
||||
|
||||
const providerDeletionResult = await wgProvider.deleteClient(device.publicKey);
|
||||
if (providerDeletionResult._tag === 'err') {
|
||||
console.error('failed to delete provider client for device', deviceId, device.publicKey);
|
||||
return err([500, 'Error deleting client in provider']);
|
||||
}
|
||||
|
||||
await db.delete(devices).where(eq(devices.id, deviceId));
|
||||
return ok(null);
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
import { db } from '$lib/server/db';
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { devices } from '$lib/server/db/schema';
|
||||
import type { DeviceDetails } from '$lib/devices';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getIpsFromIndex } from '$lib/server/devices/index';
|
||||
import wgProvider from '$lib/server/wg-provider';
|
||||
|
||||
export async function findDevices(userId: string) {
|
||||
return db.query.devices.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
publicKey: true,
|
||||
privateKey: true,
|
||||
preSharedKey: true,
|
||||
},
|
||||
with: {
|
||||
ipAllocation: true,
|
||||
},
|
||||
where: eq(devices.userId, userId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function findDevice(userId: string, deviceId: number) {
|
||||
return db.query.devices.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
publicKey: true,
|
||||
privateKey: true,
|
||||
preSharedKey: true,
|
||||
},
|
||||
with: {
|
||||
ipAllocation: true,
|
||||
},
|
||||
where: and(eq(devices.userId, userId), eq(devices.id, deviceId)),
|
||||
});
|
||||
}
|
||||
|
||||
export function mapDeviceToDetails(
|
||||
device: Awaited<ReturnType<typeof findDevices>>[0],
|
||||
): DeviceDetails {
|
||||
const ips = getIpsFromIndex(device.ipAllocation.id);
|
||||
return {
|
||||
id: device.id,
|
||||
name: device.name,
|
||||
publicKey: device.publicKey,
|
||||
privateKey: device.privateKey,
|
||||
preSharedKey: device.preSharedKey,
|
||||
ips,
|
||||
vpnPublicKey: wgProvider.getServerPublicKey(),
|
||||
vpnEndpoint: env.VPN_ENDPOINT,
|
||||
vpnDns: env.VPN_DNS,
|
||||
};
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
export { findDevices, findDevice, mapDeviceToDetails } from './find';
|
||||
export { createDevice } from './create';
|
||||
export { getIpsFromIndex } from './utils';
|
@ -1,14 +0,0 @@
|
||||
import { Address4, Address6 } from 'ip-address';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
export function getIpsFromIndex(ipIndex: number) {
|
||||
ipIndex -= 1; // 1-indexed in the db
|
||||
const v4StartingAddr = new Address4(env.IPV4_STARTING_ADDR);
|
||||
const v6StartingAddr = new Address6(env.IPV6_STARTING_ADDR);
|
||||
const v4Allowed = Address4.fromBigInt(v4StartingAddr.bigInt() + BigInt(ipIndex));
|
||||
const v6Offset = BigInt(ipIndex) << (128n - BigInt(env.IPV6_CLIENT_PREFIX_SIZE));
|
||||
const v6Allowed = Address6.fromBigInt(v6StartingAddr.bigInt() + v6Offset);
|
||||
const v6AllowedShort = v6Allowed.parsedAddress.join(':');
|
||||
|
||||
return [v4Allowed.address + '/32', v6AllowedShort + '/' + env.IPV6_CLIENT_PREFIX_SIZE];
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
import { envToBool } from '$lib/utils';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { Authentik, decodeIdToken } from 'arctic';
|
||||
import { assertGuard } from 'typia';
|
||||
import type { IOAuthProvider } from '$lib/server/oauth';
|
||||
|
||||
const authentikProvider = new Authentik(
|
||||
env.AUTH_AUTHENTIK_DOMAIN,
|
||||
env.AUTH_AUTHENTIK_CLIENT_ID,
|
||||
env.AUTH_AUTHENTIK_CLIENT_SECRET,
|
||||
`${env.ORIGIN}/auth/authentik/callback`,
|
||||
);
|
||||
|
||||
export const authentik: IOAuthProvider = {
|
||||
requireInvite: envToBool(env.AUTH_AUTHENTIK_REQUIRE_INVITE, true),
|
||||
createAuthorizationURL: (state: string, codeVerifier: string) => {
|
||||
const scopes = ['openid', 'profile'];
|
||||
return authentikProvider.createAuthorizationURL(state, codeVerifier, scopes);
|
||||
},
|
||||
validateAuthorizationCode: async (code: string, codeVerifier: string) => {
|
||||
const tokens = await authentikProvider.validateAuthorizationCode(code, codeVerifier);
|
||||
const claims = decodeIdToken(tokens.idToken());
|
||||
assertGuard<{
|
||||
sub: string;
|
||||
name: string;
|
||||
preferred_username: string;
|
||||
}>(claims);
|
||||
return {
|
||||
sub: claims.sub,
|
||||
name: claims.name,
|
||||
username: claims.preferred_username,
|
||||
};
|
||||
},
|
||||
};
|
@ -1,33 +0,0 @@
|
||||
import { decodeIdToken, Google } from 'arctic';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { envToBool } from '$lib/utils';
|
||||
import { assertGuard } from 'typia';
|
||||
import type { IOAuthProvider } from '$lib/server/oauth';
|
||||
|
||||
const googleProvider = new Google(
|
||||
env.AUTH_GOOGLE_CLIENT_ID,
|
||||
env.AUTH_GOOGLE_CLIENT_SECRET,
|
||||
`${env.ORIGIN}/auth/google/callback`,
|
||||
);
|
||||
|
||||
export const google: IOAuthProvider = {
|
||||
requireInvite: envToBool(env.AUTH_GOOGLE_REQUIRE_INVITE, true),
|
||||
createAuthorizationURL: (state: string, codeVerifier: string) => {
|
||||
const scopes = ['openid', 'profile', 'email'];
|
||||
return googleProvider.createAuthorizationURL(state, codeVerifier, scopes);
|
||||
},
|
||||
validateAuthorizationCode: async (code: string, codeVerifier: string) => {
|
||||
const tokens = await googleProvider.validateAuthorizationCode(code, codeVerifier);
|
||||
const claims = decodeIdToken(tokens.idToken());
|
||||
assertGuard<{
|
||||
sub: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}>(claims);
|
||||
return {
|
||||
sub: claims.sub,
|
||||
name: claims.name,
|
||||
username: claims.email,
|
||||
};
|
||||
},
|
||||
};
|
@ -1,2 +0,0 @@
|
||||
export { authentik } from './authentik';
|
||||
export { google } from './google';
|
@ -1,19 +1,9 @@
|
||||
import type { AuthProvider } from '$lib/auth';
|
||||
import { authentik, google } from '$lib/server/oauth-providers';
|
||||
import { Authentik } from 'arctic';
|
||||
import * as env from '$env/static/private';
|
||||
|
||||
export interface IOAuthClaims {
|
||||
sub: string;
|
||||
name: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface IOAuthProvider {
|
||||
readonly requireInvite: boolean;
|
||||
createAuthorizationURL(state: string, codeVerifier: string): URL;
|
||||
validateAuthorizationCode(code: string, codeVerifier: string): Promise<IOAuthClaims>;
|
||||
}
|
||||
|
||||
export const oauthProviders: Record<AuthProvider, IOAuthProvider> = {
|
||||
authentik,
|
||||
google,
|
||||
};
|
||||
export const authentik = new Authentik(
|
||||
env.AUTH_DOMAIN,
|
||||
env.AUTH_CLIENT_ID,
|
||||
env.AUTH_CLIENT_SECRET,
|
||||
env.AUTH_REDIRECT_URI
|
||||
);
|
||||
|
49
src/lib/server/opnsense/index.ts
Normal file
49
src/lib/server/opnsense/index.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import { env } from '$env/dynamic/private';
|
||||
import assert from 'node:assert';
|
||||
import { encodeBasicCredentials } from 'arctic/dist/request';
|
||||
import { dev } from '$app/environment';
|
||||
import type { OpnsenseWgServers } from '$lib/opnsense/wg';
|
||||
|
||||
assert(env.OPNSENSE_API_URL, 'OPNSENSE_API_URL is not set');
|
||||
assert(env.OPNSENSE_API_KEY, 'OPNSENSE_API_KEY is not set');
|
||||
assert(env.OPNSENSE_API_SECRET, 'OPNSENSE_API_SECRET is not set');
|
||||
assert(env.OPNSENSE_WG_IFNAME, 'OPNSENSE_WG_IFNAME is not set');
|
||||
|
||||
export const opnsenseUrl = env.OPNSENSE_API_URL;
|
||||
export const opnsenseAuth =
|
||||
'Basic ' + encodeBasicCredentials(env.OPNSENSE_API_KEY, env.OPNSENSE_API_SECRET);
|
||||
export const opnsenseIfname = env.OPNSENSE_WG_IFNAME;
|
||||
|
||||
// unset secret for security
|
||||
if (!dev) env.OPNSENSE_API_SECRET = '';
|
||||
|
||||
// this might be pretty bad if the server is down and in a bunch of other cases
|
||||
// TODO: write a retry loop later
|
||||
const resServers = await fetch(`${opnsenseUrl}/api/wireguard/client/list_servers`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
assert(resServers.ok, 'Failed to fetch OPNsense WireGuard servers');
|
||||
const servers = (await resServers.json()) as OpnsenseWgServers;
|
||||
assert.equal(servers.status, 'ok', 'Failed to fetch OPNsense WireGuard servers');
|
||||
export const serverUuid = servers.rows.find((server) => server.name === opnsenseIfname)?.uuid;
|
||||
assert(serverUuid, 'Failed to find server UUID for OPNsense WireGuard server');
|
||||
console.log('OPNsense WireGuard server UUID:', serverUuid);
|
||||
|
||||
const resServerInfo = await fetch(
|
||||
`${opnsenseUrl}/api/wireguard/client/get_server_info/${serverUuid}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
},
|
||||
);
|
||||
assert(resServerInfo.ok, 'Failed to fetch OPNsense WireGuard server info');
|
||||
const serverInfo = await resServerInfo.json();
|
||||
assert.equal(serverInfo.status, 'ok', 'Failed to fetch OPNsense WireGuard server info');
|
||||
export const serverPublicKey = serverInfo['pubkey'];
|
@ -1,38 +0,0 @@
|
||||
import type { Result } from '$lib/types';
|
||||
import type { User } from '$lib/server/db/schema';
|
||||
|
||||
export interface IWgProvider {
|
||||
init(): Promise<Result<null, Error>>;
|
||||
|
||||
getServerPublicKey(): string;
|
||||
|
||||
generateKeys(): Promise<Result<WgKeys, Error>>;
|
||||
|
||||
createClient(params: CreateClientParams): Promise<Result<null, Error>>;
|
||||
|
||||
findConnections(user: User): Promise<Result<ClientConnection[], Error>>;
|
||||
|
||||
deleteClient(publicKey: string): Promise<Result<null, Error>>;
|
||||
}
|
||||
|
||||
export type WgKeys = {
|
||||
publicKey: string;
|
||||
privateKey: string;
|
||||
preSharedKey: string;
|
||||
};
|
||||
|
||||
export type CreateClientParams = {
|
||||
user: User;
|
||||
publicKey: string;
|
||||
preSharedKey: string;
|
||||
allowedIps: string;
|
||||
}
|
||||
|
||||
export type ClientConnection = {
|
||||
publicKey: string;
|
||||
endpoint: string;
|
||||
allowedIps: string;
|
||||
transferRx: number;
|
||||
transferTx: number;
|
||||
latestHandshake: number;
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
import { WgProviderOpnsense } from '$lib/server/wg-providers/opnsense';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import type { IWgProvider } from '$lib/server/types';
|
||||
|
||||
const wgProvider: IWgProvider = new WgProviderOpnsense({
|
||||
opnsenseUrl: env.OPNSENSE_API_URL,
|
||||
opnsenseApiKey: env.OPNSENSE_API_KEY,
|
||||
opnsenseApiSecret: env.OPNSENSE_API_SECRET,
|
||||
opnsenseWgIfname: env.OPNSENSE_WG_IFNAME,
|
||||
});
|
||||
|
||||
export default wgProvider;
|
@ -1,244 +0,0 @@
|
||||
import type { ClientConnection, CreateClientParams, IWgProvider, WgKeys } from '$lib/server/types';
|
||||
import { encodeBasicCredentials } from 'arctic/dist/request';
|
||||
import { is } from 'typia';
|
||||
import type { OpnsenseWgPeers, OpnsenseWgServers } from '$lib/server/wg-providers/opnsense/types';
|
||||
import { err, ok, type Result } from '$lib/types';
|
||||
import assert from 'node:assert';
|
||||
import type { User } from '$lib/server/db/schema';
|
||||
|
||||
export class WgProviderOpnsense implements IWgProvider {
|
||||
private opnsenseUrl: string;
|
||||
private opnsenseAuth: string;
|
||||
private opnsenseIfname: string;
|
||||
private opnsenseWgServerUuid: string | undefined;
|
||||
private opnsenseWgServerPublicKey: string | undefined;
|
||||
|
||||
public constructor(params: OpnsenseParams) {
|
||||
this.opnsenseUrl = params.opnsenseUrl;
|
||||
this.opnsenseAuth =
|
||||
'Basic ' + encodeBasicCredentials(params.opnsenseApiKey, params.opnsenseApiSecret);
|
||||
this.opnsenseIfname = params.opnsenseWgIfname;
|
||||
}
|
||||
|
||||
public async init(): Promise<Result<null, Error>> {
|
||||
const resServers = await fetch(`${this.opnsenseUrl}/api/wireguard/client/list_servers`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
const servers = await resServers.json();
|
||||
if (!is<OpnsenseWgServers>(servers)) {
|
||||
console.error('Unexpected response for OPNsense WireGuard servers', servers);
|
||||
return err(new Error('Failed to fetch OPNsense WireGuard servers'));
|
||||
}
|
||||
|
||||
const uuid = servers.rows.find((server) => server.name === this.opnsenseIfname)?.uuid;
|
||||
if (!uuid) {
|
||||
console.error('OPNsense WireGuard servers', servers);
|
||||
return err(new Error('Failed to find server UUID for OPNsense WireGuard server'));
|
||||
}
|
||||
|
||||
const resServerInfo = await fetch(
|
||||
`${this.opnsenseUrl}/api/wireguard/client/get_server_info/${uuid}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
},
|
||||
);
|
||||
const serverInfo = await resServerInfo.json();
|
||||
const serverPublicKey = serverInfo['pubkey'];
|
||||
if (serverInfo['status'] !== 'ok' || typeof serverPublicKey !== 'string') {
|
||||
console.error('Failed to fetch OPNsense WireGuard server info', serverInfo);
|
||||
return err(new Error('Failed to fetch OPNsense WireGuard server info'));
|
||||
}
|
||||
|
||||
console.debug('OPNsense WireGuard server UUID:', uuid);
|
||||
console.debug('OPNsense WireGuard server public key:', serverPublicKey);
|
||||
this.opnsenseWgServerUuid = uuid;
|
||||
this.opnsenseWgServerPublicKey = serverPublicKey;
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
getServerPublicKey(): string {
|
||||
assert(
|
||||
this.opnsenseWgServerPublicKey,
|
||||
'OPNsense server public key not set, init() must be called first',
|
||||
);
|
||||
return this.opnsenseWgServerPublicKey;
|
||||
}
|
||||
|
||||
public async generateKeys(): Promise<Result<WgKeys, Error>> {
|
||||
const options: RequestInit = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
};
|
||||
const resKeyPair = await fetch(`${this.opnsenseUrl}/api/wireguard/server/key_pair`, options);
|
||||
const resPsk = await fetch(`${this.opnsenseUrl}/api/wireguard/client/psk`, options);
|
||||
const keyPair = await resKeyPair.json();
|
||||
const psk = await resPsk.json();
|
||||
|
||||
if (!is<{ pubkey: string; privkey: string }>(keyPair)) {
|
||||
console.error('Unexpected response for OPNsense key pair', keyPair);
|
||||
return err(new Error('Failed to fetch OPNsense key pair'));
|
||||
}
|
||||
if (!is<{ psk: string }>(psk)) {
|
||||
console.error('Unexpected response for OPNsense PSK', psk);
|
||||
return err(new Error('Failed to fetch OPNsense PSK'));
|
||||
}
|
||||
|
||||
return ok({
|
||||
publicKey: keyPair.pubkey,
|
||||
privateKey: keyPair.privkey,
|
||||
preSharedKey: psk.psk,
|
||||
});
|
||||
}
|
||||
|
||||
async createClient(params: CreateClientParams): Promise<Result<null, Error>> {
|
||||
assert(this.opnsenseWgServerUuid, 'OPNsense server UUID not set, init() must be called first');
|
||||
|
||||
const createClientRes = await fetch(
|
||||
`${this.opnsenseUrl}/api/wireguard/client/addClientBuilder`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
configbuilder: {
|
||||
enabled: '1',
|
||||
name: `vpgen-${opnsenseSanitezedUsername(params.user.username)}`,
|
||||
pubkey: params.publicKey,
|
||||
psk: params.preSharedKey,
|
||||
tunneladdress: params.allowedIps,
|
||||
server: this.opnsenseWgServerUuid,
|
||||
endpoint: '',
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
const createClientResJson = await createClientRes.json();
|
||||
if (createClientResJson['result'] !== 'saved') {
|
||||
console.error('Error creating client in OPNsense', createClientResJson);
|
||||
return err(new Error('Failed to create client in OPNsense'));
|
||||
}
|
||||
|
||||
const reconfigureRes = await fetch(`${this.opnsenseUrl}/api/wireguard/service/reconfigure`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (reconfigureRes.status !== 200) {
|
||||
console.error('Error reconfiguring OPNsense', reconfigureRes);
|
||||
return err(new Error('Failed to reconfigure OPNsense'));
|
||||
}
|
||||
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
async findConnections(user: User): Promise<Result<ClientConnection[], Error>> {
|
||||
const res = await fetch(`${this.opnsenseUrl}/api/wireguard/service/show`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
current: 1,
|
||||
// "rowCount": 7,
|
||||
sort: {},
|
||||
// TODO: use a more unique search phrase
|
||||
// unfortunately 64 character limit,
|
||||
// but it should be fine if users can't change their own username
|
||||
searchPhrase: `vpgen-${opnsenseSanitezedUsername(user.username)}`,
|
||||
type: ['peer'],
|
||||
}),
|
||||
});
|
||||
|
||||
const peers = await res.json();
|
||||
if (!is<OpnsenseWgPeers>(peers)) {
|
||||
console.error('Unexpected response for OPNsense WireGuard peers', peers);
|
||||
return err(new Error('Failed to fetch OPNsense WireGuard peers'));
|
||||
}
|
||||
|
||||
return ok(
|
||||
peers.rows.map((peer) => {
|
||||
return {
|
||||
publicKey: peer['public-key'],
|
||||
endpoint: peer['endpoint'],
|
||||
allowedIps: peer['allowed-ips'],
|
||||
transferRx: peer['transfer-rx'],
|
||||
transferTx: peer['transfer-tx'],
|
||||
latestHandshake: peer['latest-handshake'] * 1000,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async deleteClient(publicKey: string): Promise<Result<null, Error>> {
|
||||
const client = await this.findOpnsenseClient(publicKey);
|
||||
const clientUuid = client?.uuid;
|
||||
if (typeof clientUuid !== 'string') {
|
||||
console.error('Failed to get OPNsense client UUID for deletion', client);
|
||||
return err(new Error('Failed to get OPNsense client UUID for deletion'));
|
||||
}
|
||||
|
||||
const res = await fetch(`${this.opnsenseUrl}/api/wireguard/client/delClient/${clientUuid}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
const resJson = await res.json();
|
||||
if (resJson['result'] !== 'deleted') {
|
||||
console.error('Failed to delete OPNsense client', resJson);
|
||||
return err(new Error('Failed to delete OPNsense client'));
|
||||
}
|
||||
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
private async findOpnsenseClient(publicKey: string) {
|
||||
const res = await fetch(`${this.opnsenseUrl}/api/wireguard/client/searchClient`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: this.opnsenseAuth,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
current: 1,
|
||||
sort: {},
|
||||
searchPhrase: publicKey,
|
||||
type: ['peer'],
|
||||
}),
|
||||
});
|
||||
return (await res.json())?.rows?.[0] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
function opnsenseSanitezedUsername(username: string) {
|
||||
return username.slice(0, 63).replace(/[^a-zA-Z0-9_-]/g, '_');
|
||||
}
|
||||
|
||||
export type OpnsenseParams = {
|
||||
opnsenseUrl: string;
|
||||
opnsenseApiKey: string;
|
||||
opnsenseApiSecret: string;
|
||||
opnsenseWgIfname: string;
|
||||
};
|
11
src/lib/types/clients.ts
Normal file
11
src/lib/types/clients.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export type ClientDetails = {
|
||||
id: number;
|
||||
name: string;
|
||||
publicKey: string;
|
||||
privateKey: string | null;
|
||||
preSharedKey: string | null;
|
||||
ips: string[];
|
||||
vpnPublicKey: string;
|
||||
vpnEndpoint: string;
|
||||
vpnDns: string;
|
||||
};
|
@ -1,2 +1,27 @@
|
||||
export type { Result } from './result';
|
||||
export { ok, err } from './result';
|
||||
class Ok<T> {
|
||||
readonly _tag = 'ok';
|
||||
value: T;
|
||||
|
||||
constructor(value: T) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
class Err<E> {
|
||||
readonly _tag = 'err';
|
||||
error: E;
|
||||
|
||||
constructor(error: E) {
|
||||
this.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
export type Result<T, E> = Ok<T> | Err<E>;
|
||||
|
||||
export function err<E>(e: E): Err<E> {
|
||||
return new Err(e);
|
||||
}
|
||||
|
||||
export function ok<T>(t: T): Ok<T> {
|
||||
return new Ok(t);
|
||||
}
|
||||
|
@ -1,27 +0,0 @@
|
||||
class Ok<T> {
|
||||
readonly _tag = 'ok';
|
||||
value: T;
|
||||
|
||||
constructor(value: T) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
class Err<E> {
|
||||
readonly _tag = 'err';
|
||||
error: E;
|
||||
|
||||
constructor(error: E) {
|
||||
this.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
export type Result<T, E> = Ok<T> | Err<E>;
|
||||
|
||||
export function err<E>(e: E): Err<E> {
|
||||
return new Err(e);
|
||||
}
|
||||
|
||||
export function ok<T>(t: T): Ok<T> {
|
||||
return new Ok(t);
|
||||
}
|
@ -1,14 +1,62 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { cubicOut } from "svelte/easing";
|
||||
import type { TransitionConfig } from "svelte/transition";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function envToBool(value: string | undefined, defaultValue = false): boolean {
|
||||
if (typeof value === "undefined") {
|
||||
return defaultValue;
|
||||
}
|
||||
type FlyAndScaleParams = {
|
||||
y?: number;
|
||||
x?: number;
|
||||
start?: number;
|
||||
duration?: number;
|
||||
};
|
||||
|
||||
return ['true', '1', 'yes'].includes(value.toLowerCase());
|
||||
}
|
||||
export const flyAndScale = (
|
||||
node: Element,
|
||||
params: FlyAndScaleParams = { y: -8, x: 0, start: 0.95, duration: 150 }
|
||||
): TransitionConfig => {
|
||||
const style = getComputedStyle(node);
|
||||
const transform = style.transform === "none" ? "" : style.transform;
|
||||
|
||||
const scaleConversion = (
|
||||
valueA: number,
|
||||
scaleA: [number, number],
|
||||
scaleB: [number, number]
|
||||
) => {
|
||||
const [minA, maxA] = scaleA;
|
||||
const [minB, maxB] = scaleB;
|
||||
|
||||
const percentage = (valueA - minA) / (maxA - minA);
|
||||
const valueB = percentage * (maxB - minB) + minB;
|
||||
|
||||
return valueB;
|
||||
};
|
||||
|
||||
const styleToString = (
|
||||
style: Record<string, number | string | undefined>
|
||||
): string => {
|
||||
return Object.keys(style).reduce((str, key) => {
|
||||
if (style[key] === undefined) return str;
|
||||
return str + `${key}:${style[key]};`;
|
||||
}, "");
|
||||
};
|
||||
|
||||
return {
|
||||
duration: params.duration ?? 200,
|
||||
delay: 0,
|
||||
css: (t) => {
|
||||
const y = scaleConversion(t, [0, 1], [params.y ?? 5, 0]);
|
||||
const x = scaleConversion(t, [0, 1], [params.x ?? 0, 0]);
|
||||
const scale = scaleConversion(t, [0, 1], [params.start ?? 0.95, 1]);
|
||||
|
||||
return styleToString({
|
||||
transform: `${transform} translate3d(${x}px, ${y}px, 0) scale(${scale})`,
|
||||
opacity: t
|
||||
});
|
||||
},
|
||||
easing: cubicOut
|
||||
};
|
||||
};
|
@ -1,44 +1,35 @@
|
||||
<script lang="ts">
|
||||
import '../app.css';
|
||||
import { page } from '$app/stores';
|
||||
import { cn } from '$lib/utils';
|
||||
import { page } from '$app/state';
|
||||
|
||||
const { data, children } = $props();
|
||||
const { user } = data;
|
||||
|
||||
function getNavClass(path: RegExp) {
|
||||
return cn(
|
||||
'hover:text-foreground/80 transition-colors',
|
||||
path.test(page.url.pathname) ? 'text-foreground' : 'text-foreground/60',
|
||||
);
|
||||
return cn('hover:text-foreground/80 transition-colors',
|
||||
path.test($page.url.pathname) ? 'text-foreground' : 'text-foreground/60');
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="flex w-full flex-wrap justify-between gap-x-6 gap-y-4 xl:max-w-screen-xl">
|
||||
<a href="/" class="contents">
|
||||
<span class="font-bold sm:inline-block">VPGen</span>
|
||||
</a>
|
||||
<nav class="max-w-full">
|
||||
<ul class="flex items-center gap-6 overflow-x-auto text-sm">
|
||||
<li><a href="/" class={getNavClass(/^\/$/)}>Home</a></li>
|
||||
{#if user}
|
||||
<li><a href="/user" class={getNavClass(/^\/user$/)}>Profile</a></li>
|
||||
<li><a href="/connections" class={getNavClass(/^\/connections$/)}>Connections</a></li>
|
||||
<li><a href="/devices" class={getNavClass(/^\/devices(\/\d+)?$/)}>Devices</a></li>
|
||||
{/if}
|
||||
</ul>
|
||||
<header class="p-4 sm:flex">
|
||||
<span class=" mr-6 font-bold sm:inline-block">VPGen</span>
|
||||
<nav class="flex items-center gap-6 text-sm">
|
||||
<a href="/" class={getNavClass(/^\/$/)}>Home</a>
|
||||
{#if user}
|
||||
<a href="/user" class={getNavClass(/^\/user$/)}>Profile</a>
|
||||
<a href="/connections" class={getNavClass(/^\/connections$/)}>Connections</a>
|
||||
<a href="/clients" class={getNavClass(/^\/clients(\/\d+)?$/)}>Clients</a>
|
||||
{/if}
|
||||
</nav>
|
||||
</header>
|
||||
<main class="flex min-w-full max-w-full flex-grow flex-col gap-4 xl:min-w-[78rem]">
|
||||
<main class="flex flex-col flex-grow p-4">
|
||||
{@render children()}
|
||||
</main>
|
||||
|
||||
<!--https://github.com/sveltejs/kit/discussions/7585#discussioncomment-9997936-->
|
||||
<!--Some shenanings needed to be done to get the footer position to stick correctly,
|
||||
didn't work with display: contents-->
|
||||
<footer class="inset-x-0 bottom-0 w-full text-center">
|
||||
<p>© 2025</p>
|
||||
<footer class="p-4 relative text-center inset-x-0 bottom-0">
|
||||
<p>© 2024</p>
|
||||
</footer>
|
||||
|
||||
<style>
|
||||
</style>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user