clean up naming and add /settings/ to path

This commit is contained in:
Milo Schwartz
2024-11-02 15:44:48 -04:00
parent c05342dd25
commit 54ba205fc0
34 changed files with 523 additions and 784 deletions

View File

@@ -0,0 +1,42 @@
"use client";
import { SidebarNav } from "@app/components/sidebar-nav";
import { useSiteContext } from "@app/hooks/useSiteContext";
const sidebarNavItems = [
{
title: "General",
href: "/{orgId}/settings/sites/{niceId}",
},
];
export function ClientLayout({ isCreate, children }: { isCreate: boolean; children: React.ReactNode }) {
const { site } = useSiteContext();
return (<div className="hidden space-y-6 0 pb-16 md:block">
<div className="space-y-0.5">
<h2 className="text-2xl font-bold tracking-tight">
{isCreate
? "New Site"
: site?.name + " Settings"}
</h2>
<p className="text-muted-foreground">
{isCreate
? "Create a new site"
: "Configure the settings on your site: " +
site?.name || ""}
.
</p>
</div>
<div className="flex flex-col space-y-6 lg:flex-row lg:space-x-12 lg:space-y-0">
<aside className="-mx-4 lg:w-1/5">
<SidebarNav
items={sidebarNavItems}
disabled={isCreate}
/>
</aside>
<div className="flex-1 lg:max-w-2xl">
{children}
</div>
</div>
</div>);
}

View File

@@ -0,0 +1,225 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { ChevronDownIcon } from "@radix-ui/react-icons";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { cn } from "@/lib/utils";
import { toast } from "@/hooks/use-toast";
import { Button, buttonVariants } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { generateKeypair } from "./wireguardConfig";
import React, { useState, useEffect } from "react";
import { api } from "@/api";
import { useParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { Checkbox } from "@app/components/ui/checkbox";
import { PickSiteDefaultsResponse } from "@server/routers/site";
const method = [
{ label: "Wireguard", value: "wg" },
{ label: "Newt", value: "newt" },
] as const;
const accountFormSchema = z.object({
name: z
.string()
.min(2, {
message: "Name must be at least 2 characters.",
})
.max(30, {
message: "Name must not be longer than 30 characters.",
}),
method: z.enum(["wg", "newt"]),
});
type AccountFormValues = z.infer<typeof accountFormSchema>;
const defaultValues: Partial<AccountFormValues> = {
name: "",
method: "wg",
};
export function CreateSiteForm() {
const params = useParams();
const orgId = params.orgId;
const router = useRouter();
const [keypair, setKeypair] = useState<{
publicKey: string;
privateKey: string;
} | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isChecked, setIsChecked] = useState(false);
const [siteDefaults, setSiteDefaults] =
useState<PickSiteDefaultsResponse | null>(null);
const handleCheckboxChange = (checked: boolean) => {
setIsChecked(checked);
};
const form = useForm<AccountFormValues>({
resolver: zodResolver(accountFormSchema),
defaultValues,
});
useEffect(() => {
if (typeof window !== "undefined") {
const generatedKeypair = generateKeypair();
setKeypair(generatedKeypair);
setIsLoading(false);
api.get(`/org/${orgId}/pickSiteDefaults`)
.catch((e) => {
toast({
title: "Error creating site...",
});
})
.then((res) => {
if (res && res.status === 200) {
setSiteDefaults(res.data.data);
}
});
}
}, []);
async function onSubmit(data: AccountFormValues) {
const res = await api
.put(`/org/${orgId}/site/`, {
name: data.name,
subnet: siteDefaults?.subnet,
exitNodeId: siteDefaults?.exitNodeId,
pubKey: keypair?.publicKey,
})
.catch((e) => {
toast({
title: "Error creating site...",
});
});
if (res && res.status === 201) {
const niceId = res.data.data.niceId;
// navigate to the site page
router.push(`/${orgId}/settings/sites/${niceId}`);
}
}
const wgConfig =
keypair && siteDefaults
? `[Interface]
Address = ${siteDefaults.subnet}
ListenPort = 51820
PrivateKey = ${keypair.privateKey}
[Peer]
PublicKey = ${siteDefaults.publicKey}
AllowedIPs = ${siteDefaults.address.split("/")[0]}/32
Endpoint = ${siteDefaults.endpoint}:${siteDefaults.listenPort}
PersistentKeepalive = 5`
: "";
const newtConfig = `curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh`;
return (
<>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8"
>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is the name that will be displayed for
this site.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="method"
render={({ field }) => (
<FormItem>
<FormLabel>Method</FormLabel>
<div className="relative w-max">
<FormControl>
<select
className={cn(
buttonVariants({
variant: "outline",
}),
"w-[200px] appearance-none font-normal"
)}
{...field}
>
<option value="wg">
WireGuard
</option>
<option value="newt">Newt</option>
</select>
</FormControl>
<ChevronDownIcon className="absolute right-3 top-2.5 h-4 w-4 opacity-50" />
</div>
<FormDescription>
This is how you will connect your site to
Fossorial.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{form.watch("method") === "wg" && !isLoading ? (
<pre className="mt-2 w-full rounded-md bg-muted p-4 overflow-x-auto">
<code className="whitespace-pre-wrap font-mono">
{wgConfig}
</code>
</pre>
) : form.watch("method") === "wg" && isLoading ? (
<p>Loading WireGuard configuration...</p>
) : (
<pre className="mt-2 w-full rounded-md bg-muted p-4 overflow-x-auto">
<code className="whitespace-pre-wrap">
{newtConfig}
</code>
</pre>
)}
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={isChecked}
onCheckedChange={handleCheckboxChange}
/>
<label
htmlFor="terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
I have copied the config
</label>
</div>
<Button type="submit" disabled={!isChecked}>
Create Site
</Button>
</form>
</Form>
</>
);
}

View File

@@ -0,0 +1,63 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useSiteContext } from "@app/hooks/useSiteContext";
import { useForm } from "react-hook-form";
const GeneralFormSchema = z.object({
name: z.string(),
});
type GeneralFormValues = z.infer<typeof GeneralFormSchema>;
export function GeneralForm() {
const { site, updateSite } = useSiteContext();
const form = useForm<GeneralFormValues>({
resolver: zodResolver(GeneralFormSchema),
defaultValues: {
name: site?.name,
},
mode: "onChange",
});
async function onSubmit(data: GeneralFormValues) {
await updateSite({ name: data.name });
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
This is the display name of the site.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Update Site</Button>
</form>
</Form>
);
}

View File

@@ -0,0 +1,12 @@
"use client";
export function NewtConfig() {
const config = `curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh`;
return (
<pre className="mt-2 w-full rounded-md bg-slate-950 p-4 overflow-x-auto">
<code className="text-white whitespace-pre-wrap">{config}</code>
</pre>
);
}

View File

@@ -0,0 +1,180 @@
/*! SPDX-License-Identifier: GPL-2.0
*
* Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
*/
function gf(init: number[] | undefined = undefined) {
var r = new Float64Array(16);
if (init) {
for (var i = 0; i < init.length; ++i)
r[i] = init[i];
}
return r;
}
function pack(o: Uint8Array, n: Float64Array) {
var b, m = gf(), t = gf();
for (var i = 0; i < 16; ++i)
t[i] = n[i];
carry(t);
carry(t);
carry(t);
for (var j = 0; j < 2; ++j) {
m[0] = t[0] - 0xffed;
for (var i = 1; i < 15; ++i) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
cswap(t, m, 1 - b);
}
for (var i = 0; i < 16; ++i) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function carry(o: Float64Array) {
var c;
for (var i = 0; i < 16; ++i) {
o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
o[i] &= 0xffff;
}
}
function cswap(p: Float64Array, q: Float64Array, b: number) {
var t, c = ~(b - 1);
for (var i = 0; i < 16; ++i) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function add(o: Float64Array, a: Float64Array, b: Float64Array) {
for (var i = 0; i < 16; ++i)
o[i] = (a[i] + b[i]) | 0;
}
function subtract(o: Float64Array, a: Float64Array, b: Float64Array) {
for (var i = 0; i < 16; ++i)
o[i] = (a[i] - b[i]) | 0;
}
function multmod(o: Float64Array, a: Float64Array, b: Float64Array) {
var t = new Float64Array(31);
for (var i = 0; i < 16; ++i) {
for (var j = 0; j < 16; ++j)
t[i + j] += a[i] * b[j];
}
for (var i = 0; i < 15; ++i)
t[i] += 38 * t[i + 16];
for (var i = 0; i < 16; ++i)
o[i] = t[i];
carry(o);
carry(o);
}
function invert(o: Float64Array, i: Float64Array) {
var c = gf();
for (var a = 0; a < 16; ++a)
c[a] = i[a];
for (var a = 253; a >= 0; --a) {
multmod(c, c, c);
if (a !== 2 && a !== 4)
multmod(c, c, i);
}
for (var a = 0; a < 16; ++a)
o[a] = c[a];
}
function clamp(z: Uint8Array) {
z[31] = (z[31] & 127) | 64;
z[0] &= 248;
}
function generatePublicKey(privateKey: Uint8Array) {
var r, z = new Uint8Array(32);
var a = gf([1]),
b = gf([9]),
c = gf(),
d = gf([1]),
e = gf(),
f = gf(),
_121665 = gf([0xdb41, 1]),
_9 = gf([9]);
for (var i = 0; i < 32; ++i)
z[i] = privateKey[i];
clamp(z);
for (var i = 254; i >= 0; --i) {
r = (z[i >>> 3] >>> (i & 7)) & 1;
cswap(a, b, r);
cswap(c, d, r);
add(e, a, c);
subtract(a, a, c);
add(c, b, d);
subtract(b, b, d);
multmod(d, e, e);
multmod(f, a, a);
multmod(a, c, a);
multmod(c, b, e);
add(e, a, c);
subtract(a, a, c);
multmod(b, a, a);
subtract(c, d, f);
multmod(a, c, _121665);
add(a, a, d);
multmod(c, c, a);
multmod(a, d, f);
multmod(d, b, _9);
multmod(b, e, e);
cswap(a, b, r);
cswap(c, d, r);
}
invert(c, c);
multmod(a, a, c);
pack(z, a);
return z;
}
function generatePresharedKey() {
var privateKey = new Uint8Array(32);
crypto.getRandomValues(privateKey);
return privateKey;
}
function generatePrivateKey() {
var privateKey = generatePresharedKey();
clamp(privateKey);
return privateKey;
}
function encodeBase64(dest: Uint8Array, src: Uint8Array) {
var input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]);
for (var i = 0; i < 4; ++i)
dest[i] = input[i] + 65 +
(((25 - input[i]) >> 8) & 6) -
(((51 - input[i]) >> 8) & 75) -
(((61 - input[i]) >> 8) & 15) +
(((62 - input[i]) >> 8) & 3);
}
function keyToBase64(key: Uint8Array) {
var i, base64 = new Uint8Array(44);
for (i = 0; i < 32 / 3; ++i)
encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
base64[43] = 61;
return String.fromCharCode.apply(null, base64 as any);
}
export function generateKeypair() {
var privateKey = generatePrivateKey();
var publicKey = generatePublicKey(privateKey);
return {
publicKey: keyToBase64(publicKey),
privateKey: keyToBase64(privateKey)
};
}

View File

@@ -0,0 +1,50 @@
import SiteProvider from "@app/providers/SiteProvider";
import { internal } from "@app/api";
import { GetSiteResponse } from "@server/routers/site";
import { AxiosResponse } from "axios";
import { redirect } from "next/navigation";
import { authCookieHeader } from "@app/api/cookies";
import Link from "next/link";
import { ClientLayout } from "./components/ClientLayout";
interface SettingsLayoutProps {
children: React.ReactNode;
params: Promise<{ niceId: string; orgId: string }>;
}
export default async function SettingsLayout(props: SettingsLayoutProps) {
const params = await props.params;
const { children } = props;
let site = null;
if (params.niceId !== "create") {
try {
const res = await internal.get<AxiosResponse<GetSiteResponse>>(
`/org/${params.orgId}/site/${params.niceId}`,
await authCookieHeader()
);
site = res.data.data;
} catch {
redirect(`/${params.orgId}/settings/sites`);
}
}
return (
<>
<div className="mb-4">
<Link
href={`/${params.orgId}/settings/sites`}
className="text-primary font-medium"
></Link>
</div>
<SiteProvider site={site}>
<ClientLayout isCreate={params.niceId === "create"}>
{children}
</ClientLayout>
</SiteProvider>
</>
);
}

View File

@@ -0,0 +1,29 @@
import React from "react";
import { Separator } from "@/components/ui/separator";
import { CreateSiteForm } from "./components/CreateSite";
import { GeneralForm } from "./components/GeneralForm";
export default async function SitePage(props: {
params: Promise<{ niceId: string }>;
}) {
const params = await props.params;
const isCreate = params.niceId === "create";
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-medium">
{isCreate ? "Create Site" : "General"}
</h3>
<p className="text-sm text-muted-foreground">
{isCreate
? "Create a new site"
: "Edit basic site settings"}
</p>
</div>
<Separator />
{isCreate ? <CreateSiteForm /> : <GeneralForm />}
</div>
);
}

View File

@@ -0,0 +1,142 @@
"use client";
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
getPaginationRowModel,
SortingState,
getSortedRowModel,
ColumnFiltersState,
getFilteredRowModel,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@app/components/ui/button";
import { useState } from "react";
import { Input } from "@app/components/ui/input";
import { DataTablePagination } from "../../../../../components/DataTablePagination";
import { Plus } from "lucide-react";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
addSite?: () => void;
}
export function SitesDataTable<TData, TValue>({
addSite,
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
state: {
sorting,
columnFilters,
},
});
return (
<div>
<div className="flex items-center justify-between pb-4">
<Input
placeholder="Search your sites"
value={
(table.getColumn("name")?.getFilterValue() as string) ??
""
}
onChange={(event) =>
table
.getColumn("name")
?.setFilterValue(event.target.value)
}
className="max-w-sm mr-2"
/>
<Button
onClick={() => {
if (addSite) {
addSite();
}
}}
>
<Plus className="mr-2 h-4 w-4" /> Add Site
</Button>
</div>
<div>
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef
.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={
row.getIsSelected() && "selected"
}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No sites. Create one to get started.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="mt-4">
<DataTablePagination table={table} />
</div>
</div>
);
}

View File

@@ -0,0 +1,127 @@
"use client";
import { ColumnDef } from "@tanstack/react-table";
import { SitesDataTable } from "./SitesDataTable";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@app/components/ui/dropdown-menu";
import { Button } from "@app/components/ui/button";
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import api from "@app/api";
export type SiteRow = {
id: number;
nice: string;
name: string;
mbIn: number;
mbOut: number;
orgId: string;
};
export const columns: ColumnDef<SiteRow>[] = [
{
accessorKey: "name",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
>
Name
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
},
{
accessorKey: "nice",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
>
Site
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
},
{
accessorKey: "mbIn",
header: "MB In",
},
{
accessorKey: "mbOut",
header: "MB Out",
},
{
id: "actions",
cell: ({ row }) => {
const router = useRouter();
const siteRow = row.original;
const deleteSite = (siteId: number) => {
api.delete(`/site/${siteId}`)
.catch((e) => {
console.error("Error deleting site", e);
})
.then(() => {
router.refresh();
});
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<Link
href={`/${siteRow.orgId}/settings/sites/${siteRow.id}`}
>
View settings
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<button onClick={() => deleteSite(siteRow.id)} className="text-red-600 hover:text-red-800 hover:underline cursor-pointer">Delete</button>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];
type SitesTableProps = {
sites: SiteRow[];
orgId: string;
};
export default function SitesTable({ sites, orgId }: SitesTableProps) {
const router = useRouter();
return (
<SitesDataTable
columns={columns}
data={sites}
addSite={() => {
router.push(`/${orgId}/settings/sites/create`);
}}
/>
);
}

View File

@@ -0,0 +1,49 @@
import { internal } from "@app/api";
import { authCookieHeader } from "@app/api/cookies";
import { ListSitesResponse } from "@server/routers/site";
import { AxiosResponse } from "axios";
import SitesTable, { SiteRow } from "./components/SitesTable";
type SitesPageProps = {
params: Promise<{ orgId: string }>;
};
export default async function SitesPage(props: SitesPageProps) {
const params = await props.params;
let sites: ListSitesResponse["sites"] = [];
try {
const res = await internal.get<AxiosResponse<ListSitesResponse>>(
`/org/${params.orgId}/sites`,
await authCookieHeader()
);
sites = res.data.data.sites;
} catch (e) {
console.error("Error fetching sites", e);
}
const siteRows: SiteRow[] = sites.map((site) => {
return {
name: site.name,
id: site.siteId,
nice: site.niceId.toString(),
mbIn: site.megabytesIn || 0,
mbOut: site.megabytesOut || 0,
orgId: params.orgId,
};
});
return (
<>
<div className="space-y-0.5 select-none mb-6">
<h2 className="text-2xl font-bold tracking-tight">
Manage Sites
</h2>
<p className="text-muted-foreground">
Manage your existing sites here or create a new one.
</p>
</div>
<SitesTable sites={siteRows} orgId={params.orgId} />
</>
);
}