@overcy/hive 0.0.1 → 0.2.0

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.
Files changed (134) hide show
  1. package/README.md +209 -4
  2. package/dist/api.d.ts +31 -0
  3. package/dist/api.js +83 -0
  4. package/dist/atomic.d.ts +1 -0
  5. package/dist/atomic.js +24 -0
  6. package/dist/binding.d.ts +5 -0
  7. package/dist/binding.js +16 -0
  8. package/dist/bootstrap/deps.d.ts +3 -0
  9. package/dist/bootstrap/deps.js +35 -0
  10. package/dist/bootstrap/doctor.d.ts +29 -0
  11. package/dist/bootstrap/doctor.js +80 -0
  12. package/dist/bootstrap/engine.d.ts +29 -0
  13. package/dist/bootstrap/engine.js +160 -0
  14. package/dist/bootstrap/forwarder.d.ts +11 -0
  15. package/dist/bootstrap/forwarder.js +30 -0
  16. package/dist/bootstrap/identity.d.ts +7 -0
  17. package/dist/bootstrap/identity.js +52 -0
  18. package/dist/bootstrap/index.d.ts +36 -0
  19. package/dist/bootstrap/index.js +40 -0
  20. package/dist/bootstrap/kit.d.ts +9 -0
  21. package/dist/bootstrap/kit.js +56 -0
  22. package/dist/bootstrap/manifest.d.ts +73 -0
  23. package/dist/bootstrap/manifest.js +309 -0
  24. package/dist/bootstrap/model-access.d.ts +43 -0
  25. package/dist/bootstrap/model-access.js +74 -0
  26. package/dist/bootstrap/pin.d.ts +2 -0
  27. package/dist/bootstrap/pin.js +16 -0
  28. package/dist/bootstrap/plan.d.ts +49 -0
  29. package/dist/bootstrap/plan.js +69 -0
  30. package/dist/bootstrap/prompt.d.ts +3 -0
  31. package/dist/bootstrap/prompt.js +35 -0
  32. package/dist/bootstrap/registry.d.ts +85 -0
  33. package/dist/bootstrap/registry.js +38 -0
  34. package/dist/bootstrap/secrets.d.ts +11 -0
  35. package/dist/bootstrap/secrets.js +105 -0
  36. package/dist/bootstrap/steps/agents.d.ts +9 -0
  37. package/dist/bootstrap/steps/agents.js +75 -0
  38. package/dist/bootstrap/steps/auth.d.ts +8 -0
  39. package/dist/bootstrap/steps/auth.js +138 -0
  40. package/dist/bootstrap/steps/cron.d.ts +7 -0
  41. package/dist/bootstrap/steps/cron.js +74 -0
  42. package/dist/bootstrap/steps/drift.d.ts +5 -0
  43. package/dist/bootstrap/steps/drift.js +67 -0
  44. package/dist/bootstrap/steps/env.d.ts +6 -0
  45. package/dist/bootstrap/steps/env.js +108 -0
  46. package/dist/bootstrap/steps/files.d.ts +7 -0
  47. package/dist/bootstrap/steps/files.js +28 -0
  48. package/dist/bootstrap/steps/lanes.d.ts +14 -0
  49. package/dist/bootstrap/steps/lanes.js +153 -0
  50. package/dist/bootstrap/steps/model-access.d.ts +10 -0
  51. package/dist/bootstrap/steps/model-access.js +122 -0
  52. package/dist/bootstrap/steps/preflight.d.ts +3 -0
  53. package/dist/bootstrap/steps/preflight.js +49 -0
  54. package/dist/bootstrap/steps/reporter.d.ts +12 -0
  55. package/dist/bootstrap/steps/reporter.js +155 -0
  56. package/dist/bootstrap/system.d.ts +5 -0
  57. package/dist/bootstrap/system.js +69 -0
  58. package/dist/bootstrap/types.d.ts +157 -0
  59. package/dist/bootstrap/types.js +14 -0
  60. package/dist/cli.d.ts +2 -0
  61. package/dist/cli.js +23 -0
  62. package/dist/collect.d.ts +28 -0
  63. package/dist/collect.js +63 -0
  64. package/dist/commands/connect.d.ts +33 -0
  65. package/dist/commands/connect.js +306 -0
  66. package/dist/commands/doctor.d.ts +7 -0
  67. package/dist/commands/doctor.js +13 -0
  68. package/dist/commands/login.d.ts +3 -0
  69. package/dist/commands/login.js +118 -0
  70. package/dist/commands/logout.d.ts +2 -0
  71. package/dist/commands/logout.js +37 -0
  72. package/dist/commands/node-add.d.ts +7 -0
  73. package/dist/commands/node-add.js +56 -0
  74. package/dist/commands/node.d.ts +19 -0
  75. package/dist/commands/node.js +43 -0
  76. package/dist/commands/prEvents.d.ts +7 -0
  77. package/dist/commands/prEvents.js +32 -0
  78. package/dist/commands/setup.d.ts +15 -0
  79. package/dist/commands/setup.js +35 -0
  80. package/dist/commands/status.d.ts +18 -0
  81. package/dist/commands/status.js +71 -0
  82. package/dist/commands/threads.d.ts +6 -0
  83. package/dist/commands/threads.js +36 -0
  84. package/dist/config.d.ts +71 -0
  85. package/dist/config.js +121 -0
  86. package/dist/context.d.ts +26 -0
  87. package/dist/context.js +31 -0
  88. package/dist/crypto.d.ts +7 -0
  89. package/dist/crypto.js +50 -0
  90. package/dist/machine.d.ts +66 -0
  91. package/dist/machine.js +103 -0
  92. package/dist/node/cli.d.ts +25 -0
  93. package/dist/node/cli.js +130 -0
  94. package/dist/node/engine.d.ts +47 -0
  95. package/dist/node/engine.js +463 -0
  96. package/dist/node/ingress.d.ts +102 -0
  97. package/dist/node/ingress.js +473 -0
  98. package/dist/node/layout.d.ts +56 -0
  99. package/dist/node/layout.js +55 -0
  100. package/dist/node/leave.d.ts +8 -0
  101. package/dist/node/leave.js +32 -0
  102. package/dist/node/lock.d.ts +19 -0
  103. package/dist/node/lock.js +99 -0
  104. package/dist/node/modelAccess.d.ts +2 -0
  105. package/dist/node/modelAccess.js +44 -0
  106. package/dist/node/repair.d.ts +28 -0
  107. package/dist/node/repair.js +78 -0
  108. package/dist/node/services.d.ts +58 -0
  109. package/dist/node/services.js +171 -0
  110. package/dist/node/state.d.ts +127 -0
  111. package/dist/node/state.js +95 -0
  112. package/dist/node/steps.d.ts +74 -0
  113. package/dist/node/steps.js +158 -0
  114. package/dist/node/supervisor.d.ts +22 -0
  115. package/dist/node/supervisor.js +95 -0
  116. package/dist/node/tick.d.ts +47 -0
  117. package/dist/node/tick.js +278 -0
  118. package/dist/node/toolchain.d.ts +50 -0
  119. package/dist/node/toolchain.js +230 -0
  120. package/dist/nodeContract.d.ts +101 -0
  121. package/dist/nodeContract.js +192 -0
  122. package/dist/package.d.ts +3 -0
  123. package/dist/package.js +5 -0
  124. package/dist/prEvents.d.ts +109 -0
  125. package/dist/prEvents.js +374 -0
  126. package/dist/run.d.ts +19 -0
  127. package/dist/run.js +487 -0
  128. package/dist/specs/device-client.json +920 -0
  129. package/dist/threads.d.ts +88 -0
  130. package/dist/threads.js +268 -0
  131. package/dist/version.d.ts +1 -0
  132. package/dist/version.js +1 -0
  133. package/package.json +33 -7
  134. package/bin/hive.js +0 -2
@@ -0,0 +1,102 @@
1
+ import type { Layout } from './layout.ts';
2
+ import type { NodeStep, TickRun } from './steps.ts';
3
+ /**
4
+ * The `ingress` step. It puts the node's live threads on https for Hive's thread page, and it owns the
5
+ * `stream_origin` the relay publishes. The init adapter runs the ingress as `hive-ingress`.
6
+ * - `dev_tls` is Caddy with a certificate from the harness CA.
7
+ * - `cloudflare_tunnel` is cloudflared on the token Hive minted, plus Caddy on loopback as the ticket route's method
8
+ * filter, because a tunnel's ingress rules match paths but not methods.
9
+ * - `none`, or a pause, stops the ingress and deletes its files.
10
+ */
11
+ export declare const CADDY_VERSION = "2.11.9";
12
+ /** The cloudflared release the node runs. The dev channel must serve the same version, and the step checks it. */
13
+ export declare const CLOUDFLARED_VERSION = "2026.11.2";
14
+ /** How long Hive may take to show a new origin before the step calls it broken. The relay posts within a tick. */
15
+ export declare const ECHO_GRACE_MS: number;
16
+ export declare const START_GRACE_MS = 60000;
17
+ /** The secret behind a dev_tls `SecretRef` is one PEM text: the certificate chain, then the private key. */
18
+ export declare const TLS_FILES: {
19
+ readonly cert: "node.crt";
20
+ readonly key: "node.key";
21
+ };
22
+ /** The tunnel token, 0640 in `ingress/config/`. cloudflared reads it with `--token-file`, so it is never in argv or the environment. */
23
+ export declare const TUNNEL_TOKEN_FILE = "tunnel.token";
24
+ /**
25
+ * The loopback ports a tunnel needs. Hive's tunnel config sends the ticket route to `HIVE_CF_NODE_TICKET_ORIGIN`
26
+ * (default `http://127.0.0.1:3774`) and the read routes to `HIVE_CF_NODE_ORIGIN` (default `http://127.0.0.1:3773`,
27
+ * the engine). Both must stay equal to what the node listens on. cloudflared answers `/ready` on the metrics port.
28
+ * The environment variables move them for tests only.
29
+ */
30
+ export declare const DEFAULT_TICKET_FILTER_PORT = 3774;
31
+ export declare const DEFAULT_TUNNEL_METRICS_PORT = 20241;
32
+ export declare const ticketFilterPort: (env: NodeJS.ProcessEnv) => number;
33
+ export declare const tunnelMetricsPort: (env: NodeJS.ProcessEnv) => number;
34
+ export declare const TICKET_PATH = "/api/auth/websocket-ticket/rpc";
35
+ export declare const TICKET_METHODS: readonly ["POST", "OPTIONS"];
36
+ /**
37
+ * Every other path the embedded T3 client needs, the same as `App\Ingress\TunnelIngress::readPath()` in the web app.
38
+ * `/`, `/ws`, `/pair`, `/api/auth/browser-session` and the T3 UI are never on it.
39
+ */
40
+ export declare const READ_PATH = "^/(?:\\.well-known/t3/environment|api/auth/session|hivecode/ws/(?:[A-Za-z0-9_-]|:|%3[Aa])+|api/orchestration/threads/(?:[A-Za-z0-9_-]|:|%3[Aa])+(?:/bounded|/history|/transcript)?)$";
41
+ /** What the generated Caddyfile lets through, as a function, so a test can run the shared path table over it. */
42
+ export declare function ingressAllows(method: string, path: string): boolean;
43
+ type Secret = {
44
+ name: string;
45
+ version: number;
46
+ };
47
+ type Https = {
48
+ origin: string;
49
+ host: string;
50
+ port: number;
51
+ secret: Secret;
52
+ };
53
+ export type IngressPlan = {
54
+ kind: 'off';
55
+ why: string;
56
+ } | ({
57
+ kind: 'dev_tls';
58
+ } & Https) | ({
59
+ kind: 'cloudflare_tunnel';
60
+ } & Https) | {
61
+ kind: 'unsupported';
62
+ detail: string;
63
+ fix: 'hive_button' | 'human';
64
+ };
65
+ /** What desired state asks of the ingress. A pause stops it as `none` does. */
66
+ export declare function ingressPlan(run: TickRun): IngressPlan;
67
+ /**
68
+ * The origin the relay publishes with the thread batch. `undefined` leaves it to `HIVE_T3_STREAM_ORIGIN`, as before
69
+ * plan item 8, when desired state has no ingress. `null` tells Hive the node has none.
70
+ */
71
+ export declare function streamOriginFor(run: TickRun): string | null | undefined;
72
+ /**
73
+ * Deletes the certificate and the tunnel token. A revoked node keeps no ingress credential: Hive deletes the tunnel,
74
+ * and the keeper stops the ingress once the supervisor exits 77.
75
+ */
76
+ export declare function dropIngressSecrets(layout: Layout): Promise<void>;
77
+ /**
78
+ * The Caddyfile for dev_tls. It has no admin endpoint and stores nothing outside `ingress/state/`. Only POST and
79
+ * OPTIONS reach the ticket route, because a GET there used to serve the T3 UI. Both matchers are regular expressions,
80
+ * which are case-sensitive like the tunnel's rules. Caddy's `path` matcher is not.
81
+ */
82
+ export declare function caddyfile(run: TickRun, port: number): string;
83
+ /**
84
+ * The Caddyfile for a tunnel: the ticket route's method filter, plain http on loopback only. cloudflared sends it the
85
+ * ticket path and nothing else. POST and OPTIONS go to the engine, any other method gets 405, and any other path 404.
86
+ * The site has no host, so the public hostname cloudflared forwards still matches.
87
+ */
88
+ export declare function ticketFilterCaddyfile(run: TickRun): string;
89
+ /** Splits the certificate secret into the chain and the key. */
90
+ export declare function splitPem(value: string): {
91
+ cert: string;
92
+ key: string;
93
+ };
94
+ /** A tunnel token is one line of base64. Anything else is refused before it reaches the disk. */
95
+ export declare function tunnelToken(value: string): string;
96
+ /**
97
+ * `ingress.env`, sourced by install.sh's `ingress-run`. It never holds the tunnel token. For a tunnel it names the
98
+ * loopback address cloudflared serves `/ready` on, and `ingress-run` refuses any address that is not 127.0.0.1.
99
+ */
100
+ export declare function ingressEnv(run: TickRun, kind: 'dev_tls' | 'cloudflare_tunnel'): string;
101
+ export declare const ingressStep: NodeStep;
102
+ export {};
@@ -0,0 +1,473 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { request as httpsRequest } from 'node:https';
4
+ import { rootCertificates } from 'node:tls';
5
+ import { rename, rm } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ import { enginePort, RESTART_PACE_MS } from "./engine.js";
8
+ import { fetchArtifact, isExecutable, linkTarget, readText, serviceControl, sha256, switchLink, unpack, writeIfChanged } from "./services.js";
9
+ /**
10
+ * The `ingress` step. It puts the node's live threads on https for Hive's thread page, and it owns the
11
+ * `stream_origin` the relay publishes. The init adapter runs the ingress as `hive-ingress`.
12
+ * - `dev_tls` is Caddy with a certificate from the harness CA.
13
+ * - `cloudflare_tunnel` is cloudflared on the token Hive minted, plus Caddy on loopback as the ticket route's method
14
+ * filter, because a tunnel's ingress rules match paths but not methods.
15
+ * - `none`, or a pause, stops the ingress and deletes its files.
16
+ */
17
+ export const CADDY_VERSION = '2.11.9';
18
+ /** The cloudflared release the node runs. The dev channel must serve the same version, and the step checks it. */
19
+ export const CLOUDFLARED_VERSION = '2026.11.2';
20
+ /** How long Hive may take to show a new origin before the step calls it broken. The relay posts within a tick. */
21
+ export const ECHO_GRACE_MS = 3 * 60_000;
22
+ export const START_GRACE_MS = 60_000;
23
+ /** The secret behind a dev_tls `SecretRef` is one PEM text: the certificate chain, then the private key. */
24
+ export const TLS_FILES = { cert: 'node.crt', key: 'node.key' };
25
+ /** The tunnel token, 0640 in `ingress/config/`. cloudflared reads it with `--token-file`, so it is never in argv or the environment. */
26
+ export const TUNNEL_TOKEN_FILE = 'tunnel.token';
27
+ /**
28
+ * The loopback ports a tunnel needs. Hive's tunnel config sends the ticket route to `HIVE_CF_NODE_TICKET_ORIGIN`
29
+ * (default `http://127.0.0.1:3774`) and the read routes to `HIVE_CF_NODE_ORIGIN` (default `http://127.0.0.1:3773`,
30
+ * the engine). Both must stay equal to what the node listens on. cloudflared answers `/ready` on the metrics port.
31
+ * The environment variables move them for tests only.
32
+ */
33
+ export const DEFAULT_TICKET_FILTER_PORT = 3774;
34
+ export const DEFAULT_TUNNEL_METRICS_PORT = 20241;
35
+ const portFrom = (value, fallback) => {
36
+ const port = Number(value);
37
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : fallback;
38
+ };
39
+ export const ticketFilterPort = (env) => portFrom(env.HIVE_TICKET_FILTER_PORT, DEFAULT_TICKET_FILTER_PORT);
40
+ export const tunnelMetricsPort = (env) => portFrom(env.HIVE_TUNNEL_METRICS_PORT, DEFAULT_TUNNEL_METRICS_PORT);
41
+ export const TICKET_PATH = '/api/auth/websocket-ticket/rpc';
42
+ export const TICKET_METHODS = ['POST', 'OPTIONS'];
43
+ /** One thread id: letters, digits, `_`, `-`, a raw `:` or an encoded `%3A`. Never a bare `%`, so `%2F` stays out. */
44
+ const ID = '(?:[A-Za-z0-9_-]|:|%3[Aa])+';
45
+ /**
46
+ * Every other path the embedded T3 client needs, the same as `App\Ingress\TunnelIngress::readPath()` in the web app.
47
+ * `/`, `/ws`, `/pair`, `/api/auth/browser-session` and the T3 UI are never on it.
48
+ */
49
+ export const READ_PATH = `^/(?:\\.well-known/t3/environment|api/auth/session|hivecode/ws/${ID}|api/orchestration/threads/${ID}(?:/bounded|/history|/transcript)?)$`;
50
+ /** What the generated Caddyfile lets through, as a function, so a test can run the shared path table over it. */
51
+ export function ingressAllows(method, path) {
52
+ if (path === TICKET_PATH)
53
+ return TICKET_METHODS.includes(method);
54
+ return new RegExp(READ_PATH).test(path);
55
+ }
56
+ /** What desired state asks of the ingress. A pause stops it as `none` does. */
57
+ export function ingressPlan(run) {
58
+ const spec = run.desired?.ingress;
59
+ if (run.desired?.paused === true)
60
+ return { kind: 'off', why: 'Hive paused this node, so the ingress is stopped' };
61
+ if (spec === undefined)
62
+ return { kind: 'off', why: 'Hive has not asked for an ingress' };
63
+ if (spec.kind === 'none')
64
+ return { kind: 'off', why: 'ingress is none' };
65
+ if (spec.stream_origin === undefined || spec.secret === undefined) {
66
+ const needs = spec.kind === 'dev_tls' ? 'a certificate secret' : 'a tunnel token secret';
67
+ return { kind: 'unsupported', detail: `${spec.kind} needs a stream_origin and ${needs} in desired state`, fix: 'hive_button' };
68
+ }
69
+ const url = new URL(spec.stream_origin);
70
+ return { kind: spec.kind, origin: url.origin, host: url.hostname, port: url.port === '' ? 443 : Number(url.port), secret: spec.secret };
71
+ }
72
+ /**
73
+ * The origin the relay publishes with the thread batch. `undefined` leaves it to `HIVE_T3_STREAM_ORIGIN`, as before
74
+ * plan item 8, when desired state has no ingress. `null` tells Hive the node has none.
75
+ */
76
+ export function streamOriginFor(run) {
77
+ if (run.desired?.ingress === undefined && run.desired?.paused !== true)
78
+ return undefined;
79
+ const plan = ingressPlan(run);
80
+ return plan.kind === 'dev_tls' || plan.kind === 'cloudflare_tunnel' ? plan.origin : null;
81
+ }
82
+ const files = (run) => ({
83
+ caddyfile: join(run.layout.ingressConfigDir, 'Caddyfile'),
84
+ env: join(run.layout.ingressConfigDir, 'ingress.env'),
85
+ cert: join(run.layout.ingressConfigDir, TLS_FILES.cert),
86
+ key: join(run.layout.ingressConfigDir, TLS_FILES.key),
87
+ token: join(run.layout.ingressConfigDir, TUNNEL_TOKEN_FILE),
88
+ });
89
+ /** The secret files each kind keeps in `ingress/config/`. A file another kind wrote is deleted. */
90
+ const secretFiles = (run, kind) => {
91
+ const f = files(run);
92
+ const all = { dev_tls: [f.cert, f.key], cloudflare_tunnel: [f.token], off: [] };
93
+ return { keep: all[kind], drop: [...all.dev_tls, ...all.cloudflare_tunnel].filter((path) => !all[kind].includes(path)) };
94
+ };
95
+ /**
96
+ * Deletes the certificate and the tunnel token. A revoked node keeps no ingress credential: Hive deletes the tunnel,
97
+ * and the keeper stops the ingress once the supervisor exits 77.
98
+ */
99
+ export async function dropIngressSecrets(layout) {
100
+ for (const name of [TLS_FILES.cert, TLS_FILES.key, TUNNEL_TOKEN_FILE])
101
+ await rm(join(layout.ingressConfigDir, name), { force: true });
102
+ }
103
+ const CADDY = { name: 'caddy', version: CADDY_VERSION, args: ['version'], matches: (out) => out.startsWith(`v${CADDY_VERSION} `) };
104
+ const CLOUDFLARED = { name: 'cloudflared', version: CLOUDFLARED_VERSION, args: ['--version'], matches: (out) => out.startsWith(`cloudflared version ${CLOUDFLARED_VERSION} `) };
105
+ const binariesFor = (kind) => (kind === 'dev_tls' ? [CADDY] : [CADDY, CLOUDFLARED]);
106
+ const globalOptions = (run) => `# Written by hive node run. It is rewritten within a minute of any change.
107
+ {
108
+ admin off
109
+ auto_https off
110
+ persist_config off
111
+ storage file_system ${run.layout.ingressStateDir}
112
+ }
113
+ `;
114
+ /** The access log drops the ticket, the Authorization header and cookies. */
115
+ const accessLog = (run) => ` log {
116
+ output file ${join(run.layout.ingressStateDir, 'access.log')}
117
+ format filter {
118
+ wrap json
119
+ fields {
120
+ request>uri query {
121
+ delete wsTicket
122
+ }
123
+ request>headers>Authorization delete
124
+ request>headers>Cookie delete
125
+ }
126
+ }
127
+ }
128
+ `;
129
+ /**
130
+ * The Caddyfile for dev_tls. It has no admin endpoint and stores nothing outside `ingress/state/`. Only POST and
131
+ * OPTIONS reach the ticket route, because a GET there used to serve the T3 UI. Both matchers are regular expressions,
132
+ * which are case-sensitive like the tunnel's rules. Caddy's `path` matcher is not.
133
+ */
134
+ export function caddyfile(run, port) {
135
+ const f = files(run);
136
+ const upstream = `127.0.0.1:${enginePort(run.ctx.env)}`;
137
+ return `${globalOptions(run)}
138
+ :${port} {
139
+ tls ${f.cert} ${f.key}
140
+
141
+ @ticket {
142
+ path_regexp ^${TICKET_PATH}$
143
+ method ${TICKET_METHODS.join(' ')}
144
+ }
145
+ @allowed path_regexp ${READ_PATH}
146
+ handle @ticket {
147
+ reverse_proxy ${upstream}
148
+ }
149
+ handle @allowed {
150
+ reverse_proxy ${upstream}
151
+ }
152
+ handle {
153
+ respond 404
154
+ }
155
+
156
+ ${accessLog(run)}}
157
+ `;
158
+ }
159
+ /**
160
+ * The Caddyfile for a tunnel: the ticket route's method filter, plain http on loopback only. cloudflared sends it the
161
+ * ticket path and nothing else. POST and OPTIONS go to the engine, any other method gets 405, and any other path 404.
162
+ * The site has no host, so the public hostname cloudflared forwards still matches.
163
+ */
164
+ export function ticketFilterCaddyfile(run) {
165
+ return `${globalOptions(run)}
166
+ http://:${ticketFilterPort(run.ctx.env)} {
167
+ bind 127.0.0.1
168
+
169
+ @ticket {
170
+ path_regexp ^${TICKET_PATH}$
171
+ method ${TICKET_METHODS.join(' ')}
172
+ }
173
+ @ticketOther path_regexp ^${TICKET_PATH}$
174
+ handle @ticket {
175
+ reverse_proxy 127.0.0.1:${enginePort(run.ctx.env)}
176
+ }
177
+ handle @ticketOther {
178
+ header Allow "${TICKET_METHODS.join(', ')}"
179
+ respond 405
180
+ }
181
+ handle {
182
+ respond 404
183
+ }
184
+
185
+ ${accessLog(run)}}
186
+ `;
187
+ }
188
+ /** Splits the certificate secret into the chain and the key. */
189
+ export function splitPem(value) {
190
+ const key = /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----[\s\S]+?-----END (?:EC |RSA )?PRIVATE KEY-----/.exec(value)?.[0];
191
+ const certs = value.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g);
192
+ if (key === undefined || certs === null)
193
+ throw new Error('the dev_tls secret must hold a PEM certificate chain and a PEM private key');
194
+ return { cert: `${certs.join('\n')}\n`, key: `${key}\n` };
195
+ }
196
+ /** A tunnel token is one line of base64. Anything else is refused before it reaches the disk. */
197
+ export function tunnelToken(value) {
198
+ const token = value.trim();
199
+ if (!/^[A-Za-z0-9+/=_-]{32,4096}$/.test(token))
200
+ throw new Error('the tunnel token from Hive is not one line of base64');
201
+ return token;
202
+ }
203
+ /**
204
+ * `ingress.env`, sourced by install.sh's `ingress-run`. It never holds the tunnel token. For a tunnel it names the
205
+ * loopback address cloudflared serves `/ready` on, and `ingress-run` refuses any address that is not 127.0.0.1.
206
+ */
207
+ export function ingressEnv(run, kind) {
208
+ const lines = ['# Written by hive node run.', `HIVE_INGRESS_KIND='${kind}'`];
209
+ if (kind === 'cloudflare_tunnel')
210
+ lines.push(`HIVE_TUNNEL_METRICS='127.0.0.1:${tunnelMetricsPort(run.ctx.env)}'`);
211
+ return `${lines.join('\n')}\n`;
212
+ }
213
+ const wantedCaddyfile = (run, plan) => (plan.kind === 'dev_tls' ? caddyfile(run, plan.port) : ticketFilterCaddyfile(run));
214
+ const secretKey = (secret) => `${secret.name}@${secret.version}`;
215
+ async function configHash(run, plan) {
216
+ const parts = [wantedCaddyfile(run, plan), ingressEnv(run, plan.kind)];
217
+ for (const path of secretFiles(run, plan.kind).keep)
218
+ parts.push((await readText(path)) ?? '');
219
+ for (const bin of binariesFor(plan.kind))
220
+ parts.push(`${bin.name} ${run.state.ingress[bin.name] ?? ''}`);
221
+ return sha256(parts.join('\0'));
222
+ }
223
+ function get(url, ca, signal) {
224
+ return new Promise((resolve) => {
225
+ const options = { host: url.hostname, port: url.port === '' ? undefined : Number(url.port), path: url.pathname, method: 'GET', timeout: 5_000, signal, ...(ca ? { ca } : {}) };
226
+ const req = (url.protocol === 'https:' ? httpsRequest : httpRequest)(options, (res) => {
227
+ let body = '';
228
+ res.setEncoding('utf8');
229
+ res.on('data', (chunk) => {
230
+ if (body.length < 2_000)
231
+ body += chunk;
232
+ });
233
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
234
+ res.on('error', (error) => resolve({ error: error.message }));
235
+ });
236
+ req.on('timeout', () => req.destroy(new Error('no answer within 5 seconds')));
237
+ req.on('error', (error) => resolve({ error: error.message }));
238
+ req.end();
239
+ });
240
+ }
241
+ /** The system store plus `NODE_EXTRA_CA_CERTS`, so a local box trusts the harness CA. */
242
+ function trustStore(run) {
243
+ const extra = run.ctx.env.NODE_EXTRA_CA_CERTS;
244
+ try {
245
+ if (extra !== undefined && extra !== '')
246
+ return [...rootCertificates, readFileSync(extra, 'utf8')];
247
+ }
248
+ catch {
249
+ // An unreadable extra CA leaves the system store, and the probe says what failed.
250
+ }
251
+ return [...rootCertificates];
252
+ }
253
+ /**
254
+ * Whether the ingress works on this machine. Returns why not, or null. Probed once per tick.
255
+ * - dev_tls: Caddy answers on the port with a certificate valid for the origin's host. Any HTTP answer counts,
256
+ * because the engine behind it may be down.
257
+ * - cloudflare_tunnel: cloudflared's `/ready` says a connection to Cloudflare is up, and the method filter answers a
258
+ * GET on the ticket route with 405.
259
+ */
260
+ function localProblem(run, plan) {
261
+ run.cache.ingress ??= (async () => {
262
+ if (plan.kind === 'dev_tls') {
263
+ const answer = await new Promise((resolve) => {
264
+ const req = httpsRequest({ host: '127.0.0.1', port: plan.port, servername: plan.host, ca: trustStore(run), path: '/.well-known/t3/environment', method: 'GET', timeout: 2_000, signal: run.signal }, (res) => {
265
+ res.resume();
266
+ resolve(null);
267
+ });
268
+ req.on('timeout', () => req.destroy(new Error('no answer within 2 seconds')));
269
+ req.on('error', (error) => resolve(error.message));
270
+ req.end();
271
+ });
272
+ return answer === null ? null : `https://${plan.host}:${plan.port} does not answer on loopback: ${answer}`;
273
+ }
274
+ const ready = await get(new URL(`http://127.0.0.1:${tunnelMetricsPort(run.ctx.env)}/ready`), undefined, run.signal);
275
+ if ('error' in ready)
276
+ return `cloudflared does not answer on 127.0.0.1:${tunnelMetricsPort(run.ctx.env)}: ${ready.error}`;
277
+ const connections = Number(JSON.parse(ready.body || '{}').readyConnections ?? 0);
278
+ if (ready.status !== 200 || !(connections > 0))
279
+ return `cloudflared has no connection to Cloudflare (ready ${ready.status}, ${connections} connections)`;
280
+ const filter = await get(new URL(`http://127.0.0.1:${ticketFilterPort(run.ctx.env)}${TICKET_PATH}`), undefined, run.signal);
281
+ if ('error' in filter)
282
+ return `the ticket filter does not answer on 127.0.0.1:${ticketFilterPort(run.ctx.env)}: ${filter.error}`;
283
+ if (filter.status !== 405)
284
+ return `the ticket filter answered a GET with ${filter.status}, not 405`;
285
+ return null;
286
+ })().catch((error) => error.message);
287
+ return run.cache.ingress;
288
+ }
289
+ /**
290
+ * The tunnel's public side: the environment route through Cloudflare, from this node. Returns why it fails, or null.
291
+ * A 502 means Cloudflare reached cloudflared and the engine behind it is down, which the engine step reports.
292
+ */
293
+ function edgeProblem(run, origin) {
294
+ run.cache.edge ??= get(new URL('/.well-known/t3/environment', origin), trustStore(run), run.signal).then((answer) => {
295
+ if ('error' in answer)
296
+ return `${origin} does not answer from this node: ${answer.error}`;
297
+ return answer.status === 200 || answer.status === 502 ? null : `${origin}/.well-known/t3/environment answered ${answer.status} through Cloudflare`;
298
+ });
299
+ return run.cache.edge;
300
+ }
301
+ /** The origin Hive shows for this node, read once per tick and only while it is not yet the one the node publishes. */
302
+ function hiveShows(run) {
303
+ run.cache.echo ??= run.ctx.api.json('GET', '/api/v0/nodes/me', { token: run.node.token, key: run.key, signal: run.signal }).then((me) => (typeof me.stream_origin === 'string' ? me.stream_origin : null));
304
+ return run.cache.echo;
305
+ }
306
+ const since = (run, at) => (at === null ? Infinity : run.ctx.now().getTime() - Date.parse(at));
307
+ const linkOf = (run, bin) => join(run.layout.binDir, bin.name);
308
+ const releasePath = (bin) => join('releases', bin.name, bin.version, bin.name);
309
+ async function binaryReady(run, bin) {
310
+ return run.state.ingress[bin.name] === bin.version && (await linkTarget(linkOf(run, bin))) === releasePath(bin) && (await isExecutable(linkOf(run, bin)));
311
+ }
312
+ const label = (bin) => (bin.name === 'caddy' ? 'Caddy' : 'cloudflared');
313
+ const what = (kind) => (kind === 'dev_tls' ? 'certificate' : 'tunnel token');
314
+ async function present(paths) {
315
+ const found = [];
316
+ for (const path of paths)
317
+ if ((await readText(path)) !== null)
318
+ found.push(path);
319
+ return found;
320
+ }
321
+ async function observeIngress(run) {
322
+ const plan = ingressPlan(run);
323
+ const f = files(run);
324
+ if (plan.kind === 'unsupported')
325
+ return { status: 'needs_action', detail: plan.detail, fix: plan.fix };
326
+ if (plan.kind === 'off') {
327
+ const left = await present([f.env, ...secretFiles(run, 'off').drop]);
328
+ if (left.length > 0 || run.state.ingress.kind !== null)
329
+ return { status: 'stale', detail: `${plan.why}, and the ingress is still configured` };
330
+ return { status: 'ok', detail: plan.why };
331
+ }
332
+ const stale = [];
333
+ for (const bin of binariesFor(plan.kind))
334
+ if (!(await binaryReady(run, bin)))
335
+ stale.push(`${label(bin)} ${bin.version} is not installed`);
336
+ const own = secretFiles(run, plan.kind);
337
+ if (run.state.ingress.secret !== secretKey(plan.secret) || (await present(own.keep)).length < own.keep.length)
338
+ stale.push(`${what(plan.kind)} ${plan.secret.name} version ${plan.secret.version} is not on the node`);
339
+ if ((await present(own.drop)).length > 0)
340
+ stale.push('files of another ingress kind are still on the node');
341
+ if ((await readText(f.caddyfile)) !== wantedCaddyfile(run, plan))
342
+ stale.push('the Caddyfile differs from what Hive wants');
343
+ if ((await readText(f.env)) !== ingressEnv(run, plan.kind))
344
+ stale.push('ingress.env differs from what Hive wants');
345
+ if (stale.length === 0 && run.state.ingress.config_hash !== (await configHash(run, plan)))
346
+ stale.push('the ingress has not restarted since its files changed');
347
+ if (stale.length > 0)
348
+ return { status: 'stale', detail: stale.join('; ') };
349
+ const name = plan.kind === 'dev_tls' ? 'dev_tls' : 'the tunnel';
350
+ const problem = await localProblem(run, plan);
351
+ if (problem !== null) {
352
+ return since(run, run.state.ingress.restarted_at) < START_GRACE_MS ? { status: 'ok', detail: `${name} is starting` } : { status: 'failing', detail: problem, fix: 'rerun_install' };
353
+ }
354
+ if (run.state.ingress.echoed !== plan.origin) {
355
+ const shown = await hiveShows(run);
356
+ if (shown === plan.origin) {
357
+ // A fact read from Hive, kept so the next ticks do not ask again. It is the only state an observation sets.
358
+ run.state.ingress.echoed = shown;
359
+ }
360
+ else if (run.state.ingress.origin !== plan.origin || since(run, run.state.ingress.published_at) < ECHO_GRACE_MS) {
361
+ return { status: 'ok', detail: `${name} at ${plan.origin}, waiting for Hive to show it` };
362
+ }
363
+ else {
364
+ return { status: 'failing', detail: `Hive shows ${shown ?? 'no origin'} for this node, not ${plan.origin}`, fix: 'rerun_install' };
365
+ }
366
+ }
367
+ if (plan.kind === 'cloudflare_tunnel') {
368
+ const edge = await edgeProblem(run, plan.origin);
369
+ if (edge !== null) {
370
+ // A new hostname can take a while to resolve, and a resolver may have cached its absence.
371
+ const settling = Math.min(since(run, run.state.ingress.restarted_at), since(run, run.state.ingress.published_at)) < ECHO_GRACE_MS;
372
+ return settling ? { status: 'ok', detail: `the tunnel is connected, waiting for ${plan.origin} to answer: ${edge}` } : { status: 'failing', detail: edge };
373
+ }
374
+ return { status: 'ok', detail: `the tunnel is connected, ${plan.origin} answers, and Hive shows it` };
375
+ }
376
+ return { status: 'ok', detail: `dev_tls at ${plan.origin}, and Hive shows it` };
377
+ }
378
+ async function installBinary(run, bin) {
379
+ const root = join(run.layout.binDir, 'releases', bin.name);
380
+ const route = run.desired?.versions?.channel === 'dev' ? 'dev' : bin.version;
381
+ const download = await fetchArtifact(run, bin.name, route, root);
382
+ const stage = join(root, `.stage-${process.pid}`);
383
+ try {
384
+ const unpacked = await unpack(run, download.file, stage, bin.name);
385
+ const probe = await run.exec(join(unpacked, bin.name), bin.args);
386
+ if (probe.code !== 0 || !bin.matches(probe.stdout))
387
+ throw new Error(`the downloaded ${bin.name} is not ${bin.version}: ${(probe.stdout || probe.stderr).trim().slice(0, 200)}`);
388
+ const dest = join(root, bin.version);
389
+ await rm(dest, { recursive: true, force: true });
390
+ await rename(unpacked, dest);
391
+ await switchLink(linkOf(run, bin), releasePath(bin));
392
+ run.state.ingress[bin.name] = bin.version;
393
+ }
394
+ finally {
395
+ await rm(stage, { recursive: true, force: true });
396
+ await rm(download.file, { force: true });
397
+ }
398
+ }
399
+ async function fetchSecret(run, secret) {
400
+ const answer = await run.ctx.api.json('GET', `/api/v0/nodes/me/secrets/${secret.name}`, { query: { version: String(secret.version) }, token: run.node.token, key: run.key, signal: run.signal });
401
+ if (typeof answer.value !== 'string')
402
+ throw new Error(`Hive's secret ${secret.name} version ${secret.version} has no value`);
403
+ return answer.value;
404
+ }
405
+ /** Writes the kind's secret files. `ingress/config/` is setgid hive-ingress, so 0640 lets the ingress read them and keeps the engine's user out. */
406
+ async function writeSecret(run, plan) {
407
+ const f = files(run);
408
+ const value = await fetchSecret(run, plan.secret);
409
+ if (plan.kind === 'dev_tls') {
410
+ const pem = splitPem(value);
411
+ await writeIfChanged(f.cert, pem.cert, 0o640);
412
+ await writeIfChanged(f.key, pem.key, 0o640);
413
+ }
414
+ else {
415
+ await writeIfChanged(f.token, tunnelToken(value), 0o640);
416
+ }
417
+ run.state.ingress.secret = secretKey(plan.secret);
418
+ }
419
+ async function repairIngress(run) {
420
+ const plan = ingressPlan(run);
421
+ const f = files(run);
422
+ if (plan.kind === 'unsupported')
423
+ return;
424
+ if (plan.kind === 'off') {
425
+ // ingress.env goes first: without it neither adapter starts the ingress again, after a reboot or a container restart.
426
+ await rm(f.env, { force: true });
427
+ await serviceControl(run, 'stop', 'ingress');
428
+ for (const path of secretFiles(run, 'off').drop)
429
+ await rm(path, { force: true });
430
+ run.state.ingress = { ...run.state.ingress, kind: null, secret: null, config_hash: null, origin: null, published_at: null, echoed: null };
431
+ return;
432
+ }
433
+ for (const bin of binariesFor(plan.kind))
434
+ if (!(await binaryReady(run, bin)))
435
+ await installBinary(run, bin);
436
+ const own = secretFiles(run, plan.kind);
437
+ for (const path of own.drop)
438
+ await rm(path, { force: true });
439
+ if (run.state.ingress.secret !== secretKey(plan.secret) || (await present(own.keep)).length < own.keep.length)
440
+ await writeSecret(run, plan);
441
+ await writeIfChanged(f.caddyfile, wantedCaddyfile(run, plan), 0o640);
442
+ // ingress.env comes last: the foreground keeper starts the ingress as soon as it exists.
443
+ await writeIfChanged(f.env, ingressEnv(run, plan.kind), 0o640);
444
+ const hash = await configHash(run, plan);
445
+ const changed = hash !== run.state.ingress.config_hash;
446
+ // A broken ingress is restarted, paced like the engine. Its unit already restarts a crashed process. An edge that
447
+ // does not answer while cloudflared is connected is a DNS or tunnel config problem on Hive's side, which a restart
448
+ // does not fix, so it only turns the row red.
449
+ const stuck = !changed && since(run, run.state.ingress.restarted_at) >= Math.max(START_GRACE_MS, RESTART_PACE_MS) && (await localProblem(run, plan)) !== null;
450
+ if (changed || stuck) {
451
+ await serviceControl(run, 'restart', 'ingress');
452
+ run.state.ingress.config_hash = hash;
453
+ run.state.ingress.restarted_at = run.ctx.now().toISOString();
454
+ run.cache.ingress = undefined;
455
+ run.cache.edge = undefined;
456
+ }
457
+ if (run.state.ingress.origin !== plan.origin) {
458
+ run.state.ingress.origin = plan.origin;
459
+ run.state.ingress.published_at = run.ctx.now().toISOString();
460
+ run.state.ingress.echoed = null;
461
+ }
462
+ else if (run.state.ingress.echoed !== plan.origin && since(run, run.state.ingress.published_at) >= ECHO_GRACE_MS) {
463
+ // Hive learns the origin from the relay's batch. Clearing the relay's memory makes the next batch go out this tick.
464
+ run.state.relay = null;
465
+ }
466
+ run.state.ingress.kind = plan.kind;
467
+ }
468
+ export const ingressStep = {
469
+ id: 'ingress',
470
+ needs: ['desired'],
471
+ observe: observeIngress,
472
+ repair: repairIngress,
473
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The supervisor's exit codes. The keeper (install.sh, plan item 7) acts on them, so they are
3
+ * one exported constant and are documented in docs/supervisor.md.
4
+ */
5
+ export declare const EXIT: {
6
+ /** The supervisor swapped `cli/current` and wants the keeper to start it again at once. */
7
+ readonly RESTART: 75;
8
+ /** Hive revoked or removed this node. The supervisor wrote `node/revoked` before it exited. */
9
+ readonly REVOKED: 77;
10
+ };
11
+ export declare const DEFAULT_STATE_DIR = "/var/lib/hive";
12
+ /** Where install.sh puts the root-owned helpers, `servicectl` among them. `HIVE_LIB_DIR` moves it for tests. */
13
+ export declare const DEFAULT_LIB_DIR = "/usr/local/lib/hive";
14
+ /** Where every file of a node lives. The one place paths are decided, so tests only set `HIVE_STATE_DIR`. */
15
+ export type Layout = {
16
+ root: string;
17
+ /** Node key, `node.json`, supervisor state. Mode 0700. */
18
+ nodeDir: string;
19
+ lockFile: string;
20
+ supervisorState: string;
21
+ desiredCache: string;
22
+ revokedMarker: string;
23
+ repairRequest: string;
24
+ reportDir: string;
25
+ reportFile: string;
26
+ /** `cli/`: one directory per CLI release, plus the `current` and `previous` links. */
27
+ cliDir: string;
28
+ cliCurrent: string;
29
+ cliPrevious: string;
30
+ /** The model key from Hive, 0600 in `node/`. Only the supervisor reads it. It reaches the engine through `service.env`. */
31
+ modelKey: string;
32
+ /** Engine database copies made before an upgrade. */
33
+ backupsDir: string;
34
+ /** Pinned binaries: `bin/t3`, `bin/caddy` and `bin/cloudflared` are links into versioned directories here. Mode 0755, `hive-node`. */
35
+ binDir: string;
36
+ /** `bin/tools/`: links to the agent tools the toolchain step installs, such as `claude`. The engine's PATH starts here. */
37
+ toolsDir: string;
38
+ /** The engine's own data (`T3CODE_HOME`). 2770, `hive:hive`. */
39
+ engineHome: string;
40
+ /** `engine-config/service.env`, 0640 `hive-node:hive`. The supervisor is its only writer. */
41
+ serviceEnv: string;
42
+ /** `ingress/config/`, 2750 `hive-node:hive-ingress`: the Caddyfile, `ingress.env`, and the certificate or the tunnel token. */
43
+ ingressConfigDir: string;
44
+ ingressStateDir: string;
45
+ /** The one way to start, stop or restart the engine and the ingress. See docs/supervisor.md, "Service control". */
46
+ servicectl: string;
47
+ /** install.sh's check of a CLI release, the one the keeper runs before it starts a release. */
48
+ releaseVerify: string;
49
+ };
50
+ export declare function stateRoot(env: NodeJS.ProcessEnv): string;
51
+ export declare function layoutOf(env: NodeJS.ProcessEnv): Layout;
52
+ /**
53
+ * Node mode: this machine keeps its identity under the state root. It holds when `HIVE_STATE_DIR` is set or
54
+ * `/var/lib/hive/node` already exists. Anything else is a personal machine that keeps `~/.config/hive`.
55
+ */
56
+ export declare function nodeMode(env: NodeJS.ProcessEnv): boolean;