@neuralnomads/codenomad 0.14.0 → 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.
- package/dist/cli-upgrade.js +53 -0
- package/dist/cli-upgrade.test.js +31 -0
- package/dist/filesystem/browser.js +15 -1
- package/dist/index.js +23 -6
- package/dist/opencode-config/package-lock.json +380 -0
- package/dist/opencode-config/package.json +2 -2
- package/dist/server/__tests__/remote-proxy.test.js +204 -0
- package/dist/server/http-server.js +8 -32
- package/dist/server/remote-proxy.js +466 -0
- package/dist/server/routes/remote-proxy.js +42 -0
- package/dist/server/routes/settings.js +1 -1
- package/dist/server/routes/workspaces.js +118 -0
- package/dist/workspaces/__tests__/git-worktrees.test.js +43 -0
- package/dist/workspaces/__tests__/spawn.test.js +140 -0
- package/dist/workspaces/git-mutations.js +98 -0
- package/dist/workspaces/git-status.js +323 -0
- package/dist/workspaces/git-worktrees.js +18 -1
- package/dist/workspaces/manager.js +9 -4
- package/dist/workspaces/opencode-auth.js +18 -0
- package/dist/workspaces/opencode-auth.test.js +34 -0
- package/dist/workspaces/runtime.js +54 -77
- package/dist/workspaces/spawn.js +219 -0
- package/dist/workspaces/worktree-directory.js +74 -0
- package/package.json +1 -1
- package/public/assets/ChangesTab-ovdqLHc3.js +2 -0
- package/public/assets/DiffToolbar-B12EfXMX.js +1 -0
- package/public/assets/FilesTab-nb_itEXG.js +2 -0
- package/public/assets/GitChangesTab-DcT_4BL2.js +2 -0
- package/public/assets/{SplitFilePanel-CupweEA5.js → SplitFilePanel-BOHH3F--.js} +1 -1
- package/public/assets/StatusTab-Dyt_EG33.js +1 -0
- package/public/assets/align-justify-9zpyaAdy.js +1 -0
- package/public/assets/{bundle-full-B-5u6Iv3.js → bundle-full-xFW13Lny.js} +1 -1
- package/public/assets/{diff-viewer-_ehhYA-Z.js → diff-viewer-xG9yjpN8.js} +1 -1
- package/public/assets/index-7DpT014-.js +1 -0
- package/public/assets/index-BDK4V9L0.js +1 -0
- package/public/assets/index-Bx-Bezt2.js +1 -0
- package/public/assets/{index-BqiNjV6R.js → index-CCAZZY0l.js} +1 -1
- package/public/assets/{index-BntAaLZs.js → index-CEcZq5WB.js} +1 -1
- package/public/assets/index-CQCmSDHL.js +1 -0
- package/public/assets/{index-CxQr-wOF.js → index-Cz_fl8aY.js} +1 -1
- package/public/assets/index-Dcgftm1m.css +1 -0
- package/public/assets/index-m4C3yx3J.js +1 -0
- package/public/assets/index-mh_z9p40.js +2 -0
- package/public/assets/{loading-Dck2H3XH.js → loading-HUhLEgb_.js} +1 -1
- package/public/assets/main-CKhfaeKI.js +48 -0
- package/public/assets/{markdown-CFV9kR80.js → markdown-BeXU9Z-x.js} +22 -22
- package/public/assets/monaco-viewer-BgP6xpZ6.js +26 -0
- package/public/assets/{todo-Ghwirj-b.js → todo-D6PVVp_f.js} +1 -1
- package/public/assets/tool-call-Dgn3NlA8.js +60 -0
- package/public/assets/{unified-picker-Dw0kTXoT.js → unified-picker-DuNuUpLy.js} +1 -1
- package/public/assets/wrap-text-zghCl6wN.js +1 -0
- 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/public/assets/ChangesTab-CFkk3tAp.js +0 -2
- package/public/assets/DiffToolbar-CQQLR1mp.js +0 -1
- package/public/assets/FilesTab-CXgucPtN.js +0 -2
- package/public/assets/GitChangesTab-BidSb28_.js +0 -2
- package/public/assets/StatusTab-C2Pl_Vce.js +0 -1
- package/public/assets/index-BnfDkr8C.js +0 -1
- package/public/assets/index-BwCEJ4BE.css +0 -1
- package/public/assets/index-DXaitXVC.js +0 -1
- package/public/assets/index-DzRzoTK8.js +0 -2
- package/public/assets/index-ShHad48G.js +0 -1
- package/public/assets/index-_EaXFUIj.js +0 -1
- package/public/assets/index-mMh5TJvW.js +0 -1
- package/public/assets/main-BsIf5lOY.js +0 -50
- package/public/assets/monaco-viewer-CMM6n0T3.js +0 -25
- package/public/assets/tool-call-BC2Pv3uG.js +0 -60
- package/public/assets/wrap-text-D2MJk2ad.js +0 -1
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
import Fastify from "fastify";
|
|
2
|
+
import { randomBytes, randomUUID } from "crypto";
|
|
3
|
+
import { Readable } from "stream";
|
|
4
|
+
import { pipeline } from "stream/promises";
|
|
5
|
+
import { Agent, fetch } from "undici";
|
|
6
|
+
const LOOPBACK_HOST = "127.0.0.1";
|
|
7
|
+
const BOOTSTRAP_PAGE_PATH = "/__codenomad/auth/token";
|
|
8
|
+
const BOOTSTRAP_EXCHANGE_PATH = "/__codenomad/api/auth/token";
|
|
9
|
+
const SESSION_IDLE_TTL_MS = 30 * 60000;
|
|
10
|
+
export class RemoteProxySessionManager {
|
|
11
|
+
constructor(options) {
|
|
12
|
+
this.options = options;
|
|
13
|
+
this.sessions = new Map();
|
|
14
|
+
this.cleanupTimer = setInterval(() => {
|
|
15
|
+
void this.cleanupExpiredSessions();
|
|
16
|
+
}, 60000);
|
|
17
|
+
this.cleanupTimer.unref();
|
|
18
|
+
}
|
|
19
|
+
async createSession(baseUrl, skipTlsVerify) {
|
|
20
|
+
if (!this.options.httpsOptions) {
|
|
21
|
+
throw new Error("Local HTTPS is required for remote proxy sessions");
|
|
22
|
+
}
|
|
23
|
+
const targetBaseUrl = normalizeBaseUrl(baseUrl);
|
|
24
|
+
const sessionId = randomUUID();
|
|
25
|
+
const bootstrapToken = randomBytes(32).toString("base64url");
|
|
26
|
+
const dispatcher = skipTlsVerify ? new Agent({ connect: { rejectUnauthorized: false } }) : undefined;
|
|
27
|
+
const app = Fastify({ logger: false, https: this.options.httpsOptions });
|
|
28
|
+
let session = null;
|
|
29
|
+
app.removeAllContentTypeParsers();
|
|
30
|
+
// Preserve raw request bodies for proxying while still letting token JSON parse from Buffer.
|
|
31
|
+
app.addContentTypeParser("*", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
|
|
32
|
+
app.get(BOOTSTRAP_PAGE_PATH, async (request, reply) => {
|
|
33
|
+
if (!this.options.authManager.isLoopbackRequest(request)) {
|
|
34
|
+
reply.code(404).send({ error: "Not found" });
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
reply.header("Cache-Control", "no-store");
|
|
38
|
+
reply.header("Pragma", "no-cache");
|
|
39
|
+
reply.header("Expires", "0");
|
|
40
|
+
reply.type("text/html").send(buildBootstrapPageHtml());
|
|
41
|
+
});
|
|
42
|
+
app.post(BOOTSTRAP_EXCHANGE_PATH, async (request, reply) => {
|
|
43
|
+
if (!this.options.authManager.isLoopbackRequest(request)) {
|
|
44
|
+
reply.code(404).send({ error: "Not found" });
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (!session) {
|
|
48
|
+
reply.code(503).send({ error: "Remote proxy session is unavailable" });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const body = parseTokenBody(request.body);
|
|
52
|
+
if (body.token !== session.bootstrapToken) {
|
|
53
|
+
reply.code(401).send({ error: "Invalid token" });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
session.activated = true;
|
|
57
|
+
session.lastAccessAt = Date.now();
|
|
58
|
+
reply.send({ ok: true });
|
|
59
|
+
});
|
|
60
|
+
app.all("/*", async (request, reply) => {
|
|
61
|
+
if (!session) {
|
|
62
|
+
reply.code(503).send({ error: "Remote proxy session is unavailable" });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (!session.activated) {
|
|
66
|
+
reply.code(403).send({ error: "Remote proxy session is not activated" });
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
session.lastAccessAt = Date.now();
|
|
70
|
+
await proxyRequest({ request, reply, session, logger: this.options.logger });
|
|
71
|
+
});
|
|
72
|
+
app.setNotFoundHandler(async (request, reply) => {
|
|
73
|
+
if (!session) {
|
|
74
|
+
reply.code(503).send({ error: "Remote proxy session is unavailable" });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (!session.activated) {
|
|
78
|
+
reply.code(403).send({ error: "Remote proxy session is not activated" });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
session.lastAccessAt = Date.now();
|
|
82
|
+
await proxyRequest({ request, reply, session, logger: this.options.logger });
|
|
83
|
+
});
|
|
84
|
+
const addressInfo = await app.listen({ host: LOOPBACK_HOST, port: 0 });
|
|
85
|
+
const address = new URL(addressInfo);
|
|
86
|
+
const localBaseUrl = new URL(`https://${LOOPBACK_HOST}:${address.port}`);
|
|
87
|
+
const entryUrl = new URL(targetBaseUrl.pathname || "/", localBaseUrl);
|
|
88
|
+
const returnTo = buildReturnToTarget(entryUrl);
|
|
89
|
+
session = {
|
|
90
|
+
id: sessionId,
|
|
91
|
+
bootstrapToken,
|
|
92
|
+
targetBaseUrl,
|
|
93
|
+
skipTlsVerify,
|
|
94
|
+
localBaseUrl,
|
|
95
|
+
entryUrl,
|
|
96
|
+
bootstrapUrl: `${localBaseUrl.origin}${BOOTSTRAP_PAGE_PATH}?returnTo=${encodeURIComponent(returnTo)}#${encodeURIComponent(bootstrapToken)}`,
|
|
97
|
+
activated: false,
|
|
98
|
+
cookiePrefix: `cnrp_${randomBytes(6).toString("hex")}_`,
|
|
99
|
+
app,
|
|
100
|
+
dispatcher,
|
|
101
|
+
createdAt: Date.now(),
|
|
102
|
+
lastAccessAt: Date.now(),
|
|
103
|
+
};
|
|
104
|
+
this.sessions.set(sessionId, session);
|
|
105
|
+
this.options.logger.info({ sessionId, targetBaseUrl: targetBaseUrl.toString(), localBaseUrl: localBaseUrl.toString() }, "Created remote proxy session");
|
|
106
|
+
return { sessionId, windowUrl: session.bootstrapUrl };
|
|
107
|
+
}
|
|
108
|
+
async deleteSession(sessionId) {
|
|
109
|
+
return this.disposeSession(sessionId);
|
|
110
|
+
}
|
|
111
|
+
async cleanupExpiredSessions() {
|
|
112
|
+
const now = Date.now();
|
|
113
|
+
for (const session of Array.from(this.sessions.values())) {
|
|
114
|
+
if (now - session.lastAccessAt <= SESSION_IDLE_TTL_MS) {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
await this.disposeSession(session.id);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async disposeSession(sessionId) {
|
|
121
|
+
const session = this.sessions.get(sessionId);
|
|
122
|
+
if (!session) {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
this.sessions.delete(sessionId);
|
|
126
|
+
session.dispatcher?.close().catch(() => { });
|
|
127
|
+
await session.app.close().catch(() => { });
|
|
128
|
+
this.options.logger.info({ sessionId }, "Disposed remote proxy session");
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function normalizeBaseUrl(input) {
|
|
133
|
+
const parsed = new URL(input.trim());
|
|
134
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
135
|
+
throw new Error("Server URL must use http:// or https://");
|
|
136
|
+
}
|
|
137
|
+
parsed.hash = "";
|
|
138
|
+
parsed.search = "";
|
|
139
|
+
parsed.pathname = parsed.pathname === "/" ? "/" : parsed.pathname.replace(/\/+$/, "") || "/";
|
|
140
|
+
return parsed;
|
|
141
|
+
}
|
|
142
|
+
function buildReturnToTarget(entryUrl) {
|
|
143
|
+
const query = entryUrl.search ? entryUrl.search : "";
|
|
144
|
+
return `${entryUrl.pathname || "/"}${query}`;
|
|
145
|
+
}
|
|
146
|
+
function buildBootstrapPageHtml() {
|
|
147
|
+
return `<!doctype html>
|
|
148
|
+
<html lang="en">
|
|
149
|
+
<head>
|
|
150
|
+
<meta charset="utf-8" />
|
|
151
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
152
|
+
<title>CodeNomad</title>
|
|
153
|
+
<style>
|
|
154
|
+
body { font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial; background: #0b0b0f; color: #fff; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
|
|
155
|
+
.card { width: 420px; max-width: calc(100vw - 32px); background: #14141c; border: 1px solid rgba(255,255,255,0.08); border-radius: 14px; padding: 24px; }
|
|
156
|
+
h1 { font-size: 18px; margin: 0 0 12px; }
|
|
157
|
+
p { margin: 0; color: rgba(255,255,255,0.7); font-size: 13px; line-height: 1.4; }
|
|
158
|
+
.error { margin-top: 12px; color: #ff6b6b; font-size: 13px; display: none; }
|
|
159
|
+
</style>
|
|
160
|
+
</head>
|
|
161
|
+
<body>
|
|
162
|
+
<div class="card">
|
|
163
|
+
<h1>Connecting...</h1>
|
|
164
|
+
<p>Finalizing local authentication.</p>
|
|
165
|
+
<div id="error" class="error"></div>
|
|
166
|
+
</div>
|
|
167
|
+
<script>
|
|
168
|
+
const token = decodeURIComponent((location.hash || "").replace(/^#/, "").trim())
|
|
169
|
+
const params = new URLSearchParams(location.search)
|
|
170
|
+
const returnTo = sanitizeReturnTo(params.get("returnTo"))
|
|
171
|
+
const errorEl = document.getElementById("error")
|
|
172
|
+
|
|
173
|
+
function sanitizeReturnTo(value) {
|
|
174
|
+
if (!value || typeof value !== "string") return "/"
|
|
175
|
+
if (!value.startsWith("/")) return "/"
|
|
176
|
+
if (value.startsWith("//")) return "/"
|
|
177
|
+
return value
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function showError(message) {
|
|
181
|
+
errorEl.textContent = message
|
|
182
|
+
errorEl.style.display = "block"
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function run() {
|
|
186
|
+
if (!token) {
|
|
187
|
+
showError("Missing bootstrap token.")
|
|
188
|
+
return
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
const res = await fetch("${BOOTSTRAP_EXCHANGE_PATH}", {
|
|
193
|
+
method: "POST",
|
|
194
|
+
headers: { "Content-Type": "application/json" },
|
|
195
|
+
body: JSON.stringify({ token }),
|
|
196
|
+
credentials: "include",
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
if (!res.ok) {
|
|
200
|
+
let message = ""
|
|
201
|
+
try {
|
|
202
|
+
const json = await res.json()
|
|
203
|
+
message = json && json.error ? String(json.error) : ""
|
|
204
|
+
} catch {
|
|
205
|
+
message = ""
|
|
206
|
+
}
|
|
207
|
+
showError(message || "Token exchange failed (" + res.status + ")")
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
window.location.replace(returnTo)
|
|
212
|
+
} catch (error) {
|
|
213
|
+
showError(error && error.message ? error.message : String(error))
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
run()
|
|
218
|
+
</script>
|
|
219
|
+
</body>
|
|
220
|
+
</html>`;
|
|
221
|
+
}
|
|
222
|
+
function parseTokenBody(body) {
|
|
223
|
+
const value = normalizeJsonBody(body);
|
|
224
|
+
const token = typeof value?.token === "string" ? value.token.trim() : "";
|
|
225
|
+
if (!token) {
|
|
226
|
+
throw new Error("Missing bootstrap token");
|
|
227
|
+
}
|
|
228
|
+
return { token };
|
|
229
|
+
}
|
|
230
|
+
function normalizeJsonBody(body) {
|
|
231
|
+
if (Buffer.isBuffer(body)) {
|
|
232
|
+
return JSON.parse(body.toString("utf-8"));
|
|
233
|
+
}
|
|
234
|
+
if (typeof body === "string") {
|
|
235
|
+
return JSON.parse(body);
|
|
236
|
+
}
|
|
237
|
+
return body;
|
|
238
|
+
}
|
|
239
|
+
function toRequestBody(body) {
|
|
240
|
+
if (body == null) {
|
|
241
|
+
return undefined;
|
|
242
|
+
}
|
|
243
|
+
if (Buffer.isBuffer(body) || typeof body === "string" || body instanceof Uint8Array) {
|
|
244
|
+
return body;
|
|
245
|
+
}
|
|
246
|
+
return JSON.stringify(body);
|
|
247
|
+
}
|
|
248
|
+
async function proxyRequest(args) {
|
|
249
|
+
const { request, reply, session, logger } = args;
|
|
250
|
+
const upstreamUrl = buildUpstreamUrl(session.targetBaseUrl, request.raw.url ?? request.url);
|
|
251
|
+
const headers = filterRequestHeaders(request.headers, session);
|
|
252
|
+
const init = {
|
|
253
|
+
method: request.method,
|
|
254
|
+
headers,
|
|
255
|
+
dispatcher: session.dispatcher,
|
|
256
|
+
redirect: "manual",
|
|
257
|
+
};
|
|
258
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
259
|
+
const body = toRequestBody(request.body);
|
|
260
|
+
if (body !== undefined) {
|
|
261
|
+
init.body = body;
|
|
262
|
+
init.duplex = "half";
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
const response = await fetch(upstreamUrl, init);
|
|
267
|
+
reply.code(response.status);
|
|
268
|
+
applyResponseHeaders(reply, response, session);
|
|
269
|
+
if (!response.body || request.method === "HEAD") {
|
|
270
|
+
reply.send();
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
reply.hijack();
|
|
274
|
+
reply.raw.writeHead(reply.statusCode, toOutgoingHeaders(reply.getHeaders()));
|
|
275
|
+
await pipeline(Readable.fromWeb(response.body), reply.raw);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
logger.error({ err: error, upstreamUrl }, "Failed to proxy remote session request");
|
|
279
|
+
if (!reply.sent) {
|
|
280
|
+
reply.code(502).send({ error: "Remote proxy request failed" });
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function buildUpstreamUrl(baseUrl, rawUrl) {
|
|
285
|
+
const parsed = new URL(rawUrl, "https://localhost");
|
|
286
|
+
const url = new URL(baseUrl.toString());
|
|
287
|
+
url.pathname = rewriteRequestPath(baseUrl, parsed.pathname);
|
|
288
|
+
url.search = stripInternalQuery(parsed.search);
|
|
289
|
+
url.hash = "";
|
|
290
|
+
return url.toString();
|
|
291
|
+
}
|
|
292
|
+
function rewriteRequestPath(baseUrl, requestPath) {
|
|
293
|
+
const basePath = normalizedBasePath(baseUrl);
|
|
294
|
+
if (basePath === "/") {
|
|
295
|
+
return requestPath;
|
|
296
|
+
}
|
|
297
|
+
if (requestPath === "/") {
|
|
298
|
+
return basePath;
|
|
299
|
+
}
|
|
300
|
+
if (pathHasBasePrefix(basePath, requestPath)) {
|
|
301
|
+
return requestPath;
|
|
302
|
+
}
|
|
303
|
+
return `${basePath}${requestPath}`;
|
|
304
|
+
}
|
|
305
|
+
function normalizedBasePath(baseUrl) {
|
|
306
|
+
return baseUrl.pathname || "/";
|
|
307
|
+
}
|
|
308
|
+
function pathHasBasePrefix(basePath, requestPath) {
|
|
309
|
+
return requestPath === basePath || requestPath.startsWith(`${basePath}/`);
|
|
310
|
+
}
|
|
311
|
+
function stripInternalQuery(search) {
|
|
312
|
+
if (!search || search === "?") {
|
|
313
|
+
return "";
|
|
314
|
+
}
|
|
315
|
+
return search;
|
|
316
|
+
}
|
|
317
|
+
function filterRequestHeaders(headers, session) {
|
|
318
|
+
const next = {};
|
|
319
|
+
for (const [key, value] of Object.entries(headers ?? {})) {
|
|
320
|
+
if (!value)
|
|
321
|
+
continue;
|
|
322
|
+
const lower = key.toLowerCase();
|
|
323
|
+
if (isHopByHopHeader(lower) ||
|
|
324
|
+
lower === "host" ||
|
|
325
|
+
lower === "content-length" ||
|
|
326
|
+
lower === "accept-encoding") {
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (lower === "origin") {
|
|
330
|
+
next[key] = session.targetBaseUrl.origin;
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (lower === "referer") {
|
|
334
|
+
const rewritten = rewriteRefererHeader(Array.isArray(value) ? value[0] : value, session.targetBaseUrl);
|
|
335
|
+
if (rewritten) {
|
|
336
|
+
next[key] = rewritten;
|
|
337
|
+
}
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (lower === "cookie") {
|
|
341
|
+
const rewritten = rewriteRequestCookieHeader(Array.isArray(value) ? value.join("; ") : value, session.cookiePrefix);
|
|
342
|
+
if (rewritten) {
|
|
343
|
+
next[key] = rewritten;
|
|
344
|
+
}
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
next[key] = Array.isArray(value) ? value.join(",") : value;
|
|
348
|
+
}
|
|
349
|
+
next.host = session.targetBaseUrl.port ? `${session.targetBaseUrl.hostname}:${session.targetBaseUrl.port}` : session.targetBaseUrl.hostname;
|
|
350
|
+
if (!next.origin) {
|
|
351
|
+
next.origin = session.targetBaseUrl.origin;
|
|
352
|
+
}
|
|
353
|
+
return next;
|
|
354
|
+
}
|
|
355
|
+
function rewriteRefererHeader(referer, targetBaseUrl) {
|
|
356
|
+
if (!referer) {
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
const parsed = new URL(referer);
|
|
361
|
+
const rewritten = new URL(targetBaseUrl.toString());
|
|
362
|
+
rewritten.pathname = rewriteRequestPath(targetBaseUrl, parsed.pathname);
|
|
363
|
+
rewritten.search = parsed.search;
|
|
364
|
+
rewritten.hash = parsed.hash;
|
|
365
|
+
return rewritten.toString();
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function applyResponseHeaders(reply, response, session) {
|
|
372
|
+
const setCookie = response.headers.getSetCookie?.();
|
|
373
|
+
if (Array.isArray(setCookie)) {
|
|
374
|
+
for (const cookie of setCookie) {
|
|
375
|
+
reply.header("set-cookie", rewriteSetCookie(cookie, session.cookiePrefix));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
response.headers.forEach((value, key) => {
|
|
379
|
+
const lower = key.toLowerCase();
|
|
380
|
+
if (isHopByHopHeader(lower) ||
|
|
381
|
+
lower === "set-cookie" ||
|
|
382
|
+
lower === "content-length" ||
|
|
383
|
+
lower === "content-encoding") {
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (lower === "location") {
|
|
387
|
+
reply.header(key, rewriteLocation(value, session.targetBaseUrl, session.localBaseUrl));
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
reply.header(key, value);
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
function toOutgoingHeaders(headers) {
|
|
394
|
+
const next = {};
|
|
395
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
396
|
+
if (value === undefined) {
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
next[key] = Array.isArray(value) ? value.map(String) : String(value);
|
|
400
|
+
}
|
|
401
|
+
return next;
|
|
402
|
+
}
|
|
403
|
+
function rewriteSetCookie(cookie, cookiePrefix) {
|
|
404
|
+
const parts = cookie.split(";").map((part) => part.trim());
|
|
405
|
+
const first = parts.shift() ?? "";
|
|
406
|
+
const separator = first.indexOf("=");
|
|
407
|
+
if (separator <= 0) {
|
|
408
|
+
return cookie;
|
|
409
|
+
}
|
|
410
|
+
const name = first.slice(0, separator).trim();
|
|
411
|
+
const value = first.slice(separator + 1);
|
|
412
|
+
const rewritten = [`${cookiePrefix}${name}=${value}`];
|
|
413
|
+
for (const part of parts) {
|
|
414
|
+
if (part.slice(0, 7).toLowerCase().startsWith("domain=")) {
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
rewritten.push(part);
|
|
418
|
+
}
|
|
419
|
+
return rewritten.join("; ");
|
|
420
|
+
}
|
|
421
|
+
function rewriteRequestCookieHeader(cookieHeader, cookiePrefix) {
|
|
422
|
+
const next = [];
|
|
423
|
+
for (const rawPart of cookieHeader.split(";")) {
|
|
424
|
+
const part = rawPart.trim();
|
|
425
|
+
if (!part)
|
|
426
|
+
continue;
|
|
427
|
+
const separator = part.indexOf("=");
|
|
428
|
+
if (separator <= 0)
|
|
429
|
+
continue;
|
|
430
|
+
const name = part.slice(0, separator).trim();
|
|
431
|
+
const value = part.slice(separator + 1);
|
|
432
|
+
if (!name.startsWith(cookiePrefix)) {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
next.push(`${name.slice(cookiePrefix.length)}=${value}`);
|
|
436
|
+
}
|
|
437
|
+
return next.join("; ");
|
|
438
|
+
}
|
|
439
|
+
function rewriteLocation(location, targetBaseUrl, localBaseUrl) {
|
|
440
|
+
try {
|
|
441
|
+
const parsed = new URL(location, targetBaseUrl);
|
|
442
|
+
if (parsed.origin !== targetBaseUrl.origin) {
|
|
443
|
+
return location;
|
|
444
|
+
}
|
|
445
|
+
const rewritten = new URL(localBaseUrl.toString());
|
|
446
|
+
rewritten.pathname = parsed.pathname;
|
|
447
|
+
rewritten.search = parsed.search;
|
|
448
|
+
rewritten.hash = parsed.hash;
|
|
449
|
+
return rewritten.toString();
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
return location;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
function isHopByHopHeader(name) {
|
|
456
|
+
return new Set([
|
|
457
|
+
"connection",
|
|
458
|
+
"keep-alive",
|
|
459
|
+
"proxy-authenticate",
|
|
460
|
+
"proxy-authorization",
|
|
461
|
+
"te",
|
|
462
|
+
"trailer",
|
|
463
|
+
"transfer-encoding",
|
|
464
|
+
"upgrade",
|
|
465
|
+
]).has(name);
|
|
466
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { isLoopbackAddress } from "../../auth/http-auth";
|
|
3
|
+
const CreateSessionSchema = z.object({
|
|
4
|
+
baseUrl: z.string().min(1),
|
|
5
|
+
skipTlsVerify: z.boolean().optional(),
|
|
6
|
+
});
|
|
7
|
+
const SessionParamsSchema = z.object({
|
|
8
|
+
id: z.string().uuid(),
|
|
9
|
+
});
|
|
10
|
+
export function registerRemoteProxyRoutes(app, deps) {
|
|
11
|
+
app.post("/api/remote-proxy/sessions", async (request, reply) => {
|
|
12
|
+
try {
|
|
13
|
+
const body = CreateSessionSchema.parse(request.body ?? {});
|
|
14
|
+
return await deps.sessionManager.createSession(body.baseUrl, Boolean(body.skipTlsVerify));
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
deps.logger.warn({ err: error }, "Failed to create remote proxy session");
|
|
18
|
+
reply.code(400);
|
|
19
|
+
return { error: error instanceof Error ? error.message : "Failed to create remote proxy session" };
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
app.delete("/api/remote-proxy/sessions/:id", async (request, reply) => {
|
|
23
|
+
if (!isLoopbackAddress(request.socket.remoteAddress)) {
|
|
24
|
+
reply.code(404);
|
|
25
|
+
return { error: "Not found" };
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const params = SessionParamsSchema.parse(request.params ?? {});
|
|
29
|
+
const deleted = await deps.sessionManager.deleteSession(params.id);
|
|
30
|
+
if (!deleted) {
|
|
31
|
+
reply.code(404);
|
|
32
|
+
return { error: "Remote proxy session not found" };
|
|
33
|
+
}
|
|
34
|
+
return { ok: true };
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
deps.logger.warn({ err: error }, "Failed to delete remote proxy session");
|
|
38
|
+
reply.code(400);
|
|
39
|
+
return { error: error instanceof Error ? error.message : "Failed to delete remote proxy session" };
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { probeBinaryVersion } from "../../workspaces/
|
|
2
|
+
import { probeBinaryVersion } from "../../workspaces/spawn";
|
|
3
3
|
import { sanitizeConfigDoc, sanitizeConfigOwner } from "../../settings/public-config";
|
|
4
4
|
const ValidateBinarySchema = z.object({
|
|
5
5
|
path: z.string(),
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { getWorktreeGitDiff, getWorktreeGitStatus } from "../../workspaces/git-status";
|
|
3
|
+
import { commitWorktreeChanges, isGitMutationError, stageWorktreePaths, unstageWorktreePaths } from "../../workspaces/git-mutations";
|
|
4
|
+
import { isGitAvailable, resolveRepoRoot } from "../../workspaces/git-worktrees";
|
|
5
|
+
import { resolveWorktreeDirectory } from "../../workspaces/worktree-directory";
|
|
2
6
|
const WorkspaceCreateSchema = z.object({
|
|
3
7
|
path: z.string(),
|
|
4
8
|
name: z.string().optional(),
|
|
@@ -12,6 +16,17 @@ const WorkspaceFileContentQuerySchema = z.object({
|
|
|
12
16
|
const WorkspaceFileContentBodySchema = z.object({
|
|
13
17
|
contents: z.string(),
|
|
14
18
|
});
|
|
19
|
+
const WorktreeGitDiffQuerySchema = z.object({
|
|
20
|
+
path: z.string().trim().min(1, "Path is required"),
|
|
21
|
+
originalPath: z.string().trim().optional(),
|
|
22
|
+
scope: z.enum(["staged", "unstaged"]),
|
|
23
|
+
});
|
|
24
|
+
const WorktreeGitPathsBodySchema = z.object({
|
|
25
|
+
paths: z.array(z.string().trim().min(1, "Path is required")).min(1, "At least one path is required"),
|
|
26
|
+
});
|
|
27
|
+
const WorktreeGitCommitBodySchema = z.object({
|
|
28
|
+
message: z.string().trim().min(1, "Commit message is required"),
|
|
29
|
+
});
|
|
15
30
|
const WorkspaceFileSearchQuerySchema = z.object({
|
|
16
31
|
q: z.string().trim().min(1, "Query is required"),
|
|
17
32
|
limit: z.coerce.number().int().positive().max(200).optional(),
|
|
@@ -92,8 +107,111 @@ export function registerWorkspaceRoutes(app, deps) {
|
|
|
92
107
|
return handleWorkspaceError(error, reply);
|
|
93
108
|
}
|
|
94
109
|
});
|
|
110
|
+
app.get("/api/workspaces/:id/worktrees/:slug/git-status", async (request, reply) => {
|
|
111
|
+
try {
|
|
112
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
113
|
+
if (!directory)
|
|
114
|
+
return;
|
|
115
|
+
return await getWorktreeGitStatus({ workspaceFolder: directory, logger: request.log });
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
return handleWorkspaceError(error, reply);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
app.get("/api/workspaces/:id/worktrees/:slug/git-diff", async (request, reply) => {
|
|
122
|
+
try {
|
|
123
|
+
const query = WorktreeGitDiffQuerySchema.parse(request.query ?? {});
|
|
124
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
125
|
+
if (!directory)
|
|
126
|
+
return;
|
|
127
|
+
return await getWorktreeGitDiff({
|
|
128
|
+
workspaceFolder: directory,
|
|
129
|
+
path: query.path,
|
|
130
|
+
originalPath: query.originalPath,
|
|
131
|
+
scope: query.scope,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
return handleWorkspaceError(error, reply);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
app.post("/api/workspaces/:id/worktrees/:slug/git-stage", async (request, reply) => {
|
|
139
|
+
try {
|
|
140
|
+
const body = WorktreeGitPathsBodySchema.parse(request.body ?? {});
|
|
141
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
142
|
+
if (!directory)
|
|
143
|
+
return;
|
|
144
|
+
await stageWorktreePaths({ workspaceFolder: directory, paths: body.paths });
|
|
145
|
+
return { ok: true };
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
return handleWorkspaceError(error, reply);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
app.post("/api/workspaces/:id/worktrees/:slug/git-unstage", async (request, reply) => {
|
|
152
|
+
try {
|
|
153
|
+
const body = WorktreeGitPathsBodySchema.parse(request.body ?? {});
|
|
154
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
155
|
+
if (!directory)
|
|
156
|
+
return;
|
|
157
|
+
await unstageWorktreePaths({ workspaceFolder: directory, paths: body.paths });
|
|
158
|
+
return { ok: true };
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
return handleWorkspaceError(error, reply);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
app.post("/api/workspaces/:id/worktrees/:slug/git-commit", async (request, reply) => {
|
|
165
|
+
try {
|
|
166
|
+
const body = WorktreeGitCommitBodySchema.parse(request.body ?? {});
|
|
167
|
+
const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
|
|
168
|
+
if (!directory)
|
|
169
|
+
return;
|
|
170
|
+
const result = await commitWorktreeChanges({ workspaceFolder: directory, message: body.message });
|
|
171
|
+
return { ok: true, ...result };
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
return handleWorkspaceError(error, reply);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
async function resolveGitWorktreeDirectory(workspaceManager, workspaceId, worktreeSlug, logger, reply) {
|
|
179
|
+
const workspace = workspaceManager.get(workspaceId);
|
|
180
|
+
if (!workspace) {
|
|
181
|
+
reply.code(404);
|
|
182
|
+
reply.send({ error: "Workspace not found" });
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
const gitAvailable = await isGitAvailable(workspace.path);
|
|
186
|
+
if (!gitAvailable) {
|
|
187
|
+
reply.code(503);
|
|
188
|
+
reply.send({ error: "Git is not installed or not available in PATH" });
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
const { isGitRepo } = await resolveRepoRoot(workspace.path, logger);
|
|
192
|
+
if (!isGitRepo) {
|
|
193
|
+
reply.code(400);
|
|
194
|
+
reply.send({ error: "Workspace is not a Git repository" });
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
const directory = await resolveWorktreeDirectory({
|
|
198
|
+
workspaceId: workspace.id,
|
|
199
|
+
workspacePath: workspace.path,
|
|
200
|
+
worktreeSlug,
|
|
201
|
+
logger,
|
|
202
|
+
});
|
|
203
|
+
if (!directory) {
|
|
204
|
+
reply.code(404);
|
|
205
|
+
reply.send({ error: "Worktree not found" });
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
return directory;
|
|
95
209
|
}
|
|
96
210
|
function handleWorkspaceError(error, reply) {
|
|
211
|
+
if (isGitMutationError(error)) {
|
|
212
|
+
reply.code(error.statusCode);
|
|
213
|
+
return { error: error.message };
|
|
214
|
+
}
|
|
97
215
|
if (error instanceof Error && error.message === "Workspace not found") {
|
|
98
216
|
reply.code(404);
|
|
99
217
|
return { error: "Workspace not found" };
|