mirror of
https://github.com/tale/headplane.git
synced 2026-08-19 01:16:18 +00:00
chore: format everything with oxfmt
This commit is contained in:
+54
-56
@@ -1,74 +1,72 @@
|
||||
interface ErrorCodes {
|
||||
CONFLICTING_SECRET_PATH_FIELD: {
|
||||
fieldName: string;
|
||||
};
|
||||
CONFLICTING_SECRET_PATH_FIELD: {
|
||||
fieldName: string;
|
||||
};
|
||||
|
||||
INVALID_REQUIRED_FIELDS: {
|
||||
messages: string[];
|
||||
};
|
||||
INVALID_REQUIRED_FIELDS: {
|
||||
messages: string[];
|
||||
};
|
||||
|
||||
MISSING_INTERPOLATION_VARIABLE: {
|
||||
pathKey: string;
|
||||
variableName: string;
|
||||
};
|
||||
MISSING_INTERPOLATION_VARIABLE: {
|
||||
pathKey: string;
|
||||
variableName: string;
|
||||
};
|
||||
|
||||
MISSING_SECRET_FILE: {
|
||||
pathKey: string;
|
||||
filePath: string;
|
||||
};
|
||||
MISSING_SECRET_FILE: {
|
||||
pathKey: string;
|
||||
filePath: string;
|
||||
};
|
||||
}
|
||||
|
||||
const translationsWithVars: {
|
||||
[K in keyof ErrorCodes]: (vars: ErrorCodes[K]) => string;
|
||||
[K in keyof ErrorCodes]: (vars: ErrorCodes[K]) => string;
|
||||
} = {
|
||||
CONFLICTING_SECRET_PATH_FIELD: ({ fieldName }) =>
|
||||
`Both "${fieldName}" and "${fieldName}_path" are set; please provide only one of these fields.`,
|
||||
INVALID_REQUIRED_FIELDS: ({ messages }) =>
|
||||
`The configuration is missing required fields or has invalid values:\n- ${messages.join('\n- ')}`,
|
||||
MISSING_INTERPOLATION_VARIABLE: ({ pathKey, variableName }) =>
|
||||
`Could not resolve environment variable "${variableName}" for configuration key "${pathKey}".`,
|
||||
CONFLICTING_SECRET_PATH_FIELD: ({ fieldName }) =>
|
||||
`Both "${fieldName}" and "${fieldName}_path" are set; please provide only one of these fields.`,
|
||||
INVALID_REQUIRED_FIELDS: ({ messages }) =>
|
||||
`The configuration is missing required fields or has invalid values:\n- ${messages.join("\n- ")}`,
|
||||
MISSING_INTERPOLATION_VARIABLE: ({ pathKey, variableName }) =>
|
||||
`Could not resolve environment variable "${variableName}" for configuration key "${pathKey}".`,
|
||||
|
||||
MISSING_SECRET_FILE: ({ pathKey, filePath }) =>
|
||||
`The secret file specified in "${pathKey}" could not be accessed at path "${filePath}". Please ensure the file exists and is readable.`,
|
||||
MISSING_SECRET_FILE: ({ pathKey, filePath }) =>
|
||||
`The secret file specified in "${pathKey}" could not be accessed at path "${filePath}". Please ensure the file exists and is readable.`,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Custom error class for configuration-related errors.
|
||||
*/
|
||||
export class ConfigError extends Error {
|
||||
/**
|
||||
* The error code representing the type of configuration error.
|
||||
*/
|
||||
code: keyof ErrorCodes;
|
||||
/**
|
||||
* The error code representing the type of configuration error.
|
||||
*/
|
||||
code: keyof ErrorCodes;
|
||||
|
||||
/**
|
||||
* Creates a new ConfigError instance.
|
||||
*
|
||||
* @param code The error code
|
||||
* @param vars The variables to interpolate into the error message
|
||||
*/
|
||||
constructor(code: keyof ErrorCodes, vars: unknown) {
|
||||
super(
|
||||
translationsWithVars[code](
|
||||
vars as (typeof translationsWithVars)[typeof code] extends (
|
||||
vars: infer U,
|
||||
) => string
|
||||
? U
|
||||
: never,
|
||||
),
|
||||
);
|
||||
this.code = code;
|
||||
this.name = 'ConfigError';
|
||||
}
|
||||
/**
|
||||
* Creates a new ConfigError instance.
|
||||
*
|
||||
* @param code The error code
|
||||
* @param vars The variables to interpolate into the error message
|
||||
*/
|
||||
constructor(code: keyof ErrorCodes, vars: unknown) {
|
||||
super(
|
||||
translationsWithVars[code](
|
||||
vars as (typeof translationsWithVars)[typeof code] extends (vars: infer U) => string
|
||||
? U
|
||||
: never,
|
||||
),
|
||||
);
|
||||
this.code = code;
|
||||
this.name = "ConfigError";
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create a ConfigError instance.
|
||||
*
|
||||
* @param code The error code
|
||||
* @param vars The variables to interpolate into the error message
|
||||
* @returns A new ConfigError instance
|
||||
*/
|
||||
static from<K extends keyof ErrorCodes>(code: K, vars: ErrorCodes[K]) {
|
||||
return new ConfigError(code, vars);
|
||||
}
|
||||
/**
|
||||
* Factory method to create a ConfigError instance.
|
||||
*
|
||||
* @param code The error code
|
||||
* @param vars The variables to interpolate into the error message
|
||||
* @returns A new ConfigError instance
|
||||
*/
|
||||
static from<K extends keyof ErrorCodes>(code: K, vars: ErrorCodes[K]) {
|
||||
return new ConfigError(code, vars);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import type { RuntimeApiClient } from '~/server/headscale/api/endpoints';
|
||||
import type { RuntimeApiClient } from "~/server/headscale/api/endpoints";
|
||||
|
||||
export abstract class Integration<T> {
|
||||
protected context: NonNullable<T>;
|
||||
constructor(context: T) {
|
||||
if (!context) {
|
||||
throw new Error('Missing integration context');
|
||||
}
|
||||
protected context: NonNullable<T>;
|
||||
constructor(context: T) {
|
||||
if (!context) {
|
||||
throw new Error("Missing integration context");
|
||||
}
|
||||
|
||||
this.context = context;
|
||||
}
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
abstract isAvailable(): Promise<boolean> | boolean;
|
||||
abstract onConfigChange(client: RuntimeApiClient): Promise<void> | void;
|
||||
abstract get name(): string;
|
||||
abstract isAvailable(): Promise<boolean> | boolean;
|
||||
abstract onConfigChange(client: RuntimeApiClient): Promise<void> | void;
|
||||
abstract get name(): string;
|
||||
}
|
||||
|
||||
@@ -1,62 +1,58 @@
|
||||
import log from '~/utils/log';
|
||||
import type { HeadplaneConfig } from '../config-schema';
|
||||
import dockerIntegration from './docker';
|
||||
import kubernetesIntegration from './kubernetes';
|
||||
import procIntegration from './proc';
|
||||
import log from "~/utils/log";
|
||||
|
||||
export async function loadIntegration(context: HeadplaneConfig['integration']) {
|
||||
const integration = getIntegration(context);
|
||||
if (!integration) {
|
||||
return;
|
||||
}
|
||||
import type { HeadplaneConfig } from "../config-schema";
|
||||
import dockerIntegration from "./docker";
|
||||
import kubernetesIntegration from "./kubernetes";
|
||||
import procIntegration from "./proc";
|
||||
|
||||
try {
|
||||
const res = await integration.isAvailable();
|
||||
if (!res) {
|
||||
log.error('config', 'Integration %s is not available', integration.name);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
log.error(
|
||||
'config',
|
||||
'Failed to load integration %s: %s',
|
||||
integration,
|
||||
error,
|
||||
);
|
||||
log.debug('config', 'Loading error: %o', error);
|
||||
return;
|
||||
}
|
||||
export async function loadIntegration(context: HeadplaneConfig["integration"]) {
|
||||
const integration = getIntegration(context);
|
||||
if (!integration) {
|
||||
return;
|
||||
}
|
||||
|
||||
return integration;
|
||||
try {
|
||||
const res = await integration.isAvailable();
|
||||
if (!res) {
|
||||
log.error("config", "Integration %s is not available", integration.name);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("config", "Failed to load integration %s: %s", integration, error);
|
||||
log.debug("config", "Loading error: %o", error);
|
||||
return;
|
||||
}
|
||||
|
||||
return integration;
|
||||
}
|
||||
|
||||
function getIntegration(integration: HeadplaneConfig['integration']) {
|
||||
const docker = integration?.docker;
|
||||
const k8s = integration?.kubernetes;
|
||||
const proc = integration?.proc;
|
||||
function getIntegration(integration: HeadplaneConfig["integration"]) {
|
||||
const docker = integration?.docker;
|
||||
const k8s = integration?.kubernetes;
|
||||
const proc = integration?.proc;
|
||||
|
||||
if (!docker?.enabled && !k8s?.enabled && !proc?.enabled) {
|
||||
log.debug('config', 'No integrations enabled');
|
||||
return;
|
||||
}
|
||||
if (!docker?.enabled && !k8s?.enabled && !proc?.enabled) {
|
||||
log.debug("config", "No integrations enabled");
|
||||
return;
|
||||
}
|
||||
|
||||
if (docker?.enabled && k8s?.enabled && proc?.enabled) {
|
||||
log.error('config', 'Multiple integrations enabled, please pick one only');
|
||||
return;
|
||||
}
|
||||
if (docker?.enabled && k8s?.enabled && proc?.enabled) {
|
||||
log.error("config", "Multiple integrations enabled, please pick one only");
|
||||
return;
|
||||
}
|
||||
|
||||
if (docker?.enabled) {
|
||||
log.info('config', 'Using Docker integration');
|
||||
return new dockerIntegration(integration!.docker!);
|
||||
}
|
||||
if (docker?.enabled) {
|
||||
log.info("config", "Using Docker integration");
|
||||
return new dockerIntegration(integration!.docker!);
|
||||
}
|
||||
|
||||
if (k8s?.enabled) {
|
||||
log.info('config', 'Using Kubernetes integration');
|
||||
return new kubernetesIntegration(integration!.kubernetes!);
|
||||
}
|
||||
if (k8s?.enabled) {
|
||||
log.info("config", "Using Kubernetes integration");
|
||||
return new kubernetesIntegration(integration!.kubernetes!);
|
||||
}
|
||||
|
||||
if (proc?.enabled) {
|
||||
log.info('config', 'Using Proc integration');
|
||||
return new procIntegration(integration!.proc!);
|
||||
}
|
||||
if (proc?.enabled) {
|
||||
log.info("config", "Using Proc integration");
|
||||
return new procIntegration(integration!.proc!);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { CoreV1Api, KubeConfig } from "@kubernetes/client-node";
|
||||
import { type } from "arktype";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { platform } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { RuntimeApiClient } from "~/server/headscale/api/endpoints";
|
||||
import { CoreV1Api, KubeConfig } from "@kubernetes/client-node";
|
||||
import { type } from "arktype";
|
||||
|
||||
import type { RuntimeApiClient } from "~/server/headscale/api/endpoints";
|
||||
import log from "~/utils/log";
|
||||
|
||||
import { Integration } from "./abstract";
|
||||
|
||||
@@ -4,7 +4,6 @@ import { kill } from "node:process";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
|
||||
import type { RuntimeApiClient } from "~/server/headscale/api/endpoints";
|
||||
|
||||
import log from "~/utils/log";
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { type } from "arktype";
|
||||
import { platform } from "node:os";
|
||||
|
||||
import type { RuntimeApiClient } from "~/server/headscale/api/endpoints";
|
||||
import { type } from "arktype";
|
||||
|
||||
import type { RuntimeApiClient } from "~/server/headscale/api/endpoints";
|
||||
import log from "~/utils/log";
|
||||
|
||||
import { Integration } from "./abstract";
|
||||
|
||||
+149
-154
@@ -1,14 +1,17 @@
|
||||
import { access, constants, readFile } from 'node:fs/promises';
|
||||
import { type } from 'arktype';
|
||||
import { load } from 'js-yaml';
|
||||
import log from '~/utils/log';
|
||||
import { access, constants, readFile } from "node:fs/promises";
|
||||
|
||||
import { type } from "arktype";
|
||||
import { load } from "js-yaml";
|
||||
|
||||
import log from "~/utils/log";
|
||||
|
||||
import {
|
||||
headplaneConfig,
|
||||
PartialHeadplaneConfig,
|
||||
partialHeadplaneConfig,
|
||||
pathSupportedKeys,
|
||||
} from './config-schema';
|
||||
import { ConfigError } from './error';
|
||||
headplaneConfig,
|
||||
PartialHeadplaneConfig,
|
||||
partialHeadplaneConfig,
|
||||
pathSupportedKeys,
|
||||
} from "./config-schema";
|
||||
import { ConfigError } from "./error";
|
||||
|
||||
/**
|
||||
* Main entrypoint that attempts to load and merge configuration from both
|
||||
@@ -25,27 +28,27 @@ import { ConfigError } from './error';
|
||||
* @throws {Error} If there are validation errors in the final configuration
|
||||
*/
|
||||
export async function loadConfig(configPathOverride?: string) {
|
||||
const configPath =
|
||||
configPathOverride != null
|
||||
? configPathOverride
|
||||
: process.env.HEADPLANE_CONFIG_PATH != null
|
||||
? String(process.env.HEADPLANE_CONFIG_PATH)
|
||||
: '/etc/headplane/config.yaml';
|
||||
const configPath =
|
||||
configPathOverride != null
|
||||
? configPathOverride
|
||||
: process.env.HEADPLANE_CONFIG_PATH != null
|
||||
? String(process.env.HEADPLANE_CONFIG_PATH)
|
||||
: "/etc/headplane/config.yaml";
|
||||
|
||||
const fileConfig = await loadConfigFile(configPath);
|
||||
const envConfig = await loadConfigEnv();
|
||||
const fileConfig = await loadConfigFile(configPath);
|
||||
const envConfig = await loadConfigEnv();
|
||||
|
||||
const combinedConfig = deepMerge(fileConfig, envConfig);
|
||||
await loadConfigKeyPaths(combinedConfig);
|
||||
const combinedConfig = deepMerge(fileConfig, envConfig);
|
||||
await loadConfigKeyPaths(combinedConfig);
|
||||
|
||||
const finalConfig = headplaneConfig(combinedConfig);
|
||||
if (finalConfig instanceof type.errors) {
|
||||
throw ConfigError.from('INVALID_REQUIRED_FIELDS', {
|
||||
messages: finalConfig.map((e) => e.toString()),
|
||||
});
|
||||
}
|
||||
const finalConfig = headplaneConfig(combinedConfig);
|
||||
if (finalConfig instanceof type.errors) {
|
||||
throw ConfigError.from("INVALID_REQUIRED_FIELDS", {
|
||||
messages: finalConfig.map((e) => e.toString()),
|
||||
});
|
||||
}
|
||||
|
||||
return finalConfig;
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,23 +60,23 @@ export async function loadConfig(configPathOverride?: string) {
|
||||
* @throws {Error} If there are validation errors in the loaded configuration
|
||||
*/
|
||||
export async function loadConfigFile(path: string) {
|
||||
try {
|
||||
await access(path, constants.R_OK);
|
||||
} catch {
|
||||
log.info('config', 'Could not access config file at path: %s', path);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await access(path, constants.R_OK);
|
||||
} catch {
|
||||
log.info("config", "Could not access config file at path: %s", path);
|
||||
return;
|
||||
}
|
||||
|
||||
const rawBuffer = await readFile(path, 'utf8');
|
||||
const rawConfig = load(rawBuffer);
|
||||
const config = partialHeadplaneConfig(rawConfig);
|
||||
if (config instanceof type.errors) {
|
||||
throw ConfigError.from('INVALID_REQUIRED_FIELDS', {
|
||||
messages: config.map((e) => e.toString()),
|
||||
});
|
||||
}
|
||||
const rawBuffer = await readFile(path, "utf8");
|
||||
const rawConfig = load(rawBuffer);
|
||||
const config = partialHeadplaneConfig(rawConfig);
|
||||
if (config instanceof type.errors) {
|
||||
throw ConfigError.from("INVALID_REQUIRED_FIELDS", {
|
||||
messages: config.map((e) => e.toString()),
|
||||
});
|
||||
}
|
||||
|
||||
return config;
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,36 +89,36 @@ export async function loadConfigFile(path: string) {
|
||||
* @throws {Error} If there are validation errors in the loaded configuration
|
||||
*/
|
||||
export async function loadConfigEnv() {
|
||||
if (process.env.HEADPLANE_LOAD_ENV_OVERRIDES != null) {
|
||||
log.warn(
|
||||
'config',
|
||||
'HEADPLANE_LOAD_ENV_OVERRIDES is deprecated and will be removed in future versions',
|
||||
);
|
||||
log.warn(
|
||||
'config',
|
||||
'Environment variables are always loaded and `.env` files are no longer supported',
|
||||
);
|
||||
}
|
||||
if (process.env.HEADPLANE_LOAD_ENV_OVERRIDES != null) {
|
||||
log.warn(
|
||||
"config",
|
||||
"HEADPLANE_LOAD_ENV_OVERRIDES is deprecated and will be removed in future versions",
|
||||
);
|
||||
log.warn(
|
||||
"config",
|
||||
"Environment variables are always loaded and `.env` files are no longer supported",
|
||||
);
|
||||
}
|
||||
|
||||
const rawConfig: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (value == null || !key.startsWith('HEADPLANE_')) {
|
||||
continue;
|
||||
}
|
||||
const rawConfig: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (value == null || !key.startsWith("HEADPLANE_")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const parsedValue = parseEnvValue(value);
|
||||
const configKey = key.slice('HEADPLANE_'.length).toLowerCase();
|
||||
deepSet(rawConfig, configKey.split('__'), parsedValue);
|
||||
}
|
||||
const parsedValue = parseEnvValue(value);
|
||||
const configKey = key.slice("HEADPLANE_".length).toLowerCase();
|
||||
deepSet(rawConfig, configKey.split("__"), parsedValue);
|
||||
}
|
||||
|
||||
const config = partialHeadplaneConfig(rawConfig);
|
||||
if (config instanceof type.errors) {
|
||||
throw ConfigError.from('INVALID_REQUIRED_FIELDS', {
|
||||
messages: config.map((e) => e.toString()),
|
||||
});
|
||||
}
|
||||
const config = partialHeadplaneConfig(rawConfig);
|
||||
if (config instanceof type.errors) {
|
||||
throw ConfigError.from("INVALID_REQUIRED_FIELDS", {
|
||||
messages: config.map((e) => e.toString()),
|
||||
});
|
||||
}
|
||||
|
||||
return Object.keys(config).length > 0 ? config : undefined;
|
||||
return Object.keys(config).length > 0 ? config : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,29 +129,25 @@ export async function loadConfigEnv() {
|
||||
* @returns The merged object
|
||||
*/
|
||||
function deepMerge<T>(...objects: (T | undefined)[]): T {
|
||||
const result: { [key: string]: unknown } = {};
|
||||
for (const obj of objects.filter((o) => o != null)) {
|
||||
for (const [key, value] of Object.entries(
|
||||
obj as {
|
||||
[key: string]: unknown;
|
||||
},
|
||||
)) {
|
||||
if (value != null && typeof value === 'object' && !Array.isArray(value)) {
|
||||
if (
|
||||
result[key] == null ||
|
||||
typeof result[key] !== 'object' ||
|
||||
Array.isArray(result[key])
|
||||
) {
|
||||
result[key] = {};
|
||||
}
|
||||
result[key] = deepMerge(result[key], value);
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
const result: { [key: string]: unknown } = {};
|
||||
for (const obj of objects.filter((o) => o != null)) {
|
||||
for (const [key, value] of Object.entries(
|
||||
obj as {
|
||||
[key: string]: unknown;
|
||||
},
|
||||
)) {
|
||||
if (value != null && typeof value === "object" && !Array.isArray(value)) {
|
||||
if (result[key] == null || typeof result[key] !== "object" || Array.isArray(result[key])) {
|
||||
result[key] = {};
|
||||
}
|
||||
result[key] = deepMerge(result[key], value);
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result as T;
|
||||
return result as T;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,22 +157,18 @@ function deepMerge<T>(...objects: (T | undefined)[]): T {
|
||||
* @param path An array of keys representing the path to set
|
||||
* @param value The value to set at the specified path
|
||||
*/
|
||||
function deepSet(
|
||||
obj: { [key: string]: unknown },
|
||||
path: string[],
|
||||
value: unknown,
|
||||
): void {
|
||||
let current = obj;
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
const key = path[i];
|
||||
if (current[key] == null || typeof current[key] !== 'object') {
|
||||
current[key] = {};
|
||||
}
|
||||
function deepSet(obj: { [key: string]: unknown }, path: string[], value: unknown): void {
|
||||
let current = obj;
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
const key = path[i];
|
||||
if (current[key] == null || typeof current[key] !== "object") {
|
||||
current[key] = {};
|
||||
}
|
||||
|
||||
current = current[key] as { [key: string]: unknown };
|
||||
}
|
||||
current = current[key] as { [key: string]: unknown };
|
||||
}
|
||||
|
||||
current[path[path.length - 1]] = value;
|
||||
current[path[path.length - 1]] = value;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,18 +179,18 @@ function deepSet(
|
||||
* @returns The parsed value
|
||||
*/
|
||||
function parseEnvValue(value: string): unknown {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true') return true;
|
||||
if (v === 'false') return false;
|
||||
if (v === 'null') return null;
|
||||
if (v === 'undefined') return undefined;
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === "true") return true;
|
||||
if (v === "false") return false;
|
||||
if (v === "null") return null;
|
||||
if (v === "undefined") return undefined;
|
||||
|
||||
if (/^-?\d+(\.\d+)?$/.test(v)) {
|
||||
const num = Number(v);
|
||||
if (!Number.isNaN(num)) return num;
|
||||
}
|
||||
if (/^-?\d+(\.\d+)?$/.test(v)) {
|
||||
const num = Number(v);
|
||||
if (!Number.isNaN(num)) return num;
|
||||
}
|
||||
|
||||
return value;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,43 +202,43 @@ function parseEnvValue(value: string): unknown {
|
||||
* @param partial The partial configuration object to update
|
||||
*/
|
||||
export async function loadConfigKeyPaths(partial: PartialHeadplaneConfig) {
|
||||
for (const key of pathSupportedKeys) {
|
||||
const pathKey = `${key}_path`;
|
||||
const pathValue = deepGet(partial, pathKey.split('.'));
|
||||
const existing = deepGet(partial, key.split('.'));
|
||||
for (const key of pathSupportedKeys) {
|
||||
const pathKey = `${key}_path`;
|
||||
const pathValue = deepGet(partial, pathKey.split("."));
|
||||
const existing = deepGet(partial, key.split("."));
|
||||
|
||||
if (pathValue == null || typeof pathValue !== 'string') {
|
||||
continue;
|
||||
}
|
||||
if (pathValue == null || typeof pathValue !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existing != null) {
|
||||
throw ConfigError.from('CONFLICTING_SECRET_PATH_FIELD', {
|
||||
fieldName: key,
|
||||
});
|
||||
}
|
||||
if (existing != null) {
|
||||
throw ConfigError.from("CONFLICTING_SECRET_PATH_FIELD", {
|
||||
fieldName: key,
|
||||
});
|
||||
}
|
||||
|
||||
const realPath = pathValue.replace(/\$\{([^}]+)\}/g, (_, variableName) => {
|
||||
const value = process.env[variableName];
|
||||
if (value === undefined) {
|
||||
throw ConfigError.from('MISSING_INTERPOLATION_VARIABLE', {
|
||||
pathKey: `${key}_path`,
|
||||
variableName: variableName,
|
||||
});
|
||||
}
|
||||
const realPath = pathValue.replace(/\$\{([^}]+)\}/g, (_, variableName) => {
|
||||
const value = process.env[variableName];
|
||||
if (value === undefined) {
|
||||
throw ConfigError.from("MISSING_INTERPOLATION_VARIABLE", {
|
||||
pathKey: `${key}_path`,
|
||||
variableName: variableName,
|
||||
});
|
||||
}
|
||||
|
||||
return value;
|
||||
});
|
||||
return value;
|
||||
});
|
||||
|
||||
try {
|
||||
const fileContent = await readFile(realPath, 'utf8');
|
||||
deepSet(partial, key.split('.'), fileContent.trim().normalize());
|
||||
} catch {
|
||||
throw ConfigError.from('MISSING_SECRET_FILE', {
|
||||
pathKey: `${key}_path`,
|
||||
filePath: realPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
const fileContent = await readFile(realPath, "utf8");
|
||||
deepSet(partial, key.split("."), fileContent.trim().normalize());
|
||||
} catch {
|
||||
throw ConfigError.from("MISSING_SECRET_FILE", {
|
||||
pathKey: `${key}_path`,
|
||||
filePath: realPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -254,14 +249,14 @@ export async function loadConfigKeyPaths(partial: PartialHeadplaneConfig) {
|
||||
* @returns The value at the specified path or undefined if not found
|
||||
*/
|
||||
function deepGet(obj: { [key: string]: unknown }, path: string[]): unknown {
|
||||
let current = obj;
|
||||
for (const segment of path) {
|
||||
if (current == null || typeof current !== 'object') {
|
||||
return undefined;
|
||||
}
|
||||
let current = obj;
|
||||
for (const segment of path) {
|
||||
if (current == null || typeof current !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
current = current[segment] as { [key: string]: unknown };
|
||||
}
|
||||
current = current[segment] as { [key: string]: unknown };
|
||||
}
|
||||
|
||||
return current;
|
||||
return current;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { Traversal } from 'arktype';
|
||||
import log from '~/utils/log';
|
||||
import type { Traversal } from "arktype";
|
||||
|
||||
import log from "~/utils/log";
|
||||
|
||||
export function deprecatedField() {
|
||||
return (_: unknown, ctx: Traversal) => {
|
||||
log.warn('config', `${ctx.propString} is deprecated and has no effect.`);
|
||||
return true;
|
||||
};
|
||||
return (_: unknown, ctx: Traversal) => {
|
||||
log.warn("config", `${ctx.propString} is deprecated and has no effect.`);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,23 +1,20 @@
|
||||
import type { Key } from '~/types';
|
||||
import { defineApiEndpoints } from '../factory';
|
||||
import type { Key } from "~/types";
|
||||
|
||||
import { defineApiEndpoints } from "../factory";
|
||||
|
||||
export interface ApiKeyEndpoints {
|
||||
/**
|
||||
* Retrieves all API keys from the Headscale instance.
|
||||
*
|
||||
* @returns An array of `Key` objects representing the API keys.
|
||||
*/
|
||||
getApiKeys(): Promise<Key[]>;
|
||||
/**
|
||||
* Retrieves all API keys from the Headscale instance.
|
||||
*
|
||||
* @returns An array of `Key` objects representing the API keys.
|
||||
*/
|
||||
getApiKeys(): Promise<Key[]>;
|
||||
}
|
||||
|
||||
export default defineApiEndpoints<ApiKeyEndpoints>((client, apiKey) => ({
|
||||
getApiKeys: async () => {
|
||||
const { apiKeys } = await client.apiFetch<{ apiKeys: Key[] }>(
|
||||
'GET',
|
||||
'v1/apikey',
|
||||
apiKey,
|
||||
);
|
||||
getApiKeys: async () => {
|
||||
const { apiKeys } = await client.apiFetch<{ apiKeys: Key[] }>("GET", "v1/apikey", apiKey);
|
||||
|
||||
return apiKeys;
|
||||
},
|
||||
return apiKeys;
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,56 +1,54 @@
|
||||
import {
|
||||
composeEndpoints,
|
||||
defineApiEndpoints,
|
||||
type ExtractApiEndpoints,
|
||||
type UnionToIntersection,
|
||||
} from '../factory';
|
||||
import type { HeadscaleApiInterface } from '../index';
|
||||
import apiKeyEndpoints from './api-keys';
|
||||
import nodeEndpoints from './nodes';
|
||||
import policyEndpoints from './policy';
|
||||
import preAuthKeyEndpoints from './pre-auth-keys';
|
||||
import userEndpoints from './users';
|
||||
composeEndpoints,
|
||||
defineApiEndpoints,
|
||||
type ExtractApiEndpoints,
|
||||
type UnionToIntersection,
|
||||
} from "../factory";
|
||||
import type { HeadscaleApiInterface } from "../index";
|
||||
import apiKeyEndpoints from "./api-keys";
|
||||
import nodeEndpoints from "./nodes";
|
||||
import policyEndpoints from "./policy";
|
||||
import preAuthKeyEndpoints from "./pre-auth-keys";
|
||||
import userEndpoints from "./users";
|
||||
|
||||
interface HealthcheckEndpoint {
|
||||
/**
|
||||
* Checks if the Headscale instance is healthy.
|
||||
*
|
||||
* @returns A boolean indicating if the instance is healthy.
|
||||
*/
|
||||
isHealthy(): Promise<boolean>;
|
||||
/**
|
||||
* Checks if the Headscale instance is healthy.
|
||||
*
|
||||
* @returns A boolean indicating if the instance is healthy.
|
||||
*/
|
||||
isHealthy(): Promise<boolean>;
|
||||
}
|
||||
|
||||
const healthcheckEndpoint = defineApiEndpoints<HealthcheckEndpoint>(
|
||||
(client, apiKey) => ({
|
||||
isHealthy: async () => {
|
||||
try {
|
||||
const res = await client.rawFetch('/health', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
// This doesn't really matter
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
});
|
||||
const healthcheckEndpoint = defineApiEndpoints<HealthcheckEndpoint>((client, apiKey) => ({
|
||||
isHealthy: async () => {
|
||||
try {
|
||||
const res = await client.rawFetch("/health", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
// This doesn't really matter
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
});
|
||||
|
||||
return res.statusCode === 200;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
return res.statusCode === 200;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* A constant list of all endpoint groups.
|
||||
* Add new endpoint groups here.
|
||||
*/
|
||||
export const endpointSets = [
|
||||
apiKeyEndpoints,
|
||||
healthcheckEndpoint,
|
||||
nodeEndpoints,
|
||||
policyEndpoints,
|
||||
preAuthKeyEndpoints,
|
||||
userEndpoints,
|
||||
apiKeyEndpoints,
|
||||
healthcheckEndpoint,
|
||||
nodeEndpoints,
|
||||
policyEndpoints,
|
||||
preAuthKeyEndpoints,
|
||||
userEndpoints,
|
||||
] as const;
|
||||
|
||||
/**
|
||||
@@ -63,7 +61,7 @@ export const endpointSets = [
|
||||
* passing in different internal implementations based on the OpenAPI spec.
|
||||
*/
|
||||
export type RuntimeApiClient = UnionToIntersection<
|
||||
ExtractApiEndpoints<(typeof endpointSets)[number]>
|
||||
ExtractApiEndpoints<(typeof endpointSets)[number]>
|
||||
>;
|
||||
|
||||
/**
|
||||
@@ -73,7 +71,5 @@ export type RuntimeApiClient = UnionToIntersection<
|
||||
* @param apiKey - The API key for authentication.
|
||||
* @returns A fully composed runtime API client.
|
||||
*/
|
||||
export default (
|
||||
client: HeadscaleApiInterface['clientHelpers'],
|
||||
apiKey: string,
|
||||
) => composeEndpoints(endpointSets, client, apiKey);
|
||||
export default (client: HeadscaleApiInterface["clientHelpers"], apiKey: string) =>
|
||||
composeEndpoints(endpointSets, client, apiKey);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Machine } from "~/types";
|
||||
|
||||
import type { HeadscaleApiInterface } from "..";
|
||||
|
||||
import { defineApiEndpoints } from "../factory";
|
||||
|
||||
interface RawMachine extends Omit<Machine, "tags"> {
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import { defineApiEndpoints } from '../factory';
|
||||
import { defineApiEndpoints } from "../factory";
|
||||
|
||||
export interface PolicyEndpoints {
|
||||
/**
|
||||
* Retrieves the current ACL policy from the Headscale instance.
|
||||
*
|
||||
* @returns The ACL policy as a string and the date it was last updated.
|
||||
*/
|
||||
getPolicy(): Promise<{ policy: string; updatedAt: Date | null }>;
|
||||
/**
|
||||
* Retrieves the current ACL policy from the Headscale instance.
|
||||
*
|
||||
* @returns The ACL policy as a string and the date it was last updated.
|
||||
*/
|
||||
getPolicy(): Promise<{ policy: string; updatedAt: Date | null }>;
|
||||
|
||||
/**
|
||||
* Sets the ACL policy for the Headscale instance.
|
||||
*
|
||||
* @param policy The ACL policy as a string.
|
||||
* @returns The updated ACL policy as a string and the date it was last updated.
|
||||
*/
|
||||
setPolicy(policy: string): Promise<{ policy: string; updatedAt: Date }>;
|
||||
/**
|
||||
* Sets the ACL policy for the Headscale instance.
|
||||
*
|
||||
* @param policy The ACL policy as a string.
|
||||
* @returns The updated ACL policy as a string and the date it was last updated.
|
||||
*/
|
||||
setPolicy(policy: string): Promise<{ policy: string; updatedAt: Date }>;
|
||||
}
|
||||
|
||||
export default defineApiEndpoints<PolicyEndpoints>((client, apiKey) => ({
|
||||
getPolicy: async () => {
|
||||
const { policy, updatedAt } = await client.apiFetch<{
|
||||
policy: string;
|
||||
updatedAt: string;
|
||||
}>('GET', 'v1/policy', apiKey);
|
||||
getPolicy: async () => {
|
||||
const { policy, updatedAt } = await client.apiFetch<{
|
||||
policy: string;
|
||||
updatedAt: string;
|
||||
}>("GET", "v1/policy", apiKey);
|
||||
|
||||
return {
|
||||
policy,
|
||||
updatedAt: updatedAt !== null ? new Date(updatedAt) : null,
|
||||
};
|
||||
},
|
||||
return {
|
||||
policy,
|
||||
updatedAt: updatedAt !== null ? new Date(updatedAt) : null,
|
||||
};
|
||||
},
|
||||
|
||||
setPolicy: async (policy) => {
|
||||
const { policy: newPolicy, updatedAt } = await client.apiFetch<{
|
||||
policy: string;
|
||||
updatedAt: string;
|
||||
}>('PUT', 'v1/policy', apiKey, { policy });
|
||||
setPolicy: async (policy) => {
|
||||
const { policy: newPolicy, updatedAt } = await client.apiFetch<{
|
||||
policy: string;
|
||||
updatedAt: string;
|
||||
}>("PUT", "v1/policy", apiKey, { policy });
|
||||
|
||||
return { policy: newPolicy, updatedAt: new Date(updatedAt) };
|
||||
},
|
||||
return { policy: newPolicy, updatedAt: new Date(updatedAt) };
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,88 +1,83 @@
|
||||
import type { User } from '~/types';
|
||||
import { defineApiEndpoints } from '../factory';
|
||||
import type { User } from "~/types";
|
||||
|
||||
import { defineApiEndpoints } from "../factory";
|
||||
|
||||
export interface UserEndpoints {
|
||||
/**
|
||||
* Retrieves users from the Headscale instance, optionally filtering by ID, name, or email.
|
||||
*
|
||||
* @param id Optional ID of the user to retrieve.
|
||||
* @param name Optional name of the user to retrieve.
|
||||
* @param email Optional email of the user to retrieve.
|
||||
* @returns An array of `User` objects representing the users.
|
||||
*/
|
||||
getUsers(id?: string, name?: string, email?: string): Promise<User[]>;
|
||||
/**
|
||||
* Retrieves users from the Headscale instance, optionally filtering by ID, name, or email.
|
||||
*
|
||||
* @param id Optional ID of the user to retrieve.
|
||||
* @param name Optional name of the user to retrieve.
|
||||
* @param email Optional email of the user to retrieve.
|
||||
* @returns An array of `User` objects representing the users.
|
||||
*/
|
||||
getUsers(id?: string, name?: string, email?: string): Promise<User[]>;
|
||||
|
||||
/**
|
||||
* Creates a new user in the Headscale instance.
|
||||
*
|
||||
* @param username The username of the new user.
|
||||
* @param email Optional email of the new user.
|
||||
* @param displayName Optional display name of the new user.
|
||||
* @param pictureUrl Optional picture URL of the new user.
|
||||
* @returns A `User` object representing the newly created user.
|
||||
*/
|
||||
createUser(
|
||||
username: string,
|
||||
email?: string,
|
||||
displayName?: string,
|
||||
pictureUrl?: string,
|
||||
): Promise<User>;
|
||||
/**
|
||||
* Creates a new user in the Headscale instance.
|
||||
*
|
||||
* @param username The username of the new user.
|
||||
* @param email Optional email of the new user.
|
||||
* @param displayName Optional display name of the new user.
|
||||
* @param pictureUrl Optional picture URL of the new user.
|
||||
* @returns A `User` object representing the newly created user.
|
||||
*/
|
||||
createUser(
|
||||
username: string,
|
||||
email?: string,
|
||||
displayName?: string,
|
||||
pictureUrl?: string,
|
||||
): Promise<User>;
|
||||
|
||||
/**
|
||||
* Deletes a specific user by its ID.
|
||||
*
|
||||
* @param id The ID of the user to delete.
|
||||
*/
|
||||
deleteUser(id: string): Promise<void>;
|
||||
/**
|
||||
* Deletes a specific user by its ID.
|
||||
*
|
||||
* @param id The ID of the user to delete.
|
||||
*/
|
||||
deleteUser(id: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Renames a specific user by its ID.
|
||||
*
|
||||
* @param id The ID of the user to rename.
|
||||
* @param newName The new name for the user.
|
||||
*/
|
||||
renameUser(id: string, newName: string): Promise<void>;
|
||||
/**
|
||||
* Renames a specific user by its ID.
|
||||
*
|
||||
* @param id The ID of the user to rename.
|
||||
* @param newName The new name for the user.
|
||||
*/
|
||||
renameUser(id: string, newName: string): Promise<void>;
|
||||
}
|
||||
|
||||
export default defineApiEndpoints<UserEndpoints>((client, apiKey) => ({
|
||||
getUsers: async (id, name, email) => {
|
||||
const moreThanOneFilter =
|
||||
[id, name, email].filter((v) => v !== undefined).length > 1;
|
||||
getUsers: async (id, name, email) => {
|
||||
const moreThanOneFilter = [id, name, email].filter((v) => v !== undefined).length > 1;
|
||||
|
||||
if (moreThanOneFilter) {
|
||||
throw new Error('Only one of id, name, or email filters can be provided');
|
||||
}
|
||||
if (moreThanOneFilter) {
|
||||
throw new Error("Only one of id, name, or email filters can be provided");
|
||||
}
|
||||
|
||||
const { users } = await client.apiFetch<{ users: User[] }>(
|
||||
'GET',
|
||||
'v1/user',
|
||||
apiKey,
|
||||
{ id, name, email },
|
||||
);
|
||||
const { users } = await client.apiFetch<{ users: User[] }>("GET", "v1/user", apiKey, {
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
});
|
||||
|
||||
return users;
|
||||
},
|
||||
return users;
|
||||
},
|
||||
|
||||
createUser: async (username, email, displayName, pictureUrl) => {
|
||||
const { user } = await client.apiFetch<{ user: User }>(
|
||||
'POST',
|
||||
'v1/user',
|
||||
apiKey,
|
||||
{ name: username, email, displayName, pictureUrl },
|
||||
);
|
||||
createUser: async (username, email, displayName, pictureUrl) => {
|
||||
const { user } = await client.apiFetch<{ user: User }>("POST", "v1/user", apiKey, {
|
||||
name: username,
|
||||
email,
|
||||
displayName,
|
||||
pictureUrl,
|
||||
});
|
||||
|
||||
return user;
|
||||
},
|
||||
return user;
|
||||
},
|
||||
|
||||
deleteUser: async (id) => {
|
||||
await client.apiFetch<void>('DELETE', `v1/user/${id}`, apiKey);
|
||||
},
|
||||
deleteUser: async (id) => {
|
||||
await client.apiFetch<void>("DELETE", `v1/user/${id}`, apiKey);
|
||||
},
|
||||
|
||||
renameUser: async (oldId, newName) => {
|
||||
await client.apiFetch<void>(
|
||||
'POST',
|
||||
`v1/user/${oldId}/rename/${newName}`,
|
||||
apiKey,
|
||||
);
|
||||
},
|
||||
renameUser: async (oldId, newName) => {
|
||||
await client.apiFetch<void>("POST", `v1/user/${oldId}/rename/${newName}`, apiKey);
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import type { HeadscaleConnectionError } from './error';
|
||||
import type { HeadscaleConnectionError } from "./error";
|
||||
|
||||
/**
|
||||
* Represents an error returned by the Headscale API.
|
||||
*/
|
||||
export interface HeadscaleAPIError {
|
||||
requestUrl: `${string} ${string}`;
|
||||
statusCode: number;
|
||||
rawData: string;
|
||||
data: Record<string, unknown> | null;
|
||||
requestUrl: `${string} ${string}`;
|
||||
statusCode: number;
|
||||
rawData: string;
|
||||
data: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -16,14 +16,14 @@ export interface HeadscaleAPIError {
|
||||
* @returns True if the error is a HeadscaleAPIError, false otherwise.
|
||||
*/
|
||||
export function isApiError(error: unknown): error is HeadscaleAPIError {
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === 'object' &&
|
||||
'requestUrl' in error &&
|
||||
'statusCode' in error &&
|
||||
'rawData' in error &&
|
||||
'data' in error
|
||||
);
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === "object" &&
|
||||
"requestUrl" in error &&
|
||||
"statusCode" in error &&
|
||||
"rawData" in error &&
|
||||
"data" in error
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -31,17 +31,15 @@ export function isApiError(error: unknown): error is HeadscaleAPIError {
|
||||
* @param error - The error to check.
|
||||
* @returns True if the error is a HeadscaleConnectionError, false otherwise.
|
||||
*/
|
||||
export function isConnectionError(
|
||||
error: unknown,
|
||||
): error is HeadscaleConnectionError {
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === 'object' &&
|
||||
'requestUrl' in error &&
|
||||
'errorCode' in error &&
|
||||
'errorMessage' in error &&
|
||||
'extraData' in error
|
||||
);
|
||||
export function isConnectionError(error: unknown): error is HeadscaleConnectionError {
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === "object" &&
|
||||
"requestUrl" in error &&
|
||||
"errorCode" in error &&
|
||||
"errorMessage" in error &&
|
||||
"extraData" in error
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,15 +50,15 @@ export function isConnectionError(
|
||||
* @returns True if the error is a DataUnauthorizedError, false otherwise.
|
||||
*/
|
||||
export function isDataUnauthorizedError(error: unknown): boolean {
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === 'object' &&
|
||||
'data' in error &&
|
||||
typeof error.data === 'object' &&
|
||||
error.data != null &&
|
||||
'statusCode' in error.data &&
|
||||
error.data.statusCode === 401
|
||||
);
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === "object" &&
|
||||
"data" in error &&
|
||||
typeof error.data === "object" &&
|
||||
error.data != null &&
|
||||
"statusCode" in error.data &&
|
||||
error.data.statusCode === 401
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -72,13 +70,6 @@ export function isDataUnauthorizedError(error: unknown): boolean {
|
||||
* @returns True if the error is a DataWithResponseInit containing a
|
||||
* HeadscaleAPIError, false otherwise.
|
||||
*/
|
||||
export function isDataWithApiError(
|
||||
error: unknown,
|
||||
): error is { data: HeadscaleAPIError } {
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === 'object' &&
|
||||
'data' in error &&
|
||||
isApiError(error.data)
|
||||
);
|
||||
export function isDataWithApiError(error: unknown): error is { data: HeadscaleAPIError } {
|
||||
return error != null && typeof error === "object" && "data" in error && isApiError(error.data);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { errors } from 'undici';
|
||||
import { errors } from "undici";
|
||||
|
||||
/**
|
||||
* Helper function that determines if an error is a Node.js exception
|
||||
@@ -6,22 +6,17 @@ import { errors } from 'undici';
|
||||
* @returns True if the error is a Node.js exception, false otherwise
|
||||
*/
|
||||
function isNodeNetworkError(error: unknown): error is NodeJS.ErrnoException {
|
||||
return (
|
||||
error != null &&
|
||||
typeof error === 'object' &&
|
||||
'code' in error &&
|
||||
'errno' in error
|
||||
);
|
||||
return error != null && typeof error === "object" && "code" in error && "errno" in error;
|
||||
}
|
||||
|
||||
/**
|
||||
* A friendly error representation for Headscale connection issues.
|
||||
*/
|
||||
export interface HeadscaleConnectionError {
|
||||
requestUrl: string;
|
||||
errorCode: string;
|
||||
errorMessage: string;
|
||||
extraData: Record<string, unknown> | null;
|
||||
requestUrl: string;
|
||||
errorCode: string;
|
||||
errorMessage: string;
|
||||
extraData: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,40 +28,40 @@ export interface HeadscaleConnectionError {
|
||||
* @returns A friendly HeadscaleAPIError.
|
||||
*/
|
||||
export function undiciToFriendlyError(
|
||||
error: unknown,
|
||||
requestUrl: string,
|
||||
error: unknown,
|
||||
requestUrl: string,
|
||||
): HeadscaleConnectionError {
|
||||
// MARK: Do we need to go deeper into causes here?
|
||||
if (error instanceof AggregateError) {
|
||||
error = error.errors[0];
|
||||
}
|
||||
// MARK: Do we need to go deeper into causes here?
|
||||
if (error instanceof AggregateError) {
|
||||
error = error.errors[0];
|
||||
}
|
||||
|
||||
if (error instanceof errors.UndiciError) {
|
||||
return {
|
||||
requestUrl,
|
||||
errorCode: error.code,
|
||||
errorMessage: error.message,
|
||||
extraData: null,
|
||||
};
|
||||
}
|
||||
if (error instanceof errors.UndiciError) {
|
||||
return {
|
||||
requestUrl,
|
||||
errorCode: error.code,
|
||||
errorMessage: error.message,
|
||||
extraData: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (isNodeNetworkError(error)) {
|
||||
return {
|
||||
requestUrl,
|
||||
errorCode: error.code ?? 'UNKNOWN_NODE_NETWORK_ERROR',
|
||||
errorMessage: error.message,
|
||||
extraData: {
|
||||
syscall: error.syscall,
|
||||
path: error.path,
|
||||
errno: error.errno,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (isNodeNetworkError(error)) {
|
||||
return {
|
||||
requestUrl,
|
||||
errorCode: error.code ?? "UNKNOWN_NODE_NETWORK_ERROR",
|
||||
errorMessage: error.message,
|
||||
extraData: {
|
||||
syscall: error.syscall,
|
||||
path: error.path,
|
||||
errno: error.errno,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
requestUrl,
|
||||
errorCode: 'UNKNOWN_ERROR',
|
||||
errorMessage: 'An unknown error occured',
|
||||
extraData: null,
|
||||
};
|
||||
return {
|
||||
requestUrl,
|
||||
errorCode: "UNKNOWN_ERROR",
|
||||
errorMessage: "An unknown error occured",
|
||||
extraData: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HeadscaleApiInterface } from '../api';
|
||||
import type { HeadscaleApiInterface } from "../api";
|
||||
|
||||
/**
|
||||
* Creates a strongly-typed group factory for a given endpoint interface.
|
||||
@@ -8,38 +8,31 @@ import type { HeadscaleApiInterface } from '../api';
|
||||
*/
|
||||
|
||||
export interface EndpointFactory<T extends object> {
|
||||
__type?: T;
|
||||
(client: HeadscaleApiInterface['clientHelpers'], apiKey: string): T;
|
||||
__type?: T;
|
||||
(client: HeadscaleApiInterface["clientHelpers"], apiKey: string): T;
|
||||
}
|
||||
|
||||
export function defineApiEndpoints<T extends object>(
|
||||
factories: (
|
||||
client: HeadscaleApiInterface['clientHelpers'],
|
||||
apiKey: string,
|
||||
) => T,
|
||||
factories: (client: HeadscaleApiInterface["clientHelpers"], apiKey: string) => T,
|
||||
): EndpointFactory<T> {
|
||||
return factories;
|
||||
return factories;
|
||||
}
|
||||
|
||||
export type ExtractApiEndpoints<F> = F extends EndpointFactory<infer T>
|
||||
? T
|
||||
: never;
|
||||
export type UnionToIntersection<U> = (
|
||||
U extends any
|
||||
? (k: U) => void
|
||||
: never
|
||||
) extends (k: infer I) => void
|
||||
? I
|
||||
: never;
|
||||
export type ExtractApiEndpoints<F> = F extends EndpointFactory<infer T> ? T : never;
|
||||
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
|
||||
k: infer I,
|
||||
) => void
|
||||
? I
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Compose multiple endpoint sets into a single typed runtime client
|
||||
*/
|
||||
export function composeEndpoints<T extends readonly EndpointFactory<any>[]>(
|
||||
factories: T,
|
||||
clientHelpers: any,
|
||||
apiKey: string,
|
||||
factories: T,
|
||||
clientHelpers: any,
|
||||
apiKey: string,
|
||||
): UnionToIntersection<ExtractApiEndpoints<T[number]>> {
|
||||
const instances = factories.map((f) => f(clientHelpers, apiKey));
|
||||
return Object.assign({}, ...instances) as any;
|
||||
const instances = factories.map((f) => f(clientHelpers, apiKey));
|
||||
return Object.assign({}, ...instances) as any;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { dereference } from '@readme/openapi-parser';
|
||||
import { OpenAPIV2 } from 'openapi-types';
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { dereference } from "@readme/openapi-parser";
|
||||
import { OpenAPIV2 } from "openapi-types";
|
||||
|
||||
/**
|
||||
* A map of operation IDs to their hashes.
|
||||
*/
|
||||
export interface DocumentHash {
|
||||
[operationId: string]: string;
|
||||
[operationId: string]: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,36 +18,34 @@ export interface DocumentHash {
|
||||
* @param doc The OpenAPI v2 document to hash.
|
||||
* @returns A map of operation IDs to their hashes.
|
||||
*/
|
||||
export async function hashOpenApiDocument(
|
||||
doc: OpenAPIV2.Document,
|
||||
): Promise<DocumentHash> {
|
||||
const spec = await dereference(doc);
|
||||
const hashes: DocumentHash = {};
|
||||
const seen = new Set<string>();
|
||||
export async function hashOpenApiDocument(doc: OpenAPIV2.Document): Promise<DocumentHash> {
|
||||
const spec = await dereference(doc);
|
||||
const hashes: DocumentHash = {};
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const [path, item] of Object.entries(spec.paths)) {
|
||||
for (const [method, operation] of Object.entries(item)) {
|
||||
if (typeof operation !== 'object') {
|
||||
continue;
|
||||
}
|
||||
for (const [path, item] of Object.entries(spec.paths)) {
|
||||
for (const [method, operation] of Object.entries(item)) {
|
||||
if (typeof operation !== "object") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const { parameters, responses } = operation as OpenAPIV2.OperationObject;
|
||||
const raw = JSON.stringify(
|
||||
{
|
||||
path,
|
||||
method: method.toUpperCase(),
|
||||
parameters,
|
||||
responses,
|
||||
},
|
||||
Object.keys({ path, method, parameters, responses }).sort(),
|
||||
);
|
||||
const { parameters, responses } = operation as OpenAPIV2.OperationObject;
|
||||
const raw = JSON.stringify(
|
||||
{
|
||||
path,
|
||||
method: method.toUpperCase(),
|
||||
parameters,
|
||||
responses,
|
||||
},
|
||||
Object.keys({ path, method, parameters, responses }).sort(),
|
||||
);
|
||||
|
||||
const hash = createHash('md5').update(raw).digest('hex').slice(0, 16);
|
||||
const final = seen.has(hash) ? `${hash}_${seen.size}` : hash;
|
||||
seen.add(final);
|
||||
hashes[`${method.toUpperCase()} ${path}`] = final;
|
||||
}
|
||||
}
|
||||
const hash = createHash("md5").update(raw).digest("hex").slice(0, 16);
|
||||
const final = seen.has(hash) ? `${hash}_${seen.size}` : hash;
|
||||
seen.add(final);
|
||||
hashes[`${method.toUpperCase()} ${path}`] = final;
|
||||
}
|
||||
}
|
||||
|
||||
return hashes;
|
||||
return hashes;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import canonicals from '~/openapi-canonical-families.json';
|
||||
import hashes from '~/openapi-operation-hashes.json';
|
||||
import log from '~/utils/log';
|
||||
import canonicals from "~/openapi-canonical-families.json";
|
||||
import hashes from "~/openapi-operation-hashes.json";
|
||||
import log from "~/utils/log";
|
||||
|
||||
/**
|
||||
* The known API versions based on operation hashes.
|
||||
@@ -15,80 +15,63 @@ const VERSIONS = Object.keys(hashes) as Version[];
|
||||
* @param observed - A mapping of operation identifiers to their hashes.
|
||||
* @returns The detected API version.
|
||||
*/
|
||||
export function detectApiVersion(
|
||||
observed: Record<string, string> | null,
|
||||
): Version {
|
||||
if (!observed) {
|
||||
const latest = VERSIONS.at(-1)!;
|
||||
log.warn(
|
||||
'api',
|
||||
'No operation hashes observed, defaulting to version %s',
|
||||
latest,
|
||||
);
|
||||
return latest;
|
||||
}
|
||||
export function detectApiVersion(observed: Record<string, string> | null): Version {
|
||||
if (!observed) {
|
||||
const latest = VERSIONS.at(-1)!;
|
||||
log.warn("api", "No operation hashes observed, defaulting to version %s", latest);
|
||||
return latest;
|
||||
}
|
||||
|
||||
let bestVersion: Version | null = null;
|
||||
let bestScore = -1;
|
||||
let bestVersion: Version | null = null;
|
||||
let bestScore = -1;
|
||||
|
||||
for (const [version, known] of Object.entries(hashes) as [
|
||||
Version,
|
||||
Record<string, string>,
|
||||
][]) {
|
||||
let score = 0;
|
||||
for (const [op, hash] of Object.entries(observed)) {
|
||||
if (known[op] === hash) score++;
|
||||
}
|
||||
if (score > bestScore) {
|
||||
bestVersion = version;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
for (const [version, known] of Object.entries(hashes) as [Version, Record<string, string>][]) {
|
||||
let score = 0;
|
||||
for (const [op, hash] of Object.entries(observed)) {
|
||||
if (known[op] === hash) score++;
|
||||
}
|
||||
if (score > bestScore) {
|
||||
bestVersion = version;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestVersion || bestScore === 0) {
|
||||
const latest = VERSIONS.at(-1)!;
|
||||
log.warn(
|
||||
'api',
|
||||
'Could not determine API version, defaulting to %s',
|
||||
latest,
|
||||
);
|
||||
return latest;
|
||||
}
|
||||
if (!bestVersion || bestScore === 0) {
|
||||
const latest = VERSIONS.at(-1)!;
|
||||
log.warn("api", "Could not determine API version, defaulting to %s", latest);
|
||||
return latest;
|
||||
}
|
||||
|
||||
if (bestScore < Object.keys(observed).length) {
|
||||
log.warn(
|
||||
'api',
|
||||
'Partial version match: %d/%d endpoints for version %s',
|
||||
bestScore,
|
||||
Object.keys(observed).length,
|
||||
bestVersion,
|
||||
);
|
||||
}
|
||||
if (bestScore < Object.keys(observed).length) {
|
||||
log.warn(
|
||||
"api",
|
||||
"Partial version match: %d/%d endpoints for version %s",
|
||||
bestScore,
|
||||
Object.keys(observed).length,
|
||||
bestVersion,
|
||||
);
|
||||
}
|
||||
|
||||
const canonical = Object.entries(canonicals).find(([_, family]) =>
|
||||
family.includes(bestVersion),
|
||||
)?.[0] as Version | undefined;
|
||||
const canonical = Object.entries(canonicals).find(([_, family]) =>
|
||||
family.includes(bestVersion),
|
||||
)?.[0] as Version | undefined;
|
||||
|
||||
if (!canonical) {
|
||||
log.warn(
|
||||
'api',
|
||||
'Could not canonicalize detected version %s, using as-is',
|
||||
bestVersion,
|
||||
);
|
||||
if (!canonical) {
|
||||
log.warn("api", "Could not canonicalize detected version %s, using as-is", bestVersion);
|
||||
|
||||
return bestVersion;
|
||||
}
|
||||
return bestVersion;
|
||||
}
|
||||
|
||||
if (canonical !== bestVersion) {
|
||||
log.info(
|
||||
'api',
|
||||
'Canonicalizing detected version %s → %s (same schema)',
|
||||
bestVersion,
|
||||
canonical,
|
||||
);
|
||||
}
|
||||
if (canonical !== bestVersion) {
|
||||
log.info(
|
||||
"api",
|
||||
"Canonicalizing detected version %s → %s (same schema)",
|
||||
bestVersion,
|
||||
canonical,
|
||||
);
|
||||
}
|
||||
|
||||
return canonical;
|
||||
return canonical;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -99,5 +82,5 @@ export function detectApiVersion(
|
||||
* @returns True if current is at least baseline, false otherwise.
|
||||
*/
|
||||
export function isAtLeast(current: Version, baseline: Version) {
|
||||
return VERSIONS.indexOf(current) >= VERSIONS.indexOf(baseline);
|
||||
return VERSIONS.indexOf(current) >= VERSIONS.indexOf(baseline);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { access, constants, readFile, writeFile } from 'node:fs/promises';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
import log from '~/utils/log';
|
||||
import { access, constants, readFile, writeFile } from "node:fs/promises";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
|
||||
import log from "~/utils/log";
|
||||
|
||||
export interface DNSRecord {
|
||||
type: 'A' | 'AAAA' | (string & {});
|
||||
name: string;
|
||||
value: string;
|
||||
type: "A" | "AAAA" | (string & {});
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
// This class is solely for DNS records that are out of tree in the main
|
||||
@@ -15,113 +16,104 @@ export interface DNSRecord {
|
||||
// All DNS insertions and deletions are handled by the main config manager,
|
||||
// but are passed through to here if the extra file is being used.
|
||||
export class HeadscaleDNSConfig {
|
||||
private records: DNSRecord[];
|
||||
private access: 'rw' | 'ro' | 'no';
|
||||
private path?: string;
|
||||
private writeLock = false;
|
||||
private records: DNSRecord[];
|
||||
private access: "rw" | "ro" | "no";
|
||||
private path?: string;
|
||||
private writeLock = false;
|
||||
|
||||
constructor(
|
||||
access: 'rw' | 'ro' | 'no',
|
||||
records?: DNSRecord[],
|
||||
path?: string,
|
||||
) {
|
||||
this.access = access;
|
||||
this.records = records ?? [];
|
||||
this.path = path;
|
||||
}
|
||||
constructor(access: "rw" | "ro" | "no", records?: DNSRecord[], path?: string) {
|
||||
this.access = access;
|
||||
this.records = records ?? [];
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
readable() {
|
||||
return this.access !== 'no';
|
||||
}
|
||||
readable() {
|
||||
return this.access !== "no";
|
||||
}
|
||||
|
||||
writable() {
|
||||
return this.access === 'rw';
|
||||
}
|
||||
writable() {
|
||||
return this.access === "rw";
|
||||
}
|
||||
|
||||
get r() {
|
||||
return this.records;
|
||||
}
|
||||
get r() {
|
||||
return this.records;
|
||||
}
|
||||
|
||||
async patch(records: DNSRecord[]) {
|
||||
if (!this.path || !this.readable() || !this.writable()) {
|
||||
return;
|
||||
}
|
||||
async patch(records: DNSRecord[]) {
|
||||
if (!this.path || !this.readable() || !this.writable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.records = records;
|
||||
log.debug(
|
||||
'config',
|
||||
'Patching DNS records (%d -> %d)',
|
||||
this.records.length,
|
||||
records.length,
|
||||
);
|
||||
this.records = records;
|
||||
log.debug("config", "Patching DNS records (%d -> %d)", this.records.length, records.length);
|
||||
|
||||
return this.write();
|
||||
}
|
||||
return this.write();
|
||||
}
|
||||
|
||||
private async write() {
|
||||
if (!this.path || !this.writable()) {
|
||||
return;
|
||||
}
|
||||
private async write() {
|
||||
if (!this.path || !this.writable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (this.writeLock) {
|
||||
await setTimeout(100);
|
||||
}
|
||||
while (this.writeLock) {
|
||||
await setTimeout(100);
|
||||
}
|
||||
|
||||
this.writeLock = true;
|
||||
log.debug('config', 'Writing updated DNS configuration to %s', this.path);
|
||||
const data = JSON.stringify(this.records, null, 4);
|
||||
await writeFile(this.path, data);
|
||||
this.writeLock = false;
|
||||
}
|
||||
this.writeLock = true;
|
||||
log.debug("config", "Writing updated DNS configuration to %s", this.path);
|
||||
const data = JSON.stringify(this.records, null, 4);
|
||||
await writeFile(this.path, data);
|
||||
this.writeLock = false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadHeadscaleDNS(path?: string) {
|
||||
if (!path) {
|
||||
return;
|
||||
}
|
||||
if (!path) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.debug('config', 'Loading Headscale DNS configuration file: %s', path);
|
||||
const { w, r } = await validateConfigPath(path);
|
||||
if (!r) {
|
||||
return new HeadscaleDNSConfig('no');
|
||||
}
|
||||
log.debug("config", "Loading Headscale DNS configuration file: %s", path);
|
||||
const { w, r } = await validateConfigPath(path);
|
||||
if (!r) {
|
||||
return new HeadscaleDNSConfig("no");
|
||||
}
|
||||
|
||||
const records = await loadConfigFile(path);
|
||||
if (!records) {
|
||||
return new HeadscaleDNSConfig('no');
|
||||
}
|
||||
const records = await loadConfigFile(path);
|
||||
if (!records) {
|
||||
return new HeadscaleDNSConfig("no");
|
||||
}
|
||||
|
||||
return new HeadscaleDNSConfig(w ? 'rw' : 'ro', records, path);
|
||||
return new HeadscaleDNSConfig(w ? "rw" : "ro", records, path);
|
||||
}
|
||||
|
||||
async function validateConfigPath(path: string) {
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.R_OK);
|
||||
log.info('config', 'Found a valid Headscale DNS file at %s', path);
|
||||
} catch (error) {
|
||||
log.error('config', 'Unable to read a Headscale DNS file at %s', path);
|
||||
log.error('config', '%s', error);
|
||||
return { w: false, r: false };
|
||||
}
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.R_OK);
|
||||
log.info("config", "Found a valid Headscale DNS file at %s", path);
|
||||
} catch (error) {
|
||||
log.error("config", "Unable to read a Headscale DNS file at %s", path);
|
||||
log.error("config", "%s", error);
|
||||
return { w: false, r: false };
|
||||
}
|
||||
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.W_OK);
|
||||
return { w: true, r: true };
|
||||
} catch (error) {
|
||||
log.warn('config', 'Headscale DNS file at %s is not writable', path);
|
||||
return { w: false, r: true };
|
||||
}
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.W_OK);
|
||||
return { w: true, r: true };
|
||||
} catch (error) {
|
||||
log.warn("config", "Headscale DNS file at %s is not writable", path);
|
||||
return { w: false, r: true };
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfigFile(path: string) {
|
||||
log.debug('config', 'Reading Headscale DNS file at %s', path);
|
||||
try {
|
||||
const data = await readFile(path, 'utf8');
|
||||
const records = JSON.parse(data) as DNSRecord[];
|
||||
return records;
|
||||
} catch (e) {
|
||||
log.error('config', 'Error reading Headscale DNS file at %s', path);
|
||||
log.error('config', '%s', e);
|
||||
return false;
|
||||
}
|
||||
log.debug("config", "Reading Headscale DNS file at %s", path);
|
||||
try {
|
||||
const data = await readFile(path, "utf8");
|
||||
const records = JSON.parse(data) as DNSRecord[];
|
||||
return records;
|
||||
} catch (e) {
|
||||
log.error("config", "Error reading Headscale DNS file at %s", path);
|
||||
log.error("config", "%s", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,422 +1,373 @@
|
||||
import { constants, access, readFile, writeFile } from 'node:fs/promises';
|
||||
import { exit } from 'node:process';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
import { type } from 'arktype';
|
||||
import { Document, parseDocument } from 'yaml';
|
||||
import log from '~/utils/log';
|
||||
import { DNSRecord, HeadscaleDNSConfig, loadHeadscaleDNS } from './config-dns';
|
||||
import { headscaleConfig } from './config-schema';
|
||||
import { constants, access, readFile, writeFile } from "node:fs/promises";
|
||||
import { exit } from "node:process";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
|
||||
import { type } from "arktype";
|
||||
import { Document, parseDocument } from "yaml";
|
||||
|
||||
import log from "~/utils/log";
|
||||
|
||||
import { DNSRecord, HeadscaleDNSConfig, loadHeadscaleDNS } from "./config-dns";
|
||||
import { headscaleConfig } from "./config-schema";
|
||||
|
||||
interface PatchConfig {
|
||||
path: string;
|
||||
value: unknown;
|
||||
path: string;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
// We need a class for the config because we need to be able to
|
||||
// support retrieving it via a getter but also be able to
|
||||
// patch it and to query it for its mode
|
||||
class HeadscaleConfig {
|
||||
private config?: typeof headscaleConfig.infer;
|
||||
private document?: Document;
|
||||
private access: 'rw' | 'ro' | 'no';
|
||||
private path?: string;
|
||||
private writeLock = false;
|
||||
private dns?: HeadscaleDNSConfig;
|
||||
private config?: typeof headscaleConfig.infer;
|
||||
private document?: Document;
|
||||
private access: "rw" | "ro" | "no";
|
||||
private path?: string;
|
||||
private writeLock = false;
|
||||
private dns?: HeadscaleDNSConfig;
|
||||
|
||||
constructor(
|
||||
access: 'rw' | 'ro' | 'no',
|
||||
dns?: HeadscaleDNSConfig,
|
||||
config?: typeof headscaleConfig.infer,
|
||||
document?: Document,
|
||||
path?: string,
|
||||
) {
|
||||
this.access = access;
|
||||
this.config = config;
|
||||
this.document = document;
|
||||
this.path = path;
|
||||
this.dns = dns;
|
||||
}
|
||||
constructor(
|
||||
access: "rw" | "ro" | "no",
|
||||
dns?: HeadscaleDNSConfig,
|
||||
config?: typeof headscaleConfig.infer,
|
||||
document?: Document,
|
||||
path?: string,
|
||||
) {
|
||||
this.access = access;
|
||||
this.config = config;
|
||||
this.document = document;
|
||||
this.path = path;
|
||||
this.dns = dns;
|
||||
}
|
||||
|
||||
readable() {
|
||||
return this.access !== 'no';
|
||||
}
|
||||
readable() {
|
||||
return this.access !== "no";
|
||||
}
|
||||
|
||||
writable() {
|
||||
return this.access === 'rw';
|
||||
}
|
||||
writable() {
|
||||
return this.access === "rw";
|
||||
}
|
||||
|
||||
get c() {
|
||||
return this.config;
|
||||
}
|
||||
get c() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
get d() {
|
||||
if (this.dns) {
|
||||
return this.dns.r;
|
||||
}
|
||||
get d() {
|
||||
if (this.dns) {
|
||||
return this.dns.r;
|
||||
}
|
||||
|
||||
return this.config?.dns.extra_records ?? [];
|
||||
}
|
||||
return this.config?.dns.extra_records ?? [];
|
||||
}
|
||||
|
||||
async patch(patches: PatchConfig[]) {
|
||||
if (!this.path || !this.document || !this.readable() || !this.writable()) {
|
||||
return;
|
||||
}
|
||||
async patch(patches: PatchConfig[]) {
|
||||
if (!this.path || !this.document || !this.readable() || !this.writable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.debug('config', 'Patching Headscale configuration');
|
||||
for (const patch of patches) {
|
||||
const { path, value } = patch;
|
||||
log.debug('config', 'Patching %s with %o', path, value);
|
||||
log.debug("config", "Patching Headscale configuration");
|
||||
for (const patch of patches) {
|
||||
const { path, value } = patch;
|
||||
log.debug("config", "Patching %s with %o", path, 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.
|
||||
// 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.
|
||||
|
||||
// Iterate through each character, and if we find a dot, we check if
|
||||
// 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 key = [];
|
||||
let current = '';
|
||||
let quote = false;
|
||||
// Iterate through each character, and if we find a dot, we check if
|
||||
// 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 key = [];
|
||||
let current = "";
|
||||
let quote = false;
|
||||
|
||||
for (const char of path) {
|
||||
if (char === '"') {
|
||||
quote = !quote;
|
||||
}
|
||||
for (const char of path) {
|
||||
if (char === '"') {
|
||||
quote = !quote;
|
||||
}
|
||||
|
||||
if (char === '.' && !quote) {
|
||||
key.push(current);
|
||||
current = '';
|
||||
continue;
|
||||
}
|
||||
if (char === "." && !quote) {
|
||||
key.push(current);
|
||||
current = "";
|
||||
continue;
|
||||
}
|
||||
|
||||
current += char;
|
||||
}
|
||||
current += char;
|
||||
}
|
||||
|
||||
key.push(current.replaceAll('"', ''));
|
||||
if (value === null) {
|
||||
this.document.deleteIn(key);
|
||||
continue;
|
||||
}
|
||||
key.push(current.replaceAll('"', ""));
|
||||
if (value === null) {
|
||||
this.document.deleteIn(key);
|
||||
continue;
|
||||
}
|
||||
|
||||
this.document.setIn(key, value);
|
||||
}
|
||||
this.document.setIn(key, value);
|
||||
}
|
||||
|
||||
// Revalidate our configuration and update the config
|
||||
// object with the new configuration
|
||||
log.info('config', 'Revalidating Headscale configuration');
|
||||
const config = validateConfig(this.document.toJSON());
|
||||
if (!config) {
|
||||
return;
|
||||
}
|
||||
// Revalidate our configuration and update the config
|
||||
// object with the new configuration
|
||||
log.info("config", "Revalidating Headscale configuration");
|
||||
const config = validateConfig(this.document.toJSON());
|
||||
if (!config) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'config',
|
||||
'Writing updated Headscale configuration to %s',
|
||||
this.path,
|
||||
);
|
||||
log.debug("config", "Writing updated Headscale configuration to %s", this.path);
|
||||
|
||||
// We need to lock the writeLock so that we don't try to write
|
||||
// to the file while we're already writing to it
|
||||
while (this.writeLock) {
|
||||
await setTimeout(100);
|
||||
}
|
||||
// We need to lock the writeLock so that we don't try to write
|
||||
// to the file while we're already writing to it
|
||||
while (this.writeLock) {
|
||||
await setTimeout(100);
|
||||
}
|
||||
|
||||
this.writeLock = true;
|
||||
await writeFile(this.path, this.document.toString(), 'utf8');
|
||||
this.config = config;
|
||||
this.writeLock = false;
|
||||
return;
|
||||
}
|
||||
this.writeLock = true;
|
||||
await writeFile(this.path, this.document.toString(), "utf8");
|
||||
this.config = config;
|
||||
this.writeLock = false;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a DNS record to the Headscale configuration.
|
||||
* Differentiates between the file mode and config mode automatically.
|
||||
* @param record The DNS record to add.
|
||||
* @returns True if we need to restart the integration.
|
||||
*/
|
||||
async addDNS(record: DNSRecord) {
|
||||
if (this.dns) {
|
||||
if (!this.dns.readable() || !this.dns.writable()) {
|
||||
log.debug('config', 'DNS config is not writable');
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Adds a DNS record to the Headscale configuration.
|
||||
* Differentiates between the file mode and config mode automatically.
|
||||
* @param record The DNS record to add.
|
||||
* @returns True if we need to restart the integration.
|
||||
*/
|
||||
async addDNS(record: DNSRecord) {
|
||||
if (this.dns) {
|
||||
if (!this.dns.readable() || !this.dns.writable()) {
|
||||
log.debug("config", "DNS config is not writable");
|
||||
return;
|
||||
}
|
||||
|
||||
const records = this.dns.r;
|
||||
if (
|
||||
records.some((i) => i.name === record.name && i.type === record.type)
|
||||
) {
|
||||
log.debug('config', 'DNS record already exists');
|
||||
return;
|
||||
}
|
||||
const records = this.dns.r;
|
||||
if (records.some((i) => i.name === record.name && i.type === record.type)) {
|
||||
log.debug("config", "DNS record already exists");
|
||||
return;
|
||||
}
|
||||
|
||||
return this.dns.patch([...records, record]);
|
||||
}
|
||||
return this.dns.patch([...records, record]);
|
||||
}
|
||||
|
||||
// If we get here, we need to add to the main config instead of
|
||||
// a separate file (which requires an integration restart)
|
||||
const existing = this.config?.dns.extra_records ?? [];
|
||||
if (
|
||||
existing.some((i) => i.name === record.name && i.type === record.type)
|
||||
) {
|
||||
log.debug('config', 'DNS record already exists');
|
||||
return;
|
||||
}
|
||||
// If we get here, we need to add to the main config instead of
|
||||
// a separate file (which requires an integration restart)
|
||||
const existing = this.config?.dns.extra_records ?? [];
|
||||
if (existing.some((i) => i.name === record.name && i.type === record.type)) {
|
||||
log.debug("config", "DNS record already exists");
|
||||
return;
|
||||
}
|
||||
|
||||
await this.patch([
|
||||
{
|
||||
path: 'dns.extra_records',
|
||||
value: Array.from(new Set([...existing, record])),
|
||||
},
|
||||
]);
|
||||
await this.patch([
|
||||
{
|
||||
path: "dns.extra_records",
|
||||
value: Array.from(new Set([...existing, record])),
|
||||
},
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a DNS record from the Headscale configuration.
|
||||
* Differentiates between the file mode and config mode automatically.
|
||||
* @param records The DNS record to remove.
|
||||
* @returns True if we need to restart the integration.
|
||||
*/
|
||||
async removeDNS(record: DNSRecord) {
|
||||
// In this case we need to check both the main config and the DNS config
|
||||
// to see if the record exists, and if it does, we need to remove it
|
||||
// from both places.
|
||||
/**
|
||||
* Removes a DNS record from the Headscale configuration.
|
||||
* Differentiates between the file mode and config mode automatically.
|
||||
* @param records The DNS record to remove.
|
||||
* @returns True if we need to restart the integration.
|
||||
*/
|
||||
async removeDNS(record: DNSRecord) {
|
||||
// In this case we need to check both the main config and the DNS config
|
||||
// to see if the record exists, and if it does, we need to remove it
|
||||
// from both places.
|
||||
|
||||
if (this.dns) {
|
||||
if (!this.dns.readable() || !this.dns.writable()) {
|
||||
log.debug('config', 'DNS config is not writable');
|
||||
return;
|
||||
}
|
||||
if (this.dns) {
|
||||
if (!this.dns.readable() || !this.dns.writable()) {
|
||||
log.debug("config", "DNS config is not writable");
|
||||
return;
|
||||
}
|
||||
|
||||
const records = this.dns.r.filter(
|
||||
(i) => i.name !== record.name || i.type !== record.type,
|
||||
);
|
||||
const records = this.dns.r.filter((i) => i.name !== record.name || i.type !== record.type);
|
||||
|
||||
return this.dns.patch(records);
|
||||
}
|
||||
return this.dns.patch(records);
|
||||
}
|
||||
|
||||
// If we get here, we need to remove from the main config instead of
|
||||
// a separate file (which requires an integration restart)
|
||||
const existing = this.config?.dns.extra_records ?? [];
|
||||
const filtered = existing.filter(
|
||||
(i) => i.name !== record.name || i.type !== record.type,
|
||||
);
|
||||
// If we get here, we need to remove from the main config instead of
|
||||
// a separate file (which requires an integration restart)
|
||||
const existing = this.config?.dns.extra_records ?? [];
|
||||
const filtered = existing.filter((i) => i.name !== record.name || i.type !== record.type);
|
||||
|
||||
// If the length of the existing records is the same as the filtered
|
||||
// records, then we don't need to do anything
|
||||
if (existing.length === filtered.length) {
|
||||
return;
|
||||
}
|
||||
// If the length of the existing records is the same as the filtered
|
||||
// records, then we don't need to do anything
|
||||
if (existing.length === filtered.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.patch([
|
||||
{
|
||||
path: 'dns.extra_records',
|
||||
value: existing.filter(
|
||||
(i) => i.name !== record.name || i.type !== record.type,
|
||||
),
|
||||
},
|
||||
]);
|
||||
await this.patch([
|
||||
{
|
||||
path: "dns.extra_records",
|
||||
value: existing.filter((i) => i.name !== record.name || i.type !== record.type),
|
||||
},
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadHeadscaleConfig(
|
||||
path?: string,
|
||||
strict = true,
|
||||
dnsPath?: string,
|
||||
) {
|
||||
if (!path) {
|
||||
log.debug('config', 'No Headscale configuration file was provided');
|
||||
return new HeadscaleConfig('no');
|
||||
}
|
||||
export async function loadHeadscaleConfig(path?: string, strict = true, dnsPath?: string) {
|
||||
if (!path) {
|
||||
log.debug("config", "No Headscale configuration file was provided");
|
||||
return new HeadscaleConfig("no");
|
||||
}
|
||||
|
||||
log.debug('config', 'Loading Headscale configuration file: %s', path);
|
||||
const { r, w } = await validateConfigPath(path);
|
||||
if (!r) {
|
||||
return new HeadscaleConfig('no');
|
||||
}
|
||||
log.debug("config", "Loading Headscale configuration file: %s", path);
|
||||
const { r, w } = await validateConfigPath(path);
|
||||
if (!r) {
|
||||
return new HeadscaleConfig("no");
|
||||
}
|
||||
|
||||
const document = await loadConfigFile(path);
|
||||
if (!document) {
|
||||
return new HeadscaleConfig('no');
|
||||
}
|
||||
const document = await loadConfigFile(path);
|
||||
if (!document) {
|
||||
return new HeadscaleConfig("no");
|
||||
}
|
||||
|
||||
if (!strict) {
|
||||
return new HeadscaleConfig(
|
||||
w ? 'rw' : 'ro',
|
||||
new HeadscaleDNSConfig('no'),
|
||||
augmentUnstrictConfig(document.toJSON()),
|
||||
document,
|
||||
path,
|
||||
);
|
||||
}
|
||||
if (!strict) {
|
||||
return new HeadscaleConfig(
|
||||
w ? "rw" : "ro",
|
||||
new HeadscaleDNSConfig("no"),
|
||||
augmentUnstrictConfig(document.toJSON()),
|
||||
document,
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
const config = validateConfig(document.toJSON());
|
||||
if (!config) {
|
||||
return new HeadscaleConfig('no');
|
||||
}
|
||||
const config = validateConfig(document.toJSON());
|
||||
if (!config) {
|
||||
return new HeadscaleConfig("no");
|
||||
}
|
||||
|
||||
if (config.dns.extra_records && config.dns.extra_records_path) {
|
||||
log.warn(
|
||||
'config',
|
||||
'Both extra_records and extra_records_path are set, Headscale will crash',
|
||||
);
|
||||
if (config.dns.extra_records && config.dns.extra_records_path) {
|
||||
log.warn("config", "Both extra_records and extra_records_path are set, Headscale will crash");
|
||||
|
||||
log.warn('config', 'Please remove one of them from the configuration file');
|
||||
return new HeadscaleConfig('no');
|
||||
}
|
||||
log.warn("config", "Please remove one of them from the configuration file");
|
||||
return new HeadscaleConfig("no");
|
||||
}
|
||||
|
||||
const dns = await loadHeadscaleDNS(dnsPath);
|
||||
if (dns && !config.dns.extra_records_path) {
|
||||
log.error(
|
||||
'config',
|
||||
'Using separate DNS config file but dns.extra_records_path is not set in Headscale config',
|
||||
);
|
||||
log.error(
|
||||
'config',
|
||||
'Please set `dns.extra_records_path` in the Headscale config',
|
||||
);
|
||||
log.error(
|
||||
'config',
|
||||
'Or remove `headscale.dns_records_path` from the Headplane config',
|
||||
);
|
||||
const dns = await loadHeadscaleDNS(dnsPath);
|
||||
if (dns && !config.dns.extra_records_path) {
|
||||
log.error(
|
||||
"config",
|
||||
"Using separate DNS config file but dns.extra_records_path is not set in Headscale config",
|
||||
);
|
||||
log.error("config", "Please set `dns.extra_records_path` in the Headscale config");
|
||||
log.error("config", "Or remove `headscale.dns_records_path` from the Headplane config");
|
||||
|
||||
exit(1);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
return new HeadscaleConfig(w ? 'rw' : 'ro', dns, config, document, path);
|
||||
return new HeadscaleConfig(w ? "rw" : "ro", dns, config, document, path);
|
||||
}
|
||||
|
||||
async function validateConfigPath(path: string) {
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.R_OK);
|
||||
log.info(
|
||||
'config',
|
||||
'Found a valid Headscale configuration file at %s',
|
||||
path,
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(
|
||||
'config',
|
||||
'Unable to read a Headscale configuration file at %s',
|
||||
path,
|
||||
);
|
||||
log.error('config', '%s', error);
|
||||
return { w: false, r: false };
|
||||
}
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.R_OK);
|
||||
log.info("config", "Found a valid Headscale configuration file at %s", path);
|
||||
} catch (error) {
|
||||
log.error("config", "Unable to read a Headscale configuration file at %s", path);
|
||||
log.error("config", "%s", error);
|
||||
return { w: false, r: false };
|
||||
}
|
||||
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.W_OK);
|
||||
return { w: true, r: true };
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'config',
|
||||
'Headscale configuration file at %s is not writable',
|
||||
path,
|
||||
);
|
||||
return { w: false, r: true };
|
||||
}
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.W_OK);
|
||||
return { w: true, r: true };
|
||||
} catch (error) {
|
||||
log.warn("config", "Headscale configuration file at %s is not writable", path);
|
||||
return { w: false, r: true };
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfigFile(path: string) {
|
||||
log.debug('config', 'Reading Headscale configuration file at %s', path);
|
||||
try {
|
||||
const data = await readFile(path, 'utf8');
|
||||
const configYaml = parseDocument(data);
|
||||
if (configYaml.errors.length > 0) {
|
||||
log.error(
|
||||
'config',
|
||||
'Cannot parse Headscale configuration file at %s',
|
||||
path,
|
||||
);
|
||||
for (const error of configYaml.errors) {
|
||||
log.error('config', ` - ${error.toString()}`);
|
||||
}
|
||||
log.debug("config", "Reading Headscale configuration file at %s", path);
|
||||
try {
|
||||
const data = await readFile(path, "utf8");
|
||||
const configYaml = parseDocument(data);
|
||||
if (configYaml.errors.length > 0) {
|
||||
log.error("config", "Cannot parse Headscale configuration file at %s", path);
|
||||
for (const error of configYaml.errors) {
|
||||
log.error("config", ` - ${error.toString()}`);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return configYaml;
|
||||
} catch (e) {
|
||||
log.error(
|
||||
'config',
|
||||
'Error reading Headscale configuration file at %s',
|
||||
path,
|
||||
);
|
||||
log.error('config', '%s', e);
|
||||
return false;
|
||||
}
|
||||
return configYaml;
|
||||
} catch (e) {
|
||||
log.error("config", "Error reading Headscale configuration file at %s", path);
|
||||
log.error("config", "%s", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateConfig(config: unknown) {
|
||||
log.debug('config', 'Validating Headscale configuration');
|
||||
const result = headscaleConfig(config);
|
||||
if (result instanceof type.errors) {
|
||||
log.error('config', 'Error validating Headscale configuration:');
|
||||
for (const [number, error] of result.entries()) {
|
||||
log.error('config', ` - (${number}): ${error.toString()}`);
|
||||
}
|
||||
log.debug("config", "Validating Headscale configuration");
|
||||
const result = headscaleConfig(config);
|
||||
if (result instanceof type.errors) {
|
||||
log.error("config", "Error validating Headscale configuration:");
|
||||
for (const [number, error] of result.entries()) {
|
||||
log.error("config", ` - (${number}): ${error.toString()}`);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
// If config_strict is false, we set the defaults and disable
|
||||
// the schema checking for the values that are not present
|
||||
function augmentUnstrictConfig(loaded: Partial<typeof headscaleConfig.infer>) {
|
||||
log.debug('config', 'Augmenting Headscale configuration in non-strict mode');
|
||||
const 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',
|
||||
grpc_listen_addr: loaded.grpc_listen_addr ?? ':50443',
|
||||
grpc_allow_insecure: loaded.grpc_allow_insecure ?? false,
|
||||
randomize_client_port: loaded.randomize_client_port ?? false,
|
||||
unix_socket: loaded.unix_socket ?? '/var/run/headscale/headscale.sock',
|
||||
unix_socket_permission: loaded.unix_socket_permission ?? '0770',
|
||||
log.debug("config", "Augmenting Headscale configuration in non-strict mode");
|
||||
const 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",
|
||||
grpc_listen_addr: loaded.grpc_listen_addr ?? ":50443",
|
||||
grpc_allow_insecure: loaded.grpc_allow_insecure ?? false,
|
||||
randomize_client_port: loaded.randomize_client_port ?? false,
|
||||
unix_socket: loaded.unix_socket ?? "/var/run/headscale/headscale.sock",
|
||||
unix_socket_permission: loaded.unix_socket_permission ?? "0770",
|
||||
|
||||
log: loaded.log ?? {
|
||||
level: 'info',
|
||||
format: 'text',
|
||||
},
|
||||
log: loaded.log ?? {
|
||||
level: "info",
|
||||
format: "text",
|
||||
},
|
||||
|
||||
logtail: loaded.logtail ?? {
|
||||
enabled: false,
|
||||
},
|
||||
logtail: loaded.logtail ?? {
|
||||
enabled: false,
|
||||
},
|
||||
|
||||
prefixes: loaded.prefixes ?? {
|
||||
allocation: 'sequential',
|
||||
v4: '',
|
||||
v6: '',
|
||||
},
|
||||
prefixes: loaded.prefixes ?? {
|
||||
allocation: "sequential",
|
||||
v4: "",
|
||||
v6: "",
|
||||
},
|
||||
|
||||
dns: loaded.dns ?? {
|
||||
nameservers: {
|
||||
global: [],
|
||||
split: {},
|
||||
},
|
||||
search_domains: [],
|
||||
extra_records: [],
|
||||
magic_dns: false,
|
||||
base_domain: 'headscale.net',
|
||||
},
|
||||
};
|
||||
dns: loaded.dns ?? {
|
||||
nameservers: {
|
||||
global: [],
|
||||
split: {},
|
||||
},
|
||||
search_domains: [],
|
||||
extra_records: [],
|
||||
magic_dns: false,
|
||||
base_domain: "headscale.net",
|
||||
},
|
||||
};
|
||||
|
||||
log.warn('config', 'Headscale configuration was loaded in non-strict mode');
|
||||
log.warn('config', 'This is very dangerous and comes with a few caveats:');
|
||||
log.warn('config', ' - Headplane could very easily crash');
|
||||
log.warn('config', ' - Headplane could break your Headscale installation');
|
||||
log.warn(
|
||||
'config',
|
||||
' - The UI could throw random errors/show incorrect data',
|
||||
);
|
||||
log.warn("config", "Headscale configuration was loaded in non-strict mode");
|
||||
log.warn("config", "This is very dangerous and comes with a few caveats:");
|
||||
log.warn("config", " - Headplane could very easily crash");
|
||||
log.warn("config", " - Headplane could break your Headscale installation");
|
||||
log.warn("config", " - The UI could throw random errors/show incorrect data");
|
||||
|
||||
return config as typeof headscaleConfig.infer;
|
||||
return config as typeof headscaleConfig.infer;
|
||||
}
|
||||
|
||||
@@ -1,150 +1,150 @@
|
||||
import { type } from 'arktype';
|
||||
import { type } from "arktype";
|
||||
|
||||
const goBool = type('boolean | "true" | "false"').pipe((v) => {
|
||||
if (v === 'true') return true;
|
||||
if (v === 'false') return false;
|
||||
return v;
|
||||
if (v === "true") return true;
|
||||
if (v === "false") return false;
|
||||
return v;
|
||||
});
|
||||
|
||||
const goDuration = type('0 | string').pipe((v) => {
|
||||
return v.toString();
|
||||
const goDuration = type("0 | string").pipe((v) => {
|
||||
return v.toString();
|
||||
});
|
||||
|
||||
const databaseConfig = type({
|
||||
type: '"sqlite" | "sqlite3"',
|
||||
sqlite: {
|
||||
path: 'string',
|
||||
write_ahead_log: goBool.default(true),
|
||||
wal_autocheckpoint: 'number = 1000',
|
||||
},
|
||||
type: '"sqlite" | "sqlite3"',
|
||||
sqlite: {
|
||||
path: "string",
|
||||
write_ahead_log: goBool.default(true),
|
||||
wal_autocheckpoint: "number = 1000",
|
||||
},
|
||||
})
|
||||
.or({
|
||||
type: '"postgres"',
|
||||
postgres: {
|
||||
host: 'string',
|
||||
port: 'number | ""',
|
||||
name: 'string',
|
||||
user: 'string',
|
||||
pass: 'string',
|
||||
max_open_conns: 'number = 10',
|
||||
max_idle_conns: 'number = 10',
|
||||
conn_max_idle_time_secs: 'number = 3600',
|
||||
ssl: goBool.default(false),
|
||||
},
|
||||
})
|
||||
.merge({
|
||||
debug: goBool.default(false),
|
||||
'gorm?': {
|
||||
prepare_stmt: goBool.default(true),
|
||||
parameterized_queries: goBool.default(true),
|
||||
skip_err_record_not_found: goBool.default(true),
|
||||
slow_threshold: 'number = 1000',
|
||||
},
|
||||
});
|
||||
.or({
|
||||
type: '"postgres"',
|
||||
postgres: {
|
||||
host: "string",
|
||||
port: 'number | ""',
|
||||
name: "string",
|
||||
user: "string",
|
||||
pass: "string",
|
||||
max_open_conns: "number = 10",
|
||||
max_idle_conns: "number = 10",
|
||||
conn_max_idle_time_secs: "number = 3600",
|
||||
ssl: goBool.default(false),
|
||||
},
|
||||
})
|
||||
.merge({
|
||||
debug: goBool.default(false),
|
||||
"gorm?": {
|
||||
prepare_stmt: goBool.default(true),
|
||||
parameterized_queries: goBool.default(true),
|
||||
skip_err_record_not_found: goBool.default(true),
|
||||
slow_threshold: "number = 1000",
|
||||
},
|
||||
});
|
||||
|
||||
// Not as strict parsing because we just need the values
|
||||
// to be slightly truthy enough to safely modify them
|
||||
export type HeadscaleConfig = typeof headscaleConfig.infer;
|
||||
export const headscaleConfig = type({
|
||||
server_url: 'string',
|
||||
listen_addr: 'string',
|
||||
'metrics_listen_addr?': 'string',
|
||||
grpc_listen_addr: 'string = ":50433"',
|
||||
grpc_allow_insecure: goBool.default(false),
|
||||
noise: {
|
||||
private_key_path: 'string',
|
||||
},
|
||||
prefixes: {
|
||||
v4: 'string?',
|
||||
v6: 'string?',
|
||||
allocation: '"sequential" | "random" = "sequential"',
|
||||
},
|
||||
derp: {
|
||||
server: {
|
||||
enabled: goBool.default(true),
|
||||
region_id: 'number?',
|
||||
region_code: 'string?',
|
||||
region_name: 'string?',
|
||||
stun_listen_addr: 'string?',
|
||||
private_key_path: 'string?',
|
||||
ipv4: 'string?',
|
||||
ipv6: 'string?',
|
||||
automatically_add_embedded_derp_region: goBool.default(true),
|
||||
},
|
||||
urls: 'string[]?',
|
||||
paths: 'string[]?',
|
||||
auto_update_enabled: goBool.default(true),
|
||||
update_frequency: goDuration.default('24h'),
|
||||
},
|
||||
server_url: "string",
|
||||
listen_addr: "string",
|
||||
"metrics_listen_addr?": "string",
|
||||
grpc_listen_addr: 'string = ":50433"',
|
||||
grpc_allow_insecure: goBool.default(false),
|
||||
noise: {
|
||||
private_key_path: "string",
|
||||
},
|
||||
prefixes: {
|
||||
v4: "string?",
|
||||
v6: "string?",
|
||||
allocation: '"sequential" | "random" = "sequential"',
|
||||
},
|
||||
derp: {
|
||||
server: {
|
||||
enabled: goBool.default(true),
|
||||
region_id: "number?",
|
||||
region_code: "string?",
|
||||
region_name: "string?",
|
||||
stun_listen_addr: "string?",
|
||||
private_key_path: "string?",
|
||||
ipv4: "string?",
|
||||
ipv6: "string?",
|
||||
automatically_add_embedded_derp_region: goBool.default(true),
|
||||
},
|
||||
urls: "string[]?",
|
||||
paths: "string[]?",
|
||||
auto_update_enabled: goBool.default(true),
|
||||
update_frequency: goDuration.default("24h"),
|
||||
},
|
||||
|
||||
disable_check_updates: goBool.default(false),
|
||||
ephemeral_node_inactivity_timeout: goDuration.default('30m'),
|
||||
database: databaseConfig,
|
||||
disable_check_updates: goBool.default(false),
|
||||
ephemeral_node_inactivity_timeout: goDuration.default("30m"),
|
||||
database: databaseConfig,
|
||||
|
||||
acme_url: 'string = "https://acme-v02.api.letsencrypt.org/directory"',
|
||||
acme_email: 'string = ""',
|
||||
tls_letsencrypt_hostname: 'string = ""',
|
||||
tls_letsencrypt_cache_dir: 'string = "/var/lib/headscale/cache"',
|
||||
tls_letsencrypt_challenge_type: 'string = "HTTP-01"',
|
||||
tls_letsencrypt_listen: 'string = ":http"',
|
||||
'tls_cert_path?': 'string',
|
||||
'tls_key_path?': 'string',
|
||||
acme_url: 'string = "https://acme-v02.api.letsencrypt.org/directory"',
|
||||
acme_email: 'string = ""',
|
||||
tls_letsencrypt_hostname: 'string = ""',
|
||||
tls_letsencrypt_cache_dir: 'string = "/var/lib/headscale/cache"',
|
||||
tls_letsencrypt_challenge_type: 'string = "HTTP-01"',
|
||||
tls_letsencrypt_listen: 'string = ":http"',
|
||||
"tls_cert_path?": "string",
|
||||
"tls_key_path?": "string",
|
||||
|
||||
log: type({
|
||||
format: 'string = "text"',
|
||||
level: 'string = "info"',
|
||||
}).default(() => ({ format: 'text', level: 'info' })),
|
||||
log: type({
|
||||
format: 'string = "text"',
|
||||
level: 'string = "info"',
|
||||
}).default(() => ({ format: "text", level: "info" })),
|
||||
|
||||
'policy?': {
|
||||
mode: '"database" | "file" = "file"',
|
||||
path: 'string?',
|
||||
},
|
||||
"policy?": {
|
||||
mode: '"database" | "file" = "file"',
|
||||
path: "string?",
|
||||
},
|
||||
|
||||
dns: {
|
||||
magic_dns: goBool.default(true),
|
||||
base_domain: 'string = "headscale.net"',
|
||||
override_local_dns: goBool.default(false),
|
||||
nameservers: type({
|
||||
global: type('string[]').default(() => []),
|
||||
split: type('Record<string, string[]>').default(() => ({})),
|
||||
}).default(() => ({ global: [], split: {} })),
|
||||
search_domains: type('string[]').default(() => []),
|
||||
extra_records: type({
|
||||
name: 'string',
|
||||
value: 'string',
|
||||
type: 'string | "A"',
|
||||
})
|
||||
.array()
|
||||
.optional(),
|
||||
extra_records_path: 'string?',
|
||||
},
|
||||
dns: {
|
||||
magic_dns: goBool.default(true),
|
||||
base_domain: 'string = "headscale.net"',
|
||||
override_local_dns: goBool.default(false),
|
||||
nameservers: type({
|
||||
global: type("string[]").default(() => []),
|
||||
split: type("Record<string, string[]>").default(() => ({})),
|
||||
}).default(() => ({ global: [], split: {} })),
|
||||
search_domains: type("string[]").default(() => []),
|
||||
extra_records: type({
|
||||
name: "string",
|
||||
value: "string",
|
||||
type: 'string | "A"',
|
||||
})
|
||||
.array()
|
||||
.optional(),
|
||||
extra_records_path: "string?",
|
||||
},
|
||||
|
||||
unix_socket: 'string?',
|
||||
unix_socket_permission: 'string = "0770"',
|
||||
unix_socket: "string?",
|
||||
unix_socket_permission: 'string = "0770"',
|
||||
|
||||
'oidc?': {
|
||||
only_start_if_oidc_is_available: goBool.default(false),
|
||||
issuer: 'string',
|
||||
client_id: 'string',
|
||||
client_secret: 'string?',
|
||||
client_secret_path: 'string?',
|
||||
expiry: goDuration.default('180d'),
|
||||
use_expiry_from_token: goBool.default(false),
|
||||
scope: type('string[]').default(() => ['openid', 'email', 'profile']),
|
||||
extra_params: 'Record<string, string>?',
|
||||
allowed_domains: 'string[]?',
|
||||
allowed_groups: 'string[]?',
|
||||
allowed_users: 'string[]?',
|
||||
'pkce?': {
|
||||
enabled: goBool.default(false),
|
||||
method: 'string = "S256"',
|
||||
},
|
||||
map_legacy_users: goBool.default(false),
|
||||
},
|
||||
"oidc?": {
|
||||
only_start_if_oidc_is_available: goBool.default(false),
|
||||
issuer: "string",
|
||||
client_id: "string",
|
||||
client_secret: "string?",
|
||||
client_secret_path: "string?",
|
||||
expiry: goDuration.default("180d"),
|
||||
use_expiry_from_token: goBool.default(false),
|
||||
scope: type("string[]").default(() => ["openid", "email", "profile"]),
|
||||
extra_params: "Record<string, string>?",
|
||||
allowed_domains: "string[]?",
|
||||
allowed_groups: "string[]?",
|
||||
allowed_users: "string[]?",
|
||||
"pkce?": {
|
||||
enabled: goBool.default(false),
|
||||
method: 'string = "S256"',
|
||||
},
|
||||
map_legacy_users: goBool.default(false),
|
||||
},
|
||||
|
||||
'logtail?': {
|
||||
enabled: goBool.default(false),
|
||||
},
|
||||
"logtail?": {
|
||||
enabled: goBool.default(false),
|
||||
},
|
||||
|
||||
randomize_client_port: goBool.default(false),
|
||||
randomize_client_port: goBool.default(false),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user