mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 02:49:31 +08:00
The guest joins a tailnet from Node or the page: ts2021 control over WebSocket, DERP relays, WireGuard and the packet filter in JS, loaded as a separate chunk only when the option is used. SDK net option, CLI --tailscale* flags and a page panel. Relay only; exit nodes, IPv6 and real peer traffic are not covered yet.
795 lines
28 KiB
TypeScript
795 lines
28 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// Tailscale control client: registers a node with a coordination server
|
|
// (Tailscale's or headscale) and keeps a current network map from the map
|
|
// long-poll, over ts2021 (control-noise.ts, a Noise channel on a WebSocket)
|
|
// and HTTP/2 inside it (h2.ts). It holds no storage: the caller persists
|
|
// ControlClient.state (keys and whether control accepted them).
|
|
//
|
|
// const client = new ControlClient({ hostname: "box", authKey, state });
|
|
// client.on("state", (s) => save(s));
|
|
// client.on("netmap", (nm) => use(nm.self.Addresses, nm.peers, nm.derpMap));
|
|
// client.start();
|
|
// await client.setPreferredDERP(1);
|
|
|
|
import { randomBytes, x25519Public } from "./crypto.ts";
|
|
import { dialNoise, NoiseError, type NoiseConn, type WebSocketConstructor, type EarlyNoise } from "./control-noise.ts";
|
|
import { MapSession, type NetMap } from "./control-netmap.ts";
|
|
import {
|
|
keyFromText,
|
|
keyToText,
|
|
ZERO_NODE_KEY,
|
|
type Hostinfo,
|
|
type MapRequest,
|
|
type MapResponse,
|
|
type NetInfo,
|
|
type PingRequest,
|
|
type RegisterRequest,
|
|
type RegisterResponse,
|
|
type ServerKeys,
|
|
type UserInfo,
|
|
} from "./control-types.ts";
|
|
import { H2Connection, H2Error, type H2Response } from "./h2.ts";
|
|
import { ChunkQueue, widenConnectAttempts } from "./bytes.ts";
|
|
|
|
export type { NetMap } from "./control-netmap.ts";
|
|
export type * from "./control-types.ts";
|
|
export { keyFromText, keyToText } from "./control-types.ts";
|
|
export { normalizeNode, MapSession } from "./control-netmap.ts";
|
|
|
|
/** Tailscale's coordination server. */
|
|
export const DEFAULT_CONTROL_URL = "https://controlplane.tailscale.com";
|
|
/**
|
|
* The capability version this client claims (tailcfg.CapabilityVersion):
|
|
* it understands HomeDERP (111), a nil AllowedIPs (112) and
|
|
* PeersChangedPatch, and asks for no compression.
|
|
*/
|
|
export const CAPABILITY_VERSION = 130;
|
|
|
|
/**
|
|
* What the caller persists between runs. Plain JSON; keep it secret (the
|
|
* machine and node keys are the device's identity on the tailnet).
|
|
*/
|
|
export interface ControlState {
|
|
/** Machine private key, "privkey:<hex>": identifies the device to control. */
|
|
machineKey: string;
|
|
/** Node private key, "privkey:<hex>": the WireGuard key. */
|
|
nodeKey: string;
|
|
/** Disco private key, "privkey:<hex>": for disco (path discovery) messages. */
|
|
discoKey: string;
|
|
/** The previous node key while a rotation is being registered. */
|
|
oldNodeKey?: string;
|
|
/** Control accepted nodeKey (registration done). */
|
|
authorized?: boolean;
|
|
/** The control URL the keys were registered with. */
|
|
controlURL?: string;
|
|
/** The user control reported at registration. */
|
|
user?: { id?: number; loginName?: string; displayName?: string };
|
|
/**
|
|
* The home DERP region last reported (setPreferredDERP). Tailscale's
|
|
* control never shows a node its own region in the netmap (headscale
|
|
* does), so a node that comes back finds it here.
|
|
*/
|
|
homeDERP?: number;
|
|
}
|
|
|
|
/** Status of the client's background loop. */
|
|
export type ControlStatus =
|
|
| "idle"
|
|
| "connecting"
|
|
| "registering"
|
|
/** Waiting for the user to visit the AuthURL (the "authurl" event). */
|
|
| "needs-login"
|
|
/** Registered but waiting for an admin to approve the machine. */
|
|
| "needs-machine-auth"
|
|
| "polling"
|
|
| "backoff"
|
|
| "stopped";
|
|
|
|
export interface ControlOptions {
|
|
/** Coordination server, default https://controlplane.tailscale.com. */
|
|
controlURL?: string;
|
|
/** The node's host name. */
|
|
hostname: string;
|
|
/** Pre-auth key ("tskey-auth-..." or a headscale key); without one, login is interactive. */
|
|
authKey?: string;
|
|
/** Persisted state; new keys are generated when absent. */
|
|
state?: ControlState;
|
|
/** Register as an ephemeral node (removed when it goes offline). */
|
|
ephemeral?: boolean;
|
|
/** ACL tags to request ("tag:x"). */
|
|
tags?: string[];
|
|
/** Extra Hostinfo fields (merged over the defaults). */
|
|
hostinfo?: Partial<Hostinfo>;
|
|
/** WebSocket constructor, default globalThis.WebSocket. */
|
|
WebSocket?: WebSocketConstructor;
|
|
/**
|
|
* The control server's Noise key ("mkey:<hex>"), to skip GET /key (which
|
|
* headscale serves without CORS headers, so a browser cannot read it).
|
|
*/
|
|
controlPublicKey?: string;
|
|
/** fetch, for GET /key; default globalThis.fetch. */
|
|
fetch?: typeof fetch;
|
|
/** Debug logger. */
|
|
logger?: (msg: string) => void;
|
|
/** Capability version to claim, default CAPABILITY_VERSION. */
|
|
capabilityVersion?: number;
|
|
/** Reconnect backoff in ms: first delay and cap (default 1000 and 30000). */
|
|
backoff?: { min?: number; max?: number };
|
|
/** Restart the map poll when nothing arrives for this long (ms), default 120000. */
|
|
watchdog?: number;
|
|
/** Every map message as it arrives, keep-alives included (diagnostics). */
|
|
onMapResponse?: (resp: MapResponse) => void;
|
|
}
|
|
|
|
/** Result of a registration. */
|
|
export interface LoginResult {
|
|
/** Control accepted the node; false while an admin has yet to approve the machine. */
|
|
machineAuthorized: boolean;
|
|
user?: UserInfo;
|
|
login?: UserInfo;
|
|
}
|
|
|
|
/** Events and their listener arguments. */
|
|
export interface ControlEvents {
|
|
/** The persisted state changed: save it. */
|
|
state: (state: ControlState) => void;
|
|
/** Interactive login: the user must open this URL. */
|
|
authurl: (url: string) => void;
|
|
/** A new network map. */
|
|
netmap: (netmap: NetMap) => void;
|
|
status: (status: ControlStatus) => void;
|
|
/** A non-fatal error (the loop retries). */
|
|
error: (err: Error) => void;
|
|
/** Control asks the client to open a URL (MapResponse.PopBrowserURL). */
|
|
popbrowser: (url: string) => void;
|
|
}
|
|
|
|
/** An error from control (HTTP status or RegisterResponse.Error). */
|
|
export class ControlError extends Error {
|
|
override name = "ControlError";
|
|
/** HTTP status, when the error came with one. */
|
|
readonly status: number;
|
|
|
|
constructor(message: string, status = 0) {
|
|
super(message);
|
|
this.status = status;
|
|
}
|
|
}
|
|
|
|
/** Generates fresh keys. */
|
|
export function newControlState(): ControlState {
|
|
return {
|
|
machineKey: keyToText("privkey", randomBytes(32)),
|
|
nodeKey: keyToText("privkey", randomBytes(32)),
|
|
discoKey: keyToText("privkey", randomBytes(32)),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The ts2021 WebSocket URL for a control URL, as client_js.go picks it: ws://
|
|
* for http with a port other than 80, wss:// otherwise. (Unlike Go, an
|
|
* https URL keeps its explicit port.)
|
|
*/
|
|
export function controlWebSocketURL(controlURL: string): string {
|
|
const u = new URL(controlURL);
|
|
if (u.protocol === "http:" && u.port && u.port !== "80") return `ws://${u.host}/ts2021`;
|
|
if (u.protocol === "https:") return `wss://${u.host}/ts2021`;
|
|
return `wss://${u.hostname}/ts2021`;
|
|
}
|
|
|
|
const MAX_MAP_MESSAGE = 256 << 20;
|
|
const textEncoder = new TextEncoder();
|
|
const textDecoder = new TextDecoder();
|
|
|
|
/** A connection to control: the Noise channel and HTTP/2 on it. */
|
|
interface Conn {
|
|
noise: NoiseConn;
|
|
h2: H2Connection;
|
|
early: Promise<EarlyNoise | null>;
|
|
}
|
|
|
|
/** A Tailscale control client for one node. */
|
|
export class ControlClient {
|
|
readonly controlURL: string;
|
|
readonly #opts: ControlOptions;
|
|
readonly #log: (msg: string) => void;
|
|
readonly #fetch: typeof fetch;
|
|
readonly #capver: number;
|
|
readonly #authority: string;
|
|
#state: ControlState;
|
|
#hostinfo: Hostinfo;
|
|
#endpoints: string[] = [];
|
|
#serverKey: Uint8Array | null = null;
|
|
#conn: Conn | null = null;
|
|
#dialing: Promise<Conn> | null = null;
|
|
#netmap: NetMap | null = null;
|
|
#status: ControlStatus = "idle";
|
|
readonly #listeners = new Map<keyof ControlEvents, Set<(...args: never[]) => void>>();
|
|
#run: AbortController | null = null;
|
|
#loop: Promise<void> | null = null;
|
|
#loginPromise: Promise<LoginResult> | null = null;
|
|
#lastPopURL = "";
|
|
/** stop() ran (and no start() since): nothing may open a connection. */
|
|
#stopped = false;
|
|
/** The current map poll has had a message. */
|
|
#polled = false;
|
|
|
|
constructor(opts: ControlOptions) {
|
|
this.#opts = opts;
|
|
widenConnectAttempts();
|
|
this.controlURL = (opts.controlURL ?? DEFAULT_CONTROL_URL).replace(/\/+$/, "");
|
|
const u = new URL(this.controlURL);
|
|
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error(`control: bad URL ${this.controlURL}`);
|
|
this.#authority = u.host;
|
|
this.#log = opts.logger ?? (() => {});
|
|
this.#fetch = opts.fetch ?? ((...a) => globalThis.fetch(...a));
|
|
this.#capver = opts.capabilityVersion ?? CAPABILITY_VERSION;
|
|
this.#state = opts.state ? { ...opts.state } : newControlState();
|
|
if (this.#state.controlURL && this.#state.controlURL !== this.controlURL) {
|
|
// Registered elsewhere: the keys stay, the registration does not.
|
|
this.#state.authorized = false;
|
|
}
|
|
this.#state.controlURL = this.controlURL;
|
|
// Validate the keys early.
|
|
keyFromText(this.#state.machineKey, "privkey");
|
|
keyFromText(this.#state.nodeKey, "privkey");
|
|
keyFromText(this.#state.discoKey, "privkey");
|
|
this.#hostinfo = {
|
|
IPNVersion: "1.80.0-unkernel",
|
|
OS: "js",
|
|
GoArch: "wasm",
|
|
Hostname: opts.hostname,
|
|
...(opts.tags?.length ? { RequestTags: opts.tags } : {}),
|
|
...opts.hostinfo,
|
|
};
|
|
}
|
|
|
|
// ---- Accessors ----
|
|
|
|
/** A copy of the state to persist. */
|
|
get state(): ControlState {
|
|
return structuredClone(this.#state);
|
|
}
|
|
|
|
/** The latest network map, null before the first. */
|
|
get netmap(): NetMap | null {
|
|
return this.#netmap;
|
|
}
|
|
|
|
get status(): ControlStatus {
|
|
return this.#status;
|
|
}
|
|
|
|
/** Raw node (WireGuard) private key. */
|
|
get nodePrivateKey(): Uint8Array {
|
|
return keyFromText(this.#state.nodeKey, "privkey");
|
|
}
|
|
|
|
/** Raw node public key. */
|
|
get nodePublicKey(): Uint8Array {
|
|
return x25519Public(this.nodePrivateKey);
|
|
}
|
|
|
|
/** Node public key as "nodekey:<hex>". */
|
|
get nodeKey(): string {
|
|
return keyToText("nodekey", this.nodePublicKey);
|
|
}
|
|
|
|
/** Raw disco private key. */
|
|
get discoPrivateKey(): Uint8Array {
|
|
return keyFromText(this.#state.discoKey, "privkey");
|
|
}
|
|
|
|
/** Raw disco public key. */
|
|
get discoPublicKey(): Uint8Array {
|
|
return x25519Public(this.discoPrivateKey);
|
|
}
|
|
|
|
/** Machine public key as "mkey:<hex>". */
|
|
get machineKey(): string {
|
|
return keyToText("mkey", x25519Public(keyFromText(this.#state.machineKey, "privkey")));
|
|
}
|
|
|
|
/** The Hostinfo sent to control. */
|
|
get hostinfo(): Hostinfo {
|
|
return structuredClone(this.#hostinfo);
|
|
}
|
|
|
|
// ---- Events ----
|
|
|
|
/** Adds a listener; returns a function that removes it. */
|
|
on<K extends keyof ControlEvents>(event: K, fn: ControlEvents[K]): () => void {
|
|
let set = this.#listeners.get(event);
|
|
if (!set) this.#listeners.set(event, (set = new Set()));
|
|
set.add(fn);
|
|
return () => void set.delete(fn);
|
|
}
|
|
|
|
#emit<K extends keyof ControlEvents>(event: K, ...args: Parameters<ControlEvents[K]>): void {
|
|
for (const fn of this.#listeners.get(event) ?? []) {
|
|
try {
|
|
(fn as unknown as (...a: Parameters<ControlEvents[K]>) => void)(...args);
|
|
} catch (e) {
|
|
this.#log(`control: ${event} listener threw: ${(e as Error)?.message ?? e}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
#setStatus(s: ControlStatus): void {
|
|
if (this.#status === s) return;
|
|
this.#status = s;
|
|
this.#log(`control: ${s}`);
|
|
this.#emit("status", s);
|
|
}
|
|
|
|
#saveState(): void {
|
|
this.#emit("state", this.state);
|
|
}
|
|
|
|
/**
|
|
* Resolves with the first netmap for which pred holds (default: any),
|
|
* the current one included.
|
|
*/
|
|
waitForNetMap(pred: (nm: NetMap) => boolean = () => true, opts: { timeout?: number; signal?: AbortSignal } = {}): Promise<NetMap> {
|
|
if (this.#netmap && pred(this.#netmap)) return Promise.resolve(this.#netmap);
|
|
return new Promise((resolve, reject) => {
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const off = this.on("netmap", (nm) => {
|
|
if (!pred(nm)) return;
|
|
done();
|
|
resolve(nm);
|
|
});
|
|
const onAbort = () => {
|
|
done();
|
|
reject(opts.signal!.reason);
|
|
};
|
|
const done = () => {
|
|
off();
|
|
clearTimeout(timer);
|
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
};
|
|
if (opts.timeout) {
|
|
timer = setTimeout(() => {
|
|
done();
|
|
reject(new ControlError(`control: no matching netmap in ${opts.timeout} ms`));
|
|
}, opts.timeout);
|
|
}
|
|
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
}
|
|
|
|
// ---- Connection ----
|
|
|
|
async #controlKey(signal?: AbortSignal): Promise<Uint8Array> {
|
|
if (this.#serverKey) return this.#serverKey;
|
|
if (this.#opts.controlPublicKey) return (this.#serverKey = keyFromText(this.#opts.controlPublicKey, "mkey"));
|
|
const res = await this.#fetch(`${this.controlURL}/key?v=${this.#capver}`, { signal });
|
|
if (!res.ok) throw new ControlError(`control: GET /key: HTTP ${res.status}`, res.status);
|
|
const keys = (await res.json()) as ServerKeys;
|
|
if (!keys.publicKey) throw new ControlError("control: server has no Noise key (too old?)");
|
|
this.#serverKey = keyFromText(keys.publicKey, "mkey");
|
|
return this.#serverKey;
|
|
}
|
|
|
|
/** The shared connection, dialled on demand. */
|
|
async #connection(signal?: AbortSignal): Promise<Conn> {
|
|
if (this.#stopped) throw new ControlError("control: stopped");
|
|
if (this.#conn && !this.#conn.h2.closed && !this.#conn.noise.closed) return this.#conn;
|
|
this.#dialing ??= this.#dial(signal).finally(() => (this.#dialing = null));
|
|
return this.#dialing;
|
|
}
|
|
|
|
async #dial(signal?: AbortSignal): Promise<Conn> {
|
|
const controlPublicKey = await this.#controlKey(signal);
|
|
let noise: NoiseConn;
|
|
try {
|
|
noise = await dialNoise({
|
|
url: controlWebSocketURL(this.controlURL),
|
|
machinePrivateKey: keyFromText(this.#state.machineKey, "privkey"),
|
|
controlPublicKey,
|
|
protocolVersion: this.#capver,
|
|
WebSocket: this.#opts.WebSocket,
|
|
signal,
|
|
});
|
|
} catch (e) {
|
|
// The server key may have rotated: fetch it again next time.
|
|
if (e instanceof NoiseError) this.#serverKey = null;
|
|
throw e;
|
|
}
|
|
const h2 = new H2Connection({
|
|
write: (d) => noise.write(d),
|
|
close: () => noise.close(),
|
|
}, { logger: this.#log });
|
|
noise.ondata = (d) => h2.receive(d);
|
|
noise.onclose = (err) => h2.transportClosed(err);
|
|
const conn: Conn = { noise, h2, early: noise.earlyPayload };
|
|
if (this.#stopped) {
|
|
// stop() came while dialling: this connection must not stay open.
|
|
h2.close();
|
|
noise.close();
|
|
throw new ControlError("control: stopped");
|
|
}
|
|
h2.onclose = (err) => {
|
|
if (err) this.#log(`control: connection closed: ${err.message}`);
|
|
if (this.#conn === conn) this.#conn = null;
|
|
};
|
|
this.#conn = conn;
|
|
this.#log(`control: connected to ${this.controlURL}`);
|
|
return conn;
|
|
}
|
|
|
|
/** POSTs JSON over the Noise channel, retrying once on a fresh connection when the request never reached the server. */
|
|
async #post(path: string, body: unknown, signal?: AbortSignal): Promise<H2Response> {
|
|
const json = textEncoder.encode(JSON.stringify(body));
|
|
const headers: [string, string][] = [["content-type", "application/json"]];
|
|
const old = this.#state.oldNodeKey ? keyToText("nodekey", x25519Public(keyFromText(this.#state.oldNodeKey, "privkey"))) : "";
|
|
if (old && path === "/machine/register") headers.push(["ts-lb", old]);
|
|
headers.push(["ts-lb", this.nodeKey]);
|
|
for (let attempt = 0; ; attempt++) {
|
|
const conn = await this.#connection(signal);
|
|
try {
|
|
return await conn.h2.request({ method: "POST", path, authority: this.#authority, headers, body: json, signal });
|
|
} catch (e) {
|
|
if (attempt === 0 && e instanceof H2Error && e.retryable) continue;
|
|
throw e;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- Registration ----
|
|
|
|
/**
|
|
* Registers the node key with control: with the auth key, or
|
|
* interactively (the "authurl" event, then waiting until the user has
|
|
* logged in). Resolves once control has accepted the key.
|
|
*/
|
|
login(opts: { signal?: AbortSignal } = {}): Promise<LoginResult> {
|
|
this.#loginPromise ??= this.#login(opts.signal).finally(() => (this.#loginPromise = null));
|
|
return this.#loginPromise;
|
|
}
|
|
|
|
async #login(signal?: AbortSignal): Promise<LoginResult> {
|
|
this.#setStatus("registering");
|
|
let followup = "";
|
|
let rotated = false;
|
|
for (;;) {
|
|
signal?.throwIfAborted();
|
|
const resp = await this.#register({ followup, signal });
|
|
if (resp.Error) throw new ControlError(`control: register: ${resp.Error}`);
|
|
if (resp.NodeKeyExpired) {
|
|
if (rotated) throw new ControlError("control: register: new node key reported expired");
|
|
this.#log("control: node key expired, rotating");
|
|
rotated = true;
|
|
this.#state.oldNodeKey = this.#state.nodeKey;
|
|
this.#state.nodeKey = keyToText("privkey", randomBytes(32));
|
|
this.#state.authorized = false;
|
|
this.#saveState();
|
|
followup = "";
|
|
continue;
|
|
}
|
|
if (resp.AuthURL) {
|
|
if (resp.AuthURL !== followup) {
|
|
this.#setStatus("needs-login");
|
|
this.#emit("authurl", resp.AuthURL);
|
|
} else {
|
|
// The server answered the followup without news: do not spin.
|
|
await sleep(1000, signal);
|
|
}
|
|
followup = resp.AuthURL;
|
|
continue;
|
|
}
|
|
delete this.#state.oldNodeKey;
|
|
this.#state.authorized = true;
|
|
const user = resp.User ?? {};
|
|
const login = resp.Login ?? {};
|
|
this.#state.user = { id: user.ID, loginName: login.LoginName, displayName: login.DisplayName ?? user.DisplayName };
|
|
this.#saveState();
|
|
const machineAuthorized = resp.MachineAuthorized !== false;
|
|
this.#setStatus(machineAuthorized ? "idle" : "needs-machine-auth");
|
|
return { machineAuthorized, user: resp.User, login: resp.Login };
|
|
}
|
|
}
|
|
|
|
async #register(o: { followup?: string; expiry?: string; signal?: AbortSignal }): Promise<RegisterResponse> {
|
|
const req: RegisterRequest = {
|
|
Version: this.#capver,
|
|
NodeKey: this.nodeKey,
|
|
OldNodeKey: this.#state.oldNodeKey ? keyToText("nodekey", x25519Public(keyFromText(this.#state.oldNodeKey, "privkey"))) : ZERO_NODE_KEY,
|
|
Hostinfo: this.#hostinfo,
|
|
Timestamp: new Date(Math.round(Date.now() / 1000) * 1000).toISOString().replace(".000Z", "Z"),
|
|
};
|
|
if (o.followup) req.Followup = o.followup;
|
|
else if (this.#opts.authKey && !o.expiry) req.Auth = { AuthKey: this.#opts.authKey };
|
|
if (o.expiry) req.Expiry = o.expiry;
|
|
if (this.#opts.ephemeral) req.Ephemeral = true;
|
|
const res = await this.#post("/machine/register", req, o.signal);
|
|
const text = await res.text();
|
|
if (res.status !== 200) throw new ControlError(`control: register: HTTP ${res.status}: ${text.trim().slice(0, 200)}`, res.status);
|
|
try {
|
|
return JSON.parse(text) as RegisterResponse;
|
|
} catch {
|
|
throw new ControlError(`control: register: bad response ${JSON.stringify(text.slice(0, 100))}`);
|
|
}
|
|
}
|
|
|
|
/** Expires the node key at control (log out); the state is no longer authorized. */
|
|
async logout(): Promise<void> {
|
|
const resp = await this.#register({ expiry: "0001-01-01T00:02:03Z" });
|
|
if (resp.Error) throw new ControlError(`control: logout: ${resp.Error}`);
|
|
this.#state.authorized = false;
|
|
this.#saveState();
|
|
}
|
|
|
|
// ---- Map ----
|
|
|
|
#mapRequest(stream: boolean, omitPeers: boolean): MapRequest {
|
|
const req: MapRequest = {
|
|
Version: this.#capver,
|
|
Compress: "",
|
|
KeepAlive: stream,
|
|
NodeKey: this.nodeKey,
|
|
DiscoKey: keyToText("discokey", this.discoPublicKey),
|
|
Stream: stream,
|
|
Hostinfo: this.#hostinfo,
|
|
};
|
|
if (omitPeers) req.OmitPeers = true;
|
|
if (this.#endpoints.length) {
|
|
req.Endpoints = this.#endpoints;
|
|
req.EndpointTypes = this.#endpoints.map(() => 0);
|
|
}
|
|
return req;
|
|
}
|
|
|
|
/**
|
|
* Tells control about changed Hostinfo or endpoints without disturbing
|
|
* the long-poll (a non-streaming MapRequest with OmitPeers).
|
|
*/
|
|
async sendUpdate(signal?: AbortSignal): Promise<void> {
|
|
const res = await this.#post("/machine/map", this.#mapRequest(false, true), signal);
|
|
const body = await res.bytes();
|
|
if (res.status !== 200) throw new ControlError(`control: map update: HTTP ${res.status}: ${textDecoder.decode(body).trim().slice(0, 200)}`, res.status);
|
|
}
|
|
|
|
/** Merges fields into the Hostinfo and, when registered, sends it to control. */
|
|
async updateHostinfo(patch: Partial<Hostinfo>): Promise<void> {
|
|
this.#hostinfo = { ...this.#hostinfo, ...patch };
|
|
if (this.#state.authorized) await this.sendUpdate(this.#run?.signal);
|
|
}
|
|
|
|
/** Merges fields into Hostinfo.NetInfo and, when registered, sends it to control. */
|
|
async updateNetInfo(patch: Partial<NetInfo>): Promise<void> {
|
|
await this.updateHostinfo({ NetInfo: { ...this.#hostinfo.NetInfo, ...patch } });
|
|
}
|
|
|
|
/** Reports the home DERP region (NetInfo.PreferredDERP), with optional latencies in seconds. */
|
|
async setPreferredDERP(region: number, latency?: Record<string, number>): Promise<void> {
|
|
await this.updateNetInfo(latency ? { PreferredDERP: region, DERPLatency: latency } : { PreferredDERP: region });
|
|
if (this.#state.homeDERP !== region) {
|
|
this.#state.homeDERP = region;
|
|
this.#saveState();
|
|
}
|
|
}
|
|
|
|
/** Sets the UDP endpoints ("ip:port") to advertise; empty for DERP only. */
|
|
async setEndpoints(endpoints: string[]): Promise<void> {
|
|
this.#endpoints = [...endpoints];
|
|
if (this.#state.authorized) await this.sendUpdate(this.#run?.signal);
|
|
}
|
|
|
|
/**
|
|
* One non-streaming full map request: the netmap as of now. (headscale
|
|
* answers these with an empty body; it serves maps only as streams.)
|
|
*/
|
|
async fetchNetMap(signal?: AbortSignal): Promise<NetMap> {
|
|
const res = await this.#post("/machine/map", this.#mapRequest(false, false), signal);
|
|
const body = await res.bytes();
|
|
if (res.status !== 200) throw new ControlError(`control: map: HTTP ${res.status}: ${textDecoder.decode(body).trim().slice(0, 200)}`, res.status);
|
|
const session = new MapSession();
|
|
for (const msg of splitMapMessages(body)) session.apply(decodeMapMessage(msg));
|
|
const nm = session.netmap();
|
|
if (!nm) throw new ControlError(body.length ? "control: map response without this node" : "control: empty map response (the server only streams maps)");
|
|
return nm;
|
|
}
|
|
|
|
// ---- The loop ----
|
|
|
|
/** Starts registering (if needed) and following the map in the background, reconnecting on failures. */
|
|
start(): void {
|
|
if (this.#run) return;
|
|
this.#stopped = false;
|
|
const run = new AbortController();
|
|
this.#run = run;
|
|
this.#loop = this.#runLoop(run.signal).finally(() => {
|
|
if (this.#run === run) this.#run = null;
|
|
});
|
|
}
|
|
|
|
/** Stops the loop and closes the connection. */
|
|
async stop(): Promise<void> {
|
|
this.#stopped = true;
|
|
const run = this.#run;
|
|
this.#run = null;
|
|
run?.abort(new ControlError("control: stopped"));
|
|
const conn = this.#conn;
|
|
this.#conn = null;
|
|
conn?.h2.close();
|
|
conn?.noise.close();
|
|
await this.#loop?.catch(() => {});
|
|
await this.#dialing?.catch(() => {});
|
|
this.#loop = null;
|
|
this.#setStatus("stopped");
|
|
}
|
|
|
|
async #runLoop(signal: AbortSignal): Promise<void> {
|
|
const min = this.#opts.backoff?.min ?? 1000;
|
|
const max = this.#opts.backoff?.max ?? 30000;
|
|
let delay = min;
|
|
while (!signal.aborted) {
|
|
this.#polled = false;
|
|
try {
|
|
if (!this.#state.authorized) await this.login({ signal });
|
|
await this.#poll(signal);
|
|
} catch (e) {
|
|
if (signal.aborted) break;
|
|
const err = e as Error;
|
|
this.#log(`control: ${err.message}`);
|
|
this.#emit("error", err);
|
|
if (err instanceof ControlError && (err.status === 401 || err.status === 403 || err.status === 404)) {
|
|
// Unknown or rejected node key: register again.
|
|
this.#state.authorized = false;
|
|
this.#saveState();
|
|
}
|
|
}
|
|
if (signal.aborted) break;
|
|
// A stream that carried messages starts the backoff over, however it ended (a watchdog, a server's close).
|
|
if (this.#polled) delay = min;
|
|
this.#setStatus("backoff");
|
|
const jittered = delay * (0.75 + Math.random() * 0.5);
|
|
this.#log(`control: reconnecting in ${Math.round(jittered)} ms`);
|
|
await sleep(jittered, signal).catch(() => {});
|
|
delay = Math.min(delay * 2, max);
|
|
}
|
|
}
|
|
|
|
/** Runs one streaming map request until it ends. Returns whether any message arrived. */
|
|
async #poll(signal: AbortSignal): Promise<boolean> {
|
|
this.#setStatus("connecting");
|
|
const stream = new AbortController();
|
|
const onAbort = () => stream.abort(signal.reason);
|
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
const watchdogMs = this.#opts.watchdog ?? 120000;
|
|
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
|
const pet = () => {
|
|
clearTimeout(watchdog);
|
|
watchdog = setTimeout(() => {
|
|
stream.abort(new ControlError(`control: no map message in ${watchdogMs} ms`));
|
|
// The connection may be dead without knowing it: do not reuse it.
|
|
this.#conn?.h2.transportClosed(new ControlError("control: connection stalled"));
|
|
}, watchdogMs);
|
|
};
|
|
let progressed = false;
|
|
try {
|
|
pet();
|
|
const res = await this.#post("/machine/map", this.#mapRequest(true, false), stream.signal);
|
|
if (res.status !== 200) {
|
|
const text = await res.text().catch(() => "");
|
|
throw new ControlError(`control: map: HTTP ${res.status}: ${text.trim().slice(0, 200)}`, res.status);
|
|
}
|
|
const session = new MapSession();
|
|
const reader = res.body.getReader();
|
|
// Chunks queue up until a whole message is there, which is copied once.
|
|
const q = new ChunkQueue();
|
|
for (;;) {
|
|
const { value, done } = await reader.read();
|
|
if (done) break;
|
|
pet();
|
|
q.push(value);
|
|
while (q.length >= 4) {
|
|
const h = q.peek(4);
|
|
const len = (h[0]! | (h[1]! << 8) | (h[2]! << 16) | (h[3]! << 24)) >>> 0;
|
|
if (len > MAX_MAP_MESSAGE) throw new ControlError(`control: map message of ${len} bytes`);
|
|
if (q.length - 4 < len) break;
|
|
q.take(4);
|
|
const msg = q.take(len);
|
|
if (!progressed) {
|
|
progressed = true;
|
|
this.#polled = true;
|
|
this.#setStatus("polling");
|
|
}
|
|
this.#onMapResponse(session, decodeMapMessage(msg));
|
|
}
|
|
}
|
|
if (stream.signal.aborted) throw stream.signal.reason;
|
|
this.#log("control: map stream ended");
|
|
return progressed;
|
|
} catch (e) {
|
|
if (stream.signal.aborted && !signal.aborted) throw stream.signal.reason;
|
|
throw e;
|
|
} finally {
|
|
clearTimeout(watchdog);
|
|
signal.removeEventListener("abort", onAbort);
|
|
if (!stream.signal.aborted) stream.abort();
|
|
}
|
|
}
|
|
|
|
#onMapResponse(session: MapSession, resp: MapResponse): void {
|
|
try { this.#opts.onMapResponse?.(resp); } catch {}
|
|
if (resp.PopBrowserURL && resp.PopBrowserURL !== this.#lastPopURL) {
|
|
this.#lastPopURL = resp.PopBrowserURL;
|
|
this.#emit("popbrowser", resp.PopBrowserURL);
|
|
}
|
|
if (resp.PingRequest) void this.#answerPing(resp.PingRequest);
|
|
if (!session.apply(resp)) return;
|
|
const nm = session.netmap();
|
|
if (!nm) return;
|
|
if (nm.self.MachineAuthorized === false) this.#setStatus("needs-machine-auth");
|
|
else this.#setStatus("polling");
|
|
this.#netmap = nm;
|
|
this.#emit("netmap", nm);
|
|
if (nm.expired) {
|
|
// Expired, logged out or deleted at control: register again, which
|
|
// rotates the key if need be. headscale sets Node.Expired (also for a
|
|
// deleted node); Tailscale's control, after a logout, keeps serving
|
|
// the map with only KeyExpiry in the past.
|
|
throw new ControlError("control: node key expired", 401);
|
|
}
|
|
}
|
|
|
|
/** Answers a plain PingRequest (no Types) with a HEAD to its URL, as tailscaled does. */
|
|
async #answerPing(pr: PingRequest): Promise<void> {
|
|
if (!pr.URL || pr.Types) return;
|
|
try {
|
|
if (pr.URLIsNoise) {
|
|
const u = new URL(pr.URL);
|
|
const conn = await this.#connection();
|
|
const res = await conn.h2.request({ method: "HEAD", path: u.pathname + u.search, authority: this.#authority });
|
|
await res.body.cancel().catch(() => {});
|
|
} else {
|
|
await this.#fetch(pr.URL, { method: "HEAD" });
|
|
}
|
|
} catch (e) {
|
|
this.#log(`control: ping answer failed: ${(e as Error)?.message ?? e}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Splits a non-streaming map body into its u32-LE length-prefixed messages. */
|
|
function splitMapMessages(body: Uint8Array): Uint8Array[] {
|
|
const out: Uint8Array[] = [];
|
|
let p = 0;
|
|
while (body.length - p >= 4) {
|
|
const len = (body[p]! | (body[p + 1]! << 8) | (body[p + 2]! << 16) | (body[p + 3]! << 24)) >>> 0;
|
|
if (body.length - p - 4 < len) throw new ControlError("control: truncated map message");
|
|
out.push(body.subarray(p + 4, p + 4 + len));
|
|
p += 4 + len;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function decodeMapMessage(msg: Uint8Array): MapResponse {
|
|
if (msg[0] === 0x28 && msg[1] === 0xb5 && msg[2] === 0x2f && msg[3] === 0xfd) {
|
|
throw new ControlError("control: map message is zstd-compressed although Compress was empty");
|
|
}
|
|
try {
|
|
return JSON.parse(textDecoder.decode(msg)) as MapResponse;
|
|
} catch {
|
|
throw new ControlError(`control: bad map message ${JSON.stringify(textDecoder.decode(msg.subarray(0, 80)))}`);
|
|
}
|
|
}
|
|
|
|
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
if (signal?.aborted) return reject(signal.reason);
|
|
const t = setTimeout(() => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
resolve();
|
|
}, ms);
|
|
const onAbort = () => {
|
|
clearTimeout(t);
|
|
reject(signal!.reason);
|
|
};
|
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
}
|