chore: switch to react-router v7

This commit is contained in:
Aarnav Tale
2024-12-31 10:30:14 +05:30
parent 39504e2487
commit aa9872a45b
101 changed files with 3825 additions and 6796 deletions
+3 -3
View File
@@ -1,4 +1,4 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs))
export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs));
+116 -108
View File
@@ -3,82 +3,82 @@
//
// Around the codebase, this is referred to as the context
import { access, constants, readFile, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { access, constants, readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { parse } from 'yaml'
import { parse } from 'yaml';
import { IntegrationFactory, loadIntegration } from '~/integration'
import { HeadscaleConfig, loadConfig } from '~/utils/config/headscale'
import { testOidc } from '~/utils/oidc'
import log from '~/utils/log'
import { IntegrationFactory, loadIntegration } from '~/integration';
import { HeadscaleConfig, loadConfig } from '~/utils/config/headscale';
import { testOidc } from '~/utils/oidc';
import log from '~/utils/log';
export interface HeadplaneContext {
debug: boolean
headscaleUrl: string
headscalePublicUrl?: string
cookieSecret: string
integration: IntegrationFactory | undefined
debug: boolean;
headscaleUrl: string;
headscalePublicUrl?: string;
cookieSecret: string;
integration: IntegrationFactory | undefined;
config: {
read: boolean
write: boolean
}
read: boolean;
write: boolean;
};
oidc?: {
issuer: string
client: string
secret: string
rootKey: string
method: string
disableKeyLogin: boolean
}
issuer: string;
client: string;
secret: string;
rootKey: string;
method: string;
disableKeyLogin: boolean;
};
}
let context: HeadplaneContext | undefined
let context: HeadplaneContext | undefined;
export async function loadContext(): Promise<HeadplaneContext> {
if (context) {
return context
return context;
}
const envFile = process.env.LOAD_ENV_FILE === 'true'
const envFile = process.env.LOAD_ENV_FILE === 'true';
if (envFile) {
log.info('CTXT', 'Loading environment variables from .env')
await import('dotenv/config')
log.info('CTXT', 'Loading environment variables from .env');
await import('dotenv/config');
}
const debug = process.env.DEBUG === 'true'
const debug = process.env.DEBUG === 'true';
if (debug) {
log.info('CTXT', 'Debug mode is enabled! Logs will spam a lot.')
log.info('CTXT', 'Please disable debug mode in production.')
log.info('CTXT', 'Debug mode is enabled! Logs will spam a lot.');
log.info('CTXT', 'Please disable debug mode in production.');
}
const path = resolve(process.env.CONFIG_FILE ?? '/etc/headscale/config.yaml')
const { config, contextData } = await checkConfig(path)
const path = resolve(process.env.CONFIG_FILE ?? '/etc/headscale/config.yaml');
const { config, contextData } = await checkConfig(path);
let headscaleUrl = process.env.HEADSCALE_URL
let headscalePublicUrl = process.env.HEADSCALE_PUBLIC_URL
let headscaleUrl = process.env.HEADSCALE_URL;
let headscalePublicUrl = process.env.HEADSCALE_PUBLIC_URL;
if (!headscaleUrl && !config) {
throw new Error('HEADSCALE_URL not set')
throw new Error('HEADSCALE_URL not set');
}
if (config) {
headscaleUrl = headscaleUrl ?? config.server_url
headscaleUrl = headscaleUrl ?? config.server_url;
if (!headscalePublicUrl) {
// Fallback to the config value if the env var is not set
headscalePublicUrl = config.public_url
headscalePublicUrl = config.public_url;
}
}
if (!headscaleUrl) {
throw new Error('Missing server_url in headscale config')
throw new Error('Missing server_url in headscale config');
}
const cookieSecret = process.env.COOKIE_SECRET
const cookieSecret = process.env.COOKIE_SECRET;
if (!cookieSecret) {
throw new Error('COOKIE_SECRET not set')
throw new Error('COOKIE_SECRET not set');
}
context = {
@@ -89,48 +89,51 @@ export async function loadContext(): Promise<HeadplaneContext> {
integration: await loadIntegration(),
config: contextData,
oidc: await checkOidc(config),
}
};
log.info('CTXT', 'Starting Headplane with Context')
log.info('CTXT', 'HEADSCALE_URL: %s', headscaleUrl)
log.info('CTXT', 'Starting Headplane with Context');
log.info('CTXT', 'HEADSCALE_URL: %s', headscaleUrl);
if (headscalePublicUrl) {
log.info('CTXT', 'HEADSCALE_PUBLIC_URL: %s', headscalePublicUrl)
log.info('CTXT', 'HEADSCALE_PUBLIC_URL: %s', headscalePublicUrl);
}
log.info('CTXT', 'Integration: %s', context.integration?.name ?? 'None')
log.info('CTXT', 'Config: %s', contextData.read
? `Found ${contextData.write ? '' : '(Read Only)'}`
: 'Unavailable',
)
log.info('CTXT', 'Integration: %s', context.integration?.name ?? 'None');
log.info(
'CTXT',
'Config: %s',
contextData.read
? `Found ${contextData.write ? '' : '(Read Only)'}`
: 'Unavailable',
);
log.info('CTXT', 'OIDC: %s', context.oidc ? 'Configured' : 'Unavailable')
return context
log.info('CTXT', 'OIDC: %s', context.oidc ? 'Configured' : 'Unavailable');
return context;
}
async function checkConfig(path: string) {
log.debug('CTXT', 'Checking config at %s', path)
log.debug('CTXT', 'Checking config at %s', path);
let config: HeadscaleConfig | undefined
let config: HeadscaleConfig | undefined;
try {
config = await loadConfig(path)
config = await loadConfig(path);
} catch {
log.debug('CTXT', 'Config at %s failed to load', path)
log.debug('CTXT', 'Config at %s failed to load', path);
return {
config: undefined,
contextData: {
read: false,
write: false,
},
}
};
}
let write = false
let write = false;
try {
log.debug('CTXT', 'Checking write access to %s', path)
await access(path, constants.W_OK)
write = true
log.debug('CTXT', 'Checking write access to %s', path);
await access(path, constants.W_OK);
write = true;
} catch {
log.debug('CTXT', 'No write access to %s', path)
log.debug('CTXT', 'No write access to %s', path);
}
return {
@@ -139,49 +142,52 @@ async function checkConfig(path: string) {
read: true,
write,
},
}
};
}
async function checkOidc(config?: HeadscaleConfig) {
log.debug('CTXT', 'Checking OIDC configuration')
log.debug('CTXT', 'Checking OIDC configuration');
const disableKeyLogin = process.env.DISABLE_API_KEY_LOGIN === 'true'
log.debug('CTXT', 'API Key Login Enabled: %s', !disableKeyLogin)
const disableKeyLogin = process.env.DISABLE_API_KEY_LOGIN === 'true';
log.debug('CTXT', 'API Key Login Enabled: %s', !disableKeyLogin);
log.debug('CTXT', 'Checking ROOT_API_KEY and falling back to API_KEY')
const rootKey = process.env.ROOT_API_KEY ?? process.env.API_KEY
log.debug('CTXT', 'Checking ROOT_API_KEY and falling back to API_KEY');
const rootKey = process.env.ROOT_API_KEY ?? process.env.API_KEY;
if (!rootKey) {
throw new Error('ROOT_API_KEY or API_KEY not set')
throw new Error('ROOT_API_KEY or API_KEY not set');
}
let issuer = process.env.OIDC_ISSUER
let client = process.env.OIDC_CLIENT_ID
let secret = process.env.OIDC_CLIENT_SECRET
let method = process.env.OIDC_CLIENT_SECRET_METHOD ?? 'client_secret_basic'
let skip = process.env.OIDC_SKIP_CONFIG_VALIDATION === 'true'
let issuer = process.env.OIDC_ISSUER;
let client = process.env.OIDC_CLIENT_ID;
let secret = process.env.OIDC_CLIENT_SECRET;
let method = process.env.OIDC_CLIENT_SECRET_METHOD ?? 'client_secret_basic';
let skip = process.env.OIDC_SKIP_CONFIG_VALIDATION === 'true';
log.debug('CTXT', 'Checking OIDC environment variables')
log.debug('CTXT', 'Issuer: %s', issuer)
log.debug('CTXT', 'Client: %s', client)
log.debug('CTXT', 'Checking OIDC environment variables');
log.debug('CTXT', 'Issuer: %s', issuer);
log.debug('CTXT', 'Client: %s', client);
if (
(issuer ?? client ?? secret)
&& !(issuer && client && secret)
&& !config
(issuer ?? client ?? secret) &&
!(issuer && client && secret) &&
!config
) {
throw new Error('OIDC environment variables are incomplete')
throw new Error('OIDC environment variables are incomplete');
}
if (issuer && client && secret) {
if (!skip) {
log.debug('CTXT', 'Validating OIDC configuration from environment variables')
const result = await testOidc(issuer, client, secret)
log.debug(
'CTXT',
'Validating OIDC configuration from environment variables',
);
const result = await testOidc(issuer, client, secret);
if (!result) {
return
return;
}
} else {
log.debug('CTXT', 'OIDC_SKIP_CONFIG_VALIDATION is set')
log.debug('CTXT', 'Skipping OIDC configuration validation')
log.debug('CTXT', 'OIDC_SKIP_CONFIG_VALIDATION is set');
log.debug('CTXT', 'Skipping OIDC configuration validation');
}
return {
@@ -191,51 +197,53 @@ async function checkOidc(config?: HeadscaleConfig) {
method,
rootKey,
disableKeyLogin,
}
};
}
if ((!issuer || !client || !secret) && config) {
issuer = config.oidc?.issuer
client = config.oidc?.client_id
secret = config.oidc?.client_secret
issuer = config.oidc?.issuer;
client = config.oidc?.client_id;
secret = config.oidc?.client_secret;
if (!secret && config.oidc?.client_secret_path) {
log.debug('CTXT', 'Trying to read OIDC client secret from %s', config.oidc.client_secret_path)
log.debug(
'CTXT',
'Trying to read OIDC client secret from %s',
config.oidc.client_secret_path,
);
try {
const data = await readFile(
config.oidc.client_secret_path,
'utf8',
)
const data = await readFile(config.oidc.client_secret_path, 'utf8');
if (data && data.length > 0) {
secret = data.trim()
secret = data.trim();
}
} catch {
log.error('CTXT', 'Failed to read OIDC client secret from %s', config.oidc.client_secret_path)
log.error(
'CTXT',
'Failed to read OIDC client secret from %s',
config.oidc.client_secret_path,
);
}
}
}
if (
(issuer ?? client ?? secret)
&& !(issuer && client && secret)
) {
throw new Error('OIDC configuration is incomplete')
if ((issuer ?? client ?? secret) && !(issuer && client && secret)) {
throw new Error('OIDC configuration is incomplete');
}
if (!issuer || !client || !secret) {
return
return;
}
if (config.oidc.only_start_if_oidc_is_available) {
log.debug('CTXT', 'Validating OIDC configuration from headscale config')
const result = await testOidc(issuer, client, secret)
log.debug('CTXT', 'Validating OIDC configuration from headscale config');
const result = await testOidc(issuer, client, secret);
if (!result) {
return
return;
}
} else {
log.debug('CTXT', 'OIDC validation is disabled in headscale config')
log.debug('CTXT', 'Skipping OIDC configuration validation')
log.debug('CTXT', 'OIDC validation is disabled in headscale config');
log.debug('CTXT', 'Skipping OIDC configuration validation');
}
return {
@@ -245,5 +253,5 @@ async function checkOidc(config?: HeadscaleConfig) {
rootKey,
method,
disableKeyLogin,
}
};
}
+135 -112
View File
@@ -6,29 +6,31 @@
// Around the codebase, this is referred to as the config
// Refer to this file on juanfont/headscale for the default values:
// https://github.com/juanfont/headscale/blob/main/hscontrol/types/config.go
import { readFile, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { type Document, parseDocument } from 'yaml'
import { z } from 'zod'
import { type Document, parseDocument } from 'yaml';
import { z } from 'zod';
import log from '~/utils/log'
import log from '~/utils/log';
const goBool = z
.union([z.boolean(), z.literal('true'), z.literal('false')])
.transform((value) => {
if (typeof value === 'boolean') {
return value
return value;
}
return value === 'true'
})
return value === 'true';
});
const goDuration = z.union([z.literal(0), z.string()])
const goDuration = z.union([z.literal(0), z.string()]);
const HeadscaleConfig = z.object({
tls_letsencrypt_cache_dir: z.string().default('/var/www/cache'),
tls_letsencrypt_challenge_type: z.enum(['HTTP-01', 'TLS-ALPN-01']).default('HTTP-01'),
tls_letsencrypt_challenge_type: z
.enum(['HTTP-01', 'TLS-ALPN-01'])
.default('HTTP-01'),
tls_letsencrypt_hostname: z.string().optional(),
tls_letsencrypt_listen: z.string().optional(),
@@ -52,35 +54,45 @@ const HeadscaleConfig = z.object({
unix_socket: z.string().default('/var/run/headscale/headscale.sock'),
unix_socket_permission: z.string().default('0o770'),
policy: z.object({
mode: z.enum(['file', 'database']).default('file'),
path: z.string().optional(),
}).optional(),
policy: z
.object({
mode: z.enum(['file', 'database']).default('file'),
path: z.string().optional(),
})
.optional(),
tuning: z.object({
batch_change_delay: goDuration.default('800ms'),
node_mapsession_buffered_chan_size: z.number().default(30),
}).optional(),
tuning: z
.object({
batch_change_delay: goDuration.default('800ms'),
node_mapsession_buffered_chan_size: z.number().default(30),
})
.optional(),
noise: z.object({
private_key_path: z.string(),
}),
log: z.object({
level: z.string().default('info'),
format: z.enum(['text', 'json']).default('text'),
}).default({ level: 'info', format: 'text' }),
log: z
.object({
level: z.string().default('info'),
format: z.enum(['text', 'json']).default('text'),
})
.default({ level: 'info', format: 'text' }),
logtail: z.object({
enabled: goBool.default(false),
}).default({ enabled: false }),
logtail: z
.object({
enabled: goBool.default(false),
})
.default({ enabled: false }),
cli: z.object({
address: z.string().optional(),
api_key: z.string().optional(),
timeout: goDuration.default('10s'),
insecure: goBool.default(false),
}).optional(),
cli: z
.object({
address: z.string().optional(),
api_key: z.string().optional(),
timeout: goDuration.default('10s'),
insecure: goBool.default(false),
})
.optional(),
prefixes: z.object({
allocation: z.enum(['sequential', 'random']).default('sequential'),
@@ -91,34 +103,42 @@ const HeadscaleConfig = z.object({
dns: z.object({
magic_dns: goBool.default(true),
base_domain: z.string().default('headscale.net'),
nameservers: z.object({
global: z.array(z.string()).default([]),
split: z.record(z.array(z.string())).default({}),
}).default({ global: [], split: {} }),
nameservers: z
.object({
global: z.array(z.string()).default([]),
split: z.record(z.array(z.string())).default({}),
})
.default({ global: [], split: {} }),
search_domains: z.array(z.string()).default([]),
extra_records: z.array(z.object({
name: z.string(),
type: z.literal('A'),
value: z.string(),
})).default([]),
extra_records: z
.array(
z.object({
name: z.string(),
type: z.literal('A'),
value: z.string(),
}),
)
.default([]),
use_username_in_magic_dns: goBool.default(false),
}),
oidc: z.object({
only_start_if_oidc_is_available: goBool.default(false),
issuer: z.string().optional(),
client_id: z.string().optional(),
client_secret: z.string().optional(),
client_secret_path: z.string().optional(),
scope: z.array(z.string()).default(['openid', 'profile', 'email']),
extra_params: z.record(z.unknown()).default({}),
allowed_domains: z.array(z.string()).optional(),
allowed_users: z.array(z.string()).optional(),
allowed_groups: z.array(z.string()).optional(),
strip_email_domain: goBool.default(false),
expiry: goDuration.default('180d'),
use_expiry_from_token: goBool.default(false),
}).optional(),
oidc: z
.object({
only_start_if_oidc_is_available: goBool.default(false),
issuer: z.string().optional(),
client_id: z.string().optional(),
client_secret: z.string().optional(),
client_secret_path: z.string().optional(),
scope: z.array(z.string()).default(['openid', 'profile', 'email']),
extra_params: z.record(z.unknown()).default({}),
allowed_domains: z.array(z.string()).optional(),
allowed_users: z.array(z.string()).optional(),
allowed_groups: z.array(z.string()).optional(),
strip_email_domain: goBool.default(false),
expiry: goDuration.default('180d'),
use_expiry_from_token: goBool.default(false),
})
.optional(),
database: z.union([
z.object({
@@ -171,33 +191,35 @@ const HeadscaleConfig = z.object({
auto_update_enabled: goBool.default(true),
update_frequency: goDuration.default('24h'),
}),
})
});
export type HeadscaleConfig = z.infer<typeof HeadscaleConfig>
export type HeadscaleConfig = z.infer<typeof HeadscaleConfig>;
export let configYaml: Document | undefined
export let config: HeadscaleConfig | undefined
export let configYaml: Document | undefined;
export let config: HeadscaleConfig | undefined;
export async function loadConfig(path?: string) {
if (config) {
return config
return config;
}
if (!path) {
throw new Error('Path is required to lazy load config')
throw new Error('Path is required to lazy load config');
}
log.debug('CFGX', 'Loading Headscale configuration from %s', path)
const data = await readFile(path, 'utf8')
configYaml = parseDocument(data)
log.debug('CFGX', 'Loading Headscale configuration from %s', path);
const data = await readFile(path, 'utf8');
configYaml = parseDocument(data);
if (process.env.HEADSCALE_CONFIG_UNSTRICT === 'true') {
log.debug('CFGX', 'Loaded Headscale configuration in non-strict mode')
const loaded = configYaml.toJSON() as Record<string, unknown>
log.debug('CFGX', 'Loaded Headscale configuration in non-strict mode');
const loaded = configYaml.toJSON() as Record<string, unknown>;
config = {
...loaded,
tls_letsencrypt_cache_dir: loaded.tls_letsencrypt_cache_dir ?? '/var/www/cache',
tls_letsencrypt_challenge_type: loaded.tls_letsencrypt_challenge_type ?? 'HTTP-01',
tls_letsencrypt_cache_dir:
loaded.tls_letsencrypt_cache_dir ?? '/var/www/cache',
tls_letsencrypt_challenge_type:
loaded.tls_letsencrypt_challenge_type ?? 'HTTP-01',
grpc_listen_addr: loaded.grpc_listen_addr ?? ':50443',
grpc_allow_insecure: loaded.grpc_allow_insecure ?? false,
randomize_client_port: loaded.randomize_client_port ?? false,
@@ -238,54 +260,54 @@ export async function loadConfig(path?: string) {
magic_dns: false,
base_domain: 'headscale.net',
},
} as HeadscaleConfig
} as HeadscaleConfig;
log.warn('CFGX', 'Loaded Headscale configuration in non-strict mode')
log.warn('CFGX', 'By using this mode you forfeit GitHub issue support')
log.warn('CFGX', 'This is very dangerous and comes with a few caveats:')
log.warn('CFGX', 'Headplane could very easily crash')
log.warn('CFGX', 'Headplane could break your Headscale installation')
log.warn('CFGX', 'The UI could throw random errors/show incorrect data')
log.warn('CFGX', '')
return config
log.warn('CFGX', 'Loaded Headscale configuration in non-strict mode');
log.warn('CFGX', 'By using this mode you forfeit GitHub issue support');
log.warn('CFGX', 'This is very dangerous and comes with a few caveats:');
log.warn('CFGX', 'Headplane could very easily crash');
log.warn('CFGX', 'Headplane could break your Headscale installation');
log.warn('CFGX', 'The UI could throw random errors/show incorrect data');
log.warn('CFGX', '');
return config;
}
try {
log.debug('CFGX', 'Attempting to parse Headscale configuration')
config = await HeadscaleConfig.parseAsync(configYaml.toJSON())
log.debug('CFGX', 'Attempting to parse Headscale configuration');
config = await HeadscaleConfig.parseAsync(configYaml.toJSON());
} catch (error) {
log.debug('CFGX', 'Failed to load Headscale configuration')
log.debug('CFGX', 'Failed to load Headscale configuration');
if (error instanceof z.ZodError) {
log.error('CFGX', 'Recieved invalid configuration file')
log.error('CFGX', 'The following schema issues were found:')
log.error('CFGX', 'Recieved invalid configuration file');
log.error('CFGX', 'The following schema issues were found:');
for (const issue of error.issues) {
const path = issue.path.map(String).join('.')
const message = issue.message
const path = issue.path.map(String).join('.');
const message = issue.message;
log.error('CFGX', ` '${path}': ${message}`)
log.error('CFGX', ` '${path}': ${message}`);
}
log.error('CFGX', '')
log.error('CFGX', 'Resolve these issues and try again.')
log.error('CFGX', 'Headplane will operate without the config')
log.error('CFGX', '')
log.error('CFGX', '');
log.error('CFGX', 'Resolve these issues and try again.');
log.error('CFGX', 'Headplane will operate without the config');
log.error('CFGX', '');
}
throw error
throw error;
}
return config
return config;
}
// This is so obscenely dangerous, please have a check around it
export async function patchConfig(partial: Record<string, unknown>) {
if (!configYaml || !config) {
throw new Error('Config not loaded')
throw new Error('Config not loaded');
}
log.debug('CFGX', 'Patching Headscale configuration')
log.debug('CFGX', 'Patching Headscale configuration');
for (const [key, value] of Object.entries(partial)) {
log.debug('CFGX', 'Patching %s with %s', key, value)
log.debug('CFGX', 'Patching %s with %s', key, value);
// If the key is something like `test.bar."foo.bar"`, then we treat
// the foo.bar as a single key, and not as two keys, so that needs
// to be split correctly.
@@ -294,39 +316,40 @@ export async function patchConfig(partial: Record<string, unknown>) {
// the next character is a quote, and if it is, we skip until the next
// quote, and then we skip the next character, which should be a dot.
// If it's not a quote, we split it.
const path = []
let temp = ''
let inQuote = false
const path = [];
let temp = '';
let inQuote = false;
for (const element of key) {
if (element === '"') {
inQuote = !inQuote
inQuote = !inQuote;
}
if (element === '.' && !inQuote) {
path.push(temp.replaceAll('"', ''))
temp = ''
continue
path.push(temp.replaceAll('"', ''));
temp = '';
continue;
}
temp += element
temp += element;
}
// Push the remaining element
path.push(temp.replaceAll('"', ''))
path.push(temp.replaceAll('"', ''));
if (value === null) {
configYaml.deleteIn(path)
continue
configYaml.deleteIn(path);
continue;
}
configYaml.setIn(path, value)
configYaml.setIn(path, value);
}
config = process.env.HEADSCALE_CONFIG_UNSTRICT === 'true'
? configYaml.toJSON() as HeadscaleConfig
: (await HeadscaleConfig.parseAsync(configYaml.toJSON()))
config =
process.env.HEADSCALE_CONFIG_UNSTRICT === 'true'
? (configYaml.toJSON() as HeadscaleConfig)
: await HeadscaleConfig.parseAsync(configYaml.toJSON());
const path = resolve(process.env.CONFIG_FILE ?? '/etc/headscale/config.yaml')
log.debug('CFGX', 'Writing patched configuration to %s', path)
await writeFile(path, configYaml.toString(), 'utf8')
const path = resolve(process.env.CONFIG_FILE ?? '/etc/headscale/config.yaml');
log.debug('CFGX', 'Writing patched configuration to %s', path);
await writeFile(path, configYaml.toString(), 'utf8');
}
+62 -40
View File
@@ -1,116 +1,138 @@
import { loadContext } from './config/headplane'
import log from './log'
import { loadContext } from './config/headplane';
import log from './log';
export class HeadscaleError extends Error {
status: number
status: number;
constructor(message: string, status: number) {
super(message)
this.name = 'HeadscaleError'
this.status = status
super(message);
this.name = 'HeadscaleError';
this.status = status;
}
}
export class FatalError extends Error {
constructor() {
super('The Headscale server is not accessible or the supplied API key is invalid')
this.name = 'FatalError'
super(
'The Headscale server is not accessible or the supplied API key is invalid',
);
this.name = 'FatalError';
}
}
export async function pull<T>(url: string, key: string) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?')
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = await loadContext()
const prefix = context.headscaleUrl
const context = await loadContext();
const prefix = context.headscaleUrl;
log.debug('APIC', 'GET %s', `${prefix}/api/${url}`)
log.debug('APIC', 'GET %s', `${prefix}/api/${url}`);
const response = await fetch(`${prefix}/api/${url}`, {
headers: {
Authorization: `Bearer ${key}`,
},
})
});
if (!response.ok) {
log.debug('APIC', 'GET %s failed with status %d', `${prefix}/api/${url}`, response.status)
throw new HeadscaleError(await response.text(), response.status)
log.debug(
'APIC',
'GET %s failed with status %d',
`${prefix}/api/${url}`,
response.status,
);
throw new HeadscaleError(await response.text(), response.status);
}
return (response.json() as Promise<T>)
return response.json() as Promise<T>;
}
export async function post<T>(url: string, key: string, body?: unknown) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?')
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = await loadContext()
const prefix = context.headscaleUrl
const context = await loadContext();
const prefix = context.headscaleUrl;
log.debug('APIC', 'POST %s', `${prefix}/api/${url}`)
log.debug('APIC', 'POST %s', `${prefix}/api/${url}`);
const response = await fetch(`${prefix}/api/${url}`, {
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Bearer ${key}`,
},
})
});
if (!response.ok) {
log.debug('APIC', 'POST %s failed with status %d', `${prefix}/api/${url}`, response.status)
throw new HeadscaleError(await response.text(), response.status)
log.debug(
'APIC',
'POST %s failed with status %d',
`${prefix}/api/${url}`,
response.status,
);
throw new HeadscaleError(await response.text(), response.status);
}
return (response.json() as Promise<T>)
return response.json() as Promise<T>;
}
export async function put<T>(url: string, key: string, body?: unknown) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?')
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = await loadContext()
const prefix = context.headscaleUrl
const context = await loadContext();
const prefix = context.headscaleUrl;
log.debug('APIC', 'PUT %s', `${prefix}/api/${url}`)
log.debug('APIC', 'PUT %s', `${prefix}/api/${url}`);
const response = await fetch(`${prefix}/api/${url}`, {
method: 'PUT',
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Bearer ${key}`,
},
})
});
if (!response.ok) {
log.debug('APIC', 'PUT %s failed with status %d', `${prefix}/api/${url}`, response.status)
throw new HeadscaleError(await response.text(), response.status)
log.debug(
'APIC',
'PUT %s failed with status %d',
`${prefix}/api/${url}`,
response.status,
);
throw new HeadscaleError(await response.text(), response.status);
}
return (response.json() as Promise<T>)
return response.json() as Promise<T>;
}
export async function del<T>(url: string, key: string) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?')
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const context = await loadContext()
const prefix = context.headscaleUrl
const context = await loadContext();
const prefix = context.headscaleUrl;
log.debug('APIC', 'DELETE %s', `${prefix}/api/${url}`)
log.debug('APIC', 'DELETE %s', `${prefix}/api/${url}`);
const response = await fetch(`${prefix}/api/${url}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${key}`,
},
})
});
if (!response.ok) {
log.debug('APIC', 'DELETE %s failed with status %d', `${prefix}/api/${url}`, response.status)
throw new HeadscaleError(await response.text(), response.status)
log.debug(
'APIC',
'DELETE %s failed with status %d',
`${prefix}/api/${url}`,
response.status,
);
throw new HeadscaleError(await response.text(), response.status);
}
return (response.json() as Promise<T>)
return response.json() as Promise<T>;
}
+8 -8
View File
@@ -1,22 +1,22 @@
export default {
info: (category: string, message: string, ...args: unknown[]) => {
defaultLog('INFO', category, message, ...args)
defaultLog('INFO', category, message, ...args);
},
warn: (category: string, message: string, ...args: unknown[]) => {
defaultLog('WARN', category, message, ...args)
defaultLog('WARN', category, message, ...args);
},
error: (category: string, message: string, ...args: unknown[]) => {
defaultLog('ERRO', category, message, ...args)
defaultLog('ERRO', category, message, ...args);
},
debug: (category: string, message: string, ...args: unknown[]) => {
if (process.env.DEBUG === 'true') {
defaultLog('DEBG', category, message, ...args)
defaultLog('DEBG', category, message, ...args);
}
}
}
},
};
function defaultLog(
level: string,
@@ -24,6 +24,6 @@ function defaultLog(
message: string,
...args: unknown[]
) {
const date = new Date().toISOString()
console.log(`${date} (${level}) [${category}] ${message}`, ...args)
const date = new Date().toISOString();
console.log(`${date} (${level}) [${category}] ${message}`, ...args);
}
+76 -72
View File
@@ -1,4 +1,4 @@
import { redirect } from '@remix-run/node'
import { redirect } from 'react-router';
import {
authorizationCodeGrantRequest,
calculatePKCECodeChallenge,
@@ -13,99 +13,99 @@ import {
processAuthorizationCodeOpenIDResponse,
processDiscoveryResponse,
validateAuthResponse,
} from 'oauth4webapi'
} from 'oauth4webapi';
import { post } from '~/utils/headscale'
import { commitSession, getSession } from '~/utils/sessions'
import log from '~/utils/log'
import { post } from '~/utils/headscale';
import { commitSession, getSession } from '~/utils/sessions';
import log from '~/utils/log';
import { HeadplaneContext } from './config/headplane'
import { HeadplaneContext } from './config/headplane';
type OidcConfig = NonNullable<HeadplaneContext['oidc']>
type OidcConfig = NonNullable<HeadplaneContext['oidc']>;
export async function startOidc(oidc: OidcConfig, req: Request) {
const session = await getSession(req.headers.get('Cookie'))
const session = await getSession(req.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/', {
status: 302,
headers: {
'Set-Cookie': await commitSession(session),
},
})
});
}
const issuerUrl = new URL(oidc.issuer)
const issuerUrl = new URL(oidc.issuer);
const oidcClient = {
client_id: oidc.client,
token_endpoint_auth_method: oidc.method,
} satisfies Client
} satisfies Client;
const response = await discoveryRequest(issuerUrl)
const processed = await processDiscoveryResponse(issuerUrl, response)
const response = await discoveryRequest(issuerUrl);
const processed = await processDiscoveryResponse(issuerUrl, response);
if (!processed.authorization_endpoint) {
throw new Error('No authorization endpoint found on the OIDC provider')
throw new Error('No authorization endpoint found on the OIDC provider');
}
const state = generateRandomState()
const nonce = generateRandomNonce()
const verifier = generateRandomCodeVerifier()
const challenge = await calculatePKCECodeChallenge(verifier)
const state = generateRandomState();
const nonce = generateRandomNonce();
const verifier = generateRandomCodeVerifier();
const challenge = await calculatePKCECodeChallenge(verifier);
const callback = new URL('/admin/oidc/callback', req.url)
callback.protocol = req.headers.get('X-Forwarded-Proto') ?? 'http:'
callback.host = req.headers.get('Host') ?? ''
const authUrl = new URL(processed.authorization_endpoint)
const callback = new URL('/admin/oidc/callback', req.url);
callback.protocol = req.headers.get('X-Forwarded-Proto') ?? 'http:';
callback.host = req.headers.get('Host') ?? '';
const authUrl = new URL(processed.authorization_endpoint);
authUrl.searchParams.set('client_id', oidcClient.client_id)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('redirect_uri', callback.href)
authUrl.searchParams.set('scope', 'openid profile email')
authUrl.searchParams.set('code_challenge', challenge)
authUrl.searchParams.set('code_challenge_method', 'S256')
authUrl.searchParams.set('state', state)
authUrl.searchParams.set('nonce', nonce)
authUrl.searchParams.set('client_id', oidcClient.client_id);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('redirect_uri', callback.href);
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('code_challenge', challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('nonce', nonce);
session.set('authState', state)
session.set('authNonce', nonce)
session.set('authVerifier', verifier)
session.set('authState', state);
session.set('authNonce', nonce);
session.set('authVerifier', verifier);
return redirect(authUrl.href, {
status: 302,
headers: {
'Set-Cookie': await commitSession(session),
},
})
});
}
export async function finishOidc(oidc: OidcConfig, req: Request) {
const session = await getSession(req.headers.get('Cookie'))
const session = await getSession(req.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/', {
status: 302,
headers: {
'Set-Cookie': await commitSession(session),
},
})
});
}
const issuerUrl = new URL(oidc.issuer)
const issuerUrl = new URL(oidc.issuer);
const oidcClient = {
client_id: oidc.client,
client_secret: oidc.secret,
token_endpoint_auth_method: oidc.method,
} satisfies Client
} satisfies Client;
const response = await discoveryRequest(issuerUrl)
const processed = await processDiscoveryResponse(issuerUrl, response)
const response = await discoveryRequest(issuerUrl);
const processed = await processDiscoveryResponse(issuerUrl, response);
if (!processed.authorization_endpoint) {
throw new Error('No authorization endpoint found on the OIDC provider')
throw new Error('No authorization endpoint found on the OIDC provider');
}
const state = session.get('authState')
const nonce = session.get('authNonce')
const verifier = session.get('authVerifier')
const state = session.get('authState');
const nonce = session.get('authNonce');
const verifier = session.get('authVerifier');
if (!state || !nonce || !verifier) {
throw new Error('No OIDC state found in the session')
throw new Error('No OIDC state found in the session');
}
const parameters = validateAuthResponse(
@@ -113,15 +113,15 @@ export async function finishOidc(oidc: OidcConfig, req: Request) {
oidcClient,
new URL(req.url),
state,
)
);
if (isOAuth2Error(parameters)) {
throw new Error('Invalid response from the OIDC provider')
throw new Error('Invalid response from the OIDC provider');
}
const callback = new URL('/admin/oidc/callback', req.url)
callback.protocol = req.headers.get('X-Forwarded-Proto') ?? 'http:'
callback.host = req.headers.get('Host') ?? ''
const callback = new URL('/admin/oidc/callback', req.url);
callback.protocol = req.headers.get('X-Forwarded-Proto') ?? 'http:';
callback.host = req.headers.get('Host') ?? '';
const tokenResponse = await authorizationCodeGrantRequest(
processed,
@@ -129,11 +129,11 @@ export async function finishOidc(oidc: OidcConfig, req: Request) {
parameters,
callback.href,
verifier,
)
);
const challenges = parseWwwAuthenticateChallenges(tokenResponse)
const challenges = parseWwwAuthenticateChallenges(tokenResponse);
if (challenges) {
throw new Error('Recieved a challenge from the OIDC provider')
throw new Error('Recieved a challenge from the OIDC provider');
}
const result = await processAuthorizationCodeOpenIDResponse(
@@ -141,14 +141,14 @@ export async function finishOidc(oidc: OidcConfig, req: Request) {
oidcClient,
tokenResponse,
nonce,
)
);
if (isOAuth2Error(result)) {
throw new Error('Invalid response from the OIDC provider')
throw new Error('Invalid response from the OIDC provider');
}
const claims = getValidatedIdTokenClaims(result)
const expDate = new Date(claims.exp * 1000).toISOString()
const claims = getValidatedIdTokenClaims(result);
const expDate = new Date(claims.exp * 1000).toISOString();
const keyResponse = await post<{ apiKey: string }>(
'v1/apikey',
@@ -156,19 +156,19 @@ export async function finishOidc(oidc: OidcConfig, req: Request) {
{
expiration: expDate,
},
)
);
session.set('hsApiKey', keyResponse.apiKey)
session.set('hsApiKey', keyResponse.apiKey);
session.set('user', {
name: claims.name ? String(claims.name) : 'Anonymous',
email: claims.email ? String(claims.email) : undefined,
})
});
return redirect('/machines', {
headers: {
'Set-Cookie': await commitSession(session),
},
})
});
}
// Runs at application startup to validate the OIDC configuration
@@ -177,23 +177,27 @@ export async function testOidc(issuer: string, client: string, secret: string) {
client_id: client,
client_secret: secret,
token_endpoint_auth_method: 'client_secret_post',
} satisfies Client
} satisfies Client;
const issuerUrl = new URL(issuer)
const issuerUrl = new URL(issuer);
try {
log.debug('OIDC', 'Checking OIDC well-known endpoint')
const response = await discoveryRequest(issuerUrl)
const processed = await processDiscoveryResponse(issuerUrl, response)
log.debug('OIDC', 'Checking OIDC well-known endpoint');
const response = await discoveryRequest(issuerUrl);
const processed = await processDiscoveryResponse(issuerUrl, response);
if (!processed.authorization_endpoint) {
log.debug('OIDC', 'No authorization endpoint found on the OIDC provider')
return false
log.debug('OIDC', 'No authorization endpoint found on the OIDC provider');
return false;
}
log.debug('OIDC', 'Found auth endpoint: %s', processed.authorization_endpoint)
return true
log.debug(
'OIDC',
'Found auth endpoint: %s',
processed.authorization_endpoint,
);
return true;
} catch (e) {
log.debug('OIDC', 'Validation failed: %s', e.message)
return false
log.debug('OIDC', 'Validation failed: %s', e.message);
return false;
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { data } from '@remix-run/node'
import { data } from 'react-router';
export function send<T>(payload: T, init?: number | ResponseInit) {
return data(payload, init)
return data(payload, init);
}
+7 -13
View File
@@ -1,4 +1,4 @@
import { createCookieSessionStorage } from '@remix-run/node' // Or cloudflare/deno
import { createCookieSessionStorage } from 'react-router'; // Or cloudflare/deno
export type SessionData = {
hsApiKey: string;
@@ -9,18 +9,14 @@ export type SessionData = {
name: string;
email?: string;
};
}
};
type SessionFlashData = {
error: string;
}
};
export const {
getSession,
commitSession,
destroySession
} = createCookieSessionStorage<SessionData, SessionFlashData>(
{
export const { getSession, commitSession, destroySession } =
createCookieSessionStorage<SessionData, SessionFlashData>({
cookie: {
name: 'hp_sess',
httpOnly: true,
@@ -29,7 +25,5 @@ export const {
sameSite: 'lax',
secrets: [process.env.COOKIE_SECRET!],
secure: process.env.COOKIE_SECURE !== 'false',
}
}
)
},
});
+16 -16
View File
@@ -1,35 +1,35 @@
import { useRevalidator } from '@remix-run/react'
import { useEffect } from 'react'
import { useInterval } from 'usehooks-ts'
import { useRevalidator } from 'react-router';
import { useEffect } from 'react';
import { useInterval } from 'usehooks-ts';
interface Props {
interval: number
interval: number;
}
export function useLiveData({ interval }: Props) {
const revalidator = useRevalidator()
const revalidator = useRevalidator();
// Handle normal stale-while-revalidate behavior
useInterval(() => {
if (revalidator.state === 'idle') {
revalidator.revalidate()
revalidator.revalidate();
}
}, interval)
}, interval);
useEffect(() => {
const handler = () => {
if (revalidator.state === 'idle') {
revalidator.revalidate()
revalidator.revalidate();
}
}
};
window.addEventListener('online', handler)
document.addEventListener('focus', handler)
window.addEventListener('online', handler);
document.addEventListener('focus', handler);
return () => {
window.removeEventListener('online', handler)
document.removeEventListener('focus', handler)
}
}, [revalidator])
return revalidator
window.removeEventListener('online', handler);
document.removeEventListener('focus', handler);
};
}, [revalidator]);
return revalidator;
}
+22 -22
View File
@@ -1,47 +1,47 @@
// This is a "side-effect" but we want a lifecycle cache map of
// peer statuses to prevent unnecessary fetches to the agent.
import type { LoaderFunctionArgs } from 'remix'
import type { LoaderFunctionArgs } from 'react-router';
type Context = LoaderFunctionArgs['context']
const cache: { [nodeID: string]: unknown } = {}
type Context = LoaderFunctionArgs['context'];
const cache: { [nodeID: string]: unknown } = {};
export async function queryWS(context: Context, nodeIDs: string[]) {
const ws = context.ws
const firstClient = ws.clients.values().next().value
const ws = context.ws;
const firstClient = ws.clients.values().next().value;
if (!firstClient) {
return cache
return cache;
}
const cached = nodeIDs.map((nodeID) => {
const cached = cache[nodeID]
const cached = cache[nodeID];
if (cached) {
return cached
return cached;
}
})
});
// We only need to query the nodes that are not cached
const uncached = nodeIDs.filter((nodeID) => !cached.includes(nodeID))
const uncached = nodeIDs.filter((nodeID) => !cached.includes(nodeID));
if (uncached.length === 0) {
return cache
return cache;
}
firstClient.send(JSON.stringify({ NodeIDs: uncached }))
await new Promise((resolve) => {
firstClient.send(JSON.stringify({ NodeIDs: uncached }));
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
resolve()
}, 3000)
resolve();
}, 3000);
firstClient.on('message', (message) => {
const data = JSON.parse(message.toString())
firstClient.on('message', (message: string) => {
const data = JSON.parse(message.toString());
if (Object.keys(data).length === 0) {
resolve()
resolve();
}
for (const [nodeID, status] of Object.entries(data)) {
cache[nodeID] = status
cache[nodeID] = status;
}
})
})
});
});
return cache
return cache;
}