mirror of
https://github.com/tale/headplane.git
synced 2026-08-27 23:47:31 +00:00
feat: switch to a central singleton handler
This also adds support for Headscale TLS installations
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { constants, access, readFile, writeFile } from 'node:fs/promises';
|
||||
import { Document, parseDocument } from 'yaml';
|
||||
import { hp_getIntegration } from '~/utils/integration/loader';
|
||||
import log from '~/utils/log';
|
||||
import mutex from '~/utils/mutex';
|
||||
import { hp_getConfig } from '~server/context/global';
|
||||
import log from '~server/utils/log';
|
||||
import { HeadscaleConfig, validateConfig } from './parser';
|
||||
|
||||
let runtimeYaml: Document | undefined = undefined;
|
||||
@@ -181,8 +182,9 @@ export async function hs_patchConfig(patches: PatchConfig[]) {
|
||||
}
|
||||
|
||||
// Revalidate the configuration
|
||||
const context = hp_getConfig();
|
||||
const newRawConfig = runtimeYaml.toJSON() as unknown;
|
||||
runtimeConfig = __hs_context.config_strict
|
||||
runtimeConfig = context.headscale.config_strict
|
||||
? validateConfig(newRawConfig, true)
|
||||
: (newRawConfig as HeadscaleConfig);
|
||||
|
||||
@@ -196,5 +198,7 @@ export async function hs_patchConfig(patches: PatchConfig[]) {
|
||||
}
|
||||
|
||||
// IMPORTANT THIS IS A SIDE EFFECT ON INIT
|
||||
hs_loadConfig(__hs_context.config_path, __hs_context.config_strict);
|
||||
// TODO: Replace this into the new singleton system
|
||||
const context = hp_getConfig();
|
||||
hs_loadConfig(context.headscale.config_path, context.headscale.config_strict);
|
||||
hp_getIntegration();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type } from 'arktype';
|
||||
import log from '~/utils/log';
|
||||
import log from '~server/utils/log';
|
||||
|
||||
const goBool = type('boolean | "true" | "false"').pipe((v) => {
|
||||
if (v === 'true') return true;
|
||||
|
||||
+35
-39
@@ -1,4 +1,6 @@
|
||||
import log, { noContext } from '~/utils/log';
|
||||
import { request } from 'undici';
|
||||
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
|
||||
import log from '~server/utils/log';
|
||||
|
||||
export class HeadscaleError extends Error {
|
||||
status: number;
|
||||
@@ -19,24 +21,18 @@ export class FatalError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
interface HeadscaleContext {
|
||||
url: string;
|
||||
}
|
||||
|
||||
declare const global: typeof globalThis & { __hs_context: HeadscaleContext };
|
||||
export async function healthcheck() {
|
||||
const prefix = __hs_context.url;
|
||||
log.debug('APIC', 'GET /health');
|
||||
|
||||
const health = new URL('health', prefix);
|
||||
const response = await fetch(health.toString(), {
|
||||
const health = new URL('health', hp_getConfig().headscale.url);
|
||||
const response = await request(health.toString(), {
|
||||
dispatcher: hp_getSingleton('api_agent'),
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Intentionally not catching
|
||||
return response.status === 200;
|
||||
return response.statusCode === 200;
|
||||
}
|
||||
|
||||
export async function pull<T>(url: string, key: string) {
|
||||
@@ -44,26 +40,26 @@ export async function pull<T>(url: string, key: string) {
|
||||
throw new Error('Missing API key, could this be a cookie setting issue?');
|
||||
}
|
||||
|
||||
const prefix = __hs_context.url;
|
||||
|
||||
const prefix = hp_getConfig().headscale.url;
|
||||
log.debug('APIC', 'GET %s', `${prefix}/api/${url}`);
|
||||
const response = await fetch(`${prefix}/api/${url}`, {
|
||||
const response = await request(`${prefix}/api/${url}`, {
|
||||
dispatcher: hp_getSingleton('api_agent'),
|
||||
headers: {
|
||||
Authorization: `Bearer ${key}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.statusCode >= 400) {
|
||||
log.debug(
|
||||
'APIC',
|
||||
'GET %s failed with status %d',
|
||||
`${prefix}/api/${url}`,
|
||||
response.status,
|
||||
response.statusCode,
|
||||
);
|
||||
throw new HeadscaleError(await response.text(), response.status);
|
||||
throw new HeadscaleError(await response.body.text(), response.statusCode);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
return response.body.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function post<T>(url: string, key: string, body?: unknown) {
|
||||
@@ -71,10 +67,10 @@ export async function post<T>(url: string, key: string, body?: unknown) {
|
||||
throw new Error('Missing API key, could this be a cookie setting issue?');
|
||||
}
|
||||
|
||||
const prefix = __hs_context.url;
|
||||
|
||||
const prefix = hp_getConfig().headscale.url;
|
||||
log.debug('APIC', 'POST %s', `${prefix}/api/${url}`);
|
||||
const response = await fetch(`${prefix}/api/${url}`, {
|
||||
const response = await request(`${prefix}/api/${url}`, {
|
||||
dispatcher: hp_getSingleton('api_agent'),
|
||||
method: 'POST',
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
headers: {
|
||||
@@ -82,17 +78,17 @@ export async function post<T>(url: string, key: string, body?: unknown) {
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.statusCode >= 400) {
|
||||
log.debug(
|
||||
'APIC',
|
||||
'POST %s failed with status %d',
|
||||
`${prefix}/api/${url}`,
|
||||
response.status,
|
||||
response.statusCode,
|
||||
);
|
||||
throw new HeadscaleError(await response.text(), response.status);
|
||||
throw new HeadscaleError(await response.body.text(), response.statusCode);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
return response.body.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function put<T>(url: string, key: string, body?: unknown) {
|
||||
@@ -100,10 +96,10 @@ export async function put<T>(url: string, key: string, body?: unknown) {
|
||||
throw new Error('Missing API key, could this be a cookie setting issue?');
|
||||
}
|
||||
|
||||
const prefix = __hs_context.url;
|
||||
|
||||
const prefix = hp_getConfig().headscale.url;
|
||||
log.debug('APIC', 'PUT %s', `${prefix}/api/${url}`);
|
||||
const response = await fetch(`${prefix}/api/${url}`, {
|
||||
const response = await request(`${prefix}/api/${url}`, {
|
||||
dispatcher: hp_getSingleton('api_agent'),
|
||||
method: 'PUT',
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
headers: {
|
||||
@@ -111,17 +107,17 @@ export async function put<T>(url: string, key: string, body?: unknown) {
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.statusCode >= 400) {
|
||||
log.debug(
|
||||
'APIC',
|
||||
'PUT %s failed with status %d',
|
||||
`${prefix}/api/${url}`,
|
||||
response.status,
|
||||
response.statusCode,
|
||||
);
|
||||
throw new HeadscaleError(await response.text(), response.status);
|
||||
throw new HeadscaleError(await response.body.text(), response.statusCode);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
return response.body.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function del<T>(url: string, key: string) {
|
||||
@@ -129,25 +125,25 @@ export async function del<T>(url: string, key: string) {
|
||||
throw new Error('Missing API key, could this be a cookie setting issue?');
|
||||
}
|
||||
|
||||
const prefix = __hs_context.url;
|
||||
|
||||
const prefix = hp_getConfig().headscale.url;
|
||||
log.debug('APIC', 'DELETE %s', `${prefix}/api/${url}`);
|
||||
const response = await fetch(`${prefix}/api/${url}`, {
|
||||
const response = await request(`${prefix}/api/${url}`, {
|
||||
dispatcher: hp_getSingleton('api_agent'),
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${key}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.statusCode >= 400) {
|
||||
log.debug(
|
||||
'APIC',
|
||||
'DELETE %s failed with status %d',
|
||||
`${prefix}/api/${url}`,
|
||||
response.status,
|
||||
response.statusCode,
|
||||
);
|
||||
throw new HeadscaleError(await response.text(), response.status);
|
||||
throw new HeadscaleError(await response.body.text(), response.statusCode);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
return response.body.json() as Promise<T>;
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ import { constants, access } from 'node:fs/promises';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
import { Client } from 'undici';
|
||||
import { HeadscaleError, healthcheck, pull } from '~/utils/headscale';
|
||||
import log from '~/utils/log';
|
||||
import { HeadplaneConfig } from '~server/context/parser';
|
||||
import log from '~server/utils/log';
|
||||
import { Integration } from './abstract';
|
||||
|
||||
type T = NonNullable<HeadplaneConfig['integration']>['docker'];
|
||||
|
||||
@@ -5,8 +5,8 @@ import { kill } from 'node:process';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
import { Config, CoreV1Api, KubeConfig } from '@kubernetes/client-node';
|
||||
import { HeadscaleError, healthcheck } from '~/utils/headscale';
|
||||
import log from '~/utils/log';
|
||||
import { HeadplaneConfig } from '~server/context/parser';
|
||||
import log from '~server/utils/log';
|
||||
import { Integration } from './abstract';
|
||||
|
||||
// TODO: Upgrade to the new CoreV1Api from @kubernetes/client-node
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import log from '~/utils/log';
|
||||
import { hp_getConfig } from '~server/context/global';
|
||||
import { HeadplaneConfig } from '~server/context/parser';
|
||||
import log from '~server/utils/log';
|
||||
import { Integration } from './abstract';
|
||||
import dockerIntegration from './docker';
|
||||
import kubernetesIntegration from './kubernetes';
|
||||
@@ -66,4 +67,6 @@ function getIntegration(integration: HeadplaneConfig['integration']) {
|
||||
}
|
||||
|
||||
// IMPORTANT THIS IS A SIDE EFFECT ON INIT
|
||||
hp_loadIntegration(__integration_context);
|
||||
// TODO: Switch this to the new singleton system
|
||||
const context = hp_getConfig();
|
||||
hp_loadIntegration(context.integration);
|
||||
|
||||
@@ -4,8 +4,8 @@ import { join, resolve } from 'node:path';
|
||||
import { kill } from 'node:process';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
import { HeadscaleError, healthcheck } from '~/utils/headscale';
|
||||
import log from '~/utils/log';
|
||||
import { HeadplaneConfig } from '~server/context/parser';
|
||||
import log from '~server/utils/log';
|
||||
import { Integration } from './abstract';
|
||||
|
||||
type T = NonNullable<HeadplaneConfig['integration']>['proc'];
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
export function hp_loadLogger(debug: boolean) {
|
||||
if (debug) {
|
||||
log.debug = (category: string, message: string, ...args: unknown[]) => {
|
||||
defaultLog('DEBG', category, message, ...args);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const log = {
|
||||
info: (category: string, message: string, ...args: unknown[]) => {
|
||||
defaultLog('INFO', category, message, ...args);
|
||||
},
|
||||
|
||||
warn: (category: string, message: string, ...args: unknown[]) => {
|
||||
defaultLog('WARN', category, message, ...args);
|
||||
},
|
||||
|
||||
error: (category: string, message: string, ...args: unknown[]) => {
|
||||
defaultLog('ERRO', category, message, ...args);
|
||||
},
|
||||
|
||||
// Default to a no-op until the logger is initialized
|
||||
debug: (category: string, message: string, ...args: unknown[]) => {},
|
||||
};
|
||||
|
||||
function defaultLog(
|
||||
level: string,
|
||||
category: string,
|
||||
message: string,
|
||||
...args: unknown[]
|
||||
) {
|
||||
const date = new Date().toISOString();
|
||||
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;
|
||||
+6
-23
@@ -1,9 +1,10 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import * as client from 'openid-client';
|
||||
import type { AppContext } from '~server/context/app';
|
||||
import { hp_getSingleton, hp_setSingleton } from '~server/context/global';
|
||||
import { HeadplaneConfig } from '~server/context/parser';
|
||||
import log from '~server/utils/log';
|
||||
|
||||
type OidcConfig = NonNullable<AppContext['context']['oidc']>;
|
||||
type OidcConfig = NonNullable<HeadplaneConfig['oidc']>;
|
||||
declare global {
|
||||
const __PREFIX__: string;
|
||||
}
|
||||
@@ -103,13 +104,7 @@ function clientAuthMethod(
|
||||
}
|
||||
|
||||
export async function beginAuthFlow(oidc: OidcConfig, redirect_uri: string) {
|
||||
const config = await client.discovery(
|
||||
new URL(oidc.issuer),
|
||||
oidc.client_id,
|
||||
oidc.client_secret,
|
||||
clientAuthMethod(oidc.token_endpoint_auth_method)(__oidc_context.secret),
|
||||
);
|
||||
|
||||
const config = hp_getSingleton('oidc_client');
|
||||
const codeVerifier = client.randomPKCECodeVerifier();
|
||||
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
|
||||
|
||||
@@ -145,16 +140,7 @@ interface FlowOptions {
|
||||
}
|
||||
|
||||
export async function finishAuthFlow(oidc: OidcConfig, options: FlowOptions) {
|
||||
const config = await client.discovery(
|
||||
new URL(oidc.issuer),
|
||||
oidc.client_id,
|
||||
oidc.client_secret,
|
||||
clientAuthMethod(oidc.token_endpoint_auth_method)(__oidc_context.secret),
|
||||
);
|
||||
|
||||
let subject: string;
|
||||
let accessToken: string;
|
||||
|
||||
const config = hp_getSingleton('oidc_client');
|
||||
const tokens = await client.authorizationCodeGrant(
|
||||
config,
|
||||
new URL(options.redirect_uri),
|
||||
@@ -255,10 +241,6 @@ export function formatError(error: unknown) {
|
||||
};
|
||||
}
|
||||
|
||||
export function oidcEnabled() {
|
||||
return __oidc_context.valid;
|
||||
}
|
||||
|
||||
export async function testOidc(oidc: OidcConfig) {
|
||||
await resolveClientSecret(oidc);
|
||||
if (!oidcSecret) {
|
||||
@@ -312,5 +294,6 @@ export async function testOidc(oidc: OidcConfig) {
|
||||
}
|
||||
|
||||
log.debug('OIDC', 'OIDC configuration is valid');
|
||||
hp_setSingleton('oidc_client', config);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Session, createCookieSessionStorage } from 'react-router';
|
||||
import { hp_getConfig } from '~server/context/global';
|
||||
|
||||
export type SessionData = {
|
||||
hsApiKey: string;
|
||||
@@ -21,6 +22,8 @@ type SessionFlashData = {
|
||||
};
|
||||
|
||||
// TODO: Domain config in cookies
|
||||
// TODO: Move this to the singleton system
|
||||
const context = hp_getConfig();
|
||||
const sessionStorage = createCookieSessionStorage<
|
||||
SessionData,
|
||||
SessionFlashData
|
||||
@@ -31,8 +34,8 @@ const sessionStorage = createCookieSessionStorage<
|
||||
maxAge: 60 * 60 * 24, // 24 hours
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
secrets: [__cookie_context.cookie_secret],
|
||||
secure: __cookie_context.cookie_secure,
|
||||
secrets: [context.server.cookie_secret],
|
||||
secure: context.server.cookie_secure,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { setTimeout as pSetTimeout } from 'node:timers/promises';
|
||||
import type { LoaderFunctionArgs } from 'react-router';
|
||||
import { WebSocket } from 'ws';
|
||||
import type { HostInfo } from '~/types';
|
||||
import log from './log';
|
||||
import log from '~server/utils/log';
|
||||
|
||||
// Essentially a HashMap which invalidates entries after a certain time.
|
||||
// It also is capable of syncing as a compressed file to disk.
|
||||
@@ -99,7 +99,6 @@ export function initAgentSocket(context: LoaderFunctionArgs['context']) {
|
||||
// If we aren't connected to an agent, then debug log and return the cache
|
||||
export async function queryAgent(nodes: string[]) {
|
||||
return;
|
||||
// biome-ignore lint: bruh
|
||||
if (!cache) {
|
||||
log.error('CACH', 'Cache not initialized');
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user