Compare commits

...

38 Commits

Author SHA1 Message Date
Aarnav Tale 83a69792ea chore: v0.5.6 2025-04-02 13:47:45 -04:00
Aarnav Tale fee5f423a6 chore: update nix hash 2025-04-02 13:40:50 -04:00
Aarnav Tale d698cf5478 fix: open file in a+ to avoid read issues 2025-04-02 13:40:01 -04:00
Aarnav Tale 80c987f383 feat: implement onboarding for non-registered users 2025-04-02 13:26:58 -04:00
Aarnav Tale 17d477bf0f fix: join copied commands without a space 2025-04-02 13:25:33 -04:00
Aarnav Tale 5e5c7c4c7a fix: remove unreleased feature and ignore invalid keys in config 2025-04-02 10:16:34 -04:00
Aarnav Tale 2e383ddabe feat: reimplement user actions 2025-04-01 12:27:44 -04:00
Aarnav Tale 2299907932 chore: document user login state 2025-03-29 14:28:11 -04:00
Aarnav Tale 3771890f98 fix: disable live data fetching when a dialog is open 2025-03-29 14:27:56 -04:00
Aarnav Tale bf02015dc7 feat: begin working on user auth 2025-03-29 14:12:15 -04:00
Aarnav Tale 8429b19c4a docs: use git tags for bare metal 2025-03-29 14:10:46 -04:00
Aarnav Tale 9a5952adcb fix: split email for username if preferred_username is unavailable 2025-03-29 12:16:38 -04:00
Aarnav Tale 222ac7a279 chore: make prefixes.v4/6 optional 2025-03-27 12:20:47 -04:00
Aarnav Tale 6f40f9cfac feat: rework github actions 2025-03-24 16:49:54 -04:00
Aarnav Tale 457cbc45e6 fix: do not bundle ssr deps in dev 2025-03-24 16:26:47 -04:00
Aarnav Tale aac8a9ef12 fix: update nix hash 2025-03-24 16:15:38 -04:00
Aarnav Tale b8d22beb17 feat: bundle node_modules into the server 2025-03-24 16:15:38 -04:00
Aarnav Tale cac64a6fbe chore: remove old server code 2025-03-24 16:15:38 -04:00
Aarnav Tale 5918d0e501 fix: allow hostname passthrough for hono node 2025-03-24 16:15:38 -04:00
Aarnav Tale 03acebb23e fix: env variables did not resolve in prod 2025-03-24 16:15:38 -04:00
Aarnav Tale 73ea35980d feat: switch agent fetching to the server side
this brings the benefit of fitting in the revalidator lifecycle we have
created via the useLiveData hook.
2025-03-24 16:15:38 -04:00
Aarnav Tale 9a1051b9af feat: reimplement websocket to use hono 2025-03-24 16:15:38 -04:00
Aarnav Tale c066b3064d fix: make useLiveData a context that is pausable 2025-03-24 16:15:38 -04:00
Aarnav Tale 98d02bb595 chore: migrate patching to HeadscaleConfig 2025-03-24 16:15:38 -04:00
Aarnav Tale 2964ff295e fix: set config after loading 2025-03-24 16:15:38 -04:00
Aarnav Tale b0a3f9d5fd chore: update deps 2025-03-24 16:15:38 -04:00
Aarnav Tale 34cfee7cff feat: reach an initial working stage 2025-03-24 16:15:38 -04:00
Aarnav Tale 8db323b63f style: use biome in zed settings 2025-03-24 16:15:38 -04:00
Aarnav Tale 08c25caca3 chore: add deps and include 2025-03-24 16:15:38 -04:00
Aarnav Tale cbbd64e91a feat: initial server side systems 2025-03-24 16:15:38 -04:00
Aarnav Tale 48fc0f7ef3 fix: remove unnecessary title in templates 2025-03-18 12:25:19 -04:00
Aarnav Tale 23fd2bbda2 chore: update nix sha 2025-03-18 01:59:16 -04:00
Aarnav Tale 05837963c4 chore: FUNDING 2025-03-18 01:56:17 -04:00
Aarnav Tale 2a16115e69 feat: add issue templates 2025-03-18 01:54:36 -04:00
Aarnav Tale 5675ecdeac chore: add 'community' things 2025-03-18 01:32:05 -04:00
Aarnav Tale 29424366a8 chore: v0.5.5 2025-03-18 00:46:54 -04:00
Aarnav Tale c47346df52 fix: do not require authkey 2025-03-18 00:46:35 -04:00
Aarnav Tale 92dedf51aa fix: ignore ws_agents if there are no agents connected 2025-03-18 00:43:52 -04:00
97 changed files with 4395 additions and 3217 deletions
+2
View File
@@ -0,0 +1,2 @@
github: tale
ko_fi: atale
+31
View File
@@ -0,0 +1,31 @@
name: Bug Report
description: Report an issue with Headplane
assignees: [tale]
labels: [bug, triage]
body:
- type: textarea
attributes:
label: Description
description: |
A detailed description of the issue and steps to reproduce it.
If applicable, include any error messages or screenshots.
If this is not an issue with Headplane, but an issue with your
environment, please consider opening a discussion instead.
placeholder: e.g. "When I try to upload a file, I get an error message."
validations:
required: true
- type: input
attributes:
label: Headplane Version
description: What version of Headplane are you using?
placeholder: e.g. "v0.5.5"
validations:
required: true
- type: input
attributes:
label: Headscale Version
description: What version of Headscale are you using?
placeholder: e.g. "v0.25.1"
validations:
required: true
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,15 @@
name: Feature Request
description: Request a new feature or enhancement for Headplane
assignees: [tale]
labels: [enhancement, triage]
body:
- type: textarea
attributes:
label: Description
description: |
A detailed description of the feature you would like to see added.
Please include any relevant context, such as why this feature is
important and how it would benefit other users beyond yourself.
placeholder: e.g. "I would like to see support for custom themes in Headplane so that I can personalize the interface to my liking."
validations:
required: true
+33
View File
@@ -0,0 +1,33 @@
name: Automated
on:
schedule:
- cron: "0 8 * * 0"
workflow_dispatch:
concurrency:
group: automation-${{ github.ref }}
cancel-in-progress: true
permissions:
actions: write # Allow canceling in-progress runs
contents: read # Read access to the repository
pull-requests: write # Allow creating pull requests
jobs:
flake-inputs:
name: flake-inputs
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@main
with:
determinate: true
- uses: DeterminateSystems/update-flake-lock@main
with:
pr-title: "chore: update flake.lock"
pr-labels: |
automated
+70
View File
@@ -0,0 +1,70 @@
name: Build
on:
push:
branches:
- "main"
pull_request:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
actions: write # Allow canceling in-progress runs
contents: read # Read access to the repository
jobs:
native:
name: native
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Install node.js
uses: actions/setup-node@v4
with:
node-version: 22
- uses: pnpm/action-setup@v4
name: Install pnpm
with:
version: 10
run_install: false
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v4
name: Setup pnpm cache
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm build
nix:
name: nix
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@main
with:
determinate: true
- name: Check flake inputs
uses: DeterminateSystems/flake-checker-action@main
- name: Check flake outputs
run: nix flake check --all-systems
+45 -36
View File
@@ -1,44 +1,53 @@
name: Publish Nightly Docker Image
name: Nightly
on:
schedule:
- cron: "0 8 * * *"
workflow_dispatch:
schedule:
- cron: "0 8 * * *"
workflow_dispatch:
concurrency:
group: publish-nightly-${{ github.ref }}
cancel-in-progress: true
permissions:
actions: write # Allow canceling in-progress runs
contents: read # Read access to the repository
packages: write # Write access to the container registry
jobs:
publish:
name: Build and Publish Nightly
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
publish:
name: docker-publish
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to ghcr.io
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to ghcr.io
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker Metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=edge,branch=main
- name: Docker Metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=edge,branch=main
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64, linux/arm64
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64, linux/arm64
-20
View File
@@ -1,20 +0,0 @@
name: Update flake.lock
on:
workflow_dispatch:
schedule:
- cron: "0 0 * * 0"
jobs:
update-flake-inputs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/update-flake-lock@main
with:
pr-title: "chore: update flake.lock"
pr-labels: |
dependencies
automated
- uses: DeterminateSystems/flake-checker-action@main
- run: nix flake check --all-systems
-24
View File
@@ -1,24 +0,0 @@
name: Nix CI
on:
pull_request:
workflow_dispatch:
push:
branches:
- main
tags:
- v?[0-9]+.[0-9]+.[0-9]+*
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
nix-ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
with:
determinate: true
- uses: DeterminateSystems/flake-checker-action@main
- run: nix flake check --all-systems
-46
View File
@@ -1,46 +0,0 @@
name: Publish Docker Image
on:
push:
tags:
- "*"
jobs:
publish:
name: Build and Publish
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to ghcr.io
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker Metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest,enable=false
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64, linux/arm64
-44
View File
@@ -1,44 +0,0 @@
name: "Build"
on:
push:
branches:
- "main"
pull_request:
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Install node.js
uses: actions/setup-node@v4
with:
node-version: 22
- uses: pnpm/action-setup@v4
name: Install pnpm
with:
version: 10
run_install: false
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v4
name: Setup pnpm cache
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm build
+55
View File
@@ -0,0 +1,55 @@
name: Release
on:
push:
tags:
- "*"
concurrency:
group: publish-${{ github.ref }}
cancel-in-progress: true
permissions:
actions: write # Allow canceling in-progress runs
contents: read # Read access to the repository
packages: write # Write access to the container registry
jobs:
publish:
name: docker-publish
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to ghcr.io
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker Metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest,enable=false
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64, linux/arm64
+1 -1
View File
@@ -1,2 +1,2 @@
side-effects-cache = false
shamefully-hoist = true
public-hoist-pattern[]=*hono*
+17
View File
@@ -0,0 +1,17 @@
{
"formatter": {
"language_server": {
"name": "biome"
}
},
"code_actions_on_format": {
"source.fixAll.biome": true,
"source.organizeImports.biome": true
},
"languages": {
"YAML": {
"tab_size": 2,
"hard_tabs": false
}
}
}
+23
View File
@@ -1,3 +1,26 @@
### 0.5.6 (April 2, 2025)
### IMPORTANT
> **PLEASE** update to this ASAP if you were using Google OIDC. This is because previously *ANY* accounts have admin access to your Tailnet if they discover the URL that Headplane is being hosted on. This new change enforces that new logins by default are not given any permissions. You will need to re-login to Headplane to generate an owner account and prevent unauthorized access.
Implemented *proper* authentication methods for OIDC.
This is a large update and copies the permission system from Tailscale.
Permissions are not automatically derived from OIDC, but they can be configured via the UI.
Additionally, certain roles give certain capabilities, limiting access to parts of the dashboard.
By default, new users will have a `member` role which forbids access to the UI.
If there are no users, the first user will be given an `owner` role which cannot be removed.
**Changes**:
- Switched the internal server to use `hono` for better performance.
- Fixed an issue that caused dialogs to randomly refocus every 3 seconds.
- Headplane will not send API requests when the tab is not focused.
- Continue loosening the configuration requirements for Headscale (part of an ongoing effort).
- Unknown values in the Headplane config no longer cause a crash.
- Fixed an issue that caused copied commands to have a random space (fixes [#161](https://github.com/tale/headplane/issues/161))
### 0.5.5 (March 18, 2025)
- Hotfix an issue that caused Headplane to crash if no agents are available
### 0.5.4 (March 18, 2025)
- Fixed a typo in the Kubernetes documentation
- Handle split and global DNS records not being set in the Headscale config (via [#129](https://github.com/tale/headplane/pull/129))
+1 -8
View File
@@ -9,15 +9,8 @@ RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm run build
RUN pnpm prune --prod
FROM node:22-alpine
WORKDIR /app
COPY --from=build /app/build /app/build
COPY --from=build /app/node_modules /app/node_modules
RUN echo '{"type":"module"}' > /app/package.json
EXPOSE 3000
ENV NODE_ENV=production
ENV HOST=0.0.0.0
CMD [ "node", "./build/headplane/server.js" ]
CMD [ "node", "./build/server/index.js" ]
+5
View File
@@ -44,6 +44,11 @@ There are 2 ways to deploy Headplane:
Simple mode does not include the automatic management of DNS and Headplane
settings, requiring manual editing and reloading when making changes.
## Contributing
Headplane is an open-source project and contributions are welcome! If you have
any suggestions, bug reports, or feature requests, please open an issue. Also
refer to the [contributor guidelines](./docs/CONTRIBUTING.md) for more info.
<picture>
<source
media="(prefers-color-scheme: dark)"
+6
View File
@@ -53,5 +53,11 @@ func httpToWs(controlURL string) (string, error) {
return "", fmt.Errorf("unsupported scheme: %s", u.Scheme)
}
// We also need to append /_dial to the path
if u.Path[len(u.Path)-1] != '/' {
u.Path += "/"
}
u.Path += "_dial"
return u.String(), nil
}
+1 -3
View File
@@ -24,9 +24,7 @@ export default function Code({ isCopyable, children, className }: CodeProps) {
type="button"
className="bottom-0 right-0 absolute"
onClick={async (event) => {
const text = Array.isArray(children)
? children.join(' ')
: children;
const text = Array.isArray(children) ? children.join('') : children;
const svgs = event.currentTarget.querySelectorAll('svg');
for (const svg of svgs) {
+11 -1
View File
@@ -1,4 +1,4 @@
import React, { cloneElement, useRef } from 'react';
import React, { cloneElement, useEffect, useRef } from 'react';
import {
type AriaDialogProps,
type AriaModalOverlayProps,
@@ -19,6 +19,7 @@ import IconButton, { IconButtonProps } from '~/components/IconButton';
import Text from '~/components/Text';
import Title from '~/components/Title';
import cn from '~/utils/cn';
import { useLiveData } from '~/utils/live-data';
export interface DialogProps extends OverlayTriggerProps {
children:
@@ -30,6 +31,7 @@ export interface DialogProps extends OverlayTriggerProps {
}
function Dialog(props: DialogProps) {
const { pause, resume } = useLiveData();
const state = useOverlayTriggerState(props);
const { triggerProps, overlayProps } = useOverlayTrigger(
{
@@ -38,6 +40,14 @@ function Dialog(props: DialogProps) {
state,
);
useEffect(() => {
if (state.isOpen) {
pause();
} else {
resume();
}
}, [state.isOpen]);
if (Array.isArray(props.children)) {
const [button, panel] = props.children;
return (
-4
View File
@@ -1,10 +1,6 @@
import Link from '~/components/Link';
import cn from '~/utils/cn';
declare global {
const __VERSION__: string;
}
interface FooterProps {
url: string;
debug: boolean;
+29 -25
View File
@@ -10,12 +10,14 @@ import {
import type { ReactNode } from 'react';
import { NavLink, useSubmit } from 'react-router';
import Menu from '~/components/Menu';
import { AuthSession } from '~/server/web/sessions';
import cn from '~/utils/cn';
import type { SessionData } from '~/utils/sessions.server';
interface Props {
configAvailable: boolean;
user?: SessionData['user'];
uiAccess: boolean;
onboarding: boolean;
user?: AuthSession['user'];
}
interface LinkProps {
@@ -135,29 +137,31 @@ export default function Header(data: Props) {
) : undefined}
</div>
</div>
<nav className="container flex items-center gap-x-4 overflow-x-auto font-semibold">
<TabLink
to="/machines"
name="Machines"
icon={<Server className="w-5" />}
/>
<TabLink to="/users" name="Users" icon={<Users className="w-5" />} />
<TabLink
to="/acls"
name="Access Control"
icon={<Lock className="w-5" />}
/>
{data.configAvailable ? (
<>
<TabLink to="/dns" name="DNS" icon={<Globe2 className="w-5" />} />
<TabLink
to="/settings"
name="Settings"
icon={<Settings className="w-5" />}
/>
</>
) : undefined}
</nav>
{data.uiAccess && !data.onboarding ? (
<nav className="container flex items-center gap-x-4 overflow-x-auto font-semibold">
<TabLink
to="/machines"
name="Machines"
icon={<Server className="w-5" />}
/>
<TabLink to="/users" name="Users" icon={<Users className="w-5" />} />
<TabLink
to="/acls"
name="Access Control"
icon={<Lock className="w-5" />}
/>
{data.configAvailable ? (
<>
<TabLink to="/dns" name="DNS" icon={<Globe2 className="w-5" />} />
<TabLink
to="/settings"
name="Settings"
icon={<Settings className="w-5" />}
/>
</>
) : undefined}
</nav>
) : undefined}
</header>
);
}
+78
View File
@@ -0,0 +1,78 @@
import { useRef } from 'react';
import {
AriaTabListProps,
AriaTabPanelProps,
useTab,
useTabList,
useTabPanel,
} from 'react-aria';
import { Item, Node, TabListState, useTabListState } from 'react-stately';
import cn from '~/utils/cn';
export interface OptionsProps extends AriaTabListProps<object> {
label: string;
className?: string;
}
function Options({ label, className, ...props }: OptionsProps) {
const state = useTabListState(props);
const ref = useRef<HTMLDivElement | null>(null);
const { tabListProps } = useTabList(props, state, ref);
return (
<div className={cn('flex flex-col', className)}>
<div
{...tabListProps}
ref={ref}
className="flex items-center gap-2 overflow-x-scroll"
>
{[...state.collection].map((item) => (
<Option key={item.key} item={item} state={state} />
))}
</div>
<OptionsPanel key={state.selectedItem?.key} state={state} />
</div>
);
}
export interface OptionsOptionProps {
item: Node<object>;
state: TabListState<object>;
}
function Option({ item, state }: OptionsOptionProps) {
const { key, rendered } = item;
const ref = useRef<HTMLDivElement | null>(null);
const { tabProps } = useTab({ key }, state, ref);
return (
<div
{...tabProps}
ref={ref}
className={cn(
'pl-0.5 pr-2 py-0.5 rounded-lg cursor-pointer',
'aria-selected:bg-headplane-100 dark:aria-selected:bg-headplane-950',
'focus:outline-none focus:ring z-10',
'border border-headplane-100 dark:border-headplane-800',
)}
>
{rendered}
</div>
);
}
export interface OptionsPanelProps extends AriaTabPanelProps {
state: TabListState<object>;
}
function OptionsPanel({ state, ...props }: OptionsPanelProps) {
const ref = useRef<HTMLDivElement | null>(null);
const { tabPanelProps } = useTabPanel(props, state, ref);
return (
<div {...tabPanelProps} ref={ref} className="w-full mt-2">
{state.selectedItem?.props.children}
</div>
);
}
export default Object.assign(Options, { Item });
+14 -20
View File
@@ -1,34 +1,29 @@
import { XCircleFillIcon } from '@primer/octicons-react';
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { Outlet, useLoaderData } from 'react-router';
import type { LoadContext } from '~/server';
import { ResponseError } from '~/server/headscale/api-client';
import cn from '~/utils/cn';
import { HeadscaleError, healthcheck, pull } from '~/utils/headscale';
import { destroySession, getSession } from '~/utils/sessions.server';
import { useLiveData } from '~/utils/useLiveData';
import log from '~server/utils/log';
import log from '~/utils/log';
export async function loader({ request }: LoaderFunctionArgs) {
let healthy = false;
try {
healthy = await healthcheck();
} catch (error) {
log.debug('APIC', 'Healthcheck failed %o', error);
}
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const healthy = await context.client.healthcheck();
const session = await context.sessions.auth(request);
// We shouldn't session invalidate if Headscale is down
// TODO: Notify in the logs or the UI that OIDC auth key is wrong if enabled
if (healthy) {
// We can assert because shell ensures this is set
const session = await getSession(request.headers.get('Cookie'));
const apiKey = session.get('hsApiKey')!;
try {
await pull('v1/apikey', apiKey);
await context.client.get('v1/apikey', session.get('api_key')!);
} catch (error) {
if (error instanceof HeadscaleError) {
log.debug('APIC', 'API Key validation failed %o', error);
if (error instanceof ResponseError) {
log.debug('api', 'API Key validation failed %o', error);
return redirect('/login', {
headers: {
'Set-Cookie': await destroySession(session),
'Set-Cookie': await context.sessions.destroy(session),
},
});
}
@@ -41,7 +36,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function Layout() {
useLiveData({ interval: 3000 });
const { healthy } = useLoaderData<typeof loader>();
return (
+107 -19
View File
@@ -1,42 +1,130 @@
import { BanIcon, CircleCheckIcon } from 'lucide-react';
import {
LoaderFunctionArgs,
Outlet,
redirect,
useLoaderData,
} from 'react-router';
import Button from '~/components/Button';
import Card from '~/components/Card';
import Code from '~/components/Code';
import Footer from '~/components/Footer';
import Header from '~/components/Header';
import { hs_getConfig } from '~/utils/config/loader';
import { getSession } from '~/utils/sessions.server';
import type { AppContext } from '~server/context/app';
import { hp_getConfig } from '~server/context/global';
import type { LoadContext } from '~/server';
import { Capabilities } from '~/server/web/roles';
import { User } from '~/types';
import log from '~/utils/log';
// This loads the bare minimum for the application to function
// So we know that if context fails to load then well, oops?
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (!session.has('hsApiKey')) {
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
try {
const session = await context.sessions.auth(request);
if (!session.has('api_key')) {
// There is a session, but it's not valid
return redirect('/login', {
headers: {
'Set-Cookie': await context.sessions.destroy(session),
},
});
}
// Onboarding is only a feature of the OIDC flow
if (context.oidc && !request.url.endsWith('/onboarding')) {
let onboarded = true;
try {
const { users } = await context.client.get<{ users: User[] }>(
'v1/user',
session.get('api_key')!,
);
if (users.length === 0) {
onboarded = false;
}
const user = users.find((u) => {
if (u.provider !== 'oidc') {
return false;
}
// For some reason, headscale makes providerID a url where the
// last component is the subject, so we need to strip that out
const subject = u.providerId?.split('/').pop();
if (!subject) {
return false;
}
const sessionUser = session.get('user');
if (!sessionUser) {
return false;
}
return subject === sessionUser.subject;
});
if (user) {
onboarded = true;
}
} catch (e) {
// If we cannot lookup users, just assume our user is onboarded
log.debug('api', 'Failed to lookup users %o', e);
onboarded = true;
}
if (!onboarded) {
return redirect('/onboarding');
}
}
const check = await context.sessions.check(request, Capabilities.ui_access);
return {
config: context.hs.c,
url: context.config.headscale.public_url ?? context.config.headscale.url,
configAvailable: context.hs.readable(),
debug: context.config.debug,
user: session.get('user'),
uiAccess: check,
onboarding: request.url.endsWith('/onboarding'),
};
} catch {
// No session, so we can just return
return redirect('/login');
}
const context = hp_getConfig();
const { mode, config } = hs_getConfig();
return {
config,
url: context.headscale.public_url ?? context.headscale.url,
configAvailable: mode !== 'no',
debug: context.debug,
user: session.get('user'),
};
}
export default function Shell() {
const data = useLoaderData<typeof loader>();
return (
<>
<Header {...data} />
<Outlet />
{data.uiAccess ? (
<Outlet />
) : (
<Card className="mx-auto w-fit mt-24">
<div className="flex items-center justify-between">
<Card.Title className="text-3xl mb-0">Connected</Card.Title>
<CircleCheckIcon className="w-10 h-10" />
</div>
<Card.Text className="my-4 text-lg">
Connect to Tailscale with your devices to access this Tailnet. Use
this command to help you get started:
</Card.Text>
<Button className="pointer-events-none text-md hover:bg-initial focus:ring-0">
<Code className="pointer-events-auto bg-transparent" isCopyable>
tailscale up --login-server={data.url}
</Code>
</Button>
<p className="mt-4 text-sm opacity-50">
Your account does not have access to the UI. Please contact your
administrator if you believe this is a mistake.
</p>
</Card>
)}
<Footer {...data} />
</>
);
+27 -15
View File
@@ -1,4 +1,8 @@
import type { LinksFunction, MetaFunction } from 'react-router';
import type {
LinksFunction,
LoaderFunctionArgs,
MetaFunction,
} from 'react-router';
import {
Links,
Meta,
@@ -12,7 +16,10 @@ import { ErrorPopup } from '~/components/Error';
import ProgressBar from '~/components/ProgressBar';
import ToastProvider from '~/components/ToastProvider';
import stylesheet from '~/tailwind.css?url';
import { LiveDataProvider } from '~/utils/live-data';
import { useToastQueue } from '~/utils/toast';
import { LoadContext } from './server';
import log from './utils/log';
export const meta: MetaFunction = () => [
{ title: 'Headplane' },
@@ -29,21 +36,26 @@ export const links: LinksFunction = () => [
export function Layout({ children }: { readonly children: React.ReactNode }) {
const toastQueue = useToastQueue();
// LiveDataProvider is wrapped at the top level since dialogs and things
// that control its state are usually open in portal containers which
// are not a part of the normal React tree.
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body className="overscroll-none dark:bg-headplane-900 dark:text-headplane-50">
{children}
<ToastProvider queue={toastQueue} />
<ScrollRestoration />
<Scripts />
</body>
</html>
<LiveDataProvider>
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body className="overscroll-none dark:bg-headplane-900 dark:text-headplane-50">
{children}
<ToastProvider queue={toastQueue} />
<ScrollRestoration />
<Scripts />
</body>
</html>
</LiveDataProvider>
);
}
+1 -3
View File
@@ -11,12 +11,10 @@ export default [
route('/oidc/callback', 'routes/auth/oidc-callback.ts'),
route('/oidc/start', 'routes/auth/oidc-start.ts'),
// API
route('/api/agent', 'routes/api/agent.ts'),
// All the main logged-in dashboard routes
// Double nested to separate error propagations
layout('layouts/shell.tsx', [
route('/onboarding', 'routes/users/onboarding.tsx'),
layout('layouts/dashboard.tsx', [
...prefix('/machines', [
index('routes/machines/overview.tsx'),
+29 -24
View File
@@ -1,25 +1,31 @@
import { Construction, Eye, FlaskConical, Pencil } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router';
import { useFetcher, useLoaderData, useRevalidator } from 'react-router';
import {
redirect,
useFetcher,
useLoaderData,
useRevalidator,
} from 'react-router';
import Button from '~/components/Button';
import Link from '~/components/Link';
import Notice from '~/components/Notice';
import Spinner from '~/components/Spinner';
import Tabs from '~/components/Tabs';
import { hs_getConfig } from '~/utils/config/loader';
import { HeadscaleError, pull, put } from '~/utils/headscale';
import type { LoadContext } from '~/server';
import { ResponseError } from '~/server/headscale/api-client';
import log from '~/utils/log';
import { send } from '~/utils/res';
import { getSession } from '~/utils/sessions.server';
import toast from '~/utils/toast';
import type { AppContext } from '~server/context/app';
import log from '~server/utils/log';
import { Differ, Editor } from './components/cm.client';
import { ErrorView } from './components/error';
import { Unavailable } from './components/unavailable';
export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
// The way policy is handled in 0.23 of Headscale and later is verbose.
// The 2 ACL policy modes are either the database one or file one
@@ -45,31 +51,30 @@ export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
// We can do damage control by checking for write access and if we are not
// able to PUT an ACL policy on the v1/policy route, we can already know
// that the policy is at the very-least readonly or not available.
const { mode, config } = hs_getConfig();
let modeGuess = 'database'; // Assume database mode
if (mode !== 'no') {
modeGuess = config.policy?.mode ?? 'database';
if (!context.hs.readable()) {
modeGuess = context.hs.c!.policy?.mode ?? 'database';
}
// Attempt to load the policy, for both the frontend and for checking
// if we are able to write to the policy for write access
try {
const { policy } = await pull<{ policy: string }>(
const { policy } = await context.client.get<{ policy: string }>(
'v1/policy',
session.get('hsApiKey')!,
session.get('api_key')!,
);
let write = false; // On file mode we already know it's readonly
if (modeGuess === 'database' && policy.length > 0) {
try {
await put('v1/policy', session.get('hsApiKey')!, {
await context.client.put('v1/policy', session.get('api_key')!, {
policy: policy,
});
write = true;
} catch (error) {
write = false;
log.debug('APIC', 'Failed to write to ACL policy with error %s', error);
log.debug('api', 'Failed to write to ACL policy with error %s', error);
}
}
@@ -102,17 +107,17 @@ export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
}
}
export async function action({ request }: ActionFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (!session.has('hsApiKey')) {
return send({ success: false, error: null }, 401);
}
export async function action({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
try {
const { acl } = (await request.json()) as { acl: string };
const { policy } = await put<{ policy: string }>(
const { policy } = await context.client.put<{ policy: string }>(
'v1/policy',
session.get('hsApiKey')!,
session.get('api_key')!,
{
policy: acl,
},
@@ -120,14 +125,14 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true, policy, error: null };
} catch (error) {
log.debug('APIC', 'Failed to update ACL policy with error %s', error);
log.debug('api', 'Failed to update ACL policy with error %s', error);
// @ts-ignore: TODO: Shut UP we know it's a string most of the time
const text = JSON.parse(error.message);
return send(
{ success: false, error: text.message },
{
status: error instanceof HeadscaleError ? error.status : 500,
status: error instanceof ResponseError ? error.status : 500,
},
);
}
-39
View File
@@ -1,39 +0,0 @@
import { LoaderFunctionArgs } from 'react-router';
import { hp_getSingleton, hp_getSingletonUnsafe } from '~server/context/global';
export async function loader({ request }: LoaderFunctionArgs) {
const data = hp_getSingletonUnsafe('ws_agent_data');
if (!data) {
return new Response(JSON.stringify({ error: 'Agent data unavailable' }), {
status: 400,
headers: {
'Content-Type': 'application/json',
},
});
}
const qp = new URLSearchParams(request.url.split('?')[1]);
const nodeIds = qp.get('node_ids')?.split(',');
if (!nodeIds) {
return new Response(JSON.stringify({ error: 'No node IDs provided' }), {
status: 400,
headers: {
'Content-Type': 'application/json',
},
});
}
const entries = data.toJSON();
const missing = nodeIds.filter((nodeID) => !entries[nodeID]);
if (missing.length > 0) {
const requestCall = hp_getSingleton('ws_fetch_data');
requestCall(missing);
}
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
},
});
}
+36 -37
View File
@@ -8,50 +8,42 @@ import Button from '~/components/Button';
import Card from '~/components/Card';
import Code from '~/components/Code';
import Input from '~/components/Input';
import type { LoadContext } from '~/server';
import type { Key } from '~/types';
import { pull } from '~/utils/headscale';
import { commitSession, getSession } from '~/utils/sessions.server';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/machines', {
headers: {
'Set-Cookie': await commitSession(session),
},
});
}
const context = hp_getConfig();
const disableApiKeyLogin = context.oidc?.disable_api_key_login;
let oidc = false;
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
try {
// Only set if OIDC is properly enabled anyways
hp_getSingleton('oidc_client');
oidc = true;
if (disableApiKeyLogin) {
return redirect('/oidc/start');
const session = await context.sessions.auth(request);
if (session.has('api_key')) {
return redirect('/machines');
}
} catch {}
const disableApiKeyLogin = context.config.oidc?.disable_api_key_login;
if (context.oidc && disableApiKeyLogin) {
return redirect('/oidc/start');
}
return {
oidc,
apiKey: !disableApiKeyLogin,
oidc: context.oidc,
disableApiKeyLogin,
};
}
export async function action({ request }: ActionFunctionArgs) {
export async function action({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
const formData = await request.formData();
const oidcStart = formData.get('oidc-start');
const session = await getSession(request.headers.get('Cookie'));
const session = await context.sessions.getOrCreate(request);
if (oidcStart) {
const context = hp_getConfig();
if (!context.oidc) {
throw new Error('An invalid OIDC configuration was provided');
throw new Error('OIDC is not enabled');
}
return redirect('/oidc/start');
@@ -61,17 +53,24 @@ export async function action({ request }: ActionFunctionArgs) {
// Test the API key
try {
const apiKeys = await pull<{ apiKeys: Key[] }>('v1/apikey', apiKey);
const apiKeys = await context.client.get<{ apiKeys: Key[] }>(
'v1/apikey',
apiKey,
);
const key = apiKeys.apiKeys.find((k) => apiKey.startsWith(k.prefix));
if (!key) {
throw new Error('Invalid API key');
return {
error: 'Invalid API key',
};
}
const expiry = new Date(key.expiration);
const expiresIn = expiry.getTime() - Date.now();
const expiresDays = Math.round(expiresIn / 1000 / 60 / 60 / 24);
session.set('hsApiKey', apiKey);
session.set('state', 'auth');
session.set('api_key', apiKey);
session.set('user', {
subject: 'unknown-non-oauth',
name: key.prefix,
@@ -80,7 +79,7 @@ export async function action({ request }: ActionFunctionArgs) {
return redirect('/machines', {
headers: {
'Set-Cookie': await commitSession(session, {
'Set-Cookie': await context.sessions.commit(session, {
maxAge: expiresIn,
}),
},
@@ -100,7 +99,7 @@ export default function Page() {
<div className="flex min-h-screen items-center justify-center">
<Card className="max-w-sm m-4 sm:m-0" variant="raised">
<Card.Title>Welcome to Headplane</Card.Title>
{data.apiKey ? (
{!data.disableApiKeyLogin ? (
<Form method="post">
<Card.Text>
Enter an API key to authenticate with Headplane. You can generate
@@ -125,9 +124,9 @@ export default function Page() {
</Button>
</Form>
) : undefined}
{data.oidc === true ? (
{data.oidc ? (
<Form method="POST">
{!data.apiKey ? (
{data.disableApiKeyLogin ? (
<Card.Text className="mb-6">
Sign in with your authentication provider to continue. Your
administrator has disabled API key login.
@@ -137,7 +136,7 @@ export default function Page() {
<input type="hidden" name="oidc-start" value="true" />
<Button
className="w-full mt-2"
variant={data.apiKey ? 'light' : 'heavy'}
variant={data.disableApiKeyLogin ? 'heavy' : 'light'}
type="submit"
>
Single Sign-On
+11 -4
View File
@@ -1,15 +1,22 @@
import { type ActionFunctionArgs, redirect } from 'react-router';
import { destroySession, getSession } from '~/utils/sessions.server';
import type { LoadContext } from '~/server';
export async function loader() {
return redirect('/machines');
}
export async function action({ request }: ActionFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
export async function action({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
if (!session.has('api_key')) {
return redirect('/login');
}
return redirect('/login', {
headers: {
'Set-Cookie': await destroySession(session),
'Set-Cookie': await context.sessions.destroy(session),
},
});
}
+25 -32
View File
@@ -1,68 +1,61 @@
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { type LoaderFunctionArgs, Session, redirect } from 'react-router';
import type { LoadContext } from '~/server';
import type { AuthSession, OidcFlowSession } from '~/server/web/sessions';
import { finishAuthFlow, formatError } from '~/utils/oidc';
import { send } from '~/utils/res';
import { commitSession, getSession } from '~/utils/sessions.server';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
export async function loader({ request }: LoaderFunctionArgs) {
const { oidc } = hp_getConfig();
try {
if (!oidc) {
throw new Error('OIDC is not enabled');
}
hp_getSingleton('oidc_client');
} catch {
return send({ error: 'OIDC is not enabled' }, { status: 400 });
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
if (!context.oidc) {
throw new Error('OIDC is not enabled');
}
// Check if we have 0 query parameters
const url = new URL(request.url);
if (url.searchParams.toString().length === 0) {
return redirect('/machines');
return redirect('/login');
}
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
return redirect('/machines');
const session = await context.sessions.getOrCreate<OidcFlowSession>(request);
if (session.get('state') !== 'flow') {
return redirect('/login'); // Haven't started an OIDC flow
}
const codeVerifier = session.get('oidc_code_verif');
const state = session.get('oidc_state');
const nonce = session.get('oidc_nonce');
const redirectUri = session.get('oidc_redirect_uri');
if (!codeVerifier || !state || !nonce || !redirectUri) {
const payload = session.get('oidc')!;
const { code_verifier, state, nonce, redirect_uri } = payload;
if (!code_verifier || !state || !nonce || !redirect_uri) {
return send({ error: 'Missing OIDC state' }, { status: 400 });
}
// Reconstruct the redirect URI using the query parameters
// and the one we saved in the session
const flowRedirectUri = new URL(redirectUri);
const flowRedirectUri = new URL(redirect_uri);
flowRedirectUri.search = url.search;
const flowOptions = {
redirect_uri: flowRedirectUri.toString(),
codeVerifier,
code_verifier,
state,
nonce: nonce === '<none>' ? undefined : nonce,
};
try {
const user = await finishAuthFlow(oidc, flowOptions);
session.set('user', user);
session.unset('oidc_code_verif');
session.unset('oidc_state');
session.unset('oidc_nonce');
const user = await finishAuthFlow(context.oidc, flowOptions);
session.unset('oidc');
const userSession = session as Session<AuthSession>;
// TODO: This is breaking, to stop the "over-generation" of API
// keys because they are currently non-deletable in the headscale
// database. Look at this in the future once we have a solution
// or we have permissioned API keys.
session.set('hsApiKey', oidc.headscale_api_key);
userSession.set('user', user);
userSession.set('api_key', context.config.oidc?.headscale_api_key!);
userSession.set('state', 'auth');
return redirect('/machines', {
headers: {
'Set-Cookie': await commitSession(session),
'Set-Cookie': await context.sessions.commit(userSession),
},
});
} catch (error) {
+28 -23
View File
@@ -1,37 +1,42 @@
import { type LoaderFunctionArgs, redirect } from 'react-router';
import { type LoaderFunctionArgs, Session, redirect } from 'react-router';
import type { LoadContext } from '~/server';
import { AuthSession, OidcFlowSession } from '~/server/web/sessions';
import { beginAuthFlow, getRedirectUri } from '~/utils/oidc';
import { send } from '~/utils/res';
import { commitSession, getSession } from '~/utils/sessions.server';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (session.has('hsApiKey')) {
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.getOrCreate<OidcFlowSession>(request);
if ((session as Session<AuthSession>).has('api_key')) {
return redirect('/machines');
}
const { oidc } = hp_getConfig();
try {
if (!oidc) {
throw new Error('OIDC is not enabled');
}
hp_getSingleton('oidc_client');
} catch {
return send({ error: 'OIDC is not enabled' }, { status: 400 });
if (!context.oidc) {
throw new Error('OIDC is not enabled');
}
const redirectUri = oidc.redirect_uri ?? getRedirectUri(request);
const data = await beginAuthFlow(oidc, redirectUri);
session.set('oidc_code_verif', data.codeVerifier);
session.set('oidc_state', data.state);
session.set('oidc_nonce', data.nonce);
session.set('oidc_redirect_uri', redirectUri);
const redirectUri =
context.config.oidc?.redirect_uri ?? getRedirectUri(request);
const data = await beginAuthFlow(
context.oidc,
redirectUri,
// We can't get here without the OIDC config being defined
context.config.oidc!.token_endpoint_auth_method,
);
session.set('state', 'flow');
session.set('oidc', {
state: data.state,
nonce: data.nonce,
code_verifier: data.codeVerifier,
redirect_uri: redirectUri,
});
return redirect(data.url, {
status: 302,
headers: {
'Set-Cookie': await commitSession(session),
'Set-Cookie': await context.sessions.commit(session),
},
});
}
+38 -67
View File
@@ -1,16 +1,12 @@
import { ActionFunctionArgs, data } from 'react-router';
import { hs_getConfig, hs_patchConfig } from '~/utils/config/loader';
import { LoadContext } from '~/server';
import { hp_getIntegration } from '~/utils/integration/loader';
import { auth } from '~/utils/sessions.server';
export async function dnsAction({ request }: ActionFunctionArgs) {
const session = await auth(request);
if (!session) {
return data({ success: false }, 401);
}
const { mode } = hs_getConfig();
if (mode !== 'rw') {
export async function dnsAction({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
if (!context.hs.writable()) {
return data({ success: false }, 403);
}
@@ -22,33 +18,33 @@ export async function dnsAction({ request }: ActionFunctionArgs) {
switch (action) {
case 'rename_tailnet':
return renameTailnet(formData);
return renameTailnet(formData, context);
case 'toggle_magic':
return toggleMagic(formData);
return toggleMagic(formData, context);
case 'remove_ns':
return removeNs(formData);
return removeNs(formData, context);
case 'add_ns':
return addNs(formData);
return addNs(formData, context);
case 'remove_domain':
return removeDomain(formData);
return removeDomain(formData, context);
case 'add_domain':
return addDomain(formData);
return addDomain(formData, context);
case 'remove_record':
return removeRecord(formData);
return removeRecord(formData, context);
case 'add_record':
return addRecord(formData);
return addRecord(formData, context);
default:
return data({ success: false }, 400);
}
}
async function renameTailnet(formData: FormData) {
async function renameTailnet(formData: FormData, context: LoadContext) {
const newName = formData.get('new_name')?.toString();
if (!newName) {
return data({ success: false }, 400);
}
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.base_domain',
value: newName,
@@ -58,13 +54,13 @@ async function renameTailnet(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function toggleMagic(formData: FormData) {
async function toggleMagic(formData: FormData, context: LoadContext) {
const newState = formData.get('new_state')?.toString();
if (!newState) {
return data({ success: false }, 400);
}
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.magic_dns',
value: newState === 'enabled',
@@ -74,7 +70,8 @@ async function toggleMagic(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function removeNs(formData: FormData) {
async function removeNs(formData: FormData, context: LoadContext) {
const config = context.hs.c!;
const ns = formData.get('ns')?.toString();
const splitName = formData.get('split_name')?.toString();
@@ -82,15 +79,10 @@ async function removeNs(formData: FormData) {
return data({ success: false }, 400);
}
const { config, mode } = hs_getConfig();
if (mode !== 'rw') {
return data({ success: false }, 403);
}
if (splitName === 'global') {
const servers = config.dns.nameservers.global.filter((i) => i !== ns);
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.nameservers.global',
value: servers,
@@ -100,7 +92,7 @@ async function removeNs(formData: FormData) {
const splits = config.dns.nameservers.split;
const servers = splits[splitName].filter((i) => i !== ns);
await hs_patchConfig([
await context.hs.patch([
{
path: `dns.nameservers.split."${splitName}"`,
value: servers,
@@ -111,7 +103,8 @@ async function removeNs(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function addNs(formData: FormData) {
async function addNs(formData: FormData, context: LoadContext) {
const config = context.hs.c!;
const ns = formData.get('ns')?.toString();
const splitName = formData.get('split_name')?.toString();
@@ -119,16 +112,11 @@ async function addNs(formData: FormData) {
return data({ success: false }, 400);
}
const { config, mode } = hs_getConfig();
if (mode !== 'rw') {
return data({ success: false }, 403);
}
if (splitName === 'global') {
const servers = config.dns.nameservers.global;
servers.push(ns);
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.nameservers.global',
value: servers,
@@ -139,7 +127,7 @@ async function addNs(formData: FormData) {
const servers = splits[splitName] ?? [];
servers.push(ns);
await hs_patchConfig([
await context.hs.patch([
{
path: `dns.nameservers.split."${splitName}"`,
value: servers,
@@ -150,20 +138,15 @@ async function addNs(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function removeDomain(formData: FormData) {
async function removeDomain(formData: FormData, context: LoadContext) {
const config = context.hs.c!;
const domain = formData.get('domain')?.toString();
if (!domain) {
return data({ success: false }, 400);
}
const { config, mode } = hs_getConfig();
if (mode !== 'rw') {
return data({ success: false }, 403);
}
const domains = config.dns.search_domains.filter((i) => i !== domain);
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.search_domains',
value: domains,
@@ -173,21 +156,17 @@ async function removeDomain(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function addDomain(formData: FormData) {
async function addDomain(formData: FormData, context: LoadContext) {
const config = context.hs.c!;
const domain = formData.get('domain')?.toString();
if (!domain) {
return data({ success: false }, 400);
}
const { config, mode } = hs_getConfig();
if (mode !== 'rw') {
return data({ success: false }, 403);
}
const domains = config.dns.search_domains;
domains.push(domain);
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.search_domains',
value: domains,
@@ -197,7 +176,8 @@ async function addDomain(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function removeRecord(formData: FormData) {
async function removeRecord(formData: FormData, context: LoadContext) {
const config = context.hs.c!;
const recordName = formData.get('record_name')?.toString();
const recordType = formData.get('record_type')?.toString();
@@ -205,16 +185,11 @@ async function removeRecord(formData: FormData) {
return data({ success: false }, 400);
}
const { config, mode } = hs_getConfig();
if (mode !== 'rw') {
return data({ success: false }, 403);
}
const records = config.dns.extra_records.filter(
(i) => i.name !== recordName || i.type !== recordType,
);
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.extra_records',
value: records,
@@ -224,7 +199,8 @@ async function removeRecord(formData: FormData) {
await hp_getIntegration()?.onConfigChange();
}
async function addRecord(formData: FormData) {
async function addRecord(formData: FormData, context: LoadContext) {
const config = context.hs.c!;
const recordName = formData.get('record_name')?.toString();
const recordType = formData.get('record_type')?.toString();
const recordValue = formData.get('record_value')?.toString();
@@ -233,15 +209,10 @@ async function addRecord(formData: FormData) {
return data({ success: false }, 400);
}
const { config, mode } = hs_getConfig();
if (mode !== 'rw') {
return data({ success: false }, 403);
}
const records = config.dns.extra_records;
records.push({ name: recordName, type: recordType, value: recordValue });
await hs_patchConfig([
await context.hs.patch([
{
path: 'dns.extra_records',
value: records,
+8 -8
View File
@@ -1,8 +1,8 @@
import type { ActionFunctionArgs } from 'react-router';
import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router';
import { useLoaderData } from 'react-router';
import Code from '~/components/Code';
import Notice from '~/components/Notice';
import { hs_getConfig } from '~/utils/config/loader';
import type { LoadContext } from '~/server';
import ManageDomains from './components/manage-domains';
import ManageNS from './components/manage-ns';
import ManageRecords from './components/manage-records';
@@ -11,12 +11,12 @@ import ToggleMagic from './components/toggle-magic';
import { dnsAction } from './dns-actions';
// We do not want to expose every config value
export async function loader() {
const { config, mode } = hs_getConfig();
if (mode === 'no') {
export async function loader({ context }: LoaderFunctionArgs<LoadContext>) {
if (!context.hs.readable()) {
throw new Error('No configuration is available');
}
const config = context.hs.c!;
const dns = {
prefixes: config.prefixes,
magicDns: config.dns.magic_dns,
@@ -29,7 +29,7 @@ export async function loader() {
return {
...dns,
mode,
writable: context.hs.writable(),
};
}
@@ -46,11 +46,11 @@ export default function Page() {
}
allNs.global = data.nameservers;
const isDisabled = data.mode !== 'rw';
const isDisabled = data.writable === false;
return (
<div className="flex flex-col gap-16 max-w-screen-lg">
{data.mode === 'rw' ? undefined : (
{data.writable ? undefined : (
<Notice>
The Headscale configuration is read-only. You cannot make changes to
the configuration
+41 -28
View File
@@ -1,20 +1,14 @@
import type { ActionFunctionArgs } from 'react-router';
import { del, post } from '~/utils/headscale';
import type { LoadContext } from '~/server';
import log from '~/utils/log';
import { send } from '~/utils/res';
import { getSession } from '~/utils/sessions.server';
import log from '~server/utils/log';
export async function menuAction(request: ActionFunctionArgs['request']) {
const session = await getSession(request.headers.get('Cookie'));
if (!session.has('hsApiKey')) {
return send(
{ message: 'Unauthorized' },
{
status: 401,
},
);
}
// TODO: Turn this into the same thing as dns-actions like machine-actions!!!
export async function menuAction({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const data = await request.formData();
if (!data.has('_method') || !data.has('id')) {
return send(
@@ -30,12 +24,15 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
switch (method) {
case 'delete': {
await del(`v1/node/${id}`, session.get('hsApiKey')!);
await context.client.delete(`v1/node/${id}`, session.get('api_key')!);
return { message: 'Machine removed' };
}
case 'expire': {
await post(`v1/node/${id}/expire`, session.get('hsApiKey')!);
await context.client.post(
`v1/node/${id}/expire`,
session.get('api_key')!,
);
return { message: 'Machine expired' };
}
@@ -50,8 +47,10 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
}
const name = String(data.get('name'));
await post(`v1/node/${id}/rename/${name}`, session.get('hsApiKey')!);
await context.client.post(
`v1/node/${id}/rename/${name}`,
session.get('api_key')!,
);
return { message: 'Machine renamed' };
}
@@ -69,7 +68,10 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
const enabled = data.get('enabled') === 'true';
const postfix = enabled ? 'enable' : 'disable';
await post(`v1/routes/${route}/${postfix}`, session.get('hsApiKey')!);
await context.client.post(
`v1/routes/${route}/${postfix}`,
session.get('api_key')!,
);
return { message: 'Route updated' };
}
@@ -89,7 +91,10 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
await Promise.all(
routes.map(async (route) => {
await post(`v1/routes/${route}/${postfix}`, session.get('hsApiKey')!);
await context.client.post(
`v1/routes/${route}/${postfix}`,
session.get('api_key')!,
);
}),
);
@@ -109,9 +114,13 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
const to = String(data.get('to'));
try {
await post(`v1/node/${id}/user`, session.get('hsApiKey')!, {
user: to,
});
await context.client.post(
`v1/node/${id}/user`,
session.get('api_key')!,
{
user: to,
},
);
return { message: `Moved node ${id} to ${to}` };
} catch (error) {
@@ -134,13 +143,17 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
.filter((tag) => tag.trim() !== '') ?? [];
try {
await post(`v1/node/${id}/tags`, session.get('hsApiKey')!, {
tags,
});
await context.client.post(
`v1/node/${id}/tags`,
session.get('api_key')!,
{
tags,
},
);
return { message: 'Tags updated' };
} catch (error) {
log.debug('APIC', 'Failed to update tags: %s', error);
log.debug('api', 'Failed to update tags: %s', error);
return send(
{ message: 'Failed to update tags' },
{
@@ -178,7 +191,7 @@ export async function menuAction(request: ActionFunctionArgs['request']) {
qp.append('key', key);
const url = `v1/node/register?${qp.toString()}`;
await post(url, session.get('hsApiKey')!, {
await context.client.post(url, session.get('api_key')!, {
user,
key,
});
+16 -13
View File
@@ -96,7 +96,7 @@ export default function MachineRow({
return (
<tr
key={machine.id}
className="'group hover:bg-headplane-50 dark:hover:bg-headplane-950"
className="group hover:bg-headplane-50 dark:hover:bg-headplane-950"
>
<td className="pl-0.5 py-2 focus-within:ring">
<Link
@@ -152,18 +152,21 @@ export default function MachineRow({
</Menu>
</div>
</td>
<td className="py-2">
{stats !== undefined ? (
<>
<p className="leading-snug">{hinfo.getTSVersion(stats)}</p>
<p className="text-sm opacity-50 max-w-48 truncate">
{hinfo.getOSInfo(stats)}
</p>
</>
) : (
<p className="text-sm opacity-50">Unknown</p>
)}
</td>
{/* We pass undefined when agents are not enabled */}
{isAgent !== undefined ? (
<td className="py-2">
{stats !== undefined ? (
<>
<p className="leading-snug">{hinfo.getTSVersion(stats)}</p>
<p className="text-sm opacity-50 max-w-48 truncate">
{hinfo.getOSInfo(stats)}
</p>
</>
) : (
<p className="text-sm opacity-50">Unknown</p>
)}
</td>
) : undefined}
<td className="py-2">
<span
className={cn(
+25 -16
View File
@@ -9,35 +9,40 @@ import Chip from '~/components/Chip';
import Link from '~/components/Link';
import StatusCircle from '~/components/StatusCircle';
import Tooltip from '~/components/Tooltip';
import type { LoadContext } from '~/server';
import type { Machine, Route, User } from '~/types';
import cn from '~/utils/cn';
import { hs_getConfig } from '~/utils/config/loader';
import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import { hp_getSingleton } from '~server/context/global';
import { menuAction } from './action';
import MenuOptions from './components/menu';
import Routes from './dialogs/routes';
export async function loader({ request, params }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
export async function loader({
request,
params,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
if (!params.id) {
throw new Error('No machine ID provided');
}
const { mode, config } = hs_getConfig();
let magic: string | undefined;
if (mode !== 'no') {
if (config.dns.magic_dns) {
magic = config.dns.base_domain;
if (context.hs.readable()) {
if (context.hs.c?.dns.magic_dns) {
magic = context.hs.c.dns.base_domain;
}
}
const [machine, routes, users] = await Promise.all([
pull<{ node: Machine }>(`v1/node/${params.id}`, session.get('hsApiKey')!),
pull<{ routes: Route[] }>('v1/routes', session.get('hsApiKey')!),
pull<{ users: User[] }>('v1/user', session.get('hsApiKey')!),
context.client.get<{ node: Machine }>(
`v1/node/${params.id}`,
session.get('api_key')!,
),
context.client.get<{ routes: Route[] }>(
'v1/routes',
session.get('api_key')!,
),
context.client.get<{ users: User[] }>('v1/user', session.get('api_key')!),
]);
return {
@@ -45,11 +50,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
routes: routes.routes.filter((route) => route.node.id === params.id),
users: users.users,
magic,
agent: [...hp_getSingleton('ws_agents').keys()].includes(machine.node.id),
// TODO: Fix agent
agent: false,
// agent: [...(hp_getSingletonUnsafe('ws_agents') ?? []).keys()].includes(
// machine.node.id,
// ),
};
}
export async function action({ request }: ActionFunctionArgs) {
export async function action(request: ActionFunctionArgs) {
return menuAction(request);
}
+32 -27
View File
@@ -1,38 +1,38 @@
import { InfoIcon } from '@primer/octicons-react';
import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router';
import { useLoaderData } from 'react-router';
import Code from '~/components/Code';
import { ErrorPopup } from '~/components/Error';
import Link from '~/components/Link';
import Tooltip from '~/components/Tooltip';
import type { LoadContext } from '~/server';
import type { Machine, Route, User } from '~/types';
import cn from '~/utils/cn';
import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import Tooltip from '~/components/Tooltip';
import { hs_getConfig } from '~/utils/config/loader';
import useAgent from '~/utils/useAgent';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
import { menuAction } from './action';
import MachineRow from './components/machine';
import NewMachine from './dialogs/new';
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const [machines, routes, users] = await Promise.all([
pull<{ nodes: Machine[] }>('v1/node', session.get('hsApiKey')!),
pull<{ routes: Route[] }>('v1/routes', session.get('hsApiKey')!),
pull<{ users: User[] }>('v1/user', session.get('hsApiKey')!),
context.client.get<{ nodes: Machine[] }>(
'v1/node',
session.get('api_key')!,
),
context.client.get<{ routes: Route[] }>(
'v1/routes',
session.get('api_key')!,
),
context.client.get<{ users: User[] }>('v1/user', session.get('api_key')!),
]);
const context = hp_getConfig();
const { mode, config } = hs_getConfig();
let magic: string | undefined;
if (mode !== 'no') {
if (config.dns.magic_dns) {
magic = config.dns.base_domain;
if (context.hs.readable()) {
if (context.hs.c?.dns.magic_dns) {
magic = context.hs.c.dns.base_domain;
}
}
@@ -41,19 +41,19 @@ export async function loader({ request }: LoaderFunctionArgs) {
routes: routes.routes,
users: users.users,
magic,
server: context.headscale.url,
publicServer: context.headscale.public_url,
agents: [...hp_getSingleton('ws_agents').keys()],
server: context.config.headscale.url,
publicServer: context.config.headscale.public_url,
agents: context.agents?.tailnetIDs(),
stats: context.agents?.lookup(machines.nodes.map((node) => node.nodeKey)),
};
}
export async function action({ request }: ActionFunctionArgs) {
export async function action(request: ActionFunctionArgs) {
return menuAction(request);
}
export default function Page() {
const data = useLoaderData<typeof loader>();
const { data: stats } = useAgent(data.nodes.map((node) => node.nodeKey));
return (
<>
@@ -97,7 +97,10 @@ export default function Page() {
) : undefined}
</div>
</th>
<th className="uppercase text-xs font-bold pb-2">Version</th>
{/* We only want to show the version column if there are agents */}
{data.agents !== undefined ? (
<th className="uppercase text-xs font-bold pb-2">Version</th>
) : undefined}
<th className="uppercase text-xs font-bold pb-2">Last Seen</th>
</tr>
</thead>
@@ -116,8 +119,10 @@ export default function Page() {
)}
users={data.users}
magic={data.magic}
stats={stats?.[machine.nodeKey]}
isAgent={data.agents.includes(machine.id)}
// If we pass undefined, the column will not be rendered
// This is useful for when there are no agents configured
isAgent={data.agents?.includes(machine.id)}
stats={data.stats?.[machine.nodeKey]}
/>
))}
</tbody>
+20 -26
View File
@@ -5,30 +5,30 @@ import { Link as RemixLink } from 'react-router';
import Link from '~/components/Link';
import Select from '~/components/Select';
import TableList from '~/components/TableList';
import type { LoadContext } from '~/server';
import type { PreAuthKey, User } from '~/types';
import { post, pull } from '~/utils/headscale';
import { send } from '~/utils/res';
import { getSession } from '~/utils/sessions.server';
import { hp_getConfig } from '~server/context/global';
import AuthKeyRow from './components/key';
import AddPreAuthKey from './dialogs/new';
export async function loader({ request }: LoaderFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
const users = await pull<{ users: User[] }>(
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const users = await context.client.get<{ users: User[] }>(
'v1/user',
session.get('hsApiKey')!,
session.get('api_key')!,
);
const context = hp_getConfig();
const preAuthKeys = await Promise.all(
users.users.map((user) => {
const qp = new URLSearchParams();
qp.set('user', user.name);
return pull<{ preAuthKeys: PreAuthKey[] }>(
return context.client.get<{ preAuthKeys: PreAuthKey[] }>(
`v1/preauthkey?${qp.toString()}`,
session.get('hsApiKey')!,
session.get('api_key')!,
);
}),
);
@@ -36,21 +36,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
return {
keys: preAuthKeys.flatMap((keys) => keys.preAuthKeys),
users: users.users,
server: context.headscale.public_url ?? context.headscale.url,
server: context.config.headscale.public_url ?? context.config.headscale.url,
};
}
export async function action({ request }: ActionFunctionArgs) {
const session = await getSession(request.headers.get('Cookie'));
if (!session.has('hsApiKey')) {
return send(
{ message: 'Unauthorized' },
{
status: 401,
},
);
}
export async function action({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const data = await request.formData();
// Expiring a pre-auth key
@@ -67,9 +61,9 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
await post<{ preAuthKey: PreAuthKey }>(
await context.client.post<{ preAuthKey: PreAuthKey }>(
'v1/preauthkey/expire',
session.get('hsApiKey')!,
session.get('api_key')!,
{
user: user,
key: key,
@@ -101,9 +95,9 @@ export async function action({ request }: ActionFunctionArgs) {
const date = new Date();
date.setDate(date.getDate() + day);
const key = await post<{ preAuthKey: PreAuthKey }>(
const key = await context.client.post<{ preAuthKey: PreAuthKey }>(
'v1/preauthkey',
session.get('hsApiKey')!,
session.get('api_key')!,
{
user: user,
ephemeral: ephemeral === 'on',
@@ -1,7 +1,7 @@
import { Building2, House, Key } from 'lucide-react';
import Card from '~/components/Card';
import Link from '~/components/Link';
import type { HeadplaneConfig } from '~server/context/parser';
import type { HeadplaneConfig } from '~/server/config/schema';
import CreateUser from '../dialogs/create-user';
interface Props {
+62
View File
@@ -0,0 +1,62 @@
import { Ellipsis } from 'lucide-react';
import { useState } from 'react';
import Menu from '~/components/Menu';
import type { Machine, User } from '~/types';
import cn from '~/utils/cn';
import Delete from '../dialogs/delete-user';
import Rename from '../dialogs/rename-user';
interface MenuProps {
user: User & {
machines: Machine[];
};
}
type Modal = 'rename' | 'delete' | null;
export default function UserMenu({ user }: MenuProps) {
const [modal, setModal] = useState<Modal>(null);
return (
<>
{modal === 'rename' && (
<Rename
user={user}
isOpen={modal === 'rename'}
setIsOpen={(isOpen) => {
if (!isOpen) setModal(null);
}}
/>
)}
{modal === 'delete' && (
<Delete
user={user}
isOpen={modal === 'delete'}
setIsOpen={(isOpen) => {
if (!isOpen) setModal(null);
}}
/>
)}
<Menu>
<Menu.IconButton
label="Machine Options"
className={cn(
'py-0.5 w-10 bg-transparent border-transparent',
'border group-hover:border-headplane-200',
'dark:group-hover:border-headplane-700',
)}
>
<Ellipsis className="h-5" />
</Menu.IconButton>
<Menu.Panel onAction={(key) => setModal(key as Modal)}>
<Menu.Section>
<Menu.Item key="rename">Rename user</Menu.Item>
<Menu.Item key="delete" textValue="Delete">
<p className="text-red-500 dark:text-red-400">Delete</p>
</Menu.Item>
</Menu.Section>
</Menu.Panel>
</Menu>
</>
);
}
+90
View File
@@ -0,0 +1,90 @@
import { CircleUser } from 'lucide-react';
import StatusCircle from '~/components/StatusCircle';
import { Machine, User } from '~/types';
import cn from '~/utils/cn';
import MenuOptions from './menu';
interface UserRowProps {
role: string;
user: User & { machines: Machine[] };
}
export default function UserRow({ user, role }: UserRowProps) {
const isOnline = user.machines.some((machine) => machine.online);
const lastSeen = user.machines.reduce(
(acc, machine) => Math.max(acc, new Date(machine.lastSeen).getTime()),
0,
);
return (
<tr
key={user.id}
className="group hover:bg-headplane-50 dark:hover:bg-headplane-950"
>
<td className="pl-0.5 py-2">
<div className="flex items-center">
{user.profilePicUrl ? (
<img
src={user.profilePicUrl}
alt={user.name}
className="w-10 h-10 rounded-full"
/>
) : (
<CircleUser className="w-10 h-10" />
)}
<div className="ml-4">
<p className={cn('font-semibold leading-snug')}>{user.name}</p>
<p className="text-sm opacity-50">{user.email}</p>
</div>
</div>
</td>
<td className="pl-0.5 py-2">
<p>{mapRoleToName(role)}</p>
</td>
<td className="pl-0.5 py-2">
<p className="text-sm text-headplane-600 dark:text-headplane-300">
{new Date(user.createdAt).toLocaleDateString()}
</p>
</td>
<td className="pl-0.5 py-2">
<span
className={cn(
'flex items-center gap-x-1 text-sm',
'text-headplane-600 dark:text-headplane-300',
)}
>
<StatusCircle isOnline={isOnline} className="w-4 h-4" />
<p>{isOnline ? 'Connected' : new Date(lastSeen).toLocaleString()}</p>
</span>
</td>
<td className="py-2 pr-0.5">
<MenuOptions user={user} />
</td>
</tr>
);
}
function mapRoleToName(role: string) {
switch (role) {
case 'no-oidc':
return <p className="opacity-50">Unmanaged</p>;
case 'invalid-oidc':
return <p className="opacity-50">Invalid</p>;
case 'no-role':
return <p className="opacity-50">Unregistered</p>;
case 'owner':
return 'Owner';
case 'admin':
return 'Admin';
case 'network_admin':
return 'Network Admin';
case 'it_admin':
return 'IT Admin';
case 'auditor':
return 'Auditor';
case 'member':
return 'Member';
default:
return 'Unknown';
}
}
+26 -15
View File
@@ -1,27 +1,38 @@
import { X } from 'lucide-react';
import Dialog from '~/components/Dialog';
import { User } from '~/types';
import { Machine, User } from '~/types';
interface Props {
user: User;
interface DeleteProps {
user: User & { machines: Machine[] };
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}
// TODO: Warn that OIDC users will be recreated on next login
export default function DeleteUser({ user }: Props) {
export default function DeleteUser({ user, isOpen, setIsOpen }: DeleteProps) {
const name =
(user.displayName?.length ?? 0) > 0 ? user.displayName : user.name;
return (
<Dialog>
<Dialog.IconButton label={`Delete ${name}`}>
<X className="p-0.5" />
</Dialog.IconButton>
<Dialog.Panel>
<Dialog isOpen={isOpen} onOpenChange={setIsOpen}>
<Dialog.Panel
variant={user.machines.length > 0 ? 'unactionable' : 'normal'}
>
<Dialog.Title>Delete {name}?</Dialog.Title>
<Dialog.Text className="mb-6">
Are you sure you want to delete {name}? A deleted user cannot be
recovered.
</Dialog.Text>
{user.machines.length > 0 ? (
<Dialog.Text className="mb-6">
Users cannot be deleted if they have machines. Please delete or
re-assign their machines to other users before proceeding.
</Dialog.Text>
) : (
<Dialog.Text className="mb-6">
Deleted users cannot be recovered.
{user.provider === 'oidc' && (
<p className="mt-4 text-sm text-headplane-600 dark:text-headplane-300">
Since this user is authenticated via an external provider, they
will be recreated if they sign in again.
</p>
)}
</Dialog.Text>
)}
<input type="hidden" name="action_id" value="delete_user" />
<input type="hidden" name="user_id" value={user.id} />
</Dialog.Panel>
+5 -7
View File
@@ -1,19 +1,17 @@
import { Pencil } from 'lucide-react';
import Dialog from '~/components/Dialog';
import Input from '~/components/Input';
import { User } from '~/types';
interface Props {
interface RenameProps {
user: User;
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}
// TODO: Server side validation before submitting
export default function RenameUser({ user }: Props) {
export default function RenameUser({ user, isOpen, setIsOpen }: RenameProps) {
return (
<Dialog>
<Dialog.IconButton label={`Rename ${user.name}`}>
<Pencil className="p-1" />
</Dialog.IconButton>
<Dialog isOpen={isOpen} onOpenChange={setIsOpen}>
<Dialog.Panel>
<Dialog.Title>Rename {user.name}?</Dialog.Title>
<Dialog.Text className="mb-6">
+341
View File
@@ -0,0 +1,341 @@
import { useEffect } from 'react';
import { GrApple } from 'react-icons/gr';
import { ImFinder } from 'react-icons/im';
import { MdAndroid } from 'react-icons/md';
import { PiTerminalFill, PiWindowsLogoFill } from 'react-icons/pi';
import {
LoaderFunctionArgs,
NavLink,
redirect,
useLoaderData,
} from 'react-router';
import Button from '~/components/Button';
import Card from '~/components/Card';
import Code from '~/components/Code';
import Link from '~/components/Link';
import Options from '~/components/Options';
import StatusCircle from '~/components/StatusCircle';
import { LoadContext } from '~/server';
import { Machine } from '~/types';
import cn from '~/utils/cn';
import { useLiveData } from '~/utils/live-data';
import log from '~/utils/log';
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const user = session.get('user');
if (!user) {
return redirect('/login');
}
// Try to determine the OS split between Linux, Windows, macOS, iOS, and Android
// We need to convert this to a known value to return it to the client so we can
// automatically tab to the correct download button.
const userAgent = request.headers.get('user-agent');
const os = userAgent?.match(/(Linux|Windows|Mac OS X|iPhone|iPad|Android)/);
let osValue = 'linux';
switch (os?.[0]) {
case 'Windows':
osValue = 'windows';
break;
case 'Mac OS X':
osValue = 'macos';
break;
case 'iPhone':
case 'iPad':
osValue = 'ios';
break;
case 'Android':
osValue = 'android';
break;
default:
osValue = 'linux';
break;
}
let firstMachine: Machine | undefined = undefined;
try {
const { nodes } = await context.client.get<{ nodes: Machine[] }>(
'v1/node',
session.get('api_key')!,
);
const node = nodes.find((n) => {
if (n.user.provider !== 'oidc') {
return false;
}
// For some reason, headscale makes providerID a url where the
// last component is the subject, so we need to strip that out
const subject = n.user.providerId?.split('/').pop();
if (!subject) {
return false;
}
const sessionUser = session.get('user');
if (!sessionUser) {
return false;
}
if (subject !== sessionUser.subject) {
return false;
}
return true;
});
firstMachine = node;
} catch (e) {
// If we cannot lookup nodes, we cannot proceed
log.debug('api', 'Failed to lookup nodes %o', e);
}
return {
user,
osValue,
firstMachine,
};
}
export default function Page() {
const { user, osValue, firstMachine } = useLoaderData<typeof loader>();
const { pause, resume } = useLiveData();
useEffect(() => {
if (firstMachine) {
pause();
} else {
resume();
}
}, [firstMachine]);
const subject = user.email ? (
<>
as <strong>{user.email}</strong>
</>
) : (
'with your OIDC provider'
);
return (
<div className="fixed w-full h-screen flex items-center px-4">
<div className="w-fit mx-auto grid grid-cols-1 md:grid-cols-2 gap-4 mb-24">
<Card variant="flat" className="max-w-lg">
<Card.Title className="mb-8">
Welcome!
<br />
Let's get set up
</Card.Title>
<Card.Text>
Install Tailscale and sign in {subject}. Once you sign in on a
device, it will be automatically added to your Headscale network.
</Card.Text>
<Options
defaultSelectedKey={osValue}
label="Download Selector"
className="my-4"
>
<Options.Item
key="linux"
title={
<div className="flex items-center gap-1">
<PiTerminalFill className="ml-1 w-4" />
<span>Linux</span>
</div>
}
>
<Button
variant="heavy"
className={cn(
'my-4 px-0 w-full pointer-events-none',
'hover:bg-initial focus:ring-0',
)}
>
<Code
isCopyable
className="bg-transparent pointer-events-auto mx-0"
>
curl -fsSL https://tailscale.com/install.sh | sh
</Code>
</Button>
<p className="text-end text-sm">
<Link
name="Linux installation script"
to="https://github.com/tailscale/tailscale/blob/main/scripts/installer.sh"
>
View script source
</Link>
</p>
</Options.Item>
<Options.Item
key="windows"
title={
<div className="flex items-center gap-1">
<PiWindowsLogoFill className="ml-1 w-4" />
<span>Windows</span>
</div>
}
>
<a
href="https://pkgs.tailscale.com/stable/tailscale-setup-latest.exe"
aria-label="Download for Windows"
target="_blank"
rel="noreferrer"
>
<Button variant="heavy" className="my-4 w-full">
Download for Windows
</Button>
</a>
<p className="text-sm text-headplane-600 dark:text-headplane-300 text-center">
Requires Windows 10 or later.
</p>
</Options.Item>
<Options.Item
key="macos"
title={
<div className="flex items-center gap-1">
<ImFinder className="ml-1 w-4" />
<span>macOS</span>
</div>
}
>
<a
href="https://pkgs.tailscale.com/stable/Tailscale-latest-macos.pkg"
aria-label="Download for macOS"
target="_blank"
rel="noreferrer"
>
<Button variant="heavy" className="my-4 w-full">
Download for macOS
</Button>
</a>
<p className="text-sm text-headplane-600 dark:text-headplane-300 text-center">
Requires macOS Big Sur 11.0 or later.
<br />
You can also download Tailscale on the{' '}
<Link
name="macOS App Store"
to="https://apps.apple.com/ca/app/tailscale/id1475387142"
>
macOS App Store
</Link>
{'.'}
</p>
</Options.Item>
<Options.Item
key="ios"
title={
<div className="flex items-center gap-1">
<GrApple className="ml-1 w-4" />
<span>iOS</span>
</div>
}
>
<a
href="https://apps.apple.com/us/app/tailscale/id1470499037"
aria-label="Download for iOS"
target="_blank"
rel="noreferrer"
>
<Button variant="heavy" className="my-4 w-full">
Download for iOS
</Button>
</a>
<p className="text-sm text-headplane-600 dark:text-headplane-300 text-center">
Requires iOS 15 or later.
</p>
</Options.Item>
<Options.Item
key="android"
title={
<div className="flex items-center gap-1">
<MdAndroid className="ml-1 w-4" />
<span>Android</span>
</div>
}
>
<a
href="https://play.google.com/store/apps/details?id=com.tailscale.ipn"
aria-label="Download for Android"
target="_blank"
rel="noreferrer"
>
<Button variant="heavy" className="my-4 w-full">
Download for Android
</Button>
</a>
<p className="text-sm text-headplane-600 dark:text-headplane-300 text-center">
Requires Android 8 or later.
</p>
</Options.Item>
</Options>
</Card>
<Card variant="flat">
{firstMachine ? (
<div className="flex flex-col justify-between h-full">
<Card.Title className="mb-8">
Success!
<br />
We found your first device
</Card.Title>
<div className="border border-headplane-100 dark:border-headplane-800 rounded-xl p-4">
<div className="flex items-start gap-4">
<StatusCircle
isOnline={firstMachine.online}
className="size-6 mt-3"
/>
<div>
<p className="font-semibold leading-snug">
{firstMachine.givenName}
</p>
<p className="text-sm font-mono opacity-50">
{firstMachine.name}
</p>
<div className="mt-6">
<p className="text-sm font-semibold">IP Addresses</p>
{firstMachine.ipAddresses.map((ip) => (
<p key={ip} className="text-xs font-mono opacity-50">
{ip}
</p>
))}
</div>
</div>
</div>
</div>
<NavLink to="/">
<Button variant="heavy" className="w-full">
Continue
</Button>
</NavLink>
</div>
) : (
<div className="flex flex-col items-center justify-center gap-4 h-full">
<span className="relative flex size-4">
<span
className={cn(
'absolute inline-flex h-full w-full',
'rounded-full opacity-75 animate-ping',
'bg-headplane-500',
)}
/>
<span
className={cn(
'relative inline-flex size-4 rounded-full',
'bg-headplane-400',
)}
/>
</span>
<p className="font-lg">Waiting for your first device...</p>
</div>
)}
</Card>
</div>
</div>
);
}
+72 -21
View File
@@ -3,30 +3,30 @@ import { PersonIcon } from '@primer/octicons-react';
import { useEffect, useState } from 'react';
import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router';
import { useLoaderData, useSubmit } from 'react-router';
import { ClientOnly } from 'remix-utils/client-only';
import Attribute from '~/components/Attribute';
import Card from '~/components/Card';
import { ErrorPopup } from '~/components/Error';
import StatusCircle from '~/components/StatusCircle';
import type { LoadContext } from '~/server';
import type { Machine, User } from '~/types';
import cn from '~/utils/cn';
import { pull } from '~/utils/headscale';
import { getSession } from '~/utils/sessions.server';
import { hs_getConfig } from '~/utils/config/loader';
import type { AppContext } from '~server/context/app';
import { hp_getConfig } from '~server/context/global';
import ManageBanner from './components/manage-banner';
import UserRow from './components/user-row';
import DeleteUser from './dialogs/delete-user';
import RenameUser from './dialogs/rename-user';
import { userAction } from './user-actions';
export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
const session = await getSession(request.headers.get('Cookie'));
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const [machines, apiUsers] = await Promise.all([
pull<{ nodes: Machine[] }>('v1/node', session.get('hsApiKey')!),
pull<{ users: User[] }>('v1/user', session.get('hsApiKey')!),
context.client.get<{ nodes: Machine[] }>(
'v1/node',
session.get('api_key')!,
),
context.client.get<{ users: User[] }>('v1/user', session.get('api_key')!),
]);
const users = apiUsers.users.map((user) => ({
@@ -34,18 +34,41 @@ export async function loader({ request }: LoaderFunctionArgs<AppContext>) {
machines: machines.nodes.filter((machine) => machine.user.id === user.id),
}));
const { oidc } = hp_getConfig();
const { mode, config } = hs_getConfig();
let magic: string | undefined;
const roles = users
.sort((a, b) => a.name.localeCompare(b.name))
.map((user) => {
if (user.provider !== 'oidc') {
return 'no-oidc';
}
if (mode !== 'no') {
if (config.dns.magic_dns) {
magic = config.dns.base_domain;
if (user.provider === 'oidc' && user.providerId) {
// For some reason, headscale makes providerID a url where the
// last component is the subject, so we need to strip that out
const subject = user.providerId.split('/').pop();
if (!subject) {
return 'invalid-oidc';
}
const role = context.sessions.roleForSubject(subject);
return role ?? 'no-role';
}
// No role means the user is not registered in Headplane, but they
// are in Headscale. We also need to handle what happens if someone
// logs into the UI and they don't have a Headscale setup.
return 'no-role';
});
let magic: string | undefined;
if (context.hs.readable()) {
if (context.hs.c?.dns.magic_dns) {
magic = context.hs.c.dns.base_domain;
}
}
return {
oidc,
oidc: context.config.oidc,
roles,
magic,
users,
};
@@ -75,7 +98,35 @@ export default function Page() {
drag machines between users to change ownership.
</p>
<ManageBanner oidc={data.oidc} />
<ClientOnly fallback={<Users users={users} />}>
<table className="table-auto w-full rounded-lg">
<thead className="text-headplane-600 dark:text-headplane-300">
<tr className="text-left px-0.5">
<th className="uppercase text-xs font-bold pb-2">User</th>
<th className="uppercase text-xs font-bold pb-2">Role</th>
<th className="uppercase text-xs font-bold pb-2">Created At</th>
<th className="uppercase text-xs font-bold pb-2">Last Seen</th>
</tr>
</thead>
<tbody
className={cn(
'divide-y divide-headplane-100 dark:divide-headplane-800 align-top',
'border-t border-headplane-100 dark:border-headplane-800',
)}
>
{users
.sort((a, b) => a.name.localeCompare(b.name))
.map((user) => (
<UserRow
key={user.id}
user={user}
role={data.roles[users.indexOf(user)]}
/>
))}
</tbody>
</table>
{/* <Users users={users} /> */}
{/* <ClientOnly fallback={<Users users={users} />}>
{() => (
<InteractiveUsers
users={users}
@@ -83,7 +134,7 @@ export default function Page() {
magic={data.magic}
/>
)}
</ClientOnly>
</ClientOnly> */}
</>
);
}
+35 -24
View File
@@ -1,12 +1,12 @@
import { ActionFunctionArgs, data } from 'react-router';
import { del, post } from '~/utils/headscale';
import { auth } from '~/utils/sessions.server';
import type { LoadContext } from '~/server';
export async function userAction({ request }: ActionFunctionArgs) {
const session = await auth(request);
if (!session) {
return data({ success: false }, 401);
}
export async function userAction({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
const session = await context.sessions.auth(request);
const apiKey = session.get('api_key')!;
const formData = await request.formData();
const action = formData.get('action_id')?.toString();
@@ -14,26 +14,25 @@ export async function userAction({ request }: ActionFunctionArgs) {
return data({ success: false }, 400);
}
const apiKey = session.get('hsApiKey');
if (!apiKey) {
return data({ success: false }, 401);
}
switch (action) {
case 'create_user':
return createUser(formData, apiKey);
return createUser(formData, apiKey, context);
case 'delete_user':
return deleteUser(formData, apiKey);
return deleteUser(formData, apiKey, context);
case 'rename_user':
return renameUser(formData, apiKey);
return renameUser(formData, apiKey, context);
case 'change_owner':
return changeOwner(formData, apiKey);
return changeOwner(formData, apiKey, context);
default:
return data({ success: false }, 400);
}
}
async function createUser(formData: FormData, apiKey: string) {
async function createUser(
formData: FormData,
apiKey: string,
context: LoadContext,
) {
const name = formData.get('username')?.toString();
const displayName = formData.get('display_name')?.toString();
const email = formData.get('email')?.toString();
@@ -42,40 +41,52 @@ async function createUser(formData: FormData, apiKey: string) {
return data({ success: false }, 400);
}
await post('v1/user', apiKey, {
await context.client.post('v1/user', apiKey, {
name,
displayName,
email,
});
}
async function deleteUser(formData: FormData, apiKey: string) {
async function deleteUser(
formData: FormData,
apiKey: string,
context: LoadContext,
) {
const userId = formData.get('user_id')?.toString();
if (!userId) {
return data({ success: false }, 400);
}
await del(`v1/user/${userId}`, apiKey);
await context.client.delete(`v1/user/${userId}`, apiKey);
}
async function renameUser(formData: FormData, apiKey: string) {
async function renameUser(
formData: FormData,
apiKey: string,
context: LoadContext,
) {
const userId = formData.get('user_id')?.toString();
const newName = formData.get('new_name')?.toString();
if (!userId || !newName) {
return data({ success: false }, 400);
}
await post(`v1/user/${userId}/rename/${newName}`, apiKey);
await context.client.post(`v1/user/${userId}/rename/${newName}`, apiKey);
}
async function changeOwner(formData: FormData, apiKey: string) {
async function changeOwner(
formData: FormData,
apiKey: string,
context: LoadContext,
) {
const userId = formData.get('user_id')?.toString();
const nodeId = formData.get('node_id')?.toString();
if (!userId || !nodeId) {
return data({ success: false }, 400);
}
await post(`v1/node/${nodeId}/user`, apiKey, {
await context.client.post(`v1/node/${nodeId}/user`, apiKey, {
user: userId,
});
}
+4 -10
View File
@@ -1,14 +1,8 @@
import { healthcheck } from '~/utils/headscale';
import log from '~server/utils/log';
export async function loader() {
let healthy = false;
try {
healthy = await healthcheck();
} catch (error) {
log.debug('APIC', 'Healthcheck failed %o', error);
}
import { LoaderFunctionArgs } from 'react-router';
import type { LoadContext } from '~/server';
export async function loader({ context }: LoaderFunctionArgs<LoadContext>) {
const healthy = await context.client.healthcheck();
return new Response(JSON.stringify({ status: healthy ? 'OK' : 'ERROR' }), {
status: healthy ? 200 : 500,
headers: {
+22
View File
@@ -0,0 +1,22 @@
# Headplane Server
This code is responsible for all code that is necessary *before* any
web server is started. It is the only part of the code that contains
many side-effects (in this case, importing a module may run code).
# Hierarchy
```
server
├── index.ts: Loads everything and starts the web server.
├── config/
│ ├── env.ts: Checks the environment variables for custom overrides.
│ ├── loader.ts: Checks the configuration file and coalesces with ENV.
│ ├── schema.ts: Defines the schema for the Headplane configuration.
├── headscale/
│ ├── api-client.ts: Creates the HTTP client that talks to the Headscale API.
│ ├── config-loader.ts: Loads the Headscale configuration (if available).
│ ├── config-schema.ts: Defines the schema for the Headscale configuration.
├── web/
│ ├── agent.ts: Handles setting up the agent WebSocket if needed.
│ ├── oidc.ts: Loads and validates an OIDC configuration (if available).
│ ├── roles.ts: Contains information about authentication permissions.
│ ├── sessions.ts: Initializes the session store and methods to manage it.
+76
View File
@@ -0,0 +1,76 @@
import { exit } from 'node:process';
import { type } from 'arktype';
import log from '~/utils/log';
// Custom type for boolean environment variables, allowing for values like
// 1, true, yes, and on to count as a truthy value.
const booleanEnv = type('string | undefined').pipe((v) => {
return ['1', 'true', 'yes', 'on'].includes(v?.toLowerCase() ?? '');
});
export const envVariables = {
debugLog: 'HEADPLANE_DEBUG_LOG',
envOverrides: 'HEADPLANE_LOAD_ENV_OVERRIDES',
configPath: 'HEADPLANE_CONFIG_PATH',
} as const;
export function configureLogger(env: string | undefined) {
const result = booleanEnv(env);
if (result instanceof type.errors) {
log.error(
'config',
'HEADPLANE_DEBUG_LOG value is invalid: %s',
result.summary,
);
log.info('config', 'Using a default value: false');
log.debug = () => {}; // Disable debug logging if the value is invalid
log.debugEnabled = false;
return;
}
if (result === false) {
log.debug = () => {}; // Disable debug logging if the value is false
log.debugEnabled = false;
return;
}
log.debug('config', 'Debug logging has been enabled');
log.debug('config', 'It is recommended this be disabled in production');
}
export interface EnvOverrides {
loadEnv: boolean;
path: string;
}
export function configureConfig(overrides: {
loadEnv: string | undefined;
path: string | undefined;
}): EnvOverrides {
const loadResult = booleanEnv(overrides.loadEnv);
if (loadResult instanceof type.errors) {
log.error(
'config',
'HEADPLANE_LOAD_ENV_OVERRIDES value is invalid: %s',
loadResult.summary,
);
exit(1);
}
const pathResult = type('string | undefined')(overrides.path);
if (pathResult instanceof type.errors) {
log.error(
'config',
'HEADPLANE_CONFIG_PATH value is invalid: %s',
pathResult.summary,
);
exit(1);
}
return {
loadEnv: loadResult,
path: pathResult ?? '/etc/headplane/config.yaml',
};
}
+225
View File
@@ -0,0 +1,225 @@
import { constants, access, readFile } from 'node:fs/promises';
import { env, exit } from 'node:process';
import { type } from 'arktype';
import { configDotenv } from 'dotenv';
import { parseDocument } from 'yaml';
import log from '~/utils/log';
import { EnvOverrides, envVariables } from './env';
import {
HeadplaneConfig,
headplaneConfig,
partialHeadplaneConfig,
} from './schema';
// loadConfig is a has a lifetime of the entire application and is
// used to load the configuration for Headplane. It is called once.
//
// TODO: Potential for file watching on the configuration
// But this may not be necessary as a use-case anyways
export async function loadConfig({ loadEnv, path }: EnvOverrides) {
log.debug('config', 'Loading configuration file: %s', path);
const valid = await validateConfigPath(path);
if (!valid) {
exit(1);
}
const data = await loadConfigFile(path);
if (!data) {
exit(1);
}
let config = validateConfig({ ...data, debug: log.debugEnabled });
if (!config) {
exit(1);
}
if (!loadEnv) {
log.debug('config', 'Environment variable overrides are disabled');
log.debug('config', 'This also disables the loading of a .env file');
return config;
}
log.info('config', 'Loading a .env file (if available)');
configDotenv({ override: true });
config = coalesceEnv(config);
if (!config) {
exit(1);
}
return config;
}
export async function hp_loadConfig() {
// // OIDC Related Checks
// if (config.oidc) {
// if (!config.oidc.client_secret && !config.oidc.client_secret_path) {
// log.error('CFGX', 'OIDC configuration is missing a secret, disabling');
// log.error(
// 'CFGX',
// 'Please specify either `oidc.client_secret` or `oidc.client_secret_path`',
// );
// }
// if (config.oidc?.strict_validation) {
// const result = await testOidc(config.oidc);
// if (!result) {
// log.error('CFGX', 'OIDC configuration failed validation, disabling');
// }
// }
// }
}
async function validateConfigPath(path: string) {
try {
await access(path, constants.F_OK | constants.R_OK);
log.info('config', 'Found a valid configuration file at %s', path);
return true;
} catch (error) {
log.error('config', 'Unable to read a configuration file at %s', path);
log.error('config', '%s', error);
return false;
}
}
async function loadConfigFile(path: string): Promise<unknown> {
log.debug('config', 'Reading 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 configuration file at %s', path);
for (const error of configYaml.errors) {
log.error('config', ` - ${error.toString()}`);
}
return false;
}
if (configYaml.warnings.length > 0) {
log.warn(
'config',
'Warnings while parsing configuration file at %s',
path,
);
for (const warning of configYaml.warnings) {
log.warn('config', ` - ${warning.toString()}`);
}
}
return configYaml.toJSON() as unknown;
} catch (e) {
log.error('config', 'Error reading configuration file at %s', path);
log.error('config', '%s', e);
return false;
}
}
export function validateConfig(config: unknown) {
log.debug('config', 'Validating Headplane configuration');
const result = headplaneConfig(config);
if (result instanceof type.errors) {
log.error('config', 'Error validating Headplane configuration:');
for (const [number, error] of result.entries()) {
log.error('config', ` - (${number}): ${error.toString()}`);
}
return;
}
return result;
}
function coalesceEnv(config: HeadplaneConfig) {
const envConfig: Record<string, unknown> = {};
const rootKeys: string[] = Object.values(envVariables);
// Typescript is still insanely stupid at nullish filtering
const vars = Object.entries(env).filter(([key, value]) => {
if (!value) {
return false;
}
if (!key.startsWith('HEADPLANE_')) {
return false;
}
// Filter out the rootEnv configurations
if (rootKeys.includes(key)) {
return false;
}
return true;
}) as [string, string][];
log.debug('config', 'Coalescing %s environment variables', vars.length);
for (const [key, value] of vars) {
const configPath = key.replace('HEADPLANE_', '').toLowerCase().split('__');
log.debug(
'config',
` - ${key}=${new Array(value.length).fill('*').join('')}`,
);
let current = envConfig;
while (configPath.length > 1) {
const path = configPath.shift() as string;
if (!(path in current)) {
current[path] = {};
}
current = current[path] as Record<string, unknown>;
}
current[configPath[0]] = value;
}
const toMerge = coalesceConfig(envConfig);
if (!toMerge) {
return;
}
// Deep merge the environment variables into the configuration
// This will overwrite any existing values in the configuration
return deepMerge(config, toMerge);
}
export function coalesceConfig(config: unknown) {
log.debug('config', 'Revalidating config after coalescing variables');
const out = partialHeadplaneConfig(config);
if (out instanceof type.errors) {
log.error('config', 'Error parsing variables:');
for (const [number, error] of out.entries()) {
log.error('config', ` - (${number}): ${error.toString()}`);
}
return;
}
return out;
}
type DeepPartial<T> =
| {
[P in keyof T]?: DeepPartial<T[P]>;
}
| undefined;
function deepMerge<T>(target: T, source: DeepPartial<T>): T {
if (typeof target !== 'object' || typeof source !== 'object')
return source as T;
const result = { ...target } as T;
for (const key in source) {
const val = source[key];
if (val === undefined) {
continue;
}
if (typeof val === 'object') {
result[key] = deepMerge(result[key], val);
continue;
}
result[key] = val;
}
return result;
}
@@ -1,7 +1,5 @@
import { type } from 'arktype';
import log from '~server/utils/log';
export type HeadplaneConfig = typeof headplaneConfig.infer;
const stringToBool = type('string | boolean').pipe((v) => Boolean(v));
const serverConfig = type({
host: 'string.ip',
@@ -9,7 +7,7 @@ const serverConfig = type({
cookie_secret: '32 <= string <= 32',
cookie_secure: stringToBool,
agent: type({
authkey: 'string',
authkey: 'string = ""',
ttl: 'number.integer = 180000', // Default to 3 minutes
cache_path: 'string = "/var/lib/headplane/agent_cache.json"',
})
@@ -29,6 +27,7 @@ const oidcConfig = type({
token_endpoint_auth_method:
'"client_secret_basic" | "client_secret_post" | "client_secret_jwt"',
redirect_uri: 'string.url?',
user_storage_file: 'string = "/var/lib/headplane/users.json"',
disable_api_key_login: stringToBool,
headscale_api_key: 'string',
strict_validation: stringToBool.default(true),
@@ -64,21 +63,21 @@ const integrationConfig = type({
'proc?': procConfig,
}).onDeepUndeclaredKey('reject');
const headplaneConfig = type({
debug: stringToBool,
server: serverConfig,
'oidc?': oidcConfig,
'integration?': integrationConfig,
headscale: headscaleConfig,
}).onDeepUndeclaredKey('reject');
const partialIntegrationConfig = type({
'docker?': dockerConfig.partial(),
'kubernetes?': kubernetesConfig.partial(),
'proc?': procConfig.partial(),
}).partial();
const partialHeadplaneConfig = type({
export const headplaneConfig = type({
debug: stringToBool,
server: serverConfig,
'oidc?': oidcConfig,
'integration?': integrationConfig,
headscale: headscaleConfig,
}).onDeepUndeclaredKey('delete');
export const partialHeadplaneConfig = type({
debug: stringToBool,
server: serverConfig.partial(),
'oidc?': oidcConfig.partial(),
@@ -86,34 +85,5 @@ const partialHeadplaneConfig = type({
headscale: headscaleConfig.partial(),
}).partial();
export function validateConfig(config: unknown) {
log.debug('CFGX', 'Validating Headplane configuration...');
const out = headplaneConfig(config);
if (out instanceof type.errors) {
log.error('CFGX', 'Error parsing Headplane configuration:');
for (const [number, error] of out.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
return;
}
log.debug('CFGX', 'Headplane configuration is valid.');
return out;
}
export function coalesceConfig(config: unknown) {
log.debug('CFGX', 'Validating coalescing vars for configuration...');
const out = partialHeadplaneConfig(config);
if (out instanceof type.errors) {
log.error('CFGX', 'Error parsing variables:');
for (const [number, error] of out.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
return;
}
log.debug('CFGX', 'Coalescing variables is valid.');
return out;
}
export type HeadplaneConfig = typeof headplaneConfig.infer;
export type PartialHeadplaneConfig = typeof partialHeadplaneConfig.infer;
+142
View File
@@ -0,0 +1,142 @@
import { readFile } from 'node:fs/promises';
import { Agent, Dispatcher, request } from 'undici';
import log from '~/utils/log';
export async function createApiClient(base: string, certPath?: string) {
if (!certPath) {
return new ApiClient(new Agent(), base);
}
try {
log.debug('config', 'Loading certificate from %s', certPath);
const data = await readFile(certPath, 'utf8');
log.info('config', 'Using certificate from %s', certPath);
return new ApiClient(new Agent({ connect: { ca: data.trim() } }), base);
} catch (error) {
log.error('config', 'Failed to load Headscale TLS cert: %s', error);
log.debug('config', 'Error Details: %o', error);
return new ApiClient(new Agent(), base);
}
}
// Represents an error that occurred during a response
// Thrown when status codes are >= 400
export class ResponseError extends Error {
status: number;
response: string;
constructor(status: number, response: string) {
super(`Response Error (${status}): ${response}`);
this.name = 'ResponseError';
this.status = status;
this.response = response;
}
}
// Represents an error that occurred during a request
// class RequestError extends Error {
class ApiClient {
private agent: Agent;
private base: string;
constructor(agent: Agent, base: string) {
this.agent = agent;
this.base = base;
}
private async defaultFetch(
url: string,
options?: Partial<Dispatcher.RequestOptions>,
) {
const method = options?.method ?? 'GET';
log.debug('api', '%s %s', method, url);
return await request(new URL(url, this.base), {
dispatcher: this.agent,
headers: {
...options?.headers,
Accept: 'application/json',
'User-Agent': `Headplane/${__VERSION__}`,
},
body: options?.body,
method,
});
}
async healthcheck() {
try {
const res = await this.defaultFetch('/health');
return res.statusCode === 200;
} catch (error) {
log.debug('api', 'Healthcheck failed %o', error);
return false;
}
}
async get<T = unknown>(url: string, key: string) {
const res = await this.defaultFetch(`/api/${url}`, {
headers: {
Authorization: `Bearer ${key}`,
},
});
if (res.statusCode >= 400) {
log.debug('api', 'GET %s failed with status %d', url, res.statusCode);
throw new ResponseError(res.statusCode, await res.body.text());
}
return res.body.json() as Promise<T>;
}
async post<T = unknown>(url: string, key: string, body?: unknown) {
const res = await this.defaultFetch(`/api/${url}`, {
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Bearer ${key}`,
},
});
if (res.statusCode >= 400) {
log.debug('api', 'POST %s failed with status %d', url, res.statusCode);
throw new ResponseError(res.statusCode, await res.body.text());
}
return res.body.json() as Promise<T>;
}
async put<T = unknown>(url: string, key: string, body?: unknown) {
const res = await this.defaultFetch(`/api/${url}`, {
method: 'PUT',
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Bearer ${key}`,
},
});
if (res.statusCode >= 400) {
log.debug('api', 'PUT %s failed with status %d', url, res.statusCode);
throw new ResponseError(res.statusCode, await res.body.text());
}
return res.body.json() as Promise<T>;
}
async delete<T = unknown>(url: string, key: string) {
const res = await this.defaultFetch(`/api/${url}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${key}`,
},
});
if (res.statusCode >= 400) {
log.debug('api', 'DELETE %s failed with status %d', url, res.statusCode);
throw new ResponseError(res.statusCode, await res.body.text());
}
return res.body.json() as Promise<T>;
}
}
+283
View File
@@ -0,0 +1,283 @@
import { constants, access, readFile, writeFile } from 'node:fs/promises';
import { setTimeout } from 'node:timers/promises';
import { type } from 'arktype';
import { Document, parseDocument } from 'yaml';
import log from '~/utils/log';
import { headscaleConfig } from './config-schema';
interface PatchConfig {
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;
constructor(
access: 'rw' | 'ro' | 'no',
config?: typeof headscaleConfig.infer,
document?: Document,
path?: string,
) {
this.access = access;
this.config = config;
this.document = document;
this.path = path;
}
readable() {
return this.access !== 'no';
}
writable() {
return this.access === 'rw';
}
get c() {
return this.config;
}
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);
// 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;
for (const char of path) {
if (char === '"') {
quote = !quote;
}
if (char === '.' && !quote) {
key.push(current);
current = '';
continue;
}
current += char;
}
key.push(current.replaceAll('"', ''));
if (value === null) {
this.document.deleteIn(key);
continue;
}
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;
}
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);
}
this.writeLock = true;
await writeFile(this.path, this.document.toString(), 'utf8');
this.config = config;
this.writeLock = false;
return;
}
}
export async function loadHeadscaleConfig(path?: string, strict = true) {
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');
}
const document = await loadConfigFile(path);
if (!document) {
return new HeadscaleConfig('no');
}
if (!strict) {
return new HeadscaleConfig(
w ? 'rw' : 'ro',
augmentUnstrictConfig(document.toJSON()),
document,
path,
);
}
const config = validateConfig(document.toJSON());
if (!config) {
return new HeadscaleConfig('no');
}
return new HeadscaleConfig(w ? 'rw' : 'ro', 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.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()}`);
}
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()}`);
}
return;
}
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: loaded.log ?? {
level: 'info',
format: 'text',
},
logtail: loaded.logtail ?? {
enabled: false,
},
prefixes: loaded.prefixes ?? {
allocation: 'sequential',
v4: '',
v6: '',
},
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',
);
return config as typeof headscaleConfig.infer;
}
@@ -1,5 +1,4 @@
import { type } from 'arktype';
import log from '~server/utils/log';
const goBool = type('boolean | "true" | "false"').pipe((v) => {
if (v === 'true') return true;
@@ -46,7 +45,7 @@ const databaseConfig = type({
// 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;
const headscaleConfig = type({
export const headscaleConfig = type({
server_url: 'string',
listen_addr: 'string',
'metrics_listen_addr?': 'string',
@@ -56,8 +55,8 @@ const headscaleConfig = type({
private_key_path: 'string',
},
prefixes: {
v4: 'string',
v6: 'string',
v4: 'string?',
v6: 'string?',
allocation: '"sequential" | "random" = "sequential"',
},
derp: {
@@ -147,82 +146,3 @@ const headscaleConfig = type({
randomize_client_port: goBool.default(false),
});
export function validateConfig(config: unknown, strict: boolean) {
log.debug('CFGX', 'Validating Headscale configuration...');
const out = strict
? headscaleConfig(config)
: headscaleConfig(augmentUnstrictConfig(config as HeadscaleConfig));
if (out instanceof type.errors) {
log.error('CFGX', 'Error parsing Headscale configuration:');
for (const [number, error] of out.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
log.error('CFGX', '');
log.error('CFGX', 'Resolve these issues and try again.');
log.error('CFGX', 'Headplane will operate without the config');
log.error('CFGX', '');
return;
}
log.debug('CFGX', 'Headscale configuration is valid.');
return out;
}
// 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<HeadscaleConfig>,
): HeadscaleConfig {
log.debug('CFGX', 'Loaded 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',
},
logtail: loaded.logtail ?? {
enabled: false,
},
prefixes: loaded.prefixes ?? {
allocation: 'sequential',
v4: '',
v6: '',
},
dns: loaded.dns ?? {
nameservers: {
global: [],
split: {},
},
search_domains: [],
extra_records: [],
magic_dns: false,
base_domain: 'headscale.net',
},
};
log.warn('CFGX', 'Loaded Headscale configuration in non-strict mode');
log.warn('CFGX', 'By using this mode you forfeit GitHub issue support');
log.warn('CFGX', 'This is very dangerous and comes with a few caveats:');
log.warn('CFGX', ' Headplane could very easily crash');
log.warn('CFGX', ' Headplane could break your Headscale installation');
log.warn('CFGX', ' The UI could throw random errors/show incorrect data');
log.warn('CFGX', '');
return config as HeadscaleConfig;
}
+103
View File
@@ -0,0 +1,103 @@
import { env, versions } from 'node:process';
import type { UpgradeWebSocket } from 'hono/ws';
import { createHonoServer } from 'react-router-hono-server/node';
import type { WebSocket } from 'ws';
import log from '~/utils/log';
import { configureConfig, configureLogger, envVariables } from './config/env';
import { loadConfig } from './config/loader';
import { createApiClient } from './headscale/api-client';
import { loadHeadscaleConfig } from './headscale/config-loader';
import { loadAgentSocket } from './web/agent';
import { createOidcClient } from './web/oidc';
import { createSessionStorage } from './web/sessions';
declare global {
const __PREFIX__: string;
const __VERSION__: string;
}
// MARK: Side-Effects
// This module contains a side-effect because everything running here
// exists for the lifetime of the process, making it appropriate.
log.info('server', 'Running Node.js %s', versions.node);
configureLogger(env[envVariables.debugLog]);
const config = await loadConfig(
configureConfig({
loadEnv: env[envVariables.envOverrides],
path: env[envVariables.configPath],
}),
);
// We also use this file to load anything needed by the react router code.
// These are usually per-request things that we need access to, like the
// helper that can issue and revoke cookies.
export type LoadContext = typeof appLoadContext;
const appLoadContext = {
config,
hs: await loadHeadscaleConfig(
config.headscale.config_path,
config.headscale.config_strict,
),
// TODO: Better cookie options in config
sessions: await createSessionStorage(
{
name: '_hp_session',
maxAge: 60 * 60 * 24, // 24 hours
secure: config.server.cookie_secure,
secrets: [config.server.cookie_secret],
},
config.oidc?.user_storage_file,
),
client: await createApiClient(
config.headscale.url,
config.headscale.tls_cert_path,
),
agents: await loadAgentSocket(
config.server.agent.authkey,
config.server.agent.cache_path,
config.server.agent.ttl,
),
oidc: config.oidc ? await createOidcClient(config.oidc) : undefined,
};
declare module 'react-router' {
interface AppLoadContext extends LoadContext {}
}
export default createHonoServer({
useWebSocket: true,
overrideGlobalObjects: true,
port: config.server.port,
hostname: config.server.host,
// Only log in development mode
defaultLogger: import.meta.env.DEV,
getLoadContext() {
// TODO: This is the place where we can handle reverse proxy translation
// This is better than doing it in the OIDC client, since we can do it
// for all requests, not just OIDC ones.
return appLoadContext;
},
configure(app, { upgradeWebSocket }) {
const agentManager = appLoadContext.agents;
if (agentManager) {
app.get(
`${__PREFIX__}/_dial`,
// We need this since we cannot pass the WSEvents context
// Also important to not pass the callback directly
// since we need to retain `this` context
(upgradeWebSocket as UpgradeWebSocket<WebSocket>)((c) =>
agentManager.configureSocket(c),
),
);
}
},
listeningListener(info) {
log.info('server', 'Running on %s:%s', info.address, info.port);
},
});
+283
View File
@@ -0,0 +1,283 @@
import { createHash } from 'node:crypto';
import { open, readFile, writeFile } from 'node:fs/promises';
import { setTimeout } from 'node:timers/promises';
import { getConnInfo } from '@hono/node-server/conninfo';
import { type } from 'arktype';
import type { Context } from 'hono';
import type { WSContext, WSEvents } from 'hono/ws';
import { WebSocket } from 'ws';
import { HostInfo } from '~/types';
import log from '~/utils/log';
export async function loadAgentSocket(
authkey: string,
path: string,
ttl: number,
) {
if (authkey.length === 0) {
return;
}
try {
const handle = await open(path, 'w');
log.info('agent', 'Using agent cache file at %s', path);
await handle.close();
} catch (error) {
log.info('agent', 'Agent cache file not accessible at %s', path);
log.debug('agent', 'Error details: %s', error);
return;
}
const cache = new TimedCache<HostInfo>(ttl, path);
return new AgentManager(cache, authkey);
}
class AgentManager {
private cache: TimedCache<HostInfo>;
private agents: Map<string, WSContext>;
private timers: Map<string, NodeJS.Timeout>;
private authkey: string;
constructor(cache: TimedCache<HostInfo>, authkey: string) {
this.cache = cache;
this.authkey = authkey;
this.agents = new Map();
this.timers = new Map();
}
tailnetIDs() {
return Array.from(this.agents.keys());
}
lookup(nodeIds: string[]) {
const entries = this.cache.toJSON();
const missing = nodeIds.filter((nodeId) => !entries[nodeId]);
if (missing.length > 0) {
this.requestData(missing);
}
return entries;
}
// Request data from all connected agents
// This does not return anything, but caches the data which then needs to be
// queried by the caller separately.
private requestData(nodeList: string[]) {
const NodeIDs = [...new Set(nodeList)];
NodeIDs.map((node) => {
log.debug('agent', 'Requesting agent data for %s', node);
});
for (const agent of this.agents.values()) {
agent.send(JSON.stringify({ NodeIDs }));
}
}
// Since we are using Node, Hono is built on 'ws' WebSocket types.
configureSocket(c: Context): WSEvents<WebSocket> {
return {
onOpen: (_, ws) => {
const id = c.req.header('x-headplane-tailnet-id');
if (!id) {
log.warn(
'agent',
'Rejecting an agent WebSocket connection without a tailnet ID',
);
ws.close(1008, 'ERR_INVALID_TAILNET_ID');
return;
}
const auth = c.req.header('authorization');
if (auth !== `Bearer ${this.authkey}`) {
log.warn('agent', 'Rejecting an unauthorized WebSocket connection');
const info = getConnInfo(c);
if (info.remote.address) {
log.warn('agent', 'Agent source IP: %s', info.remote.address);
}
ws.close(1008, 'ERR_UNAUTHORIZED');
return;
}
const pinger = setInterval(() => {
if (ws.readyState !== 1) {
clearInterval(pinger);
return;
}
ws.raw?.ping();
}, 30000);
this.agents.set(id, ws);
this.timers.set(id, pinger);
},
onClose: () => {
const id = c.req.header('x-headplane-tailnet-id');
if (!id) {
return;
}
clearInterval(this.timers.get(id));
this.agents.delete(id);
},
onError: (event, ws) => {
const id = c.req.header('x-headplane-tailnet-id');
if (!id) {
return;
}
clearInterval(this.timers.get(id));
if (event instanceof ErrorEvent) {
log.error('agent', 'WebSocket error: %s', event.message);
}
log.debug('agent', 'Closing agent WebSocket connection');
ws.close(1011, 'ERR_INTERNAL_ERROR');
},
// This is where we receive the data from the agent
// Requests are made in the AgentManager.requestData function
onMessage: (event, ws) => {
const id = c.req.header('x-headplane-tailnet-id');
if (!id) {
return;
}
const data = JSON.parse(event.data.toString());
log.debug('agent', 'Received agent data from %s', id);
for (const [node, info] of Object.entries<HostInfo>(data)) {
this.cache.set(node, info);
log.debug('agent', 'Cached HostInfo for %s', node);
}
},
};
}
}
const diskSchema = type({
key: 'string',
value: 'unknown',
expires: 'number?',
}).array();
// A persistent HashMap with a TTL for each key
class TimedCache<V> {
private _cache = new Map<string, V>();
private _timings = new Map<string, number>();
// Default TTL is 1 minute
private defaultTTL: number;
private filePath: string;
private writeLock = false;
// Last flush ID is essentially a hash of the flush contents
// Prevents unnecessary flushing if nothing has changed
private lastFlushId = '';
constructor(defaultTTL: number, filePath: string) {
this.defaultTTL = defaultTTL;
this.filePath = filePath;
// Load the cache from disk and then queue flushes every 10 seconds
this.load().then(() => {
setInterval(() => this.flush(), 10000);
});
}
set(key: string, value: V, ttl: number = this.defaultTTL) {
this._cache.set(key, value);
this._timings.set(key, Date.now() + ttl);
}
get(key: string) {
const value = this._cache.get(key);
if (!value) {
return;
}
const expires = this._timings.get(key);
if (!expires || expires < Date.now()) {
this._cache.delete(key);
this._timings.delete(key);
return;
}
return value;
}
// Map into a Record without any TTLs
toJSON() {
const result: Record<string, V> = {};
for (const [key, value] of this._cache.entries()) {
result[key] = value;
}
return result;
}
// WARNING: This function expects that this.filePath is NOT ENOENT
private async load() {
const data = await readFile(this.filePath, 'utf-8');
const cache = () => {
try {
return JSON.parse(data);
} catch (e) {
return undefined;
}
};
const diskData = cache();
if (diskData === undefined) {
log.error('agent', 'Failed to load cache at %s', this.filePath);
return;
}
const cacheData = diskSchema(diskData);
if (cacheData instanceof type.errors) {
log.debug('agent', 'Failed to load cache at %s', this.filePath);
log.debug('agent', 'Error details: %s', cacheData.toString());
// Skip loading the cache (it should be overwritten soon)
return;
}
for (const { key, value, expires } of diskData) {
this._cache.set(key, value);
this._timings.set(key, expires);
}
log.info('agent', 'Loaded cache from %s', this.filePath);
}
private async flush() {
const data = Array.from(this._cache.entries()).map(([key, value]) => {
return { key, value, expires: this._timings.get(key) };
});
if (data.length === 0) {
return;
}
// Calculate the hash of the data
const dumpData = JSON.stringify(data);
const sha = createHash('sha256').update(dumpData).digest('hex');
if (sha === this.lastFlushId) {
return;
}
// 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.filePath, dumpData, 'utf-8');
log.debug('agent', 'Flushed cache to %s', this.filePath);
this.lastFlushId = sha;
this.writeLock = false;
}
}
+150
View File
@@ -0,0 +1,150 @@
import { readFile } from 'node:fs/promises';
import * as client from 'openid-client';
import log from '~/utils/log';
import type { HeadplaneConfig } from '../config/schema';
async function loadClientSecret(path: string) {
// We need to interpolate environment variables into the path
// Path formatting can be like ${ENV_NAME}/path/to/secret
const matches = path.match(/\${(.*?)}/g);
let resolvedPath = path;
if (matches) {
for (const match of matches) {
const env = match.slice(2, -1);
const value = process.env[env];
if (!value) {
log.error('config', 'Environment variable %s is not set', env);
return;
}
log.debug('config', 'Interpolating %s with %s', match, value);
resolvedPath = resolvedPath.replace(match, value);
}
}
try {
log.debug('config', 'Reading client secret from %s', resolvedPath);
const secret = await readFile(resolvedPath, 'utf-8');
if (secret.trim().length === 0) {
log.error('config', 'Empty OIDC client secret');
return;
}
return secret;
} catch (error) {
log.error('config', 'Failed to read client secret from %s', path);
log.error('config', 'Error: %s', error);
log.debug('config', 'Error details: %o', error);
}
}
function clientAuthMethod(
method: string,
): (secret: string) => client.ClientAuth {
switch (method) {
case 'client_secret_post':
return client.ClientSecretPost;
case 'client_secret_basic':
return client.ClientSecretBasic;
case 'client_secret_jwt':
return client.ClientSecretJwt;
default:
throw new Error('Invalid client authentication method');
}
}
// Loads and configures an OIDC client to support OIDC authentication.
// This runs under the assumption the OIDC configuration exists and is valid.
// If it is invalid, Headplane automatically disables it.
//
// TODO: Support custom endpoints instead of relying on OIDC discovery.
// This will enable us to support servers like GitHub that do not support
// nor advertise a .well-known endpoint.
export async function createOidcClient(
config: NonNullable<HeadplaneConfig['oidc']>,
) {
// const secret = await loadClientSecret(oidc);
const secret = config.client_secret_path
? await loadClientSecret(config.client_secret_path)
: config.client_secret;
if (!secret) {
log.error('config', 'Missing an OIDC client secret');
return;
}
log.debug('config', 'Running OIDC discovery for %s', config.issuer);
const oidc = await client.discovery(
new URL(config.issuer),
config.client_id,
secret,
clientAuthMethod(config.token_endpoint_auth_method)(secret),
);
const metadata = oidc.serverMetadata();
if (!metadata.authorization_endpoint) {
log.error(
'config',
'Issuer discovery did not return `authorization_endpoint`',
);
log.error('config', 'OIDC server does not support authorization code flow');
return;
}
if (!metadata.token_endpoint) {
log.error('config', 'Issuer discovery did not return `token_endpoint`');
log.error('config', 'OIDC server does not support token exchange');
return;
}
// If this field is missing, assume the server supports all response types
// and that we can continue safely.
if (metadata.response_types_supported) {
if (!metadata.response_types_supported.includes('code')) {
log.error(
'config',
'Issuer discovery `response_types_supported` does not include `code`',
);
log.error('config', 'OIDC server does not support code flow');
return;
}
}
if (metadata.token_endpoint_auth_methods_supported) {
if (
!metadata.token_endpoint_auth_methods_supported.includes(
config.token_endpoint_auth_method,
)
) {
log.error(
'config',
'Issuer discovery `token_endpoint_auth_methods_supported` does not include `%s`',
config.token_endpoint_auth_method,
);
log.error(
'config',
'OIDC server does not support %s',
config.token_endpoint_auth_method,
);
return;
}
}
if (!metadata.userinfo_endpoint) {
log.error('config', 'Issuer discovery did not return `userinfo_endpoint`');
log.error('config', 'OIDC server does not support userinfo endpoint');
return;
}
log.debug('config', 'OIDC client created successfully');
log.info('config', 'Using %s as the OIDC issuer', config.issuer);
log.debug(
'config',
'Authorization endpoint: %s',
metadata.authorization_endpoint,
);
log.debug('config', 'Token endpoint: %s', metadata.token_endpoint);
log.debug('config', 'Userinfo endpoint: %s', metadata.userinfo_endpoint);
return oidc;
}
+144
View File
@@ -0,0 +1,144 @@
export type Capabilities = (typeof Capabilities)[keyof typeof Capabilities];
export const Capabilities = {
// Can access the admin console
ui_access: 1 << 0,
// Read tailnet policy file
read_policy: 1 << 1,
// Write tailnet policy file
write_policy: 1 << 2,
// Read network configurations
read_network: 1 << 3,
// Write network configurations, for example, enable MagicDNS, split DNS,
// make subnet, or allow a node to be an exit node, enable HTTPS
write_network: 1 << 4,
// Read feature configuration
read_feature: 1 << 5,
// Write feature configuration, for example, enable Taildrop
write_feature: 1 << 6,
// Configure user & group provisioning
configure_iam: 1 << 7,
// Read machines, for example, see machine names and status
read_machines: 1 << 8,
// Write machines, for example, approve, rename, and remove machines
write_machines: 1 << 9,
// Read users and user roles
read_users: 1 << 10,
// Write users and user roles, for example, remove users,
// approve users, make Admin
write_users: 1 << 11,
// Can generate authkeys
generate_authkeys: 1 << 12,
// Can use any tag (without being tag owner)
use_tags: 1 << 13,
// Write tailnet name
write_tailnet: 1 << 14,
// Owner flag
owner: 1 << 15,
} as const;
export type Roles = [keyof typeof Roles];
export const Roles = {
owner:
Capabilities.ui_access |
Capabilities.read_policy |
Capabilities.write_policy |
Capabilities.read_network |
Capabilities.write_network |
Capabilities.read_feature |
Capabilities.write_feature |
Capabilities.configure_iam |
Capabilities.read_machines |
Capabilities.write_machines |
Capabilities.read_users |
Capabilities.write_users |
Capabilities.generate_authkeys |
Capabilities.use_tags |
Capabilities.write_tailnet |
Capabilities.owner,
admin:
Capabilities.ui_access |
Capabilities.read_policy |
Capabilities.write_policy |
Capabilities.read_network |
Capabilities.write_network |
Capabilities.read_feature |
Capabilities.write_feature |
Capabilities.configure_iam |
Capabilities.read_machines |
Capabilities.write_machines |
Capabilities.read_users |
Capabilities.write_users |
Capabilities.generate_authkeys |
Capabilities.use_tags |
Capabilities.write_tailnet,
network_admin:
Capabilities.ui_access |
Capabilities.read_policy |
Capabilities.write_policy |
Capabilities.read_network |
Capabilities.write_network |
Capabilities.read_feature |
Capabilities.read_machines |
Capabilities.read_users |
Capabilities.generate_authkeys |
Capabilities.use_tags |
Capabilities.write_tailnet,
it_admin:
Capabilities.ui_access |
Capabilities.read_policy |
Capabilities.read_network |
Capabilities.read_feature |
Capabilities.write_feature |
Capabilities.configure_iam |
Capabilities.read_machines |
Capabilities.write_machines |
Capabilities.read_users |
Capabilities.write_users |
Capabilities.generate_authkeys,
auditor:
Capabilities.ui_access |
Capabilities.read_policy |
Capabilities.read_network |
Capabilities.read_feature |
Capabilities.read_machines |
Capabilities.read_users,
// Default role for new users with 0 capabilities on the UI side of things
member: 0,
} as const;
export type Role = keyof typeof Roles;
export type Capability = keyof typeof Capabilities;
export function hasCapability(role: Role, capability: Capability): boolean {
return (Roles[role] & Capabilities[capability]) !== 0;
}
export function getRoleFromCapabilities(capabilities: Capabilities): Role {
const iterable = Roles as Record<string, Capabilities>;
for (const role in iterable) {
if (iterable[role] === capabilities) {
return role as Role;
}
}
return 'member';
}
+230
View File
@@ -0,0 +1,230 @@
import { open, readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { exit } from 'node:process';
import {
CookieSerializeOptions,
Session,
SessionStorage,
createCookieSessionStorage,
} from 'react-router';
import log from '~/utils/log';
import { Capabilities, Roles } from './roles';
export interface AuthSession {
state: 'auth';
api_key: string;
user: {
subject: string;
name: string;
email?: string;
username?: string;
picture?: string;
};
}
export interface OidcFlowSession {
state: 'flow';
oidc: {
state: string;
nonce: string;
code_verifier: string;
redirect_uri: string;
};
}
type JoinedSession = AuthSession | OidcFlowSession;
interface Error {
error: string;
}
interface CookieOptions {
name: string;
secure: boolean;
maxAge: number;
secrets: string[];
domain?: string;
}
class Sessionizer {
private storage: SessionStorage<JoinedSession, Error>;
private caps: Record<string, Capabilities>;
private capsPath?: string;
constructor(
options: CookieOptions,
caps: Record<string, Capabilities>,
capsPath?: string,
) {
this.caps = caps;
this.capsPath = capsPath;
this.storage = createCookieSessionStorage({
cookie: {
...options,
httpOnly: true,
path: __PREFIX__, // Only match on the prefix
sameSite: 'lax', // TODO: Strictify with Domain,
},
});
}
// This throws on the assumption that auth is already checked correctly
// on something that wraps the route calling auth. The top-level routes
// that call this are wrapped with try/catch to handle the error.
async auth(request: Request) {
const cookie = request.headers.get('cookie');
const session = await this.storage.getSession(cookie);
const type = session.get('state');
if (!type) {
throw new Error('Session state not found');
}
if (type !== 'auth') {
throw new Error('Session is not authenticated');
}
return session as Session<AuthSession, Error>;
}
roleForSubject(subject: string) {
const role = this.caps[subject];
// We need this in string form based on Object.keys of the roles
for (const [key, value] of Object.entries(Roles)) {
if (value === role) {
return key;
}
}
}
// Given an OR of capabilities, check if the session has the required
// capabilities. If not, return false. Can throw since it calls auth()
async check(request: Request, capabilities: Capabilities) {
const session = await this.auth(request);
const { subject } = session.get('user') ?? {};
if (!subject) {
return false;
}
// This is the subject we set on API key based sessions. API keys
// inherently imply admin access so we return true for all checks.
if (subject === 'unknown-non-oauth') {
return true;
}
// If the role does not exist, then this is a new subject that we have
// not seen before. Since this is new, we set access to the lowest
// level by default which is the member role.
//
// This also allows us to avoid configuring preventing sign ups with
// OIDC, since the default sign up logic gives member which does not
// have access to the UI whatsoever.
const role = this.caps[subject];
if (!role) {
const memberRole = await this.registerSubject(subject);
return (capabilities & memberRole) === capabilities;
}
return (capabilities & role) === capabilities;
}
// This code is very simple, if the user does not exist in the database
// file then we register it with the lowest level of access. If the user
// database is empty, the first user to sign in will be given the owner
// role.
private async registerSubject(subject: string) {
if (this.caps[subject]) {
return this.caps[subject];
}
if (Object.keys(this.caps).length === 0) {
log.debug('auth', 'First user registered as owner: %s', subject);
this.caps[subject] = Roles.owner;
await this.flushUserDatabase();
return this.caps[subject];
}
log.debug('auth', 'New user registered as member: %s', subject);
this.caps[subject] = Roles.member;
await this.flushUserDatabase();
return this.caps[subject];
}
private async flushUserDatabase() {
if (!this.capsPath) {
return;
}
const data = Object.entries(this.caps).map(([u, c]) => ({ u, c }));
try {
const handle = await open(this.capsPath, 'w');
await handle.write(JSON.stringify(data));
await handle.close();
} catch (error) {
log.error('config', 'Error writing user database file: %s', error);
}
}
getOrCreate<T extends JoinedSession = AuthSession>(request: Request) {
return this.storage.getSession(request.headers.get('cookie')) as Promise<
Session<T, Error>
>;
}
destroy(session: Session) {
return this.storage.destroySession(session);
}
commit(session: Session, options?: CookieSerializeOptions) {
return this.storage.commitSession(session, options);
}
}
export async function createSessionStorage(
options: CookieOptions,
usersPath?: string,
) {
const map: Record<string, Capabilities> = {};
if (usersPath) {
// We need to load our users from the file (default to empty map)
// We then translate each user into a capability object using the helper
// method defined in the roles.ts file
const data = await loadUserFile(usersPath);
log.debug('config', 'Loaded %d users from database', data.length);
for (const user of data) {
map[user.u] = user.c;
}
}
return new Sessionizer(options, map, usersPath);
}
async function loadUserFile(path: string) {
const realPath = resolve(path);
try {
const handle = await open(realPath, 'a+');
log.info('config', 'Using user database file at %s', realPath);
await handle.close();
} catch (error) {
log.info('config', 'User database file not accessible at %s', realPath);
log.debug('config', 'Error details: %s', error);
exit(1);
}
try {
const data = await readFile(realPath, 'utf8');
const users = JSON.parse(data.trim()) as { u?: string; c?: number }[];
// Never trust user input
return users.filter(
(user) => user.u !== undefined && user.c !== undefined,
) as {
u: string;
c: number;
}[];
} catch (error) {
log.debug('config', 'Error reading user database file: %s', error);
log.debug('config', 'Using empty user database');
return [];
}
}
-204
View File
@@ -1,204 +0,0 @@
import { constants, access, readFile, writeFile } from 'node:fs/promises';
import { Document, parseDocument } from 'yaml';
import { hp_getIntegration } from '~/utils/integration/loader';
import mutex from '~/utils/mutex';
import { hp_getConfig } from '~server/context/global';
import log from '~server/utils/log';
import { HeadscaleConfig, validateConfig } from './parser';
let runtimeYaml: Document | undefined = undefined;
let runtimeConfig: HeadscaleConfig | undefined = undefined;
let runtimePath: string | undefined = undefined;
let runtimeMode: 'rw' | 'ro' | 'no' = 'no';
const runtimeLock = mutex();
export type ConfigModes =
| {
mode: 'rw' | 'ro';
config: HeadscaleConfig;
}
| {
mode: 'no';
config: undefined;
};
export function hs_getConfig(): ConfigModes {
if (runtimeMode === 'no') {
return {
mode: 'no',
config: undefined,
};
}
runtimeLock.acquire();
// We can assert if mode is not 'no'
const config = runtimeConfig!;
runtimeLock.release();
return {
mode: runtimeMode,
config: config,
};
}
export async function hs_loadConfig(path?: string, strict?: boolean) {
if (runtimeConfig !== undefined) {
return;
}
runtimeLock.acquire();
if (!path) {
runtimeLock.release();
return;
}
runtimeMode = await validateConfigPath(path);
if (runtimeMode === 'no') {
runtimeLock.release();
return;
}
runtimePath = path;
const rawConfig = await loadConfigFile(path);
if (!rawConfig) {
return;
}
const config = validateConfig(rawConfig, strict ?? true);
if (!config) {
runtimeMode = 'no';
}
runtimeConfig = config;
}
async function validateConfigPath(path: string) {
log.debug('CFGX', `Validating Headscale configuration file at ${path}`);
try {
await access(path, constants.F_OK | constants.R_OK);
log.info('CFGX', `Headscale configuration found at ${path}`);
} catch (e) {
log.error('CFGX', `Headscale configuration not readable at ${path}`);
log.error('CFGX', `${e}`);
return 'no';
}
let writeable = false;
try {
await access(path, constants.W_OK);
writeable = true;
} catch (e) {
log.warn('CFGX', `Headscale configuration not writeable at ${path}`);
log.debug('CFGX', `${e}`);
}
return writeable ? 'rw' : 'ro';
}
async function loadConfigFile(path: string) {
log.debug('CFGX', `Loading Headscale configuration file at ${path}`);
try {
const data = await readFile(path, 'utf8');
const configYaml = parseDocument(data);
if (configYaml.errors.length > 0) {
log.error(
'CFGX',
`Error parsing Headscale configuration file at ${path}`,
);
for (const error of configYaml.errors) {
log.error('CFGX', ` ${error.toString()}`);
}
return;
}
runtimeYaml = configYaml;
return configYaml.toJSON() as unknown;
} catch (e) {
log.error('CFGX', `Error reading Headscale configuration file at ${path}`);
log.error('CFGX', `${e}`);
return;
}
}
type PatchConfig = { path: string; value: unknown };
export async function hs_patchConfig(patches: PatchConfig[]) {
if (!runtimeConfig || !runtimeYaml || !runtimePath) {
log.error('CFGX', 'Headscale configuration not loaded');
return;
}
if (runtimeMode === 'no') {
return;
}
if (runtimeMode === 'ro') {
throw new Error('Headscale configuration is read-only');
}
runtimeLock.acquire();
const config = runtimeConfig!;
log.debug('CFGX', 'Patching Headscale configuration');
for (const patch of patches) {
const { path, value } = patch;
log.debug('CFGX', 'Patching %s in Headscale configuration', path);
// 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;
for (const char of path) {
if (char === '"') {
quote = !quote;
}
if (char === '.' && !quote) {
key.push(current);
current = '';
continue;
}
current += char;
}
key.push(current.replaceAll('"', ''));
// Deletion handling
if (value === null) {
runtimeYaml.deleteIn(key);
continue;
}
runtimeYaml.setIn(key, value);
}
// Revalidate the configuration
const context = hp_getConfig();
const newRawConfig = runtimeYaml.toJSON() as unknown;
runtimeConfig = context.headscale.config_strict
? validateConfig(newRawConfig, true)
: (newRawConfig as HeadscaleConfig);
log.debug(
'CFGX',
'Writing patched Headscale configuration to %s',
runtimePath,
);
await writeFile(runtimePath, runtimeYaml.toString(), 'utf8');
runtimeLock.release();
}
// IMPORTANT THIS IS A SIDE EFFECT ON INIT
// TODO: Replace this into the new singleton system
const context = hp_getConfig();
hs_loadConfig(context.headscale.config_path, context.headscale.config_strict);
hp_getIntegration();
-149
View File
@@ -1,149 +0,0 @@
import { request } from 'undici';
import { hp_getConfig, hp_getSingleton } from '~server/context/global';
import log from '~server/utils/log';
export class HeadscaleError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.name = 'HeadscaleError';
this.status = status;
}
}
export class FatalError extends Error {
constructor() {
super(
'The Headscale server is not accessible or the supplied API key is invalid',
);
this.name = 'FatalError';
}
}
export async function healthcheck() {
log.debug('APIC', 'GET /health');
const health = new URL('health', hp_getConfig().headscale.url);
const response = await request(health.toString(), {
dispatcher: hp_getSingleton('api_agent'),
headers: {
Accept: 'application/json',
},
});
// Intentionally not catching
return response.statusCode === 200;
}
export async function pull<T>(url: string, key: string) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const prefix = hp_getConfig().headscale.url;
log.debug('APIC', 'GET %s', `${prefix}/api/${url}`);
const response = await request(`${prefix}/api/${url}`, {
dispatcher: hp_getSingleton('api_agent'),
headers: {
Authorization: `Bearer ${key}`,
},
});
if (response.statusCode >= 400) {
log.debug(
'APIC',
'GET %s failed with status %d',
`${prefix}/api/${url}`,
response.statusCode,
);
throw new HeadscaleError(await response.body.text(), response.statusCode);
}
return response.body.json() as Promise<T>;
}
export async function post<T>(url: string, key: string, body?: unknown) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const prefix = hp_getConfig().headscale.url;
log.debug('APIC', 'POST %s', `${prefix}/api/${url}`);
const response = await request(`${prefix}/api/${url}`, {
dispatcher: hp_getSingleton('api_agent'),
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Bearer ${key}`,
},
});
if (response.statusCode >= 400) {
log.debug(
'APIC',
'POST %s failed with status %d',
`${prefix}/api/${url}`,
response.statusCode,
);
throw new HeadscaleError(await response.body.text(), response.statusCode);
}
return response.body.json() as Promise<T>;
}
export async function put<T>(url: string, key: string, body?: unknown) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const prefix = hp_getConfig().headscale.url;
log.debug('APIC', 'PUT %s', `${prefix}/api/${url}`);
const response = await request(`${prefix}/api/${url}`, {
dispatcher: hp_getSingleton('api_agent'),
method: 'PUT',
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Bearer ${key}`,
},
});
if (response.statusCode >= 400) {
log.debug(
'APIC',
'PUT %s failed with status %d',
`${prefix}/api/${url}`,
response.statusCode,
);
throw new HeadscaleError(await response.body.text(), response.statusCode);
}
return response.body.json() as Promise<T>;
}
export async function del<T>(url: string, key: string) {
if (!key || key === 'undefined' || key.length === 0) {
throw new Error('Missing API key, could this be a cookie setting issue?');
}
const prefix = hp_getConfig().headscale.url;
log.debug('APIC', 'DELETE %s', `${prefix}/api/${url}`);
const response = await request(`${prefix}/api/${url}`, {
dispatcher: hp_getSingleton('api_agent'),
method: 'DELETE',
headers: {
Authorization: `Bearer ${key}`,
},
});
if (response.statusCode >= 400) {
log.debug(
'APIC',
'DELETE %s failed with status %d',
`${prefix}/api/${url}`,
response.statusCode,
);
throw new HeadscaleError(await response.body.text(), response.statusCode);
}
return response.body.json() as Promise<T>;
}
+36 -39
View File
@@ -1,12 +1,11 @@
import { hp_getConfig } from '~server/context/global';
import { HeadplaneConfig } from '~server/context/parser';
import log from '~server/utils/log';
import { HeadplaneConfig } from '~/server/config/schema';
import log from '~/utils/log';
import { Integration } from './abstract';
import dockerIntegration from './docker';
import kubernetesIntegration from './kubernetes';
import procIntegration from './proc';
// import dockerIntegration from './docker';
// import kubernetesIntegration from './kubernetes';
// import procIntegration from './proc';
let runtimeIntegration: Integration<unknown> | undefined = undefined;
const runtimeIntegration: Integration<unknown> | undefined = undefined;
export function hp_getIntegration() {
return runtimeIntegration;
@@ -15,24 +14,22 @@ export function hp_getIntegration() {
export async function hp_loadIntegration(
context: HeadplaneConfig['integration'],
) {
const integration = getIntegration(context);
if (!integration) {
return;
}
try {
const res = await integration.isAvailable();
if (!res) {
log.error('INTG', 'Integration %s is not available', integration);
return;
}
} catch (error) {
log.error('INTG', 'Failed to load integration %s: %s', integration, error);
log.debug('INTG', 'Loading error: %o', error);
return;
}
runtimeIntegration = integration;
// const integration = getIntegration(context);
// if (!integration) {
// return;
// }
// try {
// const res = await integration.isAvailable();
// if (!res) {
// log.error('INTG', 'Integration %s is not available', integration);
// return;
// }
// } catch (error) {
// log.error('INTG', 'Failed to load integration %s: %s', integration, error);
// log.debug('INTG', 'Loading error: %o', error);
// return;
// }
// runtimeIntegration = integration;
}
function getIntegration(integration: HeadplaneConfig['integration']) {
@@ -50,23 +47,23 @@ function getIntegration(integration: HeadplaneConfig['integration']) {
return;
}
if (docker?.enabled) {
log.info('INTG', 'Using Docker integration');
return new dockerIntegration(integration?.docker);
}
// if (docker?.enabled) {
// log.info('INTG', 'Using Docker integration');
// return new dockerIntegration(integration?.docker);
// }
if (k8s?.enabled) {
log.info('INTG', 'Using Kubernetes integration');
return new kubernetesIntegration(integration?.kubernetes);
}
// if (k8s?.enabled) {
// log.info('INTG', 'Using Kubernetes integration');
// return new kubernetesIntegration(integration?.kubernetes);
// }
if (proc?.enabled) {
log.info('INTG', 'Using Proc integration');
return new procIntegration(integration?.proc);
}
// if (proc?.enabled) {
// log.info('INTG', 'Using Proc integration');
// return new procIntegration(integration?.proc);
// }
}
// IMPORTANT THIS IS A SIDE EFFECT ON INIT
// TODO: Switch this to the new singleton system
const context = hp_getConfig();
hp_loadIntegration(context.integration);
// const context = hp_getConfig();
// hp_loadIntegration(context.integration);
+67
View File
@@ -0,0 +1,67 @@
import { createContext, useContext, useEffect, useState } from 'react';
import { useRevalidator } from 'react-router';
import { useInterval } from 'usehooks-ts';
const LiveDataPausedContext = createContext({
paused: false,
setPaused: (_: boolean) => {},
});
interface LiveDataProps {
children: React.ReactNode;
}
export function LiveDataProvider({ children }: LiveDataProps) {
const [paused, setPaused] = useState(false);
const revalidator = useRevalidator();
// Document is marked as optional here because it's not available in SSR
// The optional chain means if document is not defined, visible is false
const [visible, setVisible] = useState(
() =>
typeof document !== 'undefined' && document.visibilityState === 'visible',
);
// Function to revalidate safely
const revalidateIfIdle = () => {
if (revalidator.state === 'idle') {
revalidator.revalidate();
}
};
useEffect(() => {
const handleVisibilityChange = () => {
setVisible(document.visibilityState === 'visible');
if (!paused && document.visibilityState === 'visible') {
revalidateIfIdle();
}
};
window.addEventListener('online', revalidateIfIdle);
document.addEventListener('focus', revalidateIfIdle);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
window.removeEventListener('online', revalidateIfIdle);
document.removeEventListener('focus', revalidateIfIdle);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [paused, revalidator]);
// Poll only when visible and not paused
useInterval(revalidateIfIdle, visible && !paused ? 3000 : null);
return (
<LiveDataPausedContext.Provider value={{ paused, setPaused }}>
{children}
</LiveDataPausedContext.Provider>
);
}
export function useLiveData() {
const context = useContext(LiveDataPausedContext);
return {
pause: () => context.setPaused(true),
resume: () => context.setPaused(false),
};
}
+31
View File
@@ -0,0 +1,31 @@
// MARK: Side-Effects
// This module contains a side-effect because everything running here
// is static and logger is later modified in `app/server/index.ts` to
// disable debug logging if the `HEADPLANE_DEBUG_LOG` specifies as such.
const levels = ['info', 'warn', 'error', 'debug'] as const;
type Category = 'server' | 'config' | 'agent' | 'api' | 'auth';
export interface Logger
extends Record<
(typeof levels)[number],
(category: Category, message: string, ...args: unknown[]) => void
> {
debugEnabled: boolean;
}
export default {
debugEnabled: true,
...Object.fromEntries(
levels.map((level) => [
level,
(category: Category, message: string, ...args: unknown[]) => {
const date = new Date().toISOString();
console.log(
`${date} [${category}] ${level.toUpperCase()}: ${message}`,
...args,
);
},
]),
),
} as Logger;
-32
View File
@@ -1,32 +0,0 @@
class Mutex {
private locked = false;
private queue: (() => void)[] = [];
constructor(locked: boolean) {
this.locked = locked;
}
acquire() {
return new Promise<void>((resolve) => {
if (!this.locked) {
this.locked = true;
resolve();
} else {
this.queue.push(resolve);
}
});
}
release() {
if (this.queue.length > 0) {
const next = this.queue.shift();
next?.();
} else {
this.locked = false;
}
}
}
export default function mutex(locked = false) {
return new Mutex(locked);
}
+38 -140
View File
@@ -1,13 +1,6 @@
import { readFile } from 'node:fs/promises';
import * as client from 'openid-client';
import { hp_getSingleton, hp_setSingleton } from '~server/context/global';
import { HeadplaneConfig } from '~server/context/parser';
import log from '~server/utils/log';
type OidcConfig = NonNullable<HeadplaneConfig['oidc']>;
declare global {
const __PREFIX__: string;
}
import { Configuration, IDToken, UserInfoResponse } from 'openid-client';
import log from '~/utils/log';
// We try our best to infer the callback URI of our Headplane instance
// By default it is always /<base_path>/oidc/callback
@@ -37,74 +30,11 @@ export function getRedirectUri(req: Request) {
return url.href;
}
let oidcSecret: string | undefined = undefined;
export function getOidcSecret() {
return oidcSecret;
}
async function resolveClientSecret(oidc: OidcConfig) {
if (!oidc.client_secret && !oidc.client_secret_path) {
return;
}
if (oidc.client_secret_path) {
// We need to interpolate environment variables into the path
// Path formatting can be like ${ENV_NAME}/path/to/secret
let path = oidc.client_secret_path;
const matches = path.match(/\${(.*?)}/g);
if (matches) {
for (const match of matches) {
const env = match.slice(2, -1);
const value = process.env[env];
if (!value) {
log.error('CFGX', 'Environment variable %s is not set', env);
return;
}
log.debug('CFGX', 'Interpolating %s with %s', match, value);
path = path.replace(match, value);
}
}
try {
log.debug('CFGX', 'Reading client secret from %s', path);
const secret = await readFile(path, 'utf-8');
if (secret.trim().length === 0) {
log.error('CFGX', 'Empty OIDC client secret');
return;
}
oidcSecret = secret;
} catch (error) {
log.error('CFGX', 'Failed to read client secret from %s', path);
log.error('CFGX', 'Error: %s', error);
log.debug('CFGX', 'Error details: %o', error);
}
}
if (oidc.client_secret) {
oidcSecret = oidc.client_secret;
}
}
function clientAuthMethod(
method: string,
): (secret: string) => client.ClientAuth {
switch (method) {
case 'client_secret_post':
return client.ClientSecretPost;
case 'client_secret_basic':
return client.ClientSecretBasic;
case 'client_secret_jwt':
return client.ClientSecretJwt;
default:
throw new Error('Invalid client authentication method');
}
}
export async function beginAuthFlow(oidc: OidcConfig, redirect_uri: string) {
const config = hp_getSingleton('oidc_client');
export async function beginAuthFlow(
config: Configuration,
redirect_uri: string,
token_endpoint_auth_method: string,
) {
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
@@ -113,7 +43,7 @@ export async function beginAuthFlow(oidc: OidcConfig, redirect_uri: string) {
scope: 'openid profile email',
code_challenge: codeChallenge,
code_challenge_method: 'S256',
token_endpoint_auth_method: oidc.token_endpoint_auth_method,
token_endpoint_auth_method,
state: client.randomState(),
};
@@ -134,18 +64,20 @@ export async function beginAuthFlow(oidc: OidcConfig, redirect_uri: string) {
interface FlowOptions {
redirect_uri: string;
codeVerifier: string;
code_verifier: string;
state: string;
nonce?: string;
}
export async function finishAuthFlow(oidc: OidcConfig, options: FlowOptions) {
const config = hp_getSingleton('oidc_client');
export async function finishAuthFlow(
config: Configuration,
options: FlowOptions,
) {
const tokens = await client.authorizationCodeGrant(
config,
new URL(options.redirect_uri),
{
pkceCodeVerifier: options.codeVerifier,
pkceCodeVerifier: options.code_verifier,
expectedNonce: options.nonce,
expectedState: options.state,
idTokenExpected: true,
@@ -167,11 +99,34 @@ export async function finishAuthFlow(oidc: OidcConfig, options: FlowOptions) {
subject: user.sub,
name: getName(user, claims),
email: user.email ?? claims.email?.toString(),
username: user.preferred_username ?? claims.preferred_username?.toString(),
username: calculateUsername(claims, user),
picture: user.picture,
};
}
function calculateUsername(claims: IDToken, user: UserInfoResponse) {
if (user.preferred_username) {
return user.preferred_username;
}
if (
claims.preferred_username &&
typeof claims.preferred_username === 'string'
) {
return claims.preferred_username;
}
if (user.email) {
return user.email.split('@')[0];
}
if (claims.email && typeof claims.email === 'string') {
return claims.email.split('@')[0];
}
return;
}
function getName(user: client.UserInfoResponse, claims: client.IDToken) {
if (user.name) {
return user.name;
@@ -240,60 +195,3 @@ export function formatError(error: unknown) {
},
};
}
export async function testOidc(oidc: OidcConfig) {
await resolveClientSecret(oidc);
if (!oidcSecret) {
log.debug(
'OIDC',
'Cannot validate OIDC configuration without a client secret',
);
return false;
}
log.debug('OIDC', 'Discovering OIDC configuration from %s', oidc.issuer);
const secret = await resolveClientSecret(oidc);
const config = await client.discovery(
new URL(oidc.issuer),
oidc.client_id,
oidc.client_secret,
clientAuthMethod(oidc.token_endpoint_auth_method)(oidcSecret),
);
const meta = config.serverMetadata();
if (meta.authorization_endpoint === undefined) {
return false;
}
log.debug('OIDC', 'Authorization endpoint: %s', meta.authorization_endpoint);
log.debug('OIDC', 'Token endpoint: %s', meta.token_endpoint);
if (meta.response_types_supported) {
if (meta.response_types_supported.includes('code') === false) {
log.error('OIDC', 'OIDC server does not support code flow');
return false;
}
} else {
log.warn('OIDC', 'OIDC server does not advertise response_types_supported');
}
if (meta.token_endpoint_auth_methods_supported) {
if (
meta.token_endpoint_auth_methods_supported.includes(
oidc.token_endpoint_auth_method,
) === false
) {
log.error(
'OIDC',
'OIDC server does not support %s',
oidc.token_endpoint_auth_method,
);
return false;
}
}
log.debug('OIDC', 'OIDC configuration is valid');
hp_setSingleton('oidc_client', config);
return true;
}
-63
View File
@@ -1,63 +0,0 @@
import { Session, createCookieSessionStorage } from 'react-router';
import { hp_getConfig } from '~server/context/global';
export type SessionData = {
hsApiKey: string;
oidc_state: string;
oidc_code_verif: string;
oidc_nonce: string;
oidc_redirect_uri: string;
agent_onboarding: boolean;
user: {
subject: string;
name: string;
email?: string;
username?: string;
picture?: string;
};
};
type SessionFlashData = {
error: string;
};
// TODO: Domain config in cookies
// TODO: Move this to the singleton system
const context = hp_getConfig();
const sessionStorage = createCookieSessionStorage<
SessionData,
SessionFlashData
>({
cookie: {
name: 'hp_sess',
httpOnly: true,
maxAge: 60 * 60 * 24, // 24 hours
path: '/',
sameSite: 'lax',
secrets: [context.server.cookie_secret],
secure: context.server.cookie_secure,
},
});
export function getSession(cookie: string | null) {
return sessionStorage.getSession(cookie);
}
export type ServerSession = Session<SessionData, SessionFlashData>;
export async function auth(request: Request) {
const cookie = request.headers.get('Cookie');
const session = await sessionStorage.getSession(cookie);
if (!session.has('hsApiKey')) {
return false;
}
return session;
}
export function destroySession(session: Session) {
return sessionStorage.destroySession(session);
}
export function commitSession(session: Session, opts?: { maxAge?: number }) {
return sessionStorage.commitSession(session, opts);
}
-32
View File
@@ -1,32 +0,0 @@
import { useEffect, useMemo, useRef } from 'react';
import { useFetcher } from 'react-router';
import { HostInfo } from '~/types';
export default function useAgent(nodeIds: string[], interval = 3000) {
const fetcher = useFetcher<Record<string, HostInfo>>();
const qp = useMemo(
() => new URLSearchParams({ node_ids: nodeIds.join(',') }),
[nodeIds],
);
const idRef = useRef<string[]>([]);
useEffect(() => {
if (idRef.current.join(',') !== nodeIds.join(',')) {
fetcher.load(`/api/agent?${qp.toString()}`);
idRef.current = nodeIds;
}
const intervalID = setInterval(() => {
fetcher.load(`/api/agent?${qp.toString()}`);
}, interval);
return () => {
clearInterval(intervalID);
};
}, [interval, qp]);
return {
data: fetcher.data,
isLoading: fetcher.state === 'loading',
};
}
-35
View File
@@ -1,35 +0,0 @@
import { useRevalidator } from 'react-router';
import { useEffect } from 'react';
import { useInterval } from 'usehooks-ts';
interface Props {
interval: number;
}
export function useLiveData({ interval }: Props) {
const revalidator = useRevalidator();
// Handle normal stale-while-revalidate behavior
useInterval(() => {
if (revalidator.state === 'idle') {
revalidator.revalidate();
}
}, interval);
useEffect(() => {
const handler = () => {
if (revalidator.state === 'idle') {
revalidator.revalidate();
}
};
window.addEventListener('online', handler);
document.addEventListener('focus', handler);
return () => {
window.removeEventListener('online', handler);
document.removeEventListener('focus', handler);
};
}, [revalidator]);
return revalidator;
}
-158
View File
@@ -1,158 +0,0 @@
// Handlers for the Local Agent on the server side
import { readFile, writeFile } from 'node:fs/promises';
import { setTimeout as pSetTimeout } from 'node:timers/promises';
import type { LoaderFunctionArgs } from 'react-router';
import { WebSocket } from 'ws';
import type { HostInfo } from '~/types';
import log from '~server/utils/log';
// Essentially a HashMap which invalidates entries after a certain time.
// It also is capable of syncing as a compressed file to disk.
class TimedCache<K, V> {
private _cache = new Map<K, V>();
private _timeCache = new Map<K, number>();
private defaultTTL: number;
private filepath: string;
private writeLock = false;
constructor(defaultTTL: number, filepath: string) {
this.defaultTTL = defaultTTL;
this.filepath = filepath;
}
async set(key: K, value: V, ttl: number = this.defaultTTL) {
this._cache.set(key, value);
this._timeCache.set(key, Date.now() + ttl);
await this.syncToFile();
}
async get(key: K) {
const entry = this._cache.get(key);
if (!entry) {
return;
}
const expires = this._timeCache.get(key);
if (!expires || expires < Date.now()) {
this._cache.delete(key);
this._timeCache.delete(key);
await this.syncToFile();
return;
}
return entry;
}
async loadFromFile() {
try {
const data = await readFile(this.filepath, 'utf-8');
const cache = JSON.parse(data);
for (const { key, value, expires } of cache) {
this._cache.set(key, value);
this._timeCache.set(key, expires);
}
} catch (e) {
if (e.code === 'ENOENT') {
log.debug('CACH', 'Cache file not found, creating new cache');
return;
}
log.error('CACH', 'Failed to load cache from file', e);
}
}
private async syncToFile() {
while (this.writeLock) {
await pSetTimeout(100);
}
this.writeLock = true;
const data = Array.from(this._cache.entries()).map(([key, value]) => {
return { key, value, expires: this._timeCache.get(key) };
});
await writeFile(this.filepath, JSON.stringify(data), 'utf-8');
await this.loadFromFile();
this.writeLock = false;
}
}
let cache: TimedCache<string, HostInfo> | undefined;
export async function initAgentCache(defaultTTL: number, filepath: string) {
cache = new TimedCache(defaultTTL, filepath);
await pSetTimeout(500);
await cache.loadFromFile();
}
let agentSocket: WebSocket | undefined;
// TODO: Actually type this?
export function initAgentSocket(context: LoaderFunctionArgs['context']) {
if (!context.ws) {
return;
}
const client = context.ws.clients.values().next().value;
agentSocket = client;
}
// Check the cache and then attempt the websocket query
// If we aren't connected to an agent, then debug log and return the cache
export async function queryAgent(nodes: string[]) {
return;
if (!cache) {
log.error('CACH', 'Cache not initialized');
return;
}
const cached: Record<string, HostInfo> = {};
await Promise.all(
nodes.map(async (node) => {
const cachedData = await cache?.get(node);
if (cachedData) {
cached[node] = cachedData;
}
}),
);
const uncached = nodes.filter((node) => !cached[node]);
// No need to query the agent if we have all the data cached
if (uncached.length === 0) {
return cached;
}
// We don't have an agent socket, so we can't query the agent
// and we just return the cached values available instead
if (!agentSocket) {
return cached;
}
agentSocket?.send(JSON.stringify({ NodeIDs: uncached }));
// biome-ignore lint: bruh
const returnData = await new Promise<Record<string, HostInfo> | void>(
(resolve, reject) => {
const timeout = setTimeout(() => {
agentSocket?.removeAllListeners('message');
resolve();
}, 3000);
agentSocket?.on('message', async (message: string) => {
const data = JSON.parse(message.toString());
if (Object.keys(data).length === 0) {
resolve();
}
agentSocket?.removeAllListeners('message');
resolve(data);
});
},
);
// if (returnData) {
// for await (const [node, info] of Object.entries(returnData)) {
// await cache?.set(node, info);
// }
// }
return returnData ? { ...cached, ...returnData } : cached;
}
+86 -82
View File
@@ -1,107 +1,111 @@
# Configuration for the Headplane server and web application
server:
host: "0.0.0.0"
port: 3000
host: "0.0.0.0"
port: 3000
# The secret used to encode and decode web sessions
# Ensure that this is exactly 32 characters long
cookie_secret: "<change_me_to_something_secure!>"
# The secret used to encode and decode web sessions
# Ensure that this is exactly 32 characters long
cookie_secret: "<change_me_to_something_secure!>"
# Should the cookies only work over HTTPS?
# Set to false if running via HTTP without a proxy
# (I recommend this is true in production)
cookie_secure: true
# Should the cookies only work over HTTPS?
# Set to false if running via HTTP without a proxy
# (I recommend this is true in production)
cookie_secure: true
# Headscale specific settings to allow Headplane to talk
# to Headscale and access deep integration features
headscale:
# The URL to your Headscale instance
# (All API requests are routed through this URL)
# (THIS IS NOT the gRPC endpoint, but the HTTP endpoint)
#
# IMPORTANT: If you are using TLS this MUST be set to `https://`
url: "http://headscale:5000"
# The URL to your Headscale instance
# (All API requests are routed through this URL)
# (THIS IS NOT the gRPC endpoint, but the HTTP endpoint)
#
# IMPORTANT: If you are using TLS this MUST be set to `https://`
url: "http://headscale:5000"
# If you use the TLS configuration in Headscale, and you are not using
# Let's Encrypt for your certificate, pass in the path to the certificate.
# (This has no effect `url` does not start with `https://`)
# tls_cert_path: "/var/lib/headplane/tls.crt"
# If you use the TLS configuration in Headscale, and you are not using
# Let's Encrypt for your certificate, pass in the path to the certificate.
# (This has no effect `url` does not start with `https://`)
# tls_cert_path: "/var/lib/headplane/tls.crt"
# Optional, public URL if they differ
# This affects certain parts of the web UI
# public_url: "https://headscale.example.com"
# Optional, public URL if they differ
# This affects certain parts of the web UI
# public_url: "https://headscale.example.com"
# Path to the Headscale configuration file
# This is optional, but HIGHLY recommended for the best experience
# If this is read only, Headplane will show your configuration settings
# in the Web UI, but they cannot be changed.
config_path: "/etc/headscale/config.yaml"
# Path to the Headscale configuration file
# This is optional, but HIGHLY recommended for the best experience
# If this is read only, Headplane will show your configuration settings
# in the Web UI, but they cannot be changed.
config_path: "/etc/headscale/config.yaml"
# Headplane internally validates the Headscale configuration
# to ensure that it changes the configuration in a safe way.
# If you want to disable this validation, set this to false.
config_strict: true
# Headplane internally validates the Headscale configuration
# to ensure that it changes the configuration in a safe way.
# If you want to disable this validation, set this to false.
config_strict: true
# Integration configurations for Headplane to interact with Headscale
# Only one of these should be enabled at a time or you will get errors
integration:
docker:
enabled: false
# The name (or ID) of the container running Headscale
container_name: "headscale"
# The path to the Docker socket (do not change this if you are unsure)
# Docker socket paths must start with unix:// or tcp:// and at the moment
# https connections are not supported.
socket: "unix:///var/run/docker.sock"
# Please refer to docs/integration/Kubernetes.md for more information
# on how to configure the Kubernetes integration. There are requirements in
# order to allow Headscale to be controlled by Headplane in a cluster.
kubernetes:
enabled: false
# Validates the manifest for the Pod to ensure all of the criteria
# are set correctly. Turn this off if you are having issues with
# shareProcessNamespace not being validated correctly.
validate_manifest: true
# This should be the name of the Pod running Headscale and Headplane.
# If this isn't static you should be using the Kubernetes Downward API
# to set this value (refer to docs/Integrated-Mode.md for more info).
pod_name: "headscale"
docker:
enabled: false
# The name (or ID) of the container running Headscale
container_name: "headscale"
# The path to the Docker socket (do not change this if you are unsure)
# Docker socket paths must start with unix:// or tcp:// and at the moment
# https connections are not supported.
socket: "unix:///var/run/docker.sock"
# Please refer to docs/integration/Kubernetes.md for more information
# on how to configure the Kubernetes integration. There are requirements in
# order to allow Headscale to be controlled by Headplane in a cluster.
kubernetes:
enabled: false
# Validates the manifest for the Pod to ensure all of the criteria
# are set correctly. Turn this off if you are having issues with
# shareProcessNamespace not being validated correctly.
validate_manifest: true
# This should be the name of the Pod running Headscale and Headplane.
# If this isn't static you should be using the Kubernetes Downward API
# to set this value (refer to docs/Integrated-Mode.md for more info).
pod_name: "headscale"
# Proc is the "Native" integration that only works when Headscale and
# Headplane are running outside of a container. There is no configuration,
# but you need to ensure that the Headplane process can terminate the
# Headscale process.
#
# (If they are both running under systemd as sudo, this will work).
proc:
enabled: false
# Proc is the "Native" integration that only works when Headscale and
# Headplane are running outside of a container. There is no configuration,
# but you need to ensure that the Headplane process can terminate the
# Headscale process.
#
# (If they are both running under systemd as sudo, this will work).
proc:
enabled: false
# OIDC Configuration for simpler authentication
# (This is optional, but recommended for the best experience)
oidc:
issuer: "https://accounts.google.com"
client_id: "your-client-id"
issuer: "https://accounts.google.com"
client_id: "your-client-id"
# The client secret for the OIDC client
# Either this or `client_secret_path` must be set for OIDC to work
client_secret: "<your-client-secret>"
# You can alternatively set `client_secret_path` to read the secret from disk.
# The path specified can resolve environment variables, making integration
# with systemd's `LoadCredential` straightforward:
# client_secret_path: "${CREDENTIALS_DIRECTORY}/oidc_client_secret"
# The client secret for the OIDC client
# Either this or `client_secret_path` must be set for OIDC to work
client_secret: "<your-client-secret>"
# You can alternatively set `client_secret_path` to read the secret from disk.
# The path specified can resolve environment variables, making integration
# with systemd's `LoadCredential` straightforward:
# client_secret_path: "${CREDENTIALS_DIRECTORY}/oidc_client_secret"
disable_api_key_login: false
token_endpoint_auth_method: "client_secret_post"
disable_api_key_login: false
token_endpoint_auth_method: "client_secret_post"
# If you are using OIDC, you need to generate an API key
# that can be used to authenticate other sessions when signing in.
#
# This can be done with `headscale apikeys create --expiration 999d`
headscale_api_key: "<your-headscale-api-key>"
# If you are using OIDC, you need to generate an API key
# that can be used to authenticate other sessions when signing in.
#
# This can be done with `headscale apikeys create --expiration 999d`
headscale_api_key: "<your-headscale-api-key>"
# Optional, but highly recommended otherwise Headplane
# will attempt to automatically guess this from the issuer
#
# This should point to your publicly accessibly URL
# for your Headplane instance with /admin/oidc/callback
redirect_uri: "http://localhost:3000/admin/oidc/callback"
# Optional, but highly recommended otherwise Headplane
# will attempt to automatically guess this from the issuer
#
# This should point to your publicly accessibly URL
# for your Headplane instance with /admin/oidc/callback
redirect_uri: "http://localhost:3000/admin/oidc/callback"
# Stores the users and their permissions for Headplane
# This is a path to a JSON file, default is specified below.
user_storage_file: "/var/lib/headplane/users.json"
+1
View File
@@ -20,6 +20,7 @@ Clone the Headplane repository, install dependencies, and build the project:
```sh
git clone https://github.com/tale/headplane
cd headplane
git checkout v0.5.5 # Or whatever tag you want to use
pnpm install
pnpm build
```
+47
View File
@@ -0,0 +1,47 @@
# Contributing to Headplane
Thank you for your interest in contributing to Headplane. I maintain this
project entirely on my own so any help is greatly appreciated. Since I am the
sole maintainer, I have a few guidelines which help make it significantly easier
for me to review and merge your contributions.
## Contribution Types
- **Bug Reports/Feature Requests**: If you find a bug, please open an
[issue](https://github.com/tale/headplane/issues) using one of the predefined
templates. Issues are only for bug reports and feature requests, not problems
that you encounter from misconfiguration or usage. Those belong in the
[discussions](https://github.com/tale/headplane/discussions) section.
- **Documentation/Examples**: If you find any issues in the documentation or
would like to contribute examples for setting up Headplane, please open a PR
and I will review it and possibly make changes.
- **Code Contributions**: Code contributions are done via PRs but *must* be
linked to an issue or a feature request (you can make one if it doesn't exist).
Please tag them with the appropriate labels when opening an issue or PR.
### Code Contribution Restrictions
- **No Large Refactors**: I am not interested in large refactors of the codebase
because I've already had do to this a lot and it becomes a headache to review,
maintain, and merge. This also means you should split up multiple contributions
into multiple PRs if they are unrelated to each other.
- **No Project/Tooling Changes**: Unless there is a very good reason to do so,
I will not accept changes to the project structure, build system, or tooling
used to develop Headplane. This includes things like changing the package
manager, docker environment, or CI/CD.
- **Minimal Breaking Changes**: I will not accept any changes that break any
existing functionality or change the API unless there is a very good reason
to do so. If you want to make a breaking change, please open an issue first
and discuss it with me.
### Code Style
This is very easy and self-explanatory. [Biome](https://biomejs.dev) is used as
a linter and formatter for the TypeScript, while Go's default formatting and
lint tooling are used within `agent/` code. I've setup a git hook to run
before commit to make these changes automatically.
> All of these guidelines are fairly simple to follow and are flexible if needed.
> I won't automatically close PRs or issues if they don't follow these rules,
> but instead we can discuss them and see if we can come to a compromise.
+3
View File
@@ -22,6 +22,9 @@ Here are a few more examples:
**This functionality is NOT enabled by default!**
To enable it, set the environment variable **`HEADPLANE_LOAD_ENV_OVERRIDES=true`**.
Setting this also tells Headplane to load the relative `.env` file into the environment.
> Also note that this is **only** for configuration overrides, not for general
> environment variables meaning you cannot specify variables such as
> `HEADPLANE_DEBUG_LOG=true` or `HEADPLANE_CONFIG_PATH=/etc/headplane/config.yaml`.
## Debugging
To enable debug logging, set the **`HEADPLANE_DEBUG_LOG=true`** environment variable.
+9
View File
@@ -0,0 +1,9 @@
# Reporting Security Issues
If you discover a security vulnerability within Headplane, please report it
directly via the GitHub security advisory system. Please include as much
information as possible, what the implications are, and a deterministic way
to reproduce the issue. This will help me to quickly assess and address the
vulnerability.
> [Open a New Vulnerability Report](https://github.com/tale/headplane/security/advisories/new)
+4 -7
View File
@@ -23,26 +23,23 @@ stdenv.mkDerivation (finalAttrs: {
pnpmDeps = pnpm_10.fetchDeps {
inherit (finalAttrs) pname version src;
hash = "sha256-j+3fcxukK19fXVIlVe+tXenYf28MylHy+/qHy7FpvL0=";
hash = "sha256-GtpwQz7ngLpP+BubH6uaG1uUZsZdCQzvTI1WKBYU2T4=";
};
buildPhase = ''
runHook preBuild
pnpm build
pnpm prune --prod
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out/{bin,share/headplane}
cp -r {build,node_modules} $out/share/headplane/
sed -i "s;$PWD;../..;" $out/share/headplane/build/headplane/server.js
cp -r build $out/share/headplane/
sed -i "s;$PWD;../..;" $out/share/headplane/build/server/index.js
makeWrapper ${lib.getExe nodejs_22} $out/bin/headplane \
--chdir $out/share/headplane \
--set BUILD_PATH $out/share/headplane/build \
--set NODE_ENV production \
--add-flags $out/share/headplane/build/headplane/server.js
--add-flags $out/share/headplane/build/server/index.js
runHook postInstall
'';
})
+17 -13
View File
@@ -2,12 +2,12 @@
"name": "headplane",
"private": true,
"sideEffects": false,
"version": "0.5.4",
"version": "0.5.6",
"type": "module",
"scripts": {
"build": "react-router build && vite build -c server/vite.config.ts",
"dev": "HEADPLANE_LOAD_ENV_OVERRIDES=true vite-node -w -c server/vite.config.ts server/entry.ts",
"start": "node build/headplane/server.js",
"build": "react-router build",
"dev": "HEADPLANE_LOAD_ENV_OVERRIDES=true HEADPLANE_CONFIG_PATH=./config.example.yaml react-router dev",
"start": "node build/server/index.js",
"typecheck": "tsc"
},
"dependencies": {
@@ -16,10 +16,11 @@
"@dnd-kit/sortable": "^8.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.1.1",
"@hono/node-server": "^1.14.0",
"@kubernetes/client-node": "^0.22.3",
"@primer/octicons-react": "^19.14.0",
"@react-aria/toast": "3.0.0-beta.18",
"@react-router/node": "^7.0.0",
"@react-router/node": "^7.4.0",
"@react-stately/toast": "3.0.0-beta.7",
"@shopify/lang-jsonc": "^1.0.0",
"@types/react": "^19.0.2",
@@ -39,7 +40,9 @@
"react-codemirror-merge": "^4.23.7",
"react-dom": "19.0.0",
"react-error-boundary": "^5.0.0",
"react-router": "^7.0.0",
"react-icons": "^5.5.0",
"react-router": "^7.4.0",
"react-router-hono-server": "^2.11.0",
"react-stately": "^3.35.0",
"remix-utils": "^8.0.0",
"tailwind-merge": "^2.6.0",
@@ -52,20 +55,20 @@
"devDependencies": {
"@babel/preset-typescript": "^7.26.0",
"@biomejs/biome": "^1.9.4",
"@react-router/dev": "^7.0.0",
"@react-router/dev": "^7.4.0",
"@types/websocket": "^1.0.10",
"@types/ws": "^8.5.13",
"autoprefixer": "^10.4.20",
"autoprefixer": "^10.4.21",
"babel-plugin-react-compiler": "19.0.0-beta-55955c9-20241229",
"lefthook": "^1.10.9",
"postcss": "^8.4.49",
"react-router-dom": "^7.1.1",
"postcss": "^8.5.3",
"react-router-dom": "^7.4.0",
"react-scan": "^0.1.0",
"tailwindcss": "^3.4.17",
"tailwindcss-animate": "^1.0.7",
"tailwindcss-react-aria-components": "^2.0.0",
"typescript": "^5.7.2",
"vite": "^6.0.6",
"typescript": "^5.8.2",
"vite": "^6.2.2",
"vite-node": "^3.0.8",
"vite-plugin-babel": "^1.3.0",
"vite-tsconfig-paths": "^5.1.4"
@@ -76,7 +79,8 @@
},
"pnpm": {
"patchedDependencies": {
"@shopify/lang-jsonc@1.0.0": "patches/@shopify__lang-jsonc@1.0.0.patch"
"@shopify/lang-jsonc@1.0.0": "patches/@shopify__lang-jsonc@1.0.0.patch",
"react-router-hono-server": "patches/react-router-hono-server.patch"
}
}
}
+27
View File
@@ -0,0 +1,27 @@
diff --git a/dist/adapters/node.d.ts b/dist/adapters/node.d.ts
index 68742808892c1282ccff1e3321167862196d1229..f9a9249e1d1e573018d7ff3d3b967c4a1667d6ca 100644
--- a/dist/adapters/node.d.ts
+++ b/dist/adapters/node.d.ts
@@ -50,6 +50,10 @@ interface HonoNodeServerOptions<E extends Env = BlankEnv> extends HonoServerOpti
/**
* Callback executed just after `serve` from `@hono/node-server`
*/
+ /**
+ * Customize the hostname of the node server
+ */
+ hostname?: string;
onServe?: (server: ServerType) => void;
/**
* The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
diff --git a/dist/adapters/node.js b/dist/adapters/node.js
index 481dec801537f6ccf7f7a8a8e2294f4b0f20bb7d..0fbc43c3a345b341a08e8179ea0eabfaca62e3b3 100644
--- a/dist/adapters/node.js
+++ b/dist/adapters/node.js
@@ -86,6 +86,7 @@ async function createHonoServer(options) {
...app,
...mergedOptions.customNodeServer,
port: mergedOptions.port,
+ hostname: mergedOptions.hostname,
overrideGlobalObjects: mergedOptions.overrideGlobalObjects
},
mergedOptions.listeningListener
+824 -388
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -3,4 +3,8 @@ import type { Config } from '@react-router/dev/config';
export default {
basename: '/admin/',
ssr: true,
future: {
unstable_optimizeDeps: true,
unstable_splitRouteModules: 'enforce',
},
} satisfies Config;
-11
View File
@@ -1,11 +0,0 @@
import { hp_agentRequest } from '~server/ws/data';
export interface AppContext {
hp_agentRequest: typeof hp_agentRequest;
}
export default function appContext(): AppContext {
return {
hp_agentRequest,
};
}
-85
View File
@@ -1,85 +0,0 @@
import type { Configuration } from 'openid-client';
import type { Agent } from 'undici';
import type { WebSocket } from 'ws';
import type { HostInfo } from '~/types';
import type { HeadplaneConfig } from '~server/context/parser';
import type { Logger } from '~server/utils/log';
import type { TimedCache } from '~server/ws/cache';
// This is a stupid workaround for how the Remix import context works
// Even though they run in the same Node instance, they have different
// contexts which means importing this in the app code will not work
// because it will be a different instance of the module.
//
// Instead we can rely on globalThis to share the module between the
// different contexts and use some helper functions to make it easier.
// As a part of this global module, we also define all our singletons
// here in order to avoid polluting the global scope and instead just using
// the `__headplane_server_context` object.
interface ServerContext {
config: HeadplaneConfig;
singletons: ServerSingletons;
}
interface ServerSingletons {
api_agent: Agent;
logger: Logger;
oidc_client: Configuration;
ws_agents: Map<string, WebSocket>;
ws_agent_data: TimedCache<HostInfo>;
ws_fetch_data: (nodeList: string[]) => Promise<void>;
}
// These declarations are separate to prevent the Remix context
// from modifying the globalThis object and causing issues with
// the server context.
declare namespace globalThis {
let __headplane_server_context: {
[K in keyof ServerContext]: ServerContext[K] | null | object;
};
}
// We need to check if the context is already initialized and set a default
// value. This is fine as a side-effect since it's just setting up a framework
// for the object to get modified later.
if (!globalThis.__headplane_server_context) {
globalThis.__headplane_server_context = {
config: null,
singletons: {},
};
}
declare global {
const __headplane_server_context: ServerContext;
}
export function hp_getConfig(): HeadplaneConfig {
return __headplane_server_context.config;
}
export function hp_setConfig(config: HeadplaneConfig): void {
__headplane_server_context.config = config;
}
export function hp_getSingleton<T extends keyof ServerSingletons>(
key: T,
): ServerSingletons[T] {
if (!__headplane_server_context.singletons[key]) {
throw new Error(`Singleton ${key} not initialized`);
}
return __headplane_server_context.singletons[key];
}
export function hp_getSingletonUnsafe<T extends keyof ServerSingletons>(
key: T,
): ServerSingletons[T] | undefined {
return __headplane_server_context.singletons[key];
}
export function hp_setSingleton<
T extends ServerSingletons[keyof ServerSingletons],
>(key: keyof ServerSingletons, value: T): void {
(__headplane_server_context.singletons[key] as T) = value;
}
-252
View File
@@ -1,252 +0,0 @@
import { constants, access, readFile } from 'node:fs/promises';
import { env } from 'node:process';
import { type } from 'arktype';
import dotenv from 'dotenv';
import { Agent } from 'undici';
import { parseDocument } from 'yaml';
import { testOidc } from '~/utils/oidc';
import log, { hp_loadLogger } from '~server/utils/log';
import mutex from '~server/utils/mutex';
import { hp_setConfig, hp_setSingleton } from './global';
import { HeadplaneConfig, coalesceConfig, validateConfig } from './parser';
const envBool = type('string | undefined').pipe((v) => {
return ['1', 'true', 'yes', 'on'].includes(v?.toLowerCase() ?? '');
});
const rootEnvs = type({
HEADPLANE_DEBUG_LOG: envBool,
HEADPLANE_LOAD_ENV_OVERRIDES: envBool,
HEADPLANE_CONFIG_PATH: 'string | undefined',
}).onDeepUndeclaredKey('reject');
const HEADPLANE_DEFAULT_CONFIG_PATH = '/etc/headplane/config.yaml';
const runtimeLock = mutex();
// hp_loadConfig should ONLY be called when we explicitly need to reload
// the configuration. This should be done when the configuration file
// changes and we ignore environment variable changes.
//
// TODO: File watching for hp_loadConfig()
export async function hp_loadConfig() {
runtimeLock.acquire();
let path = HEADPLANE_DEFAULT_CONFIG_PATH;
const envs = rootEnvs({
HEADPLANE_DEBUG_LOG: env.HEADPLANE_DEBUG_LOG,
HEADPLANE_CONFIG_PATH: env.HEADPLANE_CONFIG_PATH,
HEADPLANE_LOAD_ENV_OVERRIDES: env.HEADPLANE_LOAD_ENV_OVERRIDES,
});
if (envs instanceof type.errors) {
log.error('CFGX', 'Error parsing environment variables:');
for (const [number, error] of envs.entries()) {
log.error('CFGX', ` (${number}): ${error.toString()}`);
}
return;
}
// Load our debug based logger before ANYTHING
await hp_loadLogger(envs.HEADPLANE_DEBUG_LOG);
if (envs.HEADPLANE_CONFIG_PATH) {
path = envs.HEADPLANE_CONFIG_PATH;
}
await validateConfigPath(path);
const rawConfig = await loadConfigFile(path);
if (!rawConfig) {
log.error('CFGX', 'Failed to load Headplane configuration file');
process.exit(1);
}
let config = validateConfig({
...rawConfig,
debug: envs.HEADPLANE_DEBUG_LOG,
});
if (config && envs.HEADPLANE_LOAD_ENV_OVERRIDES) {
log.info('CFGX', 'Loading a .env file if one exists');
dotenv.config();
log.info(
'CFGX',
'Loading environment variables to override the configuration',
);
config = coalesceEnv(config);
}
if (!config) {
runtimeLock.release();
log.error('CFGX', 'Fatal error encountered with configuration');
process.exit(1);
}
// OIDC Related Checks
if (config.oidc) {
if (!config.oidc.client_secret && !config.oidc.client_secret_path) {
log.error('CFGX', 'OIDC configuration is missing a secret, disabling');
log.error(
'CFGX',
'Please specify either `oidc.client_secret` or `oidc.client_secret_path`',
);
}
if (config.oidc?.strict_validation) {
const result = await testOidc(config.oidc);
if (!result) {
log.error('CFGX', 'OIDC configuration failed validation, disabling');
}
}
}
if (config.headscale.tls_cert_path) {
log.debug('CFGX', 'Attempting to load supplied Headscale TLS cert');
try {
const data = await readFile(config.headscale.tls_cert_path, 'utf8');
log.info('CFGX', 'Headscale TLS cert loaded successfully');
hp_setSingleton(
'api_agent',
new Agent({
connect: {
ca: data.trim(),
},
}),
);
} catch (error) {
log.error('CFGX', 'Failed to load Headscale TLS cert');
log.debug('CFGX', 'Error Details: %o', error);
}
} else {
hp_setSingleton('api_agent', new Agent());
}
hp_setConfig(config);
runtimeLock.release();
}
async function validateConfigPath(path: string) {
log.debug('CFGX', `Validating Headplane configuration file at ${path}`);
try {
await access(path, constants.F_OK | constants.R_OK);
log.info('CFGX', `Headplane configuration found at ${path}`);
return true;
} catch (e) {
log.error('CFGX', `Headplane configuration not readable at ${path}`);
log.error('CFGX', `${e}`);
return false;
}
}
async function loadConfigFile(path: string) {
log.debug('CFGX', `Loading Headplane configuration file at ${path}`);
try {
const data = await readFile(path, 'utf8');
const configYaml = parseDocument(data);
if (configYaml.errors.length > 0) {
log.error(
'CFGX',
`Error parsing Headplane configuration file at ${path}`,
);
for (const error of configYaml.errors) {
log.error('CFGX', ` ${error.toString()}`);
}
return;
}
if (configYaml.warnings.length > 0) {
log.warn(
'CFGX',
`Warnings parsing Headplane configuration file at ${path}`,
);
for (const warning of configYaml.warnings) {
log.warn('CFGX', ` ${warning.toString()}`);
}
}
return configYaml.toJSON() as unknown;
} catch (e) {
log.error('CFGX', `Error reading Headplane configuration file at ${path}`);
log.error('CFGX', `${e}`);
return;
}
}
function coalesceEnv(config: HeadplaneConfig) {
const envConfig: Record<string, unknown> = {};
const rootKeys: string[] = rootEnvs.props.map((prop) => prop.key);
// Typescript is still insanely stupid at nullish filtering
const vars = Object.entries(env).filter(([key, value]) => {
if (!value) {
return false;
}
if (!key.startsWith('HEADPLANE_')) {
return false;
}
// Filter out the rootEnv configurations
if (rootKeys.includes(key)) {
return false;
}
return true;
}) as [string, string][];
log.debug('CFGX', `Coalescing ${vars.length} environment variables`);
for (const [key, value] of vars) {
const configPath = key.replace('HEADPLANE_', '').toLowerCase().split('__');
log.debug('CFGX', ` ${key}=${new Array(value.length).fill('*').join('')}`);
let current = envConfig;
while (configPath.length > 1) {
const path = configPath.shift() as string;
if (!(path in current)) {
current[path] = {};
}
current = current[path] as Record<string, unknown>;
}
current[configPath[0]] = value;
}
const toMerge = coalesceConfig(envConfig);
if (!toMerge) {
return;
}
// Deep merge the environment variables into the configuration
// This will overwrite any existing values in the configuration
return deepMerge(config, toMerge);
}
type DeepPartial<T> =
| {
[P in keyof T]?: DeepPartial<T[P]>;
}
| undefined;
function deepMerge<T>(target: T, source: DeepPartial<T>): T {
if (typeof target !== 'object' || typeof source !== 'object')
return source as T;
const result = { ...target } as T;
for (const key in source) {
const val = source[key];
if (val === undefined) {
continue;
}
if (typeof val === 'object') {
result[key] = deepMerge(result[key], val);
continue;
}
result[key] = val;
}
return result;
}
-7
View File
@@ -1,7 +0,0 @@
import { createRequestHandler } from 'react-router';
export default createRequestHandler(
// @ts-expect-error: React Router Vite plugin
() => import('virtual:react-router/server-build'),
'development',
);
-56
View File
@@ -1,56 +0,0 @@
import { type ViteDevServer, createServer } from 'vite';
import log from '~server/utils/log';
// TODO: Remove env.NODE_ENV
let server: ViteDevServer | undefined;
export async function loadDevtools() {
log.info('DEVX', 'Starting Vite Development server');
process.env.NODE_ENV = 'development';
// This is loading the ROOT vite.config.ts
server = await createServer({
server: {
middlewareMode: true,
},
});
// We can't just do ssrLoadModule for virtual:react-router/server-build
// because for hot reload to work server side it needs to be imported
// using builtin import in its own file.
const handler = await server.ssrLoadModule('./server/dev/dev-handler.ts');
return {
server,
handler: handler.default,
};
}
export async function stacksafeTry(
devtools: {
server: ViteDevServer;
handler: (req: Request, context: unknown) => Promise<Response>;
},
req: Request,
context: unknown,
) {
try {
const result = await devtools.handler(req, context);
return result;
} catch (error) {
log.error('DEVX', 'Error in request handler', error);
if (typeof error === 'object' && error instanceof Error) {
devtools.server.ssrFixStacktrace(error);
}
throw error;
}
}
if (import.meta.hot) {
import.meta.hot.on('vite:beforeFullReload', () => {
server?.close();
});
import.meta.hot.dispose(() => {
server?.close();
});
}
-52
View File
@@ -1,52 +0,0 @@
import { constants, access } from 'node:fs/promises';
import { createServer } from 'node:http';
import { WebSocketServer } from 'ws';
import { hp_getConfig } from '~server/context/global';
import { hp_loadConfig } from '~server/context/loader';
import { listener } from '~server/listener';
import { hp_loadAgentCache } from '~server/ws/data';
import { initWebsocket } from '~server/ws/socket';
import log from './utils/log';
log.info('SRVX', 'Running Node.js %s', process.versions.node);
try {
await access('./node_modules/react-router', constants.F_OK | constants.R_OK);
log.info('SRVX', 'Found dependencies');
} catch (error) {
log.error('SRVX', 'No dependencies found. Please run `npm install`');
console.error(error);
process.exit(1);
}
await hp_loadConfig();
const server = createServer(listener);
const context = hp_getConfig();
if (context.server.agent.authkey.length > 0) {
const ws = new WebSocketServer({ server });
initWebsocket(ws, context.server.agent.authkey);
await hp_loadAgentCache(
context.server.agent.ttl,
context.server.agent.cache_path,
);
}
server.listen(context.server.port, context.server.host, () => {
log.info(
'SRVX',
'Running on %s:%s',
context.server.host,
context.server.port,
);
});
if (import.meta.hot) {
import.meta.hot.on('vite:beforeFullReload', () => {
server.close();
});
import.meta.hot.dispose(() => {
server.close();
});
}
-149
View File
@@ -1,149 +0,0 @@
import { createReadStream, existsSync, statSync } from 'node:fs';
import { type RequestListener } from 'node:http';
import { join, resolve } from 'node:path';
import {
createReadableStreamFromReadable,
writeReadableStreamToWritable,
} from '@react-router/node';
import mime from 'mime/lite';
import type { RequestHandler } from 'react-router';
import type { ViteDevServer } from 'vite';
import appContext from '~server/context/app';
import { loadDevtools, stacksafeTry } from '~server/dev/hot-server';
import prodBuild from '~server/prod-handler';
import { hp_loadConfig } from './context/loader';
declare global {
// Prefix is a build-time constant
const __hp_prefix: string;
}
// biome-ignore lint/suspicious/noExplicitAny: Who cares man
let devtools: { server: ViteDevServer; handler: any } | undefined = undefined;
let prodHandler: RequestHandler | undefined = undefined;
let loaded = false;
async function loadGlobals() {
await hp_loadConfig();
devtools = import.meta.env.DEV ? await loadDevtools() : undefined;
prodHandler = import.meta.env.PROD ? await prodBuild() : undefined;
loaded = true;
}
const baseDir = resolve(join('./build', 'client'));
export const listener: RequestListener = async (req, res) => {
if (!loaded) {
await loadGlobals();
}
const url = new URL(`http://${req.headers.host}${req.url}`);
// build:strip
if (devtools) {
await new Promise((resolve) => {
devtools?.server.middlewares(req, res, resolve);
});
}
if (!url.pathname.startsWith(__hp_prefix)) {
res.writeHead(404);
res.end();
return;
}
// We need to handle an issue where say we are navigating to $PREFIX
// but Remix does not handle it without the trailing slash. This is
// because Remix uses the URL constructor to parse the URL and it
// will remove the trailing slash. We need to redirect to the correct
// URL so that Remix can handle it correctly.
if (url.pathname === __hp_prefix) {
res.writeHead(301, {
Location: `${__hp_prefix}/`,
});
res.end();
return;
}
// Before we pass any requests to our Remix handler we need to check
// if we can handle a raw file request. This is important for the
// Remix loader to work correctly.
//
// To optimize this, we send them as readable streams in the node
// response and we also set headers for aggressive caching.
if (url.pathname.startsWith(`${__hp_prefix}/assets/`)) {
const filePath = join(baseDir, url.pathname.slice(__hp_prefix.length));
const exists = existsSync(filePath);
const stats = exists ? statSync(filePath) : null;
if (exists && stats && stats.isFile()) {
// Build assets are cache-bust friendly so we can cache them heavily
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
// Send the file as a readable stream
const fileStream = createReadStream(filePath);
const type = mime.getType(filePath);
res.writeHead(200, {
'Content-Type': type || 'application/octet-stream',
});
fileStream.pipe(res);
return;
}
// Handling the request
const controller = new AbortController();
res.on('close', () => controller.abort());
const headers = new Headers();
for (const [key, value] of Object.entries(req.headers)) {
if (!value) continue;
if (Array.isArray(value)) {
for (const v of value) {
headers.append(key, v);
}
continue;
}
headers.append(key, value);
}
const frameworkReq = new Request(url.href, {
headers,
method: req.method,
signal: controller.signal,
// If we have a body, we set the duplex and load it
...(req.method !== 'GET' && req.method !== 'HEAD'
? {
body: createReadableStreamFromReadable(req),
duplex: 'half',
}
: {}),
});
const response = devtools
? await stacksafeTry(devtools, frameworkReq, appContext())
: await prodHandler?.(frameworkReq, appContext());
if (!response) {
res.writeHead(404);
res.end();
return;
}
res.statusCode = response.status;
res.statusMessage = response.statusText;
for (const [key, value] of response.headers.entries()) {
res.appendHeader(key, value);
}
if (response.body) {
await writeReadableStreamToWritable(response.body, res);
}
res.end();
};
-26
View File
@@ -1,26 +0,0 @@
import { constants, access } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { createRequestHandler } from 'react-router';
import log from '~server/utils/log';
export default async function () {
const buildPath = process.env.BUILD_PATH ?? './build';
const server = resolve(join(buildPath, 'server'));
try {
await access(server, constants.F_OK | constants.R_OK);
log.info('SRVX', 'Using build directory %s', resolve(buildPath));
} catch (error) {
log.error('SRVX', 'No build found. Please refer to the documentation');
log.error(
'SRVX',
'https://github.com/tale/headplane/blob/main/docs/integration/Native.md',
);
console.error(error);
process.exit(1);
}
// @vite-ignore
const build = await import(resolve(join(server, 'index.js')));
return createRequestHandler(build, 'production');
}
-61
View File
@@ -1,61 +0,0 @@
import {
hp_getSingleton,
hp_getSingletonUnsafe,
hp_setSingleton,
} from '~server/context/global';
export interface Logger {
info: (category: string, message: string, ...args: unknown[]) => void;
warn: (category: string, message: string, ...args: unknown[]) => void;
error: (category: string, message: string, ...args: unknown[]) => void;
debug: (category: string, message: string, ...args: unknown[]) => void;
}
export function hp_loadLogger(debug: boolean) {
const newLog = { ...log };
if (debug) {
newLog.debug = (category: string, message: string, ...args: unknown[]) => {
defaultLog('DEBG', category, message, ...args);
};
newLog.info('CFGX', 'Debug logging enabled');
newLog.info(
'CFGX',
'This is very verbose and should only be used for debugging purposes',
);
newLog.info(
'CFGX',
'If you run this in production, your storage COULD fill up quickly',
);
}
hp_setSingleton('logger', newLog);
}
function defaultLog(
level: string,
category: string,
message: string,
...args: unknown[]
) {
const date = new Date().toISOString();
console.log(`${date} (${level}) [${category}] ${message}`, ...args);
}
const log = {
info: (category: string, message: string, ...args: unknown[]) => {
defaultLog('INFO', category, message, ...args);
},
warn: (category: string, message: string, ...args: unknown[]) => {
defaultLog('WARN', category, message, ...args);
},
error: (category: string, message: string, ...args: unknown[]) => {
defaultLog('ERRO', category, message, ...args);
},
debug: (category: string, message: string, ...args: unknown[]) => {},
};
export default hp_getSingletonUnsafe('logger') ?? log;
-32
View File
@@ -1,32 +0,0 @@
class Mutex {
private locked = false;
private queue: (() => void)[] = [];
constructor(locked: boolean) {
this.locked = locked;
}
acquire() {
return new Promise<void>((resolve) => {
if (!this.locked) {
this.locked = true;
resolve();
} else {
this.queue.push(resolve);
}
});
}
release() {
if (this.queue.length > 0) {
const next = this.queue.shift();
next?.();
} else {
this.locked = false;
}
}
}
export default function mutex(locked = false) {
return new Mutex(locked);
}
-76
View File
@@ -1,76 +0,0 @@
import { createRequire } from 'node:module';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import { devDependencies } from '../package.json';
const prefix = process.env.__INTERNAL_PREFIX || '/admin';
if (prefix.endsWith('/')) {
throw new Error('Prefix must not end with a slash');
}
const require = createRequire(import.meta.url);
export default defineConfig({
define: {
__hp_prefix: JSON.stringify(prefix),
},
resolve: {
preserveSymlinks: true,
alias: {
buffer: 'node:buffer',
crypto: 'node:crypto',
events: 'node:events',
fs: 'node:fs',
net: 'node:net',
http: 'node:http',
https: 'node:https',
os: 'node:os',
path: 'node:path',
stream: 'node:stream',
tls: 'node:tls',
url: 'node:url',
zlib: 'node:zlib',
ws: require.resolve('ws'),
},
},
plugins: [tsconfigPaths()],
build: {
minify: false,
target: 'node18',
// lib: {
// entry: 'server/entry.ts',
// formats: ['es'],
// },
rollupOptions: {
input: 'server/entry.ts',
treeshake: {
moduleSideEffects: false,
},
output: {
entryFileNames: 'server.js',
dir: 'build/headplane',
banner: '#!/usr/bin/env node\n',
},
// We are selecting a list of dependencies we want to include
// We are only including our production dependencies
external: (id) => {
if (id.startsWith('node:')) {
return true;
}
if (id === 'ws') {
return true;
}
const match = id.match(/node_modules\/([^/]+)/);
if (match) {
return true;
// const dep = match[1];
// if ((devDependencies as Record<string, string>)[dep]) {
// return true;
// }
}
},
},
},
});
-126
View File
@@ -1,126 +0,0 @@
import { createHash } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import { type } from 'arktype';
import log from '~server/utils/log';
import mutex from '~server/utils/mutex';
const diskSchema = type({
key: 'string',
value: 'unknown',
expires: 'number?',
}).array();
// A persistent HashMap with a TTL for each key
export class TimedCache<V> {
private _cache = new Map<string, V>();
private _timings = new Map<string, number>();
// Default TTL is 1 minute
private defaultTTL: number;
private filePath: string;
private writeLock = mutex();
// Last flush ID is essentially a hash of the flush contents
// Prevents unnecessary flushing if nothing has changed
private lastFlushId = '';
constructor(defaultTTL: number, filePath: string) {
this.defaultTTL = defaultTTL;
this.filePath = filePath;
// Load the cache from disk and then queue flushes every 10 seconds
this.load().then(() => {
setInterval(() => this.flush(), 10000);
});
}
set(key: string, value: V, ttl: number = this.defaultTTL) {
this._cache.set(key, value);
this._timings.set(key, Date.now() + ttl);
}
get(key: string) {
const value = this._cache.get(key);
if (!value) {
return;
}
const expires = this._timings.get(key);
if (!expires || expires < Date.now()) {
this._cache.delete(key);
this._timings.delete(key);
return;
}
return value;
}
// Map into a Record without any TTLs
toJSON() {
const result: Record<string, V> = {};
for (const [key, value] of this._cache.entries()) {
result[key] = value;
}
return result;
}
// WARNING: This function expects that this.filePath is NOT ENOENT
private async load() {
const data = await readFile(this.filePath, 'utf-8');
const cache = () => {
try {
return JSON.parse(data);
} catch (e) {
return undefined;
}
};
const diskData = cache();
if (diskData === undefined) {
log.error('CACH', 'Failed to load cache at %s', this.filePath);
return;
}
const cacheData = diskSchema(diskData);
if (cacheData instanceof type.errors) {
log.error('CACH', 'Failed to load cache at %s', this.filePath);
log.debug('CACHE', 'Error details: %s', cacheData.toString());
// Skip loading the cache (it should be overwritten soon)
return;
}
for (const { key, value, expires } of diskData) {
this._cache.set(key, value);
this._timings.set(key, expires);
}
log.info('CACH', 'Loaded cache from %s', this.filePath);
}
private async flush() {
this.writeLock.acquire();
const data = Array.from(this._cache.entries()).map(([key, value]) => {
return { key, value, expires: this._timings.get(key) };
});
if (data.length === 0) {
this.writeLock.release();
return;
}
// Calculate the hash of the data
const dumpData = JSON.stringify(data);
const sha = createHash('sha256').update(dumpData).digest('hex');
if (sha === this.lastFlushId) {
this.writeLock.release();
return;
}
await writeFile(this.filePath, dumpData, 'utf-8');
this.lastFlushId = sha;
this.writeLock.release();
log.debug('CACH', 'Flushed cache to %s', this.filePath);
}
}
-62
View File
@@ -1,62 +0,0 @@
import { open } from 'node:fs/promises';
import type { HostInfo } from '~/types';
import {
hp_getSingleton,
hp_getSingletonUnsafe,
hp_setSingleton,
} from '~server/context/global';
import log from '~server/utils/log';
import { TimedCache } from './cache';
export async function hp_loadAgentCache(defaultTTL: number, filepath: string) {
log.debug('CACH', `Loading agent cache from ${filepath}`);
try {
const handle = await open(filepath, 'w');
log.info('CACH', `Using agent cache file at ${filepath}`);
await handle.close();
} catch (e) {
log.info('CACH', `Agent cache file not found at ${filepath}`);
return;
}
const cache = new TimedCache<HostInfo>(defaultTTL, filepath);
hp_setSingleton('ws_agent_data', cache);
}
export async function hp_agentRequest(nodeList: string[]) {
// Request to all connected agents (we can have multiple)
// Luckily we can parse all the data at once through message parsing
// and then overlapping cache entries will be overwritten by time
const agents = hp_getSingleton('ws_agents');
const cache = hp_getSingletonUnsafe('ws_agent_data');
// Deduplicate the list of nodes
const NodeIDs = [...new Set(nodeList)];
NodeIDs.map((node) => {
log.debug('CACH', 'Requesting agent data for', node);
});
// Await so that data loads on first request without racing
// Since we do agent.once() we NEED to wait for it to finish
await Promise.allSettled(
[...agents].map(async ([id, agent]) => {
agent.send(JSON.stringify({ NodeIDs }));
await new Promise<void>((resolve) => {
// Just as a safety measure, we set a maximum timeout of 3 seconds
setTimeout(() => resolve(), 3000);
agent.once('message', (data) => {
const parsed = JSON.parse(data.toString());
log.debug('CACH', 'Received agent data from %s', id);
for (const [node, info] of Object.entries<HostInfo>(parsed)) {
cache?.set(node, info);
log.debug('CACH', 'Cached %s', node);
}
resolve();
});
});
}),
);
}
-58
View File
@@ -1,58 +0,0 @@
import WebSocket, { WebSocketServer } from 'ws';
import { hp_setSingleton } from '~server/context/global';
import log from '~server/utils/log';
import { hp_agentRequest } from './data';
export function initWebsocket(server: WebSocketServer, authKey: string) {
log.info('SRVX', 'Starting a WebSocket server for agent connections');
const agents = new Map<string, WebSocket>();
hp_setSingleton('ws_agents', agents);
hp_setSingleton('ws_fetch_data', hp_agentRequest);
server.on('connection', (ws, req) => {
const tailnetID = req.headers['x-headplane-tailnet-id'];
if (!tailnetID || typeof tailnetID !== 'string') {
log.warn(
'SRVX',
'Rejecting an agent WebSocket connection without a tailnet ID',
);
ws.close(1008, 'ERR_INVALID_TAILNET_ID');
return;
}
if (req.headers.authorization !== `Bearer ${authKey}`) {
log.warn('SRVX', 'Rejecting an unauthorized WebSocket connection');
if (req.socket.remoteAddress) {
log.warn('SRVX', 'Agent source IP: %s', req.socket.remoteAddress);
}
ws.close(1008, 'ERR_UNAUTHORIZED');
return;
}
agents.set(tailnetID, ws);
const pinger = setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) {
clearInterval(pinger);
return;
}
ws.ping();
}, 30000);
ws.on('close', () => {
clearInterval(pinger);
agents.delete(tailnetID);
});
ws.on('error', (error) => {
clearInterval(pinger);
log.error('SRVX', 'Agent WebSocket error: %s', error);
log.debug('SRVX', 'Error details: %o', error);
log.error('SRVX', 'Closing agent WebSocket connection');
ws.close(1011, 'ERR_INTERNAL_ERROR');
});
});
return server;
}
+9 -5
View File
@@ -1,9 +1,9 @@
import { readFile } from 'node:fs/promises';
import { reactRouter } from '@react-router/dev/vite';
import autoprefixer from 'autoprefixer';
import { reactRouterHonoServer } from 'react-router-hono-server/dev';
import tailwindcss from 'tailwindcss';
import { defineConfig } from 'vite';
import babel from 'vite-plugin-babel';
import tsconfigPaths from 'vite-tsconfig-paths';
const prefix = process.env.__INTERNAL_PREFIX || '/admin';
@@ -18,16 +18,20 @@ if (!version) {
throw new Error('Unable to read version from package.json');
}
export default defineConfig({
base: `${prefix}/`,
plugins: [reactRouter(), tsconfigPaths()],
export default defineConfig(({ isSsrBuild }) => ({
// base: `${prefix}/`,
plugins: [reactRouterHonoServer(), reactRouter(), tsconfigPaths()],
css: {
postcss: {
plugins: [tailwindcss, autoprefixer],
},
},
ssr: {
target: 'node',
noExternal: isSsrBuild ? true : undefined,
},
define: {
__VERSION__: JSON.stringify(version),
__PREFIX__: JSON.stringify(prefix),
},
});
}));