@moondeck/station 1.0.1 → 1.0.3

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/src/main.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env tsx
2
2
  import { stationAgentCliAdvertisable } from "../lib/agent-cli";
3
+ import { PREVIEW_UPSTREAM_PROTOCOL_FEATURE, parsePreviewUpstream, tunnelPreviewUpstream } from "./preview-upstream";
4
+ import { preparePreviewUpstream, previewRequestHeaders, isPreviewConnectFailure } from "../lib/preview-upstream";
3
5
  import { describeClose, suspendedFor } from "./bridge-diagnostics";
4
6
  import { internalHostGatewayAdvertisable } from "../lib/custom-connection-launch";
5
7
  import "./load-env";
@@ -1553,6 +1555,7 @@ function buildCapabilities(): HostCapabilities {
1553
1555
  internalConnections: isOwnedInternalConnectionRuntime(internalRuntimeProvider()),
1554
1556
  ...(diskSnapshot ? { disk: diskSnapshot } : {}),
1555
1557
  protocolFeatures: [
1558
+ PREVIEW_UPSTREAM_PROTOCOL_FEATURE,
1556
1559
  "host-workspace-file-read-v1",
1557
1560
  ASSIGNMENT_EVIDENCE_PROTOCOL_FEATURE,
1558
1561
  FIRST_TURN_DEDUP_PROTOCOL_FEATURE,
@@ -4064,10 +4067,16 @@ async function handleTunnelOpen(
4064
4067
  wsSocket: WebSocket,
4065
4068
  frame: Extract<CloudToHost, { kind: "tunnel.open" }>,
4066
4069
  ): Promise<void> {
4067
- let target: UpstreamAddr | null;
4070
+ let target: UpstreamAddr | null = null;
4068
4071
  try {
4072
+ const settings = tunnelPreviewUpstream(frame);
4073
+ if (!settings) throw new Error("invalid preview upstream settings");
4074
+ frame = { ...frame, reqLine: { ...frame.reqLine, headers: previewRequestHeaders(frame.reqLine.headers, settings) } };
4069
4075
  target = await resolveTunnelTarget(frame);
4076
+ if (target) target = await preparePreviewUpstream(target, settings);
4070
4077
  } catch (error) {
4078
+ if (target) invalidatePreviewSidecar(target.port);
4079
+ if (isPreviewConnectFailure(error)) invalidateMachineTunnelRoute(frame.taskId);
4071
4080
  // A thrown resolution (daemon flap mid-inspect) must settle the
4072
4081
  // opening entry: abortAll() joins it during bridge replacement, and the
4073
4082
  // rejection must not escape the `void handleTunnelOpen(...)` call as a
@@ -4114,12 +4123,13 @@ function handleHttpTunnelOpen(
4114
4123
  target: UpstreamAddr,
4115
4124
  ): void {
4116
4125
  let acked = false;
4126
+ let connected = Boolean(target.socket);
4117
4127
  const requestOptions = {
4118
4128
  host: target.host,
4119
4129
  port: target.port,
4120
4130
  method: frame.reqLine.method,
4121
4131
  path: frame.reqLine.url,
4122
- headers: requestHeaders(frame.reqLine.headers),
4132
+ headers: requestHeaders(frame.reqLine.headers, frame.upstreamHost),
4123
4133
  // Reuse the connection proven inside the task lifecycle slot; http will
4124
4134
  // manage (and eventually close) the socket it is handed.
4125
4135
  ...(target.socket ? { createConnection: () => target.socket! } : {}),
@@ -4152,6 +4162,11 @@ function handleHttpTunnelOpen(
4152
4162
  },
4153
4163
  );
4154
4164
 
4165
+ upstream.once("socket", (socket: Socket) => {
4166
+ if (!socket.connecting) connected = true;
4167
+ else socket.once("connect", () => { connected = true; });
4168
+ });
4169
+
4155
4170
  // ADR-121: a memoised machine address may black-hole (instance stopped
4156
4171
  // while memoised), and a black-holed dial neither errors nor answers for
4157
4172
  // the kernel's SYN budget. Bound the connect phase only — never `timeout`
@@ -4175,7 +4190,7 @@ function handleHttpTunnelOpen(
4175
4190
  invalidatePreviewSidecar(target.port);
4176
4191
  // ADR-121: a memoised machine address that no longer answers is stale —
4177
4192
  // a refused dial and a connect timeout (tunnel-dial.ts) both land here.
4178
- invalidateMachineTunnelRoute(frame.taskId);
4193
+ if (!connected) invalidateMachineTunnelRoute(frame.taskId);
4179
4194
  if (!acked) {
4180
4195
  send(wsSocket, {
4181
4196
  kind: "tunnel.ack",
@@ -4207,10 +4222,12 @@ function handleRawTunnelOpen(
4207
4222
  const upstream = target.socket ?? new Socket();
4208
4223
 
4209
4224
  let acked = false;
4225
+ let connected = Boolean(target.socket);
4210
4226
  let responseBuffer = Buffer.alloc(0);
4211
4227
 
4212
4228
  if (!target.socket) {
4213
4229
  upstream.on("connect", () => {
4230
+ connected = true;
4214
4231
  upstream.write(serializeRequest(frame.reqLine));
4215
4232
  });
4216
4233
  }
@@ -4243,7 +4260,7 @@ function handleRawTunnelOpen(
4243
4260
  // the next request recreates it (no-op for published / container-IP targets).
4244
4261
  invalidatePreviewSidecar(target.port);
4245
4262
  // ADR-121: a memoised machine address that no longer answers is stale.
4246
- invalidateMachineTunnelRoute(frame.taskId);
4263
+ if (!connected) invalidateMachineTunnelRoute(frame.taskId);
4247
4264
  if (!acked) {
4248
4265
  send(wsSocket, {
4249
4266
  kind: "tunnel.ack",
@@ -4505,13 +4522,13 @@ function serializeRequest(reqLine: {
4505
4522
  return Buffer.from(`${lines.join("\r\n")}\r\n\r\n`, "latin1");
4506
4523
  }
4507
4524
 
4508
- function requestHeaders(headers: [string, string][]): OutgoingHttpHeaders {
4525
+ function requestHeaders(headers: [string, string][], upstreamHost?: string): OutgoingHttpHeaders {
4509
4526
  const out: OutgoingHttpHeaders = {};
4510
4527
  for (const [name, value] of headers) {
4511
4528
  const lower = name.toLowerCase();
4512
4529
  if (isHopByHopHeader(lower)) continue;
4513
4530
  if (lower === "host") {
4514
- out.host = "127.0.0.1";
4531
+ out.host = upstreamHost?.toLowerCase() ?? "127.0.0.1";
4515
4532
  continue;
4516
4533
  }
4517
4534
 
@@ -4709,11 +4726,13 @@ async function dispatchCommand(
4709
4726
  parseTranscriptTargets(args[3]),
4710
4727
  );
4711
4728
  case "previewEnsure":
4729
+ if (parsePreviewUpstream(args[3]) === null) throw new Error("invalid preview upstream settings");
4712
4730
  return hostCommands.previewEnsure(
4713
4731
  ctx,
4714
4732
  expectString(args, 0),
4715
4733
  expectString(args, 1),
4716
4734
  expectNumberArg(args, 2),
4735
+ parsePreviewUpstream(args[3])!,
4717
4736
  );
4718
4737
  case "hostUpdate":
4719
4738
  return hostCommands.hostUpdate(ctx, typeof args[0] === "string" ? args[0] : "");
@@ -5014,6 +5033,8 @@ function parseCloudFrame(data: RawData): CloudToHost | null {
5014
5033
  isReqLine(frame.reqLine) &&
5015
5034
  typeof frame.upgrade === "boolean"
5016
5035
  ) {
5036
+ const upstream = tunnelPreviewUpstream(frame as Extract<CloudToHost, { kind: "tunnel.open" }>);
5037
+ if (!upstream) return null;
5017
5038
  return {
5018
5039
  kind: "tunnel.open",
5019
5040
  tunnelId: frame.tunnelId,
@@ -5024,6 +5045,7 @@ function parseCloudFrame(data: RawData): CloudToHost | null {
5024
5045
  // node-proxy sidecar (NOT the unreachable bridge IP — see resolveTunnelTarget).
5025
5046
  containerPort:
5026
5047
  typeof frame.containerPort === "number" ? frame.containerPort : undefined,
5048
+ ...upstream,
5027
5049
  reqLine: frame.reqLine,
5028
5050
  upgrade: frame.upgrade,
5029
5051
  };
@@ -0,0 +1,41 @@
1
+ /** Optional preview behavior, negotiated per live Station connection. */
2
+ export const PREVIEW_UPSTREAM_PROTOCOL_FEATURE = "preview-upstream-v1";
3
+
4
+ export interface PreviewUpstream {
5
+ upstreamHost?: string;
6
+ upstreamTls?: boolean;
7
+ }
8
+
9
+ /** DNS spelling only. URL parsing here detects numeric/hex/octal IP aliases;
10
+ * it never resolves a name. No URL, authority, port or header syntax is allowed. */
11
+ export function isPreviewUpstreamHost(value: unknown): value is string {
12
+ if (typeof value !== "string" || value.length < 1 || value.length > 253) return false;
13
+ if (!value.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))) return false;
14
+ try {
15
+ return !/^\d+\.\d+\.\d+\.\d+$/.test(new URL(`http://${value}`).hostname);
16
+ } catch { return false; }
17
+ }
18
+
19
+ export function hasPreviewUpstream(value: PreviewUpstream): boolean {
20
+ return value.upstreamHost !== undefined || value.upstreamTls === true;
21
+ }
22
+
23
+ /** Read only these fields from a frame or declaration; reject malformed values. */
24
+ export function parsePreviewUpstream(value: unknown): PreviewUpstream | null {
25
+ if (value === undefined) return {};
26
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
27
+ const { upstreamHost, upstreamTls } = value as Record<string, unknown>;
28
+ if (upstreamHost !== undefined && !isPreviewUpstreamHost(upstreamHost)) return null;
29
+ if (upstreamTls !== undefined && typeof upstreamTls !== "boolean") return null;
30
+ return {
31
+ ...(typeof upstreamHost === "string" ? { upstreamHost: upstreamHost.toLowerCase() } : {}),
32
+ ...(typeof upstreamTls === "boolean" ? { upstreamTls } : {}),
33
+ };
34
+ }
35
+
36
+ export function tunnelPreviewUpstream(frame: { target: string; containerPort?: number } & PreviewUpstream): PreviewUpstream | null {
37
+ const settings = parsePreviewUpstream(frame);
38
+ if (!settings) return null;
39
+ if (hasPreviewUpstream(settings) && (frame.target !== "preview" || !Number.isInteger(frame.containerPort) || frame.containerPort! < 1 || frame.containerPort! > 65535)) return null;
40
+ return settings;
41
+ }
package/src/protocol.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from "./custom-connections";
2
+ export * from "./preview-upstream";
3
+ import type { PreviewUpstream } from "./preview-upstream";
2
4
  import type { AccountBinding, EngineConnectCustomDiscoverFrame, EngineConnectCustomDiscoveredFrame, EngineConnectCustomSaveFrame, EngineConnectCustomManualSaveFrame, EngineConnectCustomSavedFrame, OpenRouterBudgetFrame } from "./custom-connections";
3
5
  import type { TaskSecretApplied, TaskSecretStagingPut, TaskSecretStagingAck } from "./task-secrets";
4
6
  import { isNeverProxiedDomain } from "./never-proxied-domains";
@@ -4835,6 +4837,7 @@ export interface HostCommands {
4835
4837
  taskId: string,
4836
4838
  name: string,
4837
4839
  containerPort: number,
4840
+ upstream?: PreviewUpstream,
4838
4841
  ): Promise<HostCommandResult<{ hostPort: number | null }>>;
4839
4842
  /** ADR-116: remove a labeled engine account by id. Refuses `default:*`
4840
4843
  * exactly like the local API; re-advertises capabilities on success. */
@@ -4997,6 +5000,8 @@ export type CloudToHost =
4997
5000
  // proxies to <container-ip>:<containerPort> over the Docker network.
4998
5001
  // Absent for the editor target (which uses the published codeServerPort).
4999
5002
  containerPort?: number;
5003
+ upstreamHost?: string;
5004
+ upstreamTls?: boolean;
5000
5005
  reqLine: TunnelReqLine;
5001
5006
  upgrade: boolean;
5002
5007
  }