@neuralnomads/codenomad 0.15.0 → 0.17.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.
- package/README.md +50 -4
- package/dist/background-processes/manager.js +0 -1
- package/dist/config/schema.js +1 -0
- package/dist/filesystem/__tests__/browser.test.js +65 -0
- package/dist/filesystem/__tests__/search-cache.test.js +2 -2
- package/dist/filesystem/browser.js +25 -4
- package/dist/index.js +13 -6
- package/dist/launcher.js +12 -1
- package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
- package/dist/opencode-plugin.js +146 -0
- package/dist/opencode-plugin.test.js +28 -0
- package/dist/previews/manager.js +63 -0
- package/dist/server/__tests__/listener-base-url.test.js +30 -0
- package/dist/server/http-server.js +378 -152
- package/dist/server/listener-base-url.js +17 -0
- package/dist/server/routes/config-files.js +92 -0
- package/dist/server/routes/config-files.test.js +115 -0
- package/dist/server/routes/filesystem.js +13 -0
- package/dist/server/routes/previews.js +25 -0
- package/dist/server/routes/workspaces.js +38 -1
- package/dist/workspaces/__tests__/git-clone.test.js +142 -0
- package/dist/workspaces/__tests__/spawn.test.js +27 -9
- package/dist/workspaces/git-clone.js +148 -0
- package/dist/workspaces/manager.js +27 -6
- package/dist/workspaces/spawn.js +35 -9
- package/dist/workspaces/worktree-map.js +16 -0
- package/package.json +3 -3
- package/public/assets/FilesTab-B5ysoRLh.js +2 -0
- package/public/assets/GitChangesTab-BksCi53d.js +2 -0
- package/public/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/public/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/public/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/public/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/public/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/public/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/public/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/public/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/public/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/public/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/public/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/public/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/public/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/public/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/public/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/public/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/public/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/public/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/public/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/public/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/public/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/public/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/public/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/public/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/public/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/public/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/public/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/public/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/public/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/public/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/public/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/public/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/public/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/public/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/public/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/public/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/public/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/public/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/public/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/public/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/public/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/public/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/public/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/public/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/public/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/public/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/public/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/public/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/public/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/public/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/public/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/public/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/public/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/public/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/public/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/public/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/public/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/public/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/public/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/public/assets/{SplitFilePanel-BOHH3F--.js → SplitFilePanel-CrSfR22r.js} +1 -1
- package/public/assets/StatusTab-Dgqekgjn.js +1 -0
- package/public/assets/{align-justify-9zpyaAdy.js → align-justify-hRtBz8xe.js} +1 -1
- package/public/assets/{bundle-full-xFW13Lny.js → bundle-full-BVDA-a9Y.js} +2 -2
- package/public/assets/{diff-viewer-xG9yjpN8.js → diff-viewer-BCAI0Cw8.js} +1 -1
- package/public/assets/index-B2Qd6xQq.css +1 -0
- package/public/assets/index-BQpEhdk5.js +1 -0
- package/public/assets/index-BXIEm2zT.js +1 -0
- package/public/assets/index-CWjU9mAF.js +1 -0
- package/public/assets/index-Cvtlo58a.js +1 -0
- package/public/assets/index-DFlxnvHT.js +2 -0
- package/public/assets/index-Ddsv8Uc0.js +1 -0
- package/public/assets/index-Dn7woJnK.js +1 -0
- package/public/assets/index-DnCBfFB3.js +1 -0
- package/public/assets/index-DnXT1F8T.js +1 -0
- package/public/assets/index-Kv-3BRTi.js +1 -0
- package/public/assets/index-g-G1RiME.js +1 -0
- package/public/assets/{loading-HUhLEgb_.js → loading-bD3ppK2l.js} +1 -1
- package/public/assets/main-BsbMOeQg.js +65 -0
- package/public/assets/markdown-DJuaMC5H.js +315 -0
- package/public/assets/monaco-viewer-BFNhPQX7.js +26 -0
- package/public/assets/tool-call-BSJluZRW.js +59 -0
- package/public/assets/{unified-picker-DuNuUpLy.js → unified-picker-DmFyrIis.js} +1 -1
- package/public/assets/{wrap-text-zghCl6wN.js → wrap-text-BkcW_eTA.js} +1 -1
- package/public/index.html +4 -4
- package/public/loading.html +4 -4
- package/public/sw.js +1 -1
- package/public/ui-version.json +1 -1
- package/dist/opencode-config/README.md +0 -32
- package/dist/opencode-config/opencode.jsonc +0 -3
- package/dist/opencode-config/package-lock.json +0 -380
- package/dist/opencode-config/package.json +0 -9
- package/dist/opencode-config/plugin/codenomad.ts +0 -62
- package/dist/opencode-config/plugin/lib/background-process.ts +0 -265
- package/dist/opencode-config/plugin/lib/client.ts +0 -133
- package/dist/opencode-config/plugin/lib/request.ts +0 -214
- package/dist/opencode-config.js +0 -26
- package/public/assets/ChangesTab-ovdqLHc3.js +0 -2
- package/public/assets/DiffToolbar-B12EfXMX.js +0 -1
- package/public/assets/FilesTab-nb_itEXG.js +0 -2
- package/public/assets/GitChangesTab-DcT_4BL2.js +0 -2
- package/public/assets/StatusTab-Dyt_EG33.js +0 -1
- package/public/assets/index-7DpT014-.js +0 -1
- package/public/assets/index-BDK4V9L0.js +0 -1
- package/public/assets/index-Bx-Bezt2.js +0 -1
- package/public/assets/index-CCAZZY0l.js +0 -1
- package/public/assets/index-CEcZq5WB.js +0 -1
- package/public/assets/index-CQCmSDHL.js +0 -1
- package/public/assets/index-Cz_fl8aY.js +0 -1
- package/public/assets/index-Dcgftm1m.css +0 -1
- package/public/assets/index-m4C3yx3J.js +0 -1
- package/public/assets/index-mh_z9p40.js +0 -2
- package/public/assets/main-CKhfaeKI.js +0 -48
- package/public/assets/markdown-BeXU9Z-x.js +0 -58
- package/public/assets/monaco-viewer-BgP6xpZ6.js +0 -26
- package/public/assets/todo-D6PVVp_f.js +0 -1
- package/public/assets/tool-call-Dgn3NlA8.js +0 -60
|
@@ -7,11 +7,10 @@ import { connect as connectTcp } from "net";
|
|
|
7
7
|
import path from "path";
|
|
8
8
|
import { connect as connectTls } from "tls";
|
|
9
9
|
import { fetch } from "undici";
|
|
10
|
-
import { isValidWorktreeSlug } from "../workspaces/git-worktrees";
|
|
11
|
-
import { resolveWorktreeDirectory } from "../workspaces/worktree-directory";
|
|
12
10
|
import { registerWorkspaceRoutes } from "./routes/workspaces";
|
|
13
11
|
import { registerSettingsRoutes } from "./routes/settings";
|
|
14
12
|
import { registerFilesystemRoutes } from "./routes/filesystem";
|
|
13
|
+
import { registerConfigFileRoutes } from "./routes/config-files";
|
|
15
14
|
import { registerMetaRoutes } from "./routes/meta";
|
|
16
15
|
import { registerEventRoutes } from "./routes/events";
|
|
17
16
|
import { registerStorageRoutes } from "./routes/storage";
|
|
@@ -22,6 +21,7 @@ import { registerSpeechRoutes } from "./routes/speech";
|
|
|
22
21
|
import { registerRemoteServerRoutes } from "./routes/remote-servers";
|
|
23
22
|
import { registerRemoteProxyRoutes } from "./routes/remote-proxy";
|
|
24
23
|
import { registerSideCarRoutes } from "./routes/sidecars";
|
|
24
|
+
import { registerPreviewRoutes } from "./routes/previews";
|
|
25
25
|
import { BackgroundProcessManager } from "../background-processes/manager";
|
|
26
26
|
import { registerAuthRoutes } from "./routes/auth";
|
|
27
27
|
import { sendUnauthorized, wantsHtml } from "../auth/http-auth";
|
|
@@ -148,7 +148,7 @@ export function createHttpServer(deps) {
|
|
|
148
148
|
return;
|
|
149
149
|
}
|
|
150
150
|
const session = deps.authManager.getSessionFromRequest(request);
|
|
151
|
-
const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/") || pathname.startsWith("/sidecars/");
|
|
151
|
+
const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/") || pathname.startsWith("/sidecars/") || pathname.startsWith("/previews/");
|
|
152
152
|
if (requiresAuthForApi && !session) {
|
|
153
153
|
// Allow OpenCode plugin -> CodeNomad calls with per-instance basic auth.
|
|
154
154
|
const pluginMatch = pathname.match(/^\/workspaces\/([^/]+)\/plugin(?:\/|$)/);
|
|
@@ -193,6 +193,7 @@ export function createHttpServer(deps) {
|
|
|
193
193
|
registerWorkspaceRoutes(app, { workspaceManager: deps.workspaceManager });
|
|
194
194
|
registerSettingsRoutes(app, { settings: deps.settings, logger: apiLogger });
|
|
195
195
|
registerFilesystemRoutes(app, { fileSystemBrowser: deps.fileSystemBrowser });
|
|
196
|
+
registerConfigFileRoutes(app);
|
|
196
197
|
registerMetaRoutes(app, { serverMeta: deps.serverMeta });
|
|
197
198
|
registerEventRoutes(app, {
|
|
198
199
|
eventBus: deps.eventBus,
|
|
@@ -210,12 +211,19 @@ export function createHttpServer(deps) {
|
|
|
210
211
|
registerRemoteProxyRoutes(app, { logger: proxyLogger, sessionManager: deps.remoteProxySessionManager });
|
|
211
212
|
registerSpeechRoutes(app, { speechService: deps.speechService });
|
|
212
213
|
registerSideCarRoutes(app, { sidecarManager: deps.sidecarManager });
|
|
214
|
+
registerPreviewRoutes(app, { previewManager: deps.previewManager });
|
|
213
215
|
registerSideCarProxyRoutes(app, { sidecarManager: deps.sidecarManager, logger: proxyLogger });
|
|
216
|
+
registerPreviewProxyRoutes(app, { previewManager: deps.previewManager, logger: proxyLogger });
|
|
214
217
|
setupSideCarWebSocketProxy(app, {
|
|
215
218
|
sidecarManager: deps.sidecarManager,
|
|
216
219
|
authManager: deps.authManager,
|
|
217
220
|
logger: proxyLogger,
|
|
218
221
|
});
|
|
222
|
+
setupPreviewWebSocketProxy(app, {
|
|
223
|
+
previewManager: deps.previewManager,
|
|
224
|
+
authManager: deps.authManager,
|
|
225
|
+
logger: proxyLogger,
|
|
226
|
+
});
|
|
219
227
|
registerPluginRoutes(app, {
|
|
220
228
|
workspaceManager: deps.workspaceManager,
|
|
221
229
|
eventBus: deps.eventBus,
|
|
@@ -226,10 +234,10 @@ export function createHttpServer(deps) {
|
|
|
226
234
|
registerBackgroundProcessRoutes(app, { backgroundProcessManager });
|
|
227
235
|
registerInstanceProxyRoutes(app, { workspaceManager: deps.workspaceManager, logger: proxyLogger });
|
|
228
236
|
if (deps.uiDevServerUrl) {
|
|
229
|
-
setupDevProxy(app, deps.uiDevServerUrl, deps.authManager);
|
|
237
|
+
setupDevProxy(app, deps.uiDevServerUrl, deps.authManager, deps.previewManager, proxyLogger);
|
|
230
238
|
}
|
|
231
239
|
else {
|
|
232
|
-
setupStaticUi(app, deps.uiStaticDir, deps.authManager);
|
|
240
|
+
setupStaticUi(app, deps.uiStaticDir, deps.authManager, deps.previewManager, proxyLogger);
|
|
233
241
|
}
|
|
234
242
|
return {
|
|
235
243
|
instance: app,
|
|
@@ -306,6 +314,28 @@ function registerSideCarProxyRoutes(app, deps) {
|
|
|
306
314
|
app.all("/sidecars/:id", proxyBaseHandler);
|
|
307
315
|
app.all("/sidecars/:id/*", proxyWildcardHandler);
|
|
308
316
|
}
|
|
317
|
+
function registerPreviewProxyRoutes(app, deps) {
|
|
318
|
+
const proxyBaseHandler = async (request, reply) => {
|
|
319
|
+
await proxyPreviewRequest({
|
|
320
|
+
request,
|
|
321
|
+
reply,
|
|
322
|
+
previewManager: deps.previewManager,
|
|
323
|
+
logger: deps.logger,
|
|
324
|
+
pathSuffix: "",
|
|
325
|
+
});
|
|
326
|
+
};
|
|
327
|
+
const proxyWildcardHandler = async (request, reply) => {
|
|
328
|
+
await proxyPreviewRequest({
|
|
329
|
+
request,
|
|
330
|
+
reply,
|
|
331
|
+
previewManager: deps.previewManager,
|
|
332
|
+
logger: deps.logger,
|
|
333
|
+
pathSuffix: request.params["*"] ?? "",
|
|
334
|
+
});
|
|
335
|
+
};
|
|
336
|
+
app.all("/previews/:token", proxyBaseHandler);
|
|
337
|
+
app.all("/previews/:token/*", proxyWildcardHandler);
|
|
338
|
+
}
|
|
309
339
|
function setupSideCarWebSocketProxy(app, deps) {
|
|
310
340
|
app.server.on("upgrade", (request, socket, head) => {
|
|
311
341
|
const rawUrl = request.url ?? "/";
|
|
@@ -326,6 +356,26 @@ function setupSideCarWebSocketProxy(app, deps) {
|
|
|
326
356
|
});
|
|
327
357
|
});
|
|
328
358
|
}
|
|
359
|
+
function setupPreviewWebSocketProxy(app, deps) {
|
|
360
|
+
app.server.on("upgrade", (request, socket, head) => {
|
|
361
|
+
const rawUrl = request.url ?? "/";
|
|
362
|
+
const parsed = parsePreviewUpgradePath(rawUrl);
|
|
363
|
+
if (!parsed) {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
void proxyPreviewWebSocketUpgrade({
|
|
367
|
+
request,
|
|
368
|
+
socket: socket,
|
|
369
|
+
head,
|
|
370
|
+
token: parsed.token,
|
|
371
|
+
incomingPath: parsed.pathname,
|
|
372
|
+
search: parsed.search,
|
|
373
|
+
previewManager: deps.previewManager,
|
|
374
|
+
authManager: deps.authManager,
|
|
375
|
+
logger: deps.logger,
|
|
376
|
+
});
|
|
377
|
+
});
|
|
378
|
+
}
|
|
329
379
|
function registerInstanceProxyRoutes(app, deps) {
|
|
330
380
|
app.register(async (instance) => {
|
|
331
381
|
instance.removeAllContentTypeParsers();
|
|
@@ -335,7 +385,6 @@ function registerInstanceProxyRoutes(app, deps) {
|
|
|
335
385
|
request,
|
|
336
386
|
reply,
|
|
337
387
|
workspaceManager: deps.workspaceManager,
|
|
338
|
-
worktreeSlug: request.params.slug,
|
|
339
388
|
pathSuffix: "",
|
|
340
389
|
logger: deps.logger,
|
|
341
390
|
});
|
|
@@ -345,32 +394,17 @@ function registerInstanceProxyRoutes(app, deps) {
|
|
|
345
394
|
request,
|
|
346
395
|
reply,
|
|
347
396
|
workspaceManager: deps.workspaceManager,
|
|
348
|
-
worktreeSlug: request.params.slug,
|
|
349
397
|
pathSuffix: request.params["*"] ?? "",
|
|
350
398
|
logger: deps.logger,
|
|
351
399
|
});
|
|
352
400
|
};
|
|
353
|
-
instance.all("/workspaces/:id/
|
|
354
|
-
instance.all("/workspaces/:id/
|
|
401
|
+
instance.all("/workspaces/:id/instance", proxyBaseHandler);
|
|
402
|
+
instance.all("/workspaces/:id/instance/*", proxyWildcardHandler);
|
|
355
403
|
});
|
|
356
404
|
}
|
|
357
405
|
const INSTANCE_PROXY_HOST = "127.0.0.1";
|
|
358
|
-
// Special-case OpenCode directory override.
|
|
359
|
-
//
|
|
360
|
-
// UI clients may need to scope certain requests to an arbitrary directory that is not
|
|
361
|
-
// part of the Git worktree list. Since the OpenCode SDK does not reliably support
|
|
362
|
-
// injecting per-request headers, we encode an override into the *path* and strip it
|
|
363
|
-
// before proxying to the instance.
|
|
364
|
-
//
|
|
365
|
-
// Example proxied request path:
|
|
366
|
-
// /workspaces/:id/worktrees/:slug/instance/__dir/<base64url>/session/create
|
|
367
|
-
//
|
|
368
|
-
// The server will decode <base64url> -> absolute directory, validate it, then set
|
|
369
|
-
// x-opencode-directory accordingly and forward the request to /session/create.
|
|
370
|
-
const OPENCODE_DIR_OVERRIDE_PREFIX = "__dir/";
|
|
371
|
-
const OPENCODE_DIR_OVERRIDE_MAX_LEN = 4096;
|
|
372
406
|
async function proxyWorkspaceRequest(args) {
|
|
373
|
-
const { request, reply, workspaceManager, logger
|
|
407
|
+
const { request, reply, workspaceManager, logger } = args;
|
|
374
408
|
const workspaceId = request.params.id;
|
|
375
409
|
const workspace = workspaceManager.get(workspaceId);
|
|
376
410
|
const bodyToJson = (body) => {
|
|
@@ -440,47 +474,7 @@ async function proxyWorkspaceRequest(args) {
|
|
|
440
474
|
reply.code(502).send({ error: "Workspace instance is not ready" });
|
|
441
475
|
return;
|
|
442
476
|
}
|
|
443
|
-
|
|
444
|
-
reply.code(400).send({ error: "Invalid worktree slug" });
|
|
445
|
-
return;
|
|
446
|
-
}
|
|
447
|
-
let extracted;
|
|
448
|
-
try {
|
|
449
|
-
extracted = extractOpencodeDirectoryOverride(args.pathSuffix);
|
|
450
|
-
}
|
|
451
|
-
catch (error) {
|
|
452
|
-
const message = error instanceof Error ? error.message : "Invalid directory override";
|
|
453
|
-
reply.code(400).send({ error: message });
|
|
454
|
-
return;
|
|
455
|
-
}
|
|
456
|
-
let directory = null;
|
|
457
|
-
let forwardedSuffix = extracted.forwardedSuffix;
|
|
458
|
-
if (extracted.overrideDirectory) {
|
|
459
|
-
try {
|
|
460
|
-
directory = validateAndNormalizeOverrideDirectory({
|
|
461
|
-
overrideDirectory: extracted.overrideDirectory,
|
|
462
|
-
workspaceRoot: workspace.path,
|
|
463
|
-
});
|
|
464
|
-
}
|
|
465
|
-
catch (error) {
|
|
466
|
-
const message = error instanceof Error ? error.message : "Invalid directory override";
|
|
467
|
-
reply.code(400).send({ error: message });
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
else {
|
|
472
|
-
directory = await resolveWorktreeDirectory({
|
|
473
|
-
workspaceId,
|
|
474
|
-
workspacePath: workspace.path,
|
|
475
|
-
worktreeSlug,
|
|
476
|
-
logger,
|
|
477
|
-
});
|
|
478
|
-
if (!directory) {
|
|
479
|
-
reply.code(404).send({ error: "Worktree not found" });
|
|
480
|
-
return;
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
const normalizedSuffix = normalizeInstanceSuffix(forwardedSuffix);
|
|
477
|
+
const normalizedSuffix = normalizeInstanceSuffix(args.pathSuffix);
|
|
484
478
|
const queryIndex = (request.raw.url ?? "").indexOf("?");
|
|
485
479
|
const search = queryIndex >= 0 ? (request.raw.url ?? "").slice(queryIndex) : "";
|
|
486
480
|
const targetUrl = `http://${INSTANCE_PROXY_HOST}:${port}${normalizedSuffix}${search}`;
|
|
@@ -494,10 +488,6 @@ async function proxyWorkspaceRequest(args) {
|
|
|
494
488
|
if (instanceAuthHeader) {
|
|
495
489
|
headers.authorization = instanceAuthHeader;
|
|
496
490
|
}
|
|
497
|
-
// OpenCode expects the *full* path; we send it via header to avoid query tampering.
|
|
498
|
-
const isNonASCII = /[^\x00-\x7F]/.test(directory);
|
|
499
|
-
const encodedDirectory = isNonASCII ? encodeURIComponent(directory) : directory;
|
|
500
|
-
headers["x-opencode-directory"] = encodedDirectory;
|
|
501
491
|
if (logger.isLevelEnabled("trace")) {
|
|
502
492
|
const outgoing = {};
|
|
503
493
|
for (const [key, value] of Object.entries(headers)) {
|
|
@@ -514,8 +504,6 @@ async function proxyWorkspaceRequest(args) {
|
|
|
514
504
|
workspaceId,
|
|
515
505
|
method: request.method,
|
|
516
506
|
targetUrl,
|
|
517
|
-
worktreeSlug,
|
|
518
|
-
directory,
|
|
519
507
|
contentType: request.headers["content-type"],
|
|
520
508
|
body: bodyToJson(request.body),
|
|
521
509
|
headers: outgoing,
|
|
@@ -531,76 +519,6 @@ async function proxyWorkspaceRequest(args) {
|
|
|
531
519
|
},
|
|
532
520
|
});
|
|
533
521
|
}
|
|
534
|
-
function extractOpencodeDirectoryOverride(pathSuffix) {
|
|
535
|
-
if (!pathSuffix) {
|
|
536
|
-
return { overrideDirectory: null, forwardedSuffix: pathSuffix };
|
|
537
|
-
}
|
|
538
|
-
// Fastify wildcard param does not include a leading slash.
|
|
539
|
-
const trimmed = pathSuffix.replace(/^\/+/, "");
|
|
540
|
-
if (!trimmed.startsWith(OPENCODE_DIR_OVERRIDE_PREFIX)) {
|
|
541
|
-
return { overrideDirectory: null, forwardedSuffix: pathSuffix };
|
|
542
|
-
}
|
|
543
|
-
const rest = trimmed.slice(OPENCODE_DIR_OVERRIDE_PREFIX.length);
|
|
544
|
-
const slashIndex = rest.indexOf("/");
|
|
545
|
-
const encoded = (slashIndex >= 0 ? rest.slice(0, slashIndex) : rest).trim();
|
|
546
|
-
const remaining = slashIndex >= 0 ? rest.slice(slashIndex + 1) : "";
|
|
547
|
-
if (!encoded) {
|
|
548
|
-
throw new Error("Missing directory override");
|
|
549
|
-
}
|
|
550
|
-
if (encoded.length > OPENCODE_DIR_OVERRIDE_MAX_LEN) {
|
|
551
|
-
throw new Error("Directory override too large");
|
|
552
|
-
}
|
|
553
|
-
let overrideDirectory = "";
|
|
554
|
-
try {
|
|
555
|
-
overrideDirectory = decodeBase64Url(encoded);
|
|
556
|
-
}
|
|
557
|
-
catch {
|
|
558
|
-
throw new Error("Invalid directory override");
|
|
559
|
-
}
|
|
560
|
-
const forwardedSuffix = remaining;
|
|
561
|
-
return { overrideDirectory, forwardedSuffix };
|
|
562
|
-
}
|
|
563
|
-
function decodeBase64Url(input) {
|
|
564
|
-
// base64url -> base64
|
|
565
|
-
const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
566
|
-
const padding = normalized.length % 4 === 0 ? "" : "=".repeat(4 - (normalized.length % 4));
|
|
567
|
-
const base64 = `${normalized}${padding}`;
|
|
568
|
-
return Buffer.from(base64, "base64").toString("utf-8");
|
|
569
|
-
}
|
|
570
|
-
function validateAndNormalizeOverrideDirectory(params) {
|
|
571
|
-
const raw = params.overrideDirectory.trim();
|
|
572
|
-
if (!raw) {
|
|
573
|
-
throw new Error("Override directory is empty");
|
|
574
|
-
}
|
|
575
|
-
if (!path.isAbsolute(raw)) {
|
|
576
|
-
throw new Error("Override directory must be an absolute path");
|
|
577
|
-
}
|
|
578
|
-
if (!fs.existsSync(raw)) {
|
|
579
|
-
throw new Error(`Override directory does not exist: ${raw}`);
|
|
580
|
-
}
|
|
581
|
-
const stats = fs.statSync(raw);
|
|
582
|
-
if (!stats.isDirectory()) {
|
|
583
|
-
throw new Error(`Override path is not a directory: ${raw}`);
|
|
584
|
-
}
|
|
585
|
-
const normalizedOverride = fs.realpathSync(raw);
|
|
586
|
-
const normalizedRoot = fs.realpathSync(params.workspaceRoot);
|
|
587
|
-
if (!isSubpath(normalizedOverride, normalizedRoot)) {
|
|
588
|
-
throw new Error("Override directory must be within the workspace root");
|
|
589
|
-
}
|
|
590
|
-
return normalizedOverride;
|
|
591
|
-
}
|
|
592
|
-
function isSubpath(candidate, root) {
|
|
593
|
-
const rel = path.relative(root, candidate);
|
|
594
|
-
if (rel === "")
|
|
595
|
-
return true;
|
|
596
|
-
if (rel === "..")
|
|
597
|
-
return false;
|
|
598
|
-
if (rel.startsWith(`..${path.sep}`))
|
|
599
|
-
return false;
|
|
600
|
-
if (path.isAbsolute(rel))
|
|
601
|
-
return false;
|
|
602
|
-
return true;
|
|
603
|
-
}
|
|
604
522
|
function normalizeInstanceSuffix(pathSuffix) {
|
|
605
523
|
if (!pathSuffix || pathSuffix === "/") {
|
|
606
524
|
return "/";
|
|
@@ -608,7 +526,7 @@ function normalizeInstanceSuffix(pathSuffix) {
|
|
|
608
526
|
const trimmed = pathSuffix.replace(/^\/+/, "");
|
|
609
527
|
return trimmed.length === 0 ? "/" : `/${trimmed}`;
|
|
610
528
|
}
|
|
611
|
-
function setupStaticUi(app, uiDir, authManager) {
|
|
529
|
+
function setupStaticUi(app, uiDir, authManager, previewManager, logger) {
|
|
612
530
|
if (!uiDir) {
|
|
613
531
|
app.log.warn("UI static directory not provided; API endpoints only");
|
|
614
532
|
return;
|
|
@@ -617,6 +535,13 @@ function setupStaticUi(app, uiDir, authManager) {
|
|
|
617
535
|
app.log.warn({ uiDir }, "UI static directory missing; API endpoints only");
|
|
618
536
|
return;
|
|
619
537
|
}
|
|
538
|
+
app.addHook("preHandler", (request, reply, done) => {
|
|
539
|
+
const session = authManager.getSessionFromRequest(request);
|
|
540
|
+
if (session && proxyPreviewFallbackFromReferer(request, reply, previewManager, logger)) {
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
done();
|
|
544
|
+
});
|
|
620
545
|
app.register(fastifyStatic, {
|
|
621
546
|
root: uiDir,
|
|
622
547
|
prefix: "/",
|
|
@@ -630,6 +555,9 @@ function setupStaticUi(app, uiDir, authManager) {
|
|
|
630
555
|
return;
|
|
631
556
|
}
|
|
632
557
|
const session = authManager.getSessionFromRequest(request);
|
|
558
|
+
if (session && proxyPreviewFallbackFromReferer(request, reply, previewManager, logger)) {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
633
561
|
if (!session && wantsHtml(request)) {
|
|
634
562
|
reply.redirect("/login");
|
|
635
563
|
return;
|
|
@@ -642,7 +570,7 @@ function setupStaticUi(app, uiDir, authManager) {
|
|
|
642
570
|
}
|
|
643
571
|
});
|
|
644
572
|
}
|
|
645
|
-
function setupDevProxy(app, upstreamBase, authManager) {
|
|
573
|
+
function setupDevProxy(app, upstreamBase, authManager, previewManager, logger) {
|
|
646
574
|
app.log.info({ upstreamBase }, "Proxying UI requests to development server");
|
|
647
575
|
app.setNotFoundHandler((request, reply) => {
|
|
648
576
|
const url = request.raw.url ?? "";
|
|
@@ -651,6 +579,9 @@ function setupDevProxy(app, upstreamBase, authManager) {
|
|
|
651
579
|
return;
|
|
652
580
|
}
|
|
653
581
|
const session = authManager.getSessionFromRequest(request);
|
|
582
|
+
if (session && proxyPreviewFallbackFromReferer(request, reply, previewManager, logger)) {
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
654
585
|
if (!session && wantsHtml(request)) {
|
|
655
586
|
reply.redirect("/login");
|
|
656
587
|
return;
|
|
@@ -658,6 +589,45 @@ function setupDevProxy(app, upstreamBase, authManager) {
|
|
|
658
589
|
void proxyToDevServer(request, reply, upstreamBase);
|
|
659
590
|
});
|
|
660
591
|
}
|
|
592
|
+
function proxyPreviewFallbackFromReferer(request, reply, previewManager, logger) {
|
|
593
|
+
const rawUrl = request.raw.url ?? request.url ?? "";
|
|
594
|
+
const pathname = rawUrl.split("?")[0] ?? "";
|
|
595
|
+
if (!isPreviewFallbackPath(pathname)) {
|
|
596
|
+
return false;
|
|
597
|
+
}
|
|
598
|
+
const refererHeader = request.headers.referer ?? request.headers.referrer;
|
|
599
|
+
const referer = Array.isArray(refererHeader) ? refererHeader[0] : refererHeader;
|
|
600
|
+
if (!referer) {
|
|
601
|
+
return false;
|
|
602
|
+
}
|
|
603
|
+
const parsed = parsePreviewUpgradePath(referer);
|
|
604
|
+
if (!parsed) {
|
|
605
|
+
return false;
|
|
606
|
+
}
|
|
607
|
+
void proxyPreviewAssetRequest({
|
|
608
|
+
request,
|
|
609
|
+
reply,
|
|
610
|
+
previewManager,
|
|
611
|
+
logger,
|
|
612
|
+
token: parsed.token,
|
|
613
|
+
});
|
|
614
|
+
return true;
|
|
615
|
+
}
|
|
616
|
+
function isPreviewFallbackPath(pathname) {
|
|
617
|
+
if (!pathname || pathname === "/")
|
|
618
|
+
return false;
|
|
619
|
+
if (pathname.startsWith("/api/") || pathname === "/api")
|
|
620
|
+
return false;
|
|
621
|
+
if (pathname.startsWith("/workspaces/"))
|
|
622
|
+
return false;
|
|
623
|
+
if (pathname.startsWith("/sidecars/"))
|
|
624
|
+
return false;
|
|
625
|
+
if (pathname.startsWith("/previews/"))
|
|
626
|
+
return false;
|
|
627
|
+
if (pathname.startsWith("/auth/") || pathname === "/login")
|
|
628
|
+
return false;
|
|
629
|
+
return true;
|
|
630
|
+
}
|
|
661
631
|
async function proxyToDevServer(request, reply, upstreamBase) {
|
|
662
632
|
try {
|
|
663
633
|
const targetUrl = new URL(request.raw.url ?? "/", upstreamBase);
|
|
@@ -698,6 +668,69 @@ function buildProxyHeaders(headers) {
|
|
|
698
668
|
}
|
|
699
669
|
return result;
|
|
700
670
|
}
|
|
671
|
+
function buildFetchProxyHeaders(headers, targetOrigin) {
|
|
672
|
+
const sanitized = sanitizeSideCarProxyRequestHeaders(headers, targetOrigin);
|
|
673
|
+
const result = {};
|
|
674
|
+
for (const [key, value] of Object.entries(sanitized)) {
|
|
675
|
+
if (!value)
|
|
676
|
+
continue;
|
|
677
|
+
if (key.toLowerCase() === "cookie")
|
|
678
|
+
continue;
|
|
679
|
+
result[key] = Array.isArray(value) ? value.join(",") : value;
|
|
680
|
+
}
|
|
681
|
+
return result;
|
|
682
|
+
}
|
|
683
|
+
function headersToRecord(headers) {
|
|
684
|
+
const result = {};
|
|
685
|
+
headers.forEach((value, key) => {
|
|
686
|
+
result[key.toLowerCase()] = value;
|
|
687
|
+
});
|
|
688
|
+
return result;
|
|
689
|
+
}
|
|
690
|
+
function getHeaderValue(headers, key) {
|
|
691
|
+
const value = headers[key.toLowerCase()];
|
|
692
|
+
return Array.isArray(value) ? value[0] : value;
|
|
693
|
+
}
|
|
694
|
+
function shouldForwardRequestBody(method) {
|
|
695
|
+
const normalized = method.toUpperCase();
|
|
696
|
+
return normalized !== "GET" && normalized !== "HEAD";
|
|
697
|
+
}
|
|
698
|
+
function isHtmlContentType(contentType) {
|
|
699
|
+
const normalized = contentType.toLowerCase();
|
|
700
|
+
return normalized.includes("text/html") || normalized.includes("application/xhtml+xml");
|
|
701
|
+
}
|
|
702
|
+
function isCssContentType(contentType) {
|
|
703
|
+
return contentType.toLowerCase().includes("text/css");
|
|
704
|
+
}
|
|
705
|
+
function rewritePreviewBodyUrls(body, publicBase, kind) {
|
|
706
|
+
if (kind === "css") {
|
|
707
|
+
return rewriteCssPreviewUrls(body, publicBase);
|
|
708
|
+
}
|
|
709
|
+
return rewriteCssPreviewUrls(body
|
|
710
|
+
.replace(/\b(src|href|action|poster|data)=(["'])\/(?!\/)([^"']*)\2/gi, (_match, attr, quote, pathValue) => {
|
|
711
|
+
return `${attr}=${quote}${publicBase}/${pathValue}${quote}`;
|
|
712
|
+
})
|
|
713
|
+
.replace(/\bsrcset=(["'])([^"']*)\1/gi, (_match, quote, value) => {
|
|
714
|
+
return `srcset=${quote}${rewriteSrcsetPreviewUrls(value, publicBase)}${quote}`;
|
|
715
|
+
}), publicBase);
|
|
716
|
+
}
|
|
717
|
+
function rewriteCssPreviewUrls(body, publicBase) {
|
|
718
|
+
return body.replace(/url\((\s*)(["']?)\/(?!\/)([^"')]+)\2(\s*)\)/gi, (_match, before, quote, pathValue, after) => {
|
|
719
|
+
return `url(${before}${quote}${publicBase}/${pathValue}${quote}${after})`;
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
function rewriteSrcsetPreviewUrls(value, publicBase) {
|
|
723
|
+
return value
|
|
724
|
+
.split(",")
|
|
725
|
+
.map((entry) => {
|
|
726
|
+
const trimmed = entry.trimStart();
|
|
727
|
+
if (!trimmed.startsWith("/") || trimmed.startsWith("//"))
|
|
728
|
+
return entry;
|
|
729
|
+
const leading = entry.slice(0, entry.length - trimmed.length);
|
|
730
|
+
return `${leading}${publicBase}${trimmed}`;
|
|
731
|
+
})
|
|
732
|
+
.join(",");
|
|
733
|
+
}
|
|
701
734
|
async function proxySideCarRequest(args) {
|
|
702
735
|
const sidecarId = args.request.params.id ?? "";
|
|
703
736
|
const sidecar = await args.sidecarManager.get(sidecarId);
|
|
@@ -714,13 +747,113 @@ async function proxySideCarRequest(args) {
|
|
|
714
747
|
const targetOrigin = args.sidecarManager.buildTargetOrigin(sidecar);
|
|
715
748
|
const targetUrl = `${targetOrigin}${targetPath}`;
|
|
716
749
|
args.logger.debug({ sidecarId: sidecar.id, targetUrl, pathname, prefixMode: sidecar.prefixMode }, "Proxying request to SideCar");
|
|
717
|
-
await
|
|
718
|
-
|
|
750
|
+
await proxyTargetRequest({
|
|
751
|
+
reply: args.reply,
|
|
752
|
+
logger: args.logger,
|
|
753
|
+
targetUrl,
|
|
754
|
+
targetOrigin,
|
|
755
|
+
logContext: { sidecarId: sidecar.id },
|
|
756
|
+
errorMessage: "SideCar proxy failed",
|
|
719
757
|
rewriteHeaders: (headers) => rewriteSideCarResponseHeaders(headers, sidecarId, targetOrigin, sidecar.prefixMode),
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
async function proxyPreviewRequest(args) {
|
|
761
|
+
const token = args.request.params.token ?? "";
|
|
762
|
+
const preview = args.previewManager.get(token);
|
|
763
|
+
if (!preview) {
|
|
764
|
+
args.reply.code(404).send({ error: "Preview not found" });
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const rawUrl = args.request.raw.url ?? args.request.url ?? "";
|
|
768
|
+
const queryIndex = rawUrl.indexOf("?");
|
|
769
|
+
const search = queryIndex >= 0 ? rawUrl.slice(queryIndex) : "";
|
|
770
|
+
const pathSuffix = args.pathSuffix ?? "";
|
|
771
|
+
const requestPath = pathSuffix ? `${args.previewManager.buildProxyBasePath(token)}/${pathSuffix.replace(/^\/+/, "")}` : args.previewManager.buildProxyBasePath(token);
|
|
772
|
+
const targetUrl = args.previewManager.buildTargetUrl(token, requestPath, search);
|
|
773
|
+
if (!targetUrl) {
|
|
774
|
+
args.reply.code(404).send({ error: "Preview not found" });
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
args.logger.debug({ previewToken: token, targetUrl: targetUrl.toString() }, "Proxying request to preview");
|
|
778
|
+
await proxyPreviewTargetRequest({
|
|
779
|
+
request: args.request,
|
|
780
|
+
reply: args.reply,
|
|
781
|
+
logger: args.logger,
|
|
782
|
+
targetUrl: targetUrl.toString(),
|
|
783
|
+
targetOrigin: targetUrl.origin,
|
|
784
|
+
publicBase: args.previewManager.buildProxyBasePath(token),
|
|
785
|
+
logContext: { previewToken: token },
|
|
786
|
+
errorMessage: "Preview proxy failed",
|
|
787
|
+
rewriteHeaders: (headers) => rewritePreviewResponseHeaders(headers, token, targetUrl.origin),
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
async function proxyPreviewAssetRequest(args) {
|
|
791
|
+
const rawUrl = args.request.raw.url ?? args.request.url ?? "";
|
|
792
|
+
const queryIndex = rawUrl.indexOf("?");
|
|
793
|
+
const search = queryIndex >= 0 ? rawUrl.slice(queryIndex) : "";
|
|
794
|
+
const pathname = rawUrl.split("?")[0] ?? "/";
|
|
795
|
+
const targetUrl = args.previewManager.buildTargetUrl(args.token, pathname, search);
|
|
796
|
+
if (!targetUrl) {
|
|
797
|
+
args.reply.code(404).send({ error: "Preview not found" });
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
args.logger.debug({ previewToken: args.token, targetUrl: targetUrl.toString() }, "Proxying preview fallback asset");
|
|
801
|
+
await proxyPreviewTargetRequest({
|
|
802
|
+
request: args.request,
|
|
803
|
+
reply: args.reply,
|
|
804
|
+
logger: args.logger,
|
|
805
|
+
targetUrl: targetUrl.toString(),
|
|
806
|
+
targetOrigin: targetUrl.origin,
|
|
807
|
+
publicBase: args.previewManager.buildProxyBasePath(args.token),
|
|
808
|
+
logContext: { previewToken: args.token, previewFallback: true },
|
|
809
|
+
errorMessage: "Preview proxy failed",
|
|
810
|
+
rewriteHeaders: (headers) => rewritePreviewResponseHeaders(headers, args.token, targetUrl.origin),
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
async function proxyPreviewTargetRequest(args) {
|
|
814
|
+
try {
|
|
815
|
+
const response = await fetch(args.targetUrl, {
|
|
816
|
+
method: args.request.method,
|
|
817
|
+
headers: buildFetchProxyHeaders(args.request.headers, args.targetOrigin),
|
|
818
|
+
body: shouldForwardRequestBody(args.request.method) ? args.request.raw : undefined,
|
|
819
|
+
duplex: shouldForwardRequestBody(args.request.method) ? "half" : undefined,
|
|
820
|
+
redirect: "manual",
|
|
821
|
+
});
|
|
822
|
+
const headers = args.rewriteHeaders(headersToRecord(response.headers));
|
|
823
|
+
const contentType = getHeaderValue(headers, "content-type") ?? response.headers.get("content-type") ?? "";
|
|
824
|
+
delete headers["content-length"];
|
|
825
|
+
delete headers["content-encoding"];
|
|
826
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
827
|
+
if (value !== undefined)
|
|
828
|
+
args.reply.header(key, value);
|
|
829
|
+
}
|
|
830
|
+
args.reply.code(response.status);
|
|
831
|
+
if (!response.body || args.request.method === "HEAD") {
|
|
832
|
+
args.reply.send();
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
if (isHtmlContentType(contentType) || isCssContentType(contentType)) {
|
|
836
|
+
const text = await response.text();
|
|
837
|
+
args.reply.send(rewritePreviewBodyUrls(text, args.publicBase, isCssContentType(contentType) ? "css" : "html"));
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
args.reply.send(Buffer.from(await response.arrayBuffer()));
|
|
841
|
+
}
|
|
842
|
+
catch (error) {
|
|
843
|
+
args.logger.error({ ...args.logContext, err: error, targetUrl: args.targetUrl }, args.errorMessage);
|
|
844
|
+
if (!args.reply.sent) {
|
|
845
|
+
args.reply.code(502).send({ error: args.errorMessage });
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
async function proxyTargetRequest(args) {
|
|
850
|
+
await args.reply.from(args.targetUrl, {
|
|
851
|
+
rewriteRequestHeaders: (_originalRequest, headers) => sanitizeSideCarProxyRequestHeaders(headers, args.targetOrigin),
|
|
852
|
+
rewriteHeaders: args.rewriteHeaders,
|
|
720
853
|
onError: (reply, { error }) => {
|
|
721
|
-
args.logger.error({
|
|
854
|
+
args.logger.error({ ...args.logContext, err: error, targetUrl: args.targetUrl }, args.errorMessage);
|
|
722
855
|
if (!reply.sent) {
|
|
723
|
-
reply.code(502).send({ error:
|
|
856
|
+
reply.code(502).send({ error: args.errorMessage });
|
|
724
857
|
}
|
|
725
858
|
},
|
|
726
859
|
});
|
|
@@ -748,6 +881,29 @@ function parseSideCarUpgradePath(rawUrl) {
|
|
|
748
881
|
return null;
|
|
749
882
|
}
|
|
750
883
|
}
|
|
884
|
+
function parsePreviewUpgradePath(rawUrl) {
|
|
885
|
+
let parsed;
|
|
886
|
+
try {
|
|
887
|
+
parsed = new URL(rawUrl, "http://localhost");
|
|
888
|
+
}
|
|
889
|
+
catch {
|
|
890
|
+
return null;
|
|
891
|
+
}
|
|
892
|
+
const match = parsed.pathname.match(/^\/previews\/([^/]+)(?:\/.*)?$/);
|
|
893
|
+
if (!match) {
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
try {
|
|
897
|
+
return {
|
|
898
|
+
token: decodeURIComponent(match[1] ?? ""),
|
|
899
|
+
pathname: parsed.pathname,
|
|
900
|
+
search: parsed.search,
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
catch {
|
|
904
|
+
return null;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
751
907
|
async function proxySideCarWebSocketUpgrade(args) {
|
|
752
908
|
const { request, socket, head, sidecarId, incomingPath, search, sidecarManager, authManager, logger } = args;
|
|
753
909
|
if (!isWebSocketUpgradeRequest(request)) {
|
|
@@ -768,6 +924,46 @@ async function proxySideCarWebSocketUpgrade(args) {
|
|
|
768
924
|
const targetPath = sidecarManager.buildTargetPath(sidecarId, incomingPath, search);
|
|
769
925
|
const targetUrl = new URL(`${targetOrigin}${targetPath}`);
|
|
770
926
|
logger.debug({ sidecarId, targetUrl: targetUrl.toString(), prefixMode: sidecar.prefixMode }, "Proxying websocket to SideCar");
|
|
927
|
+
proxyTargetWebSocketUpgrade({
|
|
928
|
+
request,
|
|
929
|
+
socket,
|
|
930
|
+
head,
|
|
931
|
+
targetUrl,
|
|
932
|
+
logger,
|
|
933
|
+
logContext: { sidecarId },
|
|
934
|
+
proxyLabel: "SideCar",
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
async function proxyPreviewWebSocketUpgrade(args) {
|
|
938
|
+
const { request, socket, head, token, incomingPath, search, previewManager, authManager, logger } = args;
|
|
939
|
+
if (!isWebSocketUpgradeRequest(request)) {
|
|
940
|
+
rejectUpgrade(socket, 400, "Bad Request");
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const session = authManager.getSessionFromHeaders(request.headers);
|
|
944
|
+
if (!session) {
|
|
945
|
+
rejectUpgrade(socket, 401, "Unauthorized");
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
const targetUrl = previewManager.buildTargetUrl(token, incomingPath, search);
|
|
949
|
+
if (!targetUrl) {
|
|
950
|
+
rejectUpgrade(socket, 404, "Not Found");
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
logger.debug({ previewToken: token, targetUrl: targetUrl.toString() }, "Proxying websocket to preview");
|
|
954
|
+
proxyTargetWebSocketUpgrade({
|
|
955
|
+
request,
|
|
956
|
+
socket,
|
|
957
|
+
head,
|
|
958
|
+
targetUrl,
|
|
959
|
+
logger,
|
|
960
|
+
logContext: { previewToken: token },
|
|
961
|
+
proxyLabel: "preview",
|
|
962
|
+
stripCookies: true,
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
function proxyTargetWebSocketUpgrade(args) {
|
|
966
|
+
const { request, socket, head, targetUrl, logger, logContext, proxyLabel, stripCookies } = args;
|
|
771
967
|
const { socket: upstream, readyEvent } = createSideCarUpstreamSocket(targetUrl);
|
|
772
968
|
const closeBoth = () => {
|
|
773
969
|
if (!socket.destroyed) {
|
|
@@ -778,21 +974,21 @@ async function proxySideCarWebSocketUpgrade(args) {
|
|
|
778
974
|
}
|
|
779
975
|
};
|
|
780
976
|
upstream.once("error", (error) => {
|
|
781
|
-
logger.error({
|
|
977
|
+
logger.error({ ...logContext, err: error, targetUrl: targetUrl.toString() }, `Failed to proxy ${proxyLabel} websocket`);
|
|
782
978
|
rejectUpgrade(socket, 502, "Bad Gateway");
|
|
783
979
|
if (!upstream.destroyed) {
|
|
784
980
|
upstream.destroy();
|
|
785
981
|
}
|
|
786
982
|
});
|
|
787
983
|
socket.once("error", (error) => {
|
|
788
|
-
logger.debug({
|
|
984
|
+
logger.debug({ ...logContext, err: error }, `${proxyLabel} websocket client socket errored`);
|
|
789
985
|
if (!upstream.destroyed) {
|
|
790
986
|
upstream.destroy();
|
|
791
987
|
}
|
|
792
988
|
});
|
|
793
989
|
upstream.once(readyEvent, () => {
|
|
794
990
|
try {
|
|
795
|
-
upstream.write(buildSideCarWebSocketRequest(request, targetUrl));
|
|
991
|
+
upstream.write(buildSideCarWebSocketRequest(request, targetUrl, { stripCookies }));
|
|
796
992
|
if (head.length > 0) {
|
|
797
993
|
upstream.write(head);
|
|
798
994
|
}
|
|
@@ -800,7 +996,7 @@ async function proxySideCarWebSocketUpgrade(args) {
|
|
|
800
996
|
socket.pipe(upstream);
|
|
801
997
|
}
|
|
802
998
|
catch (error) {
|
|
803
|
-
logger.error({
|
|
999
|
+
logger.error({ ...logContext, err: error, targetUrl: targetUrl.toString() }, `Failed to forward ${proxyLabel} websocket upgrade`);
|
|
804
1000
|
closeBoth();
|
|
805
1001
|
}
|
|
806
1002
|
});
|
|
@@ -832,7 +1028,7 @@ function createSideCarUpstreamSocket(targetUrl) {
|
|
|
832
1028
|
readyEvent: "connect",
|
|
833
1029
|
};
|
|
834
1030
|
}
|
|
835
|
-
function buildSideCarWebSocketRequest(request, targetUrl) {
|
|
1031
|
+
function buildSideCarWebSocketRequest(request, targetUrl, options) {
|
|
836
1032
|
const pathWithQuery = `${targetUrl.pathname}${targetUrl.search}`;
|
|
837
1033
|
const requestLine = `${request.method ?? "GET"} ${pathWithQuery} HTTP/${request.httpVersion}\r\n`;
|
|
838
1034
|
const headerLines = [];
|
|
@@ -846,6 +1042,8 @@ function buildSideCarWebSocketRequest(request, targetUrl) {
|
|
|
846
1042
|
const lower = key.toLowerCase();
|
|
847
1043
|
if (blockedHeaders.has(lower))
|
|
848
1044
|
continue;
|
|
1045
|
+
if (options?.stripCookies && lower === "cookie")
|
|
1046
|
+
continue;
|
|
849
1047
|
if (lower === "origin") {
|
|
850
1048
|
headerLines.push(`Origin: ${targetUrl.origin}\r\n`);
|
|
851
1049
|
continue;
|
|
@@ -899,6 +1097,34 @@ function rewriteSideCarResponseHeaders(headers, sidecarId, targetOrigin, prefixM
|
|
|
899
1097
|
}
|
|
900
1098
|
return next;
|
|
901
1099
|
}
|
|
1100
|
+
function rewritePreviewResponseHeaders(headers, token, targetOrigin) {
|
|
1101
|
+
const next = { ...headers };
|
|
1102
|
+
delete next["x-frame-options"];
|
|
1103
|
+
delete next["content-security-policy"];
|
|
1104
|
+
delete next["content-security-policy-report-only"];
|
|
1105
|
+
delete next["set-cookie"];
|
|
1106
|
+
delete next["set-cookie2"];
|
|
1107
|
+
const locationHeader = next.location;
|
|
1108
|
+
const location = Array.isArray(locationHeader) ? locationHeader[0] : locationHeader;
|
|
1109
|
+
if (!location) {
|
|
1110
|
+
return next;
|
|
1111
|
+
}
|
|
1112
|
+
const publicBase = `/previews/${encodeURIComponent(token)}`;
|
|
1113
|
+
if (location.startsWith("/")) {
|
|
1114
|
+
next.location = `${publicBase}${location}`;
|
|
1115
|
+
return next;
|
|
1116
|
+
}
|
|
1117
|
+
try {
|
|
1118
|
+
const parsed = new URL(location);
|
|
1119
|
+
if (parsed.origin === targetOrigin) {
|
|
1120
|
+
next.location = `${publicBase}${parsed.pathname}${parsed.search}${parsed.hash}`;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
catch {
|
|
1124
|
+
// Relative redirects should continue to resolve against the current preview path.
|
|
1125
|
+
}
|
|
1126
|
+
return next;
|
|
1127
|
+
}
|
|
902
1128
|
function sanitizeSideCarProxyRequestHeaders(headers, targetOrigin) {
|
|
903
1129
|
const blockedHeaders = getBlockedSideCarRequestHeaders();
|
|
904
1130
|
const next = {};
|