-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathproxy.ts
More file actions
249 lines (214 loc) · 7.71 KB
/
proxy.ts
File metadata and controls
249 lines (214 loc) · 7.71 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
import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise<boolean> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'api', key: apiKey }),
})
if (response.ok) {
logger.info(`Set OpenCode auth for provider: ${providerId}`)
return true
}
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
return false
} catch (error) {
logger.error('Failed to set OpenCode auth:', error)
return false
}
}
export async function deleteOpenCodeAuth(providerId: string): Promise<boolean> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
method: 'DELETE',
})
if (response.ok) {
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
return true
}
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
return false
} catch (error) {
logger.error('Failed to delete OpenCode auth:', error)
return false
}
}
export type PatchConfigResult = {
success: boolean
error?: string
}
export async function patchOpenCodeConfig(config: Record<string, unknown>): Promise<PatchConfigResult> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config),
})
if (response.ok) {
logger.info('Patched OpenCode config via API')
return { success: true }
}
let errorMessage = `${response.status} ${response.statusText}`
try {
const errorBody = await response.json() as Record<string, unknown>
if (errorBody?.name === 'ConfigInvalidError' && errorBody?.data) {
const data = errorBody.data as { issues?: Array<{ message: string; path?: string[] }> }
if (data.issues) {
const issues = data.issues
.map((issue) =>
issue.path ? `${issue.path.join('.')}: ${issue.message}` : issue.message
)
.join('; ')
errorMessage = `Invalid config: ${issues}`
}
} else if (typeof errorBody?.error === 'string') {
errorMessage = errorBody.error
} else if (typeof errorBody?.message === 'string') {
errorMessage = errorBody.message
}
} catch {
// Use default error message if we can't parse response body
}
logger.error(`Failed to patch OpenCode config: ${errorMessage}`)
return { success: false, error: errorMessage }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
logger.error('Failed to patch OpenCode config:', error)
return { success: false, error: errorMessage }
}
}
export async function proxyRequest(request: Request) {
const url = new URL(request.url)
// Remove /api/opencode prefix from pathname before forwarding
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}`
if (url.pathname.includes('/permissions/')) {
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${targetUrl}`)
}
try {
const headers: Record<string, string> = {}
request.headers.forEach((value, key) => {
if (!['host', 'connection'].includes(key.toLowerCase())) {
headers[key] = value
}
})
const response = await fetch(targetUrl, {
method: request.method,
headers,
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
})
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
const body = await response.text()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} catch (error) {
logger.error(`Proxy request failed for ${url.pathname}${url.search}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
export async function proxyToOpenCodeWithDirectory(
path: string,
method: string,
directory: string | undefined,
body?: string,
headers?: Record<string, string>
): Promise<Response> {
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
if (directory) {
url.searchParams.set('directory', directory)
}
try {
const response = await fetch(url.toString(), {
method,
headers: headers || { 'Content-Type': 'application/json' },
body,
})
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} catch (error) {
logger.error(`Proxy to OpenCode failed for ${path}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
export async function proxyMcpAuthStart(
serverName: string,
directory: string | undefined,
): Promise<Response> {
const path = `/mcp/${encodeURIComponent(serverName)}/auth`
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
if (directory) {
url.searchParams.set('directory', directory)
}
try {
const response = await fetch(url.toString(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
})
} catch (error) {
logger.error(`MCP auth start failed for ${serverName}:`, error)
return new Response(JSON.stringify({ error: 'MCP auth start failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
export async function proxyMcpAuthAuthenticate(
serverName: string,
directory: string | undefined,
): Promise<Response> {
const path = `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
if (directory) {
url.searchParams.set('directory', directory)
}
try {
const response = await fetch(url.toString(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
})
} catch (error) {
logger.error(`MCP auth authenticate failed for ${serverName}:`, error)
return new Response(JSON.stringify({ error: 'MCP auth authenticate failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}