overvues 0.0.1 → 0.4.10
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.
- package/README.md +58 -2
- package/dist/ansi.js +24 -0
- package/dist/attach-client.js +586 -0
- package/dist/auth-connect-browser.js +112 -0
- package/dist/auth-connect.js +306 -0
- package/dist/browser-bootstrap.js +190 -0
- package/dist/browser-loopback.js +289 -0
- package/dist/build-identity.js +6 -0
- package/dist/codex-reviewer-apparmor.json +4 -0
- package/dist/codex-reviewer-seccomp.json +1238 -0
- package/dist/codex-runtime-protocol.js +1 -0
- package/dist/codex-subscription.js +53 -0
- package/dist/config.js +297 -0
- package/dist/connect-comparison-code.js +26 -0
- package/dist/development-runner.js +109 -0
- package/dist/dns-doctor.js +390 -0
- package/dist/docker-names.js +47 -0
- package/dist/doctor.js +114 -0
- package/dist/gadget-job.js +804 -0
- package/dist/health-check.js +112 -0
- package/dist/help.js +71 -0
- package/dist/host-auth.js +22 -0
- package/dist/host-diagnostics.js +20 -0
- package/dist/host-runtime-identity.js +39 -0
- package/dist/host-runtime-metadata.js +56 -0
- package/dist/host-service.js +377 -0
- package/dist/host-stack.js +484 -0
- package/dist/host-supervisor.js +237 -0
- package/dist/host-update.js +387 -0
- package/dist/hub-address.js +100 -0
- package/dist/hub-client.js +459 -0
- package/dist/hub-kind.js +88 -0
- package/dist/identity.js +73 -0
- package/dist/index.js +185 -0
- package/dist/init.js +295 -0
- package/dist/isolated-run-cache.js +116 -0
- package/dist/local-stack.js +685 -0
- package/dist/machine-capacity.js +128 -0
- package/dist/managed-runner-image.js +13 -0
- package/dist/os-acted-record.js +49 -0
- package/dist/os-adapter.js +8190 -0
- package/dist/os-command.js +292 -0
- package/dist/os-handoff.js +274 -0
- package/dist/os-keychain.js +247 -0
- package/dist/os-machine.js +818 -0
- package/dist/os-owner.js +61 -0
- package/dist/os-private-file.js +98 -0
- package/dist/os-protocol.js +468 -0
- package/dist/os-session-store.js +133 -0
- package/dist/os-status.js +102 -0
- package/dist/picker.js +863 -0
- package/dist/portable-workspace-capability.js +60 -0
- package/dist/project-environment-capability.js +62 -0
- package/dist/project-environment.js +28 -0
- package/dist/project-preparation.js +134 -0
- package/dist/readiness.js +28 -0
- package/dist/redaction.js +27 -0
- package/dist/reviewer-isolation-capability.js +61 -0
- package/dist/runner-api-auth.js +80 -0
- package/dist/runner-command-fence.js +536 -0
- package/dist/runner-inspection.js +57 -0
- package/dist/runner-inventory.js +587 -0
- package/dist/runner-server.js +2520 -0
- package/dist/runner-session.js +470 -0
- package/dist/runner-slug-folder.js +39 -0
- package/dist/runner-slug.js +40 -0
- package/dist/setup.js +139 -0
- package/dist/shutdown.js +102 -0
- package/dist/splash.js +65 -0
- package/dist/staged-workspaces.js +441 -0
- package/dist/staging-disk.js +97 -0
- package/dist/terminal-lane.js +339 -0
- package/dist/terminal-recovery.js +502 -0
- package/licenses/capnweb.txt +23 -0
- package/licenses/moby-profiles.txt +212 -0
- package/licenses/ws.txt +22 -0
- package/package.json +28 -7
- package/cli.js +0 -2
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which hub addresses `tiller` will talk to.
|
|
3
|
+
*
|
|
4
|
+
* A hub is reached at an https origin under one of a small set of parent
|
|
5
|
+
* domains: `workers.dev` for self-deployed hubs (`<worker>.workers.dev` or
|
|
6
|
+
* `<worker>.<subdomain>.workers.dev`, one or two labels) and
|
|
7
|
+
* `build.overvues.dev` for hosted ones (`<username>.build.overvues.dev`,
|
|
8
|
+
* exactly one label; packages/hub/scripts/hub-names.mjs). Nothing deeper is
|
|
9
|
+
* accepted, and neither is a parent itself: `build.overvues.dev` is the
|
|
10
|
+
* shared sign-in front door, and the rest of `overvues.dev` belongs to
|
|
11
|
+
* Overvues, which is not a hub and may serve other people's content.
|
|
12
|
+
*
|
|
13
|
+
* `TILLER_HUB_PARENT_DOMAINS` (comma-separated) replaces that set; it is read
|
|
14
|
+
* from the process environment or `tiller`'s own config folder, never from a
|
|
15
|
+
* `.env` in the folder `tiller` is run from (config.ts). Depth goes with the
|
|
16
|
+
* parent, not with where it was set: `workers.dev` always allows one or two
|
|
17
|
+
* labels (its own two-level naming), and every other parent exactly one, so
|
|
18
|
+
* an override names the hub's immediate parent domain.
|
|
19
|
+
*
|
|
20
|
+
* The address must be written exactly as its origin: lowercase, no port, no
|
|
21
|
+
* path, query, fragment or credentials, no trailing dot, and no punycode
|
|
22
|
+
* label. Anything that only resembles an allowed address is refused rather
|
|
23
|
+
* than corrected, because the address decides where the machine's
|
|
24
|
+
* credentials are sent.
|
|
25
|
+
*/
|
|
26
|
+
import { envVar } from "./identity.js";
|
|
27
|
+
export const DEFAULT_HUB_PARENT_DOMAINS = ["workers.dev", "build.overvues.dev"];
|
|
28
|
+
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
29
|
+
function isPlainLabel(label) {
|
|
30
|
+
// `xn--` labels are internationalised names written in ASCII; a hub never
|
|
31
|
+
// needs one, and they are how look-alike names are spelled.
|
|
32
|
+
return LABEL.test(label) && !label.startsWith("xn--");
|
|
33
|
+
}
|
|
34
|
+
/** A parent domain entry: at least two plain lowercase labels, nothing else. */
|
|
35
|
+
export function isValidHubParentDomain(value) {
|
|
36
|
+
const labels = value.split(".");
|
|
37
|
+
return labels.length >= 2 && labels.every(isPlainLabel);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The parent domains in force. Entries that are not plain domain names (a
|
|
41
|
+
* bare top-level domain, a leading dot, uppercase) are ignored; if nothing
|
|
42
|
+
* usable is left the default set applies, so a typo cannot widen the set.
|
|
43
|
+
*/
|
|
44
|
+
export function hubParentDomains(value = process.env[envVar("HUB_PARENT_DOMAINS")]) {
|
|
45
|
+
if (!value?.trim())
|
|
46
|
+
return [...DEFAULT_HUB_PARENT_DOMAINS];
|
|
47
|
+
const domains = value.split(",").map((entry) => entry.trim()).filter(isValidHubParentDomain);
|
|
48
|
+
return domains.length ? [...new Set(domains)] : [...DEFAULT_HUB_PARENT_DOMAINS];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* How many labels a hub's host may have below its parent domain: one or two
|
|
52
|
+
* under `workers.dev` (`<worker>.<subdomain>.workers.dev`), exactly one under
|
|
53
|
+
* any other parent.
|
|
54
|
+
*/
|
|
55
|
+
function maxLabelsUnder(parent) {
|
|
56
|
+
return parent === "workers.dev" ? 2 : 1;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* True for an https hub origin under one of the parent domains: one or two
|
|
60
|
+
* labels under `workers.dev`, exactly one under any other.
|
|
61
|
+
*/
|
|
62
|
+
export function isAllowedHubUrl(hubUrl, parents = hubParentDomains()) {
|
|
63
|
+
if (!hubUrl)
|
|
64
|
+
return false;
|
|
65
|
+
// One trailing slash is the same origin; the saved form has none.
|
|
66
|
+
const written = hubUrl.endsWith("/") ? hubUrl.slice(0, -1) : hubUrl;
|
|
67
|
+
let url;
|
|
68
|
+
try {
|
|
69
|
+
url = new URL(written);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
if (url.protocol !== "https:"
|
|
75
|
+
|| url.username !== ""
|
|
76
|
+
|| url.password !== ""
|
|
77
|
+
|| url.port !== ""
|
|
78
|
+
|| (url.pathname !== "" && url.pathname !== "/")
|
|
79
|
+
|| url.search !== ""
|
|
80
|
+
|| url.hash !== ""
|
|
81
|
+
// The URL parser lowercases, converts Unicode to punycode and drops a
|
|
82
|
+
// default port. Requiring the input to be its own origin refuses each
|
|
83
|
+
// of those instead of quietly accepting a different spelling.
|
|
84
|
+
|| url.origin !== written)
|
|
85
|
+
return false;
|
|
86
|
+
const host = url.hostname;
|
|
87
|
+
const labels = host.split(".");
|
|
88
|
+
if (!labels.every(isPlainLabel))
|
|
89
|
+
return false;
|
|
90
|
+
return parents.some((parent) => isValidHubParentDomain(parent)
|
|
91
|
+
&& host.length > parent.length + 1
|
|
92
|
+
&& host.endsWith(`.${parent}`)
|
|
93
|
+
&& labels.length - parent.split(".").length <= maxLabelsUnder(parent));
|
|
94
|
+
}
|
|
95
|
+
/** The parent domains for messages: "workers.dev or build.overvues.dev". */
|
|
96
|
+
export function hubParentDomainsText(parents = hubParentDomains()) {
|
|
97
|
+
if (parents.length <= 1)
|
|
98
|
+
return parents.join("");
|
|
99
|
+
return `${parents.slice(0, -1).join(", ")} or ${parents[parents.length - 1]}`;
|
|
100
|
+
}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { OS_HUB_TO_MACHINE_TYPES } from "./os-protocol.js";
|
|
3
|
+
import { CLI } from "./identity.js";
|
|
4
|
+
const HEARTBEAT_MS = 30_000;
|
|
5
|
+
const RECONNECT_MIN_MS = 1_000;
|
|
6
|
+
const RECONNECT_MAX_MS = 30_000;
|
|
7
|
+
const MAX_QUEUED_MESSAGES = 100;
|
|
8
|
+
const PONG_TIMEOUT_MS = 90_000; // 90s absolute threshold — within CF's 100s idle timeout
|
|
9
|
+
/**
|
|
10
|
+
* A missed pong is confirmed after a fresh ping and this grace: a timer runs
|
|
11
|
+
* before pending socket reads, so after the event loop was blocked the pongs
|
|
12
|
+
* that did arrive are still unread when the heartbeat looks at them.
|
|
13
|
+
*/
|
|
14
|
+
const PONG_GRACE_MS = 5_000;
|
|
15
|
+
/** The first reconnect after a drop waits at most this long (jitter only). */
|
|
16
|
+
const RECONNECT_FIRST_JITTER_MS = 500;
|
|
17
|
+
const CONNECT_TIMEOUT_MS = 30_000; // abort and retry if WS doesn't open within 30s
|
|
18
|
+
export class HubClient extends EventEmitter {
|
|
19
|
+
config;
|
|
20
|
+
ws = null;
|
|
21
|
+
heartbeatTimer = null;
|
|
22
|
+
reconnectAttempts = 0;
|
|
23
|
+
pongGraceTimer = null;
|
|
24
|
+
reconnectTimer = null;
|
|
25
|
+
connectTimer = null;
|
|
26
|
+
closed = false;
|
|
27
|
+
lastSeq = 0;
|
|
28
|
+
sessionId = null;
|
|
29
|
+
sessionLifecycle = "owner";
|
|
30
|
+
machineId = null;
|
|
31
|
+
terminalFastLane = false;
|
|
32
|
+
// Message queue — ring buffer for messages during disconnect
|
|
33
|
+
pendingMessages = [];
|
|
34
|
+
// Pong-based liveness detection
|
|
35
|
+
lastPongAt = 0;
|
|
36
|
+
heartbeatCycle = 0;
|
|
37
|
+
constructor(config) {
|
|
38
|
+
super();
|
|
39
|
+
this.config = config;
|
|
40
|
+
}
|
|
41
|
+
connect() {
|
|
42
|
+
this.openWs();
|
|
43
|
+
}
|
|
44
|
+
setSessionId(id, options = {}) {
|
|
45
|
+
this.sessionId = id;
|
|
46
|
+
this.sessionLifecycle = options.lifecycle ?? "owner";
|
|
47
|
+
}
|
|
48
|
+
setMachineId(id) {
|
|
49
|
+
this.machineId = id;
|
|
50
|
+
}
|
|
51
|
+
sendMessage(id, sessionId, content) {
|
|
52
|
+
this.wsSend({ type: "message", id, sessionId, content });
|
|
53
|
+
}
|
|
54
|
+
sendSessionAlive(sessionId) {
|
|
55
|
+
if (this.sessionLifecycle === "viewer") {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
this.wsSend({ type: "session-alive", sessionId });
|
|
59
|
+
}
|
|
60
|
+
sendSessionEnd(sessionId) {
|
|
61
|
+
this.wsSend({ type: "session-end", sessionId });
|
|
62
|
+
}
|
|
63
|
+
sendResize(sessionId, cols, rows) {
|
|
64
|
+
const id = crypto.randomUUID();
|
|
65
|
+
this.sendMessage(id, sessionId, {
|
|
66
|
+
role: "user",
|
|
67
|
+
type: "resize",
|
|
68
|
+
data: JSON.stringify({ cols, rows }),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
supportsTerminalFastLane() {
|
|
72
|
+
return this.terminalFastLane;
|
|
73
|
+
}
|
|
74
|
+
sendTerminalInput(sessionId, clientId, inputSeq, data, size) {
|
|
75
|
+
return this.wsSendLive({
|
|
76
|
+
type: "terminal-input",
|
|
77
|
+
sessionId,
|
|
78
|
+
clientId,
|
|
79
|
+
inputSeq,
|
|
80
|
+
data,
|
|
81
|
+
...(size ? { cols: size.cols, rows: size.rows } : {}),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
sendTerminalDetach(sessionId, clientId) {
|
|
85
|
+
return this.wsSendLive({ type: "terminal-detach", sessionId, clientId });
|
|
86
|
+
}
|
|
87
|
+
sendTerminalControl(sessionId, clientId, controlSeq, action, size, options) {
|
|
88
|
+
return this.wsSendLive({
|
|
89
|
+
type: "terminal-control",
|
|
90
|
+
sessionId,
|
|
91
|
+
clientId,
|
|
92
|
+
controlSeq,
|
|
93
|
+
action,
|
|
94
|
+
...(size ? { cols: size.cols, rows: size.rows } : {}),
|
|
95
|
+
...(options?.claim !== undefined ? { claim: options.claim } : {}),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
sendTerminalInputAck(sessionId, clientId, inputSeq, ok, error) {
|
|
99
|
+
return this.wsSendLive({
|
|
100
|
+
type: "terminal-input-ack",
|
|
101
|
+
sessionId,
|
|
102
|
+
clientId,
|
|
103
|
+
inputSeq,
|
|
104
|
+
ok,
|
|
105
|
+
...(error ? { error } : {}),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
sendTerminalControlAck(sessionId, clientId, controlSeq, ok, error) {
|
|
109
|
+
return this.wsSendLive({
|
|
110
|
+
type: "terminal-control-ack",
|
|
111
|
+
sessionId,
|
|
112
|
+
clientId,
|
|
113
|
+
controlSeq,
|
|
114
|
+
ok,
|
|
115
|
+
...(error ? { error } : {}),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
sendMachineAlive(machineId) {
|
|
119
|
+
this.wsSend({ type: "machine-alive", machineId });
|
|
120
|
+
}
|
|
121
|
+
sendMachineUpdateRunnerState(machineId, runnerState, expectedVersion) {
|
|
122
|
+
this.wsSend({ type: "machine-update-runner-state", machineId, runnerState, expectedVersion });
|
|
123
|
+
}
|
|
124
|
+
/** Tells the Hub a runner command arrived, before it runs (`command-receipts`). */
|
|
125
|
+
sendRunnerControlReceived(requestId) {
|
|
126
|
+
this.wsSend({ type: "runner-control-received", requestId });
|
|
127
|
+
}
|
|
128
|
+
sendRunnerControlResponse(requestId, ok, result, error, errorCode, currentCommandGeneration) {
|
|
129
|
+
this.wsSend({
|
|
130
|
+
type: "runner-control-response",
|
|
131
|
+
requestId,
|
|
132
|
+
ok,
|
|
133
|
+
...(result !== undefined ? { result } : {}),
|
|
134
|
+
...(error ? { error } : {}),
|
|
135
|
+
...(errorCode ? { errorCode } : {}),
|
|
136
|
+
...(currentCommandGeneration !== undefined ? { currentCommandGeneration } : {}),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/** An answer or a report about the OS (`os-protocol.ts`). Queued while the socket is down. */
|
|
140
|
+
sendOsMessage(message) {
|
|
141
|
+
this.wsSend(message);
|
|
142
|
+
}
|
|
143
|
+
/** Returns the highest message seq seen so far. */
|
|
144
|
+
getLastSeq() {
|
|
145
|
+
return this.lastSeq;
|
|
146
|
+
}
|
|
147
|
+
/** Advance only after the terminal consumer has completed its stdout write. */
|
|
148
|
+
markMessageComplete(seq) {
|
|
149
|
+
if (Number.isInteger(seq) && seq > this.lastSeq)
|
|
150
|
+
this.lastSeq = seq;
|
|
151
|
+
}
|
|
152
|
+
/** Returns the underlying WebSocket for bufferedAmount checks. */
|
|
153
|
+
getSocket() {
|
|
154
|
+
return this.ws;
|
|
155
|
+
}
|
|
156
|
+
close() {
|
|
157
|
+
this.closed = true;
|
|
158
|
+
this.terminalFastLane = false;
|
|
159
|
+
this.stopHeartbeat();
|
|
160
|
+
this.clearReconnectTimer();
|
|
161
|
+
this.clearConnectTimer();
|
|
162
|
+
this.closeSocket();
|
|
163
|
+
}
|
|
164
|
+
// ── Internal ─────────────────────────────────────────────────────
|
|
165
|
+
clearConnectTimer() {
|
|
166
|
+
if (this.connectTimer) {
|
|
167
|
+
clearTimeout(this.connectTimer);
|
|
168
|
+
this.connectTimer = null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
clearReconnectTimer() {
|
|
172
|
+
if (this.reconnectTimer) {
|
|
173
|
+
clearTimeout(this.reconnectTimer);
|
|
174
|
+
this.reconnectTimer = null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
closeSocket(target = this.ws) {
|
|
178
|
+
if (!target)
|
|
179
|
+
return;
|
|
180
|
+
if (this.ws === target) {
|
|
181
|
+
this.ws = null;
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
target.close();
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// Ignore close failures while tearing down a dead socket.
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
forceReconnect(target = this.ws) {
|
|
191
|
+
this.clearConnectTimer();
|
|
192
|
+
this.stopHeartbeat();
|
|
193
|
+
this.terminalFastLane = false;
|
|
194
|
+
this.closeSocket(target);
|
|
195
|
+
this.emit("disconnected");
|
|
196
|
+
if (!this.closed) {
|
|
197
|
+
this.scheduleReconnect();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
openWs() {
|
|
201
|
+
this.clearReconnectTimer();
|
|
202
|
+
const wsUrl = this.config.hubUrl
|
|
203
|
+
.replace(/^http/, "ws")
|
|
204
|
+
.replace(/\/$/, "");
|
|
205
|
+
const url = `${wsUrl}/parties/hub/hub`;
|
|
206
|
+
// Node.js WebSocket supports headers option for the upgrade request
|
|
207
|
+
const ws = new WebSocket(url, {
|
|
208
|
+
headers: this.config.cfAccessHeaders,
|
|
209
|
+
});
|
|
210
|
+
this.ws = ws;
|
|
211
|
+
// Abort and retry if the connection doesn't open within the timeout.
|
|
212
|
+
// Without this, a hanging TCP/TLS handshake stalls reconnection forever.
|
|
213
|
+
this.clearConnectTimer();
|
|
214
|
+
this.connectTimer = setTimeout(() => {
|
|
215
|
+
if (this.ws === ws && ws.readyState === WebSocket.CONNECTING) {
|
|
216
|
+
console.error(`${CLI.logTag} Connect timeout — aborting and retrying at ${new Date().toISOString()}`);
|
|
217
|
+
this.forceReconnect(ws);
|
|
218
|
+
}
|
|
219
|
+
}, CONNECT_TIMEOUT_MS);
|
|
220
|
+
ws.addEventListener("open", () => {
|
|
221
|
+
if (this.ws !== ws)
|
|
222
|
+
return;
|
|
223
|
+
this.clearConnectTimer();
|
|
224
|
+
// No auth message needed: the hub credential is sent on upgrade
|
|
225
|
+
this.reconnectAttempts = 0;
|
|
226
|
+
this.lastPongAt = Date.now();
|
|
227
|
+
this.heartbeatCycle = 0;
|
|
228
|
+
this.terminalFastLane = false;
|
|
229
|
+
this.startHeartbeat();
|
|
230
|
+
// Identity first: runner answers queued while the socket was down are
|
|
231
|
+
// accepted by the Hub only from a connection bound to this machine.
|
|
232
|
+
if (this.machineId) {
|
|
233
|
+
this.sendMachineAlive(this.machineId);
|
|
234
|
+
}
|
|
235
|
+
this.drainQueue();
|
|
236
|
+
// Gap-fill is handled via HTTP in attach-client (not WS reconnect)
|
|
237
|
+
this.emit("connected");
|
|
238
|
+
});
|
|
239
|
+
ws.addEventListener("message", (event) => {
|
|
240
|
+
if (this.ws !== ws)
|
|
241
|
+
return;
|
|
242
|
+
this.handleMessage(event.data);
|
|
243
|
+
});
|
|
244
|
+
ws.addEventListener("close", (event) => {
|
|
245
|
+
if (this.ws !== ws)
|
|
246
|
+
return;
|
|
247
|
+
this.ws = null;
|
|
248
|
+
this.clearConnectTimer();
|
|
249
|
+
this.stopHeartbeat();
|
|
250
|
+
this.terminalFastLane = false;
|
|
251
|
+
const reason = event.reason || "";
|
|
252
|
+
console.error(`${CLI.logTag} Disconnected (code=${event.code} clean=${event.wasClean}${reason ? ` reason="${reason}"` : ""}) at ${new Date().toISOString()}`);
|
|
253
|
+
this.emit("disconnected");
|
|
254
|
+
if (!this.closed)
|
|
255
|
+
this.scheduleReconnect();
|
|
256
|
+
});
|
|
257
|
+
ws.addEventListener("error", (event) => {
|
|
258
|
+
if (this.ws !== ws)
|
|
259
|
+
return;
|
|
260
|
+
const msg = event.message ||
|
|
261
|
+
event.error?.message ||
|
|
262
|
+
"see close event for details";
|
|
263
|
+
this.emit("error", new Error(`WebSocket error: ${msg}`));
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
handleMessage(raw) {
|
|
267
|
+
let msg;
|
|
268
|
+
try {
|
|
269
|
+
msg = JSON.parse(raw);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
switch (msg.type) {
|
|
275
|
+
case "capabilities":
|
|
276
|
+
this.terminalFastLane = msg.terminalFastLane === true;
|
|
277
|
+
this.emit("capabilities", { terminalFastLane: this.terminalFastLane });
|
|
278
|
+
break;
|
|
279
|
+
case "message-received":
|
|
280
|
+
if (!this.isMessageForCurrentSession(msg)) {
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
this.emit("message-received", msg);
|
|
284
|
+
break;
|
|
285
|
+
case "terminal-input":
|
|
286
|
+
if (this.isTerminalMessageForCurrentSession(msg)) {
|
|
287
|
+
this.emit("terminal-input", msg);
|
|
288
|
+
}
|
|
289
|
+
break;
|
|
290
|
+
case "terminal-control":
|
|
291
|
+
if (this.isTerminalMessageForCurrentSession(msg)) {
|
|
292
|
+
this.emit("terminal-control", msg);
|
|
293
|
+
}
|
|
294
|
+
break;
|
|
295
|
+
case "terminal-input-ack":
|
|
296
|
+
this.emit("terminal-input-ack", msg);
|
|
297
|
+
break;
|
|
298
|
+
case "terminal-control-ack":
|
|
299
|
+
this.emit("terminal-control-ack", msg);
|
|
300
|
+
break;
|
|
301
|
+
case "pong":
|
|
302
|
+
this.lastPongAt = Date.now();
|
|
303
|
+
break;
|
|
304
|
+
case "permission-created":
|
|
305
|
+
this.emit("permission-created", msg.permission);
|
|
306
|
+
break;
|
|
307
|
+
case "permission-resolved":
|
|
308
|
+
this.emit("permission-resolved", msg.permission);
|
|
309
|
+
break;
|
|
310
|
+
case "session-updated":
|
|
311
|
+
this.emit("session-updated", msg.session);
|
|
312
|
+
break;
|
|
313
|
+
case "session-deleted":
|
|
314
|
+
this.emit("session-deleted", msg.sessionId);
|
|
315
|
+
break;
|
|
316
|
+
case "machine-updated":
|
|
317
|
+
this.emit("machine-updated", msg.machine);
|
|
318
|
+
break;
|
|
319
|
+
case "env-status-changed":
|
|
320
|
+
this.emit("env-status-changed", msg.slug, msg.status, msg.message);
|
|
321
|
+
break;
|
|
322
|
+
case "runner-control-request":
|
|
323
|
+
this.emit("runner-control-request", msg);
|
|
324
|
+
break;
|
|
325
|
+
case "error":
|
|
326
|
+
this.emit("error", new Error(`Hub error: ${msg.message}`));
|
|
327
|
+
break;
|
|
328
|
+
default:
|
|
329
|
+
if (OS_HUB_TO_MACHINE_TYPES.includes(msg.type)) {
|
|
330
|
+
this.emit("os-message", msg);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
isMessageForCurrentSession(msg) {
|
|
335
|
+
if (msg.type !== "message-received") {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
if (!this.sessionId) {
|
|
339
|
+
return true;
|
|
340
|
+
}
|
|
341
|
+
return typeof msg.sessionId === "string" && msg.sessionId === this.sessionId;
|
|
342
|
+
}
|
|
343
|
+
isTerminalMessageForCurrentSession(msg) {
|
|
344
|
+
if (msg.type !== "terminal-input" && msg.type !== "terminal-control") {
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
// Unlike durable messages, live terminal input must never be handled
|
|
348
|
+
// before this client knows which session it owns.
|
|
349
|
+
if (!this.sessionId) {
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
return typeof msg.sessionId === "string" && msg.sessionId === this.sessionId;
|
|
353
|
+
}
|
|
354
|
+
wsSend(data) {
|
|
355
|
+
const payload = JSON.stringify(data);
|
|
356
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
357
|
+
this.ws.send(payload);
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
// Queue the message for delivery after reconnect
|
|
361
|
+
this.enqueue(payload);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
wsSendLive(data) {
|
|
365
|
+
if (this.ws?.readyState !== WebSocket.OPEN) {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
this.ws.send(JSON.stringify(data));
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
enqueue(payload) {
|
|
372
|
+
this.pendingMessages.push(payload);
|
|
373
|
+
// Drop oldest if over capacity
|
|
374
|
+
while (this.pendingMessages.length > MAX_QUEUED_MESSAGES) {
|
|
375
|
+
this.pendingMessages.shift();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
drainQueue() {
|
|
379
|
+
if (this.pendingMessages.length === 0)
|
|
380
|
+
return;
|
|
381
|
+
while (this.pendingMessages.length > 0) {
|
|
382
|
+
if (this.ws?.readyState !== WebSocket.OPEN)
|
|
383
|
+
break;
|
|
384
|
+
const payload = this.pendingMessages.shift();
|
|
385
|
+
if (!payload)
|
|
386
|
+
break;
|
|
387
|
+
this.ws.send(payload);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
startHeartbeat() {
|
|
391
|
+
this.stopHeartbeat();
|
|
392
|
+
this.heartbeatTimer = setInterval(() => {
|
|
393
|
+
// Pong liveness check — 90s absolute threshold, confirmed after a grace
|
|
394
|
+
if (this.lastPongAt > 0 && !this.pongGraceTimer) {
|
|
395
|
+
const sincePong = Date.now() - this.lastPongAt;
|
|
396
|
+
if (sincePong > PONG_TIMEOUT_MS) {
|
|
397
|
+
this.confirmPongSilence(this.ws);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
this.heartbeatCycle++;
|
|
402
|
+
if (this.sessionId && this.sessionLifecycle === "owner" && this.heartbeatCycle % 5 === 0) {
|
|
403
|
+
this.sendSessionAlive(this.sessionId);
|
|
404
|
+
}
|
|
405
|
+
if (this.machineId) {
|
|
406
|
+
this.sendMachineAlive(this.machineId);
|
|
407
|
+
}
|
|
408
|
+
this.wsSend({ type: "ping" });
|
|
409
|
+
}, HEARTBEAT_MS);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Pings and decides after PONG_GRACE_MS, so pongs left unread by a blocked
|
|
413
|
+
* event loop are read first. A grace timer that itself fired late (the loop
|
|
414
|
+
* blocked again) waits once more instead of deciding.
|
|
415
|
+
*/
|
|
416
|
+
confirmPongSilence(target) {
|
|
417
|
+
const pongBefore = this.lastPongAt;
|
|
418
|
+
const armedAt = Date.now();
|
|
419
|
+
this.wsSendLive({ type: "ping" });
|
|
420
|
+
this.pongGraceTimer = setTimeout(() => {
|
|
421
|
+
this.pongGraceTimer = null;
|
|
422
|
+
if (this.ws !== target || this.lastPongAt > pongBefore)
|
|
423
|
+
return;
|
|
424
|
+
if (Date.now() - armedAt > PONG_GRACE_MS * 2) {
|
|
425
|
+
this.confirmPongSilence(target);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
console.error(`${CLI.logTag} No pong received — connection dead, reconnecting at ${new Date().toISOString()}`);
|
|
429
|
+
this.forceReconnect(target);
|
|
430
|
+
}, PONG_GRACE_MS);
|
|
431
|
+
}
|
|
432
|
+
stopHeartbeat() {
|
|
433
|
+
if (this.heartbeatTimer) {
|
|
434
|
+
clearInterval(this.heartbeatTimer);
|
|
435
|
+
this.heartbeatTimer = null;
|
|
436
|
+
}
|
|
437
|
+
if (this.pongGraceTimer) {
|
|
438
|
+
clearTimeout(this.pongGraceTimer);
|
|
439
|
+
this.pongGraceTimer = null;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
scheduleReconnect() {
|
|
443
|
+
this.clearReconnectTimer();
|
|
444
|
+
// The first retry after a drop goes out at once (a Hub deploy or a lost
|
|
445
|
+
// TCP connection); a Hub that keeps refusing gets exponential backoff.
|
|
446
|
+
const attempt = this.reconnectAttempts++;
|
|
447
|
+
const delay = attempt === 0
|
|
448
|
+
? Math.round(RECONNECT_FIRST_JITTER_MS * Math.random())
|
|
449
|
+
: (() => {
|
|
450
|
+
const base = Math.min(RECONNECT_MIN_MS * 2 ** (attempt - 1), RECONNECT_MAX_MS);
|
|
451
|
+
return Math.round(base + base * 0.3 * Math.random());
|
|
452
|
+
})();
|
|
453
|
+
console.error(`${CLI.logTag} Reconnecting in ${delay}ms... (${new Date().toISOString()})`);
|
|
454
|
+
this.reconnectTimer = setTimeout(() => {
|
|
455
|
+
this.reconnectTimer = null;
|
|
456
|
+
this.openWs();
|
|
457
|
+
}, delay);
|
|
458
|
+
}
|
|
459
|
+
}
|
package/dist/hub-kind.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Which kinds of hub this program connects to (identity.ts `hubKinds`). The hub says its kind in
|
|
2
|
+
// `GET /api/setup/status` (`hubKind`), which every command already reads with the machine's
|
|
3
|
+
// credentials. The `tiller` build connects to both kinds and asks nothing more; the `overvues`
|
|
4
|
+
// build connects only to an Overvues Dev hub, and refuses any other before it saves a credential
|
|
5
|
+
// or starts.
|
|
6
|
+
import { CLI } from "./identity.js";
|
|
7
|
+
import { fetchHubSetupStatus } from "./codex-subscription.js";
|
|
8
|
+
export class HubKindRefusedError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "HubKindRefusedError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** True when this program connects to any kind of hub, so there is nothing to ask. */
|
|
15
|
+
export function acceptsEveryHubKind(identity = CLI) {
|
|
16
|
+
return identity.hubKinds.includes("tiller") && identity.hubKinds.includes("overvues-dev");
|
|
17
|
+
}
|
|
18
|
+
/** Null when this program connects to a hub that reports `status`; otherwise the sentence to show. */
|
|
19
|
+
export function hubKindRefusal(status, hubUrl, identity = CLI) {
|
|
20
|
+
if (acceptsEveryHubKind(identity))
|
|
21
|
+
return null;
|
|
22
|
+
const kind = status?.hubKind;
|
|
23
|
+
if (typeof kind === "string" && identity.hubKinds.includes(kind))
|
|
24
|
+
return null;
|
|
25
|
+
const said = typeof kind === "string" && kind
|
|
26
|
+
? `${hubUrl} is not an ${identity.productName} hub`
|
|
27
|
+
: `${hubUrl} did not say it is an ${identity.productName} hub`;
|
|
28
|
+
return `${said}, and \`${identity.command}\` connects only to ${identity.productName} hubs. `
|
|
29
|
+
+ "Nothing was saved and nothing was started. Check the hub address you were given.";
|
|
30
|
+
}
|
|
31
|
+
/** Throws HubKindRefusedError when the status says this program does not connect to the hub. */
|
|
32
|
+
export function assertHubKind(status, hubUrl, identity = CLI) {
|
|
33
|
+
const refusal = hubKindRefusal(status, hubUrl, identity);
|
|
34
|
+
if (refusal)
|
|
35
|
+
throw new HubKindRefusedError(refusal);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Asks the hub its kind with the given credentials and refuses a hub this program does not
|
|
39
|
+
* connect to. Returns the status read, or null when this program connects to every kind (and so
|
|
40
|
+
* asks nothing: the `tiller` build sends no request it did not send before).
|
|
41
|
+
*/
|
|
42
|
+
export async function requireHubKind(hubUrl, headers, options = {}) {
|
|
43
|
+
const identity = options.identity ?? CLI;
|
|
44
|
+
if (acceptsEveryHubKind(identity))
|
|
45
|
+
return null;
|
|
46
|
+
let status;
|
|
47
|
+
try {
|
|
48
|
+
status = await (options.fetchStatus ?? fetchHubSetupStatus)(hubUrl, headers);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
throw new HubKindRefusedError(`Could not ask ${hubUrl} what kind of hub it is (${error instanceof Error ? error.message : String(error)}). `
|
|
52
|
+
+ `\`${identity.command}\` connects only to ${identity.productName} hubs, so nothing was saved.`);
|
|
53
|
+
}
|
|
54
|
+
assertHubKind(status, hubUrl, identity);
|
|
55
|
+
return status;
|
|
56
|
+
}
|
|
57
|
+
/** The machine credential headers for a credential not yet saved. */
|
|
58
|
+
export function credentialHeaders(credential) {
|
|
59
|
+
return {
|
|
60
|
+
...(credential.clientId ? { "X-Tiller-Client-Id": credential.clientId } : {}),
|
|
61
|
+
...(credential.clientSecret ? { "X-Tiller-Client-Secret": credential.clientSecret } : {}),
|
|
62
|
+
...(credential.controlSecret ? { "X-Tiller-Capability": credential.controlSecret } : {}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The daemon's check at start. The `tiller` build connects to every kind and reads the status only
|
|
67
|
+
* to refuse nothing more. A build that does not accept every kind starts only once the hub has said
|
|
68
|
+
* its kind: while the status cannot be read (the hub restarting, the network down) it waits and
|
|
69
|
+
* asks again, from 2 seconds doubling to a minute, and never starts on no answer. It is a check
|
|
70
|
+
* at start: a daemon already running is not stopped by a brief outage, and containers it started
|
|
71
|
+
* keep running while a new one waits here.
|
|
72
|
+
*/
|
|
73
|
+
export async function hubKindAtStart(read, hubUrl, options = {}) {
|
|
74
|
+
const identity = options.identity ?? CLI;
|
|
75
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
76
|
+
let status = await read();
|
|
77
|
+
if (acceptsEveryHubKind(identity)) {
|
|
78
|
+
if (status)
|
|
79
|
+
assertHubKind(status, hubUrl, identity);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
for (let delay = 2_000; !status; delay = Math.min(delay * 2, 60_000)) {
|
|
83
|
+
options.log?.(`${hubUrl} did not say what kind of hub it is, and \`${identity.command}\` connects only to ${identity.productName} hubs, so the machine is not started yet. Asking again in ${Math.round(delay / 1000)} s.`);
|
|
84
|
+
await sleep(delay);
|
|
85
|
+
status = await read();
|
|
86
|
+
}
|
|
87
|
+
assertHubKind(status, hubUrl, identity);
|
|
88
|
+
}
|