connections page overhaul

This commit is contained in:
Yuri Tatishchev 2024-12-19 22:10:08 -08:00
parent 686383e4d1
commit e03bf11fa5
Signed by: CaZzzer
GPG Key ID: E0EBF441EA424369
8 changed files with 123 additions and 74 deletions

View File

@ -3,6 +3,8 @@ AUTH_DOMAIN=auth.lab.cazzzer.com
AUTH_CLIENT_ID= AUTH_CLIENT_ID=
AUTH_CLIENT_SECRET= AUTH_CLIENT_SECRET=
AUTH_REDIRECT_URI=http://localhost:5173/auth/authentik/callback AUTH_REDIRECT_URI=http://localhost:5173/auth/authentik/callback
OPNSENSE_API_URL=https://opnsense.home OPNSENSE_API_URL=https://opnsense.home
OPNSENSE_API_KEY= OPNSENSE_API_KEY=
OPNSENSE_API_SECRET= OPNSENSE_API_SECRET=
OPNSENSE_WG_IFNAME=wg2

View File

@ -0,0 +1,18 @@
<script lang="ts">
import { type Variant, badgeVariants } from "./index.js";
import { cn } from "$lib/utils.js";
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"}
{href}
class={cn(badgeVariants({ variant, className }))}
{...$$restProps}
>
<slot />
</svelte:element>

View File

@ -0,0 +1,21 @@
import { type VariantProps, tv } from "tailwind-variants";
export { default as Badge } 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"];

View File

@ -12,6 +12,31 @@ export interface PeerRow {
ifname: string; ifname: string;
} }
/**
* Sample response from OPNsense WireGuard API
* ```json
* {
* "total": 17,
* "rowCount": 7,
* "current": 1,
* "rows": [
* {
* "if": "wg0",
* "type": "peer",
* "public-key": "iJa5JmJbMHNlbEluNwoB2Q8LyrPAfb7S/mluanMcI08=",
* "endpoint": "10.17.20.107:42516",
* "allowed-ips": "fd00::1/112,10.6.0.3/32",
* "latest-handshake": 1729319339,
* "transfer-rx": 1052194743,
* "transfer-tx": 25203263456,
* "persistent-keepalive": "off",
* "name": "Yura-TPX13",
* "ifname": "wg0"
* }
* ]
* }
* ```
*/
export interface OpnsenseWgPeers { export interface OpnsenseWgPeers {
total: number; total: number;
rowCount: number; rowCount: number;
@ -19,38 +44,18 @@ export interface OpnsenseWgPeers {
rows: PeerRow[]; rows: PeerRow[];
} }
// Sample request to OPNsense WireGuard API /**
// const url = 'https://opnsense.home/api/wireguard/service/show'; * Sample request to OPNsense WireGuard API
// const options = { * ```js
// method: 'POST', * const url = 'https://opnsense.home/api/wireguard/service/show';
// headers: { * const options = {
// Authorization: 'Basic ...', * method: 'POST',
// 'Content-Type': 'application/json', * headers: {
// Accept: 'application/json', * Authorization: 'Basic ...',
// 'content-type': 'application/json' * 'Content-Type': 'application/json',
// }, * Accept: 'application/json',
// body: '{"current":1,"rowCount":7,"sort":{},"searchPhrase":"","type":["peer"]}' * },
// }; * body: '{"current":1,"rowCount":7,"sort":{},"searchPhrase":"","type":["peer"]}'
* };
* ```
// Sample response from OPNsense WireGuard API */
// {
// "total": 17,
// "rowCount": 7,
// "current": 1,
// "rows": [
// {
// "if": "wg0",
// "type": "peer",
// "public-key": "iJa5JmJbMHNlbEluNwoB2Q8LyrPAfb7S/mluanMcI08=",
// "endpoint": "10.17.20.107:42516",
// "allowed-ips": "fd00::1/112,10.6.0.3/32",
// "latest-handshake": 1729319339,
// "transfer-rx": 1052194743,
// "transfer-tx": 25203263456,
// "persistent-keepalive": "off",
// "name": "Yura-TPX13",
// "ifname": "wg0"
// }
// ]
// }

View File

@ -0,0 +1,16 @@
import { env } from '$env/dynamic/private';
import assert from 'node:assert';
import { encodeBasicCredentials } from 'arctic/dist/request';
import { dev } from '$app/environment';
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 = "";

View File

@ -1,14 +1,14 @@
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { env } from '$env/dynamic/private'; import { opnsenseAuth, opnsenseIfname, opnsenseUrl } from '$lib/server/opnsense';
import type { OpnsenseWgPeers } from '$lib/opnsense/wg'; import type { OpnsenseWgPeers } from '$lib/opnsense/wg';
export const GET: RequestHandler = async ({ url }) => { export const GET: RequestHandler = async () => {
const apiUrl = `${env.OPNSENSE_API_URL}/api/wireguard/service/show`; const apiUrl = `${opnsenseUrl}/api/wireguard/service/show`;
const options: RequestInit = { const options: RequestInit = {
method: 'POST', method: 'POST',
headers: { headers: {
Authorization: `Basic ${Buffer.from(`${env.OPNSENSE_API_KEY}:${env.OPNSENSE_API_SECRET}`).toString('base64')}`, Authorization: opnsenseAuth,
Accept: 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
@ -24,6 +24,7 @@ export const GET: RequestHandler = async ({ url }) => {
const res = await fetch(apiUrl, options); const res = await fetch(apiUrl, options);
const peers = await res.json() as OpnsenseWgPeers; const peers = await res.json() as OpnsenseWgPeers;
peers.rows = peers.rows.filter(peer => peer['latest-handshake'] && peer.ifname === opnsenseIfname)
if (!peers) { if (!peers) {
error(500, "Error getting info from OPNsense API"); error(500, "Error getting info from OPNsense API");

View File

@ -1,13 +1,10 @@
<script lang="ts"> <script lang="ts">
import type { PageData } from './$types'; import type { PageData } from './$types';
import { invalidate } from '$app/navigation'; import { invalidate } from '$app/navigation';
import { page } from '$app/stores';
import * as Table from '$lib/components/ui/table'; import * as Table from '$lib/components/ui/table';
import { Checkbox } from '$lib/components/ui/checkbox'; import { Badge } from '$lib/components/ui/badge';
import { Label } from '$lib/components/ui/label';
const { data }: { data: PageData } = $props(); const { data }: { data: PageData } = $props();
let showOnlyActive = $state($page.url.searchParams.get('showOnlyActive') === '1');
$effect(() => { $effect(() => {
// refresh every 5 seconds // refresh every 5 seconds
@ -18,12 +15,6 @@
return () => clearInterval(interval); return () => clearInterval(interval);
}); });
$effect(() => {
window.history.replaceState(history.state, '', window.location.pathname + `?showOnlyActive=${showOnlyActive? 1 : 0}`);
// other options that worked less well (at some things)
// pushState('', {showOnlyActive: showOnlyActive});
// goto(`?showOnlyActive=${showOnlyActive? 1 : 0}`);
});
function getSize(size: number) { function getSize(size: number) {
let sizes = ['Bytes', 'KiB', 'MiB', 'GiB', let sizes = ['Bytes', 'KiB', 'MiB', 'GiB',
@ -42,9 +33,6 @@
<title>Connections</title> <title>Connections</title>
</svelte:head> </svelte:head>
<Checkbox id="showOnlyActive" bind:checked={showOnlyActive} />
<Label for="showOnlyActive">Show only active connections</Label>
<Table.Root class="bg-accent rounded-xl"> <Table.Root class="bg-accent rounded-xl">
<Table.Header> <Table.Header>
<Table.Head>Name</Table.Head> <Table.Head>Name</Table.Head>
@ -54,30 +42,28 @@
<Table.Head>Latest Handshake</Table.Head> <Table.Head>Latest Handshake</Table.Head>
<Table.Head>RX</Table.Head> <Table.Head>RX</Table.Head>
<Table.Head>TX</Table.Head> <Table.Head>TX</Table.Head>
<Table.Head>Persistent Keepalive</Table.Head> <Table.Head class="hidden">Persistent Keepalive</Table.Head>
<Table.Head>Interface Name</Table.Head> <Table.Head class="hidden">Interface Name</Table.Head>
</Table.Header> </Table.Header>
<Table.Body> <Table.Body>
{#each data.peers.rows as peer} {#each data.peers.rows as peer}
{#if peer['latest-handshake'] || !showOnlyActive } <Table.Row class="border-y-2 border-background">
<Table.Row class="border-y-2 border-background"> <Table.Cell>{peer.name}</Table.Cell>
<Table.Cell>{peer.name}</Table.Cell> <Table.Cell class="truncate max-w-[10ch]">{peer['public-key']}</Table.Cell>
<Table.Cell>{peer['public-key'].substring(0, 10)}</Table.Cell> <Table.Cell>{peer.endpoint}</Table.Cell>
<Table.Cell>{peer.endpoint}</Table.Cell> <Table.Cell>
<Table.Cell>{peer['allowed-ips']}</Table.Cell> <div class="flex flex-wrap gap-1">
{#if peer['latest-handshake']} {#each peer['allowed-ips'].split(',') as addr}
<Table.Cell>{new Date(peer['latest-handshake'] * 1000).toLocaleString()}</Table.Cell> <Badge class="bg-background" variant="secondary">{addr}</Badge>
<Table.Cell>{getSize(peer['transfer-rx'])}</Table.Cell> {/each}
<Table.Cell>{getSize(peer['transfer-tx'])}</Table.Cell> </div>
{:else} </Table.Cell>
<Table.Cell>Never</Table.Cell> <Table.Cell>{new Date(peer['latest-handshake'] * 1000).toLocaleString()}</Table.Cell>
<Table.Cell>--</Table.Cell> <Table.Cell>{getSize(peer['transfer-rx'])}</Table.Cell>
<Table.Cell>--</Table.Cell> <Table.Cell>{getSize(peer['transfer-tx'])}</Table.Cell>
{/if} <Table.Cell class="hidden">{peer['persistent-keepalive']}</Table.Cell>
<Table.Cell>{peer['persistent-keepalive']}</Table.Cell> <Table.Cell class="hidden">{peer.ifname}</Table.Cell>
<Table.Cell>{peer.ifname}</Table.Cell> </Table.Row>
</Table.Row>
{/if}
{/each} {/each}
</Table.Body> </Table.Body>
</Table.Root> </Table.Root>

View File

@ -1,7 +1,7 @@
import type { PageLoad } from './$types'; import type { PageLoad } from './$types';
import type { OpnsenseWgPeers } from '$lib/opnsense/wg'; import type { OpnsenseWgPeers } from '$lib/opnsense/wg';
export const load: PageLoad = async ({ fetch, params }) => { export const load: PageLoad = async ({ fetch }) => {
const res = await fetch('/api/connections'); const res = await fetch('/api/connections');
const peers = await res.json() as OpnsenseWgPeers; const peers = await res.json() as OpnsenseWgPeers;