@moondeck/station 1.0.11 → 1.0.13

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,282 @@
1
+ /**
2
+ * The ONE effective cloud endpoint of a Station, and the guarded migration of an existing Station from the
3
+ * app host to the API host (wss://app.moondeck.io/host -> wss://api.moondeck.io/host) without re-enrollment.
4
+ *
5
+ * Rules (each enforced here, each tested):
6
+ * - the destination is the compiled constant STATION_API_CLOUD_URL: never a server message, redirect, task
7
+ * input or environment value; the cloud only says YES or NO, as a feature string in its authenticated
8
+ * `event.resume` (a boolean, never a URL);
9
+ * - eligibility is an exact match on STATION_LEGACY_CLOUD_URL, both in the process environment and in the
10
+ * host's own `.env.local` (so a value injected elsewhere is never "migrated" into a file that would not
11
+ * win on restart), for an enrolled Station (host id + token) with no pending enrollment/attach journal;
12
+ * - the new URL is persisted only after the first authenticated session on it, with the old one kept as
13
+ * UAI_CLOUD_URL_PREVIOUS. A fallback is NEVER persisted: it lasts for the process, `.env.local` keeps the
14
+ * API host, and the next start tries it first (an offline laptop must not un-migrate a Station).
15
+ * UAI_CLOUD_MIGRATION=reverted is an operator-set value only;
16
+ * - a COMMITTED Station falls back only on connection/TLS failures that persist (count and wall-clock span);
17
+ * a TRIAL ends on any attempt that finishes without authenticating (a refusal or an early close too),
18
+ * after a few; both have jitter and a hard cap on flips; after a fallback and a good app-host session the
19
+ * Station returns to the API URL once, after a jittered idle wait, and then stays where it lands;
20
+ * - every consumer (the bridge, GitHub token exchange, the task CLI base URL) asks this module for the
21
+ * endpoint; the human-facing app URL comes from a constant mapping, never from a task.
22
+ */
23
+
24
+ export const STATION_LEGACY_CLOUD_URL = "wss://app.moondeck.io/host";
25
+ export const STATION_API_CLOUD_URL = "wss://api.moondeck.io/host";
26
+ export const STATION_APP_URL = "https://app.moondeck.io";
27
+ /** Advertised by the cloud in `event.resume.features` when migration is switched on. */
28
+ export const STATION_API_HOST_FEATURE = "station-api-host:v1";
29
+
30
+ export const ENV_CLOUD_URL = "UAI_CLOUD_URL";
31
+ export const ENV_CLOUD_URL_PREVIOUS = "UAI_CLOUD_URL_PREVIOUS";
32
+ export const ENV_CLOUD_MIGRATION = "UAI_CLOUD_MIGRATION";
33
+ export const MIGRATION_REVERTED = "reverted";
34
+
35
+ export const TRIAL_FAILURE_THRESHOLD = 3;
36
+ export const COMMITTED_FAILURE_THRESHOLD = 5;
37
+ /** A committed Station falls back only after the API host has been unreachable this long (and enough tries). */
38
+ export const COMMITTED_FAILURE_MIN_SPAN_MS = 10 * 60_000;
39
+ export const MAX_FLIPS = 2;
40
+ export const MAX_TRIALS = 2;
41
+ export const MIGRATION_DELAY_MIN_MS = 60_000;
42
+ export const MIGRATION_DELAY_SPREAD_MS = 14 * 60_000;
43
+ export const TRIAL_RETRY_MIN_MS = 30 * 60_000;
44
+ export const TRIAL_RETRY_SPREAD_MS = 30 * 60_000;
45
+
46
+ type Env = Readonly<Record<string, string | undefined>>;
47
+
48
+ const CONNECTION_CODES = new Set([
49
+ "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ETIMEDOUT", "ECONNRESET", "EHOSTUNREACH", "ENETUNREACH", "ENETDOWN", "EPIPE",
50
+ "CERT_HAS_EXPIRED", "CERT_NOT_YET_VALID", "CERT_UNTRUSTED", "CERT_REVOKED", "DEPTH_ZERO_SELF_SIGNED_CERT",
51
+ "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "UNABLE_TO_GET_ISSUER_CERT",
52
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "HOSTNAME_MISMATCH",
53
+ ]);
54
+ const CONNECTION_MESSAGE = /socket hang up|opening handshake has timed out|handshake has timed out|getaddrinfo|ssl|tls|certificate/i;
55
+
56
+ /** "connection": the endpoint could not be reached or its TLS failed. "other": anything that is the server
57
+ * answering (credential rejection, HTTP refusal, protocol close), which is never evidence the host is down. */
58
+ export function classifyBridgeFailure(error: unknown): "connection" | "other" {
59
+ if (typeof error !== "object" || error === null) return "other";
60
+ const { code, message } = error as { code?: unknown; message?: unknown };
61
+ if (typeof code === "string" && (CONNECTION_CODES.has(code) || code.startsWith("ERR_TLS_") || code.startsWith("ERR_SSL_"))) return "connection";
62
+ if (typeof message === "string") {
63
+ if (/unexpected server response/i.test(message)) return "other";
64
+ if (CONNECTION_MESSAGE.test(message)) return "connection";
65
+ }
66
+ return "other";
67
+ }
68
+
69
+ /** https base of a bridge URL (what enrollment, GitHub exchange and the task CLI call). */
70
+ export function httpBaseFromCloudUrl(cloudUrl: string): string | null {
71
+ try {
72
+ const u = new URL(cloudUrl);
73
+ const proto = u.protocol === "wss:" ? "https:" : u.protocol === "ws:" ? "http:" : u.protocol;
74
+ return `${proto}//${u.host}`;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ /** Where a human opens links the task CLI prints (artifacts, files). A constant mapping for the Moondeck
81
+ * hosts (the API host carries no browser cookies, so its links would be unauthenticated); any other
82
+ * deployment keeps its own host. Never derived from task input. */
83
+ export function appUrlForCloudUrl(cloudUrl: string): string | null {
84
+ if (cloudUrl === STATION_API_CLOUD_URL || cloudUrl === STATION_LEGACY_CLOUD_URL) return STATION_APP_URL;
85
+ return httpBaseFromCloudUrl(cloudUrl);
86
+ }
87
+
88
+ export interface CloudEndpointDeps {
89
+ /** Process environment (UAI_CLOUD_URL, UAI_HOST_ID, UAI_HOST_TOKEN). */
90
+ readonly env: Env;
91
+ /** The host's own `.env.local`, read fresh. */
92
+ readonly readEnvLocal: () => Readonly<Record<string, string>>;
93
+ /** True when a pending enrollment or attach journal exists. */
94
+ readonly journalPending: () => boolean;
95
+ /** Atomic merge into `.env.local`. May throw. */
96
+ readonly persist: (values: Readonly<Record<string, string>>) => void;
97
+ readonly random?: () => number;
98
+ readonly now?: () => number;
99
+ readonly log?: (message: string) => void;
100
+ /** Used when UAI_CLOUD_URL is unset (development bridge). */
101
+ readonly defaultUrl: string;
102
+ }
103
+
104
+ type Mode = "legacy" | "trial" | "committed" | "fallback" | "return" | "pinned";
105
+
106
+ export class CloudEndpoint {
107
+ private mode: Mode = "legacy";
108
+ private current: string;
109
+ private enabled = false;
110
+ private failures = 0;
111
+ private firstFailureAt = 0;
112
+ private flips = 0;
113
+ private trials = 0;
114
+ private retryNotBefore = 0;
115
+ private persistAttempted = false;
116
+ private unauthenticatedAttempts = 0;
117
+ private returnsUsed = 0;
118
+ private readonly random: () => number;
119
+ private readonly now: () => number;
120
+ private readonly log: (message: string) => void;
121
+
122
+ constructor(private readonly deps: CloudEndpointDeps) {
123
+ this.random = deps.random ?? Math.random;
124
+ this.now = deps.now ?? Date.now;
125
+ this.log = deps.log ?? (() => {});
126
+ this.current = deps.env[ENV_CLOUD_URL] ?? deps.defaultUrl;
127
+ // A previously committed migration: the persisted URL is the API constant and the previous one is kept.
128
+ if (this.current === STATION_API_CLOUD_URL && this.safeEnvLocal()[ENV_CLOUD_URL_PREVIOUS] === STATION_LEGACY_CLOUD_URL) {
129
+ this.mode = "committed";
130
+ this.persistAttempted = true;
131
+ }
132
+ }
133
+
134
+ private safeEnvLocal(): Readonly<Record<string, string>> {
135
+ try { return this.deps.readEnvLocal(); } catch { return {}; }
136
+ }
137
+
138
+ /** The effective bridge URL for the NEXT connection attempt. */
139
+ url(): string { return this.current; }
140
+ /** https base for HTTP calls to the cloud (GitHub exchange/revoke, task CLI). */
141
+ httpBase(): string | null { return httpBaseFromCloudUrl(this.current); }
142
+ /** Browser origin for links shown to humans. */
143
+ appUrl(): string | null { return appUrlForCloudUrl(this.current); }
144
+ state(): Mode { return this.mode; }
145
+
146
+ /** Eligible right now? Exact match, enrolled, no journal, not previously reverted. */
147
+ eligible(): boolean {
148
+ const { env } = this.deps;
149
+ if (env[ENV_CLOUD_URL] !== STATION_LEGACY_CLOUD_URL) return false;
150
+ if (!env.UAI_HOST_ID || !env.UAI_HOST_TOKEN) return false;
151
+ if (env[ENV_CLOUD_MIGRATION] === MIGRATION_REVERTED) return false;
152
+ const local = this.safeEnvLocal();
153
+ if (local[ENV_CLOUD_URL] !== STATION_LEGACY_CLOUD_URL) return false;
154
+ if (local[ENV_CLOUD_MIGRATION] === MIGRATION_REVERTED) return false;
155
+ try { if (this.deps.journalPending()) return false; } catch { return false; }
156
+ return true;
157
+ }
158
+
159
+ /** Called with the features of every authenticated `event.resume`. Returns the jittered delay after which
160
+ * the caller should try a migration reconnect, or null when none is wanted. The cloud's answer is a boolean
161
+ * (the feature is present or it is not); it can never name a destination. */
162
+ noteSessionFeatures(features: readonly string[] | undefined): number | null {
163
+ this.enabled = features?.includes(STATION_API_HOST_FEATURE) === true;
164
+ if (!this.enabled || this.mode !== "legacy") return null;
165
+ if (this.trials >= MAX_TRIALS || this.flips >= MAX_FLIPS || this.now() < this.retryNotBefore) return null;
166
+ if (!this.eligible()) return null;
167
+ return MIGRATION_DELAY_MIN_MS + Math.floor(this.random() * MIGRATION_DELAY_SPREAD_MS);
168
+ }
169
+
170
+ /** Start the trial on the compiled API URL. False (and no change) unless still enabled and eligible. */
171
+ beginTrial(): boolean {
172
+ if (!this.enabled || this.mode !== "legacy" || this.trials >= MAX_TRIALS || this.flips >= MAX_FLIPS || !this.eligible()) return false;
173
+ this.trials += 1;
174
+ this.mode = "trial";
175
+ this.current = STATION_API_CLOUD_URL;
176
+ this.failures = 0;
177
+ this.log(`[cloud-endpoint] trying ${STATION_API_CLOUD_URL}`);
178
+ return true;
179
+ }
180
+
181
+ /** The first authenticated session on the current endpoint. */
182
+ onAuthenticated(): void {
183
+ this.failures = 0;
184
+ this.firstFailureAt = 0;
185
+ this.unauthenticatedAttempts = 0;
186
+ if (this.mode === "trial" && this.current === STATION_API_CLOUD_URL && !this.persistAttempted) {
187
+ this.persistAttempted = true; // one write attempt, ever, per process
188
+ try {
189
+ this.deps.persist({ [ENV_CLOUD_URL]: STATION_API_CLOUD_URL, [ENV_CLOUD_URL_PREVIOUS]: STATION_LEGACY_CLOUD_URL });
190
+ this.mode = "committed";
191
+ this.log(`[cloud-endpoint] migrated to ${STATION_API_CLOUD_URL} (previous kept)`);
192
+ } catch (error) {
193
+ // Stay on the API host for this process; the next start re-evaluates from the unchanged file.
194
+ this.log(`[cloud-endpoint] migration not persisted: ${error instanceof Error ? error.message : String(error)}`);
195
+ }
196
+ } else if (this.mode === "return") {
197
+ this.mode = "committed"; // the file already names the API host; nothing to write
198
+ this.log(`[cloud-endpoint] back on ${STATION_API_CLOUD_URL}`);
199
+ }
200
+ }
201
+
202
+ /** After a fallback and an authenticated app-host session: the jittered, idle-only wait before returning to
203
+ * the API URL, ONCE. Null when not in that state. */
204
+ scheduleReturn(): number | null {
205
+ if (this.mode !== "fallback" || this.returnsUsed >= 1) return null;
206
+ return TRIAL_RETRY_MIN_MS + Math.floor(this.random() * TRIAL_RETRY_SPREAD_MS);
207
+ }
208
+
209
+ /** Return to the API URL once. False (no change) unless in fallback with the one return still unused. */
210
+ beginReturn(): boolean {
211
+ if (this.mode !== "fallback" || this.returnsUsed >= 1) return false;
212
+ this.returnsUsed += 1;
213
+ this.mode = "return";
214
+ this.current = STATION_API_CLOUD_URL;
215
+ this.unauthenticatedAttempts = 0;
216
+ this.log(`[cloud-endpoint] returning to ${STATION_API_CLOUD_URL}`);
217
+ return true;
218
+ }
219
+
220
+ /** One connection attempt ended without authenticating (any reason: refusal, early close, credential
221
+ * rejection, timeout). Counted ONLY while the Station is on a trial/return of the API host, so a host that
222
+ * answers but never admits it still has an exit. Committed Stations ignore it (connection-only rule). */
223
+ onAttemptEnded(): void {
224
+ if (this.mode !== "trial" && this.mode !== "return") return;
225
+ this.unauthenticatedAttempts += 1;
226
+ if (this.unauthenticatedAttempts < TRIAL_FAILURE_THRESHOLD) return;
227
+ const at = this.now();
228
+ this.unauthenticatedAttempts = 0;
229
+ this.failures = 0;
230
+ this.current = STATION_LEGACY_CLOUD_URL;
231
+ if (this.mode === "trial") {
232
+ this.flips += 1;
233
+ this.mode = "legacy";
234
+ this.retryNotBefore = at + TRIAL_RETRY_MIN_MS + Math.floor(this.random() * TRIAL_RETRY_SPREAD_MS);
235
+ this.log("[cloud-endpoint] the API host did not admit this Station during the trial; back on the app host");
236
+ } else {
237
+ this.mode = "pinned"; // the one return failed: stay on the app host for the rest of the process
238
+ this.log("[cloud-endpoint] the API host still does not admit this Station; staying on the app host");
239
+ }
240
+ }
241
+
242
+ /** A connection attempt errored. Only connection/TLS failures count, and only toward a COMMITTED Station's
243
+ * fallback (a trial or return counts whole attempts in onAttemptEnded). The fallback is in memory only. */
244
+ onConnectFailure(error: unknown): void {
245
+ if (classifyBridgeFailure(error) !== "connection") return;
246
+ const at = this.now();
247
+ if (this.failures === 0) this.firstFailureAt = at;
248
+ this.failures += 1;
249
+ if (this.mode === "committed" && this.flips < MAX_FLIPS && this.failures >= COMMITTED_FAILURE_THRESHOLD
250
+ && at - this.firstFailureAt >= COMMITTED_FAILURE_MIN_SPAN_MS
251
+ && this.safeEnvLocal()[ENV_CLOUD_URL_PREVIOUS] === STATION_LEGACY_CLOUD_URL) {
252
+ this.flips += 1;
253
+ this.mode = "fallback";
254
+ this.current = STATION_LEGACY_CLOUD_URL;
255
+ this.failures = 0;
256
+ this.log("[cloud-endpoint] API host unreachable; using the previous endpoint for this process (the file is unchanged)");
257
+ }
258
+ }
259
+ }
260
+
261
+ let active: CloudEndpoint | null = null;
262
+ export function initCloudEndpoint(deps: CloudEndpointDeps): CloudEndpoint {
263
+ active = new CloudEndpoint(deps);
264
+ return active;
265
+ }
266
+ export function resetCloudEndpointForTesting(): void { active = null; }
267
+ export function getCloudEndpoint(): CloudEndpoint | null { return active; }
268
+
269
+ /** The single effective bridge URL, for every consumer. `configured` is the caller's own UAI_CLOUD_URL (the
270
+ * parsed host env); before the endpoint is initialised (tests, CLI commands) it is returned unchanged, i.e.
271
+ * exactly the previous behaviour. */
272
+ export function effectiveCloudUrl(configured: string | undefined = process.env[ENV_CLOUD_URL]): string | undefined {
273
+ return active?.url() ?? configured;
274
+ }
275
+ export function effectiveCloudHttpBase(configured: string | undefined = process.env[ENV_CLOUD_URL]): string | null {
276
+ const url = effectiveCloudUrl(configured);
277
+ return url ? httpBaseFromCloudUrl(url) : null;
278
+ }
279
+ export function effectiveAppUrl(configured: string | undefined = process.env[ENV_CLOUD_URL]): string | null {
280
+ const url = effectiveCloudUrl(configured);
281
+ return url ? appUrlForCloudUrl(url) : null;
282
+ }
@@ -18,6 +18,7 @@ import {
18
18
  mkdirSync,
19
19
  openSync,
20
20
  readFileSync,
21
+ readdirSync,
21
22
  unlinkSync,
22
23
  writeFileSync,
23
24
  } from "node:fs";
@@ -249,3 +250,14 @@ function validatePendingEnrollment(value: unknown): PendingEnrollment {
249
250
  createdAt: object.createdAt,
250
251
  };
251
252
  }
253
+
254
+ /** True when any pending enrollment or attach journal exists in the Station home. The cloud-endpoint migration
255
+ * never runs beside one: a half-finished enrollment names the cloud URL it started with. */
256
+ export function enrollmentJournalPending(uaiHome: string): boolean {
257
+ if (existsSync(pendingEnrollmentPath(uaiHome))) return true;
258
+ try {
259
+ return readdirSync(uaiHome).some((name) => name.startsWith(".enrollment-pending") || name.startsWith(".attach-pending"));
260
+ } catch {
261
+ return false;
262
+ }
263
+ }
@@ -7,6 +7,7 @@
7
7
  * exchange is a host→cloud HTTP POST to /api/github/oauth/exchange.
8
8
  */
9
9
 
10
+ import { effectiveCloudHttpBase } from "./cloud-endpoint";
10
11
  import { and, eq } from "drizzle-orm";
11
12
 
12
13
  import { configuredCredentialStore, queueStoreWrite, userParameterName } from "./credential-store";
@@ -930,11 +931,10 @@ export function reinjectRunningTasks(userId: string): void {
930
931
  // --- access-token exchange --------------------------------------------------
931
932
 
932
933
  function cloudHttpBase(): string {
933
- const cloud = process.env.UAI_CLOUD_URL ?? "ws://127.0.0.1:8789/host";
934
- const u = new URL(cloud);
935
- const proto =
936
- u.protocol === "wss:" ? "https:" : u.protocol === "ws:" ? "http:" : u.protocol;
937
- return `${proto}//${u.host}`;
934
+ // The Station's single effective cloud endpoint (host-agent/lib/cloud-endpoint.ts): the same origin the
935
+ // bridge uses, including after a guarded migration to the API host.
936
+ return effectiveCloudHttpBase(process.env.UAI_CLOUD_URL ?? "ws://127.0.0.1:8789/host")
937
+ ?? (() => { throw new Error("invalid cloud URL"); })();
938
938
  }
939
939
 
940
940
  function exchangeUrl(): string {