Nixify and start frontend update

This commit is contained in:
2025-03-07 01:23:15 +01:00
parent 4a3c022958
commit 5682777bfe
38 changed files with 5299 additions and 10976 deletions

4464
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

25
frontend/package.json Normal file
View File

@@ -0,0 +1,25 @@
{
"name": "apiary-frontend",
"scripts": {
"start": "parcel src/index.html",
"build": "parcel build src/index.html"
},
"devDependencies": {
"@ngneat/falso": "^7.3.0",
"parcel": "^2.13.3",
"process": "^0.11.10",
"ts-loader": "^9.5.2",
"typescript": "^5.8.2"
},
"dependencies": {
"@types/node": "^22.13.9",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"chart.js": "^4.4.8",
"react": "^19.0.0",
"react-chartjs-2": "^5.3.0",
"react-dom": "^19.0.0",
"react-router": "^7.2.0",
"swr": "^2.3.2"
}
}

View File

@@ -0,0 +1,2 @@
@import url("https://fonts.googleapis.com/css2?family=Prompt:wght@300;600&display=swap");
@import url('https://fonts.googleapis.com/css2?family=Secular+One&display=swap');

164
frontend/src/css/style.css Normal file
View File

@@ -0,0 +1,164 @@
:root {
--menu-color-bg: #212529;
--menu-color-text: hsla(0,0%,100%,.5);
--menu-color-text-hover: white;
--menu-color-title-text: white;
--table-color-bg: #009879;
}
#root {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
body {
margin: 0;
margin-top: 100px;
}
*,
*::before,
*::after {
padding: 0;
margin: 0;
border-box: box-sizing;
}
a {
text-decoration: none;
}
.navbar {
background-color: var(--menu-color-bg);
display: flex;
font-size: 1.2rem;
font-family: "Prompt", sans-serif;
height: 40px;
position: fixed;
top: 0;
width: 100%;
}
.navbar ul {
display: flex;
align-items: center;
}
.root .navbar {
justify-content: space-between;
}
.navbar ul li {
list-style-type: none;
color: var(--menu-color-text);
padding-left: 10px;
padding-right: 10px;
line-height: 40px;
}
.navbar h2 {
line-height: 40px;
align-items: center;
padding-left: 10px;
padding-right: 10px;
}
.navbar a {
color: var(--menu-color-text);
height: 1;
}
.navbar a:hover {
color: var(--menu-color-text-hover);
}
.submenu nav {
display: flex;
justify-content: space-between;
line-height: 1;
}
.totals {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: 1fr;
grid-column-gap: 0px;
grid-row-gap: 0px;
margin-top: 5px;
margin-bottom: 5px;
font-family: "Secular One", sans-serif;
font-size: 20px;
font-weight: 200;
}
.totals-key {
grid-area: 1 / 1 / 2 / 2;
text-align: right;
}
.totals-value {
grid-area: 1 / 2 / 2 / 3;
padding-left: 10px;
text-align: left;
}
#menu-title {
color: white;
font-family: "Secular One", sans-serif;
font-size: 30px;
font-weight: 300;
}
.menu-link {
color: var(--menu-color-text);
}
.menu-link:hover {
color: var(--menu-color-text-hover);
}
.menu-link-active {
color: var(--menu-color-text-hover);
}
.sub-menu-link {
color: var(--menu-color-text);
}
.sub-menu-link:hover {
color: var(--menu-color-text-hover);
}
.sub-menu-link-active {
color: var(--menu-color-text-hover);
}
.stats-pie {
height: 50vh;
width: 50vw;
}
.live-table {
border-collapse: collapse;
margin: 25px 0;
font-size: 0.9em;
font-family: sans-serif;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
.live-table thead tr {
background-color: var(--table-color-bg);
color: #ffffff;
text-align: left;
}
.live-table th,
.live-table td {
padding: 12px 15px;
}
.live-table tbody tr {
border-bottom: 1px solid #dddddd;
}
.live-table tbody tr:nth-of-type(even) {
background-color: #f3f3f3;
}
.live-table tbody tr:last-of-type {
border-bottom: 2px solid var(--table-color-bg);
}
.live-table tbody tr.active-row {
font-weight: bold;
color: #009879;
}
.content {
margin-left: 10vw;
}

13
frontend/src/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="./css/style.css" />
<link rel="stylesheet" href="./css/fonts.css" />
<script type="module" src="./js/app.tsx"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>

139
frontend/src/js/api.ts Normal file
View File

@@ -0,0 +1,139 @@
import { randUserName, randPastDate, randIp, randPassword, randUuid, randNumber } from '@ngneat/falso';
export interface LoginAttempt {
readonly date: string;
readonly remoteIP: string;
readonly username: string;
readonly password: string;
readonly sshClientVersion: string;
readonly connectionUUID: string;
readonly country: string;
}
export interface TotalStats {
readonly password: number;
readonly username: number;
readonly ip: number;
readonly country: number;
readonly attempts: number;
}
export interface StatsResult {
name: string;
count: number;
}
export interface ApiaryAPI {
live(fn: (a: LoginAttempt) => void): void;
stats(statsType: string, limit: number): Promise<StatsResult[]>;
query(queryType: string, query: string): Promise<LoginAttempt[]>;
totals(): Promise<TotalStats>;
}
function fakeLoginAttempt(): LoginAttempt {
return {
date: randPastDate().toISOString(),
remoteIP: randIp().toString(),
username: randUserName().toString(),
password: randPassword().toString(),
sshClientVersion: '1.0',
connectionUUID: randUuid().toString(),
country: 'NO'
}
}
export class DummyApiaryAPIClient implements ApiaryAPI {
live(fn: (a: LoginAttempt) => void): () => void {
const interval = setInterval(() => {
let a = fakeLoginAttempt();
fn(a);
}, 1000);
return () => { clearInterval(interval) }
}
async stats(_type: string, limit: number): Promise<StatsResult[]> {
const stats = Array.from({ length: limit }, () => {
return { name: randUserName().toString(), count: randNumber().valueOf() }
});
return Promise.resolve(stats);
}
async query(_type: string, _query: string): Promise<LoginAttempt[]> {
const attempts = Array.from({ length: 10 }, () => {
return fakeLoginAttempt();
})
return Promise.resolve(attempts);
}
async totals(): Promise<TotalStats> {
return Promise.resolve({ password: 1, username: 1, ip: 1, country: 1, attempts: 1 })
}
}
export class ApiaryAPIClient implements ApiaryAPI {
live(fn: (a: LoginAttempt) => void): () => void {
const es = new EventSource('/api/stream');
const updateFn = (ev: MessageEvent<string>) => {
const attempt: LoginAttempt = JSON.parse(ev.data);
fn(attempt);
};
es.addEventListener('message', updateFn)
return () => {
es.removeEventListener('message', updateFn);
es.close();
}
}
async stats(statsType: string, limit: number): Promise<StatsResult[]> {
const resp = await fetch(`/api/stats?type=${statsType}&limit=${limit}`)
if (!resp.ok) {
throw new Error('Failed to fetch query')
}
const data: StatsResult[] | null = await resp.json()
if (!data) {
return []
}
return data
}
async query(queryType: string, query: string): Promise<LoginAttempt[]> {
const resp = await fetch(`/api/query?type=${queryType}&query=${query}`)
if (!resp.ok) {
throw new Error('Failed to fetch query')
}
const data: LoginAttempt[] = await resp.json()
return data
}
async totals(): Promise<TotalStats> {
let password: number = -1
let username: number = -1
let ip: number = -1
let attempts: number = -1
let country: number = -1
const resp = await fetch('/api/stats?type=total')
const data: Array<StatsResult> = await resp.json()
for (const stat of data) {
switch (stat.name) {
case 'UniquePasswords':
password = stat.count
break
case 'UniqueUsernames':
username = stat.count
break
case 'UniqueIPs':
ip = stat.count
break
case 'TotalLoginAttempts':
attempts = stat.count
break
case 'UniqueCountries':
country = stat.count
break
}
}
return { password, username, ip, attempts, country }
}
}

343
frontend/src/js/app.tsx Normal file
View File

@@ -0,0 +1,343 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { useState, useEffect } from 'react';
import { ApiaryAPI, LoginAttempt, DummyApiaryAPIClient, ApiaryAPIClient, TotalStats, StatsResult } from "./api";
import { BrowserRouter, NavLink, Routes, Route } from "react-router";
import { Chart as ChartJS, Tooltip, ArcElement, Legend } from "chart.js";
import { Pie } from "react-chartjs-2";
ChartJS.register(Tooltip, ArcElement, Legend);
interface AppProps {
api: ApiaryAPI
}
let chartColors = [
"#1abc9c",
"#2ecc71",
"#3498db",
"#9b59b6",
"#34495e",
"#16a085",
"#27ae60",
"#2980b9",
"#8e44ad",
"#2c3e50",
"#f1c40f",
"#e67e22",
"#e74c3c",
"#ecf0f1",
"#95a5a6",
"#f39c12",
"#d35400",
"#c0392b",
"#bdc3c7",
"#7f8c8d"
]
export function App({ api }: AppProps) {
return (
<>
<BrowserRouter>
<Header />
<div className="content">
<Routes>
<Route path="/" element={<Home api={api} />} />
<Route path="/stats" element={<Stats api={api} />} />
<Route path="/live" element={<Live api={api} />} />
<Route path="/query" element={<Query api={api} />} />
</Routes>
</div>
</BrowserRouter>
</>
);
}
export function Stats({ api }: AppProps) {
const [stats, setStats] = useState<StatsResult[]>([]);
const [statsType, setStatsType] = useState<string>("password")
const activeMenu = (name: string): boolean => {
if (statsType === name) {
return true
}
return false
}
const subMenuItems: SubMenuProps = {
items: [
{
name: "Passwords",
active: () => { return activeMenu("password") },
onClick: () => setStatsType("password")
},
{
name: "Usernames",
active: () => { return activeMenu("username") },
onClick: () => setStatsType("username")
},
{
name: "IPs",
active: () => { return activeMenu("ip") },
onClick: () => setStatsType("ip")
},
]
}
useEffect(() => {
async function getStats() {
try {
let newStats = await api.stats(statsType, 10);
if (JSON.stringify(newStats) !== JSON.stringify(stats)) {
setStats(newStats)
}
} catch (e) {
console.log("Error getting stats", e)
}
}
getStats()
const interval = setInterval(() => {
getStats()
}, 5000)
return () => {
clearInterval(interval);
}
}, [stats, statsType])
return (
<>
<SubMenu items={subMenuItems.items} />
{stats.length > 0 ? <StatsPie data={stats} /> : <p>Loading...</p>}
</>
);
}
export interface StatsPieProps {
data: StatsResult[]
}
export function StatsPie({ data }: StatsPieProps) {
const labels = data.map((d) => d.name);
const values = data.map((d) => d.count);
const piedata = {
labels,
datasets: [{
label: "# of attempts",
data: values,
backgroundColor: chartColors,
borderWidth: 1
}]
};
return (
<div className="stats-pie">
<Pie data={piedata} options={{ plugins: { legend: {} } }} />
</div>
)
}
export function Home({ api }: AppProps) {
const [totals, setTotals] = useState<TotalStats | null>(null)
useEffect(() => {
async function getTotals() {
let totals = await api.totals();
setTotals(totals);
}
if (!totals) {
getTotals();
}
const interval = setInterval(() => {
getTotals();
}, 5000)
return () => {
clearInterval(interval);
}
})
return (
<>
{totals ? <Totals totals={totals} /> : <p>Loading...</p>}
</>
);
}
export interface TotalsProps {
totals: TotalStats
}
export function Totals({ totals }: TotalsProps) {
return (
<div className="totals">
<div className="totals-key">
<h2>Unique passwords</h2>
<h2>Unique username</h2>
<h2>Unique IPs</h2>
<h2>Total attempts</h2>
</div>
<div className="totals-value">
<h2>{totals.password}</h2>
<h2>{totals.username}</h2>
<h2>{totals.ip}</h2>
<h2>{totals.attempts}</h2>
</div>
</div>
)
}
export function Live({ api }: AppProps) {
let list: LoginAttempt[] = [];
let [liveList, setLiveList] = useState(list);
useEffect(() => {
const cleanup = api.live((a) => {
setLiveList((list) => {
return [...list, a];
});
});
return cleanup
}, [liveList, api]);
return (
<>
<LiveList list={liveList} />
</>
);
}
export interface LiveListProps {
list: LoginAttempt[]
};
export function LiveList({ list }: LiveListProps) {
let items = list.map((a) => {
return (
<tr key={a.date}>
<td>{a.date}</td>
<td>{a.username}</td>
<td>{a.password}</td>
<td>{a.remoteIP}</td>
<td>{a.country}</td>
</tr>
)
})
return (
<>
<table className="live-table">
<thead>
<tr>
<th>Date</th>
<th>Username</th>
<th>Password</th>
<th>IP</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{items}
</tbody>
</table>
</>
)
};
export function Query({ api }: AppProps) {
const [liveList, setLiveList] = useState<LoginAttempt[]>([]);
const [queryErr, setQueryErr] = useState<Error | null>(null);
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const value = event.currentTarget.query.value;
if (value === "") {
setQueryErr(new Error("Query cannot be empty"));
return
}
try {
const results = await api.query("", value)
setQueryErr(null);
setLiveList(results);
} catch (e) {
if (e instanceof Error) {
setQueryErr(e);
}
}
}
return (
<>
<form onSubmit={handleSubmit}>
<input placeholder="query" name="query" />
</form>
{queryErr ? <ErrorBox message={queryErr.message} /> : null}
<LiveList list={liveList} />
</>
);
}
interface ErrorBoxProps {
message: string | null
};
export function ErrorBox({ message }: ErrorBoxProps) {
return (
<div className="error-box">
<p>Error: {message}</p>
</div>
)
}
export function Header() {
return (
<div className="navbar">
<h2 id="menu-title">apiary.home.2rjus.net</h2>
<nav className="nav-flex">
<ul>
<li><NavLink to="/" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Home</NavLink></li>
<li><NavLink to="/stats" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Stats</NavLink></li>
<li><NavLink to="/live" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Live</NavLink></li>
<li><NavLink to="/query" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Query</NavLink></li>
</ul>
</nav>
</div>
);
}
export interface SubMenuProps {
items: Array<{ name: string, active: () => boolean, onClick: () => void }>
}
export function SubMenu({ items }: SubMenuProps) {
return (
<nav className="submenu">
<ul>
{items.map((item) => {
return <li>
<a
href="#"
className={item.active() ? "sub-menu-link-active" : "sub-menu-link"}
onClick={item.onClick}>{item.name}</a>
</li>
})}
</ul>
</nav>
)
}
const rootElement = document.getElementById('root');
if (rootElement) {
const root = createRoot(rootElement);
let api: ApiaryAPI;
if (process.env.NODE_ENV === "production") {
api = new ApiaryAPIClient();
} else {
api = new DummyApiaryAPIClient();
}
root.render(
<App api={api} />
);
}

16
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react",
"module": "esnext",
"moduleResolution": "node",
"lib": ["dom", "esnext"],
"strict": true,
"sourceMap": true,
"target": "esnext",
"types": ["node"]
},
"exclude": ["node_modules"],
"include": ["src/**/*.ts", "src/**/*.tsx"]
}