@zyro-sec/server 1.0.2 → 1.0.3
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 +8 -8
- package/script/build.ts +28 -28
- package/script/pack.ts +5 -5
- package/script/workerd-probe.ts +59 -59
- package/src/api.ts +12 -12
- package/src/auth.ts +70 -70
- package/src/content-headers.ts +32 -32
- package/src/cors.ts +34 -34
- package/src/event-feed.ts +93 -93
- package/src/fetch.ts +67 -67
- package/src/handlers/agent.ts +23 -23
- package/src/handlers/artifact.ts +242 -242
- package/src/handlers/automation.ts +63 -63
- package/src/handlers/blob.ts +55 -55
- package/src/handlers/command.ts +8 -8
- package/src/handlers/config.ts +26 -26
- package/src/handlers/credential.ts +87 -87
- package/src/handlers/debug.ts +57 -57
- package/src/handlers/event.ts +38 -38
- package/src/handlers/form.ts +15 -15
- package/src/handlers/fs.ts +180 -180
- package/src/handlers/generate.ts +117 -117
- package/src/handlers/integration.ts +310 -310
- package/src/handlers/job.ts +29 -29
- package/src/handlers/location.ts +33 -33
- package/src/handlers/machine.ts +336 -336
- package/src/handlers/mcp.ts +160 -160
- package/src/handlers/media.ts +44 -44
- package/src/handlers/message.ts +82 -82
- package/src/handlers/migration.ts +13 -13
- package/src/handlers/model.ts +25 -25
- package/src/handlers/permission.ts +131 -131
- package/src/handlers/persistent-pty.ts +285 -285
- package/src/handlers/plugin.ts +97 -97
- package/src/handlers/project.ts +23 -23
- package/src/handlers/provider.ts +32 -32
- package/src/handlers/pty-socket.ts +47 -47
- package/src/handlers/pty.ts +181 -181
- package/src/handlers/push.ts +67 -67
- package/src/handlers/reference.ts +8 -8
- package/src/handlers/rpc.ts +31 -31
- package/src/handlers/server.ts +58 -58
- package/src/handlers/session-error.ts +47 -47
- package/src/handlers/session.ts +722 -722
- package/src/handlers/shell.ts +72 -72
- package/src/handlers/skill.ts +34 -34
- package/src/handlers/usage.ts +23 -23
- package/src/handlers/vcs.ts +104 -104
- package/src/handlers/voice.ts +50 -50
- package/src/handlers/websearch.ts +50 -50
- package/src/handlers/worktree.ts +60 -60
- package/src/handlers.ts +69 -69
- package/src/location.ts +86 -86
- package/src/media-uri.ts +13 -13
- package/src/middleware/authorization.ts +111 -111
- package/src/middleware/defect-response.ts +39 -39
- package/src/middleware/form-location.ts +44 -44
- package/src/middleware/schema-error.ts +49 -49
- package/src/middleware/session-location.ts +30 -30
- package/src/options.ts +61 -61
- package/src/pairing.ts +36 -36
- package/src/process.ts +274 -274
- package/src/range.ts +16 -16
- package/src/request-site.ts +36 -36
- package/src/request-tracing.ts +9 -9
- package/src/routes.ts +261 -261
- package/src/server-info.ts +41 -41
- package/src/service-status.ts +30 -30
- package/src/workerd.ts +184 -184
- package/test/fixture/mcp-starts.cjs +20 -20
- package/test/fixture/routes.ts +37 -37
- package/test/fixture/server.ts +20 -20
- package/test/fixture/worktree-delegate/index.ts +13 -13
- package/test/fixture/worktree-plugin/index.ts +47 -47
- package/tsconfig.build.json +15 -15
- package/tsconfig.json +11 -11
- package/test/artifact.test.ts +0 -224
- package/test/auth.test.ts +0 -24
- package/test/automation.test.ts +0 -315
- package/test/client-mcp.test.ts +0 -369
- package/test/codemode-api.test.ts +0 -88
- package/test/config.test.ts +0 -104
- package/test/cors.test.ts +0 -24
- package/test/defect-response.test.ts +0 -83
- package/test/event-feed.test.ts +0 -201
- package/test/fetch-option.test.ts +0 -104
- package/test/fetch.test.ts +0 -698
- package/test/flag-channel.test.ts +0 -126
- package/test/fs.test.ts +0 -439
- package/test/generate.test.ts +0 -132
- package/test/handler-policy.test.ts +0 -43
- package/test/heap-dump.test.ts +0 -137
- package/test/integration-policy.test.ts +0 -93
- package/test/job.test.ts +0 -186
- package/test/machine-iroh.test.ts +0 -259
- package/test/machine-link.test.ts +0 -1234
- package/test/machine-routes.test.ts +0 -198
- package/test/media.test.ts +0 -343
- package/test/message.test.ts +0 -105
- package/test/model.test.ts +0 -62
- package/test/options.test.ts +0 -42
- package/test/permission-saved.test.ts +0 -73
- package/test/persistent-pty.test.ts +0 -1007
- package/test/process.test.ts +0 -261
- package/test/provider.test.ts +0 -88
- package/test/pty-socket.property.test.ts +0 -240
- package/test/pty-socket.test.ts +0 -89
- package/test/pty-transport.test.ts +0 -200
- package/test/push-routes.test.ts +0 -157
- package/test/request-site.test.ts +0 -71
- package/test/request-tracing.test.ts +0 -87
- package/test/rpc-handler-errors.test.ts +0 -76
- package/test/schema-error.test.ts +0 -68
- package/test/service-status.test.ts +0 -34
- package/test/session-admit-location.test.ts +0 -92
- package/test/session-create.test.ts +0 -65
- package/test/session-diff.test.ts +0 -100
- package/test/session-form.test.ts +0 -50
- package/test/session-import.test.ts +0 -152
- package/test/session-instances.test.ts +0 -335
- package/test/session-unarchive.test.ts +0 -73
- package/test/session-update.test.ts +0 -66
- package/test/skill.test.ts +0 -57
- package/test/sse-failure.test.ts +0 -71
- package/test/usage.test.ts +0 -88
- package/test/vcs.test.ts +0 -356
- package/test/video-generate.test.ts +0 -131
- package/test/voice.test.ts +0 -170
- package/test/workerd.test.ts +0 -227
- package/test/worktree.test.ts +0 -333
package/src/process.ts
CHANGED
|
@@ -1,274 +1,274 @@
|
|
|
1
|
-
export * as ServerProcess from "./process"
|
|
2
|
-
|
|
3
|
-
import { NodeHttpServer } from "@effect/platform-node"
|
|
4
|
-
import { Bus } from "@zyro-sec/core/bus"
|
|
5
|
-
import { SessionRestart } from "@zyro-sec/core/session/execution/restart"
|
|
6
|
-
import { Automation } from "@zyro-sec/core/automation"
|
|
7
|
-
import { SessionSearchBuild } from "@zyro-sec/core/session/search-build"
|
|
8
|
-
import { InstallationEvent } from "@zyro-sec/schema/installation-event"
|
|
9
|
-
import { hasPtyConnectTicketURL } from "@zyro-sec/protocol/groups/pty"
|
|
10
|
-
import { hasPersistentPtyConnectTicketURL } from "@zyro-sec/protocol/groups/persistent-pty"
|
|
11
|
-
import { hasMcpClientTicketURL } from "@zyro-sec/protocol/groups/mcp"
|
|
12
|
-
import { isMachineLinkUpgrade } from "@zyro-sec/protocol/groups/machine"
|
|
13
|
-
import { isPairingConnectURL } from "@zyro-sec/protocol/groups/server"
|
|
14
|
-
import { Global } from "@zyro-sec/util/global"
|
|
15
|
-
import { Cause, Context, Effect, Exit, Latch, Layer, Option, Ref, Scope } from "effect"
|
|
16
|
-
import { HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
|
|
17
|
-
import { NetAddress } from "effect/net"
|
|
18
|
-
import { createServer } from "node:http"
|
|
19
|
-
import { ServerAuth } from "./auth"
|
|
20
|
-
import { isAllowedCorsOrigin } from "./cors"
|
|
21
|
-
import { machinesEnabled } from "./handlers/machine"
|
|
22
|
-
import { authorizedRequest, unauthorizedResponse } from "./middleware/authorization"
|
|
23
|
-
import { withoutParentSpan } from "./request-tracing"
|
|
24
|
-
import { RequestSite } from "./request-site"
|
|
25
|
-
import { createRoutes } from "./routes"
|
|
26
|
-
import { ServerInfo } from "./server-info"
|
|
27
|
-
import { Status } from "./service-status"
|
|
28
|
-
import type { ServerOptions } from "./options"
|
|
29
|
-
|
|
30
|
-
export interface Lifecycle<E = never, R = never> {
|
|
31
|
-
readonly onListen: (
|
|
32
|
-
address: NetAddress.SocketAddress,
|
|
33
|
-
shutdown: Effect.Effect<void>,
|
|
34
|
-
) => Effect.Effect<Effect.Effect<void>, E, R>
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
type App = Effect.Effect<
|
|
38
|
-
HttpServerResponse.HttpServerResponse,
|
|
39
|
-
unknown,
|
|
40
|
-
HttpServerRequest.HttpServerRequest | Scope.Scope
|
|
41
|
-
>
|
|
42
|
-
|
|
43
|
-
export type Transform = (app: App) => App
|
|
44
|
-
|
|
45
|
-
const errorResponseLogger = HttpMiddleware.make((app) =>
|
|
46
|
-
HttpMiddleware.logger(
|
|
47
|
-
Effect.tap(app, (response) =>
|
|
48
|
-
response.status < 400 ? HttpMiddleware.withLoggerDisabled(Effect.void) : Effect.void,
|
|
49
|
-
),
|
|
50
|
-
),
|
|
51
|
-
)
|
|
52
|
-
|
|
53
|
-
export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
|
|
54
|
-
options: ServerOptions,
|
|
55
|
-
lifecycle?: Lifecycle<E, R>,
|
|
56
|
-
transform?: Transform,
|
|
57
|
-
remoteURLs?: () => ReadonlyArray<string>,
|
|
58
|
-
) {
|
|
59
|
-
const password = options.password
|
|
60
|
-
if (!password) return yield* Effect.fail(new Error("Missing server password"))
|
|
61
|
-
const hostname = options.hostname ?? "127.0.0.1"
|
|
62
|
-
const port = Option.fromNullishOr(options.port)
|
|
63
|
-
const shutdown = yield* Latch.make()
|
|
64
|
-
const status = yield* Status.make()
|
|
65
|
-
const bound = yield* listen({ hostname, port })
|
|
66
|
-
const localURLs = () => {
|
|
67
|
-
const address = bound.server.address()
|
|
68
|
-
if (address === null || typeof address === "string") return []
|
|
69
|
-
const host = address.family === "IPv6" ? `[${address.address}]` : address.address
|
|
70
|
-
return ServerInfo.connectionURLs(`http://${host}:${address.port}`, hostname)
|
|
71
|
-
}
|
|
72
|
-
const urls = () => [...localURLs(), ...(remoteURLs?.() ?? [])]
|
|
73
|
-
const application = yield* Ref.make(Option.none<App>())
|
|
74
|
-
// Off until the routes are up, which is when the flag can be read.
|
|
75
|
-
const machinesFlag = yield* Ref.make(Effect.succeed(false))
|
|
76
|
-
const app = dispatch(
|
|
77
|
-
password,
|
|
78
|
-
status,
|
|
79
|
-
application,
|
|
80
|
-
machinesFlag,
|
|
81
|
-
options.app?.version ?? "unknown",
|
|
82
|
-
urls,
|
|
83
|
-
Global.Path.tmp,
|
|
84
|
-
)
|
|
85
|
-
// Request fibers may continue inbound trace context, but must not inherit the server startup parent.
|
|
86
|
-
yield* bound.http
|
|
87
|
-
.serve(
|
|
88
|
-
(transform ? transform(app) : app).pipe(
|
|
89
|
-
RequestSite.middleware(options),
|
|
90
|
-
HttpMiddleware.compression(),
|
|
91
|
-
HttpMiddleware.cors({ allowedOrigins: (origin) => isAllowedCorsOrigin(origin, options), maxAge: 86_400 }),
|
|
92
|
-
),
|
|
93
|
-
errorResponseLogger,
|
|
94
|
-
)
|
|
95
|
-
.pipe(Effect.provide(NodeHttpServer.layerHttpServices), withoutParentSpan)
|
|
96
|
-
if (lifecycle)
|
|
97
|
-
yield* lifecycle.onListen(bound.http.address, shutdown.open.pipe(Effect.asVoid)).pipe(
|
|
98
|
-
Effect.flatMap((cleanup) =>
|
|
99
|
-
Effect.addFinalizer(() => Scope.close(bound.scope, Exit.void).pipe(Effect.andThen(cleanup))),
|
|
100
|
-
),
|
|
101
|
-
Effect.uninterruptible,
|
|
102
|
-
)
|
|
103
|
-
|
|
104
|
-
const parentScope = yield* Scope.Scope
|
|
105
|
-
const applicationScope = yield* Scope.fork(parentScope)
|
|
106
|
-
yield* Effect.addFinalizer(() =>
|
|
107
|
-
status.beginStopping.pipe(
|
|
108
|
-
Effect.andThen(Ref.set(application, Option.none())),
|
|
109
|
-
Effect.andThen(Effect.sync(() => bound.server.closeAllConnections())),
|
|
110
|
-
),
|
|
111
|
-
)
|
|
112
|
-
|
|
113
|
-
// Built without the startup span: route handlers and background fibers capture this context, and would
|
|
114
|
-
// otherwise nest every request and session turn for the life of the process under one trace.
|
|
115
|
-
const boot = Effect.gen(function* () {
|
|
116
|
-
const context = yield* Layer.buildWithScope(
|
|
117
|
-
createRoutes(
|
|
118
|
-
{
|
|
119
|
-
...options,
|
|
120
|
-
password,
|
|
121
|
-
},
|
|
122
|
-
urls,
|
|
123
|
-
).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
|
|
124
|
-
applicationScope,
|
|
125
|
-
)
|
|
126
|
-
if (lifecycle) {
|
|
127
|
-
yield* installRestartContinuity(Context.get(context, SessionRestart.Service)).pipe(
|
|
128
|
-
Effect.provideService(Scope.Scope, applicationScope),
|
|
129
|
-
)
|
|
130
|
-
}
|
|
131
|
-
// Automations run from any server process (`service`, `opencode serve`, or `--standalone`); the table holds all their state.
|
|
132
|
-
yield* Effect.forkIn(Context.get(context, Automation.Service).run, applicationScope)
|
|
133
|
-
// Likewise the one-time session search build, once a location has sqlite_fts on.
|
|
134
|
-
yield* Effect.forkIn(Context.get(context, SessionSearchBuild.Service).run, applicationScope)
|
|
135
|
-
yield* Ref.set(machinesFlag, yield* machinesEnabled.pipe(Effect.provide(context)))
|
|
136
|
-
yield* Ref.set(application, Option.some(Context.get(context, HttpRouter.HttpRouter).asHttpEffect()))
|
|
137
|
-
yield* status.ready
|
|
138
|
-
const bus = Context.get(context, Bus.Service)
|
|
139
|
-
return {
|
|
140
|
-
address: bound.http.address,
|
|
141
|
-
shutdown: shutdown.await,
|
|
142
|
-
updateAvailable: (version: string) =>
|
|
143
|
-
bus.publish(InstallationEvent.UpdateAvailable, { version }).pipe(Effect.asVoid),
|
|
144
|
-
updated: (version: string) => bus.publish(InstallationEvent.Updated, { version }).pipe(Effect.asVoid),
|
|
145
|
-
}
|
|
146
|
-
}).pipe(
|
|
147
|
-
withoutParentSpan,
|
|
148
|
-
Effect.catchCause((cause) => {
|
|
149
|
-
if (!lifecycle || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause)
|
|
150
|
-
return status.fail.pipe(
|
|
151
|
-
Effect.andThen(
|
|
152
|
-
Scope.close(applicationScope, Exit.failCause(cause)).pipe(
|
|
153
|
-
Effect.catchCause((cleanupCause) =>
|
|
154
|
-
Effect.logError("failed to clean up background service boot", { cause: cleanupCause }),
|
|
155
|
-
),
|
|
156
|
-
),
|
|
157
|
-
),
|
|
158
|
-
Effect.andThen(Effect.logError("background service boot failed", { cause })),
|
|
159
|
-
Effect.andThen(Effect.never),
|
|
160
|
-
)
|
|
161
|
-
}),
|
|
162
|
-
)
|
|
163
|
-
if (!lifecycle) return yield* boot
|
|
164
|
-
return yield* Effect.raceFirst(boot, shutdown.await.pipe(Effect.andThen(Effect.interrupt)))
|
|
165
|
-
})
|
|
166
|
-
|
|
167
|
-
function listen(options: { readonly hostname: string; readonly port: Option.Option<number> }) {
|
|
168
|
-
if (Option.isSome(options.port)) return bind(options.hostname, options.port.value)
|
|
169
|
-
const next = (port: number): ReturnType<typeof bind> =>
|
|
170
|
-
bind(options.hostname, port).pipe(
|
|
171
|
-
Effect.catch((error) => (port < 65_535 && addressInUse(error) ? next(port + 1) : Effect.fail(error))),
|
|
172
|
-
)
|
|
173
|
-
return next(4096)
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
function bind(hostname: string, port: number) {
|
|
177
|
-
return Effect.gen(function* () {
|
|
178
|
-
const parentScope = yield* Scope.Scope
|
|
179
|
-
const serverScope = yield* Scope.fork(parentScope)
|
|
180
|
-
const server = createServer()
|
|
181
|
-
return yield* Effect.gen(function* () {
|
|
182
|
-
const http = yield* NodeHttpServer.make(() => server, { port, host: hostname })
|
|
183
|
-
yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
|
|
184
|
-
return { http, server, scope: serverScope }
|
|
185
|
-
}).pipe(
|
|
186
|
-
Effect.provideService(Scope.Scope, serverScope),
|
|
187
|
-
Effect.onError((cause) => Scope.close(serverScope, Exit.failCause(cause))),
|
|
188
|
-
)
|
|
189
|
-
})
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
function addressInUse(error: unknown) {
|
|
193
|
-
if (typeof error !== "object" || error === null || !("cause" in error)) return false
|
|
194
|
-
const cause = error.cause
|
|
195
|
-
return typeof cause === "object" && cause !== null && "code" in cause && cause.code === "EADDRINUSE"
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function dispatch(
|
|
199
|
-
password: string,
|
|
200
|
-
status: Status.Interface,
|
|
201
|
-
application: Ref.Ref<Option.Option<App>>,
|
|
202
|
-
machinesFlag: Ref.Ref<Effect.Effect<boolean>>,
|
|
203
|
-
version: string,
|
|
204
|
-
urls: () => ReadonlyArray<string>,
|
|
205
|
-
tmp: string,
|
|
206
|
-
): App {
|
|
207
|
-
const auth = ServerAuth.Config.of({ password: Option.some(password), username: "zyrosec" })
|
|
208
|
-
return Effect.gen(function* () {
|
|
209
|
-
const request = yield* HttpServerRequest.HttpServerRequest
|
|
210
|
-
const url = new URL(request.url, "http://localhost")
|
|
211
|
-
const state = yield* status.current
|
|
212
|
-
const app = yield* Ref.get(application)
|
|
213
|
-
const machines = yield* Ref.get(machinesFlag)
|
|
214
|
-
const ready = state.type === "ready" && Option.isSome(app)
|
|
215
|
-
if (request.method === "GET" && url.pathname === "/api/info" && !ready) {
|
|
216
|
-
if (!(yield* authorizedRequest(request, auth))) return unauthorizedResponse(request)
|
|
217
|
-
return yield* infoResponse(status, version, urls, tmp)
|
|
218
|
-
}
|
|
219
|
-
if (
|
|
220
|
-
!isPairingConnectURL(url) &&
|
|
221
|
-
(!ready ||
|
|
222
|
-
(!hasPtyConnectTicketURL(url) &&
|
|
223
|
-
!hasPersistentPtyConnectTicketURL(url) &&
|
|
224
|
-
!hasMcpClientTicketURL(url) &&
|
|
225
|
-
// With machines off the link's path is an unknown route, and gets this 401 like one.
|
|
226
|
-
!(isMachineLinkUpgrade(request) && (yield* machines)))) &&
|
|
227
|
-
!(yield* authorizedRequest(request, auth))
|
|
228
|
-
)
|
|
229
|
-
return unauthorizedResponse(request)
|
|
230
|
-
if (ready) return yield* app.value
|
|
231
|
-
return unavailable(state)
|
|
232
|
-
})
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
const infoResponse = Effect.fnUntraced(function* (
|
|
236
|
-
status: Status.Interface,
|
|
237
|
-
version: string,
|
|
238
|
-
urls: () => ReadonlyArray<string>,
|
|
239
|
-
tmp: string,
|
|
240
|
-
) {
|
|
241
|
-
const state = yield* status.current
|
|
242
|
-
return HttpServerResponse.jsonUnsafe(
|
|
243
|
-
{ version, pid: process.pid, urls: urls(), paths: { tmp } },
|
|
244
|
-
{
|
|
245
|
-
status: state.type === "ready" ? 200 : state.type === "failed" ? 500 : 503,
|
|
246
|
-
headers: state.type === "starting" || state.type === "stopping" ? { "retry-after": "1" } : undefined,
|
|
247
|
-
},
|
|
248
|
-
)
|
|
249
|
-
})
|
|
250
|
-
|
|
251
|
-
function unavailable(status: Status.State) {
|
|
252
|
-
if (status.type === "failed")
|
|
253
|
-
return HttpServerResponse.jsonUnsafe(
|
|
254
|
-
{
|
|
255
|
-
code: "service_failed",
|
|
256
|
-
message: "The background service could not start.",
|
|
257
|
-
action: "Run `opencode service restart` after checking the service logs.",
|
|
258
|
-
},
|
|
259
|
-
{ status: 503 },
|
|
260
|
-
)
|
|
261
|
-
return HttpServerResponse.jsonUnsafe(
|
|
262
|
-
{ code: status.type === "stopping" ? "service_stopping" : "service_starting" },
|
|
263
|
-
{ status: 503, headers: { "retry-after": "1" } },
|
|
264
|
-
)
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* The managed server owns restart continuity: at boot it resumes Sessions whose execution claim was
|
|
269
|
-
* never released. Claims are written when execution starts (see SessionExecution), so recovery covers
|
|
270
|
-
* graceful restarts and unclean deaths alike — no shutdown hook participates.
|
|
271
|
-
*/
|
|
272
|
-
const installRestartContinuity = Effect.fnUntraced(function* (restart: SessionRestart.Interface) {
|
|
273
|
-
yield* Effect.forkScoped(restart.resumeSuspendedSessions)
|
|
274
|
-
})
|
|
1
|
+
export * as ServerProcess from "./process"
|
|
2
|
+
|
|
3
|
+
import { NodeHttpServer } from "@effect/platform-node"
|
|
4
|
+
import { Bus } from "@zyro-sec/core/bus"
|
|
5
|
+
import { SessionRestart } from "@zyro-sec/core/session/execution/restart"
|
|
6
|
+
import { Automation } from "@zyro-sec/core/automation"
|
|
7
|
+
import { SessionSearchBuild } from "@zyro-sec/core/session/search-build"
|
|
8
|
+
import { InstallationEvent } from "@zyro-sec/schema/installation-event"
|
|
9
|
+
import { hasPtyConnectTicketURL } from "@zyro-sec/protocol/groups/pty"
|
|
10
|
+
import { hasPersistentPtyConnectTicketURL } from "@zyro-sec/protocol/groups/persistent-pty"
|
|
11
|
+
import { hasMcpClientTicketURL } from "@zyro-sec/protocol/groups/mcp"
|
|
12
|
+
import { isMachineLinkUpgrade } from "@zyro-sec/protocol/groups/machine"
|
|
13
|
+
import { isPairingConnectURL } from "@zyro-sec/protocol/groups/server"
|
|
14
|
+
import { Global } from "@zyro-sec/util/global"
|
|
15
|
+
import { Cause, Context, Effect, Exit, Latch, Layer, Option, Ref, Scope } from "effect"
|
|
16
|
+
import { HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
|
|
17
|
+
import { NetAddress } from "effect/net"
|
|
18
|
+
import { createServer } from "node:http"
|
|
19
|
+
import { ServerAuth } from "./auth"
|
|
20
|
+
import { isAllowedCorsOrigin } from "./cors"
|
|
21
|
+
import { machinesEnabled } from "./handlers/machine"
|
|
22
|
+
import { authorizedRequest, unauthorizedResponse } from "./middleware/authorization"
|
|
23
|
+
import { withoutParentSpan } from "./request-tracing"
|
|
24
|
+
import { RequestSite } from "./request-site"
|
|
25
|
+
import { createRoutes } from "./routes"
|
|
26
|
+
import { ServerInfo } from "./server-info"
|
|
27
|
+
import { Status } from "./service-status"
|
|
28
|
+
import type { ServerOptions } from "./options"
|
|
29
|
+
|
|
30
|
+
export interface Lifecycle<E = never, R = never> {
|
|
31
|
+
readonly onListen: (
|
|
32
|
+
address: NetAddress.SocketAddress,
|
|
33
|
+
shutdown: Effect.Effect<void>,
|
|
34
|
+
) => Effect.Effect<Effect.Effect<void>, E, R>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type App = Effect.Effect<
|
|
38
|
+
HttpServerResponse.HttpServerResponse,
|
|
39
|
+
unknown,
|
|
40
|
+
HttpServerRequest.HttpServerRequest | Scope.Scope
|
|
41
|
+
>
|
|
42
|
+
|
|
43
|
+
export type Transform = (app: App) => App
|
|
44
|
+
|
|
45
|
+
const errorResponseLogger = HttpMiddleware.make((app) =>
|
|
46
|
+
HttpMiddleware.logger(
|
|
47
|
+
Effect.tap(app, (response) =>
|
|
48
|
+
response.status < 400 ? HttpMiddleware.withLoggerDisabled(Effect.void) : Effect.void,
|
|
49
|
+
),
|
|
50
|
+
),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
|
|
54
|
+
options: ServerOptions,
|
|
55
|
+
lifecycle?: Lifecycle<E, R>,
|
|
56
|
+
transform?: Transform,
|
|
57
|
+
remoteURLs?: () => ReadonlyArray<string>,
|
|
58
|
+
) {
|
|
59
|
+
const password = options.password
|
|
60
|
+
if (!password) return yield* Effect.fail(new Error("Missing server password"))
|
|
61
|
+
const hostname = options.hostname ?? "127.0.0.1"
|
|
62
|
+
const port = Option.fromNullishOr(options.port)
|
|
63
|
+
const shutdown = yield* Latch.make()
|
|
64
|
+
const status = yield* Status.make()
|
|
65
|
+
const bound = yield* listen({ hostname, port })
|
|
66
|
+
const localURLs = () => {
|
|
67
|
+
const address = bound.server.address()
|
|
68
|
+
if (address === null || typeof address === "string") return []
|
|
69
|
+
const host = address.family === "IPv6" ? `[${address.address}]` : address.address
|
|
70
|
+
return ServerInfo.connectionURLs(`http://${host}:${address.port}`, hostname)
|
|
71
|
+
}
|
|
72
|
+
const urls = () => [...localURLs(), ...(remoteURLs?.() ?? [])]
|
|
73
|
+
const application = yield* Ref.make(Option.none<App>())
|
|
74
|
+
// Off until the routes are up, which is when the flag can be read.
|
|
75
|
+
const machinesFlag = yield* Ref.make(Effect.succeed(false))
|
|
76
|
+
const app = dispatch(
|
|
77
|
+
password,
|
|
78
|
+
status,
|
|
79
|
+
application,
|
|
80
|
+
machinesFlag,
|
|
81
|
+
options.app?.version ?? "unknown",
|
|
82
|
+
urls,
|
|
83
|
+
Global.Path.tmp,
|
|
84
|
+
)
|
|
85
|
+
// Request fibers may continue inbound trace context, but must not inherit the server startup parent.
|
|
86
|
+
yield* bound.http
|
|
87
|
+
.serve(
|
|
88
|
+
(transform ? transform(app) : app).pipe(
|
|
89
|
+
RequestSite.middleware(options),
|
|
90
|
+
HttpMiddleware.compression(),
|
|
91
|
+
HttpMiddleware.cors({ allowedOrigins: (origin) => isAllowedCorsOrigin(origin, options), maxAge: 86_400 }),
|
|
92
|
+
),
|
|
93
|
+
errorResponseLogger,
|
|
94
|
+
)
|
|
95
|
+
.pipe(Effect.provide(NodeHttpServer.layerHttpServices), withoutParentSpan)
|
|
96
|
+
if (lifecycle)
|
|
97
|
+
yield* lifecycle.onListen(bound.http.address, shutdown.open.pipe(Effect.asVoid)).pipe(
|
|
98
|
+
Effect.flatMap((cleanup) =>
|
|
99
|
+
Effect.addFinalizer(() => Scope.close(bound.scope, Exit.void).pipe(Effect.andThen(cleanup))),
|
|
100
|
+
),
|
|
101
|
+
Effect.uninterruptible,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
const parentScope = yield* Scope.Scope
|
|
105
|
+
const applicationScope = yield* Scope.fork(parentScope)
|
|
106
|
+
yield* Effect.addFinalizer(() =>
|
|
107
|
+
status.beginStopping.pipe(
|
|
108
|
+
Effect.andThen(Ref.set(application, Option.none())),
|
|
109
|
+
Effect.andThen(Effect.sync(() => bound.server.closeAllConnections())),
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
// Built without the startup span: route handlers and background fibers capture this context, and would
|
|
114
|
+
// otherwise nest every request and session turn for the life of the process under one trace.
|
|
115
|
+
const boot = Effect.gen(function* () {
|
|
116
|
+
const context = yield* Layer.buildWithScope(
|
|
117
|
+
createRoutes(
|
|
118
|
+
{
|
|
119
|
+
...options,
|
|
120
|
+
password,
|
|
121
|
+
},
|
|
122
|
+
urls,
|
|
123
|
+
).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
|
|
124
|
+
applicationScope,
|
|
125
|
+
)
|
|
126
|
+
if (lifecycle) {
|
|
127
|
+
yield* installRestartContinuity(Context.get(context, SessionRestart.Service)).pipe(
|
|
128
|
+
Effect.provideService(Scope.Scope, applicationScope),
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
// Automations run from any server process (`service`, `opencode serve`, or `--standalone`); the table holds all their state.
|
|
132
|
+
yield* Effect.forkIn(Context.get(context, Automation.Service).run, applicationScope)
|
|
133
|
+
// Likewise the one-time session search build, once a location has sqlite_fts on.
|
|
134
|
+
yield* Effect.forkIn(Context.get(context, SessionSearchBuild.Service).run, applicationScope)
|
|
135
|
+
yield* Ref.set(machinesFlag, yield* machinesEnabled.pipe(Effect.provide(context)))
|
|
136
|
+
yield* Ref.set(application, Option.some(Context.get(context, HttpRouter.HttpRouter).asHttpEffect()))
|
|
137
|
+
yield* status.ready
|
|
138
|
+
const bus = Context.get(context, Bus.Service)
|
|
139
|
+
return {
|
|
140
|
+
address: bound.http.address,
|
|
141
|
+
shutdown: shutdown.await,
|
|
142
|
+
updateAvailable: (version: string) =>
|
|
143
|
+
bus.publish(InstallationEvent.UpdateAvailable, { version }).pipe(Effect.asVoid),
|
|
144
|
+
updated: (version: string) => bus.publish(InstallationEvent.Updated, { version }).pipe(Effect.asVoid),
|
|
145
|
+
}
|
|
146
|
+
}).pipe(
|
|
147
|
+
withoutParentSpan,
|
|
148
|
+
Effect.catchCause((cause) => {
|
|
149
|
+
if (!lifecycle || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause)
|
|
150
|
+
return status.fail.pipe(
|
|
151
|
+
Effect.andThen(
|
|
152
|
+
Scope.close(applicationScope, Exit.failCause(cause)).pipe(
|
|
153
|
+
Effect.catchCause((cleanupCause) =>
|
|
154
|
+
Effect.logError("failed to clean up background service boot", { cause: cleanupCause }),
|
|
155
|
+
),
|
|
156
|
+
),
|
|
157
|
+
),
|
|
158
|
+
Effect.andThen(Effect.logError("background service boot failed", { cause })),
|
|
159
|
+
Effect.andThen(Effect.never),
|
|
160
|
+
)
|
|
161
|
+
}),
|
|
162
|
+
)
|
|
163
|
+
if (!lifecycle) return yield* boot
|
|
164
|
+
return yield* Effect.raceFirst(boot, shutdown.await.pipe(Effect.andThen(Effect.interrupt)))
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
function listen(options: { readonly hostname: string; readonly port: Option.Option<number> }) {
|
|
168
|
+
if (Option.isSome(options.port)) return bind(options.hostname, options.port.value)
|
|
169
|
+
const next = (port: number): ReturnType<typeof bind> =>
|
|
170
|
+
bind(options.hostname, port).pipe(
|
|
171
|
+
Effect.catch((error) => (port < 65_535 && addressInUse(error) ? next(port + 1) : Effect.fail(error))),
|
|
172
|
+
)
|
|
173
|
+
return next(4096)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function bind(hostname: string, port: number) {
|
|
177
|
+
return Effect.gen(function* () {
|
|
178
|
+
const parentScope = yield* Scope.Scope
|
|
179
|
+
const serverScope = yield* Scope.fork(parentScope)
|
|
180
|
+
const server = createServer()
|
|
181
|
+
return yield* Effect.gen(function* () {
|
|
182
|
+
const http = yield* NodeHttpServer.make(() => server, { port, host: hostname })
|
|
183
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
|
|
184
|
+
return { http, server, scope: serverScope }
|
|
185
|
+
}).pipe(
|
|
186
|
+
Effect.provideService(Scope.Scope, serverScope),
|
|
187
|
+
Effect.onError((cause) => Scope.close(serverScope, Exit.failCause(cause))),
|
|
188
|
+
)
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function addressInUse(error: unknown) {
|
|
193
|
+
if (typeof error !== "object" || error === null || !("cause" in error)) return false
|
|
194
|
+
const cause = error.cause
|
|
195
|
+
return typeof cause === "object" && cause !== null && "code" in cause && cause.code === "EADDRINUSE"
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function dispatch(
|
|
199
|
+
password: string,
|
|
200
|
+
status: Status.Interface,
|
|
201
|
+
application: Ref.Ref<Option.Option<App>>,
|
|
202
|
+
machinesFlag: Ref.Ref<Effect.Effect<boolean>>,
|
|
203
|
+
version: string,
|
|
204
|
+
urls: () => ReadonlyArray<string>,
|
|
205
|
+
tmp: string,
|
|
206
|
+
): App {
|
|
207
|
+
const auth = ServerAuth.Config.of({ password: Option.some(password), username: "zyrosec" })
|
|
208
|
+
return Effect.gen(function* () {
|
|
209
|
+
const request = yield* HttpServerRequest.HttpServerRequest
|
|
210
|
+
const url = new URL(request.url, "http://localhost")
|
|
211
|
+
const state = yield* status.current
|
|
212
|
+
const app = yield* Ref.get(application)
|
|
213
|
+
const machines = yield* Ref.get(machinesFlag)
|
|
214
|
+
const ready = state.type === "ready" && Option.isSome(app)
|
|
215
|
+
if (request.method === "GET" && url.pathname === "/api/info" && !ready) {
|
|
216
|
+
if (!(yield* authorizedRequest(request, auth))) return unauthorizedResponse(request)
|
|
217
|
+
return yield* infoResponse(status, version, urls, tmp)
|
|
218
|
+
}
|
|
219
|
+
if (
|
|
220
|
+
!isPairingConnectURL(url) &&
|
|
221
|
+
(!ready ||
|
|
222
|
+
(!hasPtyConnectTicketURL(url) &&
|
|
223
|
+
!hasPersistentPtyConnectTicketURL(url) &&
|
|
224
|
+
!hasMcpClientTicketURL(url) &&
|
|
225
|
+
// With machines off the link's path is an unknown route, and gets this 401 like one.
|
|
226
|
+
!(isMachineLinkUpgrade(request) && (yield* machines)))) &&
|
|
227
|
+
!(yield* authorizedRequest(request, auth))
|
|
228
|
+
)
|
|
229
|
+
return unauthorizedResponse(request)
|
|
230
|
+
if (ready) return yield* app.value
|
|
231
|
+
return unavailable(state)
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const infoResponse = Effect.fnUntraced(function* (
|
|
236
|
+
status: Status.Interface,
|
|
237
|
+
version: string,
|
|
238
|
+
urls: () => ReadonlyArray<string>,
|
|
239
|
+
tmp: string,
|
|
240
|
+
) {
|
|
241
|
+
const state = yield* status.current
|
|
242
|
+
return HttpServerResponse.jsonUnsafe(
|
|
243
|
+
{ version, pid: process.pid, urls: urls(), paths: { tmp } },
|
|
244
|
+
{
|
|
245
|
+
status: state.type === "ready" ? 200 : state.type === "failed" ? 500 : 503,
|
|
246
|
+
headers: state.type === "starting" || state.type === "stopping" ? { "retry-after": "1" } : undefined,
|
|
247
|
+
},
|
|
248
|
+
)
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
function unavailable(status: Status.State) {
|
|
252
|
+
if (status.type === "failed")
|
|
253
|
+
return HttpServerResponse.jsonUnsafe(
|
|
254
|
+
{
|
|
255
|
+
code: "service_failed",
|
|
256
|
+
message: "The background service could not start.",
|
|
257
|
+
action: "Run `opencode service restart` after checking the service logs.",
|
|
258
|
+
},
|
|
259
|
+
{ status: 503 },
|
|
260
|
+
)
|
|
261
|
+
return HttpServerResponse.jsonUnsafe(
|
|
262
|
+
{ code: status.type === "stopping" ? "service_stopping" : "service_starting" },
|
|
263
|
+
{ status: 503, headers: { "retry-after": "1" } },
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The managed server owns restart continuity: at boot it resumes Sessions whose execution claim was
|
|
269
|
+
* never released. Claims are written when execution starts (see SessionExecution), so recovery covers
|
|
270
|
+
* graceful restarts and unclean deaths alike — no shutdown hook participates.
|
|
271
|
+
*/
|
|
272
|
+
const installRestartContinuity = Effect.fnUntraced(function* (restart: SessionRestart.Interface) {
|
|
273
|
+
yield* Effect.forkScoped(restart.resumeSuspendedSessions)
|
|
274
|
+
})
|
package/src/range.ts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
export * as ByteRange from "./range"
|
|
2
|
-
|
|
3
|
-
/** A single `bytes=` range of a `size`-byte body, inclusive. Undefined serves the whole body. */
|
|
4
|
-
export function parse(header: string | undefined, size: number) {
|
|
5
|
-
const match = header === undefined ? null : /^bytes=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(header.trim())
|
|
6
|
-
if (match === null || (match[1] === "" && match[2] === "")) return undefined
|
|
7
|
-
if (match[1] === "") {
|
|
8
|
-
const suffix = Number(match[2])
|
|
9
|
-
if (suffix === 0 || size === 0) return "unsatisfiable"
|
|
10
|
-
return { start: Math.max(size - suffix, 0), end: size - 1 }
|
|
11
|
-
}
|
|
12
|
-
const start = Number(match[1])
|
|
13
|
-
const end = match[2] === "" ? size - 1 : Number(match[2])
|
|
14
|
-
if (start > end || start >= size) return "unsatisfiable"
|
|
15
|
-
return { start, end: Math.min(end, size - 1) }
|
|
16
|
-
}
|
|
1
|
+
export * as ByteRange from "./range"
|
|
2
|
+
|
|
3
|
+
/** A single `bytes=` range of a `size`-byte body, inclusive. Undefined serves the whole body. */
|
|
4
|
+
export function parse(header: string | undefined, size: number) {
|
|
5
|
+
const match = header === undefined ? null : /^bytes=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(header.trim())
|
|
6
|
+
if (match === null || (match[1] === "" && match[2] === "")) return undefined
|
|
7
|
+
if (match[1] === "") {
|
|
8
|
+
const suffix = Number(match[2])
|
|
9
|
+
if (suffix === 0 || size === 0) return "unsatisfiable"
|
|
10
|
+
return { start: Math.max(size - suffix, 0), end: size - 1 }
|
|
11
|
+
}
|
|
12
|
+
const start = Number(match[1])
|
|
13
|
+
const end = match[2] === "" ? size - 1 : Number(match[2])
|
|
14
|
+
if (start > end || start >= size) return "unsatisfiable"
|
|
15
|
+
return { start, end: Math.min(end, size - 1) }
|
|
16
|
+
}
|
package/src/request-site.ts
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
export * as RequestSite from "./request-site"
|
|
2
|
-
|
|
3
|
-
import { Effect } from "effect"
|
|
4
|
-
import { HttpMiddleware, HttpServerRequest, HttpServerResponse } from "effect/http"
|
|
5
|
-
import { type CorsOptions, isAllowedRequestOrigin } from "./cors"
|
|
6
|
-
|
|
7
|
-
// Artifact pages render in sandboxed frames, so their own requests come from an opaque origin.
|
|
8
|
-
const ARTIFACT_VIEW = /^\/api\/experimental\/artifacts\/[^/]+\/view(\/|$)/
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* API routes are called by scripts and native clients, not opened as pages from other sites. Browsers label requests
|
|
12
|
-
* with Sec-Fetch-Site and Sec-Fetch-Mode; another site may navigate to the API or call it only from an allowed CORS
|
|
13
|
-
* origin. Clients that send no Sec-Fetch headers (CLI, TUI, SDK, mobile) and same-origin or typed-in requests pass.
|
|
14
|
-
*/
|
|
15
|
-
export function rejected(request: HttpServerRequest.HttpServerRequest, options?: CorsOptions) {
|
|
16
|
-
const site = request.headers["sec-fetch-site"]
|
|
17
|
-
if (site !== "cross-site" && site !== "same-site") return false
|
|
18
|
-
const pathname = new URL(request.url, "http://localhost").pathname
|
|
19
|
-
if (pathname !== "/api" && !pathname.startsWith("/api/")) return false
|
|
20
|
-
if (ARTIFACT_VIEW.test(pathname)) return false
|
|
21
|
-
if (request.headers["sec-fetch-mode"] === "navigate") return true
|
|
22
|
-
const origin = request.headers.origin
|
|
23
|
-
return origin !== undefined && !isAllowedRequestOrigin(origin, request.headers.host, options)
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export const middleware = (options?: CorsOptions) =>
|
|
27
|
-
HttpMiddleware.make((app) =>
|
|
28
|
-
Effect.gen(function* () {
|
|
29
|
-
const request = yield* HttpServerRequest.HttpServerRequest
|
|
30
|
-
if (!rejected(request, options)) return yield* app
|
|
31
|
-
return HttpServerResponse.jsonUnsafe(
|
|
32
|
-
{ _tag: "ForbiddenError", message: "Cross-site requests to the API are not allowed" },
|
|
33
|
-
{ status: 403 },
|
|
34
|
-
)
|
|
35
|
-
}),
|
|
36
|
-
)
|
|
1
|
+
export * as RequestSite from "./request-site"
|
|
2
|
+
|
|
3
|
+
import { Effect } from "effect"
|
|
4
|
+
import { HttpMiddleware, HttpServerRequest, HttpServerResponse } from "effect/http"
|
|
5
|
+
import { type CorsOptions, isAllowedRequestOrigin } from "./cors"
|
|
6
|
+
|
|
7
|
+
// Artifact pages render in sandboxed frames, so their own requests come from an opaque origin.
|
|
8
|
+
const ARTIFACT_VIEW = /^\/api\/experimental\/artifacts\/[^/]+\/view(\/|$)/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* API routes are called by scripts and native clients, not opened as pages from other sites. Browsers label requests
|
|
12
|
+
* with Sec-Fetch-Site and Sec-Fetch-Mode; another site may navigate to the API or call it only from an allowed CORS
|
|
13
|
+
* origin. Clients that send no Sec-Fetch headers (CLI, TUI, SDK, mobile) and same-origin or typed-in requests pass.
|
|
14
|
+
*/
|
|
15
|
+
export function rejected(request: HttpServerRequest.HttpServerRequest, options?: CorsOptions) {
|
|
16
|
+
const site = request.headers["sec-fetch-site"]
|
|
17
|
+
if (site !== "cross-site" && site !== "same-site") return false
|
|
18
|
+
const pathname = new URL(request.url, "http://localhost").pathname
|
|
19
|
+
if (pathname !== "/api" && !pathname.startsWith("/api/")) return false
|
|
20
|
+
if (ARTIFACT_VIEW.test(pathname)) return false
|
|
21
|
+
if (request.headers["sec-fetch-mode"] === "navigate") return true
|
|
22
|
+
const origin = request.headers.origin
|
|
23
|
+
return origin !== undefined && !isAllowedRequestOrigin(origin, request.headers.host, options)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const middleware = (options?: CorsOptions) =>
|
|
27
|
+
HttpMiddleware.make((app) =>
|
|
28
|
+
Effect.gen(function* () {
|
|
29
|
+
const request = yield* HttpServerRequest.HttpServerRequest
|
|
30
|
+
if (!rejected(request, options)) return yield* app
|
|
31
|
+
return HttpServerResponse.jsonUnsafe(
|
|
32
|
+
{ _tag: "ForbiddenError", message: "Cross-site requests to the API are not allowed" },
|
|
33
|
+
{ status: 403 },
|
|
34
|
+
)
|
|
35
|
+
}),
|
|
36
|
+
)
|