Files
platform/plugins/offscale/web/useHeadscaleServers.ts
T
pastilhasandClaude Opus 5 e13128846b offscale is a plugin
headscale leaves the platform. 45 files move to plugins/offscale/ and the
platform stops knowing it exists.

  api/router.ts   the thin auth-gated proxy, now at /api/offscale
  sidecar/        18 files, the whole headscale contract and its admin keys
  db/             schema + queries, offscale_servers
  web/            26 files as panels and a layout — no screen, per the rule

removed from the platform: the hono mount, the `headscale` capability, the
App.tsx route pair, the screen and its barrel, the AppRegistry spread, the
officerdev re-exports, the dock tile, the page-title rule, and both database
barrels. tsgo is clean and nothing references it.

the imports tell the story of what the plugin↔host API actually is. the sidecar
takes @@/sidecar/protocol, @@/sidecar/connect, @@/data-path and
@@/officer-url.mjs; the queries take officerdb/db and officerdb/crypto; the
schema takes officerdb/auth/schema for the one reference a plugin may make; the
web half takes useClient, copyToClipboard, WorkspaceView and TerminalView from
the officerdev barrel. all of it resolves because a plugin lives inside the repo
— no publishing, no version negotiation.

AND IT FOUND A REAL BUG IN THE INSTALLER. createSidecarProxy learns its port
from a one-shot `<name>:server` event and subscribes when the plugin's router is
first imported — at mount. install started the sidecar BEFORE mounting, so the
announcement fired into a void: process online, routes mounted, every request
answering `503 sidecar not available` until something forced a reconnect. it
would have hit every plugin with an http sidecar. `example` never caught it
because it has no listener to announce.

install and enable now mount before starting; disable still unmounts before
stopping. neither direction leaves a mounted route in front of a sidecar that
cannot be reached.

verified live: /api/offscale/_officer/servers answers {"servers":[]}, /offscale
and /offscale/nodes serve, the old /api/headscale is 404, the offscale
capability is registered from the manifest, and officer-offscale is online.

757 pass, same 10 pre-existing failures.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 00:15:38 +00:00

103 lines
3.8 KiB
TypeScript

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import type { HeadscaleServer, HeadscaleHealth, HeadscaleSshTest } from './shared';
// The registered-servers cache. Every panel in the /headscale workspace reads this one query, so switching
// the active server anywhere updates the whole screen at once.
//
// Registration is validated server-side before anything is saved (reachable, >=0.29, key accepted), which
// means a POST can fail for perfectly ordinary reasons — a typo'd URL, a revoked key. Those are not
// exceptional here, so the mutations surface their message rather than swallowing it.
const SERVERS_KEY = ['headscale', 'servers'] as const;
const EMPTY: HeadscaleServer[] = [];
const BASE = '/offscale/_officer/servers';
/**
* Readable message from a useClient rejection. It throws `{status, message}` where `message` is the raw
* body text — JSON `{error}` from our sidecar, but plain text from the platform's own 401/503 paths.
*/
export function headscaleErrorMessage(err: unknown): string {
const raw = (err as { message?: unknown } | null)?.message;
if (typeof raw !== 'string' || !raw) return 'Something went wrong';
try {
const parsed = JSON.parse(raw) as { error?: unknown };
if (typeof parsed.error === 'string' && parsed.error) return parsed.error;
} catch {
/* plain text */
}
return raw.slice(0, 300);
}
export type RegisterServerInput = { name?: string; url: string; apiKey: string; sshHost?: string };
/** `sshHost: ''` clears the console target; omitting it leaves whatever is stored alone. */
export type UpdateServerInput = { id: number; name?: string; url?: string; apiKey?: string; sshHost?: string };
export function useHeadscaleServers() {
const { get, post, patch, delete: del } = useClient();
const qc = useQueryClient();
const query = useQuery({
queryKey: SERVERS_KEY,
queryFn: () => get<{ servers: HeadscaleServer[] }>(BASE),
staleTime: 30_000,
});
const invalidate = () => qc.invalidateQueries({ queryKey: SERVERS_KEY });
const register = useMutation({
mutationFn: (input: RegisterServerInput) => post<{ server: HeadscaleServer }>(BASE, input),
onSuccess: invalidate,
});
const update = useMutation({
mutationFn: ({ id, ...rest }: UpdateServerInput) => patch<{ server: HeadscaleServer }>(`${BASE}/${id}`, rest),
onSuccess: invalidate,
});
const remove = useMutation({
mutationFn: (id: number) => del(`${BASE}/${id}`),
onSuccess: invalidate,
});
const activate = useMutation({
mutationFn: (id: number) => post<{ server: HeadscaleServer }>(`${BASE}/${id}/activate`),
// Deleting or switching reshuffles which server is active, and every domain query is scoped to it.
onSuccess: () => qc.invalidateQueries({ queryKey: ['headscale'] }),
});
const servers = query.data?.servers ?? EMPTY;
return {
servers,
active: servers.find((s) => s.isActive) ?? null,
isLoading: query.isLoading,
error: query.error,
refetch: query.refetch,
register,
update,
remove,
activate,
};
}
/**
* Try to open a shell on a console target with the keys already on this machine. Takes the host rather than a
* server id so the form can test a value before it is saved — which is when a typo is still cheap to fix.
*/
export function useHeadscaleSshTest() {
const { post } = useClient();
return useMutation({
mutationFn: (host: string) => post<HeadscaleSshTest>('/offscale/_officer/ssh-test', { host }),
});
}
/** On-demand reachability probe for one server. Never automatic — it costs two upstream round trips. */
export function useHeadscaleHealth() {
const { get } = useClient();
return useMutation({
mutationFn: (id: number) => get<HeadscaleHealth>(`${BASE}/${id}/health`),
});
}