feat: switch to a central singleton handler

This also adds support for Headscale TLS installations
This commit is contained in:
Aarnav Tale 2025-03-17 22:21:16 -04:00
parent 43e06987ad
commit 6108de52e7
No known key found for this signature in database
35 changed files with 339 additions and 399 deletions

View file

@ -9,11 +9,11 @@ import Spinner from '~/components/Spinner';
import Tabs from '~/components/Tabs';
import { hs_getConfig } from '~/utils/config/loader';
import { HeadscaleError, pull, put } from '~/utils/headscale';
import log from '~/utils/log';
import { send } from '~/utils/res';
import { getSession } from '~/utils/sessions.server';
import toast from '~/utils/toast';
import type { AppContext } from '~server/context/app';
import log from '~server/utils/log';
import { Differ, Editor } from './components/cm.client';
import { ErrorView } from './components/error';
import { Unavailable } from './components/unavailable';

View file

@ -1,11 +1,10 @@
import { LoaderFunctionArgs } from 'react-router';
import type { AppContext } from '~server/context/app';
import { hp_getSingleton, hp_getSingletonUnsafe } from '~server/context/global';
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
if (!context?.agentData) {
export async function loader({ request }: LoaderFunctionArgs) {
const data = hp_getSingletonUnsafe('ws_agent_data');
if (!data) {
return new Response(JSON.stringify({ error: 'Agent data unavailable' }), {
status: 400,
headers: {
@ -25,13 +24,14 @@ export async function loader({
});
}
const entries = context.agentData.toJSON();
const entries = data.toJSON();
const missing = nodeIds.filter((nodeID) => !entries[nodeID]);
if (missing.length > 0) {
await context.hp_agentRequest(missing);
const requestCall = hp_getSingleton('ws_fetch_data');
requestCall(missing);
}
return new Response(JSON.stringify(context.agentData), {
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
},

View file

@ -10,15 +10,10 @@ import Code from '~/components/Code';
import Input from '~/components/Input';
import type { Key } from '~/types';
import { pull } from '~/utils/headscale';
import { noContext } from '~/utils/log';
import { oidcEnabled } from '~/utils/oidc';
import { commitSession, getSession } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/machines', {
@ -28,37 +23,34 @@ export async function loader({
});
}
if (!context) {
throw noContext();
}
const context = hp_getConfig();
const disableApiKeyLogin = context.oidc?.disable_api_key_login;
let oidc = false;
// Only set if OIDC is properly enabled anyways
const ctx = context.context;
if (oidcEnabled() && ctx.oidc?.disable_api_key_login) {
return redirect('/oidc/start');
}
try {
// Only set if OIDC is properly enabled anyways
hp_getSingleton('oidc_client');
oidc = true;
if (disableApiKeyLogin) {
return redirect('/oidc/start');
}
} catch {}
return {
oidc: oidcEnabled(),
apiKey: !ctx.oidc?.disable_api_key_login,
oidc,
apiKey: !disableApiKeyLogin,
};
}
export async function action({
request,
context,
}: ActionFunctionArgs<AppContext>) {
export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const oidcStart = formData.get('oidc-start');
const session = await getSession(request.headers.get('Cookie'));
if (oidcStart) {
if (!context) {
throw noContext();
}
const ctx = context.context;
if (!ctx.oidc) {
const context = hp_getConfig();
if (!context.oidc) {
throw new Error('An invalid OIDC configuration was provided');
}

View file

@ -1,14 +1,21 @@
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { noContext } from '~/utils/log';
import { finishAuthFlow, formatError } from '~/utils/oidc';
import { send } from '~/utils/res';
import { commitSession, getSession } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
export async function loader({ request }: LoaderFunctionArgs) {
const { oidc } = hp_getConfig();
try {
if (!oidc) {
throw new Error('OIDC is not enabled');
}
hp_getSingleton('oidc_client');
} catch {
return send({ error: 'OIDC is not enabled' }, { status: 400 });
}
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
// Check if we have 0 query parameters
const url = new URL(request.url);
if (url.searchParams.toString().length === 0) {
@ -20,15 +27,6 @@ export async function loader({
return redirect('/machines');
}
if (!context) {
throw noContext();
}
const { oidc } = context.context;
if (!oidc) {
throw new Error('An invalid OIDC configuration was provided');
}
const codeVerifier = session.get('oidc_code_verif');
const state = session.get('oidc_state');
const nonce = session.get('oidc_nonce');

View file

@ -1,25 +1,24 @@
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { noContext } from '~/utils/log';
import { beginAuthFlow, getRedirectUri } from '~/utils/oidc';
import { send } from '~/utils/res';
import { commitSession, getSession } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/machines');
}
if (!context) {
throw noContext();
}
const { oidc } = hp_getConfig();
try {
if (!oidc) {
throw new Error('OIDC is not enabled');
}
const { oidc } = context.context;
if (!oidc) {
throw new Error('An invalid OIDC configuration was provided');
hp_getSingleton('oidc_client');
} catch {
return send({ error: 'OIDC is not enabled' }, { status: 400 });
}
const redirectUri = oidc.redirect_uri ?? getRedirectUri(request);

View file

@ -1,8 +1,8 @@
import type { ActionFunctionArgs } from 'react-router';
import { del, post } from '~/utils/headscale';
import log from '~/utils/log';
import { send } from '~/utils/res';
import { getSession } from '~/utils/sessions.server';
import log from '~server/utils/log';
export async function menuAction(request: ActionFunctionArgs['request']) {
const session = await getSession(request.headers.get('Cookie'));

View file

@ -14,16 +14,12 @@ import cn from '~/utils/cn';
import { hs_getConfig } from '~/utils/config/loader';
import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
import { hp_getSingleton } from '~server/context/global';
import { menuAction } from './action';
import MenuOptions from './components/menu';
import Routes from './dialogs/routes';
export async function loader({
request,
params,
context,
}: LoaderFunctionArgs<AppContext>) {
export async function loader({ request, params }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (!params.id) {
throw new Error('No machine ID provided');
@ -49,7 +45,7 @@ export async function loader({
routes: routes.routes.filter((route) => route.node.id === params.id),
users: users.users,
magic,
agent: context?.agents.includes(machine.node.id),
agent: [...hp_getSingleton('ws_agents').keys()].includes(machine.node.id),
};
}
@ -61,7 +57,6 @@ export default function Page() {
const { machine, magic, routes, users, agent } =
useLoaderData<typeof loader>();
const [showRouting, setShowRouting] = useState(false);
console.log(machine.expiry);
const expired =
machine.expiry === '0001-01-01 00:00:00' ||

View file

@ -12,17 +12,13 @@ import { getSession } from '~/utils/sessions.server';
import Tooltip from '~/components/Tooltip';
import { hs_getConfig } from '~/utils/config/loader';
import { noContext } from '~/utils/log';
import useAgent from '~/utils/useAgent';
import { AppContext } from '~server/context/app';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
import { menuAction } from './action';
import MachineRow from './components/machine';
import NewMachine from './dialogs/new';
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
const [machines, routes, users] = await Promise.all([
pull<{ nodes: Machine[] }>('v1/node', session.get('hsApiKey')!),
@ -30,11 +26,7 @@ export async function loader({
pull<{ users: User[] }>('v1/user', session.get('hsApiKey')!),
]);
if (!context) {
throw noContext();
}
const ctx = context.context;
const context = hp_getConfig();
const { mode, config } = hs_getConfig();
let magic: string | undefined;
@ -49,9 +41,9 @@ export async function loader({
routes: routes.routes,
users: users.users,
magic,
server: ctx.headscale.url,
publicServer: ctx.headscale.public_url,
agents: context.agents,
server: context.headscale.url,
publicServer: context.headscale.public_url,
agents: [...hp_getSingleton('ws_agents').keys()],
};
}

View file

@ -7,13 +7,39 @@ import Select from '~/components/Select';
import TableList from '~/components/TableList';
import type { PreAuthKey, User } from '~/types';
import { post, pull } from '~/utils/headscale';
import { noContext } from '~/utils/log';
import { send } from '~/utils/res';
import { getSession } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
import { hp_getConfig } from '~server/context/global';
import AuthKeyRow from './components/key';
import AddPreAuthKey from './dialogs/new';
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
const users = await pull<{ users: User[] }>(
'v1/user',
session.get('hsApiKey')!,
);
const context = hp_getConfig();
const preAuthKeys = await Promise.all(
users.users.map((user) => {
const qp = new URLSearchParams();
qp.set('user', user.name);
return pull<{ preAuthKeys: PreAuthKey[] }>(
`v1/preauthkey?${qp.toString()}`,
session.get('hsApiKey')!,
);
}),
);
return {
keys: preAuthKeys.flatMap((keys) => keys.preAuthKeys),
users: users.users,
server: context.headscale.public_url ?? context.headscale.url,
};
}
export async function action({ request }: ActionFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (!session.has('hsApiKey')) {
@ -91,40 +117,6 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
const users = await pull<{ users: User[] }>(
'v1/user',
session.get('hsApiKey')!,
);
if (!context) {
throw noContext();
}
const ctx = context.context;
const preAuthKeys = await Promise.all(
users.users.map((user) => {
const qp = new URLSearchParams();
qp.set('user', user.name);
return pull<{ preAuthKeys: PreAuthKey[] }>(
`v1/preauthkey?${qp.toString()}`,
session.get('hsApiKey')!,
);
}),
);
return {
keys: preAuthKeys.flatMap((keys) => keys.preAuthKeys),
users: users.users,
server: ctx.headscale.public_url ?? ctx.headscale.url,
};
}
export default function Page() {
const { keys, users, server } = useLoaderData<typeof loader>();
const [user, setUser] = useState('__headplane_all');

View file

@ -1,11 +1,11 @@
import { Building2, House, Key } from 'lucide-react';
import Card from '~/components/Card';
import Link from '~/components/Link';
import type { AppContext } from '~server/context/app';
import type { HeadplaneConfig } from '~server/context/parser';
import CreateUser from '../dialogs/create-user';
interface Props {
oidc?: NonNullable<AppContext['context']['oidc']>;
oidc?: NonNullable<HeadplaneConfig['oidc']>;
}
export default function ManageBanner({ oidc }: Props) {

View file

@ -15,22 +15,15 @@ import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import { hs_getConfig } from '~/utils/config/loader';
import { noContext } from '~/utils/log';
import type { AppContext } from '~server/context/app';
import { hp_getConfig } from '~server/context/global';
import ManageBanner from './components/manage-banner';
import DeleteUser from './dialogs/delete-user';
import RenameUser from './dialogs/rename-user';
import { userAction } from './user-actions';
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
if (!context) {
throw noContext();
}
const [machines, apiUsers] = await Promise.all([
pull<{ nodes: Machine[] }>('v1/node', session.get('hsApiKey')!),
pull<{ users: User[] }>('v1/user', session.get('hsApiKey')!),
@ -41,7 +34,7 @@ export async function loader({
machines: machines.nodes.filter((machine) => machine.user.id === user.id),
}));
const ctx = context.context;
const { oidc } = hp_getConfig();
const { mode, config } = hs_getConfig();
let magic: string | undefined;
@ -52,7 +45,7 @@ export async function loader({
}
return {
oidc: ctx.oidc,
oidc,
magic,
users,
};

View file

@ -1,5 +1,5 @@
import { healthcheck } from '~/utils/headscale';
import log from '~/utils/log';
import log from '~server/utils/log';
export async function loader() {
let healthy = false;