feat: respect context in server

This commit is contained in:
Aarnav Tale
2025-02-19 18:09:42 -05:00
parent 06049169a2
commit f5436f5ee3
32 changed files with 359 additions and 204 deletions
+19 -4
View File
@@ -1,24 +1,39 @@
import { PassThrough } from 'node:stream';
import { createReadableStreamFromReadable } from '@react-router/node';
import { isbot } from 'isbot';
import type { RenderToPipeableStreamOptions } from 'react-dom/server';
import { renderToPipeableStream } from 'react-dom/server';
import type { AppLoadContext, EntryContext } from 'react-router';
import { ServerRouter } from 'react-router';
import { hp_loadConfig } from '~/utils/context/loader';
import { hs_loadConfig } from '~/utils/config/loader';
import { hp_storeContext } from '~/utils/headscale';
import { hp_loadLogger } from '~/utils/log';
import { initSessionManager } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
hp_loadConfig();
export const streamTimeout = 5_000;
// TODO: checkOidc
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
routerContext: EntryContext,
loadContext: AppLoadContext,
loadContext: AppContext,
) {
const { context } = loadContext;
return new Promise((resolve, reject) => {
initSessionManager(
context.server.cookie_secret,
context.server.cookie_secure,
);
// This is a promise but we don't need to wait for it to finish
// before we start rendering the shell since it only loads once.
hs_loadConfig(context);
hp_storeContext(context);
hp_loadLogger(context.debug);
let shellRendered = false;
const userAgent = request.headers.get('user-agent');
+14 -5
View File
@@ -6,25 +6,34 @@ import {
} from 'react-router';
import Footer from '~/components/Footer';
import Header from '~/components/Header';
import { hs_getConfig } from '~/utils/config/loader';
import { noContext } from '~/utils/log';
import { getSession } from '~/utils/sessions.server';
import { hp_getConfig, hs_getConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
// This loads the bare minimum for the application to function
// So we know that if context fails to load then well, oops?
export async function loader({ request }: LoaderFunctionArgs) {
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
if (!session.has('hsApiKey')) {
return redirect('/login');
}
const context = hp_getConfig();
if (!context) {
throw noContext();
}
const ctx = context.context;
const { mode, config } = hs_getConfig();
return {
config,
url: context.headscale.public_url ?? context.headscale.url,
url: ctx.headscale.public_url ?? ctx.headscale.url,
configAvailable: mode !== 'no',
debug: context.debug,
debug: ctx.debug,
user: session.get('user'),
};
}
+3 -2
View File
@@ -7,17 +7,18 @@ import Link from '~/components/Link';
import Notice from '~/components/Notice';
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 { hs_getConfig } from '~/utils/state';
import toast from '~/utils/toast';
import type { AppContext } from '~server/context/app';
import { Differ, Editor } from './components/cm.client';
import { ErrorView } from './components/error';
import { Unavailable } from './components/unavailable';
export async function loader({ request }: LoaderFunctionArgs) {
export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
// The way policy is handled in 0.23 of Headscale and later is verbose.
+22 -9
View File
@@ -10,10 +10,14 @@ 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 { commitSession, getSession } from '~/utils/sessions.server';
import { hp_getConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
export async function loader({ request }: LoaderFunctionArgs) {
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/machines', {
@@ -23,28 +27,37 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
}
const context = hp_getConfig();
if (!context) {
throw noContext();
}
// Only set if OIDC is properly enabled anyways
if (context.oidc?.disable_api_key_login) {
const ctx = context.context;
if (ctx.oidc?.disable_api_key_login) {
return redirect('/oidc/start');
}
return {
oidc: context.oidc?.issuer,
apiKey: !context.oidc?.disable_api_key_login,
oidc: ctx.oidc?.issuer,
apiKey: !ctx.oidc?.disable_api_key_login,
};
}
export async function action({ request }: ActionFunctionArgs) {
export async function action({
request,
context,
}: ActionFunctionArgs<AppContext>) {
const formData = await request.formData();
const oidcStart = formData.get('oidc-start');
const session = await getSession(request.headers.get('Cookie'));
if (oidcStart) {
const context = hp_getConfig();
if (!context) {
throw noContext();
}
if (!context.oidc) {
const ctx = context.context;
if (!ctx.oidc) {
throw new Error('An invalid OIDC configuration was provided');
}
+12 -4
View File
@@ -1,10 +1,14 @@
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { finishAuthFlow, formatError, getRedirectUri } from '~/utils/oidc';
import { noContext } from '~/utils/log';
import { finishAuthFlow, formatError } from '~/utils/oidc';
import { send } from '~/utils/res';
import { commitSession, getSession } from '~/utils/sessions.server';
import { hp_getConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
export async function loader({ request }: LoaderFunctionArgs) {
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) {
@@ -16,7 +20,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/machines');
}
const { oidc } = hp_getConfig();
if (!context) {
throw noContext();
}
const { oidc } = context.context;
if (!oidc) {
throw new Error('An invalid OIDC configuration was provided');
}
+11 -5
View File
@@ -1,17 +1,23 @@
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { noContext } from '~/utils/log';
import { beginAuthFlow, getRedirectUri } from '~/utils/oidc';
import { commitSession, getSession } from '~/utils/sessions.server';
import { hp_getConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
export async function loader({ request }: LoaderFunctionArgs) {
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/machines');
}
// This is a hold-over from the old code
// TODO: Rewrite checkOIDC in the context loader
const { oidc } = hp_getConfig();
if (!context) {
throw noContext();
}
const { oidc } = context.context;
if (!oidc) {
throw new Error('An invalid OIDC configuration was provided');
}
+1 -2
View File
@@ -1,7 +1,6 @@
import { ActionFunctionArgs, data } from 'react-router';
import { hs_patchConfig } from '~/utils/config/loader';
import { hs_getConfig, hs_patchConfig } from '~/utils/config/loader';
import { auth } from '~/utils/sessions.server';
import { hs_getConfig } from '~/utils/state';
export async function dnsAction({ request }: ActionFunctionArgs) {
const session = await auth(request);
+1 -1
View File
@@ -2,7 +2,7 @@ import type { ActionFunctionArgs } from 'react-router';
import { useLoaderData } from 'react-router';
import Code from '~/components/Code';
import Notice from '~/components/Notice';
import { hs_getConfig } from '~/utils/state';
import { hs_getConfig } from '~/utils/config/loader';
import ManageDomains from './components/manage-domains';
import ManageNS from './components/manage-ns';
import ManageRecords from './components/manage-records';
+6 -2
View File
@@ -109,9 +109,13 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
const to = String(data.get('to'));
try {
await post(`v1/node/${id}/user?user=${to}`, session.get('hsApiKey')!);
await post(`v1/node/${id}/user`, session.get('hsApiKey')!, {
user: to,
});
return { message: `Moved node ${id} to ${to}` };
} catch {
} catch (error) {
console.error(error);
return send(
{ message: `Failed to move node ${id} to ${to}` },
{
+1 -1
View File
@@ -11,9 +11,9 @@ import StatusCircle from '~/components/StatusCircle';
import Tooltip from '~/components/Tooltip';
import type { Machine, Route, User } from '~/types';
import cn from '~/utils/cn';
import { hs_getConfig } from '~/utils/config/loader';
import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import { hs_getConfig } from '~/utils/state';
import { menuAction } from './action';
import MenuOptions from './components/menu';
import Routes from './dialogs/routes';
+15 -6
View File
@@ -12,12 +12,17 @@ import { getSession } from '~/utils/sessions.server';
import { initAgentSocket, queryAgent } from '~/utils/ws-agent';
import Tooltip from '~/components/Tooltip';
import { hp_getConfig, hs_getConfig } from '~/utils/state';
import { hs_getConfig } from '~/utils/config/loader';
import { noContext } from '~/utils/log';
import { AppContext } from '~server/context/app';
import { menuAction } from './action';
import MachineRow from './components/machine';
import NewMachine from './dialogs/new';
export async function loader({ request, context: lC }: LoaderFunctionArgs) {
export async function loader({
request,
context,
}: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
const [machines, routes, users] = await Promise.all([
pull<{ nodes: Machine[] }>('v1/node', session.get('hsApiKey')!),
@@ -25,10 +30,14 @@ export async function loader({ request, context: lC }: LoaderFunctionArgs) {
pull<{ users: User[] }>('v1/user', session.get('hsApiKey')!),
]);
initAgentSocket(lC);
if (!context) {
throw noContext();
}
initAgentSocket(context);
const stats = await queryAgent(machines.nodes.map((node) => node.nodeKey));
const context = hp_getConfig();
const ctx = context.context;
const { mode, config } = hs_getConfig();
let magic: string | undefined;
@@ -45,8 +54,8 @@ export async function loader({ request, context: lC }: LoaderFunctionArgs) {
users: users.users,
magic,
stats,
server: context.headscale.url,
publicServer: context.headscale.public_url,
server: ctx.headscale.url,
publicServer: ctx.headscale.public_url,
};
}
+12 -4
View File
@@ -7,9 +7,10 @@ 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 { hp_getConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
import AuthKeyRow from './components/key';
import AddPreAuthKey from './dialogs/new';
@@ -90,14 +91,21 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
export async function loader({ request }: LoaderFunctionArgs) {
const context = hp_getConfig();
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();
@@ -113,7 +121,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
return {
keys: preAuthKeys.flatMap((keys) => keys.preAuthKeys),
users: users.users,
server: context.headscale.public_url ?? context.headscale.url,
server: ctx.headscale.public_url ?? ctx.headscale.url,
};
}
+14 -16
View File
@@ -1,22 +1,23 @@
import { useMemo } from 'react';
import { useLoaderData, type LoaderFunctionArgs } from 'react-router';
import { getSession, commitSession } from '~/utils/sessions.server'
import { queryAgent } from '~/utils/ws-agent'
import AgentManagement from './components/agent/manage'
import { type LoaderFunctionArgs, useLoaderData } from 'react-router';
import { commitSession, getSession } from '~/utils/sessions.server';
import { queryAgent } from '~/utils/ws-agent';
import AgentManagement from './components/agent/manage';
export async function loader({ request, context }: LoaderFunctionArgs) {
const { ws, wsAuthKey } = context;
const session = await getSession(request.headers.get('Cookie'));
const onboarding = session.get('agent_onboarding') ?? false;
const nodeKey = 'nodekey:542dad28354eb8d51e240aada7adf0222ba3ecc74af0bbd56123f03eefdb391b'
const nodeKey =
'nodekey:542dad28354eb8d51e240aada7adf0222ba3ecc74af0bbd56123f03eefdb391b';
const stats = await queryAgent([nodeKey]);
return {
configured: wsAuthKey !== undefined,
onboarding,
stats: stats[nodeKey]
}
stats: stats?.[nodeKey],
};
}
export default function Page() {
@@ -24,21 +25,18 @@ export default function Page() {
// Whether we show the onboarding or management UI
const management = useMemo(() => {
return data.configured && (data.onboarding === false)
return data.configured && data.onboarding === false;
}, [data.configured, data.onboarding]);
return (
<div className="flex flex-col gap-8 max-w-screen-lg">
{management ? (
<AgentManagement
reachable={true}
hostInfo={data.stats}
/>
<AgentManagement reachable={true} hostInfo={data.stats} />
) : (
<div>
<h1>Local Agent Coming Soon</h1>
</div>
<div>
<h1>Local Agent Coming Soon</h1>
</div>
)}
</div>
)
);
}
@@ -1,11 +1,11 @@
import { Building2, House, Key } from 'lucide-react';
import Card from '~/components/Card';
import Link from '~/components/Link';
import { HeadplaneConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
import CreateUser from '../dialogs/create-user';
interface Props {
oidc?: NonNullable<HeadplaneConfig['oidc']>;
oidc?: NonNullable<AppContext['context']['oidc']>;
}
export default function ManageBanner({ oidc }: Props) {
+12 -4
View File
@@ -14,14 +14,22 @@ import cn from '~/utils/cn';
import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import { hp_getConfig, hs_getConfig } from '~/utils/state';
import { hs_getConfig } from '~/utils/config/loader';
import { noContext } from '~/utils/log';
import type { AppContext } from '~server/context/app';
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 }: LoaderFunctionArgs) {
export async function loader({
request,
context,
}: 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')!),
@@ -33,7 +41,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
machines: machines.nodes.filter((machine) => machine.user.id === user.id),
}));
const context = hp_getConfig();
const ctx = context.context;
const { mode, config } = hs_getConfig();
let magic: string | undefined;
@@ -44,7 +52,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
return {
oidc: context.oidc,
oidc: ctx.oidc,
magic,
users,
};
+2 -2
View File
@@ -1,8 +1,8 @@
import { constants, access, readFile, writeFile } from 'node:fs/promises';
import { Document, parseDocument } from 'yaml';
import { HeadplaneConfig } from '~/utils/context/parser';
import log from '~/utils/log';
import mutex from '~/utils/mutex';
import type { HeadplaneConfig } from '~server/context/parser';
import { HeadscaleConfig, validateConfig } from './parser';
let runtimeYaml: Document | undefined = undefined;
@@ -13,7 +13,7 @@ let runtimeStrict = true;
const runtimeLock = mutex();
type ConfigModes =
export type ConfigModes =
| {
mode: 'rw' | 'ro';
config: HeadscaleConfig;
-245
View File
@@ -1,245 +0,0 @@
import { constants, access, readFile } from 'node:fs/promises';
import { type } from 'arktype';
import { parseDocument } from 'yaml';
import { hs_loadConfig } from '~/utils/config/loader';
import log, { hp_loadLogger } from '~/utils/log';
import mutex from '~/utils/mutex';
import { testOidc } from '~/utils/oidc';
import { initSessionManager } from '~/utils/sessions.server';
import { HeadplaneConfig, coalesceConfig, validateConfig } from './parser';
const envBool = type('string | undefined').pipe((v) => {
return ['1', 'true', 'yes', 'on'].includes(v?.toLowerCase() ?? '');
});
const rootEnvs = type({
HEADPLANE_DEBUG_LOG: envBool,
HEADPLANE_LOAD_ENV_FILE: envBool,
HEADPLANE_LOAD_ENV_OVERRIDES: envBool,
HEADPLANE_CONFIG_PATH: 'string | undefined',
}).onDeepUndeclaredKey('reject');
const HEADPLANE_DEFAULT_CONFIG_PATH = '/etc/headplane/config.yaml';
let runtimeConfig: HeadplaneConfig | undefined = undefined;
const runtimeLock = mutex();
// We need to acquire here to ensure that the configuration is loaded
// properly. We can't request a configuration if its in the process
// of being updated.
export function hp_getConfig() {
runtimeLock.acquire();
if (!runtimeConfig) {
runtimeLock.release();
// This shouldn't be possible, we NEED to have a configuration
throw new Error('Configuration not loaded');
}
const config = runtimeConfig;
runtimeLock.release();
return config;
}
// hp_loadConfig should ONLY be called when we explicitly need to reload
// the configuration. This should be done when the configuration file
// changes and we ignore environment variable changes.
//
// To read the config hp_getConfig should be used.
// TODO: File watching for hp_loadConfig()
export async function hp_loadConfig() {
runtimeLock.acquire();
let path = HEADPLANE_DEFAULT_CONFIG_PATH;
const envs = rootEnvs({
HEADPLANE_DEBUG_LOG: process.env.HEADPLANE_DEBUG_LOG,
HEADPLANE_CONFIG_PATH: process.env.HEADPLANE_CONFIG_PATH,
HEADPLANE_LOAD_ENV_FILE: process.env.HEADPLANE_LOAD_ENV_FILE,
HEADPLANE_LOAD_ENV_OVERRIDES: process.env.HEADPLANE_LOAD_ENV_OVERRIDES,
});
if (envs instanceof type.errors) {
log.error('CFGX', 'Error parsing environment variables:');
for (const [number, error] of envs.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
return;
}
// Load our debug based logger before ANYTHING
hp_loadLogger(envs.HEADPLANE_DEBUG_LOG);
if (envs.HEADPLANE_CONFIG_PATH) {
path = envs.HEADPLANE_CONFIG_PATH;
}
await validateConfigPath(path);
const rawConfig = await loadConfigFile(path);
if (!rawConfig) {
log.error('CFGX', 'Failed to load Headplane configuration file');
process.exit(1);
}
let config = validateConfig({
...rawConfig,
debug: envs.HEADPLANE_DEBUG_LOG,
});
if (envs.HEADPLANE_LOAD_ENV_FILE) {
log.info('CFGX', 'Loading a .env file if one exists');
await import('dotenv/config');
}
if (config && envs.HEADPLANE_LOAD_ENV_OVERRIDES) {
log.info(
'CFGX',
'Loading environment variables to override the configuration',
);
config = coalesceEnv(config);
}
if (!config) {
runtimeLock.release();
log.error('CFGX', 'Fatal error encountered with configuration');
process.exit(1);
}
if (config.headscale.config_path) {
await hs_loadConfig(config);
}
if (config.oidc?.strict_validation) {
testOidc(config.oidc);
}
runtimeConfig = config;
initSessionManager(config.server.cookie_secret, config.server.cookie_secure);
runtimeLock.release();
}
async function validateConfigPath(path: string) {
log.debug('CFGX', `Validating Headplane configuration file at ${path}`);
try {
await access(path, constants.F_OK | constants.R_OK);
log.info('CFGX', `Headplane configuration found at ${path}`);
return true;
} catch (e) {
log.error('CFGX', `Headplane configuration not readable at ${path}`);
log.error('CFGX', `${e}`);
return false;
}
}
async function loadConfigFile(path: string) {
log.debug('CFGX', `Loading Headplane configuration file at ${path}`);
try {
const data = await readFile(path, 'utf8');
const configYaml = parseDocument(data);
if (configYaml.errors.length > 0) {
log.error(
'CFGX',
`Error parsing Headplane configuration file at ${path}`,
);
for (const error of configYaml.errors) {
log.error('CFGX', ` ${error.toString()}`);
}
return;
}
if (configYaml.warnings.length > 0) {
log.warn(
'CFGX',
`Warnings parsing Headplane configuration file at ${path}`,
);
for (const warning of configYaml.warnings) {
log.warn('CFGX', ` ${warning.toString()}`);
}
}
return configYaml.toJSON() as unknown;
} catch (e) {
log.error('CFGX', `Error reading Headplane configuration file at ${path}`);
log.error('CFGX', `${e}`);
return;
}
}
function coalesceEnv(config: HeadplaneConfig) {
const envConfig: Record<string, unknown> = {};
const rootKeys: string[] = rootEnvs.props.map((prop) => prop.key);
// Typescript is still insanely stupid at nullish filtering
const vars = Object.entries(process.env).filter(([key, value]) => {
if (!value) {
return false;
}
if (!key.startsWith('HEADPLANE_')) {
return false;
}
// Filter out the rootEnv configurations
if (rootKeys.includes(key)) {
return false;
}
return true;
}) as [string, string][];
log.debug('CFGX', `Coalescing ${vars.length} environment variables`);
for (const [key, value] of vars) {
const configPath = key.replace('HEADPLANE_', '').toLowerCase().split('__');
log.debug('CFGX', ` ${key}=${new Array(value.length).fill('*').join('')}`);
let current = envConfig;
while (configPath.length > 1) {
const path = configPath.shift() as string;
if (!(path in current)) {
current[path] = {};
}
current = current[path] as Record<string, unknown>;
}
current[configPath[0]] = value;
}
const toMerge = coalesceConfig(envConfig);
if (!toMerge) {
return;
}
// Deep merge the environment variables into the configuration
// This will overwrite any existing values in the configuration
return deepMerge(config, toMerge);
}
type DeepPartial<T> =
| {
[P in keyof T]?: DeepPartial<T[P]>;
}
| undefined;
function deepMerge<T>(target: T, source: DeepPartial<T>): T {
if (typeof target !== 'object' || typeof source !== 'object')
return source as T;
const result = { ...target } as T;
for (const key in source) {
const val = source[key];
if (val === undefined) {
continue;
}
if (typeof val === 'object') {
result[key] = deepMerge(result[key], val);
continue;
}
result[key] = val;
}
return result;
}
-78
View File
@@ -1,78 +0,0 @@
import { type } from 'arktype';
import log from '~/utils/log';
// TODO: ALLOW HEADSCALE CONFIG TO OVERRIDE HEADPLANE CONFIG MAYBE FOR OIDC?
export type HeadplaneConfig = typeof headplaneConfig.infer;
const stringToBool = type('string | boolean').pipe((v) => Boolean(v));
const serverConfig = type({
host: 'string.ip',
port: type('string | number.integer').pipe((v) => Number(v)),
cookie_secret: '32 <= string <= 32',
cookie_secure: stringToBool,
});
const oidcConfig = type({
issuer: 'string.url',
client_id: 'string',
client_secret: 'string',
token_endpoint_auth_method:
'"client_secret_basic" | "client_secret_post" | "client_secret_jwt"',
redirect_uri: 'string.url?',
disable_api_key_login: stringToBool,
headscale_api_key: 'string',
strict_validation: stringToBool.default(true),
}).onDeepUndeclaredKey('reject');
const headscaleConfig = type({
url: 'string.url',
public_url: 'string.url?',
config_path: 'string?',
config_strict: stringToBool,
}).onDeepUndeclaredKey('reject');
const headplaneConfig = type({
debug: stringToBool,
server: serverConfig,
'oidc?': oidcConfig,
headscale: headscaleConfig,
}).onDeepUndeclaredKey('reject');
const partialHeadplaneConfig = type({
debug: stringToBool,
server: serverConfig.partial(),
'oidc?': oidcConfig.partial(),
headscale: headscaleConfig.partial(),
}).partial();
export function validateConfig(config: unknown) {
log.debug('CFGX', 'Validating Headplane configuration...');
const out = headplaneConfig(config);
if (out instanceof type.errors) {
log.error('CFGX', 'Error parsing Headplane configuration:');
for (const [number, error] of out.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
return;
}
log.debug('CFGX', 'Headplane configuration is valid.');
return out;
}
export function coalesceConfig(config: unknown) {
log.debug('CFGX', 'Validating coalescing vars for configuration...');
const out = partialHeadplaneConfig(config);
if (out instanceof type.errors) {
log.error('CFGX', 'Error parsing variables:');
for (const [number, error] of out.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
return;
}
log.debug('CFGX', 'Coalescing variables is valid.');
return out;
}
+32 -7
View File
@@ -1,6 +1,7 @@
import log from '~/utils/log';
import { hp_getConfig } from '~/utils/state';
import log, { noContext } from '~/utils/log';
import { AppContext } from '~server/context/app';
type Context = AppContext['context'];
export class HeadscaleError extends Error {
status: number;
@@ -20,8 +21,20 @@ export class FatalError extends Error {
}
}
let context: Context | undefined = undefined;
export function hp_storeContext(ctx: Context) {
if (context) {
return;
}
context = ctx;
}
export async function healthcheck() {
const context = hp_getConfig();
if (!context) {
throw noContext();
}
const prefix = context.headscale.url;
log.debug('APIC', 'GET /health');
@@ -37,11 +50,14 @@ export async function healthcheck() {
}
export async function pull<T>(url: string, key: string) {
if (!context) {
throw noContext();
}
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = hp_getConfig();
const prefix = context.headscale.url;
log.debug('APIC', 'GET %s', `${prefix}/api/${url}`);
@@ -65,11 +81,14 @@ export async function pull<T>(url: string, key: string) {
}
export async function post<T>(url: string, key: string, body?: unknown) {
if (!context) {
throw noContext();
}
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = hp_getConfig();
const prefix = context.headscale.url;
log.debug('APIC', 'POST %s', `${prefix}/api/${url}`);
@@ -95,11 +114,14 @@ export async function post<T>(url: string, key: string, body?: unknown) {
}
export async function put<T>(url: string, key: string, body?: unknown) {
if (!context) {
throw noContext();
}
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = hp_getConfig();
const prefix = context.headscale.url;
log.debug('APIC', 'PUT %s', `${prefix}/api/${url}`);
@@ -125,11 +147,14 @@ export async function put<T>(url: string, key: string, body?: unknown) {
}
export async function del<T>(url: string, key: string) {
if (!context) {
throw noContext();
}
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = hp_getConfig();
const prefix = context.headscale.url;
log.debug('APIC', 'DELETE %s', `${prefix}/api/${url}`);
+6 -10
View File
@@ -3,16 +3,6 @@ export function hp_loadLogger(debug: boolean) {
log.debug = (category: string, message: string, ...args: unknown[]) => {
defaultLog('DEBG', category, message, ...args);
};
log.info('CFGX', 'Debug logging enabled');
log.info(
'CFGX',
'This is very verbose and should only be used for debugging purposes',
);
log.info(
'CFGX',
'If you run this in production, your storage WILL fill up quickly',
);
}
}
@@ -43,4 +33,10 @@ function defaultLog(
console.log(`${date} (${level}) [${category}] ${message}`, ...args);
}
export function noContext() {
return new Error(
'Context is not loaded. This is most likely a configuration error with your reverse proxy.',
);
}
export default log;
+2 -3
View File
@@ -1,13 +1,12 @@
import * as client from 'openid-client';
import log from '~/utils/log';
import { HeadplaneConfig } from '~/utils/state';
import type { AppContext } from '~server/context/app';
type OidcConfig = NonNullable<AppContext['context']['oidc']>;
declare global {
const __PREFIX__: string;
}
type OidcConfig = NonNullable<HeadplaneConfig['oidc']>;
// We try our best to infer the callback URI of our Headplane instance
// By default it is always /<base_path>/oidc/callback
// (This can ALWAYS be overridden through the OidcConfig)
-5
View File
@@ -1,5 +0,0 @@
export { hp_getConfig } from '~/utils/context/loader';
export { hs_getConfig } from '~/utils/config/loader';
export type { HeadplaneConfig } from '~/utils/context/parser';
export type { HeadscaleConfig } from '~/utils/config/parser';
+39 -32
View File
@@ -2,8 +2,8 @@
import { readFile, writeFile } from 'node:fs/promises';
import { setTimeout as pSetTimeout } from 'node:timers/promises';
import type { LoaderFunctionArgs } from 'react-router';
import type { HostInfo } from '~/types';
import { WebSocket } from 'ws';
import type { HostInfo } from '~/types';
import log from './log';
// Essentially a HashMap which invalidates entries after a certain time.
@@ -68,7 +68,7 @@ class TimedCache<K, V> {
this.writeLock = true;
const data = Array.from(this._cache.entries()).map(([key, value]) => {
return { key, value, expires: this._timeCache.get(key) }
return { key, value, expires: this._timeCache.get(key) };
});
await writeFile(this.filepath, JSON.stringify(data), 'utf-8');
@@ -85,10 +85,11 @@ export async function initAgentCache(defaultTTL: number, filepath: string) {
}
let agentSocket: WebSocket | undefined;
// TODO: Actually type this?
export function initAgentSocket(context: LoaderFunctionArgs['context']) {
if (!context.ws) {
return;
};
}
const client = context.ws.clients.values().next().value;
agentSocket = client;
@@ -97,21 +98,24 @@ export function initAgentSocket(context: LoaderFunctionArgs['context']) {
// Check the cache and then attempt the websocket query
// If we aren't connected to an agent, then debug log and return the cache
export async function queryAgent(nodes: string[]) {
return;
return;
// biome-ignore lint: bruh
if (!cache) {
log.error('CACH', 'Cache not initialized');
return;
}
const cached: Record<string, HostInfo> = {};
await Promise.all(nodes.map(async node => {
const cachedData = await cache?.get(node);
if (cachedData) {
cached[node] = cachedData;
}
}))
await Promise.all(
nodes.map(async (node) => {
const cachedData = await cache?.get(node);
if (cachedData) {
cached[node] = cachedData;
}
}),
);
const uncached = nodes.filter(node => !cached[node]);
const uncached = nodes.filter((node) => !cached[node]);
// No need to query the agent if we have all the data cached
if (uncached.length === 0) {
@@ -124,29 +128,32 @@ export async function queryAgent(nodes: string[]) {
return cached;
}
agentSocket.send(JSON.stringify({ NodeIDs: uncached }));
const returnData = await new Promise<Record<string, HostInfo> | void>((resolve, reject) => {
const timeout = setTimeout(() => {
agentSocket?.removeAllListeners('message');
resolve();
}, 3000);
agentSocket?.on('message', async (message: string) => {
const data = JSON.parse(message.toString());
if (Object.keys(data).length === 0) {
agentSocket?.send(JSON.stringify({ NodeIDs: uncached }));
// biome-ignore lint: bruh
const returnData = await new Promise<Record<string, HostInfo> | void>(
(resolve, reject) => {
const timeout = setTimeout(() => {
agentSocket?.removeAllListeners('message');
resolve();
}
}, 3000);
agentSocket?.removeAllListeners('message');
resolve(data);
});
});
if (returnData) {
for await (const [node, info] of Object.entries(returnData)) {
await cache.set(node, info);
}
}
agentSocket?.on('message', async (message: string) => {
const data = JSON.parse(message.toString());
if (Object.keys(data).length === 0) {
resolve();
}
agentSocket?.removeAllListeners('message');
resolve(data);
});
},
);
// if (returnData) {
// for await (const [node, info] of Object.entries(returnData)) {
// await cache?.set(node, info);
// }
// }
return returnData ? { ...cached, ...returnData } : cached;
}