chore: restart the repository with a clean history
CI / Docker image (push) Successful in 12s
CI / Server (push) Successful in 25s
CI / CLI (push) Successful in 13s
Development image / Development image (push) Successful in 21s
CI / CLI (windows) (push) Successful in 57s
CI / CLI (linux-arm64, static) (push) Successful in 1m37s
Release / Prepare release (push) Successful in 2s
Release / Server (linux-x64) (push) Successful in 53s
Release / CLI (linux-arm64, static) (push) Successful in 1m32s
Release / Docker image (push) Successful in 2m48s
Release / Server (windows-x64) (push) Successful in 6m20s
Release / CLI (windows-x64) (push) Successful in 6m48s
Release / CLI (linux-x64) (push) Successful in 7m8s
Release / Publish release (push) Successful in 1s

Squash the tree into one commit, drop docs/architecture.html, reset the version line to 0.3.0, consolidate the changelog, enable Renovate automerge for non-major updates and add AGENTS.md.
This commit is contained in:
fristy committed 2026-11-10 11:31:13 +03:00
commit 650807c1fb
438 files changed
+45070

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
import "./styles.sass";
import { useParams } from "react-router-dom";
import CopyField from "@/common/components/CopyField";
import OpenInFrislit from "@/common/components/OpenInFrislit";
export const Connect = () => {
const { code } = useParams();
const command = `frislit connect ${window.location.origin}/@frislit/connect/${code}`;
return (
<div className="connect-page">
<div className="form-head">
<h1>Connect to this port.</h1>
<p>The port appears on your own machine, as if it were running there.</p>
</div>
<OpenInFrislit href={`frislit://connect/${encodeURIComponent(code)}?server=${encodeURIComponent(window.location.origin)}`} />
<div className="connect-command">
<span>or run</span>
<CopyField value={command} />
</div>
<p className="connect-hint">
No frislit yet? <a href="https://git.fristy.net/fristy/frislit/blob/main/docs/installation.md" target="_blank" rel="noreferrer noopener">Install it</a> in one line.
You do not need an account to connect.
</p>
</div>
);
};
+1
View File
@@ -0,0 +1 @@
export { Connect as default } from "./Connect.jsx";
+37
View File
@@ -0,0 +1,37 @@
@use "@/common/styles/colors"
.connect-page
width: 100%
.copy-field
align-items: flex-start
code
overflow: visible
text-overflow: clip
white-space: pre-wrap
word-break: break-all
line-height: 1.5
.connect-hint
margin-top: 1rem
color: colors.$muted
font-size: 0.8125rem
line-height: 1.55
a
color: colors.$primary-bright
text-decoration: none
&:hover
text-decoration: underline
.connect-command
display: flex
flex-direction: column
gap: 0.375rem
margin-top: 1.25rem
> span
color: colors.$muted
font-size: 0.75rem
+59
View File
@@ -0,0 +1,59 @@
import "./styles.sass";
import { useEffect, useRef, useState } from "react";
import Input from "@/common/components/Input";
import Button from "@/common/components/Button";
import Loading from "@/common/components/Loading";
import { postRequest } from "@/common/utils/RequestUtil.js";
import { formValues, useAutofill } from "@/common/utils/autofill.js";
const PasswordGate = ({ id }) => {
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const formRef = useRef(null);
useAutofill(formRef, filled => {
if (filled["gate-password"]) setPassword(current => current || filled["gate-password"]);
});
const submit = async event => {
event.preventDefault();
const secret = formValues(event.currentTarget)["gate-password"] || password;
setPassword(secret);
setBusy(true);
setError(null);
try {
await postRequest(`gate/${encodeURIComponent(id)}`, { password: secret });
window.location.reload();
} catch (failure) {
setError(failure.message || "That did not work");
setBusy(false);
}
};
return (
<form className="gate" onSubmit={submit} ref={formRef}>
<div className="form-head">
<h1>Protected tunnel.</h1>
<p>Enter the password for <code>{id}</code>.</p>
</div>
<div className="form-body">
<Input id="gate-password" label="Password" type="password" value={password} setValue={setPassword}
autoFocus autoComplete="current-password" />
{error && <p className="gate-error">{error}</p>}
</div>
<div className="form-actions">
<div className="spacer" />
<Button text={busy ? "Checking…" : "Continue"} buttonType="submit" disabled={busy || !password} />
</div>
</form>
);
};
export const Gate = ({ id, auth, authorize }) => {
useEffect(() => {
if (auth === "frislit") window.location.replace(`${authorize}?return=${encodeURIComponent(window.location.href)}`);
}, [auth, authorize]);
return auth === "frislit" ? <Loading /> : <PasswordGate id={id} />;
};
+1
View File
@@ -0,0 +1 @@
export { Gate as default } from "./Gate.jsx";
+14
View File
@@ -0,0 +1,14 @@
@use "@/common/styles/colors"
.gate
width: 100%
code
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-size: 0.85em
color: colors.$primary-bright
.gate-error
color: colors.$error
font-size: 0.8125rem
margin-top: 0.5rem
+122
View File
@@ -0,0 +1,122 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Input from "@/common/components/Input";
import Button from "@/common/components/Button";
import Loading from "@/common/components/Loading";
import { getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useUser } from "@/common/contexts/user.js";
export const Handoff = () => {
const [params] = useSearchParams();
const navigate = useNavigate();
const { user, loaded } = useUser();
const code = (params.get("code") || "").toUpperCase();
const [request, setRequest] = useState(null);
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [done, setDone] = useState(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
if (!code) return setError("This link has no code in it.");
try {
const data = await getRequest(`devices/pending/${encodeURIComponent(code)}`);
setRequest(data.request);
setName(previous => previous || data.request.client || "");
} catch (failure) {
if (failure.code !== 401) setError(failure.message);
}
}, [code]);
useEffect(() => {
if (loaded && user) load();
}, [loaded, user, load]);
if (!loaded) return <Loading />;
if (!user) {
return (
<div className="handoff">
<div className="form-head">
<h1>Sign in first.</h1>
<p>Approving a device needs your frislit account.</p>
</div>
<div className="form-actions">
<div className="spacer" />
<Button text="Sign in" buttonType="button"
onClick={() => navigate("/login", { state: { from: `/handoff?code=${encodeURIComponent(code)}` } })} />
</div>
</div>
);
}
if (done) {
return (
<div className="handoff">
<div className="form-head">
<h1>{done === "approved" ? "Device linked." : "Request denied."}</h1>
<p>{done === "approved"
? "The CLI has its token and is ready to create tunnels."
: "Nothing was handed out. You can close this page."}</p>
</div>
<div className="form-actions">
<div className="spacer" />
<Button text="Go to tunnels" buttonType="button" onClick={() => navigate("/tunnels")} />
</div>
</div>
);
}
if (error) {
return (
<div className="handoff">
<div className="form-head">
<h1>That code is gone.</h1>
<p>{error} Run <code>frislit login</code> again to get a new one.</p>
</div>
</div>
);
}
if (!request) return <Loading />;
const act = async action => {
setBusy(true);
try {
await postRequest(`devices/pending/${encodeURIComponent(code)}/${action}`, action === "approve" ? { name } : {});
setDone(action === "approve" ? "approved" : "denied");
} catch (failure) {
setError(failure.message);
} finally {
setBusy(false);
}
};
return (
<div className="handoff">
<div className="form-head">
<h1>Link this device?</h1>
<p>A frislit CLI is asking to create tunnels on this server.</p>
</div>
<dl className="handoff-facts">
<div><dt>Code</dt><dd className="mono">{request.code}</dd></div>
<div><dt>From</dt><dd className="mono">{request.ip || "unknown"}</dd></div>
<div><dt>Client</dt><dd>{request.userAgent || request.client}</dd></div>
</dl>
<div className="form-body">
<Input id="handoff-name" label="Name it" placeholder="Laptop" value={name} setValue={setName} />
</div>
<div className="form-actions">
<Button type="ghost" text="Deny" buttonType="button" onClick={() => act("deny")} disabled={busy} />
<div className="spacer" />
<Button text={busy ? "Linking…" : "Approve"} buttonType="button" onClick={() => act("approve")}
disabled={busy || !name.trim()} />
</div>
</div>
);
};
+1
View File
@@ -0,0 +1 @@
export { Handoff as default } from "./Handoff.jsx";
+42
View File
@@ -0,0 +1,42 @@
@use "@/common/styles/colors"
.handoff
width: 100%
code
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-size: 0.85em
color: colors.$primary-bright
.handoff-facts
display: flex
flex-direction: column
gap: 0.4rem
margin: 1rem 0
padding: 0.875rem 1rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
> div
display: flex
align-items: baseline
gap: 0.75rem
dt
flex-shrink: 0
width: 3.5rem
color: colors.$muted
font-size: 0.75rem
dd
margin: 0
color: colors.$subtext
font-size: 0.8125rem
overflow: hidden
text-overflow: ellipsis
white-space: nowrap
.mono
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
color: colors.$text
+31
View File
@@ -0,0 +1,31 @@
import "@/pages/Connect/styles.sass";
import { useParams } from "react-router-dom";
import CopyField from "@/common/components/CopyField";
import OpenInFrislit from "@/common/components/OpenInFrislit";
export const Invite = () => {
const { token } = useParams();
const origin = window.location.origin;
const link = `${origin}/@frislit/invite/${token}`;
return (
<div className="connect-page">
<div className="form-head">
<h1>Tunnel through this server.</h1>
<p>This link lets you open tunnels here without an account. Keep it to yourself.</p>
</div>
<OpenInFrislit href={`frislit://invite/${encodeURIComponent(token)}?server=${encodeURIComponent(origin)}`} />
<div className="connect-command">
<span>or run</span>
<CopyField value={`frislit login ${link}`} />
</div>
<p className="connect-hint">
No frislit yet? <a href="https://git.fristy.net/fristy/frislit/blob/main/docs/installation.md" target="_blank" rel="noreferrer noopener">Install it</a> in one line.
Afterwards <code>frislit http 3000</code> works as usual.
</p>
</div>
);
};
+1
View File
@@ -0,0 +1 @@
export { Invite as default } from "./Invite.jsx";
+147
View File
@@ -0,0 +1,147 @@
import "./styles.sass";
import { useEffect, useRef, useState } from "react";
import { Navigate, useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { Fingerprint } from "lucide-react";
import Input from "@/common/components/Input";
import Button from "@/common/components/Button";
import { getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { passkeysSupported, signInWithPasskey } from "@/common/utils/webauthn.js";
import { formValues, useAutofill } from "@/common/utils/autofill.js";
export const Login = () => {
const { sendToast } = useToast();
const { user, setupRequired, login } = useUser();
const navigate = useNavigate();
const location = useLocation();
const [params] = useSearchParams();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [code, setCode] = useState("");
const [needsCode, setNeedsCode] = useState(false);
const [providers, setProviders] = useState([]);
const [loading, setLoading] = useState(false);
const formRef = useRef(null);
const requested = params.get("next");
const next = /^\/@frislit\/[^/\\]/.test(requested) ? requested : null;
useAutofill(formRef, filled => {
if (filled.username) setUsername(current => current || filled.username);
if (filled.password) setPassword(current => current || filled.password);
});
useEffect(() => {
getRequest("auth/providers").then(data => setProviders(data.providers)).catch(() => setProviders([]));
}, []);
useEffect(() => {
const error = params.get("error");
if (error) sendToast("Error", error);
}, [params, sendToast]);
useEffect(() => {
if (user && next) window.location.replace(next);
}, [user, next]);
if (setupRequired) return <Navigate to="/setup" replace />;
if (user && !next) return <Navigate to={location.state?.from || "/tunnels"} replace />;
const done = async () => {
if (next) return window.location.replace(next);
await login();
navigate(location.state?.from || "/tunnels", { replace: true });
};
const submit = async event => {
event.preventDefault();
const filled = formValues(event.currentTarget);
const identity = filled.username || username;
const secret = filled.password || password;
setUsername(identity);
setPassword(secret);
setLoading(true);
try {
const result = await postRequest("auth/login", {
username: identity, password: secret,
code: needsCode ? (filled.code || code) : undefined,
});
if (result.totpRequired) {
setNeedsCode(true);
setCode("");
return;
}
await done();
} catch (error) {
sendToast("Error", error.message);
} finally {
setLoading(false);
}
};
const withPasskey = async () => {
setLoading(true);
try {
await signInWithPasskey(username || undefined);
await done();
} catch (error) {
if (error.name !== "NotAllowedError") sendToast("Error", error.message);
} finally {
setLoading(false);
}
};
const withProvider = async provider => {
try {
const { url } = await postRequest(`auth/oidc/${provider.id}/start`, { next });
window.location.assign(url);
} catch (error) {
sendToast("Error", error.message);
}
};
return (
<form className="login" onSubmit={submit} ref={formRef}>
<div className="form-head">
<h1>{needsCode ? "One more step." : "Welcome back."}</h1>
{needsCode && <p>Enter the code from your authenticator app.</p>}
</div>
<div className="form-body">
{needsCode ? (
<Input id="code" label="Code" value={code} setValue={setCode} inputMode="numeric"
autoComplete="one-time-code" autoFocus required />
) : (
<>
<Input id="username" label="Username" value={username} setValue={setUsername}
autoComplete="username" autoFocus required />
<Input id="password" type="password" label="Password" value={password} setValue={setPassword}
autoComplete="current-password" required />
</>
)}
</div>
<div className="form-actions">
{needsCode
? <Button type="ghost" text="Back" buttonType="button" onClick={() => setNeedsCode(false)} />
: <div />}
<div className="spacer" />
<Button text={loading ? "Signing in" : "Sign in"} buttonType="submit" disabled={loading} />
</div>
{!needsCode && (passkeysSupported() || providers.length > 0) && (
<div className="login-alternatives">
<span className="login-divider">or</span>
{passkeysSupported() && (
<Button type="secondary" icon={Fingerprint} text="Use a passkey" buttonType="button"
onClick={withPasskey} disabled={loading} />
)}
{providers.map(provider => (
<Button key={provider.id} type="secondary" text={`Continue with ${provider.name}`}
buttonType="button" onClick={() => withProvider(provider)} disabled={loading} />
))}
</div>
)}
</form>
);
};
+1
View File
@@ -0,0 +1 @@
export { Login as default } from "./Login.jsx";
+27
View File
@@ -0,0 +1,27 @@
@use "@/common/styles/colors"
.login
width: 100%
.login-alternatives
display: flex
flex-direction: column
gap: 0.5rem
margin-top: 1.5rem
.btn
width: 100%
.login-divider
display: flex
align-items: center
gap: 0.75rem
margin-bottom: 0.25rem
color: colors.$muted
font-size: 0.75rem
&::before, &::after
content: ""
flex: 1
height: 1px
background-color: colors.$border
+39
View File
@@ -0,0 +1,39 @@
import "./styles.sass";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import Input from "@/common/components/Input";
import Button from "@/common/components/Button";
import { useUser } from "@/common/contexts/user.js";
import { resetWorkers } from "@/common/utils/tunnelTab.js";
export const Select = () => {
const { user } = useUser();
const navigate = useNavigate();
const [id, setId] = useState("");
const open = async event => {
event.preventDefault();
const name = id.trim().toLowerCase().replace(/^@/, "");
if (!name) return;
await resetWorkers();
window.location.href = `/@${encodeURIComponent(name)}`;
};
return (
<form className="select-page" onSubmit={open}>
<div className="form-head">
<h1>No tunnel selected.</h1>
<p>Enter a tunnel id to open it in this browser.</p>
</div>
<div className="form-body">
<Input id="tunnel-id" label="Tunnel id" placeholder="k3x9ab" value={id} setValue={setId} autoFocus />
</div>
<div className="form-actions">
<Button type="ghost" text={user ? "Dashboard" : "Admin login"} buttonType="button"
onClick={() => navigate(user ? "/tunnels" : "/login")} />
<div className="spacer" />
<Button text="Open" buttonType="submit" disabled={!id.trim()} />
</div>
</form>
);
};
+1
View File
@@ -0,0 +1 @@
export { Select as default } from "./Select.jsx";
+2
View File
@@ -0,0 +1,2 @@
.select-page
width: 100%
+48
View File
@@ -0,0 +1,48 @@
import "./styles.sass";
import { Suspense } from "react";
import { Navigate, NavLink, Outlet, useLocation } from "react-router-dom";
import { KeyRound, Laptop, Lock, Server, UserRound, Users, Waypoints } from "lucide-react";
import Loading from "@/common/components/Loading";
import { useUser } from "@/common/contexts/user.js";
const TABS = [
{ to: "server", label: "Server", icon: Server, adminOnly: true },
{ to: "forwarding", label: "Forwarding", icon: Waypoints, adminOnly: true },
{ to: "https", label: "HTTPS", icon: Lock, adminOnly: true },
{ to: "accounts", label: "Accounts", icon: Users, adminOnly: true },
{ to: "providers", label: "Providers", icon: KeyRound, adminOnly: true },
{ to: "devices", label: "Devices", icon: Laptop },
{ to: "account", label: "Account", icon: UserRound },
];
export const Settings = () => {
const { user } = useUser();
const { pathname } = useLocation();
const tabs = TABS.filter(tab => !tab.adminOnly || user?.role === "admin");
if (pathname.replace(/\/$/, "").endsWith("/settings")) return <Navigate to={tabs[0].to} replace />;
return (
<div className="page settings">
<div className="page-title">
<h1>Settings</h1>
</div>
<div className="settings-layout">
<nav className="settings-nav">
{tabs.map(({ to, label, icon: Glyph }) => (
<NavLink key={to} to={to}
className={({ isActive }) => `settings-nav-item${isActive ? " active" : ""}`}>
<Glyph size={15} />{label}
</NavLink>
))}
</nav>
<div className="settings-content">
<Suspense fallback={<Loading />}>
<Outlet />
</Suspense>
</div>
</div>
</div>
);
};
+1
View File
@@ -0,0 +1 @@
export { Settings as default } from "./Settings.jsx";
@@ -0,0 +1,98 @@
import { useEffect, useRef, useState } from "react";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import UsageSummary from "@/common/components/UsageSummary";
import { getRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { formValues, useAutofill } from "@/common/utils/autofill.js";
import TwoFactor from "./components/TwoFactor";
import Passkeys from "./components/Passkeys";
export const Account = () => {
const { sendToast } = useToast();
const { setUser } = useUser();
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirm, setConfirm] = useState("");
const [saving, setSaving] = useState(false);
const [quotas, setQuotas] = useState(null);
const formRef = useRef(null);
useEffect(() => {
getRequest("quotas").then(setQuotas).catch(() => null);
}, []);
useAutofill(formRef, filled => {
if (filled["current-password"]) setCurrentPassword(current => current || filled["current-password"]);
});
const submit = async event => {
event.preventDefault();
const filled = formValues(event.currentTarget);
const current = filled["current-password"] || currentPassword;
const next = filled["new-password"] || newPassword;
setCurrentPassword(current);
setNewPassword(next);
if (next.length < 8) return sendToast("Error", "Password must be at least 8 characters");
if (next !== (filled["confirm-password"] || confirm)) return sendToast("Error", "Passwords do not match");
setSaving(true);
try {
await putRequest("settings/password", { currentPassword: current, newPassword: next });
sendToast("Success", "Password changed");
setUser(null);
} catch (error) {
sendToast("Error", error.message);
} finally {
setSaving(false);
}
};
return (
<>
{quotas && (
<section className="settings-panel">
<div className="settings-head">
<h2>Usage</h2>
</div>
<UsageSummary usage={quotas.usage} limits={quotas.limits} />
</section>
)}
<form className="settings-panel" onSubmit={submit} ref={formRef}>
<div className="settings-head">
<h2>Change password</h2>
</div>
<div className="settings-form">
<Input id="current-password" type="password" label="Current" value={currentPassword}
setValue={setCurrentPassword} autoComplete="current-password" required />
<div className="settings-form-row">
<Input id="new-password" type="password" label="New" value={newPassword} setValue={setNewPassword}
autoComplete="new-password" required />
<Input id="confirm-password" type="password" label="Confirm" value={confirm} setValue={setConfirm}
autoComplete="new-password" required />
</div>
</div>
<div className="settings-actions">
<div className="spacer" />
<Button text={saving ? "Saving" : "Change password"} buttonType="submit" disabled={saving} />
</div>
</form>
<section className="settings-panel">
<div className="settings-head">
<h2>Two-factor</h2>
<p>A code from an authenticator app, on top of your password.</p>
</div>
<TwoFactor />
</section>
<section className="settings-panel">
<div className="settings-head">
<h2>Passkeys</h2>
<p>Sign in with your fingerprint, face or security key instead of a password.</p>
</div>
<Passkeys />
</section>
</>
);
};
@@ -0,0 +1,90 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import { Fingerprint, Plus, Trash2 } from "lucide-react";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import { useToast } from "@/common/contexts/toast.js";
import { formatRelative } from "@/common/utils/formatUtils.js";
import { addPasskey, listPasskeys, passkeysSupported, removePasskey } from "@/common/utils/webauthn.js";
export const Passkeys = () => {
const { sendToast } = useToast();
const [passkeys, setPasskeys] = useState(null);
const [name, setName] = useState("");
const [adding, setAdding] = useState(false);
const [removing, setRemoving] = useState(null);
const load = useCallback(async () => {
try {
setPasskeys(await listPasskeys());
} catch (error) {
if (error.code !== 401) sendToast("Error", error.message);
}
}, [sendToast]);
useEffect(() => { load(); }, [load]);
const add = async event => {
event.preventDefault();
setAdding(true);
try {
const result = await addPasskey(name);
sendToast("Success", result.message);
setName("");
await load();
} catch (error) {
if (error.name !== "NotAllowedError") sendToast("Error", error.message);
} finally {
setAdding(false);
}
};
const drop = async () => {
try {
sendToast("Success", (await removePasskey(removing.id)).message);
await load();
} catch (error) {
sendToast("Error", error.message);
}
};
if (!passkeysSupported()) {
return <p className="passkeys-unsupported">This browser cannot use passkeys.</p>;
}
return (
<div className="passkeys">
<ActionConfirmDialog open={!!removing} setOpen={open => !open && setRemoving(null)} onConfirm={drop}
title={`Remove ${removing?.name}?`}
text="That passkey can no longer sign in to this account."
confirmText="Remove" />
{passkeys?.length > 0 && (
<ul className="passkey-list">
{passkeys.map(passkey => (
<li key={passkey.id}>
<Fingerprint size={16} />
<div>
<span className="passkey-name">{passkey.name}</span>
<span className="passkey-meta">
added {formatRelative(passkey.createdAt)}
{passkey.lastUsedAt ? ` · last used ${formatRelative(passkey.lastUsedAt)}` : " · never used"}
</span>
</div>
<button type="button" onClick={() => setRemoving(passkey)} aria-label={`Remove ${passkey.name}`}>
<Trash2 />
</button>
</li>
))}
</ul>
)}
<form className="passkey-add" onSubmit={add}>
<Input id="passkey-name" label="Name" placeholder="This laptop" value={name} setValue={setName} />
<Button icon={Plus} text={adding ? "Waiting" : "Add passkey"} buttonType="submit" type="secondary"
disabled={adding} />
</form>
</div>
);
};
@@ -0,0 +1 @@
export { Passkeys as default } from "./Passkeys.jsx";
@@ -0,0 +1,72 @@
@use "@/common/styles/colors"
.passkeys
display: flex
flex-direction: column
gap: 0.875rem
.passkeys-unsupported
margin: 0
color: colors.$muted
font-size: 0.8125rem
.passkey-list
display: flex
flex-direction: column
gap: 0.5rem
li
display: flex
align-items: center
gap: 0.75rem
padding: 0.625rem 0.875rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.75rem
> svg
flex-shrink: 0
color: colors.$primary
> div
display: flex
flex-direction: column
flex: 1
min-width: 0
> button
display: flex
align-items: center
justify-content: center
width: 2rem
height: 2rem
flex-shrink: 0
background: none
border: none
border-radius: 0.5rem
color: colors.$muted
cursor: pointer
svg
width: 1rem
height: 1rem
&:hover
background-color: colors.$error-tint
color: colors.$error
.passkey-name
font-size: 0.875rem
font-weight: 600
.passkey-meta
color: colors.$muted
font-size: 0.75rem
.passkey-add
display: flex
align-items: flex-end
gap: 0.5rem
.field
flex: 1
@@ -0,0 +1,15 @@
import { useEffect, useState } from "react";
import { toDataURL } from "qrcode";
export const QrCode = ({ value, size = 148 }) => {
const [src, setSrc] = useState(null);
useEffect(() => {
toDataURL(value, { width: size * 2, margin: 1, color: { dark: "#FAFAF9", light: "#00000000" } })
.then(setSrc)
.catch(() => setSrc(null));
}, [value, size]);
if (!src) return <div className="qr-code" style={{ width: size, height: size }} />;
return <img className="qr-code" src={src} width={size} height={size} alt="" />;
};
@@ -0,0 +1,98 @@
import "./styles.sass";
import { useState } from "react";
import { ShieldCheck, ShieldOff } from "lucide-react";
import Button from "@/common/components/Button";
import CopyField from "@/common/components/CopyField";
import Input from "@/common/components/Input";
import { getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { QrCode } from "./QrCode.jsx";
export const TwoFactor = () => {
const { sendToast } = useToast();
const { user, setUser, login } = useUser();
const [setup, setSetup] = useState(null);
const [code, setCode] = useState("");
const [busy, setBusy] = useState(false);
const start = async () => {
try {
setSetup(await getRequest("auth/totp/setup"));
setCode("");
} catch (error) {
sendToast("Error", error.message);
}
};
const enable = async event => {
event.preventDefault();
setBusy(true);
try {
await postRequest("auth/totp/enable", { code });
sendToast("Success", "Two-factor is on. Sign in again to continue.");
setUser(null);
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusy(false);
}
};
const disable = async event => {
event.preventDefault();
setBusy(true);
try {
await postRequest("auth/totp/disable", { code });
sendToast("Success", "Two-factor is off");
setCode("");
await login();
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusy(false);
}
};
if (user?.totpEnabled) {
return (
<form className="two-factor" onSubmit={disable}>
<div className="two-factor-state on">
<ShieldCheck size={16} />
<span>Your account asks for a code when you sign in.</span>
</div>
<div className="two-factor-row">
<Input id="totp-off" label="Code from your app" value={code} setValue={setCode}
inputMode="numeric" autoComplete="one-time-code" required />
<Button type="danger" text="Turn off" buttonType="submit" disabled={busy || code.length < 6} />
</div>
</form>
);
}
return (
<div className="two-factor">
<div className="two-factor-state">
<ShieldOff size={16} />
<span>A password is all your account needs right now.</span>
</div>
{!setup && <Button type="secondary" text="Set up two-factor" onClick={start} />}
{setup && (
<form className="two-factor-setup" onSubmit={enable}>
<QrCode value={setup.url} />
<div className="two-factor-setup-body">
<p>Scan this with your authenticator app, or type the key in by hand.</p>
<CopyField value={setup.secret} secret />
<div className="two-factor-row">
<Input id="totp-on" label="Code from your app" value={code} setValue={setCode}
inputMode="numeric" autoComplete="one-time-code" autoFocus required />
<Button text="Turn on" buttonType="submit" disabled={busy || code.length < 6} />
</div>
</div>
</form>
)}
</div>
);
};
@@ -0,0 +1 @@
export { TwoFactor as default } from "./TwoFactor.jsx";
@@ -0,0 +1,54 @@
@use "@/common/styles/colors"
.two-factor
display: flex
flex-direction: column
align-items: flex-start
gap: 0.875rem
.two-factor-state
display: flex
align-items: center
gap: 0.5rem
color: colors.$subtext
font-size: 0.8125rem
svg
color: colors.$muted
&.on svg
color: colors.$success
.two-factor-setup
display: flex
align-items: flex-start
gap: 1.25rem
width: 100%
padding: 1rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
p
margin: 0 0 0.75rem
color: colors.$subtext
font-size: 0.8125rem
line-height: 1.5
.two-factor-setup-body
flex: 1
min-width: 0
.qr-code
flex-shrink: 0
border-radius: 0.5rem
background-color: colors.$surface-raised
.two-factor-row
display: flex
align-items: flex-end
gap: 0.5rem
margin-top: 0.75rem
.field
flex: 1
@@ -0,0 +1 @@
export { Account as default } from "./Account.jsx";
@@ -0,0 +1,151 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import { Plus, SlidersHorizontal, Trash2, UserRound } from "lucide-react";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import Button from "@/common/components/Button";
import Loading from "@/common/components/Loading";
import Select from "@/common/components/Select";
import QuotaFields, { fromForm, toForm } from "@/common/components/QuotaFields";
import { deleteRequest, getRequest, postRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { formatBytes, formatRelative } from "@/common/utils/formatUtils.js";
import NewAccountDialog from "./components/NewAccountDialog";
import LimitsDialog from "./components/LimitsDialog";
const ROLES = [{ value: "admin", label: "Admin" }, { value: "user", label: "User" }];
export const Accounts = () => {
const { sendToast } = useToast();
const { user } = useUser();
const [accounts, setAccounts] = useState(null);
const [defaults, setDefaults] = useState(null);
const [limits, setLimits] = useState(null);
const [creating, setCreating] = useState(false);
const [deleting, setDeleting] = useState(null);
const [editing, setEditing] = useState(null);
const load = useCallback(async () => {
try {
const data = await getRequest("accounts");
setAccounts(data.accounts);
setDefaults(data.defaults);
setLimits(current => current || toForm(data.defaults));
} catch (error) {
if (error.code !== 401) sendToast("Error", "Could not load accounts");
}
}, [sendToast]);
const saveDefaults = async event => {
event.preventDefault();
try {
const result = await putRequest("quotas", fromForm(limits));
sendToast("Success", result.message);
setDefaults(result.defaults);
setLimits(toForm(result.defaults));
load();
} catch (error) {
sendToast("Error", error.message);
}
};
const saveLimits = async quotas => {
const result = await putRequest(`accounts/${editing.id}`, { quotas });
sendToast("Success", result.message);
load();
};
useEffect(() => { load(); }, [load]);
const create = async values => {
const result = await postRequest("accounts", values);
sendToast("Success", result.message);
load();
};
const changeRole = async (account, role) => {
try {
const result = await putRequest(`accounts/${account.id}`, { role });
sendToast("Success", result.message);
load();
} catch (error) {
sendToast("Error", error.message);
}
};
const remove = async () => {
try {
const result = await deleteRequest(`accounts/${deleting.id}`);
sendToast("Success", result.message);
load();
} catch (error) {
sendToast("Error", error.message);
}
};
return (
<>
{limits && (
<form className="settings-panel" onSubmit={saveDefaults}>
<div className="settings-head">
<h2>Limits</h2>
<p>Per user, 0 for none. Admins are not limited.</p>
</div>
<QuotaFields idPrefix="defaults" values={limits} setValues={setLimits} />
<div className="settings-actions">
<div className="spacer" />
<Button text="Save" buttonType="submit" disabled={JSON.stringify(limits) === JSON.stringify(toForm(defaults))} />
</div>
</form>
)}
<section className="settings-panel">
<NewAccountDialog open={creating} setOpen={setCreating} onCreate={create} />
{editing && <LimitsDialog account={editing} defaults={defaults} onClose={() => setEditing(null)} onSave={saveLimits} />}
<ActionConfirmDialog open={!!deleting} setOpen={open => !open && setDeleting(null)} onConfirm={remove}
title={`Delete ${deleting?.username}?`}
text="Their devices and sessions go with them. Tunnels they have open close when the CLI reconnects."
confirmText="Delete" />
<div className="settings-head">
<h2>Accounts</h2>
<p>Everyone signs in with their own account and sees their own tunnels.</p>
</div>
{!accounts && <Loading />}
{accounts && (
<ul className="account-list">
{accounts.map(account => (
<li key={account.id}>
<div className="account-avatar"><UserRound size={16} /></div>
<div className="account-main">
<span className="account-name">
{account.username}
{account.id === user?.id && <span className="account-you">you</span>}
</span>
<span className="account-meta">
{account.role === "admin" ? `added ${formatRelative(account.createdAt)}`
: `${formatBytes(account.usage.traffic)} this month · ${account.usage.tunnels} ${account.usage.tunnels === 1 ? "tunnel" : "tunnels"}${account.quotas ? " · own limits" : ""}`}
</span>
</div>
<Select options={ROLES} selected={account.role} disabled={account.id === user?.id}
setSelected={role => changeRole(account, role)} />
<button type="button" onClick={() => setEditing(account)} title="Limits" className="account-limits"
disabled={account.role === "admin"} aria-label={`Limits for ${account.username}`}>
<SlidersHorizontal />
</button>
<button type="button" onClick={() => setDeleting(account)} title="Delete"
disabled={account.id === user?.id} aria-label={`Delete ${account.username}`}>
<Trash2 />
</button>
</li>
))}
</ul>
)}
<div className="settings-actions">
<Button text="Add account" icon={Plus} onClick={() => setCreating(true)} />
</div>
</section>
</>
);
};
@@ -0,0 +1,41 @@
import "./styles.sass";
import { useState } from "react";
import { DialogProvider } from "@/common/components/Dialog";
import Button from "@/common/components/Button";
import QuotaFields, { fromForm, toForm } from "@/common/components/QuotaFields";
import { useToast } from "@/common/contexts/toast.js";
export const LimitsDialog = ({ account, defaults, onClose, onSave }) => {
const { sendToast } = useToast();
const [values, setValues] = useState(() => toForm(account.quotas));
const [busy, setBusy] = useState(false);
const submit = async event => {
event.preventDefault();
setBusy(true);
try {
await onSave(fromForm(values));
onClose();
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusy(false);
}
};
return (
<DialogProvider open onClose={onClose}>
<form className="limits" onSubmit={submit}>
<div className="limits-head">
<h2>Limits for {account.username}.</h2>
<p>Empty fields use the defaults.</p>
</div>
<QuotaFields idPrefix="limits" values={values} setValues={setValues} placeholders={toForm(defaults)} />
<div className="limits-actions">
<Button text="Cancel" type="secondary" onClick={onClose} buttonType="button" />
<Button text={busy ? "Saving..." : "Save"} buttonType="submit" disabled={busy} />
</div>
</form>
</DialogProvider>
);
};
@@ -0,0 +1 @@
export { LimitsDialog as default } from "./LimitsDialog.jsx";
@@ -0,0 +1,23 @@
@use "@/common/styles/colors"
.limits
display: flex
flex-direction: column
gap: 1rem
.quota-fields
grid-template-columns: 1fr 1fr
.limits-head
h2
font-size: 1.25rem
p
margin: 0.5rem 0 0
color: colors.$subtext
font-size: 0.8125rem
.limits-actions
display: flex
justify-content: flex-end
gap: 0.5rem
@@ -0,0 +1,59 @@
import "./styles.sass";
import { useState } from "react";
import { DialogProvider } from "@/common/components/Dialog";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import Select from "@/common/components/Select";
import { useToast } from "@/common/contexts/toast.js";
const ROLES = [{ value: "user", label: "User" }, { value: "admin", label: "Admin" }];
export const NewAccountDialog = ({ open, setOpen, onCreate }) => {
const { sendToast } = useToast();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [role, setRole] = useState("user");
const [busy, setBusy] = useState(false);
const close = () => {
setOpen(false);
setUsername("");
setPassword("");
setRole("user");
};
const submit = async event => {
event.preventDefault();
setBusy(true);
try {
await onCreate({ username, password, role });
close();
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusy(false);
}
};
return (
<DialogProvider open={open} onClose={close}>
<form className="new-account" onSubmit={submit}>
<div className="new-account-head">
<h2>New account</h2>
<p>They sign in with these details and can change the password themselves.</p>
</div>
<Input id="new-account-username" label="Username" value={username} setValue={setUsername}
autoComplete="off" autoFocus required />
<Input id="new-account-password" label="Password" type="password" value={password} setValue={setPassword}
autoComplete="new-password" required />
<Select id="new-account-role" label="Role" options={ROLES} selected={role} setSelected={setRole} />
<div className="new-account-actions">
<Button text="Cancel" type="secondary" onClick={close} buttonType="button" />
<Button text={busy ? "Creating..." : "Create"} buttonType="submit" disabled={busy} />
</div>
</form>
</DialogProvider>
);
};
@@ -0,0 +1 @@
export { NewAccountDialog as default } from "./NewAccountDialog.jsx";
@@ -0,0 +1,26 @@
@use "@/common/styles/colors"
.new-account
display: flex
flex-direction: column
gap: 0.875rem
h2
font-size: 1.125rem
p
margin: 0
color: colors.$subtext
font-size: 0.875rem
line-height: 1.5
.new-account-head
display: flex
flex-direction: column
gap: 0.375rem
.new-account-actions
display: flex
justify-content: flex-end
gap: 0.5rem
margin-top: 0.5rem
@@ -0,0 +1 @@
export { Accounts as default } from "./Accounts.jsx";
@@ -0,0 +1,93 @@
@use "@/common/styles/colors"
.account-list
display: flex
flex-direction: column
gap: 0.5rem
li
display: flex
align-items: center
gap: 0.875rem
padding: 0.75rem 0.875rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.75rem
> button
display: flex
align-items: center
justify-content: center
flex-shrink: 0
width: 2rem
height: 2rem
background: none
border: none
border-radius: 0.5rem
color: colors.$muted
cursor: pointer
transition: background-color 0.15s ease, color 0.15s ease
svg
width: 1rem
height: 1rem
&:hover:not(:disabled)
background-color: colors.$error-tint
color: colors.$error
&.account-limits:hover:not(:disabled)
background-color: colors.$surface-hover
color: colors.$text
&:disabled
opacity: 0.3
cursor: not-allowed
.field
width: 8rem
flex-shrink: 0
.account-avatar
display: flex
align-items: center
justify-content: center
width: 2.25rem
height: 2.25rem
flex-shrink: 0
border-radius: 0.625rem
background-color: colors.$primary-tint
color: colors.$primary
.account-main
display: flex
flex-direction: column
gap: 0.125rem
flex: 1
min-width: 0
.account-name
display: flex
align-items: center
gap: 0.5rem
font-size: 0.875rem
font-weight: 600
.account-you
padding: 0.0625rem 0.375rem
border-radius: 0.375rem
background-color: colors.$surface-hover
color: colors.$muted
font-size: 0.6875rem
font-weight: 600
text-transform: uppercase
letter-spacing: 0.04em
.account-meta
color: colors.$muted
font-size: 0.75rem
.settings-actions
display: flex
justify-content: flex-end
margin-top: 1rem
@@ -0,0 +1,158 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import Loading from "@/common/components/Loading";
import Button from "@/common/components/Button";
import CopyField from "@/common/components/CopyField";
import Input from "@/common/components/Input";
import { deleteRequest, getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { formatRelative } from "@/common/utils/formatUtils.js";
import { KeyRound, Laptop, Link, X } from "lucide-react";
export const Devices = () => {
const { sendToast } = useToast();
const { serverInfo } = useUser();
const [devices, setDevices] = useState(null);
const [invites, setInvites] = useState(null);
const [revoking, setRevoking] = useState(null);
const [label, setLabel] = useState("");
const [created, setCreated] = useState(null);
const [keyName, setKeyName] = useState("");
const [createdKey, setCreatedKey] = useState(null);
const load = useCallback(async () => {
try {
const [own, links] = await Promise.all([getRequest("devices"), getRequest("invites")]);
setDevices(own.devices);
setInvites(links.invites);
} catch (error) {
if (error.code !== 401) sendToast("Error", "Could not load devices");
}
}, [sendToast]);
useEffect(() => { load(); }, [load]);
const revoke = async () => {
try {
const result = await deleteRequest(`${revoking.kind}/${revoking.id}`);
sendToast("Success", result.message);
if (revoking.kind === "invites" && created?.invite.id === revoking.id) setCreated(null);
if (revoking.kind === "devices" && createdKey?.device.id === revoking.id) setCreatedKey(null);
load();
} catch (error) {
sendToast("Error", error.message);
}
};
const createKey = async event => {
event.preventDefault();
try {
setCreatedKey(await postRequest("devices", { name: keyName }));
setKeyName("");
load();
} catch (error) {
sendToast("Error", error.message);
}
};
const create = async event => {
event.preventDefault();
try {
setCreated(await postRequest("invites", { label }));
setLabel("");
load();
} catch (error) {
sendToast("Error", error.message);
}
};
return (
<section className="settings-panel">
<ActionConfirmDialog open={!!revoking} setOpen={open => !open && setRevoking(null)} onConfirm={revoke}
title={`Revoke ${revoking?.name}?`}
text="Its tunnels close now and it can no longer open new ones."
confirmText="Revoke" />
<div className="settings-head">
<h2>Devices</h2>
</div>
{!devices && <Loading />}
{devices?.length === 0 && (
<div className="devices-empty"><Laptop size={20} /><p>No devices yet.</p></div>
)}
{devices?.length > 0 && (
<ul className="device-list">
{devices.map(device => (
<li key={device.id}>
{device.kind === "key" && <KeyRound size={16} className="invite-icon" />}
<div className="device-main">
<span className="device-name">{device.name}</span>
<span className="device-meta">
{device.ip || "unknown"} · added {formatRelative(device.createdAt)}
{device.lastUsedAt ? ` · last used ${formatRelative(device.lastUsedAt)}` : " · never used"}
</span>
</div>
<button type="button" onClick={() => setRevoking({ kind: "devices", id: device.id, name: device.name })} title="Revoke"
aria-label={`Revoke ${device.name}`}>
<X />
</button>
</li>
))}
</ul>
)}
<div className="settings-head invites-head">
<h2>API keys</h2>
<p>For servers, CI and scripts. No browser needed.</p>
</div>
<form className="invite-form" onSubmit={createKey}>
<Input id="key-name" placeholder="Where will it run?" value={keyName} setValue={setKeyName} required />
<Button text="Create key" buttonType="submit" />
</form>
{createdKey && (
<div className="invite-created">
<span>Key for {createdKey.device.name}. It is shown only now.</span>
<CopyField value={`frislit login --server ${serverInfo.publicUrl} --token ${createdKey.token}`} />
</div>
)}
<div className="settings-head invites-head">
<h2>Invite links</h2>
<p>Let someone tunnel through this server without an account.</p>
</div>
<form className="invite-form" onSubmit={create}>
<Input id="invite-label" placeholder="Who is this for?" value={label} setValue={setLabel} required />
<Button text="Create link" buttonType="submit" />
</form>
{created && (
<div className="invite-created">
<span>Link for {created.invite.label}. It is shown only now.</span>
<CopyField value={created.link} />
</div>
)}
{invites?.length > 0 && (
<ul className="device-list">
{invites.map(invite => (
<li key={invite.id}>
<Link size={16} className="invite-icon" />
<div className="device-main">
<span className="device-name">{invite.label}</span>
<span className="device-meta">
{invite.owner ? `${invite.owner} · ` : ""}created {formatRelative(invite.createdAt)}
{invite.lastUsedAt ? ` · used ${invite.uses}× · last ${formatRelative(invite.lastUsedAt)}` : " · never used"}
</span>
</div>
<button type="button" onClick={() => setRevoking({ kind: "invites", id: invite.id, name: invite.label })} title="Revoke"
aria-label={`Revoke ${invite.label}`}>
<X />
</button>
</li>
))}
</ul>
)}
</section>
);
};
@@ -0,0 +1 @@
export { Devices as default } from "./Devices.jsx";
@@ -0,0 +1,115 @@
@use "@/common/styles/colors"
.settings-head code
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
color: colors.$primary-bright
.devices-empty
display: flex
flex-direction: column
align-items: center
gap: 0.5rem
svg
color: colors.$muted
opacity: 0.7
padding: 1.5rem 1rem
text-align: center
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.75rem
p
color: colors.$muted
font-size: 0.875rem
.device-list
display: flex
flex-direction: column
gap: 0.375rem
li
display: flex
align-items: center
gap: 0.75rem
padding: 0.625rem 0.5rem 0.625rem 0.875rem
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.75rem
button
display: inline-flex
align-items: center
justify-content: center
flex-shrink: 0
width: 1.75rem
height: 1.75rem
padding: 0
background: none
border: none
border-radius: 0.5rem
color: colors.$muted
cursor: pointer
transition: background-color 0.15s ease, color 0.15s ease
&:hover
background-color: colors.$error-tint
color: colors.$error
svg
width: 1rem
height: 1rem
.device-main
display: flex
flex-direction: column
gap: 0.15rem
min-width: 0
flex: 1
.device-name
font-size: 0.875rem
font-weight: 600
.device-meta
color: colors.$muted
font-size: 0.75rem
overflow: hidden
text-overflow: ellipsis
white-space: nowrap
.invites-head
margin-top: 2rem
p
margin-top: 0.25rem
color: colors.$muted
font-size: 0.8125rem
.invite-form
display: flex
gap: 0.5rem
align-items: flex-end
margin-bottom: 0.75rem
.field
flex: 1
.invite-created
display: flex
flex-direction: column
gap: 0.375rem
margin-bottom: 0.75rem
padding: 0.75rem 0.875rem
background-color: colors.$primary-tint
border: 1px solid colors.$border
border-radius: 0.75rem
> span
color: colors.$subtext
font-size: 0.8125rem
.invite-icon
flex-shrink: 0
color: colors.$muted
@@ -0,0 +1,68 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import Button from "@/common/components/Button";
import Loading from "@/common/components/Loading";
import { ForwardingChoice, ForwardingExplainer } from "@/common/components/ForwardingChoice";
import { getRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
export const Forwarding = () => {
const { sendToast } = useToast();
const [settings, setSettings] = useState(null);
const [mode, setMode] = useState(null);
const [preview, setPreview] = useState(null);
const [saving, setSaving] = useState(false);
const load = useCallback(async () => {
try {
const data = await getRequest("settings");
setSettings(data.settings);
setMode(data.settings.httpMode);
} catch (error) {
if (error.code !== 401) sendToast("Error", "Could not load settings");
}
}, [sendToast]);
useEffect(() => { load(); }, [load]);
if (!settings) return <Loading />;
const shown = preview || mode;
const dirty = mode !== settings.httpMode;
const save = async () => {
setSaving(true);
try {
const response = await putRequest("settings", { ...settings, httpMode: mode });
setSettings(response.settings);
setMode(response.settings.httpMode);
sendToast("Success", "Forwarding mode saved");
} catch (error) {
sendToast("Error", error.message);
} finally {
setSaving(false);
}
};
return (
<div className="settings-panel">
<div className="settings-head">
<h2>Forwarding</h2>
<p>How a web tunnel is reached.</p>
</div>
<ForwardingChoice value={mode} onChange={setMode} onPreview={setPreview} />
<div className="forwarding-preview">
<ForwardingExplainer mode={shown} domain={settings.baseDomain || "frislit.example.com"} />
</div>
<div className="settings-actions">
<div className="spacer" />
<Button type="ghost" text="Reset" buttonType="button" disabled={!dirty || saving}
onClick={() => setMode(settings.httpMode)} />
<Button text={saving ? "Saving" : "Save"} buttonType="button" onClick={save} disabled={!dirty || saving} />
</div>
</div>
);
};
@@ -0,0 +1 @@
export { Forwarding as default } from "./Forwarding.jsx";
@@ -0,0 +1,42 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.forwarding-preview
margin-top: 1rem
padding: 1rem
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.875rem
.mode-explainer
max-width: none
display: grid
grid-template-columns: minmax(0, 21rem) 1fr
column-gap: 1.25rem
align-items: center
.mode-diagram
grid-column: 1
grid-row: 1 / span 2
align-self: center
h3
grid-column: 2
grid-row: 1
align-self: end
margin-top: 0
font-size: 1rem
ul
grid-column: 2
grid-row: 2
align-self: start
margin-top: 0.4rem
@media (max-width: breakpoints.$mobile)
.mode-explainer
grid-template-columns: 1fr
.mode-diagram, h3, ul
grid-column: 1
grid-row: auto
@@ -0,0 +1,143 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import { ShieldCheck } from "lucide-react";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import Loading from "@/common/components/Loading";
import Select from "@/common/components/Select";
import Toggle from "@/common/components/Toggle";
import { TlsChoice, TlsExplainer } from "@/common/components/TlsChoice";
import { getRequest, postRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import CertificatePanel from "./components/CertificatePanel";
const POLL_INTERVAL = 3000;
export const Https = () => {
const { sendToast } = useToast();
const [data, setData] = useState(null);
const [mode, setMode] = useState(null);
const [preview, setPreview] = useState(null);
const [acme, setAcme] = useState({ email: "", provider: "manual", credential: "" });
const [trustProxy, setTrustProxy] = useState(false);
const [pinned, setPinned] = useState(false);
const [saving, setSaving] = useState(false);
const load = useCallback(async (quiet = false) => {
try {
const [tls, settings] = await Promise.all([getRequest("tls"), getRequest("settings")]);
setData(tls);
setTrustProxy(!!settings.settings.trustProxy);
setPinned(settings.sources.tlsMode === "env");
if (!quiet) {
setMode(tls.mode);
setAcme({ ...tls.acme, email: tls.acme.email || "", credential: "" });
}
} catch (error) {
if (error.code !== 401) sendToast("Error", error.message);
}
}, [sendToast]);
useEffect(() => { load(); }, [load]);
useEffect(() => {
if (!data?.status?.busy) return;
const timer = setInterval(() => load(true), POLL_INTERVAL);
return () => clearInterval(timer);
}, [data?.status?.busy, load]);
if (!data || mode === null) return <Loading />;
const managed = mode === "acme";
const provider = data.providers.find(entry => entry.id === acme.provider);
const needsWildcard = data.wildcard;
const save = async () => {
setSaving(true);
try {
await putRequest("settings", { tlsMode: mode, trustProxy: managed ? false : trustProxy });
if (managed) {
const values = { email: acme.email, provider: acme.provider };
if (acme.credential) values.credential = acme.credential;
await putRequest("tls", values);
}
sendToast("Success", managed ? "Saved. Restart frislit to listen on 443." : "Saved");
await load();
} catch (error) {
sendToast("Error", error.message);
} finally {
setSaving(false);
}
};
const verify = async () => {
try {
sendToast("Info", (await postRequest("tls/verify")).message);
} catch (error) {
sendToast("Error", error.message);
}
};
return (
<section className="settings-panel">
<div className="settings-head">
<h2>HTTPS</h2>
<p>Who holds the certificate for {data.status.domains.join(" and ")}.{pinned && <> Set by <code>FRISLIT_TLS_MODE</code>.</>}</p>
</div>
<div className="tls-layout">
<TlsChoice value={mode} onChange={setMode} onPreview={setPreview} disabled={pinned} />
<TlsExplainer mode={preview || mode} />
</div>
{!managed && (
<div className="settings-form tls-section">
<Toggle id="tls-trustProxy" label="Trust proxy headers" checked={trustProxy} onChange={setTrustProxy} />
<p className="tls-note">
Turn this on only when nothing but your proxy can reach the port. The IP allowlist and the login
rate limit both believe whatever address <code>X-Forwarded-For</code> carries.
</p>
</div>
)}
{managed && (
<div className="settings-form tls-section">
<Input id="tls-email" label="Contact email" placeholder="you@example.com" value={acme.email}
setValue={value => setAcme({ ...acme, email: value })} autoComplete="off" />
<Select id="tls-provider" label="Challenge" selected={acme.provider}
setSelected={value => setAcme({ ...acme, provider: value })}
options={data.providers
.filter(entry => !needsWildcard || !entry.httpOnly)
.map(entry => ({ value: entry.id, label: entry.httpOnly ? "HTTP, no DNS provider" : entry.title }))} />
{provider?.needsCredential && (
<>
<Input id="tls-credential" type="password" label={provider.credentialLabel}
placeholder={data.acme.hasCredential ? "Saved, type to replace" : ""}
value={acme.credential} setValue={value => setAcme({ ...acme, credential: value })}
autoComplete="off" />
{data.acme.hasCredential && (
<div className="tls-inline-action">
<Button text="Test token" type="secondary" onClick={verify} />
</div>
)}
</>
)}
{needsWildcard && (
<p className="tls-note">
<ShieldCheck size={13} />
Subdomain forwarding needs the wildcard <code>*.{data.status.domains[0]}</code>, which only a
DNS challenge can prove.
</p>
)}
</div>
)}
<div className="settings-actions">
<div className="spacer" />
<Button text={saving ? "Saving" : "Save"} onClick={save} disabled={saving} />
</div>
{managed && <CertificatePanel status={data.status} onChanged={load} />}
</section>
);
};
@@ -0,0 +1,77 @@
import "./styles.sass";
import { useState } from "react";
import { CircleAlert, CircleCheck, RefreshCw } from "lucide-react";
import Button from "@/common/components/Button";
import CopyField from "@/common/components/CopyField";
import { postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { formatRelative } from "@/common/utils/formatUtils.js";
const STATES = {
none: { tone: "idle", text: "No certificate yet." },
requesting: { tone: "busy", text: "Talking to Let's Encrypt…" },
stale: { tone: "warn", text: "The certificate does not cover every hostname any more." },
expired: { tone: "warn", text: "The certificate has expired." },
error: { tone: "warn", text: "The last request did not work." },
ready: { tone: "ok", text: "Certificate in place." },
};
export const CertificatePanel = ({ status, onChanged }) => {
const { sendToast } = useToast();
const [busy, setBusy] = useState(false);
const state = STATES[status.state] || STATES.none;
const several = status.pendingRecords.length > 1;
const act = async (path, success) => {
setBusy(true);
try {
const result = await postRequest(path);
sendToast("Success", success || result.message);
await onChanged();
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusy(false);
}
};
return (
<div className="certificate">
<div className={`certificate-state ${state.tone}`}>
{state.tone === "ok" ? <CircleCheck size={16} /> : state.tone === "busy"
? <RefreshCw size={16} className="spin" /> : <CircleAlert size={16} />}
<div>
<strong>{state.text}</strong>
{status.certificate && (
<span>{status.certificate.altNames.join(", ")} · renews {formatRelative(status.certificate.expiresAt)}</span>
)}
{status.error && <span className="certificate-error">{status.error}</span>}
</div>
</div>
{status.pendingRecords.length > 0 && (
<div className="certificate-records">
<p>{several
? "Add each of these as its own TXT record at your DNS provider, then continue. Keep both, even on the same name."
: "Add this TXT record at your DNS provider, then continue."}
{" "}Let&apos;s Encrypt checks from the outside, so give it a moment to spread.</p>
{status.pendingRecords.map(record => (
<div className="certificate-record" key={record.value}>
<span>{record.record}</span>
<CopyField value={record.value} />
</div>
))}
<Button text={several ? "I added the records" : "I added the record"} onClick={() => act("tls/continue", "Checking the records")} disabled={busy} />
</div>
)}
{!status.busy && (
<div className="certificate-actions">
<Button icon={RefreshCw} type="secondary" disabled={busy}
text={status.certificate ? "Renew now" : "Request certificate"}
onClick={() => act("tls/request")} />
</div>
)}
</div>
);
};
@@ -0,0 +1 @@
export { CertificatePanel as default } from "./CertificatePanel.jsx";
@@ -0,0 +1,78 @@
@use "@/common/styles/colors"
.certificate
margin-top: 1.5rem
padding-top: 1.25rem
border-top: 1px solid colors.$border
display: flex
flex-direction: column
gap: 1rem
.certificate-state
display: flex
align-items: flex-start
gap: 0.625rem
div
display: flex
flex-direction: column
gap: 0.125rem
strong
font-size: 0.875rem
font-weight: 600
span
color: colors.$muted
font-size: 0.8125rem
&.ok svg
color: colors.$success
&.warn svg
color: colors.$warning
&.busy svg, &.idle svg
color: colors.$muted
.spin
animation: certificate-spin 1.4s linear infinite
.certificate-error
color: colors.$error
.certificate-records
display: flex
flex-direction: column
gap: 0.625rem
padding: 1rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
p
margin: 0
color: colors.$subtext
font-size: 0.8125rem
line-height: 1.5
button
align-self: flex-start
.certificate-record
display: flex
flex-direction: column
gap: 0.25rem
> span
color: colors.$muted
font-size: 0.75rem
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
.certificate-actions
display: flex
justify-content: flex-start
@keyframes certificate-spin
to
transform: rotate(360deg)
@@ -0,0 +1 @@
export { Https as default } from "./Https.jsx";
@@ -0,0 +1,35 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.tls-layout
display: grid
grid-template-columns: 1fr 1fr
gap: 1.5rem
align-items: start
@media (max-width: breakpoints.$tablet)
grid-template-columns: 1fr
.mode-choices
grid-template-columns: 1fr
align-content: start
.tls-section
margin-top: 1.5rem
.tls-note
margin: 0
color: colors.$muted
font-size: 0.8125rem
line-height: 1.55
svg
vertical-align: -0.15em
margin-right: 0.3rem
code
color: colors.$primary
.tls-inline-action
display: flex
justify-content: flex-start
@@ -0,0 +1,96 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import { KeyRound, Plus, Trash2 } from "lucide-react";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import Button from "@/common/components/Button";
import CopyField from "@/common/components/CopyField";
import Loading from "@/common/components/Loading";
import Toggle from "@/common/components/Toggle";
import { deleteRequest, getRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import ProviderDialog from "./components/ProviderDialog";
export const Providers = () => {
const { sendToast } = useToast();
const [data, setData] = useState(null);
const [adding, setAdding] = useState(false);
const [removing, setRemoving] = useState(null);
const load = useCallback(async () => {
try {
setData(await getRequest("oidc"));
} catch (error) {
if (error.code !== 401) sendToast("Error", error.message);
}
}, [sendToast]);
useEffect(() => { load(); }, [load]);
const toggle = async (provider, enabled) => {
try {
await putRequest(`oidc/${provider.id}`, { enabled });
await load();
} catch (error) {
sendToast("Error", error.message);
}
};
const drop = async () => {
try {
sendToast("Success", (await deleteRequest(`oidc/${removing.id}`)).message);
await load();
} catch (error) {
sendToast("Error", error.message);
}
};
if (!data) return <Loading />;
return (
<section className="settings-panel">
<ProviderDialog open={adding} setOpen={setAdding} onSaved={load} />
<ActionConfirmDialog open={!!removing} setOpen={open => !open && setRemoving(null)} onConfirm={drop}
title={`Remove ${removing?.name}?`}
text="Accounts it created stay, but nobody can sign in through it any more."
confirmText="Remove" />
<div className="settings-head">
<h2>Login providers</h2>
<p>Let people sign in with an OpenID Connect provider instead of a frislit password.</p>
</div>
{data.providers.length === 0 && (
<div className="providers-empty"><KeyRound size={20} /><p>No providers yet.</p></div>
)}
{data.providers.length > 0 && (
<ul className="provider-list">
{data.providers.map(provider => (
<li key={provider.id}>
<div className="provider-main">
<span className="provider-name">{provider.name}</span>
<span className="provider-meta">
{provider.issuer} · {provider.createAccounts ? "creates accounts" : "existing accounts only"}
</span>
</div>
<Toggle id={`provider-${provider.id}`} checked={provider.enabled}
onChange={value => toggle(provider, value)} />
<button type="button" onClick={() => setRemoving(provider)} aria-label={`Remove ${provider.name}`}>
<Trash2 />
</button>
</li>
))}
</ul>
)}
<div className="provider-redirect">
<span>Redirect URI to paste into the provider</span>
<CopyField value={data.redirectUri} />
</div>
<div className="settings-actions">
<Button text="Add provider" icon={Plus} onClick={() => setAdding(true)} />
</div>
</section>
);
};
@@ -0,0 +1,69 @@
import "./styles.sass";
import { useState } from "react";
import { DialogProvider } from "@/common/components/Dialog";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import Toggle from "@/common/components/Toggle";
import { postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
const EMPTY = {
name: "", issuer: "", clientId: "", clientSecret: "",
scope: "openid profile email", usernameClaim: "preferred_username", createAccounts: true,
};
export const ProviderDialog = ({ open, setOpen, onSaved }) => {
const { sendToast } = useToast();
const [values, setValues] = useState(EMPTY);
const [busy, setBusy] = useState(false);
const update = (key, value) => setValues({ ...values, [key]: value });
const close = () => {
setOpen(false);
setValues(EMPTY);
};
const submit = async event => {
event.preventDefault();
setBusy(true);
try {
sendToast("Success", (await postRequest("oidc", values)).message);
close();
await onSaved();
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusy(false);
}
};
return (
<DialogProvider open={open} onClose={close}>
<form className="provider-dialog" onSubmit={submit}>
<div className="provider-dialog-head">
<h2>Add a provider</h2>
<p>Anything that speaks OpenID Connect: Authentik, Keycloak, Entra, Google.</p>
</div>
<Input id="provider-name" label="Name" placeholder="Authentik" value={values.name}
setValue={value => update("name", value)} autoFocus required />
<Input id="provider-issuer" label="Issuer URL" placeholder="https://id.example.com/application/o/frislit/"
value={values.issuer} setValue={value => update("issuer", value)} required />
<Input id="provider-client" label="Client ID" value={values.clientId}
setValue={value => update("clientId", value)} autoComplete="off" required />
<Input id="provider-secret" type="password" label="Client secret" value={values.clientSecret}
setValue={value => update("clientSecret", value)} autoComplete="new-password" />
<Input id="provider-claim" label="Username claim" value={values.usernameClaim}
setValue={value => update("usernameClaim", value)} />
<Toggle id="provider-create" label="Create an account on first sign-in" checked={values.createAccounts}
onChange={value => update("createAccounts", value)} />
<div className="provider-dialog-actions">
<Button text="Cancel" type="secondary" onClick={close} buttonType="button" />
<Button text={busy ? "Adding" : "Add"} buttonType="submit" disabled={busy} />
</div>
</form>
</DialogProvider>
);
};
@@ -0,0 +1 @@
export { ProviderDialog as default } from "./ProviderDialog.jsx";
@@ -0,0 +1,26 @@
@use "@/common/styles/colors"
.provider-dialog
display: flex
flex-direction: column
gap: 0.875rem
h2
font-size: 1.125rem
p
margin: 0
color: colors.$subtext
font-size: 0.875rem
line-height: 1.5
.provider-dialog-head
display: flex
flex-direction: column
gap: 0.375rem
.provider-dialog-actions
display: flex
justify-content: flex-end
gap: 0.5rem
margin-top: 0.5rem
@@ -0,0 +1 @@
export { Providers as default } from "./Providers.jsx";
@@ -0,0 +1,81 @@
@use "@/common/styles/colors"
.providers-empty
display: flex
flex-direction: column
align-items: center
gap: 0.5rem
padding: 2rem 1rem
border: 1px dashed colors.$border-strong
border-radius: 0.875rem
svg
color: colors.$muted
opacity: 0.7
p
margin: 0
color: colors.$subtext
font-size: 0.875rem
.provider-list
display: flex
flex-direction: column
gap: 0.5rem
li
display: flex
align-items: center
gap: 0.875rem
padding: 0.75rem 0.875rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.75rem
> button
display: flex
align-items: center
justify-content: center
width: 2rem
height: 2rem
flex-shrink: 0
background: none
border: none
border-radius: 0.5rem
color: colors.$muted
cursor: pointer
svg
width: 1rem
height: 1rem
&:hover
background-color: colors.$error-tint
color: colors.$error
.provider-main
display: flex
flex-direction: column
flex: 1
min-width: 0
.provider-name
font-size: 0.875rem
font-weight: 600
.provider-meta
overflow: hidden
text-overflow: ellipsis
white-space: nowrap
color: colors.$muted
font-size: 0.75rem
.provider-redirect
display: flex
flex-direction: column
gap: 0.375rem
margin-top: 1.25rem
> span
color: colors.$muted
font-size: 0.75rem
@@ -0,0 +1,59 @@
import { useCallback, useEffect, useState } from "react";
import Button from "@/common/components/Button";
import Loading from "@/common/components/Loading";
import ServerSettingsForm, { normalizeSettings } from "@/common/components/ServerSettingsForm";
import { getRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
export const Server = () => {
const { sendToast } = useToast();
const [saved, setSaved] = useState(null);
const [values, setValues] = useState(null);
const [saving, setSaving] = useState(false);
const load = useCallback(async () => {
try {
const data = await getRequest("settings");
setSaved(data.settings);
setValues(data.settings);
} catch (error) {
if (error.code !== 401) sendToast("Error", "Could not load settings");
}
}, [sendToast]);
useEffect(() => { load(); }, [load]);
if (!values) return <Loading />;
const dirty = JSON.stringify(normalizeSettings(values)) !== JSON.stringify(normalizeSettings(saved));
const save = async event => {
event.preventDefault();
setSaving(true);
try {
const response = await putRequest("settings", normalizeSettings(values));
setSaved(response.settings);
setValues(response.settings);
sendToast("Success", "Settings saved");
} catch (error) {
sendToast("Error", error.message);
} finally {
setSaving(false);
}
};
return (
<form className="settings-panel" onSubmit={save}>
<div className="settings-head">
<h2>Server</h2>
</div>
<ServerSettingsForm values={values} setValues={setValues} showHttpMode={false} />
<div className="settings-actions">
<div className="spacer" />
<Button type="ghost" text="Reset" buttonType="button" disabled={!dirty || saving}
onClick={() => setValues(saved)} />
<Button text={saving ? "Saving" : "Save"} buttonType="submit" disabled={!dirty || saving} />
</div>
</form>
);
};
@@ -0,0 +1 @@
export { Server as default } from "./Server.jsx";
+82
View File
@@ -0,0 +1,82 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.settings-layout
display: grid
grid-template-columns: 11rem 1fr
gap: 1.5rem
align-items: start
@media (max-width: breakpoints.$tablet)
grid-template-columns: 1fr
gap: 1rem
.settings-nav
display: flex
flex-direction: column
gap: 0.125rem
position: sticky
top: 1.5rem
@media (max-width: breakpoints.$tablet)
position: static
flex-direction: row
overflow-x: auto
padding-bottom: 0.25rem
.settings-nav-item
display: flex
align-items: center
gap: 0.5rem
padding: 0.45rem 0.75rem
border-radius: 0.625rem
color: colors.$muted
font-size: 0.875rem
font-weight: 500
text-decoration: none
white-space: nowrap
transition: background-color 0.15s ease, color 0.15s ease
&:hover
color: colors.$text
background-color: colors.$surface
&.active
color: colors.$text
background-color: colors.$surface-hover
.settings-content
min-width: 0
max-width: 42rem
.settings-panel
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
padding: 1.25rem
.settings-head
margin-bottom: 1.25rem
h2
font-size: 1.0625rem
font-weight: 600
letter-spacing: -0.02em
p
margin-top: 0.2rem
color: colors.$muted
font-size: 0.8125rem
line-height: 1.55
.settings-actions
display: flex
align-items: center
gap: 0.5rem
margin-top: 1.25rem
.spacer
flex: 1
.settings-content > .settings-panel + .settings-panel
margin-top: 1.25rem
+79
View File
@@ -0,0 +1,79 @@
import "./styles.sass";
import { useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import Loading from "@/common/components/Loading";
import { getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { normalizeSettings } from "@/common/components/ServerSettingsForm";
import WelcomeStep from "./components/WelcomeStep";
import AccountStep from "./components/AccountStep";
import ForwardingStep from "./components/ForwardingStep";
import HttpsStep from "./components/HttpsStep";
import ServerStep from "./components/ServerStep";
import DoneStep from "./components/DoneStep";
const STEPS = ["Welcome", "Account", "Forwarding", "HTTPS", "Server", "Done"];
const LAST_EDITABLE = 4;
export const Setup = () => {
const { sendToast } = useToast();
const { setupRequired, setSetupRequired, login } = useUser();
const navigate = useNavigate();
const [settings, setSettings] = useState(null);
const [sources, setSources] = useState({});
const [step, setStep] = useState(0);
const [account, setAccount] = useState({ username: "", password: "", confirm: "" });
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
getRequest("setup/status")
.then(data => { setSettings(data.settings); setSources(data.sources); })
.catch(error => sendToast("Error", error.message));
}, [sendToast]);
if (!setupRequired) return <Navigate to="/tunnels" replace />;
if (!settings) return <Loading />;
const complete = async () => {
setSubmitting(true);
try {
await postRequest("setup/complete", {
username: account.username,
password: account.password,
settings: normalizeSettings(settings),
});
await login();
setStep(5);
} catch (error) {
sendToast("Error", error.message);
} finally {
setSubmitting(false);
}
};
const finish = () => {
setSetupRequired(false);
navigate("/tunnels", { replace: true });
};
return (
<div className="setup">
<div className="setup-rail">
{STEPS.map((title, index) => (
<button type="button" key={title} aria-label={title} aria-current={index === step}
className={`setup-rail-dot${index === step ? " active" : ""}${index < step ? " done" : ""}`}
disabled={index >= Math.min(step, LAST_EDITABLE)}
onClick={() => setStep(index)} />
))}
</div>
{step === 0 && <WelcomeStep onNext={() => setStep(1)} />}
{step === 1 && <AccountStep account={account} setAccount={setAccount} onBack={() => setStep(0)} onNext={() => setStep(2)} />}
{step === 2 && <ForwardingStep settings={settings} setSettings={setSettings} onBack={() => setStep(1)} onNext={() => setStep(3)} />}
{step === 3 && <HttpsStep settings={settings} setSettings={setSettings} pinned={sources.tlsMode === "env"} onBack={() => setStep(2)} onNext={() => setStep(4)} />}
{step === 4 && <ServerStep settings={settings} setSettings={setSettings} onBack={() => setStep(3)} onNext={complete} submitting={submitting} />}
{step === 5 && <DoneStep username={account.username} onFinish={finish} />}
</div>
);
};
@@ -0,0 +1,52 @@
import { useRef } from "react";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import { useToast } from "@/common/contexts/toast.js";
import { formValues, useAutofill } from "@/common/utils/autofill.js";
export const AccountStep = ({ account, setAccount, onBack, onNext }) => {
const { sendToast } = useToast();
const formRef = useRef(null);
const update = (key, value) => setAccount({ ...account, [key]: value });
useAutofill(formRef, filled => setAccount(current => ({
username: current.username || filled["setup-username"] || "",
password: current.password || filled["setup-password"] || "",
confirm: current.confirm || filled["setup-confirm"] || "",
})));
const submit = event => {
event.preventDefault();
const filled = formValues(event.currentTarget);
const username = filled["setup-username"] || account.username;
const password = filled["setup-password"] || account.password;
const confirm = filled["setup-confirm"] || account.confirm;
setAccount({ username, password, confirm });
if (!/^[a-zA-Z0-9._-]{3,32}$/.test(username)) return sendToast("Error", "Username must be 3-32 characters");
if (password.length < 8) return sendToast("Error", "Password must be at least 8 characters");
if (password !== confirm) return sendToast("Error", "Passwords do not match");
onNext();
};
return (
<form onSubmit={submit} ref={formRef}>
<div className="form-head">
<h1>Admin account.</h1>
<p>Signs you in to this dashboard.</p>
</div>
<div className="form-body">
<Input id="setup-username" label="Username" value={account.username} setValue={value => update("username", value)}
autoComplete="username" autoFocus required />
<Input id="setup-password" type="password" label="Password" value={account.password}
setValue={value => update("password", value)} autoComplete="new-password" required />
<Input id="setup-confirm" type="password" label="Confirm password" value={account.confirm}
setValue={value => update("confirm", value)} autoComplete="new-password" required />
</div>
<div className="form-actions">
<Button type="ghost" text="Back" onClick={onBack} buttonType="button" />
<div className="spacer" />
<Button text="Continue" buttonType="submit" />
</div>
</form>
);
};
@@ -0,0 +1 @@
export { AccountStep as default } from "./AccountStep.jsx";
@@ -0,0 +1,20 @@
import Button from "@/common/components/Button";
import { Check } from "lucide-react";
export const DoneStep = ({ username, onFinish }) => {
return (
<>
<div className="setup-done">
<div className="setup-done-icon"><Check /></div>
<div className="form-head">
<h1>All set, {username}.</h1>
<p>Your tunnels show up on the dashboard. Run <code>frislit login</code> on a machine to link it.</p>
</div>
</div>
<div className="form-actions">
<div className="spacer" />
<Button text="Open dashboard" onClick={onFinish} />
</div>
</>
);
};
@@ -0,0 +1 @@
export { DoneStep as default } from "./DoneStep.jsx";
@@ -0,0 +1,36 @@
import { useEffect, useState } from "react";
import Button from "@/common/components/Button";
import { ForwardingChoice, ForwardingExplainer } from "@/common/components/ForwardingChoice";
import { usePublicAside } from "@/common/layouts/aside.js";
export const ForwardingStep = ({ settings, setSettings, onBack, onNext }) => {
const selected = settings.httpMode || "subdomain";
const domain = settings.baseDomain?.trim() || "frislit.example.com";
const [preview, setPreview] = useState(null);
const shown = preview || selected;
const setAside = usePublicAside();
useEffect(() => {
setAside(<ForwardingExplainer mode={shown} domain={domain} />);
return () => setAside(null);
}, [setAside, shown, domain]);
return (
<div>
<div className="form-head">
<h1>Forwarding.</h1>
<p>How a web tunnel is reached. This can be changed later.</p>
</div>
<ForwardingChoice value={selected} onPreview={setPreview}
onChange={mode => setSettings({ ...settings, httpMode: mode })} />
<div className="mode-explainer-inline"><ForwardingExplainer mode={shown} domain={domain} /></div>
<div className="form-actions">
<Button type="ghost" text="Back" onClick={onBack} buttonType="button" />
<div className="spacer" />
<Button text="Continue" buttonType="button" onClick={onNext} />
</div>
</div>
);
};
@@ -0,0 +1 @@
export { ForwardingStep as default } from "./ForwardingStep.jsx";
@@ -0,0 +1,60 @@
import { useEffect, useState } from "react";
import Button from "@/common/components/Button";
import Toggle from "@/common/components/Toggle";
import { TlsChoice, TlsExplainer } from "@/common/components/TlsChoice";
import { usePublicAside } from "@/common/layouts/aside.js";
export const HttpsStep = ({ settings, setSettings, pinned, onBack, onNext }) => {
const selected = settings.tlsMode || "proxy";
const [preview, setPreview] = useState(null);
const shown = preview || selected;
const wildcard = (settings.httpMode || "subdomain") === "subdomain";
const domain = settings.baseDomain?.trim() || "frislit.example.com";
const setAside = usePublicAside();
useEffect(() => {
setAside(<TlsExplainer mode={shown} />);
return () => setAside(null);
}, [setAside, shown]);
return (
<div>
<div className="form-head">
<h1>HTTPS.</h1>
<p>{pinned ? <>Set by <code>FRISLIT_TLS_MODE</code> when the server was started.</> : "Who holds the certificate. Switching later needs a restart."}</p>
</div>
<TlsChoice value={selected} onPreview={setPreview} disabled={pinned}
onChange={mode => setSettings({ ...settings, tlsMode: mode })} />
<div className="mode-explainer-inline"><TlsExplainer mode={shown} /></div>
{selected === "proxy" ? (
<div className="setup-note">
<Toggle id="setup-trustProxy" label="Trust proxy headers" checked={!!settings.trustProxy}
onChange={value => setSettings({ ...settings, trustProxy: value })} />
<p>
Turn this on once only your proxy can reach the port. The reverse proxy guide in the
documentation has an nginx config you can paste.
</p>
</div>
) : (
<div className="setup-note">
<p>
frislit will ask Let&apos;s Encrypt for a certificate
{wildcard ? <> covering <code>{domain}</code> and <code>*.{domain}</code></> : <> for <code>{domain}</code></>}.
{wildcard
? " A wildcard needs a DNS challenge, so have an API token for your DNS provider ready."
: " Point the domain at this machine and it can use an HTTP challenge, no DNS token needed."}
</p>
<p>Finish the setup first, then request the certificate on the HTTPS settings page.</p>
</div>
)}
<div className="form-actions">
<Button type="ghost" text="Back" onClick={onBack} buttonType="button" />
<div className="spacer" />
<Button text="Continue" buttonType="button" onClick={onNext} />
</div>
</div>
);
};
@@ -0,0 +1 @@
export { HttpsStep as default } from "./HttpsStep.jsx";
@@ -0,0 +1,28 @@
import Button from "@/common/components/Button";
import ServerSettingsForm from "@/common/components/ServerSettingsForm";
import { useToast } from "@/common/contexts/toast.js";
export const ServerStep = ({ settings, setSettings, onBack, onNext, submitting }) => {
const { sendToast } = useToast();
const submit = event => {
event.preventDefault();
if (!settings.baseDomain.trim()) return sendToast("Error", "Base domain is required");
onNext();
};
return (
<form onSubmit={submit}>
<div className="form-head">
<h1>Server.</h1>
<p>You can change all of this later.</p>
</div>
<ServerSettingsForm values={settings} setValues={setSettings} idPrefix="setup" showHttpMode={false} />
<div className="form-actions">
<Button type="ghost" text="Back" onClick={onBack} buttonType="button" disabled={submitting} />
<div className="spacer" />
<Button text={submitting ? "Saving" : "Continue"} buttonType="submit" disabled={submitting} />
</div>
</form>
);
};
@@ -0,0 +1 @@
export { ServerStep as default } from "./ServerStep.jsx";
@@ -0,0 +1,22 @@
import Button from "@/common/components/Button";
import { Server, ShieldCheck, Waypoints } from "lucide-react";
export const WelcomeStep = ({ onNext }) => {
return (
<>
<div className="form-head">
<h1>Welcome.</h1>
<p>Three things and your tunnel server is ready.</p>
</div>
<ul className="setup-list">
<li><ShieldCheck />Admin account</li>
<li><Waypoints />Forwarding mode</li>
<li><Server />Server settings</li>
</ul>
<div className="form-actions">
<div className="spacer" />
<Button text="Get started" onClick={onNext} />
</div>
</>
);
};
@@ -0,0 +1 @@
export { WelcomeStep as default } from "./WelcomeStep.jsx";
+1
View File
@@ -0,0 +1 @@
export { Setup as default } from "./Setup.jsx";
+94
View File
@@ -0,0 +1,94 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.setup
width: 100%
.setup-rail
display: flex
align-items: center
gap: 0.375rem
margin-bottom: 2rem
.setup-rail-dot
width: 0.375rem
height: 0.375rem
padding: 0
flex-shrink: 0
background-color: colors.$border-strong
border: none
border-radius: 999px
cursor: default
transition: width 0.2s ease, background-color 0.2s ease
&.done
background-color: colors.$primary-deep
cursor: pointer
&:hover
background-color: colors.$primary
&.active
width: 1.125rem
background-color: colors.$primary
&:focus-visible
outline: 2px solid colors.$primary
outline-offset: 3px
.setup-list
display: flex
flex-direction: column
gap: 0.625rem
li
display: flex
align-items: center
gap: 0.625rem
color: colors.$subtext
font-size: 0.875rem
svg
width: 1rem
height: 1rem
flex-shrink: 0
color: colors.$primary
.setup-done
display: flex
flex-direction: column
gap: 0.75rem
.setup-done-icon
display: flex
align-items: center
justify-content: center
width: 2.5rem
height: 2.5rem
border-radius: 0.875rem
background-color: colors.$success-tint
color: colors.$success
margin-bottom: 0.5rem
svg
width: 1.375rem
height: 1.375rem
.setup-note
display: flex
flex-direction: column
gap: 0.625rem
margin-top: 1.25rem
padding: 1rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
p
margin: 0
color: colors.$subtext
font-size: 0.8125rem
line-height: 1.5
code
color: colors.$primary
+112
View File
@@ -0,0 +1,112 @@
import "./styles.sass";
import { useEffect, useRef, useState } from "react";
import Button from "@/common/components/Button";
import Gate from "@/pages/Gate";
import { getRequest } from "@/common/utils/RequestUtil.js";
import { bindTab, readTab, rememberTab } from "@/common/utils/tunnelTab.js";
const POLL_INTERVAL = 2000;
const BIND_TIMEOUT = 2000;
const BLOCKED = {
address: "This tunnel does not accept requests from your address.",
country: "This tunnel does not accept requests from your country.",
tor: "This tunnel does not accept requests from Tor exit nodes.",
vpn: "This tunnel does not accept requests from VPN services.",
datacenter: "This tunnel does not accept requests from datacenters.",
blocklist: "This tunnel does not accept requests from blocklisted addresses.",
};
export const Status = ({ kind, id, to, auth, authorize, ip, reason }) => {
const target = to || new URLSearchParams(window.location.search).get("to") || "/";
const [failed, setFailed] = useState(false);
const started = useRef(false);
useEffect(() => {
if (started.current) return;
started.current = true;
if (kind === "attach" || kind === "reattach") {
const tunnel = kind === "attach" ? id : readTab();
if (!tunnel) {
window.location.replace("/@frislit/select");
return;
}
rememberTab(tunnel);
let done = false;
const go = () => {
if (done) return;
done = true;
window.location.replace(target);
};
bindTab(tunnel).then(go).catch(() => setFailed(true));
const timer = setTimeout(go, BIND_TIMEOUT);
return () => clearTimeout(timer);
}
if (kind === "offline") {
const timer = setInterval(async () => {
try {
const status = await getRequest(`status/${encodeURIComponent(id)}`);
if (status.online) window.location.reload();
if (!status.exists) setFailed(true);
} catch { /* keep waiting, the server may be restarting too */ }
}, POLL_INTERVAL);
return () => clearInterval(timer);
}
}, [kind, id, target]);
if (kind === "gate") return <Gate id={id} auth={auth} authorize={authorize} />;
if (kind === "blocked") {
return (
<div className="status-page">
<div className="form-head">
<h1>Not allowed.</h1>
<p>{BLOCKED[reason]}{ip ? <> Your address is <code>{ip}</code>.</> : null}</p>
</div>
</div>
);
}
if (kind === "attach" || kind === "reattach") {
return (
<div className="status-page">
<div className="form-head">
<h1>{failed ? "Could not open this tunnel." : "Opening…"}</h1>
<p>{failed
? "This browser could not start the tunnel router. Path mode needs HTTPS or localhost."
: <>Attaching this tab to <code>{id || readTab()}</code>.</>}</p>
</div>
{failed && <div className="form-actions">
<Button text="Choose a tunnel" buttonType="button" onClick={() => window.location.replace("/@frislit/select")} />
</div>}
</div>
);
}
if (kind === "offline") {
return (
<div className="status-page">
<div className="form-head">
<h1>{failed ? "Tunnel closed." : "Reconnecting…"}</h1>
<p>{failed
? <>The tunnel <code>{id}</code> is gone.</>
: <>The client for <code>{id}</code> is disconnected. This page continues by itself once it is back.</>}</p>
</div>
<div className="status-wait">{!failed && <span className="status-spinner" />}</div>
</div>
);
}
return (
<div className="status-page">
<div className="form-head">
<h1>Tunnel not found.</h1>
<p>There is no tunnel called <code>{id}</code>. It may have been closed, or the id was mistyped.</p>
</div>
<div className="form-actions">
<Button text="Choose a tunnel" buttonType="button" onClick={() => window.location.replace("/@frislit/select")} />
</div>
</div>
);
};
+1
View File
@@ -0,0 +1 @@
export { Status as default } from "./Status.jsx";
+30
View File
@@ -0,0 +1,30 @@
@use "@/common/styles/colors"
.status-page
width: 100%
code
font-family: ui-monospace, SFMono-Regular, Menlo, monospace
font-size: 0.85em
color: var(--primary-bright)
background: var(--surface-raised)
border: 1px solid var(--border)
border-radius: 0.375rem
padding: 0.1rem 0.35rem
.status-wait
display: flex
align-items: center
min-height: 2rem
.status-spinner
width: 1.1rem
height: 1.1rem
border: 2px solid var(--border-strong)
border-top-color: var(--primary-bright)
border-radius: 50%
animation: status-spin 0.9s linear infinite
@keyframes status-spin
to
transform: rotate(360deg)
@@ -0,0 +1,249 @@
import "./styles.sass";
import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Button from "@/common/components/Button";
import CopyField from "@/common/components/CopyField";
import OpenInFrislit from "@/common/components/OpenInFrislit";
import Loading from "@/common/components/Loading";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import { deleteRequest, getRequest, postRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { formatCountdown, formatRelative } from "@/common/utils/formatUtils.js";
import TrafficTable from "./components/TrafficTable";
import VisitorsTable from "./components/VisitorsTable";
import ConnectionsTable from "./components/ConnectionsTable";
import AccessSection from "./components/AccessSection";
import DomainsSection from "./components/DomainsSection";
import StatsPanel from "./components/StatsPanel";
import { ArrowLeft, Bookmark, BookmarkX, ExternalLink, X } from "lucide-react";
const POLL_INTERVAL = 2000;
const stateOf = (live, now) => {
if (!live) return ["dormant", "Offline"];
if (live.online) return ["online", "Online"];
return ["offline", `Reconnecting · closes in ${formatCountdown(live.graceUntil, now)}`];
};
export const TunnelDetail = () => {
const { id } = useParams();
const navigate = useNavigate();
const { sendToast } = useToast();
const [data, setData] = useState(null);
const [definition, setDefinition] = useState(null);
const [checked, setChecked] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [closing, setClosing] = useState(false);
const [busyMode, setBusyMode] = useState(false);
const [releasing, setReleasing] = useState(false);
const [disconnecting, setDisconnecting] = useState(null);
const [view, setView] = useState("traffic");
const [focus, setFocus] = useState("");
const tunnelRef = useRef(null);
const load = useCallback(async () => {
try {
const response = await getRequest(`tunnels/${id}`);
tunnelRef.current = response.tunnel;
setData(response);
setNow(Date.now());
} catch (error) {
if (error.code === 401) return;
if (error.code !== 404) return sendToast("Error", "Could not load the tunnel");
tunnelRef.current = null;
setData(null);
}
}, [id, sendToast]);
const loadDefinition = useCallback(async () => {
if (tunnelRef.current && !tunnelRef.current.persistent) return setDefinition(null);
try {
setDefinition((await getRequest(`persistent/${id}`)).tunnel);
} catch (error) {
if (error.code === 404) setDefinition(null);
}
}, [id]);
useEffect(() => {
const refresh = async () => {
await load();
await loadDefinition();
setChecked(true);
};
refresh();
const poll = setInterval(refresh, POLL_INTERVAL);
const tick = setInterval(() => setNow(Date.now()), 1000);
return () => { clearInterval(poll); clearInterval(tick); };
}, [load, loadDefinition]);
const live = data?.tunnel || null;
const persistent = live ? live.persistent : !!definition;
const close = async () => {
try {
await deleteRequest(`tunnels/${id}`);
sendToast("Success", `Closed ${id}`);
if (!persistent) navigate("/tunnels");
} catch (error) {
sendToast("Error", error.message);
}
};
const keep = async () => {
try {
const result = await postRequest("persistent", { name: id });
sendToast("Success", result.message);
await load();
await loadDefinition();
} catch (error) {
sendToast("Error", error.message);
}
};
const release = async () => {
try {
const result = await deleteRequest(`persistent/${id}`);
sendToast("Success", result.message);
setDefinition(null);
if (!live) navigate("/tunnels");
else load();
} catch (error) {
sendToast("Error", error.message);
}
};
const changeMode = async mode => {
if (busyMode || mode === tunnel.mode) return;
setBusyMode(true);
try {
const result = await putRequest(`tunnels/${id}/mode`, { mode });
sendToast("Success", `${result.message} · ${result.url}`);
await load();
} catch (error) {
sendToast("Error", error.message);
} finally {
setBusyMode(false);
}
};
const disconnect = async () => {
const path = disconnecting === "all" ? `tunnels/${id}/clients` : `tunnels/${id}/clients/${disconnecting.id}`;
try {
const result = await deleteRequest(path);
sendToast("Success", result.message);
load();
} catch (error) {
sendToast("Error", error.message);
}
};
if (checked && !live && !definition) {
return (
<div className="page">
<div className="detail-gone">
<h1>Tunnel closed.</h1>
<p>There is no tunnel called <code>{id}</code> any more.</p>
<Button text="Back to tunnels" buttonType="button" onClick={() => navigate("/tunnels")} />
</div>
</div>
);
}
if (!live && !definition) return <div className="page"><Loading /></div>;
const tunnel = live || {
id: definition.name,
mode: "http",
url: definition.url,
online: false,
access: definition.access,
persistent: true,
};
const isHttp = tunnel.mode !== "tcp";
const heading = (
<div className="detail-views" role="tablist">
<button type="button" role="tab" aria-selected={view === "traffic"} className={view === "traffic" ? "active" : ""}
onClick={() => setView("traffic")}>{isHttp ? "Traffic" : "Clients"}</button>
<button type="button" role="tab" aria-selected={view === "visitors"} className={view === "visitors" ? "active" : ""}
onClick={() => setView("visitors")}>Visitors</button>
</div>
);
const domains = definition?.domains || [];
const [state, stateLabel] = stateOf(live, now);
return (
<div className="page">
<ActionConfirmDialog open={closing} setOpen={setClosing} onConfirm={close}
title={`Close ${tunnel.id}?`} text="The CLI and all visitors will be disconnected."
confirmText="Close" />
<ActionConfirmDialog open={releasing} setOpen={setReleasing} onConfirm={release}
title={`Release ${tunnel.id}?`}
text="The name becomes free again and its domains are removed."
confirmText="Release" />
<ActionConfirmDialog open={!!disconnecting} setOpen={open => !open && setDisconnecting(null)}
onConfirm={disconnect}
title={disconnecting === "all" ? "Disconnect every client?" : `Disconnect ${disconnecting?.ip}?`}
text="Their open connections drop immediately. They can connect again with the same share code."
confirmText="Disconnect" />
<button type="button" className="detail-back" onClick={() => navigate("/tunnels")}>
<ArrowLeft />Tunnels
</button>
<header className="detail-head">
<div className="detail-heading">
<h1>{tunnel.id}{persistent && <Bookmark className="detail-pin" aria-label="Persistent" />}
{isHttp && <span className={`detail-mode ${tunnel.mode}`}>{tunnel.mode === "subdomain" ? "subdomain" : "path"}</span>}
</h1>
<p className="detail-sub">
<span className={`detail-dot ${state}`} />
{stateLabel}
{live && <span className="mono"> · {tunnel.target}</span>}
{live && ` · started ${formatRelative(tunnel.createdAt)}`}
</p>
</div>
<div className="detail-actions">
{live && isHttp && (
<div className="mode-switch" role="group" aria-label="Forwarding style">
{["path", "subdomain"].map(option => (
<button key={option} type="button" disabled={busyMode}
className={tunnel.mode === option ? "active" : ""}
onClick={() => changeMode(option)}>
{option === "path" ? "Path" : "Subdomain"}
</button>
))}
</div>
)}
{live && tunnel.url && <Button type="ghost" icon={ExternalLink} title="Open"
onClick={() => window.open(tunnel.url, "_blank", "noopener")} />}
{persistent
? <Button type="ghost" icon={BookmarkX} title="Release this name" onClick={() => setReleasing(true)} />
: <Button type="ghost" icon={Bookmark} title="Keep this name" onClick={keep} />}
{live && <Button type="danger" icon={X} title="Close tunnel" onClick={() => setClosing(true)} />}
</div>
</header>
{live
? <CopyField value={tunnel.url || tunnel.shareCode} secret={!tunnel.url} />
: <CopyField value={`frislit http 3000 --name ${tunnel.id}`} />}
{live?.shareCode && <div className="detail-open"><OpenInFrislit href={`frislit://connect/${encodeURIComponent(tunnel.shareCode)}?server=${encodeURIComponent(window.location.origin)}`} /></div>}
<AccessSection tunnel={tunnel} onSaved={() => { load(); loadDefinition(); }}
endpoint={live ? `tunnels/${tunnel.id}/access` : `persistent/${tunnel.id}/access`} />
{persistent && isHttp && <DomainsSection name={tunnel.id} domains={domains} onChanged={loadDefinition} />}
{live && <StatsPanel id={tunnel.id} />}
{live && (view === "visitors"
? <VisitorsTable tunnel={tunnel} heading={heading} onSaved={load}
onInspect={isHttp ? ip => { setFocus(ip); setView("traffic"); } : null} />
: isHttp
? <TrafficTable id={tunnel.id} heading={heading} focus={focus} />
: <ConnectionsTable tunnel={tunnel} heading={heading}
onDisconnect={client => setDisconnecting(client)}
onDisconnectAll={() => setDisconnecting("all")} />)}
</div>
);
};
@@ -0,0 +1,204 @@
import "./styles.sass";
import { useEffect, useState } from "react";
import Input from "@/common/components/Input";
import Select from "@/common/components/Select";
import Button from "@/common/components/Button";
import Toggle from "@/common/components/Toggle";
import Flag from "@/common/components/Flag";
import { countryCodes, countryName } from "@/common/utils/country.js";
import { getRequest, putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { Plus, X } from "lucide-react";
const AUTH_OPTIONS = [
{ label: "Open to everyone", value: "none" },
{ label: "Password", value: "password" },
{ label: "frislit account", value: "frislit" },
];
const CATEGORIES = [["tor", "Tor exit nodes"], ["vpn", "VPN services"], ["datacenter", "Datacenters"], ["blocklist", "Blocklisted addresses"]];
const SUGGESTIONS = 6;
const matches = (text, taken) => {
const value = text.trim().toLowerCase();
if (!value) return [];
return countryCodes
.filter(code => !taken.includes(code) && (code.toLowerCase().startsWith(value) || countryName(code).toLowerCase().includes(value)))
.slice(0, SUGGESTIONS);
};
const RuleList = ({ id, items, onChange, busy, country, placeholder }) => {
const [draft, setDraft] = useState("");
const suggestions = country ? matches(draft, items) : [];
const add = value => {
const entry = country ? suggestions[0] : value.trim();
if (!entry) return;
setDraft("");
if (!items.includes(entry)) onChange([...items, entry]);
};
const pick = code => {
setDraft("");
onChange([...items, code]);
};
return (
<div className="rule-group">
{items.length > 0 && (
<ul className="rule-list">
{items.map(item => (
<li key={item}>
{country ? <><Flag code={item} /><span>{countryName(item)}</span></> : <code>{item}</code>}
<button type="button" onClick={() => onChange(items.filter(entry => entry !== item))} disabled={busy}
aria-label={`Remove ${item}`} title="Remove"><X /></button>
</li>
))}
</ul>
)}
<div className="rule-add">
<div className="rule-input">
<Input id={id} placeholder={placeholder} value={draft} setValue={setDraft} autoComplete="off"
onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); add(draft); } }} />
{suggestions.length > 0 && (
<ul className="rule-suggestions">
{suggestions.map(code => (
<li key={code}>
<button type="button" onMouseDown={event => event.preventDefault()} onClick={() => pick(code)} disabled={busy}>
<Flag code={code} /><span>{countryName(code)}</span><small>{code}</small>
</button>
</li>
))}
</ul>
)}
</div>
<Button type="ghost" icon={Plus} text="Add" buttonType="button" onClick={() => add(draft)}
disabled={busy || (country ? suggestions.length === 0 : !draft.trim())} />
</div>
</div>
);
};
export const AccessSection = ({ tunnel, onSaved, endpoint = `tunnels/${tunnel.id}/access` }) => {
const { sendToast } = useToast();
const { allow, block } = tunnel.access;
const [auth, setAuth] = useState(tunnel.access?.auth || "none");
const [password, setPassword] = useState("");
const [people, setPeople] = useState([]);
const [selected, setSelected] = useState(tunnel.access?.accounts || []);
const [busy, setBusy] = useState(false);
useEffect(() => setAuth(tunnel.access?.auth || "none"), [tunnel.id, tunnel.access?.auth]);
useEffect(() => setSelected(tunnel.access?.accounts || []), [tunnel.id, tunnel.access?.accounts]);
useEffect(() => {
if (auth !== "frislit") return;
let cancelled = false;
getRequest(`tunnels/${tunnel.id}/access/accounts`)
.then(result => { if (!cancelled) setPeople(result.accounts || []); })
.catch(() => { if (!cancelled) setPeople([]); });
return () => { cancelled = true; };
}, [auth, tunnel.id]);
const isTcp = tunnel.mode === "tcp";
const accountsChanged = JSON.stringify(selected) !== JSON.stringify(tunnel.access?.accounts || []);
const authChanged = auth !== (tunnel.access?.auth || "none") || !!password || (auth === "frislit" && accountsChanged);
const needsPassword = auth === "password" && !tunnel.access?.hasPassword && !password;
const save = async (body, message) => {
setBusy(true);
try {
await putRequest(endpoint, body);
sendToast("Success", message);
onSaved?.();
return true;
} catch (error) {
sendToast("Error", error.message);
return false;
} finally {
setBusy(false);
}
};
const saveAuth = () => save(
{ auth, ...(password ? { password } : {}), ...(auth === "frislit" ? { accounts: selected } : {}) },
auth === "none" ? "Sign-in turned off" : "Sign-in updated",
).then(ok => ok && setPassword(""));
const toggleCategory = (key, on) => save(
{ block: { categories: on ? [...block.categories, key] : block.categories.filter(entry => entry !== key) } },
"Rules updated",
);
return (
<section className="access">
<div className="section-head">
<h2>Access</h2>
<span className="section-hint">{isTcp ? "Who may use the share code" : "Who may reach this tunnel"}</span>
</div>
<div className="access-cards">
{!isTcp && (
<div className="access-card">
<div className="access-card-head">
<h3>Sign-in</h3>
</div>
<div className="access-card-body">
<Select id="access-auth" options={AUTH_OPTIONS} selected={auth} setSelected={setAuth} />
{auth === "password" && (
<Input id="access-password" type="password"
placeholder={tunnel.access?.hasPassword ? "Leave empty to keep the current password" : "Password for visitors"}
value={password} setValue={setPassword} autoComplete="new-password" />
)}
{auth === "frislit" && (
<Select id="access-accounts" multiple emptyLabel="Any frislit account"
options={people.map(person => ({ value: person.id, label: person.username }))}
selected={selected} setSelected={setSelected} disabled={busy} />
)}
</div>
{authChanged && <div className="access-card-foot">
<Button type="ghost" text="Cancel" buttonType="button"
onClick={() => { setAuth(tunnel.access?.auth || "none"); setPassword(""); setSelected(tunnel.access?.accounts || []); }} />
<Button text="Save" buttonType="button" onClick={saveAuth} disabled={busy || needsPassword} />
</div>}
</div>
)}
<div className="access-card">
<div className="access-card-head">
<h3>Allow only</h3>
{allow.ips.length + allow.countries.length === 0 && <p>Anyone not blocked may connect.</p>}
</div>
<h4>Addresses</h4>
<RuleList id="allow-ip" items={allow.ips} busy={busy} placeholder="203.0.113.5 or 10.0.0.0/8"
onChange={ips => save({ allow: { ips } }, "Rules updated")} />
<h4>Countries</h4>
<RuleList id="allow-country" items={allow.countries} busy={busy} country placeholder="Country or code"
onChange={countries => save({ allow: { countries } }, "Rules updated")} />
</div>
<div className="access-card">
<div className="access-card-head">
<h3>Block</h3>
</div>
<h4>Addresses</h4>
<RuleList id="block-ip" items={block.ips} busy={busy} placeholder="203.0.113.5 or 10.0.0.0/8"
onChange={ips => save({ block: { ips } }, "Rules updated")} />
<h4>Countries</h4>
<RuleList id="block-country" items={block.countries} busy={busy} country placeholder="Country or code"
onChange={countries => save({ block: { countries } }, "Rules updated")} />
<h4>Categories</h4>
<div className="rule-toggles">
{CATEGORIES.map(([key, label]) => (
<Toggle key={key} id={`block-${key}`} label={label} checked={block.categories.includes(key)}
disabled={busy} onChange={on => toggleCategory(key, on)} />
))}
</div>
</div>
</div>
</section>
);
};
@@ -0,0 +1 @@
export { AccessSection as default } from "./AccessSection.jsx";
@@ -0,0 +1,176 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.access
margin-top: 1.75rem
.access-cards
display: grid
grid-template-columns: repeat(3, 1fr)
gap: 0.75rem
@media (max-width: breakpoints.$tablet)
grid-template-columns: 1fr 1fr
@media (max-width: breakpoints.$mobile)
grid-template-columns: 1fr
.access-card
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
> h4
margin: 0.875rem 1rem 0
color: colors.$muted
font-size: 0.6875rem
font-weight: 600
text-transform: uppercase
letter-spacing: 0.06em
.rule-toggles
display: flex
flex-direction: column
gap: 0.5rem
padding: 0.625rem 1rem 0.875rem
.toggle-row
justify-content: space-between
label
font-size: 0.8125rem
.access-card-head
padding: 0.875rem 1rem 0
h3
font-size: 0.875rem
font-weight: 600
p
margin-top: 0.15rem
color: colors.$muted
font-size: 0.75rem
line-height: 1.5
.access-card-body
display: flex
flex-direction: column
gap: 0.625rem
padding: 0.875rem 1rem
.access-card-foot
display: flex
justify-content: flex-end
gap: 0.375rem
padding: 0.75rem 1rem
border-top: 1px solid colors.$border
border-radius: 0 0 0.8125rem 0.8125rem
background-color: colors.$surface-raised
.rule-list
margin: 0.5rem 1rem 0
display: flex
flex-direction: column
gap: 0.3rem
li
display: flex
align-items: center
gap: 0.5rem
padding: 0.35rem 0.4rem 0.35rem 0.6rem
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.5rem
code, > li > span
flex: 1
font-size: 0.8125rem
color: colors.$text
overflow: hidden
text-overflow: ellipsis
code
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
button
display: inline-flex
align-items: center
justify-content: center
flex-shrink: 0
width: 1.375rem
height: 1.375rem
padding: 0
background: none
border: none
border-radius: 0.375rem
color: colors.$muted
cursor: pointer
transition: background-color 0.15s ease, color 0.15s ease
&:hover:not(:disabled)
background-color: colors.$error-tint
color: colors.$error
&:disabled
opacity: 0.5
cursor: default
svg
width: 0.875rem
height: 0.875rem
.rule-add
display: flex
align-items: flex-start
gap: 0.5rem
padding: 0.5rem 1rem 0.25rem
.rule-group:last-child .rule-add
padding-bottom: 0.875rem
.rule-input
position: relative
flex: 1
.rule-suggestions
position: absolute
top: calc(100% + 0.25rem)
left: 0
right: 0
z-index: 10
margin: 0
padding: 0.25rem
background-color: colors.$surface-raised
border: 1px solid colors.$border-strong
border-radius: 0.625rem
box-shadow: colors.$shadow-lg
button
display: flex
align-items: center
gap: 0.5rem
width: 100%
padding: 0.4rem 0.5rem
background: none
border: none
border-radius: 0.45rem
color: colors.$text
font-family: inherit
font-size: 0.8125rem
text-align: left
cursor: pointer
&:hover
background-color: colors.$surface-hover
span
flex: 1
overflow: hidden
text-overflow: ellipsis
white-space: nowrap
small
color: colors.$muted
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-size: 0.6875rem
@@ -0,0 +1,135 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import Button from "@/common/components/Button";
import Flag from "@/common/components/Flag";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import { deleteRequest, getRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { formatBytes } from "@/common/utils/formatUtils.js";
import { ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Plug, Trash2, Unplug } from "lucide-react";
import ConnectionPanel from "./components/ConnectionPanel";
import { formatTime } from "../TrafficTable/format.js";
import { formatDuration } from "./format.js";
const POLL_INTERVAL = 1500;
const PAGE_SIZE = 50;
const COLUMNS = [["started", "Time"], ["ip", "Client"], [null, "Protocol"], [null, "From"], ["in", "In"], ["out", "Out"], [null, "Duration"], [null, "State"]];
export const ConnectionsTable = ({ tunnel, heading, onDisconnect, onDisconnectAll }) => {
const { sendToast } = useToast();
const [connections, setConnections] = useState([]);
const [loaded, setLoaded] = useState(false);
const [total, setTotal] = useState(0);
const [now, setNow] = useState(0);
const [page, setPage] = useState(0);
const [clearing, setClearing] = useState(false);
const [selected, setSelected] = useState(null);
const [sort, setSort] = useState({ by: "started", order: "desc" });
useEffect(() => setPage(0), [sort]);
const load = useCallback(async () => {
const query = new URLSearchParams({ offset: page * PAGE_SIZE, limit: PAGE_SIZE, sort: sort.by, order: sort.order });
try {
const data = await getRequest(`tunnels/${tunnel.id}/connections?${query}`);
setTotal(data.total);
setNow(data.now);
setConnections(data.connections);
setLoaded(true);
} catch {
return;
}
}, [tunnel.id, page, sort]);
useEffect(() => {
load();
const poll = setInterval(load, POLL_INTERVAL);
return () => clearInterval(poll);
}, [load]);
const clear = async () => {
try {
const result = await deleteRequest(`tunnels/${tunnel.id}/connections`);
sendToast("Success", result.message);
if (page === 0) load(); else setPage(0);
} catch (error) {
sendToast("Error", error.message);
}
};
const sortBy = key => setSort(current => ({ by: key, order: current.by === key && current.order === "desc" ? "asc" : "desc" }));
const open = tunnel.clients.length;
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const first = page * PAGE_SIZE + 1;
const last = Math.min(total, (page + 1) * PAGE_SIZE);
return (
<section className="connections">
{selected && <ConnectionPanel tunnelId={tunnel.id} entry={selected} onClose={() => setSelected(null)} />}
<ActionConfirmDialog open={clearing} setOpen={setClearing} onConfirm={clear} title="Clear connection history?"
text="Finished connections and their captured data are deleted. Open connections stay." confirmText="Clear" />
<div className="connections-head">
{heading}
<span className="connections-count">{open} open · {total} total</span>
<div className="connections-spacer" />
{open > 0 && <Button type="ghost" icon={Unplug} text="Disconnect all" buttonType="button" onClick={onDisconnectAll} />}
{total > 0 && <Button type="ghost" icon={Trash2} text="Clear" buttonType="button" onClick={() => setClearing(true)} />}
</div>
{loaded && connections.length === 0
? <div className="connections-empty">
<Plug size={20} />
<p>No connections yet.</p>
</div>
: <div className="connections-table">
<table>
<thead>
<tr>
{COLUMNS.map(([key, label]) => (
<th key={label} className={key ? "sortable" : ""} onClick={() => key && sortBy(key)}>
{label}
{key && sort.by === key && (sort.order === "desc" ? <ArrowDown /> : <ArrowUp />)}
</th>
))}
<th aria-label="Actions" />
</tr>
</thead>
<tbody>
{connections.map(entry => {
const live = !entry.endedAt;
return (
<tr key={entry.key} className={`${live ? "live" : ""}${selected?.key === entry.key ? " selected" : ""}`} tabIndex={0}
onClick={() => setSelected(entry)} onKeyDown={event => event.key === "Enter" && setSelected(entry)}>
<td className="mono dim">{formatTime(entry.startedAt)}</td>
<td className="mono client"><Flag code={entry.intel.country} />{entry.ip}</td>
<td className="protocol">
<span className="protocol-name">{entry.detail?.name || entry.protocol.toUpperCase()}</span>
{entry.detail?.info && <span className="protocol-info" title={entry.detail.info}>{entry.detail.info}</span>}
</td>
<td className="mono dim">{entry.client}</td>
<td className="mono">{formatBytes(entry.bytesIn)}</td>
<td className="mono">{formatBytes(entry.bytesOut)}</td>
<td className="mono dim">{formatDuration((entry.endedAt || now) - entry.startedAt)}</td>
<td>{live ? <span className="status ok">open</span> : <span className="dim">{entry.reason}</span>}</td>
<td className="actions">
{live && (
<button type="button" title="Disconnect" aria-label="Disconnect"
onClick={event => { event.stopPropagation(); onDisconnect({ id: entry.joiner, ip: entry.ip }); }}><Unplug /></button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
{total > PAGE_SIZE && (
<div className="connections-pages">
<span>{first}–{last} of {total}</span>
<button type="button" onClick={() => setPage(page - 1)} disabled={page === 0} aria-label="Previous page"><ChevronLeft /></button>
<button type="button" onClick={() => setPage(page + 1)} disabled={page >= pages - 1} aria-label="Next page"><ChevronRight /></button>
</div>
)}
</div>}
</section>
);
};
@@ -0,0 +1,89 @@
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import Button from "@/common/components/Button";
import CopyButton from "@/common/components/CopyButton";
import Flag from "@/common/components/Flag";
import { getRequest } from "@/common/utils/RequestUtil.js";
import { formatBytes } from "@/common/utils/formatUtils.js";
import { countryName } from "@/common/utils/country.js";
import { formatDuration } from "../../format.js";
const POLL_INTERVAL = 1500;
const Rows = ({ items }) => (
<dl className="panel-rows">
{items.filter(([, value]) => value !== undefined && value !== null && value !== "").map(([label, value, copy], index) => (
<div key={index}>
<dt>{label}</dt>
<dd>{value}{copy && <CopyButton value={copy} />}</dd>
</div>
))}
</dl>
);
export const ConnectionPanel = ({ tunnelId, entry, onClose }) => {
const [connection, setConnection] = useState(entry);
const [now, setNow] = useState(entry.endedAt || entry.startedAt);
const open = !connection.endedAt;
useEffect(() => {
document.body.classList.add("panel-open");
return () => document.body.classList.remove("panel-open");
}, []);
useEffect(() => {
const onKey = event => { if (event.key === "Escape") onClose(); };
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onClose]);
useEffect(() => {
let active = true;
const load = async () => {
try {
const data = await getRequest(`tunnels/${tunnelId}/connections/${entry.key}`);
if (!active) return;
setConnection(data.connection);
setNow(data.now);
} catch {
return;
}
};
load();
if (!open) return () => { active = false; };
const poll = setInterval(load, POLL_INTERVAL);
return () => { active = false; clearInterval(poll); };
}, [tunnelId, entry.key, open]);
const intel = connection.intel;
const label = connection.detail ? `${connection.detail.name}${connection.detail.info ? ` · ${connection.detail.info}` : ""}` : connection.protocol.toUpperCase();
return createPortal(
<aside className="request-panel">
<header className="panel-head">
<span className="panel-method">{connection.protocol.toUpperCase()}</span>
<span className="panel-path" title={connection.ip}>{connection.ip}</span>
{open ? <span className="status ok">open</span> : <span className="status">{connection.reason}</span>}
<div className="panel-actions">
<Button type="ghost" icon={X} title="Close" onClick={onClose} />
</div>
</header>
<div className="panel-scroll">
<div className="panel-card">
<Rows items={[
["Client", <span key="client" className="mono panel-client"><Flag code={intel.country} />{connection.ip}</span>, connection.ip],
["Network", intel.private ? "Private network" : [intel.org, intel.country && countryName(intel.country)].filter(Boolean).join(" · ")],
["From", <span key="from" className="mono">{connection.client}</span>, connection.client],
["Protocol", label],
["Started", new Date(connection.startedAt).toLocaleString()],
["Duration", formatDuration((connection.endedAt || now) - connection.startedAt)],
["Received", formatBytes(connection.bytesIn)],
["Sent", formatBytes(connection.bytesOut)],
]} />
</div>
</div>
</aside>,
document.body,
);
};
@@ -0,0 +1 @@
export { ConnectionPanel as default } from "./ConnectionPanel.jsx";
@@ -0,0 +1,6 @@
export const formatDuration = millis => {
if (millis < 1000) return `${millis}ms`;
if (millis < 60_000) return `${(millis / 1000).toFixed(1)}s`;
const minutes = Math.floor(millis / 60_000);
return `${minutes}m ${Math.round((millis % 60_000) / 1000)}s`;
};
@@ -0,0 +1 @@
export { ConnectionsTable as default } from "./ConnectionsTable.jsx";
@@ -0,0 +1,188 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.connections
margin-top: 1.75rem
.connections-head
display: flex
align-items: center
gap: 0.625rem
margin-bottom: 0.75rem
.connections-count
color: colors.$muted
font-size: 0.8125rem
.connections-spacer
flex: 1
.connections-empty
display: flex
flex-direction: column
align-items: center
gap: 0.5rem
padding: 2.5rem 1rem
text-align: center
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
svg
color: colors.$muted
opacity: 0.7
p
color: colors.$muted
font-size: 0.875rem
.connections-table
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
overflow: hidden
table
width: 100%
border-collapse: collapse
font-size: 0.8125rem
th
text-align: left
padding: 0.625rem 0.875rem
color: colors.$muted
font-size: 0.6875rem
font-weight: 600
text-transform: uppercase
letter-spacing: 0.06em
border-bottom: 1px solid colors.$border
white-space: nowrap
user-select: none
svg
width: 0.75rem
height: 0.75rem
margin-left: 0.25rem
vertical-align: -0.125rem
&.sortable
cursor: pointer
&:hover
color: colors.$text
td
padding: 0.5rem 0.875rem
border-bottom: 1px solid colors.$border
white-space: nowrap
vertical-align: middle
tbody tr
cursor: pointer
&:hover
background-color: colors.$surface-hover
&.selected
background-color: colors.$primary-tint
&:focus-visible
outline: 2px solid colors.$primary
outline-offset: -2px
.mono
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-variant-numeric: tabular-nums
.dim
color: colors.$muted
.client .flag
margin-right: 0.5rem
.protocol
max-width: 18rem
overflow: hidden
text-overflow: ellipsis
.protocol-name
display: inline-block
margin-right: 0.5rem
padding: 0.0625rem 0.4rem
border-radius: 0.375rem
background-color: colors.$surface-hover
color: colors.$text
font-size: 0.6875rem
font-weight: 600
.protocol-info
color: colors.$subtext
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-size: 0.75rem
.actions
width: 1%
text-align: right
button
display: inline-flex
align-items: center
justify-content: center
width: 1.75rem
height: 1.75rem
padding: 0
background: none
border: none
border-radius: 0.5rem
color: colors.$muted
cursor: pointer
svg
width: 0.875rem
height: 0.875rem
&:hover
background-color: colors.$error-tint
color: colors.$error
@media (max-width: breakpoints.$mobile)
th:nth-child(4), td:nth-child(4), th:nth-child(7), td:nth-child(7)
display: none
.connections-pages
display: flex
align-items: center
justify-content: flex-end
gap: 0.25rem
padding: 0.375rem 0.625rem
border-top: 1px solid colors.$border
color: colors.$muted
font-size: 0.75rem
font-variant-numeric: tabular-nums
span
margin-right: 0.5rem
button
display: inline-flex
align-items: center
justify-content: center
width: 1.75rem
height: 1.75rem
background: none
border: 1px solid colors.$border
border-radius: 0.5rem
color: colors.$subtext
cursor: pointer
svg
width: 0.875rem
height: 0.875rem
&:hover:not(:disabled)
background-color: colors.$surface-hover
color: colors.$text
&:disabled
opacity: 0.35
cursor: default
@@ -0,0 +1,92 @@
import "./styles.sass";
import { useState } from "react";
import Input from "@/common/components/Input";
import Button from "@/common/components/Button";
import { deleteRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { useUser } from "@/common/contexts/user.js";
import { Plus, RefreshCw, X } from "lucide-react";
const STATE_LABELS = {
pending: "Waiting for DNS",
issuing: "Getting certificate",
active: "Active",
error: "Error",
};
export const DomainsSection = ({ name, domains = [], onChanged }) => {
const { sendToast } = useToast();
const { serverInfo } = useUser();
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(null);
const run = async (key, action, message) => {
setBusy(key);
try {
const result = await action();
sendToast("Success", message || result.message);
onChanged?.();
return true;
} catch (error) {
sendToast("Error", error.message);
return false;
} finally {
setBusy(null);
}
};
const add = async () => {
const hostname = draft.trim().toLowerCase();
if (!hostname) return;
if (await run("add", () => postRequest(`persistent/${name}/domains`, { hostname }))) setDraft("");
};
return (
<section className="domains">
<div className="section-head">
<h2>Custom domains</h2>
</div>
<div className="domains-card">
{domains.length > 0 && (
<ul className="domain-list">
{domains.map(domain => (
<li key={domain.hostname}>
<div className="domain-main">
<a href={domain.state === "active" ? domain.url : undefined} target="_blank" rel="noreferrer">
{domain.hostname}
</a>
<span className={`domain-state ${domain.state}`}>{STATE_LABELS[domain.state] || domain.state}</span>
{domain.state !== "active" && domain.error && <span className="domain-error">{domain.error}</span>}
{domain.certificate && <span className="domain-cert">
certificate until {new Date(domain.certificate.expiresAt).toLocaleDateString()}
</span>}
</div>
<button type="button" title="Check again" aria-label={`Check ${domain.hostname}`}
className={busy === domain.hostname ? "spinning" : ""}
disabled={!!busy}
onClick={() => run(domain.hostname, () => postRequest(`persistent/${name}/domains/${domain.hostname}/check`))}>
<RefreshCw />
</button>
<button type="button" title="Remove" aria-label={`Remove ${domain.hostname}`} disabled={!!busy}
onClick={() => run(domain.hostname, () => deleteRequest(`persistent/${name}/domains/${domain.hostname}`))}>
<X />
</button>
</li>
))}
</ul>
)}
<div className="domain-add">
<Input id="domain-hostname" placeholder="app.example.com" value={draft} setValue={setDraft}
autoComplete="off" inputMode="url"
onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); add(); } }} />
<Button type="ghost" icon={Plus} text="Add" buttonType="button" onClick={add}
disabled={!!busy || !draft.trim()} />
</div>
<p className="domains-hint">CNAME it to <code>{serverInfo?.baseDomain}</code>.</p>
</div>
</section>
);
};
@@ -0,0 +1 @@
export { DomainsSection as default } from "./DomainsSection.jsx";
@@ -0,0 +1,123 @@
@use "@/common/styles/colors"
.domains
margin-top: 1.75rem
.domains-card
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
.domain-list
margin: 0.875rem 1rem 0
display: flex
flex-direction: column
gap: 0.3rem
li
display: flex
align-items: center
gap: 0.5rem
padding: 0.5rem 0.4rem 0.5rem 0.75rem
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.5rem
button
display: inline-flex
align-items: center
justify-content: center
flex-shrink: 0
width: 1.5rem
height: 1.5rem
padding: 0
background: none
border: none
border-radius: 0.375rem
color: colors.$muted
cursor: pointer
transition: background-color 0.15s ease, color 0.15s ease
svg
width: 0.875rem
height: 0.875rem
&:hover:not(:disabled)
background-color: colors.$surface-hover
color: colors.$text
&:last-child:hover:not(:disabled)
background-color: colors.$error-tint
color: colors.$error
&:disabled
opacity: 0.5
cursor: default
&.spinning svg
animation: domain-spin 0.8s linear infinite
@keyframes domain-spin
to
transform: rotate(360deg)
.domain-main
flex: 1
min-width: 0
display: flex
align-items: center
flex-wrap: wrap
gap: 0.25rem 0.5rem
a
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-size: 0.8125rem
color: colors.$text
&[href]:hover
color: colors.$primary-bright
.domain-state
padding: 0.0625rem 0.45rem
border-radius: 0.375rem
background-color: colors.$surface-hover
color: colors.$subtext
font-size: 0.6875rem
font-weight: 600
&.active
background-color: colors.$success-tint
color: colors.$success
&.pending, &.issuing
background-color: colors.$warning-tint
color: colors.$warning
&.error
background-color: colors.$error-tint
color: colors.$error
.domain-error, .domain-cert
width: 100%
color: colors.$muted
font-size: 0.75rem
.domain-add
display: flex
align-items: flex-start
gap: 0.5rem
padding: 0.875rem 1rem
.field
flex: 1
.domains-hint
margin: 0
padding: 0 1rem 0.875rem
color: colors.$muted
font-size: 0.75rem
line-height: 1.5
code
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
color: colors.$subtext
@@ -0,0 +1,22 @@
import { formatRate } from "@/common/utils/formatUtils.js";
export const ChartTooltip = ({ active, payload, label, series }) => {
if (!active || !payload?.length) return null;
const point = payload[0].payload;
return (
<div className="chart-tooltip">
<span className="chart-tooltip-time">{new Date(label).toLocaleTimeString()}</span>
{series.map(entry => (
<span key={entry.key} className="chart-tooltip-row">
<i style={{ backgroundColor: entry.color }} />
{entry.label}
<b>{formatRate(point[entry.key])}</b>
</span>
))}
<span className="chart-tooltip-row muted">
{point.requests} {point.requests === 1 ? "request" : "requests"}
</span>
</div>
);
};
@@ -0,0 +1,6 @@
export const StatTile = ({ label, value, accent }) => (
<div className={`stat-tile${accent ? ` accent-${accent}` : ""}`}>
<span className="stat-tile-label">{label}</span>
<span className="stat-tile-value">{value}</span>
</div>
);
@@ -0,0 +1,101 @@
import "./styles.sass";
import { useCallback, useEffect, useState } from "react";
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { getRequest } from "@/common/utils/RequestUtil.js";
import { formatBytes, formatRate } from "@/common/utils/formatUtils.js";
import { StatTile } from "./StatTile.jsx";
import { ChartTooltip } from "./ChartTooltip.jsx";
const POLL_INTERVAL = 2000;
const SERIES = [
{ key: "out", label: "Out", color: "var(--chart-out)" },
{ key: "in", label: "In", color: "var(--chart-in)" },
];
const clock = value => new Date(value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
export const StatsPanel = ({ id }) => {
const [stats, setStats] = useState(null);
const load = useCallback(async () => {
try {
setStats((await getRequest(`tunnels/${id}/stats`)).stats);
} catch { /* the tunnel may have closed while we were asking */ }
}, [id]);
useEffect(() => {
load();
const timer = setInterval(load, POLL_INTERVAL);
return () => clearInterval(timer);
}, [load]);
if (!stats) return null;
const points = stats.buckets.map(bucket => ({
t: bucket.t,
out: Math.round(bucket.out / stats.interval),
in: Math.round(bucket.in / stats.interval),
requests: bucket.requests,
}));
const peak = points.reduce((most, point) => Math.max(most, point.in + point.out), 0);
const quiet = peak === 0;
return (
<section className="stats">
<div className="section-head">
<h2>Live</h2>
<span className="section-hint">{quiet ? "idle" : `peak ${formatRate(peak)}`}</span>
</div>
<div className="stats-panel">
<div className="stats-tiles">
<StatTile label="Out now" value={formatRate(stats.rates.out)} accent="out" />
<StatTile label="In now" value={formatRate(stats.rates.in)} accent="in" />
<StatTile label="Sent" value={formatBytes(stats.totals.out)} />
<StatTile label="Received" value={formatBytes(stats.totals.in)} />
<StatTile label="Requests" value={stats.totals.requests.toLocaleString()} />
</div>
<figure className="stats-chart">
<figcaption>
<span>Throughput</span>
<div className="stats-legend">
{SERIES.map(series => (
<span key={series.key}>
<i style={{ backgroundColor: series.color }} />{series.label}
</span>
))}
</div>
</figcaption>
<div className="stats-chart-area">
<ResponsiveContainer width="100%" height={150}>
<AreaChart data={points} margin={{ top: 10, right: 4, bottom: 0, left: 0 }}>
<defs>
{SERIES.map(series => (
<linearGradient key={series.key} id={`fill-${series.key}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={series.color} stopOpacity={0.35} />
<stop offset="100%" stopColor={series.color} stopOpacity={0.02} />
</linearGradient>
))}
</defs>
<CartesianGrid stroke="var(--border)" vertical={false} />
<XAxis dataKey="t" tickFormatter={clock} tick={{ fill: "var(--muted)", fontSize: 10 }}
axisLine={false} tickLine={false} minTickGap={48} />
<YAxis tickFormatter={formatRate} tick={{ fill: "var(--muted)", fontSize: 10 }}
axisLine={false} tickLine={false} width={76} tickCount={4} />
<Tooltip content={<ChartTooltip series={SERIES} />} cursor={{ stroke: "var(--border-strong)" }} />
{SERIES.map(series => (
<Area key={series.key} type="monotone" dataKey={series.key} stroke={series.color}
strokeWidth={2} fill={`url(#fill-${series.key})`} isAnimationActive={false}
dot={false} activeDot={{ r: 4, strokeWidth: 0 }} />
))}
</AreaChart>
</ResponsiveContainer>
{quiet && <p className="stats-quiet">Nothing has come through in the last few minutes.</p>}
</div>
</figure>
</div>
</section>
);
};
@@ -0,0 +1 @@
export { StatsPanel as default } from "./StatsPanel.jsx";
@@ -0,0 +1,124 @@
@use "@/common/styles/colors"
@use "@/common/styles/breakpoints"
.stats
margin-top: 1.75rem
.stats-panel
padding: 1.25rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
.stats-tiles
display: grid
grid-template-columns: repeat(5, 1fr)
gap: 0.75rem
@media (max-width: breakpoints.$tablet)
grid-template-columns: repeat(2, 1fr)
.stat-tile
display: flex
flex-direction: column
gap: 0.1875rem
padding: 0.75rem 0.875rem
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.75rem
&.accent-out
border-color: var(--chart-out)
&.accent-in
border-color: var(--chart-in)
.stat-tile-label
color: colors.$muted
font-size: 0.6875rem
text-transform: uppercase
letter-spacing: 0.06em
.stat-tile-value
font-size: 1.0625rem
font-weight: 600
font-variant-numeric: tabular-nums
letter-spacing: -0.01em
.stats-chart
margin: 1.25rem 0 0
figcaption
display: flex
align-items: center
justify-content: space-between
margin-bottom: 0.625rem
color: colors.$subtext
font-size: 0.8125rem
font-weight: 600
.stats-legend
display: flex
gap: 0.875rem
font-weight: 500
span
display: flex
align-items: center
gap: 0.375rem
color: colors.$muted
font-size: 0.75rem
i
width: 0.5rem
height: 0.5rem
border-radius: 2px
.stats-chart-area
position: relative
.stats-quiet
position: absolute
inset: 0
display: flex
align-items: center
justify-content: center
margin: 0
color: colors.$muted
font-size: 0.8125rem
pointer-events: none
.chart-tooltip
display: flex
flex-direction: column
gap: 0.25rem
padding: 0.625rem 0.75rem
background-color: colors.$surface-raised
border: 1px solid colors.$border-strong
border-radius: 0.625rem
box-shadow: colors.$shadow-md
font-size: 0.75rem
.chart-tooltip-time
color: colors.$muted
font-size: 0.6875rem
.chart-tooltip-row
display: flex
align-items: center
gap: 0.375rem
color: colors.$subtext
i
width: 0.5rem
height: 0.5rem
border-radius: 2px
b
margin-left: auto
padding-left: 0.75rem
color: colors.$text
font-variant-numeric: tabular-nums
&.muted
color: colors.$muted
@@ -0,0 +1,264 @@
import "./styles.sass";
import { useCallback, useEffect, useRef, useState } from "react";
import Button from "@/common/components/Button";
import Flag from "@/common/components/Flag";
import ActionConfirmDialog from "@/common/components/ActionConfirmDialog";
import { deleteRequest, getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { Activity, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, CirclePause, Download, Pause, Play, Search, Trash2, X } from "lucide-react";
import RequestPanel from "./components/RequestPanel";
import BreakpointsBar, { PhaseIcon } from "./components/BreakpointsBar";
import { formatTime, statusClass } from "./format.js";
import { countryName } from "@/common/utils/country.js";
const POLL_INTERVAL = 1500;
const PAGE_SIZE = 50;
const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "WS"];
const STATUSES = [2, 3, 4, 5];
const COLUMNS = [["time", "Time"], ["client", "Client"], ["method", "Method"], ["path", "Path"], ["status", "Status"], ["duration", "Duration"]];
const EMPTY = { search: "", methods: [], statuses: [], countries: [] };
const rowClass = (...names) => names.filter(Boolean).join(" ");
const toggle = (list, value) => (list.includes(value) ? list.filter(entry => entry !== value) : [...list, value]);
const typing = () => {
const active = document.activeElement;
return active && (active.tagName === "INPUT" || active.tagName === "TEXTAREA" || active.tagName === "SELECT" || active.isContentEditable);
};
export const TrafficTable = ({ id, heading, focus }) => {
const { sendToast } = useToast();
const [clearing, setClearing] = useState(false);
const [requests, setRequests] = useState([]);
const [loaded, setLoaded] = useState(false);
const [total, setTotal] = useState(0);
const [countries, setCountries] = useState([]);
const [page, setPage] = useState(0);
const [paused, setPaused] = useState(false);
const [selected, setSelected] = useState(null);
const [filter, setFilter] = useState(EMPTY);
const [search, setSearch] = useState("");
const [sort, setSort] = useState({ by: "time", order: "desc" });
const [breakpoints, setBreakpoints] = useState({ rules: [], held: [], now: 0 });
const [showBreakpoints, setShowBreakpoints] = useState(false);
const [cursor, setCursor] = useState(null);
const keyState = useRef({});
useEffect(() => {
const timer = setTimeout(() => setFilter(current => ({ ...current, search: search.trim() })), 250);
return () => clearTimeout(timer);
}, [search]);
useEffect(() => setPage(0), [filter, sort]);
useEffect(() => { if (focus) setSearch(focus); }, [focus]);
const load = useCallback(async () => {
const query = new URLSearchParams({ offset: page * PAGE_SIZE, limit: PAGE_SIZE, sort: sort.by, order: sort.order });
if (filter.search) query.set("search", filter.search);
if (filter.methods.length) query.set("methods", filter.methods.join(","));
if (filter.statuses.length) query.set("statuses", filter.statuses.join(","));
if (filter.countries.length) query.set("countries", filter.countries.join(","));
try {
const data = await getRequest(`tunnels/${id}/requests?${query}`);
setTotal(data.total);
setCountries(data.countries);
setRequests(data.requests);
setLoaded(true);
} catch {
return;
}
}, [id, page, filter, sort]);
useEffect(() => {
load();
if (paused || page > 0) return;
const poll = setInterval(load, POLL_INTERVAL);
return () => clearInterval(poll);
}, [load, paused, page]);
const loadBreakpoints = useCallback(async () => {
try {
setBreakpoints(await getRequest(`tunnels/${id}/breakpoints`));
} catch {
return;
}
}, [id]);
useEffect(() => {
loadBreakpoints();
const poll = setInterval(loadBreakpoints, POLL_INTERVAL);
return () => clearInterval(poll);
}, [loadBreakpoints]);
useEffect(() => {
if (selected?.held && !breakpoints.held.some(entry => entry.id === selected.id)) setSelected(null);
}, [breakpoints.held, selected]);
const pick = entry => setSelected({ ...entry, held: true });
useEffect(() => {
keyState.current = { rows: [...breakpoints.held.map(entry => ({ ...entry, held: true })), ...requests], cursor, selected };
}, [breakpoints.held, requests, cursor, selected]);
useEffect(() => {
const onKey = event => {
if (event.altKey || event.ctrlKey || event.metaKey || typing()) return;
const { rows, cursor, selected } = keyState.current;
if (event.key === "j" || event.key === "k") {
if (rows.length === 0) return;
const at = rows.findIndex(entry => entry.id === (cursor ?? selected?.id));
const next = event.key === "j" ? Math.min(rows.length - 1, at + 1) : Math.max(0, at - 1);
setCursor(rows[next].id);
if (selected) setSelected(rows[next]);
document.querySelector(`.traffic-table tr[data-id="${rows[next].id}"]`)?.scrollIntoView({ block: "nearest" });
} else if (event.key === "Enter" && cursor !== null) {
const entry = rows.find(entry => entry.id === cursor);
if (entry) setSelected(entry);
} else if (event.key === "Escape") {
setCursor(null);
} else if (event.key === "r" && selected && !selected.held) {
postRequest(`tunnels/${id}/requests/${selected.id}/replay`, {})
.then(result => sendToast("Success", result.message))
.catch(error => sendToast("Error", error.message));
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [id, sendToast]);
const settle = async (held, input) => {
try {
const result = await postRequest(`tunnels/${id}/breakpoints/${held.id}`, input);
sendToast("Success", result.message);
setSelected(null);
loadBreakpoints();
load();
} catch (error) {
sendToast("Error", error.message);
}
};
const clear = async () => {
try {
const result = await deleteRequest(`tunnels/${id}/requests`);
sendToast("Success", result.message);
setSelected(null);
if (page === 0) load(); else setPage(0);
} catch (error) {
sendToast("Error", error.message);
}
};
const sortBy = key => setSort(current => ({ by: key, order: current.by === key && current.order === "desc" ? "asc" : "desc" }));
const filtering = filter.search || filter.methods.length > 0 || filter.statuses.length > 0 || filter.countries.length > 0;
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const first = page * PAGE_SIZE + 1;
const last = Math.min(total, (page + 1) * PAGE_SIZE);
return (
<section className="traffic">
{selected && <RequestPanel tunnelId={id} entry={selected} onClose={() => setSelected(null)}
onSettle={selected.held ? input => settle(selected, input) : null} />}
<ActionConfirmDialog open={clearing} setOpen={setClearing} onConfirm={clear} title="Clear all requests?"
text="The stored requests and messages of this tunnel are deleted." confirmText="Clear" />
<div className="traffic-head">
{heading}
<span className="traffic-count">{total} {total === 1 ? "request" : "requests"}</span>
<div className="traffic-spacer" />
{total > 0 && <>
<a className="btn btn-ghost" href={`/@frislit/api/tunnels/${id}/requests.har`} download={`${id}.har`}>
<Download /><span>Export HAR</span>
</a>
<Button type="ghost" icon={Trash2} text="Clear" buttonType="button" onClick={() => setClearing(true)} />
</>}
<Button type="ghost" icon={CirclePause} text={breakpoints.rules.length ? `Breakpoints · ${breakpoints.rules.length}` : "Breakpoints"}
buttonType="button" onClick={() => setShowBreakpoints(!showBreakpoints)} />
<Button type="ghost" icon={paused ? Play : Pause} text={paused ? "Resume" : "Pause"}
buttonType="button" onClick={() => setPaused(!paused)} />
</div>
{showBreakpoints && <BreakpointsBar tunnelId={id} rules={breakpoints.rules} onChanged={loadBreakpoints} />}
{loaded && (total > 0 || filtering) && (
<div className="traffic-filters">
<label className="traffic-search">
<Search />
<input value={search} onChange={event => setSearch(event.target.value)} placeholder="Path or address" spellCheck={false} />
{search && <button type="button" onClick={() => setSearch("")} aria-label="Clear search"><X /></button>}
</label>
<div className="traffic-chips">
{METHODS.map(method => (
<button key={method} type="button" className={filter.methods.includes(method) ? "active" : ""}
onClick={() => setFilter({ ...filter, methods: toggle(filter.methods, method) })}>{method}</button>
))}
</div>
<div className="traffic-chips">
{STATUSES.map(hundreds => (
<button key={hundreds} type="button" className={`${statusClass(hundreds * 100)}${filter.statuses.includes(hundreds) ? " active" : ""}`}
onClick={() => setFilter({ ...filter, statuses: toggle(filter.statuses, hundreds) })}>{hundreds}xx</button>
))}
</div>
{countries.length > 0 && (
<div className="traffic-chips traffic-countries">
{countries.map(({ code, count }) => (
<button key={code} type="button" className={filter.countries.includes(code) ? "active" : ""} title={countryName(code)}
onClick={() => setFilter({ ...filter, countries: toggle(filter.countries, code) })}><Flag code={code} />{code}<small>{count}</small></button>
))}
</div>
)}
{filtering && <Button type="ghost" text="Reset" buttonType="button" onClick={() => { setFilter(EMPTY); setSearch(""); }} />}
</div>
)}
{loaded && requests.length === 0 && breakpoints.held.length === 0
? <div className="traffic-empty">
<Activity size={20} />
<p>{filtering ? "Nothing matches." : "No requests yet."}</p>
</div>
: <div className="traffic-table">
<table>
<thead>
<tr>
{COLUMNS.map(([key, label]) => (
<th key={key} className={key === "client" ? "" : "sortable"} onClick={() => key !== "client" && sortBy(key)}>
{label}
{sort.by === key && (sort.order === "desc" ? <ArrowDown /> : <ArrowUp />)}
</th>
))}
</tr>
</thead>
<tbody>
{breakpoints.held.map(entry => (
<tr key={entry.id} data-id={entry.id} className={rowClass("held", selected?.id === entry.id && "selected", cursor === entry.id && "cursor")}
onClick={() => pick(entry)}>
<td className="mono dim">{formatTime(entry.time)}</td>
<td className="mono client">{entry.ip}</td>
<td className="mono"><PhaseIcon phase={entry.phase} />{entry.method}</td>
<td className="mono path" title={entry.path}>{entry.path}</td>
<td><span className="status warn">{entry.phase === "response" ? entry.status : "paused"}</span></td>
<td className="mono dim">{Math.round((breakpoints.now - entry.time) / 1000)}s</td>
</tr>
))}
{requests.map(entry => (
<tr key={entry.id} data-id={entry.id} className={rowClass(selected?.id === entry.id && "selected", cursor === entry.id && "cursor")}
onClick={() => setSelected(entry)}>
<td className="mono dim">{formatTime(entry.time)}</td>
<td className="mono client"><Flag code={entry.intel?.country} />{entry.ip}</td>
<td className="mono">{entry.kind === "ws" ? "WS" : entry.method}</td>
<td className="mono path" title={entry.path}>{entry.path}</td>
<td><span className={`status ${statusClass(entry.status)}`}>{entry.status}</span></td>
<td className="mono dim">{entry.duration}ms</td>
</tr>
))}
</tbody>
</table>
{total > PAGE_SIZE && (
<div className="traffic-pages">
<span>{first}–{last} of {total}</span>
<button type="button" onClick={() => setPage(page - 1)} disabled={page === 0} aria-label="Previous page"><ChevronLeft /></button>
<button type="button" onClick={() => setPage(page + 1)} disabled={page >= pages - 1} aria-label="Next page"><ChevronRight /></button>
</div>
)}
</div>}
</section>
);
};
@@ -0,0 +1,66 @@
import "./styles.sass";
import { useState } from "react";
import Button from "@/common/components/Button";
import Input from "@/common/components/Input";
import Select from "@/common/components/Select";
import { putRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { ArrowLeft, ArrowLeftRight, ArrowRight, Plus, X } from "lucide-react";
const METHODS = [["", "Any"], ["GET", "GET"], ["POST", "POST"], ["PUT", "PUT"], ["PATCH", "PATCH"], ["DELETE", "DELETE"]].map(([value, label]) => ({ value, label }));
const PHASES = [{ value: "request", label: "Request" }, { value: "response", label: "Response" }, { value: "both", label: "Both" }];
const PHASE_ICONS = { request: ArrowRight, response: ArrowLeft, both: ArrowLeftRight };
export const PhaseIcon = ({ phase }) => {
const Glyph = PHASE_ICONS[phase];
return <Glyph className="phase-icon" aria-label={phase} />;
};
export const BreakpointsBar = ({ tunnelId, rules, onChanged }) => {
const { sendToast } = useToast();
const [method, setMethod] = useState("");
const [phase, setPhase] = useState("request");
const [path, setPath] = useState("/");
const [busy, setBusy] = useState(false);
const save = async next => {
setBusy(true);
try {
await putRequest(`tunnels/${tunnelId}/breakpoints`, { rules: next });
onChanged();
return true;
} catch (error) {
sendToast("Error", error.message);
return false;
} finally {
setBusy(false);
}
};
const add = async () => {
if (await save([...rules, { method, path: path.trim(), phase }])) setPath("/");
};
return (
<div className="breakpoints">
<ul className="breakpoint-list">
{rules.map((rule, index) => (
<li key={index}>
<PhaseIcon phase={rule.phase} />
<span className="breakpoint-method">{rule.method || "ANY"}</span>
<code>{rule.path}</code>
<button type="button" onClick={() => save(rules.filter((_, at) => at !== index))} disabled={busy} aria-label="Remove" title="Remove"><X /></button>
</li>
))}
{rules.length === 0 && <li className="breakpoint-empty">No breakpoints. Matching requests wait until you continue or drop them.</li>}
</ul>
<div className="breakpoint-add">
<Select id="breakpoint-method" options={METHODS} selected={method} setSelected={setMethod} />
<Select id="breakpoint-phase" options={PHASES} selected={phase} setSelected={setPhase} />
<Input id="breakpoint-path" value={path} setValue={setPath} placeholder="/api"
onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); add(); } }} />
<Button type="ghost" icon={Plus} text="Add" buttonType="button" onClick={add} disabled={busy || !path.trim()} />
</div>
</div>
);
};
@@ -0,0 +1 @@
export { BreakpointsBar as default, PhaseIcon } from "./BreakpointsBar.jsx";
@@ -0,0 +1,74 @@
@use "@/common/styles/colors"
.breakpoints
margin-bottom: 0.75rem
background-color: colors.$surface
border: 1px solid colors.$border
border-radius: 0.875rem
.breakpoint-list
display: flex
flex-wrap: wrap
gap: 0.375rem
margin: 0
padding: 0.75rem 1rem 0
li
display: inline-flex
align-items: center
gap: 0.5rem
padding: 0.25rem 0.375rem 0.25rem 0.625rem
background-color: colors.$surface-raised
border: 1px solid colors.$border
border-radius: 0.5rem
font-size: 0.8125rem
code
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
button
display: inline-flex
align-items: center
justify-content: center
width: 1.25rem
height: 1.25rem
padding: 0
background: none
border: none
border-radius: 0.375rem
color: colors.$muted
cursor: pointer
svg
width: 0.8125rem
height: 0.8125rem
&:hover:not(:disabled)
background-color: colors.$error-tint
color: colors.$error
.breakpoint-method
color: colors.$warning
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace
font-size: 0.6875rem
font-weight: 700
.phase-icon
width: 0.875rem
height: 0.875rem
flex-shrink: 0
color: colors.$warning
.breakpoint-empty
background: none
border: none
padding: 0
color: colors.$muted
font-size: 0.8125rem
.breakpoint-add
display: grid
grid-template-columns: 8rem 8rem 1fr auto
gap: 0.5rem
align-items: start
padding: 0.75rem 1rem
@@ -0,0 +1,31 @@
import { useMemo } from "react";
import CodeEditor from "@/common/components/CodeEditor";
import { languageFor } from "@/common/components/CodeEditor/detect.js";
import { decode } from "./body.js";
const pretty = (text, language) => {
if (language !== "json") return text;
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
}
};
export const BodyView = ({ part, headers }) => {
const type = headers.find(([name]) => name.toLowerCase() === "content-type")?.[1] || "";
const language = languageFor(type);
const text = useMemo(() => (part.body ? decode(part.body) : null), [part.body]);
const source = useMemo(() => (text === null ? null : pretty(text, language)), [text, language]);
if (!part.bytes) return <p className="request-body-empty">No body</p>;
if (!part.body) return <p className="request-body-empty">Body was not stored</p>;
if (text === null) return <p className="request-body-empty">Binary, {part.bytes} bytes</p>;
return (
<>
<CodeEditor value={source} language={language} readOnly maxHeight="32rem" />
{part.truncated && <p className="request-body-note">Showing the first 64 kB of {part.bytes} bytes.</p>}
</>
);
};
@@ -0,0 +1,112 @@
import { useEffect, useRef, useState } from "react";
import { ArrowDown, ArrowUp, Send, Trash2 } from "lucide-react";
import { getRequest, postRequest } from "@/common/utils/RequestUtil.js";
import { useToast } from "@/common/contexts/toast.js";
import { formatBytes } from "@/common/utils/formatUtils.js";
import { formatTime } from "../../format.js";
import { decode } from "./body.js";
const POLL_INTERVAL = 1500;
const KEEP = 500;
const OPCODES = { 1: "text", 2: "binary", 8: "close", 9: "ping", 10: "pong" };
const FILTERS = [["all", "All"], ["in", "Received"], ["out", "Sent"]];
const describe = frame => {
const text = frame.payload ? decode(frame.payload) : "";
return { ...frame, kind: OPCODES[frame.opcode] || String(frame.opcode), text: text === null ? `binary, ${formatBytes(frame.bytes)}` : text };
};
export const FramesView = ({ tunnelId, entry }) => {
const { sendToast } = useToast();
const [frames, setFrames] = useState([]);
const [draft, setDraft] = useState("");
const [direction, setDirection] = useState("in");
const [filter, setFilter] = useState("all");
const [open, setOpen] = useState(true);
const [expanded, setExpanded] = useState(null);
const latest = useRef(0);
const list = useRef(null);
const pinned = useRef(true);
useEffect(() => {
let active = true;
const load = async () => {
try {
const data = await getRequest(`tunnels/${tunnelId}/requests/${entry.id}/frames?after=${latest.current}`);
if (!active) return;
setOpen(data.open);
if (!data.frames.length) return;
latest.current = data.frames[data.frames.length - 1].id;
setFrames(previous => [...previous, ...data.frames.map(describe)].slice(-KEEP));
} catch {
setOpen(false);
}
};
load();
if (!open) return () => { active = false; };
const poll = setInterval(load, POLL_INTERVAL);
return () => { active = false; clearInterval(poll); };
}, [tunnelId, entry.id, open]);
useEffect(() => {
if (pinned.current && list.current) list.current.scrollTop = list.current.scrollHeight;
}, [frames]);
const onScroll = () => {
const element = list.current;
pinned.current = element.scrollHeight - element.scrollTop - element.clientHeight < 8;
};
const send = async event => {
event.preventDefault();
if (!draft) return;
try {
await postRequest(`tunnels/${tunnelId}/requests/${entry.id}/frames`, { direction, text: draft });
setDraft("");
pinned.current = true;
} catch (error) {
sendToast("Error", error.message);
}
};
const shown = filter === "all" ? frames : frames.filter(frame => frame.direction === filter);
return (
<>
<div className="panel-card-head">
<h3>Messages</h3>
<div className="frame-tools">
{FILTERS.map(([key, label]) => (
<button key={key} type="button" className={filter === key ? "active" : ""} onClick={() => setFilter(key)}>{label}</button>
))}
<button type="button" onClick={() => setFrames([])} disabled={!frames.length} title="Clear" aria-label="Clear"><Trash2 /></button>
</div>
<span>{shown.length}{open ? " · live" : ""}</span>
</div>
{shown.length === 0
? <p className="request-body-empty">{open ? "No messages yet" : "No messages"}</p>
: <ul className="frames" ref={list} onScroll={onScroll}>
{shown.map(frame => (
<li key={frame.id} className={`frame ${frame.direction}${expanded === frame.id ? " expanded" : ""}`}
onClick={() => setExpanded(expanded === frame.id ? null : frame.id)}>
{frame.direction === "in" ? <ArrowUp /> : <ArrowDown />}
<span className="frame-kind">{frame.kind}</span>
<span className="frame-payload">{frame.text}</span>
<span className="frame-meta">{formatBytes(frame.bytes)} · {formatTime(frame.time)}</span>
</li>
))}
</ul>}
{open && (
<form className="frame-send" onSubmit={send}>
<div className="frame-target" role="radiogroup" aria-label="Send to">
<button type="button" className={`in${direction === "in" ? " active" : ""}`} onClick={() => setDirection("in")}><ArrowUp />App</button>
<button type="button" className={`out${direction === "out" ? " active" : ""}`} onClick={() => setDirection("out")}><ArrowDown />Visitor</button>
</div>
<input value={draft} onChange={event => setDraft(event.target.value)} spellCheck={false}
placeholder={direction === "in" ? "Message to your app" : "Message to the visitor"} />
<button type="submit" className="frame-submit" disabled={!draft} aria-label="Send"><Send /></button>
</form>
)}
</>
);
};
Loaded 100 of 438 files, more files were not shown because too many files have changed in this diff. Show more