@zyro-sec/server 1.0.0 → 1.0.1
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/package.json +15 -21
- package/script/build.ts +28 -0
- package/script/pack.ts +5 -0
- package/script/workerd-probe.ts +59 -0
- package/src/api.ts +12 -0
- package/src/auth.ts +70 -0
- package/src/content-headers.ts +32 -0
- package/src/cors.ts +34 -0
- package/src/event-feed.ts +93 -0
- package/src/fetch.ts +67 -0
- package/src/handlers/agent.ts +23 -0
- package/src/handlers/artifact.ts +242 -0
- package/src/handlers/automation.ts +63 -0
- package/src/handlers/blob.ts +55 -0
- package/src/handlers/command.ts +8 -0
- package/src/handlers/config.ts +26 -0
- package/src/handlers/credential.ts +87 -0
- package/src/handlers/debug.ts +57 -0
- package/src/handlers/event.ts +38 -0
- package/src/handlers/form.ts +15 -0
- package/src/handlers/fs.ts +180 -0
- package/src/handlers/generate.ts +117 -0
- package/src/handlers/integration.ts +310 -0
- package/src/handlers/job.ts +29 -0
- package/src/handlers/location.ts +33 -0
- package/src/handlers/machine.ts +336 -0
- package/src/handlers/mcp.ts +160 -0
- package/src/handlers/media.ts +44 -0
- package/src/handlers/message.ts +82 -0
- package/src/handlers/migration.ts +13 -0
- package/src/handlers/model.ts +25 -0
- package/src/handlers/permission.ts +131 -0
- package/src/handlers/persistent-pty.ts +285 -0
- package/src/handlers/plugin.ts +97 -0
- package/src/handlers/project.ts +23 -0
- package/src/handlers/provider.ts +32 -0
- package/src/handlers/pty-socket.ts +47 -0
- package/src/handlers/pty.ts +181 -0
- package/src/handlers/push.ts +67 -0
- package/src/handlers/reference.ts +8 -0
- package/src/handlers/rpc.ts +31 -0
- package/src/handlers/server.ts +58 -0
- package/src/handlers/session-error.ts +47 -0
- package/src/handlers/session.ts +722 -0
- package/src/handlers/shell.ts +72 -0
- package/src/handlers/skill.ts +34 -0
- package/src/handlers/usage.ts +23 -0
- package/src/handlers/vcs.ts +104 -0
- package/src/handlers/voice.ts +50 -0
- package/src/handlers/websearch.ts +50 -0
- package/src/handlers/worktree.ts +60 -0
- package/src/handlers.ts +69 -0
- package/src/location.ts +86 -0
- package/src/media-uri.ts +13 -0
- package/src/middleware/authorization.ts +111 -0
- package/src/middleware/defect-response.ts +39 -0
- package/src/middleware/form-location.ts +44 -0
- package/src/middleware/schema-error.ts +49 -0
- package/src/middleware/session-location.ts +30 -0
- package/src/options.ts +61 -0
- package/src/pairing.ts +36 -0
- package/src/process.ts +274 -0
- package/src/range.ts +16 -0
- package/src/request-site.ts +36 -0
- package/src/request-tracing.ts +9 -0
- package/src/routes.ts +261 -0
- package/src/server-info.ts +41 -0
- package/src/service-status.ts +30 -0
- package/src/workerd.ts +184 -0
- package/test/artifact.test.ts +224 -0
- package/test/auth.test.ts +24 -0
- package/test/automation.test.ts +315 -0
- package/test/client-mcp.test.ts +369 -0
- package/test/codemode-api.test.ts +88 -0
- package/test/config.test.ts +104 -0
- package/test/cors.test.ts +24 -0
- package/test/defect-response.test.ts +83 -0
- package/test/event-feed.test.ts +201 -0
- package/test/fetch-option.test.ts +104 -0
- package/test/fetch.test.ts +698 -0
- package/test/fixture/mcp-starts.cjs +20 -0
- package/test/fixture/routes.ts +37 -0
- package/test/fixture/server.ts +20 -0
- package/test/fixture/worktree-delegate/index.ts +13 -0
- package/test/fixture/worktree-plugin/index.ts +47 -0
- package/test/flag-channel.test.ts +126 -0
- package/test/fs.test.ts +439 -0
- package/test/generate.test.ts +132 -0
- package/test/handler-policy.test.ts +43 -0
- package/test/heap-dump.test.ts +137 -0
- package/test/integration-policy.test.ts +93 -0
- package/test/job.test.ts +186 -0
- package/test/machine-iroh.test.ts +259 -0
- package/test/machine-link.test.ts +1234 -0
- package/test/machine-routes.test.ts +198 -0
- package/test/media.test.ts +343 -0
- package/test/message.test.ts +105 -0
- package/test/model.test.ts +62 -0
- package/test/options.test.ts +42 -0
- package/test/permission-saved.test.ts +73 -0
- package/test/persistent-pty.test.ts +1007 -0
- package/test/process.test.ts +261 -0
- package/test/provider.test.ts +88 -0
- package/test/pty-socket.property.test.ts +240 -0
- package/test/pty-socket.test.ts +89 -0
- package/test/pty-transport.test.ts +200 -0
- package/test/push-routes.test.ts +157 -0
- package/test/request-site.test.ts +71 -0
- package/test/request-tracing.test.ts +87 -0
- package/test/rpc-handler-errors.test.ts +76 -0
- package/test/schema-error.test.ts +68 -0
- package/test/service-status.test.ts +34 -0
- package/test/session-admit-location.test.ts +92 -0
- package/test/session-create.test.ts +65 -0
- package/test/session-diff.test.ts +100 -0
- package/test/session-form.test.ts +50 -0
- package/test/session-import.test.ts +152 -0
- package/test/session-instances.test.ts +335 -0
- package/test/session-unarchive.test.ts +73 -0
- package/test/session-update.test.ts +66 -0
- package/test/skill.test.ts +57 -0
- package/test/sse-failure.test.ts +71 -0
- package/test/usage.test.ts +88 -0
- package/test/vcs.test.ts +356 -0
- package/test/video-generate.test.ts +131 -0
- package/test/voice.test.ts +170 -0
- package/test/workerd.test.ts +227 -0
- package/test/worktree.test.ts +333 -0
- package/tsconfig.build.json +15 -0
- package/tsconfig.json +11 -0
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { expect } from "bun:test"
|
|
2
|
+
import { NodeHttpServer } from "@effect/platform-node"
|
|
3
|
+
import { Location } from "@zyro-sec/core/location"
|
|
4
|
+
import { AbsolutePath } from "@zyro-sec/core/schema"
|
|
5
|
+
import { LocationLifecycle } from "@zyro-sec/core/location-lifecycle"
|
|
6
|
+
import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
|
|
7
|
+
import { Mcp } from "@zyro-sec/core/mcp/index"
|
|
8
|
+
import { Session } from "@zyro-sec/core/session"
|
|
9
|
+
import { Tool } from "@zyro-sec/core/tool"
|
|
10
|
+
import { McpTool } from "@zyro-sec/core/tool/mcp"
|
|
11
|
+
import { Context, Effect, Exit, Layer, MutableHashMap, Option, Schedule, Scope } from "effect"
|
|
12
|
+
import { HttpRouter, HttpServer } from "effect/http"
|
|
13
|
+
import { createServer } from "node:http"
|
|
14
|
+
import path from "node:path"
|
|
15
|
+
import { connectClientMcp } from "../../client/src/mcp"
|
|
16
|
+
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
|
17
|
+
import { it } from "../../core/test/lib/effect"
|
|
18
|
+
import { ServerProcess } from "../src/process"
|
|
19
|
+
import { createRoutes } from "../src/routes"
|
|
20
|
+
|
|
21
|
+
// The DOM lib hides Bun's WebSocket constructor overload that accepts upgrade request headers.
|
|
22
|
+
declare const WebSocket: {
|
|
23
|
+
new (url: string | URL, options?: Bun.WebSocketOptions): globalThis.WebSocket
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const authorization = `Basic ${btoa("opencode:secret")}`
|
|
27
|
+
|
|
28
|
+
const serve = Effect.fnUntraced(function* () {
|
|
29
|
+
const directory = (yield* tmpdirScoped("opencode-client-mcp-")).path
|
|
30
|
+
const context = yield* Layer.build(
|
|
31
|
+
createRoutes({
|
|
32
|
+
password: "secret",
|
|
33
|
+
app: { version: "test-version" },
|
|
34
|
+
database: { path: ":memory:" },
|
|
35
|
+
models: { fetch: false },
|
|
36
|
+
config: { directory, project: false, content: "{}" },
|
|
37
|
+
fs: { filewatcher: false },
|
|
38
|
+
}).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
|
|
39
|
+
)
|
|
40
|
+
const server = createServer()
|
|
41
|
+
const http = yield* NodeHttpServer.make(() => server, { port: 0, host: "127.0.0.1" })
|
|
42
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
|
|
43
|
+
yield* http
|
|
44
|
+
.serve(Context.get(context, HttpRouter.HttpRouter).asHttpEffect())
|
|
45
|
+
.pipe(Effect.provide(NodeHttpServer.layerHttpServices))
|
|
46
|
+
const base = HttpServer.formatAddress(http.address)
|
|
47
|
+
const location = LocationServiceMap.Service.get(
|
|
48
|
+
LocationServiceMap.canonical(Location.Ref.make({ directory: directory as Location.Ref["directory"] })),
|
|
49
|
+
)
|
|
50
|
+
return {
|
|
51
|
+
base,
|
|
52
|
+
directory,
|
|
53
|
+
context,
|
|
54
|
+
url: (query: Record<string, string>) => {
|
|
55
|
+
const url = new URL("/api/experimental/client-mcp", base)
|
|
56
|
+
url.protocol = "ws:"
|
|
57
|
+
url.searchParams.set("location[directory]", directory)
|
|
58
|
+
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value)
|
|
59
|
+
return url
|
|
60
|
+
},
|
|
61
|
+
inLocation: <A, E>(effect: Effect.Effect<A, E, Mcp.Service | Tool.Service | McpTool.Service>) =>
|
|
62
|
+
effect.pipe(Effect.provide(location), Effect.provideContext(context)),
|
|
63
|
+
}
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
/** Hosts an MCP server over a WebSocket opened to the endpoint, recording each call's session. */
|
|
67
|
+
const connectClient = (url: URL, headers?: Record<string, string>) =>
|
|
68
|
+
Effect.acquireRelease(
|
|
69
|
+
Effect.promise(async () => {
|
|
70
|
+
const socket = new WebSocket(url, { headers })
|
|
71
|
+
const state = { open: false, initialized: false, closed: false, code: 0 }
|
|
72
|
+
const sessions: unknown[] = []
|
|
73
|
+
const reply = (id: unknown, result: unknown) => socket.send(JSON.stringify({ jsonrpc: "2.0", id, result }))
|
|
74
|
+
socket.addEventListener("open", () => {
|
|
75
|
+
state.open = true
|
|
76
|
+
})
|
|
77
|
+
socket.addEventListener("message", (event) => {
|
|
78
|
+
const message = JSON.parse(String(event.data))
|
|
79
|
+
if (message.method === "initialize")
|
|
80
|
+
return reply(message.id, {
|
|
81
|
+
protocolVersion: message.params.protocolVersion,
|
|
82
|
+
capabilities: { tools: {} },
|
|
83
|
+
serverInfo: { name: "test-client", version: "1.0.0" },
|
|
84
|
+
})
|
|
85
|
+
if (message.method === "notifications/initialized") {
|
|
86
|
+
state.initialized = true
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
if (message.method === "tools/list")
|
|
90
|
+
return reply(message.id, {
|
|
91
|
+
tools: [{ name: "open_terminal", description: "Open a terminal", inputSchema: { type: "object" } }],
|
|
92
|
+
})
|
|
93
|
+
if (message.method === "tools/call") {
|
|
94
|
+
sessions.push(message.params._meta?.["ai.opencode/sessionID"])
|
|
95
|
+
return reply(message.id, { content: [{ type: "text", text: "opened" }] })
|
|
96
|
+
}
|
|
97
|
+
if (message.id !== undefined && message.method) reply(message.id, {})
|
|
98
|
+
})
|
|
99
|
+
socket.addEventListener("close", (event) => {
|
|
100
|
+
state.closed = true
|
|
101
|
+
state.code = event.code
|
|
102
|
+
})
|
|
103
|
+
return { socket, state, sessions }
|
|
104
|
+
}),
|
|
105
|
+
(client) => Effect.sync(() => client.socket.close()),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
const until = (check: () => boolean | Promise<boolean>) =>
|
|
109
|
+
Effect.promise(async () => check()).pipe(
|
|
110
|
+
Effect.flatMap((done) => (done ? Effect.void : Effect.fail("pending"))),
|
|
111
|
+
Effect.retry({ times: 500, schedule: Schedule.spaced("10 millis") }),
|
|
112
|
+
Effect.orDie,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
const registryIDs = Effect.gen(function* () {
|
|
116
|
+
const registration = yield* McpTool.Service
|
|
117
|
+
yield* registration.flush
|
|
118
|
+
const registry = yield* Tool.Service
|
|
119
|
+
return (yield* registry.list()).map((tool) => tool.id)
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it.live(
|
|
123
|
+
"attaches a client MCP server for the lifetime of its socket",
|
|
124
|
+
() =>
|
|
125
|
+
Effect.gen(function* () {
|
|
126
|
+
const server = yield* serve()
|
|
127
|
+
const client = yield* connectClient(server.url({ name: "tui" }), { authorization })
|
|
128
|
+
const tools = () => Effect.runPromise(server.inLocation(Mcp.Service.use((mcp) => mcp.tools())))
|
|
129
|
+
|
|
130
|
+
yield* until(async () => (await tools()).length > 0)
|
|
131
|
+
expect((yield* Effect.promise(tools)).map((tool) => [tool.server, tool.name])).toEqual([["tui", "open_terminal"]])
|
|
132
|
+
yield* until(() =>
|
|
133
|
+
Effect.runPromise(server.inLocation(registryIDs)).then((ids) => ids.includes("tui_open_terminal")),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
const call = (sessionID: string) =>
|
|
137
|
+
Effect.runPromise(
|
|
138
|
+
server.inLocation(
|
|
139
|
+
Mcp.Service.use((mcp) =>
|
|
140
|
+
mcp.callTool({ server: "tui", name: "open_terminal", sessionID: Session.ID.make(sessionID) }),
|
|
141
|
+
),
|
|
142
|
+
),
|
|
143
|
+
)
|
|
144
|
+
const result = yield* Effect.promise(() => call("ses_client_mcp"))
|
|
145
|
+
expect(result.content).toEqual([{ type: "text", text: "opened" }])
|
|
146
|
+
expect(client.sessions).toEqual(["ses_client_mcp"])
|
|
147
|
+
|
|
148
|
+
// A second client with the same name stacks on top: it takes the calls while the first stays open.
|
|
149
|
+
const newer = yield* connectClient(server.url({ name: "tui" }), { authorization })
|
|
150
|
+
yield* until(() => call("ses_newer").then(() => newer.sessions.length > 0))
|
|
151
|
+
expect(newer.sessions.every((session) => session === "ses_newer")).toBeTrue()
|
|
152
|
+
expect(client.state.closed).toBeFalse()
|
|
153
|
+
|
|
154
|
+
// Once the newest closes, calls fall back to the earlier client.
|
|
155
|
+
const before = client.sessions.length
|
|
156
|
+
newer.socket.close()
|
|
157
|
+
yield* until(() => newer.state.closed)
|
|
158
|
+
yield* until(() =>
|
|
159
|
+
call("ses_fallback").then(
|
|
160
|
+
() => client.sessions.length > before,
|
|
161
|
+
() => false,
|
|
162
|
+
),
|
|
163
|
+
)
|
|
164
|
+
expect(client.sessions.at(-1)).toBe("ses_fallback")
|
|
165
|
+
|
|
166
|
+
client.socket.close()
|
|
167
|
+
yield* until(async () => (await tools()).length === 0)
|
|
168
|
+
yield* until(() =>
|
|
169
|
+
Effect.runPromise(server.inLocation(registryIDs)).then((ids) => !ids.includes("tui_open_terminal")),
|
|
170
|
+
)
|
|
171
|
+
}),
|
|
172
|
+
20_000,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
it.live(
|
|
176
|
+
"closes a client MCP socket with 1012 on reload and reattaches to the fresh location",
|
|
177
|
+
() =>
|
|
178
|
+
Effect.gen(function* () {
|
|
179
|
+
const server = yield* serve()
|
|
180
|
+
const events: string[] = []
|
|
181
|
+
class RecordingWebSocket extends globalThis.WebSocket {
|
|
182
|
+
constructor(...args: ConstructorParameters<typeof globalThis.WebSocket>) {
|
|
183
|
+
super(...args)
|
|
184
|
+
this.addEventListener("close", (event) => events.push(`close ${event.code}`))
|
|
185
|
+
this.addEventListener("message", (event) => {
|
|
186
|
+
if (String(event.data).includes('"notifications/initialized"')) events.push("attached")
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const connection = yield* Effect.acquireRelease(
|
|
191
|
+
Effect.sync(() =>
|
|
192
|
+
connectClientMcp({
|
|
193
|
+
url: server.base,
|
|
194
|
+
name: "tui",
|
|
195
|
+
directory: server.directory,
|
|
196
|
+
headers: { authorization },
|
|
197
|
+
WebSocket: RecordingWebSocket,
|
|
198
|
+
tools: [{ name: "open_terminal", handler: () => ({ content: [{ type: "text", text: "opened" }] }) }],
|
|
199
|
+
}),
|
|
200
|
+
),
|
|
201
|
+
(connection) => Effect.promise(() => connection.close()),
|
|
202
|
+
)
|
|
203
|
+
yield* until(() => events.includes("attached"))
|
|
204
|
+
const locations = Context.get(server.context, LocationServiceMap.Service)
|
|
205
|
+
const ref = LocationServiceMap.canonical(Location.Ref.make({ directory: AbsolutePath.make(server.directory) }))
|
|
206
|
+
const entry = () =>
|
|
207
|
+
locations.rcMap.state._tag === "Open"
|
|
208
|
+
? Option.getOrUndefined(MutableHashMap.get(locations.rcMap.state.map, ref))
|
|
209
|
+
: undefined
|
|
210
|
+
const old = entry()
|
|
211
|
+
expect(old).toBeDefined()
|
|
212
|
+
// An attached client keeps the idle sweep away from its location.
|
|
213
|
+
const lifecycle = Context.get(yield* locations.contextEffect(ref).pipe(Effect.scoped), LocationLifecycle.Service)
|
|
214
|
+
expect(lifecycle.isRetained()).toBe(true)
|
|
215
|
+
|
|
216
|
+
const response = yield* Effect.promise(() =>
|
|
217
|
+
fetch(new URL("/api/location/reload", server.base), { method: "POST", headers: { authorization } }),
|
|
218
|
+
)
|
|
219
|
+
expect(response.status).toBe(204)
|
|
220
|
+
// The socket was the old location's last borrower, so closing it let the old location close.
|
|
221
|
+
yield* until(() => old?.scope.state._tag === "Closed")
|
|
222
|
+
// The client reconnected on its own and the replacement location attached it.
|
|
223
|
+
yield* until(() => events.length === 3)
|
|
224
|
+
expect(events).toEqual(["attached", "close 1012", "attached"])
|
|
225
|
+
expect(entry()).toBeDefined()
|
|
226
|
+
expect(entry()).not.toBe(old)
|
|
227
|
+
|
|
228
|
+
// Disconnect before the server stops, like the other tests here.
|
|
229
|
+
yield* Effect.promise(() => connection.close())
|
|
230
|
+
yield* until(() => events.length === 4)
|
|
231
|
+
}),
|
|
232
|
+
20_000,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
it.live(
|
|
236
|
+
"accepts a single-use ticket instead of credentials",
|
|
237
|
+
() =>
|
|
238
|
+
Effect.gen(function* () {
|
|
239
|
+
const server = yield* serve()
|
|
240
|
+
const requestToken = (name: string, headers: Record<string, string>) => {
|
|
241
|
+
const url = new URL("/api/experimental/client-mcp/token", server.base)
|
|
242
|
+
url.searchParams.set("location[directory]", server.directory)
|
|
243
|
+
url.searchParams.set("name", name)
|
|
244
|
+
return fetch(url, { method: "POST", headers })
|
|
245
|
+
}
|
|
246
|
+
const token = (name: string) =>
|
|
247
|
+
Effect.promise(async () => {
|
|
248
|
+
const response = await requestToken(name, { authorization, "x-opencode-ticket": "1" })
|
|
249
|
+
expect(response.status).toBe(200)
|
|
250
|
+
return ((await response.json()) as { data: { ticket: string } }).data.ticket
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
// Without the preflight-forcing header, a ticket cannot be minted even with credentials.
|
|
254
|
+
expect((yield* Effect.promise(() => requestToken("web", { authorization }))).status).toBe(403)
|
|
255
|
+
|
|
256
|
+
const unauthenticated = yield* connectClient(server.url({ name: "web" }))
|
|
257
|
+
yield* until(() => unauthenticated.state.closed)
|
|
258
|
+
expect(unauthenticated.state.open).toBeFalse()
|
|
259
|
+
|
|
260
|
+
const ticket = yield* token("web")
|
|
261
|
+
const mismatched = yield* connectClient(server.url({ name: "other", ticket }))
|
|
262
|
+
yield* until(() => mismatched.state.closed)
|
|
263
|
+
expect(mismatched.state.open).toBeFalse()
|
|
264
|
+
|
|
265
|
+
const otherDirectory = server.url({ name: "web", ticket: yield* token("web") })
|
|
266
|
+
otherDirectory.protocol = "http:"
|
|
267
|
+
otherDirectory.searchParams.set("location[directory]", path.join(server.directory, "other"))
|
|
268
|
+
expect((yield* Effect.promise(() => fetch(otherDirectory))).status).toBe(403)
|
|
269
|
+
|
|
270
|
+
const fresh = yield* token("web")
|
|
271
|
+
const client = yield* connectClient(server.url({ name: "web", ticket: fresh }))
|
|
272
|
+
yield* until(() =>
|
|
273
|
+
Effect.runPromise(server.inLocation(Mcp.Service.use((mcp) => mcp.tools()))).then((tools) =>
|
|
274
|
+
tools.some((tool) => tool.server === "web"),
|
|
275
|
+
),
|
|
276
|
+
)
|
|
277
|
+
expect(client.state.open).toBeTrue()
|
|
278
|
+
|
|
279
|
+
const reused = yield* connectClient(server.url({ name: "web", ticket: fresh }))
|
|
280
|
+
yield* until(() => reused.state.closed)
|
|
281
|
+
expect(reused.state.open).toBeFalse()
|
|
282
|
+
|
|
283
|
+
// The server's end of an accepted socket lives in the serving scope until the client disconnects.
|
|
284
|
+
client.socket.close()
|
|
285
|
+
yield* until(() => client.state.closed)
|
|
286
|
+
}),
|
|
287
|
+
20_000,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
it.live(
|
|
291
|
+
"rejects an invalid client name",
|
|
292
|
+
() =>
|
|
293
|
+
Effect.gen(function* () {
|
|
294
|
+
const server = yield* serve()
|
|
295
|
+
const url = server.url({ name: "bad name!" })
|
|
296
|
+
url.protocol = "http:"
|
|
297
|
+
const response = yield* Effect.promise(() => fetch(url, { headers: { authorization } }))
|
|
298
|
+
expect(response.status).toBe(400)
|
|
299
|
+
|
|
300
|
+
const client = yield* connectClient(server.url({ name: "bad.name" }), { authorization })
|
|
301
|
+
yield* until(() => client.state.closed)
|
|
302
|
+
expect(client.state.open).toBeFalse()
|
|
303
|
+
}),
|
|
304
|
+
20_000,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
it.live(
|
|
308
|
+
"closes with 1011 when the client rejects initialize",
|
|
309
|
+
() =>
|
|
310
|
+
Effect.gen(function* () {
|
|
311
|
+
const server = yield* serve()
|
|
312
|
+
const state = yield* Effect.acquireRelease(
|
|
313
|
+
Effect.sync(() => {
|
|
314
|
+
const socket = new WebSocket(server.url({ name: "tui" }), { headers: { authorization } })
|
|
315
|
+
const state = { socket, closed: false, code: 0 }
|
|
316
|
+
socket.addEventListener("message", (event) => {
|
|
317
|
+
const message = JSON.parse(String(event.data))
|
|
318
|
+
if (message.method !== "initialize") return
|
|
319
|
+
socket.send(
|
|
320
|
+
JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: "not today" } }),
|
|
321
|
+
)
|
|
322
|
+
})
|
|
323
|
+
socket.addEventListener("close", (event) => {
|
|
324
|
+
state.closed = true
|
|
325
|
+
state.code = event.code
|
|
326
|
+
})
|
|
327
|
+
return state
|
|
328
|
+
}),
|
|
329
|
+
(state) => Effect.sync(() => state.socket.close()),
|
|
330
|
+
)
|
|
331
|
+
yield* until(() => state.closed)
|
|
332
|
+
expect(state.code).toBe(1011)
|
|
333
|
+
}),
|
|
334
|
+
20_000,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
it.live(
|
|
338
|
+
"shuts the server down while a client is attached",
|
|
339
|
+
() =>
|
|
340
|
+
Effect.gen(function* () {
|
|
341
|
+
const directory = (yield* tmpdirScoped("opencode-client-mcp-")).path
|
|
342
|
+
// Released before the directory so the server lets go of it first; closing twice is a no-op.
|
|
343
|
+
const scope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void))
|
|
344
|
+
const server = yield* ServerProcess.start<never, never>(
|
|
345
|
+
{
|
|
346
|
+
hostname: "127.0.0.1",
|
|
347
|
+
port: 0,
|
|
348
|
+
password: "secret",
|
|
349
|
+
app: { version: "test-version" },
|
|
350
|
+
database: { path: ":memory:" },
|
|
351
|
+
models: { fetch: false },
|
|
352
|
+
config: { directory, project: false, content: "{}" },
|
|
353
|
+
fs: { filewatcher: false },
|
|
354
|
+
},
|
|
355
|
+
{ onListen: () => Effect.succeed(Effect.void) },
|
|
356
|
+
).pipe(Scope.provide(scope))
|
|
357
|
+
const url = new URL("/api/experimental/client-mcp", HttpServer.formatAddress(server.address))
|
|
358
|
+
url.protocol = "ws:"
|
|
359
|
+
url.searchParams.set("location[directory]", directory)
|
|
360
|
+
url.searchParams.set("name", "tui")
|
|
361
|
+
const client = yield* connectClient(url, { authorization })
|
|
362
|
+
yield* until(() => client.state.initialized)
|
|
363
|
+
|
|
364
|
+
const closed = yield* Scope.close(scope, Exit.void).pipe(Effect.timeoutOption("5 seconds"))
|
|
365
|
+
expect(closed._tag).toBe("Some")
|
|
366
|
+
yield* until(() => client.state.closed)
|
|
367
|
+
}),
|
|
368
|
+
20_000,
|
|
369
|
+
)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { expect } from "bun:test"
|
|
2
|
+
import fs from "node:fs/promises"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import { CodeModeApi } from "@zyro-sec/core/codemode/api"
|
|
5
|
+
import { CodeModeTool } from "@zyro-sec/core/codemode/tool"
|
|
6
|
+
import { Location } from "@zyro-sec/core/location"
|
|
7
|
+
import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
|
|
8
|
+
import { Permission } from "@zyro-sec/core/permission"
|
|
9
|
+
import { AbsolutePath } from "@zyro-sec/core/schema"
|
|
10
|
+
import { Tool } from "@zyro-sec/core/tool"
|
|
11
|
+
import { Agent } from "@zyro-sec/schema/agent"
|
|
12
|
+
import { Session } from "@zyro-sec/schema/session"
|
|
13
|
+
import { SessionMessage } from "@zyro-sec/schema/session-message"
|
|
14
|
+
import { Context, Effect, Layer, Schema } from "effect"
|
|
15
|
+
import { HttpEffect, HttpRouter, HttpServer } from "effect/http"
|
|
16
|
+
import { tmpdir } from "../../core/test/fixture/tmpdir"
|
|
17
|
+
import { it } from "../../core/test/lib/effect"
|
|
18
|
+
import { createRoutes } from "../src/routes"
|
|
19
|
+
|
|
20
|
+
it.live("sends Code Mode opencode:// requests to the server's own router with the server's credential", () =>
|
|
21
|
+
Effect.gen(function* () {
|
|
22
|
+
const root = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-codemode-api-")))
|
|
23
|
+
const directory = path.join(root.path, "project")
|
|
24
|
+
yield* Effect.promise(() => fs.mkdir(directory))
|
|
25
|
+
const app = yield* Layer.build(
|
|
26
|
+
createRoutes({
|
|
27
|
+
app: { version: "test-version" },
|
|
28
|
+
database: { path: ":memory:" },
|
|
29
|
+
config: { project: false, directory: root.path },
|
|
30
|
+
models: { fetch: false },
|
|
31
|
+
fs: { filewatcher: false },
|
|
32
|
+
password: "secret",
|
|
33
|
+
}).pipe(Layer.provide(HttpServer.layerServices)),
|
|
34
|
+
)
|
|
35
|
+
const handler = Context.get(app, HttpRouter.HttpRouter).asHttpEffect().pipe(HttpEffect.toWebHandlerWith(app))
|
|
36
|
+
expect((yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))).status).toBe(401)
|
|
37
|
+
|
|
38
|
+
const created = yield* Effect.promise(() =>
|
|
39
|
+
handler(
|
|
40
|
+
new Request("http://opencode.local/api/session", {
|
|
41
|
+
method: "POST",
|
|
42
|
+
headers: { "content-type": "application/json", authorization: `Basic ${btoa("opencode:secret")}` },
|
|
43
|
+
// opencode:// asks as the opencode api command, so the session allows it without a prompt.
|
|
44
|
+
body: JSON.stringify({
|
|
45
|
+
location: { directory },
|
|
46
|
+
permissions: [{ action: "*", resource: "*", effect: "allow" }],
|
|
47
|
+
}),
|
|
48
|
+
}),
|
|
49
|
+
).then((response) => response.json()),
|
|
50
|
+
)
|
|
51
|
+
const parent = Schema.decodeUnknownSync(Schema.Struct({ data: Session.Info }))(created).data
|
|
52
|
+
const locations = Context.get(app, LocationServiceMap.Service)
|
|
53
|
+
const result = yield* Effect.gen(function* () {
|
|
54
|
+
const permission = yield* Permission.Service
|
|
55
|
+
const api = Context.make(CodeModeApi.Service, Context.get(app, CodeModeApi.Service)).pipe(
|
|
56
|
+
Context.add(Location.Service, yield* Location.Service),
|
|
57
|
+
)
|
|
58
|
+
return yield* CodeModeTool.create(
|
|
59
|
+
{ tools: new Map() },
|
|
60
|
+
() => Effect.die("The program calls no tools."),
|
|
61
|
+
permission,
|
|
62
|
+
undefined,
|
|
63
|
+
api,
|
|
64
|
+
).execute(
|
|
65
|
+
{
|
|
66
|
+
code: `const info = await (await fetch("opencode:///api/info")).json()
|
|
67
|
+
const location = await (await fetch("opencode:///api/location")).json()
|
|
68
|
+
const child = await (await fetch("opencode:///api/session", {
|
|
69
|
+
method: "POST",
|
|
70
|
+
headers: { "content-type": "application/json" },
|
|
71
|
+
body: JSON.stringify({ title: "child", parentID: (await (await fetch("opencode:///api/session/current")).json()).data.id }),
|
|
72
|
+
})).json()
|
|
73
|
+
return [info.version, location.directory, child.data.title, child.data.parentID]`,
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
sessionID: parent.id,
|
|
77
|
+
agent: Agent.ID.make("build"),
|
|
78
|
+
messageID: SessionMessage.ID.create(),
|
|
79
|
+
id: Tool.CallID.make("call_opencode_api"),
|
|
80
|
+
progress: () => Effect.void,
|
|
81
|
+
},
|
|
82
|
+
)
|
|
83
|
+
}).pipe(Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(directory) }))))
|
|
84
|
+
|
|
85
|
+
expect(result.output.error, result.output.output).toBeUndefined()
|
|
86
|
+
expect(JSON.parse(result.output.output)).toEqual(["test-version", directory, "child", parent.id])
|
|
87
|
+
}),
|
|
88
|
+
)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import fs from "node:fs/promises"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
import { expect } from "bun:test"
|
|
4
|
+
import { Config } from "@zyro-sec/schema/config"
|
|
5
|
+
import { Effect, Schema } from "effect"
|
|
6
|
+
import { tmpdir } from "../../core/test/fixture/tmpdir"
|
|
7
|
+
import { it } from "../../core/test/lib/effect"
|
|
8
|
+
import { startServer } from "./fixture/server"
|
|
9
|
+
import { AbsolutePath } from "@zyro-sec/schema/schema"
|
|
10
|
+
|
|
11
|
+
it.live("returns ordered config entries for the requested directory", () =>
|
|
12
|
+
Effect.gen(function* () {
|
|
13
|
+
const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-config-endpoint-")))
|
|
14
|
+
const global = path.join(tmp.path, "global")
|
|
15
|
+
const project = path.join(tmp.path, "project")
|
|
16
|
+
const config = path.join(project, "opencode.json")
|
|
17
|
+
yield* Effect.promise(() =>
|
|
18
|
+
Promise.all([fs.mkdir(global, { recursive: true }), fs.mkdir(project, { recursive: true })]),
|
|
19
|
+
)
|
|
20
|
+
yield* Effect.promise(() =>
|
|
21
|
+
fs.writeFile(
|
|
22
|
+
config,
|
|
23
|
+
JSON.stringify({
|
|
24
|
+
permissions: [
|
|
25
|
+
{ action: "shell", resource: "*", effect: "ask" },
|
|
26
|
+
{ action: "shell", resource: "git status", effect: "allow" },
|
|
27
|
+
],
|
|
28
|
+
mcp: { servers: { docs: { type: "remote", url: "https://example.com/mcp" } } },
|
|
29
|
+
}),
|
|
30
|
+
),
|
|
31
|
+
)
|
|
32
|
+
const server = yield* startServer(global)
|
|
33
|
+
const url = new URL("/api/config", server.base)
|
|
34
|
+
url.searchParams.set("location[directory]", project)
|
|
35
|
+
const response = yield* Effect.promise(() => fetch(url, { headers: server.headers }))
|
|
36
|
+
const body: unknown = yield* Effect.promise(() => response.json())
|
|
37
|
+
const entries = Schema.decodeUnknownSync(Schema.Array(Config.Entry))(body)
|
|
38
|
+
|
|
39
|
+
expect(response.status).toBe(200)
|
|
40
|
+
expect(Array.isArray(entries)).toBe(true)
|
|
41
|
+
const document = entries.find(
|
|
42
|
+
(entry): entry is Config.Document => entry.type === "document" && entry.path === config,
|
|
43
|
+
)
|
|
44
|
+
expect(document?.info.permissions).toEqual([
|
|
45
|
+
{ action: "shell", resource: "*", effect: "ask" },
|
|
46
|
+
{ action: "shell", resource: "git status", effect: "allow" },
|
|
47
|
+
])
|
|
48
|
+
expect(document?.path).toBe(AbsolutePath.make(config))
|
|
49
|
+
if (!Array.isArray(body)) throw new Error("Expected a config entry array")
|
|
50
|
+
const raw = body.find((entry) => isRecord(entry) && entry["type"] === "document" && entry["path"] === config)
|
|
51
|
+
if (!isRecord(raw) || !isRecord(raw["info"])) throw new Error("Expected a config document")
|
|
52
|
+
expect(raw["info"]).not.toHaveProperty("default_agent")
|
|
53
|
+
expect(raw["info"]).not.toHaveProperty("model")
|
|
54
|
+
const mcp = raw["info"]["mcp"]
|
|
55
|
+
if (!isRecord(mcp) || !isRecord(mcp["servers"]) || !isRecord(mcp["servers"]["docs"]))
|
|
56
|
+
throw new Error("Expected an MCP server config")
|
|
57
|
+
expect(mcp["servers"]["docs"]).not.toHaveProperty("headers")
|
|
58
|
+
expect(mcp["servers"]["docs"]).not.toHaveProperty("oauth")
|
|
59
|
+
}),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
it.live("updates the global shell without replacing unrelated JSONC", () =>
|
|
63
|
+
Effect.gen(function* () {
|
|
64
|
+
const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-config-shells-")))
|
|
65
|
+
const global = path.join(tmp.path, "global")
|
|
66
|
+
const config = path.join(global, "opencode.jsonc")
|
|
67
|
+
yield* Effect.promise(() => fs.mkdir(global, { recursive: true }))
|
|
68
|
+
yield* Effect.promise(() =>
|
|
69
|
+
fs.writeFile(
|
|
70
|
+
config,
|
|
71
|
+
`{
|
|
72
|
+
// keep this comment
|
|
73
|
+
"model": "provider/model",
|
|
74
|
+
"shell": "bash"
|
|
75
|
+
}
|
|
76
|
+
`,
|
|
77
|
+
),
|
|
78
|
+
)
|
|
79
|
+
const server = yield* startServer(global)
|
|
80
|
+
const response = yield* Effect.promise(() =>
|
|
81
|
+
fetch(new URL("/api/experimental/config", server.base), {
|
|
82
|
+
method: "PATCH",
|
|
83
|
+
headers: { ...server.headers, "content-type": "application/json" },
|
|
84
|
+
body: JSON.stringify({ shell: "/bin/zsh" }),
|
|
85
|
+
}),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
expect(response.status).toBe(204)
|
|
89
|
+
const text = yield* Effect.promise(() => fs.readFile(config, "utf8"))
|
|
90
|
+
expect(text).toContain("// keep this comment")
|
|
91
|
+
expect(text).toContain('"model": "provider/model"')
|
|
92
|
+
expect(text).toContain('"shell": "/bin/zsh"')
|
|
93
|
+
|
|
94
|
+
const shells = yield* Effect.promise(() =>
|
|
95
|
+
fetch(new URL("/api/config/shell", server.base), { headers: server.headers }),
|
|
96
|
+
)
|
|
97
|
+
expect(shells.status).toBe(200)
|
|
98
|
+
expect(Array.isArray(yield* Effect.promise(() => shells.json()))).toBe(true)
|
|
99
|
+
}),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
103
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
104
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { isAllowedCorsOrigin, isAllowedRequestOrigin } from "../src/cors"
|
|
3
|
+
|
|
4
|
+
test("custom origins extend the defaults without allowing other origins", () => {
|
|
5
|
+
const options = { cors: ["http://192.168.1.10:3001", "https://example.com"] }
|
|
6
|
+
expect(isAllowedCorsOrigin("http://192.168.1.10:3001")).toBe(false)
|
|
7
|
+
expect(isAllowedCorsOrigin("http://192.168.1.10:3001", options)).toBe(true)
|
|
8
|
+
expect(isAllowedCorsOrigin("https://example.com", options)).toBe(true)
|
|
9
|
+
expect(isAllowedCorsOrigin("http://localhost:3001", options)).toBe(true)
|
|
10
|
+
expect(isAllowedCorsOrigin("https://app.opencode.ai", options)).toBe(true)
|
|
11
|
+
expect(isAllowedCorsOrigin(undefined, options)).toBe(true)
|
|
12
|
+
expect(isAllowedCorsOrigin("http://192.168.1.10:3002", options)).toBe(false)
|
|
13
|
+
expect(isAllowedCorsOrigin("https://example.com.evil.test", options)).toBe(false)
|
|
14
|
+
expect(isAllowedCorsOrigin("http://example.com", options)).toBe(false)
|
|
15
|
+
expect(isAllowedCorsOrigin("null", options)).toBe(false)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
test("PTY origin checks use the same allowlist and retain same-host access", () => {
|
|
19
|
+
const options = { cors: ["http://192.168.1.10:3001"] }
|
|
20
|
+
expect(isAllowedRequestOrigin("http://192.168.1.10:3001", "192.168.1.10:1029")).toBe(false)
|
|
21
|
+
expect(isAllowedRequestOrigin("http://192.168.1.10:3001", "192.168.1.10:1029", options)).toBe(true)
|
|
22
|
+
expect(isAllowedRequestOrigin("http://192.168.1.10:1029", "192.168.1.10:1029", options)).toBe(true)
|
|
23
|
+
expect(isAllowedRequestOrigin("http://192.168.1.10:3002", "192.168.1.10:1029", options)).toBe(false)
|
|
24
|
+
})
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { expect } from "bun:test"
|
|
3
|
+
import { OpenCode } from "@zyro-sec/client"
|
|
4
|
+
import { Database } from "@zyro-sec/core/database/database"
|
|
5
|
+
import { Global } from "@zyro-sec/util/global"
|
|
6
|
+
import { Context, Effect } from "effect"
|
|
7
|
+
import { tempGlobalLayer } from "../../core/test/fixture/global"
|
|
8
|
+
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
|
9
|
+
import { it } from "../../core/test/lib/effect"
|
|
10
|
+
import { serveRoutes } from "./fixture/routes"
|
|
11
|
+
|
|
12
|
+
const large = "x".repeat(60_000)
|
|
13
|
+
|
|
14
|
+
const boot = Effect.gen(function* () {
|
|
15
|
+
const dir = yield* tmpdirScoped("opencode-defect-response-")
|
|
16
|
+
const server = yield* serveRoutes(
|
|
17
|
+
{
|
|
18
|
+
app: { version: "test" },
|
|
19
|
+
database: { path: path.join(dir.path, "opencode.db") },
|
|
20
|
+
models: { fetch: false },
|
|
21
|
+
fs: { filewatcher: false },
|
|
22
|
+
},
|
|
23
|
+
[Global.node.replace(tempGlobalLayer)],
|
|
24
|
+
)
|
|
25
|
+
const db = Context.get(server.context, Database.Service).db
|
|
26
|
+
return {
|
|
27
|
+
db,
|
|
28
|
+
location: { directory: dir.path },
|
|
29
|
+
request: (method: string, route: string, body?: unknown) =>
|
|
30
|
+
Effect.promise(async () => {
|
|
31
|
+
const response = await server.fetch(`http://opencode.local${route}`, {
|
|
32
|
+
method,
|
|
33
|
+
headers: { "content-type": "application/json" },
|
|
34
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
35
|
+
})
|
|
36
|
+
return { status: response.status, body: await response.text() }
|
|
37
|
+
}),
|
|
38
|
+
api: OpenCode.make({
|
|
39
|
+
baseUrl: "http://opencode.local",
|
|
40
|
+
fetch: Object.assign(
|
|
41
|
+
(input: string | URL | Request, init?: RequestInit) => server.handler(new Request(input, init)),
|
|
42
|
+
{ preconnect: fetch.preconnect },
|
|
43
|
+
),
|
|
44
|
+
}),
|
|
45
|
+
}
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it.live("a write on a full disk answers 500 with the storage reason instead of an empty body", () =>
|
|
49
|
+
Effect.gen(function* () {
|
|
50
|
+
const server = yield* boot
|
|
51
|
+
const session = yield* Effect.promise(() => server.api.session.create({ location: server.location }))
|
|
52
|
+
// A real SQLITE_FULL: SQLite never lowers the limit below the current size, so 1 means the database may not grow
|
|
53
|
+
// and a write that needs a new page fails.
|
|
54
|
+
yield* server.db.run("PRAGMA max_page_count = 1").pipe(Effect.orDie)
|
|
55
|
+
|
|
56
|
+
const prompt = yield* server.request("POST", `/api/session/${session.id}/prompt`, { text: large })
|
|
57
|
+
expect(prompt.status).toBe(500)
|
|
58
|
+
expect(JSON.parse(prompt.body)).toEqual({
|
|
59
|
+
_tag: "UnknownError",
|
|
60
|
+
message: "Storage is full",
|
|
61
|
+
ref: expect.stringMatching(/^err_[0-9a-f]{8}$/),
|
|
62
|
+
})
|
|
63
|
+
}),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
it.live("other defects answer 500 with a ref, and unknown routes keep their 404", () =>
|
|
67
|
+
Effect.gen(function* () {
|
|
68
|
+
const server = yield* boot
|
|
69
|
+
const session = yield* Effect.promise(() => server.api.session.create({ location: server.location }))
|
|
70
|
+
// A query that is simply wrong is a bug, not a storage failure: an empty table shadows the sessions.
|
|
71
|
+
yield* server.db.run("CREATE TEMP TABLE session_v2 (shadow text)").pipe(Effect.orDie)
|
|
72
|
+
const read = yield* server.request("GET", `/api/session/${session.id}`)
|
|
73
|
+
yield* server.db.run("DROP TABLE temp.session_v2").pipe(Effect.orDie)
|
|
74
|
+
expect(read.status).toBe(500)
|
|
75
|
+
expect(JSON.parse(read.body)).toEqual({
|
|
76
|
+
_tag: "UnknownError",
|
|
77
|
+
message: "Server failed to handle the request. Check server logs for details.",
|
|
78
|
+
ref: expect.stringMatching(/^err_[0-9a-f]{8}$/),
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
expect((yield* server.request("GET", "/api/does-not-exist")).status).toBe(404)
|
|
82
|
+
}),
|
|
83
|
+
)
|