Compare commits
1 Commits
99f4016eb3
...
feature/lo
| Author | SHA1 | Date | |
|---|---|---|---|
|
b38ab19c3e
|
@@ -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
bunfig.toml
Normal file
1
bunfig.toml
Normal file
@@ -0,0 +1 @@
|
|||||||
|
logLevel = "info"
|
||||||
@@ -1,11 +1,62 @@
|
|||||||
import { devices, ipAllocations, type User } from '$lib/server/db/schema';
|
import type { User } from '$lib/server/db/schema';
|
||||||
import { err, ok, type Result } from '$lib/types';
|
import { ipAllocations, devices } from '$lib/server/db/schema';
|
||||||
import { db } from '$lib/server/db';
|
import { db } from '$lib/server/db';
|
||||||
import { count, eq, isNull } from 'drizzle-orm';
|
import { opnsenseAuth, opnsenseUrl, serverPublicKey, serverUuid } from '$lib/server/opnsense';
|
||||||
|
import { Address4, Address6 } from 'ip-address';
|
||||||
import { env } from '$env/dynamic/private';
|
import { env } from '$env/dynamic/private';
|
||||||
import { opnsenseAuth, opnsenseUrl, serverUuid } from '$lib/server/opnsense';
|
import { and, count, eq, isNull } from 'drizzle-orm';
|
||||||
|
import { err, ok, type Result } from '$lib/types';
|
||||||
|
import type { DeviceDetails } from '$lib/devices';
|
||||||
import { opnsenseSanitezedUsername } from '$lib/opnsense';
|
import { opnsenseSanitezedUsername } from '$lib/opnsense';
|
||||||
import { getIpsFromIndex } from './utils';
|
|
||||||
|
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: serverPublicKey,
|
||||||
|
vpnEndpoint: env.VPN_ENDPOINT,
|
||||||
|
vpnDns: env.VPN_DNS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function createDevice(params: {
|
export async function createDevice(params: {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -118,6 +169,18 @@ async function getKeys() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
|
||||||
async function opnsenseCreateClient(params: {
|
async function opnsenseCreateClient(params: {
|
||||||
username: string;
|
username: string;
|
||||||
pubkey: string;
|
pubkey: string;
|
||||||
@@ -1,73 +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 { opnsenseAuth, opnsenseUrl } from '$lib/server/opnsense';
|
|
||||||
|
|
||||||
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 opnsenseClientUuid = (await opnsenseFindClient(device.publicKey))?.['uuid'];
|
|
||||||
if (typeof opnsenseClientUuid !== 'string') {
|
|
||||||
console.error(
|
|
||||||
'failed to get OPNsense client for deletion for device',
|
|
||||||
deviceId,
|
|
||||||
device.publicKey,
|
|
||||||
);
|
|
||||||
return err([500, 'Error getting client from OPNsense']);
|
|
||||||
}
|
|
||||||
|
|
||||||
const opnsenseDeletionResult = await opnsenseDeleteClient(opnsenseClientUuid);
|
|
||||||
if (opnsenseDeletionResult?.['result'] !== 'deleted') {
|
|
||||||
console.error(
|
|
||||||
'failed to delete OPNsense client for device',
|
|
||||||
deviceId,
|
|
||||||
device.publicKey,
|
|
||||||
'\n',
|
|
||||||
'OPNsense client uuid:',
|
|
||||||
opnsenseClientUuid,
|
|
||||||
);
|
|
||||||
return err([500, 'Error deleting client in OPNsense']);
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.delete(devices).where(eq(devices.id, deviceId));
|
|
||||||
return ok(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function opnsenseFindClient(pubkey: string) {
|
|
||||||
const res = await fetch(`${opnsenseUrl}/api/wireguard/client/searchClient`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Authorization: opnsenseAuth,
|
|
||||||
Accept: 'application/json',
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
current: 1,
|
|
||||||
// "rowCount": 7,
|
|
||||||
sort: {},
|
|
||||||
searchPhrase: pubkey,
|
|
||||||
type: ['peer'],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
return (await res.json())?.rows?.[0] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function opnsenseDeleteClient(clientUuid: string) {
|
|
||||||
const res = await fetch(`${opnsenseUrl}/api/wireguard/client/delClient/${clientUuid}`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Authorization: opnsenseAuth,
|
|
||||||
Accept: 'application/json',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return res.json();
|
|
||||||
}
|
|
||||||
@@ -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 { serverPublicKey } from '$lib/server/opnsense';
|
|
||||||
import { env } from '$env/dynamic/private';
|
|
||||||
import { getIpsFromIndex } from '$lib/server/devices/index';
|
|
||||||
|
|
||||||
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: serverPublicKey,
|
|
||||||
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];
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,7 @@ export async function fetchOpnsenseServer() {
|
|||||||
const uuid = servers.rows.find((server) => server.name === opnsenseIfname)?.uuid;
|
const uuid = servers.rows.find((server) => server.name === opnsenseIfname)?.uuid;
|
||||||
assert(uuid, 'Failed to find server UUID for OPNsense WireGuard server');
|
assert(uuid, 'Failed to find server UUID for OPNsense WireGuard server');
|
||||||
serverUuid = uuid;
|
serverUuid = uuid;
|
||||||
console.log('OPNsense WireGuard server UUID:', serverUuid);
|
console.info('OPNsense WireGuard server UUID:', serverUuid);
|
||||||
|
|
||||||
const resServerInfo = await fetch(
|
const resServerInfo = await fetch(
|
||||||
`${opnsenseUrl}/api/wireguard/client/get_server_info/${serverUuid}`,
|
`${opnsenseUrl}/api/wireguard/client/get_server_info/${serverUuid}`,
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ export async function GET(event: RequestEvent): Promise<Response> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
const claims = decodeIdToken(tokens.idToken()) as { sub: string, preferred_username: string, name: string };
|
const claims = decodeIdToken(tokens.idToken()) as { sub: string, preferred_username: string, name: string };
|
||||||
console.log("claims", claims);
|
console.info("claims", claims);
|
||||||
const userId: string = claims.sub;
|
const userId: string = claims.sub;
|
||||||
const username: string = claims.preferred_username;
|
const username: string = claims.preferred_username;
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import type { Actions } from './$types';
|
import type { Actions } from './$types';
|
||||||
import { createDevice } from '$lib/server/devices';
|
import { createDevice } from '$lib/server/devices';
|
||||||
import { error, fail, redirect } from '@sveltejs/kit';
|
import { error, redirect } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const actions = {
|
export const actions = {
|
||||||
create: async (event) => {
|
create: async (event) => {
|
||||||
if (!event.locals.user) return error(401, 'Unauthorized');
|
if (!event.locals.user) return error(401, 'Unauthorized');
|
||||||
const formData = await event.request.formData();
|
const formData = await event.request.formData();
|
||||||
const name = formData.get('name');
|
const name = formData.get('name');
|
||||||
if (typeof name !== 'string' || name.trim() === '') return fail(400, { name, invalid: true });
|
if (typeof name !== 'string' || name.trim() === '') return error(400, 'Invalid name');
|
||||||
const res = await createDevice({
|
const res = await createDevice({
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
user: event.locals.user,
|
user: event.locals.user,
|
||||||
|
|||||||
@@ -8,7 +8,6 @@
|
|||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
import { Label } from '$lib/components/ui/label';
|
import { Label } from '$lib/components/ui/label';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import DeleteDevice from './delete-device.svelte';
|
|
||||||
|
|
||||||
const { data }: { data: PageData } = $props();
|
const { data }: { data: PageData } = $props();
|
||||||
|
|
||||||
@@ -57,9 +56,6 @@
|
|||||||
<Badge class="select-auto bg-background" variant="secondary">{ip}</Badge>
|
<Badge class="select-auto bg-background" variant="secondary">{ip}</Badge>
|
||||||
{/each}
|
{/each}
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell class="py-0">
|
|
||||||
<DeleteDevice device={device} />
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
</Table.Row>
|
||||||
{/each}
|
{/each}
|
||||||
</Table.Body>
|
</Table.Body>
|
||||||
@@ -90,11 +86,11 @@
|
|||||||
class="max-w-[20ch]"
|
class="max-w-[20ch]"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Dialog.Footer class="gap-y-2">
|
<Dialog.Footer>
|
||||||
{#if submitted}
|
<Button type="submit" disabled={submitted}>
|
||||||
<LucideLoaderCircle class="size-4 animate-spin place-self-center" />
|
{#if submitted}
|
||||||
{/if}
|
<LucideLoaderCircle class="size-4 mr-2 animate-spin" />
|
||||||
<Button type="submit" disabled={submitted} class="">
|
{/if}
|
||||||
Add
|
Add
|
||||||
</Button>
|
</Button>
|
||||||
</Dialog.Footer>
|
</Dialog.Footer>
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
import { error, redirect } from '@sveltejs/kit';
|
|
||||||
import { deleteDevice } from '$lib/server/devices/delete';
|
|
||||||
import type { Actions } from './$types';
|
|
||||||
|
|
||||||
export const actions = {
|
|
||||||
delete: async (event) => {
|
|
||||||
if (!event.locals.user) return error(401, 'Unauthorized');
|
|
||||||
|
|
||||||
const deviceId = Number.parseInt(event.params.id);
|
|
||||||
if (Number.isNaN(deviceId)) return error(400, 'Invalid device id');
|
|
||||||
|
|
||||||
const res = await deleteDevice(event.locals.user.id, deviceId);
|
|
||||||
switch (res._tag) {
|
|
||||||
case 'ok': {
|
|
||||||
return redirect(303, '/devices');
|
|
||||||
}
|
|
||||||
case 'err': {
|
|
||||||
const [status, message] = res.error;
|
|
||||||
return error(status, message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
} satisfies Actions;
|
|
||||||
@@ -3,7 +3,6 @@
|
|||||||
import QRCode from 'qrcode-svg';
|
import QRCode from 'qrcode-svg';
|
||||||
import { CodeSnippet } from '$lib/components/app/code-snippet';
|
import { CodeSnippet } from '$lib/components/app/code-snippet';
|
||||||
import { WireguardGuide } from '$lib/components/app/wireguard-guide';
|
import { WireguardGuide } from '$lib/components/app/wireguard-guide';
|
||||||
import DeleteDevice from '../delete-device.svelte';
|
|
||||||
|
|
||||||
const { data }: { data: PageData } = $props();
|
const { data }: { data: PageData } = $props();
|
||||||
|
|
||||||
@@ -26,10 +25,7 @@
|
|||||||
<title>{data.device.name}</title>
|
<title>{data.device.name}</title>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<div class="flex justify-between">
|
<h1 class="w-fit rounded-lg bg-accent p-2 text-lg">{data.device.name}</h1>
|
||||||
<h1 class="w-fit rounded-lg bg-accent p-2 text-lg">{data.device.name}</h1>
|
|
||||||
<DeleteDevice device={data.device} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<section id="device-configuration" class="flex flex-wrap items-center justify-center gap-4">
|
<section id="device-configuration" class="flex flex-wrap items-center justify-center gap-4">
|
||||||
<CodeSnippet data={data.config} filename={deviceWgCleanedName} copy download />
|
<CodeSnippet data={data.config} filename={deviceWgCleanedName} copy download />
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
<script>
|
|
||||||
import { Button, buttonVariants } from '$lib/components/ui/button';
|
|
||||||
import * as Dialog from '$lib/components/ui/dialog';
|
|
||||||
import { LucideLoaderCircle, LucideTrash } from 'lucide-svelte';
|
|
||||||
|
|
||||||
const { device } = $props();
|
|
||||||
let submitted = $state(false);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<Dialog.Root>
|
|
||||||
<Dialog.Trigger class={buttonVariants({ variant: 'destructive', size: 'sm', class: 'bg-accent hover:bg-destructive' })}>
|
|
||||||
<LucideTrash />
|
|
||||||
</Dialog.Trigger>
|
|
||||||
<Dialog.Content>
|
|
||||||
<form class="contents" method="post" action="/devices/{device.id}?/delete"
|
|
||||||
onsubmit={() => submitted = true}
|
|
||||||
>
|
|
||||||
<Dialog.Header>
|
|
||||||
Are you sure you want to permanently delete "{device.name}"?
|
|
||||||
</Dialog.Header>
|
|
||||||
You will no longer be able to connect from this device.
|
|
||||||
<Dialog.Footer class="gap-y-2">
|
|
||||||
{#if submitted}
|
|
||||||
<LucideLoaderCircle class="size-4 animate-spin place-self-center" />
|
|
||||||
{/if}
|
|
||||||
<Button type="submit" variant="destructive" disabled={submitted}>
|
|
||||||
Delete
|
|
||||||
</Button>
|
|
||||||
<Dialog.Close asChild let:builder>
|
|
||||||
<button class={buttonVariants()} disabled={submitted} use:builder.action {...builder}>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
</Dialog.Close>
|
|
||||||
</Dialog.Footer>
|
|
||||||
</form>
|
|
||||||
</Dialog.Content>
|
|
||||||
</Dialog.Root>
|
|
||||||
Reference in New Issue
Block a user