-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_proxy.js
More file actions
417 lines (364 loc) · 12.9 KB
/
bridge_proxy.js
File metadata and controls
417 lines (364 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
const fs = require("fs")
const http = require("http")
const net = require("net")
const os = require("os")
const path = require("path")
const bridgeVersion = "0.2.0"
const listenHost = process.env.OPENCODE_PROXY_HOST || "0.0.0.0"
const listenPort = Number(process.env.OPENCODE_PROXY_PORT || 4096)
const upstreamHost = process.env.OPENCODE_UPSTREAM_HOST || "127.0.0.1"
const upstreamPort = Number(process.env.OPENCODE_UPSTREAM_PORT || 4097)
const desktopGlobalPath = process.env.OPENCODE_DESKTOP_GLOBAL || defaultDesktopGlobalPath()
const manualSeedProjects = splitProjectList(process.env.OPENCODE_SEED_PROJECTS || "")
const includeMissingProjects = process.env.OPENCODE_INCLUDE_MISSING_PROJECTS === "1"
function defaultDesktopGlobalPath() {
if (process.platform === "win32") {
return path.join(process.env.APPDATA || "", "ai.opencode.desktop", "opencode.global.dat")
}
if (process.platform === "darwin") {
return path.join(os.homedir(), "Library", "Application Support", "ai.opencode.desktop", "opencode.global.dat")
}
return path.join(os.homedir(), ".config", "ai.opencode.desktop", "opencode.global.dat")
}
function splitProjectList(value) {
return value
.split(/[;\n]/)
.map((project) => normalizeProjectPath(project))
.filter(Boolean)
}
function normalizeProjectPath(value) {
if (!value) return ""
let normalized = String(value).trim()
if (!normalized || normalized === "/") return ""
if (/^https?:\/\//i.test(normalized)) return ""
normalized = normalized.replace(/^['"]|['"]$/g, "")
normalized = normalized.replace(/\\\//g, "/")
normalized = normalized.replace(/\\\\+/g, "\\")
if (/^[a-z]:\//i.test(normalized)) {
normalized = normalized.replace(/\//g, "\\")
}
normalized = normalized.replace(/\\+$/g, "")
return normalized
}
function projectExists(project) {
if (includeMissingProjects) return true
try {
return fs.existsSync(project) && fs.statSync(project).isDirectory()
} catch {
return false
}
}
function addProject(projects, seen, project, source, time) {
const worktree = normalizeProjectPath(project && (project.worktree || project.path || project))
if (!worktree) return
if (!projectExists(worktree)) return
const key = worktree.toLowerCase()
if (seen.has(key)) return
seen.add(key)
projects.push({ worktree, expanded: true, source, time: time || (project && project.time) || undefined })
}
function parseJsonStringValue(text, key) {
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
const regex = new RegExp('"' + escapedKey + '"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"')
const match = text.match(regex)
if (!match) return undefined
try {
return JSON.parse('"' + match[1] + '"')
} catch {
return undefined
}
}
function addDesktopServerProjects(text, projects, seen) {
for (const key of ["server", "server.v3", "opencode.global.dat:server", "opencode.global.dat:server.v3"]) {
const value = parseJsonStringValue(text, key)
if (!value) continue
try {
const state = JSON.parse(value)
for (const list of Object.values(state.projects || {})) {
if (!Array.isArray(list)) continue
for (const project of list) addProject(projects, seen, project, `desktop:${key}`)
}
} catch {
// Ignore malformed legacy state and fall through to regex scanning.
}
}
}
function addDesktopGlobalSyncProjects(text, projects, seen) {
const value = parseJsonStringValue(text, "globalSync.project")
if (!value) return
try {
const state = JSON.parse(value)
for (const project of state.value || []) addProject(projects, seen, project, "desktop:globalSync", project.time)
} catch {
// Ignore malformed legacy state and fall through to regex scanning.
}
}
function decodeCandidate(value) {
let decoded = value
for (let i = 0; i < 2; i++) {
try {
decoded = JSON.parse('"' + decoded.replace(/"/g, '\\"') + '"')
} catch {
break
}
}
return normalizeProjectPath(decoded)
}
function addRegexScannedProjects(text, projects, seen) {
const worktreeRegexes = [
/"worktree"\s*:\s*"((?:\\.|[^"\\])*)"/g,
/\\"worktree\\"\s*:\s*\\"((?:\\\\.|[^"\\])*)\\"/g,
]
for (const regex of worktreeRegexes) {
let match
while ((match = regex.exec(text))) {
addProject(projects, seen, decodeCandidate(match[1]), "desktop:scan")
}
}
const windowsPathRegex = /[A-Za-z]:(?:\\\\|\\\/|\/)(?:[^"'\r\n\x00<>|?*]|\\\\|\\\/){1,240}/g
let match
while ((match = windowsPathRegex.exec(text))) {
addProject(projects, seen, decodeCandidate(match[0]), "desktop:path-scan")
}
}
function readDesktopProjects() {
const projects = []
const seen = new Set()
if (!desktopGlobalPath || !fs.existsSync(desktopGlobalPath)) {
return { projects, error: desktopGlobalPath ? `Desktop state not found: ${desktopGlobalPath}` : "Desktop state path not configured" }
}
try {
const text = fs.readFileSync(desktopGlobalPath, "utf8")
addDesktopServerProjects(text, projects, seen)
addDesktopGlobalSyncProjects(text, projects, seen)
addRegexScannedProjects(text, projects, seen)
return { projects }
} catch (error) {
return { projects, error: error.message }
}
}
function fetchUpstreamJson(requestPath) {
return new Promise((resolve, reject) => {
const request = http.request(
{
hostname: upstreamHost,
port: upstreamPort,
method: "GET",
path: requestPath,
headers: {
accept: "application/json",
host: `${upstreamHost}:${upstreamPort}`,
},
timeout: 5000,
},
(response) => {
let body = ""
response.setEncoding("utf8")
response.on("data", (chunk) => {
body += chunk
})
response.on("end", () => {
if ((response.statusCode || 500) >= 400) {
reject(new Error(`Upstream ${requestPath} returned ${response.statusCode}: ${body.slice(0, 300)}`))
return
}
try {
resolve(JSON.parse(body))
} catch (error) {
reject(error)
}
})
},
)
request.on("timeout", () => {
request.destroy(new Error(`Upstream ${requestPath} timed out`))
})
request.on("error", reject)
request.end()
})
}
async function collectProjects() {
const projects = []
const seen = new Set()
const diagnostics = {
manual: 0,
desktop: 0,
upstream: 0,
desktopGlobalPath,
desktopError: undefined,
upstreamError: undefined,
}
for (const project of manualSeedProjects) {
const before = projects.length
addProject(projects, seen, project, "manual")
if (projects.length > before) diagnostics.manual += 1
}
const desktop = readDesktopProjects()
diagnostics.desktopError = desktop.error
for (const project of desktop.projects) {
const before = projects.length
addProject(projects, seen, project, project.source || "desktop", project.time)
if (projects.length > before) diagnostics.desktop += 1
}
try {
const upstreamProjects = await fetchUpstreamJson("/project")
upstreamProjects.sort((a, b) => {
const at = (a.time && (a.time.updated || a.time.created)) || 0
const bt = (b.time && (b.time.updated || b.time.created)) || 0
return bt - at
})
for (const project of upstreamProjects) {
const before = projects.length
addProject(projects, seen, project, "upstream", project.time)
if (projects.length > before) diagnostics.upstream += 1
}
} catch (error) {
diagnostics.upstreamError = error.message
}
return { projects, diagnostics }
}
function seedHtml(projects, diagnostics) {
const projectsJson = JSON.stringify(projects.map((project) => ({ worktree: project.worktree, expanded: true }))).replace(
/<\/script/gi,
"<\\/script",
)
const diagnosticsJson = JSON.stringify(diagnostics).replace(/<\/script/gi, "<\\/script")
const originListJson = JSON.stringify([
"local",
`http://localhost:${listenPort}`,
`http://127.0.0.1:${listenPort}`,
`http://localhost:${upstreamPort}`,
`http://127.0.0.1:${upstreamPort}`,
])
return `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Seed OpenCode Projects</title>
<style>
body { font-family: system-ui, sans-serif; margin: 2rem; line-height: 1.45; }
code, pre { background: #f4f4f5; border-radius: 6px; }
code { padding: 0.1rem 0.25rem; }
pre { padding: 1rem; white-space: pre-wrap; }
a { color: #0f766e; }
</style>
</head>
<body>
<h1>Seeding OpenCode projects</h1>
<pre id="status">Preparing...</pre>
<p><a id="open" href="/" style="display:none">Open OpenCode</a></p>
<script>
try {
var status = document.getElementById("status")
var open = document.getElementById("open")
var projects = ${projectsJson}
var diagnostics = ${diagnosticsJson}
var baseOrigins = ${originListJson}
var origins = [location.origin]
for (var i = 0; i < baseOrigins.length; i++) {
if (origins.indexOf(baseOrigins[i]) === -1) origins.push(baseOrigins[i])
}
if (!projects.length) throw new Error("No projects available. Check /__projects for diagnostics.")
var projectMap = {}
var lastProject = {}
for (var j = 0; j < origins.length; j++) {
projectMap[origins[j]] = projects
lastProject[origins[j]] = projects[0].worktree
}
var state = { list: [location.origin], projects: projectMap, lastProject: lastProject }
var serialized = JSON.stringify(state)
localStorage.setItem("opencode.settings.dat:defaultServerUrl", location.origin)
localStorage.setItem("opencode.global.dat:server", serialized)
localStorage.setItem("opencode.global.dat:server.v3", serialized)
status.textContent = "Seeded " + projects.length + " projects for " + location.origin + ".\\n" +
"Sources: manual=" + diagnostics.manual + ", desktop=" + diagnostics.desktop + ", upstream=" + diagnostics.upstream + ".\\n" +
"If the page does not redirect, click Open OpenCode."
open.style.display = "inline"
window.setTimeout(function() { window.location.href = "/" }, 1000)
} catch (error) {
status.textContent = "Failed to seed projects:\\n" + (error && error.stack ? error.stack : error)
}
</script>
</body>
</html>`
}
function sendJson(res, statusCode, payload) {
res.writeHead(statusCode, {
"content-type": "application/json; charset=utf-8",
"cache-control": "no-store",
})
res.end(JSON.stringify(payload, null, 2))
}
async function proxyHttp(req, res) {
const requestUrl = new URL(req.url, "http://placeholder")
if (req.method === "GET" && requestUrl.pathname === "/__health") {
sendJson(res, 200, {
ok: true,
version: bridgeVersion,
upstream: `http://${upstreamHost}:${upstreamPort}`,
proxy: `http://${listenHost}:${listenPort}`,
})
return
}
if (req.method === "GET" && requestUrl.pathname === "/__projects") {
const result = await collectProjects()
sendJson(res, 200, result)
return
}
if (req.method === "GET" && requestUrl.pathname === "/__seed") {
const result = await collectProjects()
res.writeHead(200, {
"content-type": "text/html; charset=utf-8",
"cache-control": "no-store",
})
res.end(seedHtml(result.projects, result.diagnostics))
return
}
const headers = { ...req.headers, host: `${upstreamHost}:${upstreamPort}` }
const upstream = http.request(
{
hostname: upstreamHost,
port: upstreamPort,
method: req.method,
path: req.url,
headers,
},
(upstreamRes) => {
res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers)
upstreamRes.pipe(res)
},
)
upstream.on("error", (error) => {
if (res.headersSent) {
res.destroy(error)
return
}
res.writeHead(502, { "content-type": "text/plain; charset=utf-8" })
res.end(`OpenCode upstream unavailable: ${error.message}\n`)
})
req.pipe(upstream)
}
function proxyUpgrade(req, socket, head) {
const upstream = net.connect(upstreamPort, upstreamHost, () => {
upstream.write(`${req.method} ${req.url} HTTP/${req.httpVersion}\r\n`)
for (const [name, value] of Object.entries(req.headers)) {
if (Array.isArray(value)) {
for (const item of value) upstream.write(`${name}: ${item}\r\n`)
} else if (value !== undefined) {
upstream.write(`${name}: ${value}\r\n`)
}
}
upstream.write("\r\n")
if (head.length) upstream.write(head)
socket.pipe(upstream).pipe(socket)
})
upstream.on("error", () => socket.destroy())
}
const server = http.createServer(proxyHttp)
server.on("upgrade", proxyUpgrade)
server.listen(listenPort, listenHost, () => {
console.log(`OpenCode Mobile Bridge proxy listening on http://${listenHost}:${listenPort}`)
console.log(`Proxying to http://${upstreamHost}:${upstreamPort}`)
console.log(`Desktop project state: ${desktopGlobalPath}`)
})