@agent-device/proxy 0.21.37 → 0.21.38

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 CHANGED
@@ -65,12 +65,9 @@ export default { fetch: proxy.handle };
65
65
  For a WebSocket or other message transport, turn each incoming message into a `Request` and send
66
66
  the `Response` back. Three things the proxy relies on:
67
67
 
68
- - `request.url` is the URL the client used. Upload tickets point clients at its origin. The first
69
- comma-separated `x-forwarded-proto` value overrides the scheme when it is `http` or `https`
70
- (case-insensitive). This value is client-controlled unless your ingress replaces it. Configure
71
- your ingress to replace client-supplied values with the public scheme rather than append to them.
72
- When you construct `Request` objects, use the public URL and remove untrusted forwarding
73
- headers before calling `handle`.
68
+ - Without `publicOrigin`, construct `request.url` with the canonical client-facing URL for each
69
+ request. The embedder is responsible for that URL. `Forwarded` and `X-Forwarded-*` headers do
70
+ not select the upload ticket origin.
74
71
  - `request.signal` aborts when the client goes away. The proxy then cancels the daemon request, so
75
72
  work the client stopped waiting for does not keep running.
76
73
  - Response bodies stream. Artifact downloads can be large, so forward the body as it arrives.
@@ -78,6 +75,25 @@ the `Response` back. Three things the proxy relies on:
78
75
  `handle` never rejects. Errors come back as JSON responses with a 4xx or 5xx status, except a route
79
76
  the proxy does not serve, which gets a plain `Not found` 404.
80
77
 
78
+ ### Serve uploads through a TLS tunnel
79
+
80
+ Set `publicOrigin` to the public HTTP(S) origin when TLS terminates before the proxy, for example
81
+ `https://public.example:8443`. Use the scheme, host and optional port, without credentials, a path,
82
+ query or fragment. With the CLI, run
83
+ `agent-device proxy --port 4310 --public-origin https://public.example:8443`. For an ephemeral
84
+ tunnel, obtain its public name first, then configure and restart the proxy. This replaces the
85
+ previous first-`X-Forwarded-Proto` behavior.
86
+
87
+ Without a fixed origin, the Node listener uses the actual socket scheme and one validated `Host`
88
+ header. Actual Node HTTPS sockets are supported. A custom direct-daemon HTTP embedding behind TLS
89
+ termination can pass `publicOrigin` to `createDaemonHttpServer`. The built-in daemon listens on
90
+ loopback HTTP; expose it behind TLS through a configured proxy.
91
+
92
+ Your Node HTTP client must send exactly one valid `Host` header on every request, including
93
+ `/health`. Missing, duplicate or malformed Host headers receive HTTP 400, even with `publicOrigin`
94
+ configured. Configure raw-socket and HTTP/1.0 health probes to send `Host: localhost` (or your
95
+ deployment's host and port).
96
+
81
97
  ### Reach the daemon over your own transport
82
98
 
83
99
  By default the proxy calls the daemon with the global `fetch`. Pass `upstreamFetch` when the daemon
@@ -0,0 +1,99 @@
1
+ import "node:path";
2
+ //#region ../contracts/src/daemon-http.ts
3
+ const DAEMON_HTTP_BASE_PATH = "/agent-device";
4
+ const DAEMON_HTTP_TENANT_HEADER = "x-agent-device-tenant";
5
+ const DAEMON_HTTP_NETWORK_ACCESS_HEADER = "x-agent-device-network-access";
6
+ const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = "public-only";
7
+ /** Normalize an absolute HTTP(S) origin, or throw when it contains other URL components. */
8
+ function normalizeDaemonPublicOrigin(value) {
9
+ if (!/^https?:\/\/[^\s/?#]+\/?$/i.test(value) || containsInvalidHttpUrlCharacter(value)) throw new Error("Invalid publicOrigin");
10
+ const authority = value.match(/^https?:\/\/([^/]+)/i)?.[1] ?? "";
11
+ if (authority.includes("@") || authority.endsWith(":")) throw new Error("Invalid publicOrigin");
12
+ const url = new URL(value);
13
+ if (!url.hostname || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error("Invalid publicOrigin");
14
+ return url.origin;
15
+ }
16
+ /** Validate a Node origin-form request target and its single Host header. */
17
+ function nodeHttpRequestUrl(target, rawHeaders, secure) {
18
+ if (!target || !target.startsWith("/") || target.startsWith("//") || target.includes("#") || containsInvalidHttpUrlCharacter(target)) return null;
19
+ const origin = resolveHttpRequestBaseUrl(rawHeaders, secure);
20
+ return origin === null ? null : new URL(target, origin);
21
+ }
22
+ function resolveHttpRequestBaseUrl(rawHeaders, secure) {
23
+ const hosts = [];
24
+ for (let i = 0; i + 1 < rawHeaders.length; i += 2) if (rawHeaders[i]?.toLowerCase() === "host") hosts.push(rawHeaders[i + 1] ?? "");
25
+ if (hosts.length !== 1 || /[/?#]/.test(hosts[0] ?? "")) return null;
26
+ try {
27
+ return normalizeDaemonPublicOrigin(`${secure ? "https" : "http"}://${hosts[0]}`);
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ function containsInvalidHttpUrlCharacter(value) {
33
+ for (const character of value) {
34
+ const code = character.charCodeAt(0);
35
+ if (code <= 32 || code === 127 || character === "\\") return true;
36
+ }
37
+ return false;
38
+ }
39
+ function buildDaemonHttpUrl(baseUrl, route) {
40
+ const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
41
+ return new URL(route.replace(/^\/+/, ""), normalizedBase).toString();
42
+ }
43
+ function buildDaemonHttpAuthHeaders(token) {
44
+ const normalizedToken = token?.trim();
45
+ if (!normalizedToken) return {};
46
+ return {
47
+ authorization: `Bearer ${normalizedToken}`,
48
+ "x-agent-device-token": normalizedToken
49
+ };
50
+ }
51
+ /** The tenant id every daemon route accepts, trimmed, or `undefined` when it breaks the rule. */
52
+ function normalizeTenantId(raw) {
53
+ if (!raw) return void 0;
54
+ const value = raw.trim();
55
+ if (!value) return void 0;
56
+ if (!/^[a-zA-Z0-9._-]{1,128}$/.test(value)) return void 0;
57
+ return value;
58
+ }
59
+ /** Whether `sessionName` lies beneath the `<tenant>:` prefix tenant isolation names sessions with. */
60
+ function isTenantOwnedSessionName(tenant, sessionName) {
61
+ return sessionName.startsWith(`${tenant}:`);
62
+ }
63
+ /**
64
+ * The largest serialized daemon request, in UTF-8 bytes, that any transport reads: the socket
65
+ * line, the HTTP `/rpc` body, and the proxy's `/rpc` body. Clients refuse a larger request before
66
+ * sending it. It sits well above what a client builds: `test` inlines one replay bundle per flow,
67
+ * each up to 2 MiB before JSON escaping, so 64 MiB fits a suite of several maximum-size flows with
68
+ * worst-case escaping. It also bounds the memory one unauthenticated connection can hold.
69
+ */
70
+ const DAEMON_REQUEST_MAX_BYTES = 67108864;
71
+ const DAEMON_HTTP_INSTANCE_HEADER = "x-agent-device-instance";
72
+ const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = "x-agent-device-upstream-instance";
73
+ const DAEMON_HTTP_INSTANCE_MISMATCH_HEADER = "x-agent-device-instance-mismatch";
74
+ function buildDaemonInstanceMismatchRpcResponse(id, message, data) {
75
+ return {
76
+ jsonrpc: "2.0",
77
+ id,
78
+ error: {
79
+ code: -32001,
80
+ message,
81
+ data
82
+ }
83
+ };
84
+ }
85
+ function buildDaemonHealthPayload(service, version, options = {}) {
86
+ return {
87
+ ok: true,
88
+ service,
89
+ version,
90
+ rpcProtocolVersion: 2,
91
+ ...options.instanceId !== void 0 ? { instanceId: options.instanceId } : {},
92
+ ...options.hostArch !== void 0 ? { hostArch: options.hostArch } : {},
93
+ ...options.capabilities !== void 0 ? { capabilities: options.capabilities } : {},
94
+ ...options.leaseBackends !== void 0 ? { leaseBackends: options.leaseBackends } : {},
95
+ ...options.upstream !== void 0 ? { upstream: options.upstream } : {}
96
+ };
97
+ }
98
+ //#endregion
99
+ export { DAEMON_HTTP_PUBLIC_NETWORK_ACCESS as a, DAEMON_REQUEST_MAX_BYTES as c, buildDaemonHttpUrl as d, buildDaemonInstanceMismatchRpcResponse as f, normalizeTenantId as g, normalizeDaemonPublicOrigin as h, DAEMON_HTTP_NETWORK_ACCESS_HEADER as i, buildDaemonHealthPayload as l, nodeHttpRequestUrl as m, DAEMON_HTTP_INSTANCE_HEADER as n, DAEMON_HTTP_TENANT_HEADER as o, isTenantOwnedSessionName as p, DAEMON_HTTP_INSTANCE_MISMATCH_HEADER as r, DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER as s, DAEMON_HTTP_BASE_PATH as t, buildDaemonHttpAuthHeaders as u };
package/dist/index.d.mts CHANGED
@@ -27,6 +27,8 @@ type DaemonProxyOptions = {
27
27
  upstreamBaseUrl: string;
28
28
  /** Auth token of the upstream daemon. Never leaves the proxy. */
29
29
  upstreamToken: string;
30
+ /** Fixed public HTTP(S) origin for upload tickets. */
31
+ publicOrigin?: string;
30
32
  maxRpcBodyBytes?: number;
31
33
  /**
32
34
  * Longest time one daemon request may take, including its body. Unset, an exchange lasts as long
@@ -50,11 +52,8 @@ type DaemonProxy = {
50
52
  /** Identifies this proxy instance in its health payload, so clients notice a restart. */
51
53
  readonly instanceId: string;
52
54
  /**
53
- * Answers one client request. `request.url` must be the URL the client used, because upload
54
- * tickets are rewritten to its origin. The first comma-separated `x-forwarded-proto` value
55
- * overrides its scheme when it is `http` or `https` (case-insensitive). This value is
56
- * client-controlled unless ingress replaces it with the public scheme. Replace rather than
57
- * append forwarding metadata, or remove untrusted headers and construct the public request URL.
55
+ * Answers one client request. Without `publicOrigin`, the embedder must construct
56
+ * `request.url` with the canonical client-facing origin. Forwarding headers do not select it.
58
57
  * Abort `request.signal` when the client goes away so in-flight daemon work is cancelled.
59
58
  * Resolves with an error response rather than rejecting.
60
59
  */
@@ -62,7 +61,7 @@ type DaemonProxy = {
62
61
  };
63
62
  declare function createDaemonProxy(options: DaemonProxyOptions): DaemonProxy;
64
63
  declare function createDaemonProxyServer(options: DaemonProxyOptions): http.Server;
65
- /** Serves a proxy from any `node:http` or `node:https` server; upload tickets follow its scheme. */
64
+ /** Serves a proxy from any `node:http` or `node:https` server. */
66
65
  declare function createDaemonProxyRequestListener(proxy: DaemonProxy): http.RequestListener;
67
66
  //#endregion
68
67
  export { type DaemonProxy, type DaemonProxyAuthenticate, type DaemonProxyAuthenticatedClient, type DaemonProxyOptions, type DaemonProxyUpstreamFetch, createDaemonProxy, createDaemonProxyRequestListener, createDaemonProxyServer };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { r as normalizeError, t as AppError } from "./errors.mjs";
2
+ import { a as DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, c as DAEMON_REQUEST_MAX_BYTES, d as buildDaemonHttpUrl, f as buildDaemonInstanceMismatchRpcResponse, g as normalizeTenantId, h as normalizeDaemonPublicOrigin, i as DAEMON_HTTP_NETWORK_ACCESS_HEADER, l as buildDaemonHealthPayload, n as DAEMON_HTTP_INSTANCE_HEADER, o as DAEMON_HTTP_TENANT_HEADER, p as isTenantOwnedSessionName, r as DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, s as DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER, t as DAEMON_HTTP_BASE_PATH, u as buildDaemonHttpAuthHeaders } from "./daemon-http.mjs";
2
3
  import crypto, { randomUUID } from "node:crypto";
3
4
  import http from "node:http";
4
- import "node:path";
5
5
  //#region ../host-kit/src/internal/transport.ts
6
6
  /**
7
7
  * Compares two secret strings in constant time. Hashing both inputs first
@@ -14,70 +14,6 @@ function timingSafeStringEqual(a, b) {
14
14
  return crypto.timingSafeEqual(hashA, hashB);
15
15
  }
16
16
  //#endregion
17
- //#region ../contracts/src/daemon-http.ts
18
- const DAEMON_HTTP_BASE_PATH = "/agent-device";
19
- const DAEMON_HTTP_TENANT_HEADER = "x-agent-device-tenant";
20
- const DAEMON_HTTP_NETWORK_ACCESS_HEADER = "x-agent-device-network-access";
21
- const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = "public-only";
22
- function buildDaemonHttpUrl(baseUrl, route) {
23
- const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
24
- return new URL(route.replace(/^\/+/, ""), normalizedBase).toString();
25
- }
26
- function buildDaemonHttpAuthHeaders(token) {
27
- const normalizedToken = token?.trim();
28
- if (!normalizedToken) return {};
29
- return {
30
- authorization: `Bearer ${normalizedToken}`,
31
- "x-agent-device-token": normalizedToken
32
- };
33
- }
34
- /** The tenant id every daemon route accepts, trimmed, or `undefined` when it breaks the rule. */
35
- function normalizeTenantId(raw) {
36
- if (!raw) return void 0;
37
- const value = raw.trim();
38
- if (!value) return void 0;
39
- if (!/^[a-zA-Z0-9._-]{1,128}$/.test(value)) return void 0;
40
- return value;
41
- }
42
- /** Whether `sessionName` lies beneath the `<tenant>:` prefix tenant isolation names sessions with. */
43
- function isTenantOwnedSessionName(tenant, sessionName) {
44
- return sessionName.startsWith(`${tenant}:`);
45
- }
46
- /**
47
- * The largest serialized daemon request, in UTF-8 bytes, that any transport reads: the socket
48
- * line, the HTTP `/rpc` body, and the proxy's `/rpc` body. Clients refuse a larger request before
49
- * sending it. It sits well above what a client builds: `test` inlines one replay bundle per flow,
50
- * each up to 2 MiB before JSON escaping, so 64 MiB fits a suite of several maximum-size flows with
51
- * worst-case escaping. It also bounds the memory one unauthenticated connection can hold.
52
- */
53
- const DAEMON_REQUEST_MAX_BYTES = 67108864;
54
- const DAEMON_HTTP_INSTANCE_HEADER = "x-agent-device-instance";
55
- const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = "x-agent-device-upstream-instance";
56
- const DAEMON_HTTP_INSTANCE_MISMATCH_HEADER = "x-agent-device-instance-mismatch";
57
- function buildDaemonInstanceMismatchRpcResponse(id, message, data) {
58
- return {
59
- jsonrpc: "2.0",
60
- id,
61
- error: {
62
- code: -32001,
63
- message,
64
- data
65
- }
66
- };
67
- }
68
- function buildDaemonHealthPayload(service, version, options = {}) {
69
- return {
70
- ok: true,
71
- service,
72
- version,
73
- rpcProtocolVersion: 2,
74
- ...options.instanceId !== void 0 ? { instanceId: options.instanceId } : {},
75
- ...options.hostArch !== void 0 ? { hostArch: options.hostArch } : {},
76
- ...options.leaseBackends !== void 0 ? { leaseBackends: options.leaseBackends } : {},
77
- ...options.upstream !== void 0 ? { upstream: options.upstream } : {}
78
- };
79
- }
80
- //#endregion
81
17
  //#region src/install-source-admission.ts
82
18
  function carriesUnbackedHostPathInstallSource(rpcBody) {
83
19
  const params = readRpcParams(rpcBody);
@@ -158,7 +94,7 @@ function createDaemonProxy(options) {
158
94
  function createDaemonProxyServer(options) {
159
95
  return http.createServer(createDaemonProxyRequestListener(createDaemonProxy(options)));
160
96
  }
161
- /** Serves a proxy from any `node:http` or `node:https` server; upload tickets follow its scheme. */
97
+ /** Serves a proxy from any `node:http` or `node:https` server. */
162
98
  function createDaemonProxyRequestListener(proxy) {
163
99
  return (req, res) => {
164
100
  import("./node-http.mjs").then(({ serveProxyRequest }) => serveProxyRequest(proxy, req, res)).catch((error) => {
@@ -260,7 +196,7 @@ async function proxyHealthResponse(request, options, instanceId) {
260
196
  const [upstream, { readVersion }, { readHostCpuArch }] = await Promise.all([
261
197
  readUpstreamHealth(request, options),
262
198
  import("./version.mjs"),
263
- import("./process.mjs")
199
+ import("./process.mjs").then((n) => n.t)
264
200
  ]);
265
201
  return Response.json(buildDaemonHealthPayload("agent-device-proxy", readVersion(), {
266
202
  upstream,
@@ -304,7 +240,8 @@ async function forwardProxyRequest(params) {
304
240
  request,
305
241
  upstreamResponse,
306
242
  headers,
307
- uploadHeaders: caller.uploadHeaders
243
+ uploadHeaders: caller.uploadHeaders,
244
+ publicOrigin: options.publicOrigin
308
245
  });
309
246
  return new Response(upstreamResponse.body, {
310
247
  status: upstreamResponse.status,
@@ -335,33 +272,36 @@ function routeResponseHeaders(route) {
335
272
  return [];
336
273
  }
337
274
  async function rewrittenUploadPreflightResponse(params) {
338
- const { request, upstreamResponse, headers, uploadHeaders } = params;
275
+ const { request, upstreamResponse, headers, uploadHeaders, publicOrigin } = params;
339
276
  const text = await upstreamResponse.text();
340
277
  headers.set("content-type", upstreamResponse.headers.get("content-type") ?? "application/json");
341
- return new Response(rewriteUploadPreflightResponse(text, request, uploadHeaders), {
278
+ return new Response(rewriteUploadPreflightResponse(text, request, uploadHeaders, publicOrigin, upstreamResponse.ok), {
342
279
  status: upstreamResponse.status,
343
280
  headers
344
281
  });
345
282
  }
346
- function rewriteUploadPreflightResponse(body, request, uploadHeaders) {
283
+ function rewriteUploadPreflightResponse(body, request, uploadHeaders, publicOrigin, expectTicket) {
347
284
  let parsed;
348
285
  try {
349
286
  parsed = JSON.parse(body);
350
287
  } catch {
351
- return body;
288
+ if (!expectTicket) return body;
289
+ throw new Error("Invalid upstream upload ticket");
352
290
  }
353
- if (!parsed || typeof parsed !== "object") return body;
291
+ if (!expectTicket && (!parsed || typeof parsed !== "object" || !("upload" in parsed))) return body;
292
+ if (!parsed || typeof parsed !== "object") throw new Error("Invalid upstream upload ticket");
354
293
  const record = parsed;
355
- if (!record.upload || typeof record.upload !== "object") return body;
356
- const rewrittenUrl = typeof record.upload.url === "string" ? rewriteUploadDirectUrl(record.upload.url, request) : null;
294
+ if (typeof record.uploadId !== "string" || !record.uploadId || record.uploadId.trim() !== record.uploadId || record.uploadId.includes("/") || !record.upload || typeof record.upload !== "object") throw new Error("Invalid upstream upload ticket");
295
+ const rewrittenUrl = typeof record.upload.url === "string" ? rewriteUploadDirectUrl(record.upload.url, record.uploadId, request, publicOrigin) : null;
296
+ if (!rewrittenUrl) throw new Error("Invalid upstream upload ticket");
357
297
  return JSON.stringify({
358
298
  ...parsed,
359
299
  upload: {
360
300
  ...record.upload,
361
- ...rewrittenUrl ? { url: rewrittenUrl } : {},
301
+ url: rewrittenUrl,
362
302
  headers: {
363
303
  ...upstreamTicketContentType(record.upload.headers),
364
- ...rewrittenUrl ? uploadHeaders : {}
304
+ ...uploadHeaders
365
305
  }
366
306
  }
367
307
  });
@@ -372,29 +312,31 @@ function upstreamTicketContentType(headers) {
372
312
  for (const [name, value] of Object.entries(headers)) if (name.toLowerCase() === "content-type" && typeof value === "string") return { "content-type": value };
373
313
  return {};
374
314
  }
375
- function rewriteUploadDirectUrl(upstreamUrl, request) {
315
+ function rewriteUploadDirectUrl(upstreamUrl, uploadId, request, publicOrigin) {
376
316
  let parsed;
377
317
  try {
378
318
  parsed = new URL(upstreamUrl);
379
319
  } catch {
380
320
  return null;
381
321
  }
382
- if (!parsed.pathname.startsWith("/upload/")) return null;
322
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash || parsed.pathname !== `/upload/direct/${uploadId}`) return null;
383
323
  const requestUrl = new URL(request.url);
384
324
  const uploadIndex = requestUrl.pathname.lastIndexOf("/upload/preflight");
385
325
  const uploadPrefix = uploadIndex >= 0 ? requestUrl.pathname.slice(0, uploadIndex) : "";
386
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
387
- const rewritten = new URL(requestUrl.origin);
388
- if (forwardedProto === "http" || forwardedProto === "https") rewritten.protocol = forwardedProto;
326
+ const rewritten = new URL(publicOrigin ?? requestUrl.origin);
389
327
  rewritten.pathname = `${uploadPrefix}${parsed.pathname}`;
390
328
  rewritten.search = parsed.search;
391
329
  return rewritten.toString();
392
330
  }
393
331
  function normalizeProxyOptions(options) {
332
+ const upstreamBaseUrl = normalizeBaseUrl(options.upstreamBaseUrl, "upstreamBaseUrl");
333
+ const upstreamToken = normalizeToken(options.upstreamToken, "upstreamToken");
334
+ const clientToken = options.authenticate ? void 0 : normalizeToken(options.clientToken ?? "", "clientToken");
394
335
  return {
395
- upstreamBaseUrl: normalizeBaseUrl(options.upstreamBaseUrl, "upstreamBaseUrl"),
396
- upstreamToken: normalizeToken(options.upstreamToken, "upstreamToken"),
397
- clientToken: options.authenticate ? void 0 : normalizeToken(options.clientToken ?? "", "clientToken"),
336
+ upstreamBaseUrl,
337
+ publicOrigin: options.publicOrigin === void 0 ? void 0 : normalizeDaemonPublicOrigin(options.publicOrigin),
338
+ upstreamToken,
339
+ clientToken,
398
340
  authenticate: options.authenticate,
399
341
  maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES,
400
342
  upstreamTimeoutMs: options.upstreamTimeoutMs,
@@ -1,3 +1,4 @@
1
+ import { m as nodeHttpRequestUrl } from "./daemon-http.mjs";
1
2
  import { Readable } from "node:stream";
2
3
  import { pipeline } from "node:stream/promises";
3
4
  import { TLSSocket } from "node:tls";
@@ -27,10 +28,7 @@ function endWithStatus(res, status) {
27
28
  }
28
29
  /** `null` when the Host header and path do not form a URL that Fetch accepts. */
29
30
  function requestUrl(req) {
30
- const scheme = req.socket instanceof TLSSocket ? "https" : "http";
31
- const url = URL.parse(req.url ?? "/", `${scheme}://${req.headers.host ?? "127.0.0.1"}`);
32
- if (!url || url.username || url.password) return null;
33
- return url;
31
+ return nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket);
34
32
  }
35
33
  function toWebRequest(url, req, res) {
36
34
  const method = req.method ?? "GET";
@@ -0,0 +1,101 @@
1
+ import { hostPlatform, n as runCmd, r as withoutCommandExecutorOverride, uniquePositivePids } from "./process.mjs";
2
+ import path from "node:path";
3
+ import { readlink } from "node:fs/promises";
4
+ import { clearTimeout, setTimeout } from "node:timers";
5
+ //#region ../host-kit/src/internal/process-executable-path.ts
6
+ const DEFAULT_TIMEOUT_MS = 1e3;
7
+ const WINDOWS_TIMEOUT_FLOOR_MS = 2e3;
8
+ const PATH_BUFFER_BYTES = 4096;
9
+ async function readProcessExecutablePaths(pids, host, timeoutMs = DEFAULT_TIMEOUT_MS) {
10
+ const selected = uniquePositivePids(pids).filter((pid) => pid <= 2147483647);
11
+ if (selected.length === 0) return /* @__PURE__ */ new Map();
12
+ const platform = hostPlatform();
13
+ if (platform === "linux") return await readLinuxPaths(selected, timeoutMs);
14
+ if (platform !== "darwin" && platform !== "win32") return /* @__PURE__ */ new Map();
15
+ return await withoutCommandExecutorOverride(async () => {
16
+ try {
17
+ const windows = platform === "win32";
18
+ const executable = windows ? windowsPowerShellPath(host.env) : "/usr/bin/osascript";
19
+ if (!executable) return /* @__PURE__ */ new Map();
20
+ const result = await runCmd(executable, windows ? windowsArgs(selected) : darwinArgs(selected), {
21
+ allowFailure: true,
22
+ timeoutMs: windows ? Math.max(timeoutMs, WINDOWS_TIMEOUT_FLOOR_MS) : timeoutMs
23
+ });
24
+ return result.exitCode === 0 ? parsePaths(result.stdout, selected, windows) : /* @__PURE__ */ new Map();
25
+ } catch {
26
+ return /* @__PURE__ */ new Map();
27
+ }
28
+ });
29
+ }
30
+ function windowsPowerShellPath(env) {
31
+ const key = Object.keys(env).find((name) => name.toUpperCase() === "SYSTEMROOT");
32
+ const root = key === void 0 ? void 0 : env[key];
33
+ if (!root || !path.win32.isAbsolute(root) || path.win32.parse(root).root.length < 3) return;
34
+ return path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
35
+ }
36
+ async function readLinuxPaths(pids, timeoutMs) {
37
+ const observations = Promise.all(pids.map(async (pid) => {
38
+ try {
39
+ const bytes = await readlink(`/proc/${pid}/exe`, { encoding: "buffer" });
40
+ if (bytes.length >= PATH_BUFFER_BYTES) return void 0;
41
+ const value = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
42
+ return validPath(value, false) && !value.endsWith(" (deleted)") ? [pid, value] : void 0;
43
+ } catch {
44
+ return;
45
+ }
46
+ }));
47
+ let cancelTimeout = () => {};
48
+ try {
49
+ const rows = await Promise.race([observations, new Promise((resolve) => {
50
+ const timer = setTimeout(resolve, timeoutMs);
51
+ cancelTimeout = () => clearTimeout(timer);
52
+ })]);
53
+ return new Map(rows?.filter((row) => row !== void 0) ?? []);
54
+ } finally {
55
+ cancelTimeout();
56
+ }
57
+ }
58
+ function darwinArgs(pids) {
59
+ return [
60
+ "-l",
61
+ "JavaScript",
62
+ "-e",
63
+ `ObjC.import("Foundation"); ObjC.bindFunction("proc_pidpath", ["int", ["int", "void *", "uint32"]]); JSON.stringify(${JSON.stringify(pids)}.map(function(pid) { var b=$.NSMutableData.dataWithLength(${PATH_BUFFER_BYTES}); var n=$.proc_pidpath(pid,b.mutableBytes,${PATH_BUFFER_BYTES}); if(n<=0 || n>=${PATH_BUFFER_BYTES}) return {pid:pid}; var d=$.NSData.dataWithBytesLength(b.bytes,n); try { var s=$.NSString.alloc.initWithDataEncoding(d,$.NSUTF8StringEncoding); return {pid:pid,path:ObjC.unwrap(s)}; } catch (_) { return {pid:pid}; } }));`
64
+ ];
65
+ }
66
+ function windowsArgs(pids) {
67
+ return [
68
+ "-NoProfile",
69
+ "-NonInteractive",
70
+ "-Command",
71
+ `$OutputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new(); ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process -Filter '${pids.map((pid) => `ProcessId=${pid}`).join(" OR ")}' | ForEach-Object { @{pid=$_.ProcessId; path=$_.ExecutablePath} })`
72
+ ];
73
+ }
74
+ function parsePaths(output, pids, windows) {
75
+ const paths = /* @__PURE__ */ new Map();
76
+ try {
77
+ const rows = JSON.parse(output.replace(/^\uFEFF/, ""));
78
+ if (!Array.isArray(rows)) return paths;
79
+ const requested = new Set(pids);
80
+ const seen = /* @__PURE__ */ new Set();
81
+ for (const row of rows) {
82
+ if (!row || typeof row !== "object") continue;
83
+ const { pid, path: value } = row;
84
+ if (typeof pid !== "number" || !requested.has(pid)) continue;
85
+ if (seen.has(pid)) {
86
+ paths.delete(pid);
87
+ continue;
88
+ }
89
+ seen.add(pid);
90
+ if (typeof value === "string" && validPath(value, windows)) paths.set(pid, value);
91
+ }
92
+ } catch {
93
+ return /* @__PURE__ */ new Map();
94
+ }
95
+ return paths;
96
+ }
97
+ function validPath(value, windows) {
98
+ return value.length > 0 && Buffer.byteLength(value, "utf8") < PATH_BUFFER_BYTES && !/[\0\uFFFD]/.test(value) && (windows ? path.win32.isAbsolute(value) : path.posix.isAbsolute(value));
99
+ }
100
+ //#endregion
101
+ export { readProcessExecutablePaths };
package/dist/process.mjs CHANGED
@@ -1,12 +1,24 @@
1
1
  import { i as redactDiagnosticData, n as createRequestCanceledError, t as AppError } from "./errors.mjs";
2
2
  import crypto, { randomUUID } from "node:crypto";
3
3
  import path from "node:path";
4
- import fs from "node:fs";
5
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
+ import fs from "node:fs";
6
6
  import { spawn, spawnSync } from "node:child_process";
7
7
  import { Readable } from "node:stream";
8
8
  import { pipeline } from "node:stream/promises";
9
9
  import os from "node:os";
10
+ //#region \0rolldown/runtime.js
11
+ var __defProp = Object.defineProperty;
12
+ var __exportAll = (all, no_symbols) => {
13
+ let target = {};
14
+ for (var name in all) __defProp(target, name, {
15
+ get: all[name],
16
+ enumerable: true
17
+ });
18
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
19
+ return target;
20
+ };
21
+ //#endregion
10
22
  //#region ../kernel/src/source-value.ts
11
23
  const BOOLEAN_TRUE_VALUES = /* @__PURE__ */ new Set([
12
24
  "1",
@@ -740,6 +752,32 @@ function parseHostProcessCommandRows(stdout) {
740
752
  command: match[3]
741
753
  }));
742
754
  }
755
+ /** State and start token from one `/proc/<pid>/stat` read, so a reused pid cannot mix lifetimes. */
756
+ function readLinuxProcessStat(pid) {
757
+ if (process.platform !== "linux") return null;
758
+ try {
759
+ const bootId = fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
760
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
761
+ const end = stat.lastIndexOf(")");
762
+ if (end < 0) return null;
763
+ const fields = stat.slice(end + 1).trim().split(/\s+/);
764
+ const state = fields[0];
765
+ const startTime = fields[19];
766
+ if (!bootId || !state || !startTime || !/^\d+$/.test(startTime)) return null;
767
+ return {
768
+ state,
769
+ startTime: `linux:${bootId}:${startTime}`
770
+ };
771
+ } catch {
772
+ return null;
773
+ }
774
+ }
775
+ /** Positive proof of different lifetimes; unreadable or mixed-format records prove nothing. */
776
+ function processStartTimesDiffer(left, right) {
777
+ if (!left || !right) return false;
778
+ if (left.startsWith("linux:") !== right.startsWith("linux:")) return false;
779
+ return left !== right;
780
+ }
743
781
  function readProcessStartTime(pid) {
744
782
  return readProcessField(pid, "lstart=");
745
783
  }
@@ -815,7 +853,11 @@ function parseHostProcessIdentityRows(stdout) {
815
853
  if (!match) continue;
816
854
  const pid = Number.parseInt(match[1], 10);
817
855
  if (!Number.isInteger(pid) || pid <= 0) continue;
818
- rows.push({
856
+ const linux = readLinuxProcessStat(pid);
857
+ rows.push(linux ? {
858
+ pid,
859
+ ...linux
860
+ } : {
819
861
  pid,
820
862
  state: match[2],
821
863
  startTime: match[3]
@@ -833,6 +875,10 @@ function windowsProcessIdentityRows(rows) {
833
875
  function readProcessField(pid, field) {
834
876
  if (!Number.isInteger(pid) || pid <= 0) return null;
835
877
  if (isWindowsHostPlatform()) return readWindowsProcessField(pid, field);
878
+ if (field === "lstart=") {
879
+ const token = readLinuxProcessStat(pid)?.startTime;
880
+ if (token !== void 0) return token;
881
+ }
836
882
  try {
837
883
  return processFieldValue(runCmdSync(hostPsCommand(), [
838
884
  "-p",
@@ -1039,7 +1085,7 @@ function readConfirmedProcessStopDetails(details) {
1039
1085
  function judgeProcessIdentity(expected, facts) {
1040
1086
  if (facts.zombie) return "exited";
1041
1087
  const { startTime, matches } = expected;
1042
- if (startTime && facts.startTime && facts.startTime !== startTime) return "reassigned";
1088
+ if (processStartTimesDiffer(startTime, facts.startTime)) return "reassigned";
1043
1089
  const commandMatches = facts.command === null || !matches ? void 0 : matches(facts.command);
1044
1090
  if (!startTime && commandMatches === false) return "reassigned";
1045
1091
  if (!startTime && !matches) return "unverified";
@@ -1282,7 +1328,7 @@ function isSelectedPurpose(record, policy) {
1282
1328
  return policy.purposes === void 0 || policy.purposes.has(record.purpose);
1283
1329
  }
1284
1330
  function isOpenWebSessionSkip(scope, record, policy) {
1285
- return scope === "daemon" && record.purpose === "managed-web-browser" && policy.openWebSession;
1331
+ return scope === "daemon" && (record.purpose === "managed-web-browser" || record.purpose === "verified-managed-web-browser") && policy.openWebSession;
1286
1332
  }
1287
1333
  function appendReapOutcome(summary, record, outcome, retained) {
1288
1334
  summary[outcome] += 1;
@@ -1534,7 +1580,7 @@ function ownerIdentityMatches(left, right) {
1534
1580
  */
1535
1581
  function ownerIdentityDiffers(left, right) {
1536
1582
  if (left.pid !== right.pid) return true;
1537
- return Boolean(left.startTime && right.startTime && left.startTime !== right.startTime);
1583
+ return processStartTimesDiffer(left.startTime, right.startTime);
1538
1584
  }
1539
1585
  /**
1540
1586
  * This is deliberately proof-oriented, in both directions. A filesystem read
@@ -1600,8 +1646,7 @@ function hostSaysZombie(owner, observation) {
1600
1646
  * not answer is unknown evidence, never proof.
1601
1647
  */
1602
1648
  function provesPidReused(owner, observation) {
1603
- const currentStartTime = observation === void 0 ? readProcessStartTime(owner.pid) : observation?.startTime ?? null;
1604
- return currentStartTime !== null && currentStartTime !== owner.startTime;
1649
+ return processStartTimesDiffer(observation === void 0 ? readProcessStartTime(owner.pid) : observation?.startTime ?? null, owner.startTime);
1605
1650
  }
1606
1651
  function classifyOwnerStateDirectory(stateDir) {
1607
1652
  try {
@@ -1614,4 +1659,52 @@ function classifyOwnerStateDirectory(stateDir) {
1614
1659
  }
1615
1660
  }
1616
1661
  //#endregion
1617
- export { captureHostEnvironment, classifyOwnerLiveness, classifyOwnerLivenessAsync, classifyOwnerLivenessFromObservation, confirmedProcessStopDetails, createOwnedProcessRecordStore, describeUnconfirmedProcessStop, expandProcessTree, hostNodeExecutablePath, hostNodeVersion, hostPlatform, hostProcessId, isProcessAlive, isProcessGroupAlive, isProcessPid, isProcessZombie, judgeProcessIdentity, listHostProcesses, ownerIdentityDiffers, ownerIdentityMatches, readConfirmedProcessStopDetails, readCurrentOwnerIdentity, readHostCpuArch, readHostCpuArchSync, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, readOwnedProcessRecordFile, readProcessCommand, readProcessIdentities, readProcessIdentityFacts, readProcessStartTime, reapOwnedProcessRecordsAtStartup, signalPidsBestEffort, signalProcessGroupBestEffort, stopProcessAndConfirmExit, uniquePositivePids, waitForProcessExit, writeHostStderr };
1662
+ //#region ../host-kit/src/process.ts
1663
+ var process_exports = /* @__PURE__ */ __exportAll({
1664
+ captureHostEnvironment: () => captureHostEnvironment,
1665
+ classifyOwnerLiveness: () => classifyOwnerLiveness,
1666
+ classifyOwnerLivenessAsync: () => classifyOwnerLivenessAsync,
1667
+ classifyOwnerLivenessFromObservation: () => classifyOwnerLivenessFromObservation,
1668
+ confirmedProcessStopDetails: () => confirmedProcessStopDetails,
1669
+ createOwnedProcessRecordStore: () => createOwnedProcessRecordStore,
1670
+ describeUnconfirmedProcessStop: () => describeUnconfirmedProcessStop,
1671
+ expandProcessTree: () => expandProcessTree,
1672
+ hostNodeExecutablePath: () => hostNodeExecutablePath,
1673
+ hostNodeVersion: () => hostNodeVersion,
1674
+ hostPlatform: () => hostPlatform,
1675
+ hostProcessId: () => hostProcessId,
1676
+ isProcessAlive: () => isProcessAlive,
1677
+ isProcessGroupAlive: () => isProcessGroupAlive,
1678
+ isProcessPid: () => isProcessPid,
1679
+ isProcessZombie: () => isProcessZombie,
1680
+ judgeProcessIdentity: () => judgeProcessIdentity,
1681
+ listHostProcesses: () => listHostProcesses,
1682
+ ownerIdentityDiffers: () => ownerIdentityDiffers,
1683
+ ownerIdentityMatches: () => ownerIdentityMatches,
1684
+ processStartTimesDiffer: () => processStartTimesDiffer,
1685
+ readConfirmedProcessStopDetails: () => readConfirmedProcessStopDetails,
1686
+ readCurrentOwnerIdentity: () => readCurrentOwnerIdentity,
1687
+ readHostCpuArch: () => readHostCpuArch,
1688
+ readHostCpuArchSync: () => readHostCpuArchSync,
1689
+ readHostProcessIdentityObservations: () => readHostProcessIdentityObservations,
1690
+ readHostProcessIdentityObservationsAsync: () => readHostProcessIdentityObservationsAsync,
1691
+ readOwnedProcessRecordFile: () => readOwnedProcessRecordFile,
1692
+ readProcessCommand: () => readProcessCommand,
1693
+ readProcessExecutablePaths: () => readProcessExecutablePaths,
1694
+ readProcessIdentities: () => readProcessIdentities,
1695
+ readProcessIdentityFacts: () => readProcessIdentityFacts,
1696
+ readProcessStartTime: () => readProcessStartTime,
1697
+ reapOwnedProcessRecordsAtStartup: () => reapOwnedProcessRecordsAtStartup,
1698
+ signalPidsBestEffort: () => signalPidsBestEffort,
1699
+ signalProcessGroupBestEffort: () => signalProcessGroupBestEffort,
1700
+ stopProcessAndConfirmExit: () => stopProcessAndConfirmExit,
1701
+ uniquePositivePids: () => uniquePositivePids,
1702
+ waitForProcessExit: () => waitForProcessExit,
1703
+ writeHostStderr: () => writeHostStderr
1704
+ });
1705
+ /** Observes actual executable paths. Missing entries are unknown, not proof of exit. */
1706
+ async function readProcessExecutablePaths(pids, host, timeoutMs) {
1707
+ return await (await import("./process-executable-path.mjs")).readProcessExecutablePaths(pids, host, timeoutMs);
1708
+ }
1709
+ //#endregion
1710
+ export { captureHostEnvironment, classifyOwnerLiveness, classifyOwnerLivenessAsync, classifyOwnerLivenessFromObservation, confirmedProcessStopDetails, createOwnedProcessRecordStore, describeUnconfirmedProcessStop, expandProcessTree, hostNodeExecutablePath, hostNodeVersion, hostPlatform, hostProcessId, isProcessAlive, isProcessGroupAlive, isProcessPid, isProcessZombie, judgeProcessIdentity, listHostProcesses, runCmd as n, ownerIdentityDiffers, ownerIdentityMatches, processStartTimesDiffer, withoutCommandExecutorOverride as r, readConfirmedProcessStopDetails, readCurrentOwnerIdentity, readHostCpuArch, readHostCpuArchSync, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, readOwnedProcessRecordFile, readProcessCommand, readProcessExecutablePaths, readProcessIdentities, readProcessIdentityFacts, readProcessStartTime, reapOwnedProcessRecordsAtStartup, signalPidsBestEffort, signalProcessGroupBestEffort, stopProcessAndConfirmExit, process_exports as t, uniquePositivePids, waitForProcessExit, writeHostStderr };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-device/proxy",
3
- "version": "0.21.37",
3
+ "version": "0.21.38",
4
4
  "type": "module",
5
5
  "description": "Transport-neutral authenticating proxy in front of an agent-device daemon.",
6
6
  "license": "MIT",
@@ -25,8 +25,8 @@
25
25
  "dist"
26
26
  ],
27
27
  "devDependencies": {
28
- "@agent-device/host-kit": "0.0.0",
29
28
  "@agent-device/contracts": "0.0.0",
29
+ "@agent-device/host-kit": "0.0.0",
30
30
  "@agent-device/kernel": "0.0.0"
31
31
  },
32
32
  "scripts": {