@neuralnomads/codenomad 0.13.3 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/auth/manager.js +5 -1
  2. package/dist/background-processes/manager.js +164 -25
  3. package/dist/cli-upgrade.js +53 -0
  4. package/dist/cli-upgrade.test.js +31 -0
  5. package/dist/config/schema.js +1 -0
  6. package/dist/events/bus.js +4 -0
  7. package/dist/filesystem/browser.js +15 -1
  8. package/dist/index.js +79 -11
  9. package/dist/opencode-config/package-lock.json +380 -0
  10. package/dist/opencode-config/package.json +2 -2
  11. package/dist/opencode-config/plugin/lib/background-process.ts +14 -2
  12. package/dist/plugins/voice-mode.js +2 -1
  13. package/dist/server/__tests__/network-addresses.test.js +68 -0
  14. package/dist/server/__tests__/remote-proxy.test.js +204 -0
  15. package/dist/server/http-server.js +292 -47
  16. package/dist/server/network-addresses.js +43 -1
  17. package/dist/server/remote-proxy.js +466 -0
  18. package/dist/server/routes/background-processes.js +19 -1
  19. package/dist/server/routes/meta.js +0 -3
  20. package/dist/server/routes/plugin.js +5 -1
  21. package/dist/server/routes/remote-proxy.js +42 -0
  22. package/dist/server/routes/remote-servers.js +142 -0
  23. package/dist/server/routes/settings.js +1 -1
  24. package/dist/server/routes/sidecars.js +46 -0
  25. package/dist/server/routes/workspaces.js +118 -0
  26. package/dist/settings/migrate.js +5 -0
  27. package/dist/settings/service.js +64 -4
  28. package/dist/sidecars/manager.js +193 -0
  29. package/dist/workspaces/__tests__/git-worktrees.test.js +43 -0
  30. package/dist/workspaces/__tests__/spawn.test.js +140 -0
  31. package/dist/workspaces/git-mutations.js +98 -0
  32. package/dist/workspaces/git-status.js +323 -0
  33. package/dist/workspaces/git-worktrees.js +18 -1
  34. package/dist/workspaces/manager.js +11 -4
  35. package/dist/workspaces/opencode-auth.js +18 -0
  36. package/dist/workspaces/opencode-auth.test.js +34 -0
  37. package/dist/workspaces/runtime.js +56 -78
  38. package/dist/workspaces/spawn.js +219 -0
  39. package/dist/workspaces/worktree-directory.js +74 -0
  40. package/package.json +1 -1
  41. package/public/assets/ChangesTab-ovdqLHc3.js +2 -0
  42. package/public/assets/DiffToolbar-B12EfXMX.js +1 -0
  43. package/public/assets/FilesTab-nb_itEXG.js +2 -0
  44. package/public/assets/GitChangesTab-DcT_4BL2.js +2 -0
  45. package/public/assets/{SplitFilePanel-DwrJM7GQ.js → SplitFilePanel-BOHH3F--.js} +1 -1
  46. package/public/assets/StatusTab-Dyt_EG33.js +1 -0
  47. package/public/assets/align-justify-9zpyaAdy.js +1 -0
  48. package/public/assets/{bundle-full-JwmTIwMd.js → bundle-full-xFW13Lny.js} +1 -1
  49. package/public/assets/diff-viewer-xG9yjpN8.js +1 -0
  50. package/public/assets/git-diff-vendor-CSgooKT_.js +52 -0
  51. package/public/assets/index-7DpT014-.js +1 -0
  52. package/public/assets/index-BDK4V9L0.js +1 -0
  53. package/public/assets/index-Bx-Bezt2.js +1 -0
  54. package/public/assets/index-CCAZZY0l.js +1 -0
  55. package/public/assets/index-CEcZq5WB.js +1 -0
  56. package/public/assets/index-CQCmSDHL.js +1 -0
  57. package/public/assets/{index-CkYwnPl7.js → index-Cz_fl8aY.js} +1 -1
  58. package/public/assets/index-Dcgftm1m.css +1 -0
  59. package/public/assets/index-m4C3yx3J.js +1 -0
  60. package/public/assets/index-mh_z9p40.js +2 -0
  61. package/public/assets/{loading-CfqkoCbA.js → loading-HUhLEgb_.js} +1 -1
  62. package/public/assets/main-CKhfaeKI.js +48 -0
  63. package/public/assets/{markdown-D2uUJada.js → markdown-BeXU9Z-x.js} +22 -22
  64. package/public/assets/monaco-viewer-BgP6xpZ6.js +26 -0
  65. package/public/assets/{todo-i3zWdksA.js → todo-D6PVVp_f.js} +1 -1
  66. package/public/assets/tool-call-Dgn3NlA8.js +60 -0
  67. package/public/assets/unified-picker-DuNuUpLy.js +1 -0
  68. package/public/assets/wrap-text-zghCl6wN.js +1 -0
  69. package/public/index.html +5 -5
  70. package/public/loading.html +5 -5
  71. package/public/sw.js +1 -1
  72. package/public/ui-version.json +1 -1
  73. package/public/assets/ChangesTab-X8IIoIdB.js +0 -2
  74. package/public/assets/DiffToolbar-Djg0ksr_.js +0 -1
  75. package/public/assets/FilesTab-BpYPA_Zr.js +0 -2
  76. package/public/assets/GitChangesTab-DeGsV8--.js +0 -2
  77. package/public/assets/StatusTab-mT1B3wST.js +0 -1
  78. package/public/assets/diff-viewer-CKnTxbWB.js +0 -1
  79. package/public/assets/git-diff-vendor-CAv-4upN.js +0 -52
  80. package/public/assets/index-BEzx5r3P.css +0 -1
  81. package/public/assets/index-BHjkPi4D.js +0 -1
  82. package/public/assets/index-CUkIenrg.js +0 -1
  83. package/public/assets/index-D9RMxxcS.js +0 -1
  84. package/public/assets/index-DiFfJ0HM.js +0 -1
  85. package/public/assets/index-LmDdmmJP.js +0 -1
  86. package/public/assets/index-UaIyK67v.js +0 -1
  87. package/public/assets/index-lhjxIgwf.js +0 -2
  88. package/public/assets/index-xsUu1uOf.js +0 -1
  89. package/public/assets/main-B3yZBpaS.js +0 -56
  90. package/public/assets/monaco-viewer-UU9TfOpS.js +0 -15
  91. package/public/assets/tool-call-Bl3Lai68.js +0 -60
  92. package/public/assets/unified-picker-B506AoQt.js +0 -1
@@ -0,0 +1,204 @@
1
+ import assert from "node:assert/strict";
2
+ import { after, afterEach, describe, it } from "node:test";
3
+ import fs from "node:fs";
4
+ import http from "node:http";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { Agent, fetch } from "undici";
8
+ import { RemoteProxySessionManager } from "../remote-proxy";
9
+ import { resolveHttpsOptions } from "../tls";
10
+ const sharedTempDir = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-remote-proxy-test-"));
11
+ const sharedTls = resolveHttpsOptions({
12
+ enabled: true,
13
+ configDir: sharedTempDir,
14
+ host: "127.0.0.1",
15
+ logger: createStubLogger(),
16
+ });
17
+ if (!sharedTls) {
18
+ throw new Error("Failed to generate HTTPS options for remote proxy tests");
19
+ }
20
+ const sharedHttpsOptions = sharedTls.httpsOptions;
21
+ const httpsDispatcher = new Agent({ connect: { rejectUnauthorized: false } });
22
+ const managers = new Set();
23
+ afterEach(async () => {
24
+ for (const manager of managers) {
25
+ await disposeManager(manager);
26
+ }
27
+ managers.clear();
28
+ });
29
+ after(() => {
30
+ fs.rmSync(sharedTempDir, { recursive: true, force: true });
31
+ httpsDispatcher.close().catch(() => { });
32
+ });
33
+ describe("RemoteProxySessionManager", () => {
34
+ it("blocks proxying before activation and keeps bootstrap tokens scoped per session", async () => {
35
+ await withUpstreamServer(async (upstreamBaseUrl) => {
36
+ const manager = createSessionManager();
37
+ const session1 = await createSession(manager, `${upstreamBaseUrl}/base`);
38
+ const session2 = await createSession(manager, `${upstreamBaseUrl}/base`);
39
+ const blocked = await proxyFetch(`${session1.proxyOrigin}/status`);
40
+ assert.equal(blocked.status, 403);
41
+ const wrongTokenResponse = await proxyFetch(`${session1.proxyOrigin}/__codenomad/api/auth/token`, {
42
+ method: "POST",
43
+ headers: { "content-type": "application/json" },
44
+ body: JSON.stringify({ token: session2.token }),
45
+ });
46
+ assert.equal(wrongTokenResponse.status, 401);
47
+ assert.equal(await activateSession(session1), true);
48
+ assert.equal(await activateSession(session2), true);
49
+ }, (req, res) => {
50
+ res.writeHead(200, { "content-type": "text/plain" });
51
+ res.end(req.url ?? "");
52
+ });
53
+ });
54
+ it("preserves remote base paths and rewrites same-origin redirects to the local proxy origin", async () => {
55
+ await withUpstreamServer(async (upstreamBaseUrl) => {
56
+ const manager = createSessionManager();
57
+ const session = await createSession(manager, `${upstreamBaseUrl}/base`);
58
+ await activateSession(session);
59
+ const apiResponse = await proxyFetch(`${session.proxyOrigin}/api/auth/status?foo=bar`);
60
+ assert.equal(apiResponse.status, 200);
61
+ assert.equal(await apiResponse.text(), "/base/api/auth/status?foo=bar");
62
+ const redirectResponse = await proxyFetch(`${session.proxyOrigin}/redirect`, { redirect: "manual" });
63
+ assert.equal(redirectResponse.status, 302);
64
+ assert.equal(redirectResponse.headers.get("location"), `${session.proxyOrigin}/base/after?ok=1`);
65
+ }, (req, res) => {
66
+ const requestUrl = req.url ?? "";
67
+ if (requestUrl === "/base/redirect") {
68
+ res.writeHead(302, { location: "/base/after?ok=1" });
69
+ res.end();
70
+ return;
71
+ }
72
+ res.writeHead(200, { "content-type": "text/plain" });
73
+ res.end(requestUrl);
74
+ });
75
+ });
76
+ it("rewrites set-cookie names for the proxy and restores cookie names on proxied requests", async () => {
77
+ await withUpstreamServer(async (upstreamBaseUrl) => {
78
+ const manager = createSessionManager();
79
+ const session = await createSession(manager, `${upstreamBaseUrl}/base`);
80
+ await activateSession(session);
81
+ const loginResponse = await proxyFetch(`${session.proxyOrigin}/login`);
82
+ assert.equal(loginResponse.status, 200);
83
+ const setCookie = getSetCookie(loginResponse)[0];
84
+ assert.match(setCookie, /^cnrp_[0-9a-f]+_session=abc123/i);
85
+ assert.doesNotMatch(setCookie, /domain=/i);
86
+ const cookieHeader = setCookie.split(";", 1)[0];
87
+ const whoamiResponse = await proxyFetch(`${session.proxyOrigin}/whoami`, {
88
+ headers: { cookie: cookieHeader },
89
+ });
90
+ assert.equal(await whoamiResponse.text(), "session=abc123");
91
+ }, (req, res) => {
92
+ const requestUrl = req.url ?? "";
93
+ if (requestUrl === "/base/login") {
94
+ res.writeHead(200, {
95
+ "content-type": "text/plain",
96
+ "set-cookie": "session=abc123; Path=/; Secure; HttpOnly; Domain=127.0.0.1",
97
+ });
98
+ res.end("ok");
99
+ return;
100
+ }
101
+ if (requestUrl === "/base/whoami") {
102
+ res.writeHead(200, { "content-type": "text/plain" });
103
+ res.end(req.headers.cookie ?? "");
104
+ return;
105
+ }
106
+ res.writeHead(404, { "content-type": "text/plain" });
107
+ res.end(requestUrl);
108
+ });
109
+ });
110
+ it("supports explicit deletion and idle cleanup of sessions", async () => {
111
+ await withUpstreamServer(async (upstreamBaseUrl) => {
112
+ const manager = createSessionManager();
113
+ const session = await createSession(manager, `${upstreamBaseUrl}/base`);
114
+ assert.equal(await manager.deleteSession(session.sessionId), true);
115
+ assert.equal(await manager.deleteSession(session.sessionId), false);
116
+ const session3 = await createSession(manager, `${upstreamBaseUrl}/base`);
117
+ const internalSessions = manager.sessions;
118
+ const internalCleanup = manager.cleanupExpiredSessions;
119
+ internalSessions.get(session3.sessionId).lastAccessAt = Date.now() - 31 * 60000;
120
+ await internalCleanup.call(manager);
121
+ assert.equal(internalSessions.has(session3.sessionId), false);
122
+ assert.equal(await manager.deleteSession(session3.sessionId), false);
123
+ }, (_req, res) => {
124
+ res.writeHead(200, { "content-type": "text/plain" });
125
+ res.end("ok");
126
+ });
127
+ });
128
+ });
129
+ function createSessionManager() {
130
+ const manager = new RemoteProxySessionManager({
131
+ authManager: {
132
+ isLoopbackRequest: () => true,
133
+ },
134
+ logger: createStubLogger(),
135
+ httpsOptions: sharedHttpsOptions,
136
+ });
137
+ managers.add(manager);
138
+ return manager;
139
+ }
140
+ async function createSession(manager, baseUrl) {
141
+ const created = await manager.createSession(baseUrl, false);
142
+ const windowUrl = new URL(created.windowUrl);
143
+ return {
144
+ sessionId: created.sessionId,
145
+ windowUrl,
146
+ proxyOrigin: windowUrl.origin,
147
+ token: decodeURIComponent(windowUrl.hash.replace(/^#/, "")),
148
+ };
149
+ }
150
+ async function activateSession(session) {
151
+ const response = await proxyFetch(`${session.proxyOrigin}/__codenomad/api/auth/token`, {
152
+ method: "POST",
153
+ headers: { "content-type": "application/json" },
154
+ body: JSON.stringify({ token: session.token }),
155
+ });
156
+ if (!response.ok) {
157
+ return false;
158
+ }
159
+ const body = (await response.json());
160
+ return body.ok === true;
161
+ }
162
+ function getSetCookie(response) {
163
+ const values = response.headers.getSetCookie?.();
164
+ if (Array.isArray(values) && values.length > 0) {
165
+ return values;
166
+ }
167
+ const fallback = response.headers.get("set-cookie");
168
+ return fallback ? [fallback] : [];
169
+ }
170
+ async function proxyFetch(url, init) {
171
+ return fetch(url, { dispatcher: httpsDispatcher, ...init });
172
+ }
173
+ async function disposeManager(manager) {
174
+ const sessions = Array.from(manager.sessions.keys());
175
+ for (const sessionId of sessions) {
176
+ await manager.deleteSession(sessionId);
177
+ }
178
+ clearInterval(manager.cleanupTimer);
179
+ }
180
+ async function withUpstreamServer(callback, handler) {
181
+ const server = http.createServer(handler);
182
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
183
+ try {
184
+ const address = server.address();
185
+ if (!address || typeof address === "string") {
186
+ throw new Error("Failed to resolve upstream server address");
187
+ }
188
+ await callback(`http://127.0.0.1:${address.port}`);
189
+ }
190
+ finally {
191
+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
192
+ }
193
+ }
194
+ function createStubLogger() {
195
+ const logger = {
196
+ info() { },
197
+ warn() { },
198
+ error() { },
199
+ child() {
200
+ return logger;
201
+ },
202
+ };
203
+ return logger;
204
+ }
@@ -3,9 +3,12 @@ import cors from "@fastify/cors";
3
3
  import fastifyStatic from "@fastify/static";
4
4
  import replyFrom from "@fastify/reply-from";
5
5
  import fs from "fs";
6
+ import { connect as connectTcp } from "net";
6
7
  import path from "path";
8
+ import { connect as connectTls } from "tls";
7
9
  import { fetch } from "undici";
8
- import { isValidWorktreeSlug, listWorktrees, resolveRepoRoot } from "../workspaces/git-worktrees";
10
+ import { isValidWorktreeSlug } from "../workspaces/git-worktrees";
11
+ import { resolveWorktreeDirectory } from "../workspaces/worktree-directory";
9
12
  import { registerWorkspaceRoutes } from "./routes/workspaces";
10
13
  import { registerSettingsRoutes } from "./routes/settings";
11
14
  import { registerFilesystemRoutes } from "./routes/filesystem";
@@ -16,12 +19,12 @@ import { registerPluginRoutes } from "./routes/plugin";
16
19
  import { registerBackgroundProcessRoutes } from "./routes/background-processes";
17
20
  import { registerWorktreeRoutes } from "./routes/worktrees";
18
21
  import { registerSpeechRoutes } from "./routes/speech";
22
+ import { registerRemoteServerRoutes } from "./routes/remote-servers";
23
+ import { registerRemoteProxyRoutes } from "./routes/remote-proxy";
24
+ import { registerSideCarRoutes } from "./routes/sidecars";
19
25
  import { BackgroundProcessManager } from "../background-processes/manager";
20
26
  import { registerAuthRoutes } from "./routes/auth";
21
27
  import { sendUnauthorized, wantsHtml } from "../auth/http-auth";
22
- import { ClientConnectionManager } from "../clients/connection-manager";
23
- import { PluginChannelManager } from "../plugins/channel";
24
- import { VoiceModeManager } from "../plugins/voice-mode";
25
28
  export function createHttpServer(deps) {
26
29
  // Fastify's type-level RawServer inference gets noisy when toggling HTTP vs HTTPS.
27
30
  // We keep the runtime behavior correct and cast the instance to a generic FastifyInstance.
@@ -128,13 +131,6 @@ export function createHttpServer(deps) {
128
131
  eventBus: deps.eventBus,
129
132
  logger: deps.logger.child({ component: "background-processes" }),
130
133
  });
131
- const clientConnectionManager = new ClientConnectionManager(deps.logger.child({ component: "client-connections" }));
132
- const pluginChannel = new PluginChannelManager(deps.logger.child({ component: "plugin-channel" }));
133
- const voiceModeManager = new VoiceModeManager({
134
- connections: clientConnectionManager,
135
- channel: pluginChannel,
136
- logger: deps.logger.child({ component: "voice-mode" }),
137
- });
138
134
  registerAuthRoutes(app, { authManager: deps.authManager });
139
135
  app.addHook("preHandler", (request, reply, done) => {
140
136
  const rawUrl = request.raw.url ?? request.url;
@@ -144,12 +140,15 @@ export function createHttpServer(deps) {
144
140
  if (deps.authManager.isTokenBootstrapEnabled()) {
145
141
  publicPagePaths.add("/auth/token");
146
142
  }
147
- if (publicApiPaths.has(pathname) || publicPagePaths.has(pathname)) {
143
+ const isLoopbackRemoteProxyDelete = request.method === "DELETE" &&
144
+ pathname.startsWith("/api/remote-proxy/sessions/") &&
145
+ deps.authManager.isLoopbackRequest(request);
146
+ if (publicApiPaths.has(pathname) || publicPagePaths.has(pathname) || isLoopbackRemoteProxyDelete) {
148
147
  done();
149
148
  return;
150
149
  }
151
150
  const session = deps.authManager.getSessionFromRequest(request);
152
- const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/");
151
+ const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/") || pathname.startsWith("/sidecars/");
153
152
  if (requiresAuthForApi && !session) {
154
153
  // Allow OpenCode plugin -> CodeNomad calls with per-instance basic auth.
155
154
  const pluginMatch = pathname.match(/^\/workspaces\/([^/]+)\/plugin(?:\/|$)/);
@@ -199,7 +198,7 @@ export function createHttpServer(deps) {
199
198
  eventBus: deps.eventBus,
200
199
  registerClient: registerSseClient,
201
200
  logger: sseLogger,
202
- connectionManager: clientConnectionManager,
201
+ connectionManager: deps.clientConnectionManager,
203
202
  });
204
203
  registerWorktreeRoutes(app, { workspaceManager: deps.workspaceManager });
205
204
  registerStorageRoutes(app, {
@@ -207,13 +206,22 @@ export function createHttpServer(deps) {
207
206
  eventBus: deps.eventBus,
208
207
  workspaceManager: deps.workspaceManager,
209
208
  });
209
+ registerRemoteServerRoutes(app, { logger: apiLogger });
210
+ registerRemoteProxyRoutes(app, { logger: proxyLogger, sessionManager: deps.remoteProxySessionManager });
210
211
  registerSpeechRoutes(app, { speechService: deps.speechService });
212
+ registerSideCarRoutes(app, { sidecarManager: deps.sidecarManager });
213
+ registerSideCarProxyRoutes(app, { sidecarManager: deps.sidecarManager, logger: proxyLogger });
214
+ setupSideCarWebSocketProxy(app, {
215
+ sidecarManager: deps.sidecarManager,
216
+ authManager: deps.authManager,
217
+ logger: proxyLogger,
218
+ });
211
219
  registerPluginRoutes(app, {
212
220
  workspaceManager: deps.workspaceManager,
213
221
  eventBus: deps.eventBus,
214
222
  logger: proxyLogger,
215
- channel: pluginChannel,
216
- voiceModeManager,
223
+ channel: deps.pluginChannel,
224
+ voiceModeManager: deps.voiceModeManager,
217
225
  });
218
226
  registerBackgroundProcessRoutes(app, { backgroundProcessManager });
219
227
  registerInstanceProxyRoutes(app, { workspaceManager: deps.workspaceManager, logger: proxyLogger });
@@ -272,11 +280,52 @@ export function createHttpServer(deps) {
272
280
  },
273
281
  stop: () => {
274
282
  closeSseClients();
275
- clientConnectionManager.shutdown();
276
283
  return app.close();
277
284
  },
278
285
  };
279
286
  }
287
+ function registerSideCarProxyRoutes(app, deps) {
288
+ const proxyBaseHandler = async (request, reply) => {
289
+ await proxySideCarRequest({
290
+ request,
291
+ reply,
292
+ sidecarManager: deps.sidecarManager,
293
+ logger: deps.logger,
294
+ pathSuffix: "",
295
+ });
296
+ };
297
+ const proxyWildcardHandler = async (request, reply) => {
298
+ await proxySideCarRequest({
299
+ request,
300
+ reply,
301
+ sidecarManager: deps.sidecarManager,
302
+ logger: deps.logger,
303
+ pathSuffix: request.params["*"] ?? "",
304
+ });
305
+ };
306
+ app.all("/sidecars/:id", proxyBaseHandler);
307
+ app.all("/sidecars/:id/*", proxyWildcardHandler);
308
+ }
309
+ function setupSideCarWebSocketProxy(app, deps) {
310
+ app.server.on("upgrade", (request, socket, head) => {
311
+ const rawUrl = request.url ?? "/";
312
+ const parsed = parseSideCarUpgradePath(rawUrl);
313
+ if (!parsed) {
314
+ return;
315
+ }
316
+ void proxySideCarWebSocketUpgrade({
317
+ request,
318
+ socket: socket,
319
+ head,
320
+ sidecarId: parsed.sidecarId,
321
+ incomingPath: parsed.pathname,
322
+ search: parsed.search,
323
+ sidecarManager: deps.sidecarManager,
324
+ authManager: deps.authManager,
325
+ logger: deps.logger,
326
+ });
327
+ });
328
+ }
280
329
  function registerInstanceProxyRoutes(app, deps) {
281
330
  app.register(async (instance) => {
282
331
  instance.removeAllContentTypeParsers();
@@ -559,36 +608,6 @@ function normalizeInstanceSuffix(pathSuffix) {
559
608
  const trimmed = pathSuffix.replace(/^\/+/, "");
560
609
  return trimmed.length === 0 ? "/" : `/${trimmed}`;
561
610
  }
562
- const WORKTREE_CACHE_TTL_MS = 2000;
563
- const worktreeCache = new Map();
564
- async function getCachedWorktrees(params) {
565
- const cached = worktreeCache.get(params.workspaceId);
566
- const now = Date.now();
567
- if (cached && cached.expiresAt > now) {
568
- return cached;
569
- }
570
- const { repoRoot } = await resolveRepoRoot(params.workspacePath, params.logger);
571
- const worktrees = await listWorktrees({ repoRoot, workspaceFolder: params.workspacePath, logger: params.logger });
572
- const entry = {
573
- expiresAt: now + WORKTREE_CACHE_TTL_MS,
574
- repoRoot,
575
- worktrees: worktrees.map((wt) => ({ slug: wt.slug, directory: wt.directory })),
576
- };
577
- worktreeCache.set(params.workspaceId, entry);
578
- return entry;
579
- }
580
- async function resolveWorktreeDirectory(params) {
581
- const { worktreeSlug } = params;
582
- const cached = await getCachedWorktrees({ workspaceId: params.workspaceId, workspacePath: params.workspacePath, logger: params.logger });
583
- const match = cached.worktrees.find((wt) => wt.slug === worktreeSlug);
584
- if (match) {
585
- return match.directory;
586
- }
587
- // If the slug is new (e.g., created moments ago), refresh once.
588
- worktreeCache.delete(params.workspaceId);
589
- const refreshed = await getCachedWorktrees({ workspaceId: params.workspaceId, workspacePath: params.workspacePath, logger: params.logger });
590
- return refreshed.worktrees.find((wt) => wt.slug === worktreeSlug)?.directory ?? null;
591
- }
592
611
  function setupStaticUi(app, uiDir, authManager) {
593
612
  if (!uiDir) {
594
613
  app.log.warn("UI static directory not provided; API endpoints only");
@@ -679,3 +698,229 @@ function buildProxyHeaders(headers) {
679
698
  }
680
699
  return result;
681
700
  }
701
+ async function proxySideCarRequest(args) {
702
+ const sidecarId = args.request.params.id ?? "";
703
+ const sidecar = await args.sidecarManager.get(sidecarId);
704
+ if (!sidecar) {
705
+ args.reply.code(404).send({ error: "SideCar not found" });
706
+ return;
707
+ }
708
+ const pathname = (args.request.raw.url ?? args.request.url ?? "").split("?")[0] ?? "";
709
+ const queryIndex = (args.request.raw.url ?? args.request.url ?? "").indexOf("?");
710
+ const search = queryIndex >= 0 ? (args.request.raw.url ?? args.request.url ?? "").slice(queryIndex) : "";
711
+ const pathSuffix = args.pathSuffix ?? "";
712
+ const requestPath = pathSuffix ? `${args.sidecarManager.buildProxyBasePath(sidecarId)}/${pathSuffix.replace(/^\/+/, "")}` : args.sidecarManager.buildProxyBasePath(sidecarId);
713
+ const targetPath = args.sidecarManager.buildTargetPath(sidecarId, requestPath, search);
714
+ const targetOrigin = args.sidecarManager.buildTargetOrigin(sidecar);
715
+ const targetUrl = `${targetOrigin}${targetPath}`;
716
+ args.logger.debug({ sidecarId: sidecar.id, targetUrl, pathname, prefixMode: sidecar.prefixMode }, "Proxying request to SideCar");
717
+ await args.reply.from(targetUrl, {
718
+ rewriteRequestHeaders: (_originalRequest, headers) => sanitizeSideCarProxyRequestHeaders(headers, targetOrigin),
719
+ rewriteHeaders: (headers) => rewriteSideCarResponseHeaders(headers, sidecarId, targetOrigin, sidecar.prefixMode),
720
+ onError: (reply, { error }) => {
721
+ args.logger.error({ sidecarId: sidecar.id, err: error, targetUrl }, "Failed to proxy SideCar request");
722
+ if (!reply.sent) {
723
+ reply.code(502).send({ error: "SideCar proxy failed" });
724
+ }
725
+ },
726
+ });
727
+ }
728
+ function parseSideCarUpgradePath(rawUrl) {
729
+ let parsed;
730
+ try {
731
+ parsed = new URL(rawUrl, "http://localhost");
732
+ }
733
+ catch {
734
+ return null;
735
+ }
736
+ const match = parsed.pathname.match(/^\/sidecars\/([^/]+)(?:\/.*)?$/);
737
+ if (!match) {
738
+ return null;
739
+ }
740
+ try {
741
+ return {
742
+ sidecarId: decodeURIComponent(match[1] ?? ""),
743
+ pathname: parsed.pathname,
744
+ search: parsed.search,
745
+ };
746
+ }
747
+ catch {
748
+ return null;
749
+ }
750
+ }
751
+ async function proxySideCarWebSocketUpgrade(args) {
752
+ const { request, socket, head, sidecarId, incomingPath, search, sidecarManager, authManager, logger } = args;
753
+ if (!isWebSocketUpgradeRequest(request)) {
754
+ rejectUpgrade(socket, 400, "Bad Request");
755
+ return;
756
+ }
757
+ const session = authManager.getSessionFromHeaders(request.headers);
758
+ if (!session) {
759
+ rejectUpgrade(socket, 401, "Unauthorized");
760
+ return;
761
+ }
762
+ const sidecar = await sidecarManager.get(sidecarId);
763
+ if (!sidecar) {
764
+ rejectUpgrade(socket, 404, "Not Found");
765
+ return;
766
+ }
767
+ const targetOrigin = sidecarManager.buildTargetOrigin(sidecar);
768
+ const targetPath = sidecarManager.buildTargetPath(sidecarId, incomingPath, search);
769
+ const targetUrl = new URL(`${targetOrigin}${targetPath}`);
770
+ logger.debug({ sidecarId, targetUrl: targetUrl.toString(), prefixMode: sidecar.prefixMode }, "Proxying websocket to SideCar");
771
+ const { socket: upstream, readyEvent } = createSideCarUpstreamSocket(targetUrl);
772
+ const closeBoth = () => {
773
+ if (!socket.destroyed) {
774
+ socket.destroy();
775
+ }
776
+ if (!upstream.destroyed) {
777
+ upstream.destroy();
778
+ }
779
+ };
780
+ upstream.once("error", (error) => {
781
+ logger.error({ sidecarId, err: error, targetUrl: targetUrl.toString() }, "Failed to proxy SideCar websocket");
782
+ rejectUpgrade(socket, 502, "Bad Gateway");
783
+ if (!upstream.destroyed) {
784
+ upstream.destroy();
785
+ }
786
+ });
787
+ socket.once("error", (error) => {
788
+ logger.debug({ sidecarId, err: error }, "SideCar websocket client socket errored");
789
+ if (!upstream.destroyed) {
790
+ upstream.destroy();
791
+ }
792
+ });
793
+ upstream.once(readyEvent, () => {
794
+ try {
795
+ upstream.write(buildSideCarWebSocketRequest(request, targetUrl));
796
+ if (head.length > 0) {
797
+ upstream.write(head);
798
+ }
799
+ upstream.pipe(socket);
800
+ socket.pipe(upstream);
801
+ }
802
+ catch (error) {
803
+ logger.error({ sidecarId, err: error, targetUrl: targetUrl.toString() }, "Failed to forward SideCar websocket upgrade");
804
+ closeBoth();
805
+ }
806
+ });
807
+ upstream.once("close", () => {
808
+ if (!socket.destroyed) {
809
+ socket.end();
810
+ }
811
+ });
812
+ socket.once("close", () => {
813
+ if (!upstream.destroyed) {
814
+ upstream.end();
815
+ }
816
+ });
817
+ }
818
+ function createSideCarUpstreamSocket(targetUrl) {
819
+ const port = Number(targetUrl.port || (targetUrl.protocol === "https:" ? 443 : 80));
820
+ if (targetUrl.protocol === "https:") {
821
+ return {
822
+ socket: connectTls({
823
+ host: targetUrl.hostname,
824
+ port,
825
+ servername: targetUrl.hostname,
826
+ }),
827
+ readyEvent: "secureConnect",
828
+ };
829
+ }
830
+ return {
831
+ socket: connectTcp(port, targetUrl.hostname),
832
+ readyEvent: "connect",
833
+ };
834
+ }
835
+ function buildSideCarWebSocketRequest(request, targetUrl) {
836
+ const pathWithQuery = `${targetUrl.pathname}${targetUrl.search}`;
837
+ const requestLine = `${request.method ?? "GET"} ${pathWithQuery} HTTP/${request.httpVersion}\r\n`;
838
+ const headerLines = [];
839
+ const rawHeaders = request.rawHeaders ?? [];
840
+ const blockedHeaders = getBlockedSideCarRequestHeaders();
841
+ for (let index = 0; index < rawHeaders.length; index += 2) {
842
+ const key = rawHeaders[index];
843
+ const value = rawHeaders[index + 1];
844
+ if (!key || value === undefined)
845
+ continue;
846
+ const lower = key.toLowerCase();
847
+ if (blockedHeaders.has(lower))
848
+ continue;
849
+ if (lower === "origin") {
850
+ headerLines.push(`Origin: ${targetUrl.origin}\r\n`);
851
+ continue;
852
+ }
853
+ headerLines.push(`${key}: ${value}\r\n`);
854
+ }
855
+ const hostValue = targetUrl.port ? `${targetUrl.hostname}:${targetUrl.port}` : targetUrl.hostname;
856
+ headerLines.push(`Host: ${hostValue}\r\n`);
857
+ headerLines.push("\r\n");
858
+ return requestLine + headerLines.join("");
859
+ }
860
+ function isWebSocketUpgradeRequest(request) {
861
+ const upgrade = request.headers.upgrade;
862
+ if (typeof upgrade !== "string" || upgrade.toLowerCase() !== "websocket") {
863
+ return false;
864
+ }
865
+ const connection = request.headers.connection;
866
+ const connectionValue = Array.isArray(connection) ? connection.join(",") : connection ?? "";
867
+ return connectionValue.toLowerCase().split(",").map((part) => part.trim()).includes("upgrade");
868
+ }
869
+ function rejectUpgrade(socket, statusCode, statusText) {
870
+ if (socket.destroyed) {
871
+ return;
872
+ }
873
+ socket.write(`HTTP/1.1 ${statusCode} ${statusText}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
874
+ socket.destroy();
875
+ }
876
+ function rewriteSideCarResponseHeaders(headers, sidecarId, targetOrigin, prefixMode) {
877
+ if (prefixMode === "preserve") {
878
+ return headers;
879
+ }
880
+ const next = { ...headers };
881
+ const locationHeader = next.location;
882
+ const location = Array.isArray(locationHeader) ? locationHeader[0] : locationHeader;
883
+ if (!location) {
884
+ return next;
885
+ }
886
+ const publicBase = `/sidecars/${encodeURIComponent(sidecarId)}`;
887
+ if (location.startsWith("/")) {
888
+ next.location = `${publicBase}${location}`;
889
+ return next;
890
+ }
891
+ try {
892
+ const parsed = new URL(location);
893
+ if (parsed.origin === targetOrigin) {
894
+ next.location = `${publicBase}${parsed.pathname}${parsed.search}${parsed.hash}`;
895
+ }
896
+ }
897
+ catch {
898
+ // Relative redirects should continue to resolve against the public sidecar path.
899
+ }
900
+ return next;
901
+ }
902
+ function sanitizeSideCarProxyRequestHeaders(headers, targetOrigin) {
903
+ const blockedHeaders = getBlockedSideCarRequestHeaders();
904
+ const next = {};
905
+ for (const [key, value] of Object.entries(headers)) {
906
+ if (!value)
907
+ continue;
908
+ if (blockedHeaders.has(key.toLowerCase()))
909
+ continue;
910
+ next[key] = value;
911
+ }
912
+ next.origin = targetOrigin;
913
+ return next;
914
+ }
915
+ function getBlockedSideCarRequestHeaders() {
916
+ return new Set([
917
+ "host",
918
+ "authorization",
919
+ "proxy-authorization",
920
+ "forwarded",
921
+ "x-forwarded-for",
922
+ "x-forwarded-host",
923
+ "x-forwarded-port",
924
+ "x-forwarded-proto",
925
+ ]);
926
+ }
@@ -52,9 +52,51 @@ export function resolveNetworkAddresses(args) {
52
52
  const scopeDelta = scopeWeight[a.scope] - scopeWeight[b.scope];
53
53
  if (scopeDelta !== 0)
54
54
  return scopeDelta;
55
- return a.ip.localeCompare(b.ip);
55
+ return 0;
56
56
  });
57
57
  }
58
+ export function resolveRemoteAddresses(args) {
59
+ const all = resolveNetworkAddresses(args);
60
+ const userVisible = sortUserVisibleAddresses(all.filter((address) => address.scope === "external"));
61
+ return {
62
+ all,
63
+ userVisible,
64
+ primaryRemoteUrl: userVisible[0]?.remoteUrl,
65
+ };
66
+ }
67
+ function sortUserVisibleAddresses(addresses) {
68
+ return [...addresses].sort((left, right) => getUserVisiblePriority(left.ip) - getUserVisiblePriority(right.ip));
69
+ }
70
+ function getUserVisiblePriority(ip) {
71
+ if (isPrivateIPv4(ip))
72
+ return 0;
73
+ if (isLinkLocalIPv4(ip))
74
+ return 2;
75
+ return 1;
76
+ }
77
+ function isLinkLocalIPv4(ip) {
78
+ const octets = parseIPv4(ip);
79
+ if (!octets)
80
+ return false;
81
+ const [first, second] = octets;
82
+ return first === 169 && second === 254;
83
+ }
84
+ function isPrivateIPv4(ip) {
85
+ const octets = parseIPv4(ip);
86
+ if (!octets)
87
+ return false;
88
+ const [first, second] = octets;
89
+ if (first === 10)
90
+ return true;
91
+ if (first === 192 && second === 168)
92
+ return true;
93
+ return first === 172 && second >= 16 && second <= 31;
94
+ }
95
+ function parseIPv4(value) {
96
+ if (!isIPv4Address(value))
97
+ return null;
98
+ return value.split(".").map((part) => Number(part));
99
+ }
58
100
  function isIPv4Address(value) {
59
101
  if (!value)
60
102
  return false;