@crvouga/homelab 0.23.5 → 0.23.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ import { fleet } from './fleet-config';
2
+ import { record } from './config';
3
+ import { sshArgs, sshFailure } from './ssh';
4
+ import { sshPolicyCheck, type SshPrincipal } from './ssh-policy';
5
+ import type { Check, FleetNode, Runner } from './types';
6
+ import type { MachineDefinition } from './definition';
7
+
8
+ type Network = NonNullable<MachineDefinition['network']>;
9
+
10
+ function document(text: string): Record<string, unknown> | null {
11
+ try {
12
+ const value: unknown = JSON.parse(text);
13
+ return record(value) ? value : null;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+
19
+ function principal(
20
+ status: Record<string, unknown>,
21
+ node: Record<string, unknown>
22
+ ): SshPrincipal | null {
23
+ const id = node['ID'];
24
+ const ips = node['TailscaleIPs'];
25
+ if (
26
+ typeof id !== 'string' ||
27
+ !Array.isArray(ips) ||
28
+ !ips.length ||
29
+ !ips.every((ip) => typeof ip === 'string')
30
+ )
31
+ return null;
32
+ const users = status['User'];
33
+ const user = record(users) ? users[String(node['UserID'])] : null;
34
+ const login = record(user) ? user['LoginName'] : null;
35
+ return { id, ips, ...(typeof login === 'string' ? { login } : {}) };
36
+ }
37
+
38
+ const normalized = (name: unknown): string =>
39
+ String(name).replace(/\.$/, '').toLowerCase();
40
+
41
+ function authenticated(
42
+ status: Record<string, unknown> | null
43
+ ): status is Record<string, unknown> {
44
+ if (
45
+ !status ||
46
+ status['BackendState'] !== 'Running' ||
47
+ !record(status['Self'])
48
+ )
49
+ return false;
50
+ if (Array.isArray(status['Health']) && status['Health'].length) return false;
51
+ const expires = status['Self']['KeyExpiry'];
52
+ // Tagged identities can omit expiry or use the Go zero time.
53
+ if (typeof expires === 'string' && !expires.startsWith('0001-')) {
54
+ if (!(Date.parse(expires) > Date.now())) return false;
55
+ }
56
+ return (
57
+ normalized(status['Self']['DNSName']) ===
58
+ normalized(fleet.manager.network.tailscaleName)
59
+ );
60
+ }
61
+
62
+ async function clientContext(network: Network, run: Runner) {
63
+ const local = await run(['tailscale', 'status', '--json'], {
64
+ timeoutMs: 15_000,
65
+ });
66
+ const status = local.ok ? document(local.stdout) : null;
67
+ if (!authenticated(status)) return null;
68
+ const self = status['Self'];
69
+ const peers = status['Peer'];
70
+ if (!record(self) || !record(peers)) return null;
71
+ const peer = Object.values(peers).find(
72
+ (value) =>
73
+ record(value) &&
74
+ normalized(value['DNSName']) === normalized(network.tailscaleName)
75
+ );
76
+ if (!record(peer)) return null;
77
+ const source = principal(status, self);
78
+ const reverse = principal(status, peer);
79
+ return source && reverse ? { source, reverse } : null;
80
+ }
81
+
82
+ function correctConfiguration(
83
+ text: string,
84
+ network: Network,
85
+ ips: string[]
86
+ ): boolean {
87
+ const configuration = new Map(
88
+ text.split('\n').map((line) => {
89
+ const [key, ...value] = line.trim().split(/\s+/);
90
+ return [key, value.join(' ')];
91
+ })
92
+ );
93
+ const host = normalized(configuration.get('hostname'));
94
+ return (
95
+ (host === normalized(network.tailscaleName) || ips.includes(host)) &&
96
+ configuration.get('user') === network.user &&
97
+ configuration.get('port') === '22' &&
98
+ ['none', undefined].includes(configuration.get('proxyjump')) &&
99
+ ['none', undefined].includes(configuration.get('proxycommand'))
100
+ );
101
+ }
102
+
103
+ async function configurationCheck(
104
+ remote: string[],
105
+ network: Network,
106
+ ips: string[],
107
+ run: Runner
108
+ ): Promise<Check> {
109
+ const result = await run([...remote.slice(0, -1), '-G', remote.at(-1)!], {
110
+ timeoutMs: 10_000,
111
+ });
112
+ const valid = result.ok && correctConfiguration(result.stdout, network, ips);
113
+ return {
114
+ id: 'ssh:configuration',
115
+ status: valid ? 'pass' : 'fail',
116
+ summary: valid
117
+ ? 'Effective SSH destination, account and native port match the declaration without a jump host.'
118
+ : 'SSH_CONFIGURATION_MISMATCH',
119
+ remedy: {
120
+ action:
121
+ 'Reconcile the consumer-owned SSH alias with the declared tailnet destination, account and native SSH port 22. Remove unexpected proxy routing. Homelab does not rewrite personal SSH configuration or relax host trust.',
122
+ },
123
+ };
124
+ }
125
+
126
+ async function serviceCheck(remote: string[], run: Runner): Promise<Check> {
127
+ const prefs = await run([...remote, 'sudo -n tailscale debug prefs'], {
128
+ timeoutMs: 15_000,
129
+ });
130
+ const settings = prefs.ok ? document(prefs.stdout) : null;
131
+ const enabled = settings?.['RunSSH'] === true;
132
+ return {
133
+ id: 'ssh:service',
134
+ status: enabled ? 'pass' : 'fail',
135
+ summary: enabled
136
+ ? 'Native SSH is enabled on the destination daemon.'
137
+ : 'SSH_SERVICE_UNVERIFIED',
138
+ remedy: {
139
+ action:
140
+ 'Run converge to reconcile the declared native SSH preference and enabled daemon. If SSH is unavailable, use the consumer-owned console or verified alternate transport; no remote repair is possible over a disconnected route.',
141
+ },
142
+ };
143
+ }
144
+
145
+ async function policyChecks(
146
+ remote: string[],
147
+ network: Network,
148
+ context: { source: SshPrincipal; reverse: SshPrincipal },
149
+ run: Runner
150
+ ): Promise<Check[]> {
151
+ const map = await run([...remote, 'sudo -n tailscale debug netmap'], {
152
+ timeoutMs: 15_000,
153
+ });
154
+ const forward = sshPolicyCheck(
155
+ map.ok ? document(map.stdout) : null,
156
+ context.source,
157
+ network.user
158
+ );
159
+ const localMap = await run(['tailscale', 'debug', 'netmap'], {
160
+ timeoutMs: 15_000,
161
+ });
162
+ const reverse = sshPolicyCheck(
163
+ localMap.ok ? document(localMap.stdout) : null,
164
+ context.reverse,
165
+ fleet.manager.network.user
166
+ );
167
+ return [forward, { ...reverse, id: 'ssh:policy-return' }];
168
+ }
169
+
170
+ const HTTP_STATUS = /^HTTP\/1\.[01] \d{3}[^\r\n]*\r?\n/;
171
+
172
+ async function forwardingChecks(
173
+ remote: string[],
174
+ network: Network,
175
+ run: Runner
176
+ ): Promise<Check[]> {
177
+ // Exercise the editor's direct-tcpip channel against the declared loopback
178
+ // endpoint. No listening port, persistent tunnel or server is made.
179
+ const result = await run(
180
+ [
181
+ ...remote.slice(0, -1),
182
+ '-W',
183
+ `127.0.0.1:${network.t3Port}`,
184
+ remote.at(-1)!,
185
+ ],
186
+ {
187
+ input: 'HEAD / HTTP/1.0\r\nHost: localhost\r\n\r\n',
188
+ timeoutMs: 15_000,
189
+ stopWhen: (output) => HTTP_STATUS.test(output),
190
+ }
191
+ );
192
+ const forwarded =
193
+ (result.ok || result.reason === 'stopped') &&
194
+ HTTP_STATUS.test(result.stdout);
195
+ const checks: Check[] = [
196
+ {
197
+ id: 'ssh:forwarding',
198
+ status: forwarded ? 'pass' : 'fail',
199
+ summary: forwarded
200
+ ? 'A fresh strict SSH direct-tcpip channel reached the declared editor endpoint.'
201
+ : 'SSH_FORWARDING_UNVERIFIED',
202
+ ...(!forwarded
203
+ ? {
204
+ remedy: {
205
+ action:
206
+ 'Verify the declared T3 loopback service and scoped local forwarding permission. Reconcile owned services with converge and cloud authorization with the consumer infrastructure owner, then rerun check --workers. No public port or relaxed host trust is needed.',
207
+ },
208
+ }
209
+ : {}),
210
+ },
211
+ ];
212
+ if (!forwarded && !result.ok) checks.push(sshFailure(result));
213
+ return checks;
214
+ }
215
+
216
+ /** Manager-originated evidence. Only declared native SSH fleets opt in.
217
+ * No returned check contains daemon output, identities or authorization URLs.
218
+ * Runs after adoption, on scheduled converge and on health/notify.
219
+ */
220
+ export async function sshConnectivity(
221
+ node: FleetNode,
222
+ run: Runner
223
+ ): Promise<Check[]> {
224
+ if (!fleet.nativeSsh) return [];
225
+ const network = fleet.workers.find((entry) => entry.id === node.id)?.network;
226
+ const context = network ? await clientContext(network, run) : null;
227
+ const id = 'ssh:client';
228
+ if (!context || !network)
229
+ return [
230
+ {
231
+ id,
232
+ status: 'fail',
233
+ summary: 'SSH_CLIENT_IDENTITY_UNVERIFIED',
234
+ remedy: {
235
+ action:
236
+ 'Run this check on the declared manager with a running, authenticated Tailscale daemon. Restore its identity through the existing network repair or converge. A worker checking itself cannot verify manager connectivity.',
237
+ },
238
+ },
239
+ ];
240
+ const remote = sshArgs(node);
241
+ const checks: Check[] = [
242
+ {
243
+ id,
244
+ status: 'pass',
245
+ summary: 'SSH probes originate on the declared authenticated manager.',
246
+ },
247
+ ];
248
+ const configuration = await configurationCheck(
249
+ remote,
250
+ network,
251
+ context.reverse.ips,
252
+ run
253
+ );
254
+ checks.push(configuration);
255
+ if (configuration.status !== 'pass') return checks;
256
+ checks.push(await serviceCheck(remote, run));
257
+ checks.push(...(await policyChecks(remote, network, context, run)));
258
+ checks.push(...(await forwardingChecks(remote, network, run)));
259
+ return checks;
260
+ }
@@ -0,0 +1,89 @@
1
+ import { record } from './config';
2
+ import type { Check } from './types';
3
+
4
+ export interface SshPrincipal {
5
+ id: string;
6
+ ips: string[];
7
+ login?: string;
8
+ }
9
+
10
+ const POLICY_REMEDY = {
11
+ action:
12
+ 'Reconcile the consumer-owned tailnet policy with its infrastructure owner: grant scoped noninteractive SSH accept access from the declared source to the declared destination account, including local port forwarding for the editor. Temporary check approvals do not satisfy this dependency. If inspection is unverified, restore read-only netmap access through the existing local privilege owner; no policy success is inferred from a denied probe. Homelab never edits cloud access policy. Rerun converge and check --workers after reconciliation.',
13
+ };
14
+
15
+ /** Evaluate the destination daemon’s effective policy, not a cached login.
16
+ * Expiring rules are intentionally excluded: they can hide a check rule.
17
+ * Unknown or incomplete documents never establish unattended access.
18
+ */
19
+ export function sshPolicyCheck(
20
+ map: unknown,
21
+ source: SshPrincipal,
22
+ user: string
23
+ ): Check {
24
+ const id = 'ssh:policy';
25
+ const policy = record(map) ? map['SSHPolicy'] : null;
26
+ const rules = record(policy) ? policy['rules'] : null;
27
+ const summary = policyResult(rules, source, user);
28
+ return summary === 'pass'
29
+ ? {
30
+ id,
31
+ status: 'pass',
32
+ summary:
33
+ 'Durable scoped SSH acceptance and local forwarding verified independently of cached approvals.',
34
+ }
35
+ : { id, status: 'fail', summary, remedy: POLICY_REMEDY };
36
+ }
37
+
38
+ function policyResult(
39
+ rules: unknown,
40
+ source: SshPrincipal,
41
+ user: string
42
+ ): string {
43
+ if (!Array.isArray(rules) || !source.id || !source.ips.length || !user)
44
+ return 'SSH_POLICY_UNVERIFIED';
45
+ for (const rule of rules) {
46
+ const result = ruleResult(rule, source, user);
47
+ if (result !== 'ignore') return result;
48
+ }
49
+ return 'SSH_POLICY_DENIED';
50
+ }
51
+
52
+ function ruleResult(rule: unknown, source: SshPrincipal, user: string): string {
53
+ if (!record(rule)) return 'SSH_POLICY_UNVERIFIED';
54
+ if (rule['ruleExpires']) return 'ignore';
55
+ const principals = rule['principals'];
56
+ if (!Array.isArray(principals)) return 'SSH_POLICY_UNVERIFIED';
57
+ if (!principals.some((value) => principalMatches(value, source)))
58
+ return 'ignore';
59
+ const users = rule['sshUsers'];
60
+ const action = rule['action'];
61
+ if (record(action) && action['reject'] === true && !users)
62
+ return 'SSH_POLICY_DENIED';
63
+ return userResult(users, action, user);
64
+ }
65
+
66
+ function userResult(users: unknown, action: unknown, user: string): string {
67
+ if (!record(users)) return 'ignore';
68
+ const mapped = users[user] ?? users['*'];
69
+ if (typeof mapped !== 'string' || !mapped) return 'ignore';
70
+ if (mapped !== '=' && mapped !== user) return 'SSH_POLICY_ACCOUNT_MISMATCH';
71
+ if (!record(action) || action['reject'] === true) return 'SSH_POLICY_DENIED';
72
+ if (action['holdAndDelegate'])
73
+ return 'TAILSCALE_INTERACTIVE_AUTHORIZATION_REQUIRED';
74
+ if (action['accept'] !== true) return 'SSH_POLICY_DENIED';
75
+ if (action['allowLocalPortForwarding'] !== true)
76
+ return 'SSH_POLICY_FORWARDING_DENIED';
77
+ return 'pass';
78
+ }
79
+
80
+ function principalMatches(value: unknown, source: SshPrincipal): boolean {
81
+ if (!record(value)) return false;
82
+ return (
83
+ value['any'] === true ||
84
+ value['node'] === source.id ||
85
+ (typeof value['nodeIP'] === 'string' &&
86
+ source.ips.includes(value['nodeIP'])) ||
87
+ (source.login !== undefined && value['userLogin'] === source.login)
88
+ );
89
+ }
@@ -1,3 +1,4 @@
1
+ import { sshConnectivity } from './ssh-health';
1
2
  import { compareFingerprints } from './fingerprint';
2
3
  import { probe } from './probe';
3
4
  import { inspectRemote } from './transport';
@@ -70,6 +71,7 @@ export async function tailnetHealth(
70
71
  },
71
72
  run
72
73
  );
74
+ checks.push(...(await sshConnectivity(node, run)));
73
75
  return combine(peer, checks, report, manager);
74
76
  });
75
77
  const absent = nodes.filter(