@zyro-sec/server 0.0.0-stage → 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.
Files changed (131) hide show
  1. package/package.json +40 -4
  2. package/script/build.ts +28 -0
  3. package/script/pack.ts +5 -0
  4. package/script/workerd-probe.ts +59 -0
  5. package/src/api.ts +12 -0
  6. package/src/auth.ts +70 -0
  7. package/src/content-headers.ts +32 -0
  8. package/src/cors.ts +34 -0
  9. package/src/event-feed.ts +93 -0
  10. package/src/fetch.ts +67 -0
  11. package/src/handlers/agent.ts +23 -0
  12. package/src/handlers/artifact.ts +242 -0
  13. package/src/handlers/automation.ts +63 -0
  14. package/src/handlers/blob.ts +55 -0
  15. package/src/handlers/command.ts +8 -0
  16. package/src/handlers/config.ts +26 -0
  17. package/src/handlers/credential.ts +87 -0
  18. package/src/handlers/debug.ts +57 -0
  19. package/src/handlers/event.ts +38 -0
  20. package/src/handlers/form.ts +15 -0
  21. package/src/handlers/fs.ts +180 -0
  22. package/src/handlers/generate.ts +117 -0
  23. package/src/handlers/integration.ts +310 -0
  24. package/src/handlers/job.ts +29 -0
  25. package/src/handlers/location.ts +33 -0
  26. package/src/handlers/machine.ts +336 -0
  27. package/src/handlers/mcp.ts +160 -0
  28. package/src/handlers/media.ts +44 -0
  29. package/src/handlers/message.ts +82 -0
  30. package/src/handlers/migration.ts +13 -0
  31. package/src/handlers/model.ts +25 -0
  32. package/src/handlers/permission.ts +131 -0
  33. package/src/handlers/persistent-pty.ts +285 -0
  34. package/src/handlers/plugin.ts +97 -0
  35. package/src/handlers/project.ts +23 -0
  36. package/src/handlers/provider.ts +32 -0
  37. package/src/handlers/pty-socket.ts +47 -0
  38. package/src/handlers/pty.ts +181 -0
  39. package/src/handlers/push.ts +67 -0
  40. package/src/handlers/reference.ts +8 -0
  41. package/src/handlers/rpc.ts +31 -0
  42. package/src/handlers/server.ts +58 -0
  43. package/src/handlers/session-error.ts +47 -0
  44. package/src/handlers/session.ts +722 -0
  45. package/src/handlers/shell.ts +72 -0
  46. package/src/handlers/skill.ts +34 -0
  47. package/src/handlers/usage.ts +23 -0
  48. package/src/handlers/vcs.ts +104 -0
  49. package/src/handlers/voice.ts +50 -0
  50. package/src/handlers/websearch.ts +50 -0
  51. package/src/handlers/worktree.ts +60 -0
  52. package/src/handlers.ts +69 -0
  53. package/src/location.ts +86 -0
  54. package/src/media-uri.ts +13 -0
  55. package/src/middleware/authorization.ts +111 -0
  56. package/src/middleware/defect-response.ts +39 -0
  57. package/src/middleware/form-location.ts +44 -0
  58. package/src/middleware/schema-error.ts +49 -0
  59. package/src/middleware/session-location.ts +30 -0
  60. package/src/options.ts +61 -0
  61. package/src/pairing.ts +36 -0
  62. package/src/process.ts +274 -0
  63. package/src/range.ts +16 -0
  64. package/src/request-site.ts +36 -0
  65. package/src/request-tracing.ts +9 -0
  66. package/src/routes.ts +261 -0
  67. package/src/server-info.ts +41 -0
  68. package/src/service-status.ts +30 -0
  69. package/src/workerd.ts +184 -0
  70. package/test/artifact.test.ts +224 -0
  71. package/test/auth.test.ts +24 -0
  72. package/test/automation.test.ts +315 -0
  73. package/test/client-mcp.test.ts +369 -0
  74. package/test/codemode-api.test.ts +88 -0
  75. package/test/config.test.ts +104 -0
  76. package/test/cors.test.ts +24 -0
  77. package/test/defect-response.test.ts +83 -0
  78. package/test/event-feed.test.ts +201 -0
  79. package/test/fetch-option.test.ts +104 -0
  80. package/test/fetch.test.ts +698 -0
  81. package/test/fixture/mcp-starts.cjs +20 -0
  82. package/test/fixture/routes.ts +37 -0
  83. package/test/fixture/server.ts +20 -0
  84. package/test/fixture/worktree-delegate/index.ts +13 -0
  85. package/test/fixture/worktree-plugin/index.ts +47 -0
  86. package/test/flag-channel.test.ts +126 -0
  87. package/test/fs.test.ts +439 -0
  88. package/test/generate.test.ts +132 -0
  89. package/test/handler-policy.test.ts +43 -0
  90. package/test/heap-dump.test.ts +137 -0
  91. package/test/integration-policy.test.ts +93 -0
  92. package/test/job.test.ts +186 -0
  93. package/test/machine-iroh.test.ts +259 -0
  94. package/test/machine-link.test.ts +1234 -0
  95. package/test/machine-routes.test.ts +198 -0
  96. package/test/media.test.ts +343 -0
  97. package/test/message.test.ts +105 -0
  98. package/test/model.test.ts +62 -0
  99. package/test/options.test.ts +42 -0
  100. package/test/permission-saved.test.ts +73 -0
  101. package/test/persistent-pty.test.ts +1007 -0
  102. package/test/process.test.ts +261 -0
  103. package/test/provider.test.ts +88 -0
  104. package/test/pty-socket.property.test.ts +240 -0
  105. package/test/pty-socket.test.ts +89 -0
  106. package/test/pty-transport.test.ts +200 -0
  107. package/test/push-routes.test.ts +157 -0
  108. package/test/request-site.test.ts +71 -0
  109. package/test/request-tracing.test.ts +87 -0
  110. package/test/rpc-handler-errors.test.ts +76 -0
  111. package/test/schema-error.test.ts +68 -0
  112. package/test/service-status.test.ts +34 -0
  113. package/test/session-admit-location.test.ts +92 -0
  114. package/test/session-create.test.ts +65 -0
  115. package/test/session-diff.test.ts +100 -0
  116. package/test/session-form.test.ts +50 -0
  117. package/test/session-import.test.ts +152 -0
  118. package/test/session-instances.test.ts +335 -0
  119. package/test/session-unarchive.test.ts +73 -0
  120. package/test/session-update.test.ts +66 -0
  121. package/test/skill.test.ts +57 -0
  122. package/test/sse-failure.test.ts +71 -0
  123. package/test/usage.test.ts +88 -0
  124. package/test/vcs.test.ts +356 -0
  125. package/test/video-generate.test.ts +131 -0
  126. package/test/voice.test.ts +170 -0
  127. package/test/workerd.test.ts +227 -0
  128. package/test/worktree.test.ts +333 -0
  129. package/tsconfig.build.json +15 -0
  130. package/tsconfig.json +11 -0
  131. package/README.md +0 -3
@@ -0,0 +1,336 @@
1
+ import { NodeHttpServerRequest } from "@effect/platform-node"
2
+ import { type WebSocket, WebSocketServer } from "@effect/platform-node-shared/NodeWS"
3
+ import { Environment } from "@zyro-sec/core/environment/index"
4
+ import { Flag } from "@zyro-sec/core/flag"
5
+ import { Location } from "@zyro-sec/core/location"
6
+ import { LocationServiceMap } from "@zyro-sec/core/location-services"
7
+ import { Frames } from "@zyro-sec/core/machine/frames"
8
+ import { Identity } from "@zyro-sec/core/machine/identity"
9
+ import { Iroh } from "@zyro-sec/core/machine/iroh"
10
+ import { Join } from "@zyro-sec/core/machine/join"
11
+ import { Link } from "@zyro-sec/core/machine/link"
12
+ import { Machines } from "@zyro-sec/core/machine/machines"
13
+ import { AbsolutePath } from "@zyro-sec/core/schema"
14
+ import { ConflictError, ForbiddenError, InvalidRequestError, MachineNotFoundError } from "@zyro-sec/protocol/errors"
15
+ import { isWebSocketUpgrade, type MachineAddPayload } from "@zyro-sec/protocol/groups/machine"
16
+ import { Global } from "@zyro-sec/util/global"
17
+ import { Context, Effect, Latch, Option, Scope, Semaphore } from "effect"
18
+ import { HttpMiddleware, type HttpServerRequest, HttpServerResponse } from "effect/http"
19
+ import { HttpApiSchema } from "effect/http-api"
20
+ import { Socket } from "effect/socket"
21
+ import { IncomingMessage } from "node:http"
22
+
23
+ /** Handshakes in progress across the server: what strangers can hold open at once, each for at most ten seconds. */
24
+ const MAX_HANDSHAKES = 32
25
+ /** Noise's largest message, so nothing longer is ever a frame. */
26
+ const MAX_FRAME = 65_535
27
+ /** Noise's authentication tag, which every frame ends with, so nothing shorter is ever a frame. */
28
+ const MIN_FRAME = 16
29
+ /**
30
+ * The most that may wait unread. The link holds at most the one message it is reassembling, so a message's worth
31
+ * waiting behind that means the socket is not holding the peer back, and the carrier ends rather than keep it.
32
+ */
33
+ const MAX_WAITING = Frames.MAX_MESSAGE
34
+ /** How long a send waits on a peer that takes none of what the socket already holds. */
35
+ const STALL = "60 seconds"
36
+ /** How often a served link is pinged. A peer not heard from since the last ping is gone, so within two of these. */
37
+ const PING = "30 seconds"
38
+ /** How long a machine that got past the handshake has to answer the home's close before its connection is dropped. */
39
+ const CLOSING = "5 seconds"
40
+ /** How long a stopping server gives every link at once to answer the close, so no peer can keep it from stopping. */
41
+ const STOPPING = "1 second"
42
+ /**
43
+ * Policy violation, the code RFC 6455 gives for hiding the reason. Every close the home makes carries it and no
44
+ * reason: a refused handshake, a bad frame, a removed machine and a shutdown look the same.
45
+ */
46
+ const CLOSE = 1008
47
+
48
+ /**
49
+ * Only for tests, as `Link.Fixed` is: called with the endpoint's `ws` server when it is made, so a test can count its
50
+ * clients and watch a socket from the home's side. Production never sets it.
51
+ */
52
+ export const Watch = Context.Reference<(sockets: WebSocketServer) => void>("@zyro-sec/MachineLink/Watch", {
53
+ defaultValue: () => () => {},
54
+ })
55
+
56
+ /** Whether the `machines` flag is on in the server's base configuration, where the video routes read theirs. */
57
+ export const machinesEnabled = Effect.gen(function* () {
58
+ const global = yield* Global.Service
59
+ const locations = yield* LocationServiceMap.Service
60
+ return Flag.enabled("machines").pipe(
61
+ Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) }))),
62
+ Effect.orElseSucceed(() => false),
63
+ )
64
+ })
65
+
66
+ /** Sends the close and drops the connection at once, without the time a machine has to answer it. */
67
+ const drop = (socket: WebSocket) => {
68
+ socket.close(CLOSE)
69
+ socket.terminate()
70
+ }
71
+
72
+ /**
73
+ * Upgrades a request the HTTP server took off its parser, on the endpoint's own `ws` server, and gives its `ws` socket
74
+ * for the scope. Closing the scope sends the close and waits until the connection is gone, dropping it if the peer has
75
+ * not answered within `CLOSING`: the HTTP response the route returns afterwards must find nothing to be written to.
76
+ */
77
+ export const upgrade = (sockets: WebSocketServer, request: IncomingMessage) =>
78
+ Effect.acquireRelease(
79
+ Effect.callback<WebSocket, Link.Closed>((resume) => {
80
+ // `ws` answers a handshake it refuses itself and never calls back: the connection closing is all there is.
81
+ const refused = () => resume(Effect.fail(new Link.Closed()))
82
+ if (request.socket.destroyed) return refused()
83
+ request.socket.once("close", refused)
84
+ // No head: the bytes that arrived with the request are not kept for a route, and a WebSocket client sends none
85
+ // until it has read the 101. One that did would lose them, and the link's handshake would run out of time.
86
+ sockets.handleUpgrade(request, request.socket, Buffer.alloc(0), (socket) => {
87
+ request.socket.off("close", refused)
88
+ // The reader stops reading on the bytes that wait, and frames of none would wait without end. This hears a
89
+ // message before the reader does and drops the connection on one too short to be a frame, so the reader is
90
+ // handed that one and nothing after it.
91
+ socket.on("message", (data) => {
92
+ if ([data].flat().reduce((bytes, part) => bytes + part.byteLength, 0) < MIN_FRAME) drop(socket)
93
+ })
94
+ resume(Effect.succeed(socket))
95
+ })
96
+ }),
97
+ (socket) =>
98
+ Effect.gen(function* () {
99
+ const gone = Effect.callback<void>((resume) => {
100
+ if (socket.readyState === socket.CLOSED) return resume(Effect.void)
101
+ socket.once("close", () => resume(Effect.void))
102
+ })
103
+ socket.close(CLOSE)
104
+ if (Option.isNone(yield* Effect.timeoutOption(gone, CLOSING))) socket.terminate()
105
+ }),
106
+ )
107
+
108
+ /** What the carrier and the keepalive use of a `ws` socket. */
109
+ export interface Transport {
110
+ readonly bufferedAmount: number
111
+ /** Whether reading is stopped because enough already waits unread. Nothing the peer sends is seen meanwhile. */
112
+ readonly isPaused: boolean
113
+ /** Calls back once the socket has taken the message, or cannot. */
114
+ send(message: Uint8Array, taken: () => void): void
115
+ ping(): void
116
+ on(event: "pong" | "ping" | "message", listener: () => void): unknown
117
+ off(event: "pong" | "ping" | "message", listener: () => void): unknown
118
+ /** Drops the connection at once, sending nothing more. */
119
+ terminate(): void
120
+ }
121
+
122
+ /**
123
+ * A `ws` socket as the link's carrier, read through Effect's reader. A text message ends it like a closed socket, before
124
+ * anything is decrypted: the caller closes the socket. Inbound memory is bounded by the socket: `ws` refuses a message
125
+ * over `MAX_FRAME` before buffering it, `upgrade` drops the connection on one under `MIN_FRAME`, and the reader stops
126
+ * reading once 64 KiB waits, so what is held is that and what one read of the connection brings, and a read that still
127
+ * brings more than `MAX_WAITING` ends the carrier. `send` returns once the socket has taken the message, so the link's
128
+ * one writer never has more than a frame waiting behind a slow peer, and it drops a socket that takes nothing at all
129
+ * for `STALL`.
130
+ */
131
+ export const carrier = (reader: Socket.Reader, transport: Transport): Link.Carrier => {
132
+ const waiting: Array<Uint8Array | string> = []
133
+ return {
134
+ describe: () => ({ kind: "websocket" }),
135
+ send: (message) =>
136
+ Effect.gen(function* () {
137
+ const taken = Latch.makeUnsafe()
138
+ transport.send(message, () => taken.openUnsafe())
139
+ while (true) {
140
+ const held = transport.bufferedAmount
141
+ if (Option.isSome(yield* Effect.timeoutOption(taken.await, STALL))) return
142
+ // A close frame would wait behind what the peer is not reading. The reader sees this as the socket closing.
143
+ if (transport.bufferedAmount >= held) return transport.terminate()
144
+ }
145
+ }),
146
+ receive: Effect.gen(function* () {
147
+ if (waiting.length === 0) {
148
+ const read = yield* reader.pull
149
+ if (read.reduce((bytes, message) => bytes + message.length, 0) > MAX_WAITING) return yield* new Link.Closed()
150
+ waiting.push(...read)
151
+ }
152
+ const message = waiting.shift()
153
+ if (message === undefined || typeof message === "string") return yield* new Link.Closed()
154
+ return message
155
+ }).pipe(Effect.mapError(() => new Link.Closed())),
156
+ }
157
+ }
158
+
159
+ /**
160
+ * The idle limit of a served link: pings the peer every `PING` and drops the connection once a whole interval passes
161
+ * with nothing from it. Its answer counts, and so does anything else it sent. While reading is paused none of that can
162
+ * be seen, so an interval is held against the peer only if reading was paused at neither end of it. That covers a
163
+ * pause in between as well: reading pauses on a message, and a message is the peer heard.
164
+ */
165
+ export const keepalive = (transport: Transport) =>
166
+ Effect.gen(function* () {
167
+ const interval = { heard: true, paused: false }
168
+ const heard = () => {
169
+ interval.heard = true
170
+ }
171
+ const events = ["pong", "ping", "message"] as const
172
+ events.forEach((event) => transport.on(event, heard))
173
+ yield* Effect.addFinalizer(() => Effect.sync(() => events.forEach((event) => transport.off(event, heard))))
174
+ while (interval.heard || interval.paused || transport.isPaused) {
175
+ interval.heard = false
176
+ interval.paused = transport.isPaused
177
+ transport.ping()
178
+ yield* Effect.sleep(PING)
179
+ }
180
+ transport.terminate()
181
+ }).pipe(Effect.scoped)
182
+
183
+ /**
184
+ * `machine.link` in the `server.experimental` group: the WebSocket where a machine's link lands. Anyone who can reach
185
+ * the server can open it, and only the link's handshake gets past it. One scope per connection holds the socket and the
186
+ * link's fibers, and closing it is the only way a connection ends, whatever ended it. The first request shaped like a
187
+ * link upgrade reads the flag from the server's base configuration, which loads that configuration once even when the
188
+ * flag is off; only a GET WebSocket upgrade to exactly this path does.
189
+ */
190
+ export const makeMachineLink = Effect.gen(function* () {
191
+ const enabled = yield* machinesEnabled
192
+ const services = yield* Effect.context<Machines.Service | Identity.Service>()
193
+ const handshakes = Semaphore.makeUnsafe(MAX_HANDSHAKES)
194
+ const scope = yield* Effect.scope
195
+ const watch = yield* Watch
196
+ // The endpoint's own `ws` server. The socket Effect makes of an upgraded request cannot say what waits unsent, ping
197
+ // or drop the connection, and the server behind it takes messages of 100 MiB. This one refuses a message over
198
+ // `MAX_FRAME` before it is buffered, which `ws` closes with 1009.
199
+ //
200
+ // It is made for the first request that gets past every check below, as Effect's HTTP server makes its own, and not
201
+ // with the routes: those are also built where there is no Node, whose `ws` has no server, and no request there
202
+ // gets that far.
203
+ //
204
+ // The routes' scope closes as the server begins to stop, and stopping waits on no peer: every link is sent the close,
205
+ // `ws` refuses any upgrade from here on, and what is still connected after `STOPPING` is dropped. Left open, one
206
+ // link would hold the server for the twenty seconds it gives open connections.
207
+ const server = yield* Effect.cached(
208
+ Effect.acquireRelease(
209
+ Effect.sync(() => {
210
+ const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME })
211
+ watch(sockets)
212
+ return sockets
213
+ }),
214
+ (sockets) =>
215
+ Effect.gen(function* () {
216
+ sockets.clients.forEach((socket) => socket.close(CLOSE))
217
+ const empty = Effect.callback<void>((resume) => sockets.close(() => resume(Effect.void)))
218
+ if (Option.isNone(yield* Effect.timeoutOption(empty, STOPPING)))
219
+ sockets.clients.forEach((socket) => socket.terminate())
220
+ }),
221
+ ).pipe(Scope.provide(scope)),
222
+ )
223
+ return Effect.fn("MachineLink.serve")(function* (request: HttpServerRequest.HttpServerRequest) {
224
+ const incoming = NodeHttpServerRequest.toIncomingMessage(request)
225
+ // Without the flag, or for anything but the upgrade, this is the answer an unknown route gets. HTTP/2 has no
226
+ // upgrade, and `request.upgrade` fails unless the server took the request off its HTTP parser to be upgraded; the
227
+ // socket Effect would make of it is not used.
228
+ if (
229
+ !(incoming instanceof IncomingMessage) ||
230
+ !isWebSocketUpgrade(request) ||
231
+ Option.isNone(yield* Effect.option(request.upgrade)) ||
232
+ !(yield* enabled)
233
+ )
234
+ return HttpServerResponse.empty({ status: 404 })
235
+ return yield* Effect.gen(function* () {
236
+ // A place is taken before the upgrade and held until the handshake has ended, so no more strangers than there
237
+ // are places are ever WebSockets. With none free the request is answered as HTTP, as `ws` answers an upgrade
238
+ // once the server is stopping.
239
+ const sockets = yield* server
240
+ const admitted = yield* handshakes.withPermitsIfAvailable(1)(
241
+ Effect.gen(function* () {
242
+ const transport = yield* upgrade(sockets, incoming)
243
+ // The request ended as a WebSocket: the HTTP server would otherwise log every link the home closes as aborted.
244
+ yield* HttpMiddleware.withLoggerDisabled(Effect.void)
245
+ const socket = yield* Socket.fromWebSocket(Effect.succeed(transport))
246
+ const link = yield* Link.serve(carrier(yield* socket.reader, transport)).pipe(
247
+ // A stranger gives up its place with its connection: the time to answer a close is for machines.
248
+ Effect.onError(() => Effect.sync(() => drop(transport))),
249
+ )
250
+ return { transport, link }
251
+ }),
252
+ )
253
+ if (Option.isNone(admitted)) return HttpServerResponse.empty({ status: 503 })
254
+ yield* Effect.forkScoped(keepalive(admitted.value.transport))
255
+ const machines = yield* Machines.Service
256
+ yield* machines.connect(admitted.value.link.machine, admitted.value.link.connection)
257
+ return HttpServerResponse.empty()
258
+ }).pipe(
259
+ Effect.scoped,
260
+ // A WebSocket handshake `ws` refused, a refused link and a machine removed since it: one quiet close.
261
+ Effect.orElseSucceed(() => HttpServerResponse.empty()),
262
+ Effect.provide(services),
263
+ )
264
+ })
265
+ })
266
+
267
+ /**
268
+ * `machine.*` HTTP routes in the `server.experimental` group. Every route needs the `machines` flag.
269
+ *
270
+ * The home's Iroh endpoint is bound the first time it is needed and kept for the routes' scope: when a join string is
271
+ * made, and at start when the flag is on and there are machines to come back. Until then the binding is not imported.
272
+ * Without it, logged once, join strings carry only their URLs.
273
+ */
274
+ export const makeMachine = Effect.gen(function* () {
275
+ const enabled = yield* machinesEnabled
276
+ const machines = yield* Machines.Service
277
+ const requireEnabled = Effect.gen(function* () {
278
+ if (yield* enabled) return
279
+ return yield* new ForbiddenError({ message: "Machines are disabled; enable experimental.machines" })
280
+ })
281
+ const iroh = yield* Effect.cached(
282
+ Iroh.listen(enabled).pipe(
283
+ Effect.tapError((error) =>
284
+ Effect.logWarning("Machines connect over WebSockets only: Iroh is unavailable", error),
285
+ ),
286
+ Effect.option,
287
+ Scope.provide(yield* Effect.scope),
288
+ Effect.provide(yield* Effect.context<Machines.Service | Identity.Service>()),
289
+ ),
290
+ )
291
+ yield* Effect.forkScoped(
292
+ Effect.gen(function* () {
293
+ // The list first: reading the flag starts the configuration's Location, which an idle server has not done.
294
+ const list = yield* machines.list()
295
+ if (list.length === 0) return
296
+ const on = yield* enabled
297
+ if (on) yield* iroh
298
+ }),
299
+ )
300
+
301
+ return {
302
+ list: Effect.fn("MachineHandler.list")(function* () {
303
+ yield* requireEnabled
304
+ return { data: yield* machines.list() }
305
+ }),
306
+ add: Effect.fn("MachineHandler.add")(function* (payload: MachineAddPayload) {
307
+ yield* requireEnabled
308
+ const id = yield* machines.add(payload.name).pipe(
309
+ Effect.catchTag("Machines.AlreadyExists", (error) => Effect.succeed(error.machine)),
310
+ Effect.catchTag("Machines.InvalidName", (error) =>
311
+ Effect.fail(new InvalidRequestError({ message: error.message, kind: "invalid_name", field: "name" })),
312
+ ),
313
+ )
314
+ // Prefer Iroh first so laptops moving off a home LAN don't wait for a stale LAN URL timeout; URLs remain as fallback.
315
+ const reach = Option.isSome(yield* iroh) ? [{ type: "iroh" as const }, ...payload.reach] : payload.reach
316
+ const join = yield* machines.invite(id, { reach, replace: payload.replace }).pipe(
317
+ Effect.catchTags({
318
+ "Machines.AlreadyPaired": (error) =>
319
+ Effect.fail(new ConflictError({ message: error.message, resource: error.machine })),
320
+ "Machines.NotFound": (error) =>
321
+ Effect.fail(new MachineNotFoundError({ machine: error.machine, message: error.message })),
322
+ "Identity.InvalidKey": (error) => Effect.die(error),
323
+ }),
324
+ )
325
+ const decoded = Option.getOrUndefined(Join.decode(join))
326
+ if (!decoded) return yield* Effect.die(new Error("Server produced an unreadable join string"))
327
+ return { data: { name: id, join, expires: decoded.expires, reach: decoded.reach } }
328
+ }),
329
+ remove: Effect.fn("MachineHandler.remove")(function* (name: string) {
330
+ yield* requireEnabled
331
+ if (!(yield* machines.remove(Environment.ID.make(name))))
332
+ return yield* new MachineNotFoundError({ machine: name, message: `No machine named ${JSON.stringify(name)}.` })
333
+ return HttpApiSchema.NoContent.make()
334
+ }),
335
+ }
336
+ })
@@ -0,0 +1,160 @@
1
+ import { Location } from "@zyro-sec/core/location"
2
+ import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
3
+ import { Mcp } from "@zyro-sec/core/mcp/index"
4
+ import { PtyTicket } from "@zyro-sec/core/pty/ticket"
5
+ import { ForbiddenError, McpServerNotFoundError } from "@zyro-sec/protocol/errors"
6
+ import { PTY_CONNECT_TOKEN_HEADER, PTY_CONNECT_TOKEN_HEADER_VALUE } from "@zyro-sec/protocol/groups/pty"
7
+ import { Effect, Queue } from "effect"
8
+ import { HttpServerResponse } from "effect/http"
9
+ import { HttpApiBuilder, HttpApiSchema } from "effect/http-api"
10
+ import { Socket } from "effect/socket"
11
+ import { Api } from "../api"
12
+ import { CorsConfig, isAllowedRequestOrigin } from "../cors"
13
+ import { locationErrors, requestRef, response } from "../location"
14
+ import { holdLocation, type Outbound, runPtySocket } from "./pty-socket"
15
+
16
+ const notFound = <A, R>(effect: Effect.Effect<A, Mcp.NotFoundError, R>) =>
17
+ effect.pipe(Effect.mapError((error) => new McpServerNotFoundError({ server: error.server, message: error.message })))
18
+
19
+ export const McpHandler = HttpApiBuilder.group(Api, "server.mcp", (handlers) =>
20
+ Effect.gen(function* () {
21
+ const locations = yield* LocationServiceMap.Service
22
+ const cors = yield* CorsConfig
23
+ const tickets = yield* PtyTicket.Service
24
+
25
+ return handlers
26
+ .handle(
27
+ "mcp.list",
28
+ Effect.fn(function* () {
29
+ const service = yield* Mcp.Service
30
+ return yield* response(service.servers())
31
+ }),
32
+ )
33
+ .handle(
34
+ "mcp.add",
35
+ Effect.fn(function* (ctx) {
36
+ const service = yield* Mcp.Service
37
+ yield* service.add(ctx.params.server, ctx.payload.config)
38
+ return HttpApiSchema.NoContent.make()
39
+ }),
40
+ )
41
+ .handle(
42
+ "mcp.remove",
43
+ Effect.fn(function* (ctx) {
44
+ const service = yield* Mcp.Service
45
+ yield* notFound(service.remove(ctx.params.server))
46
+ return HttpApiSchema.NoContent.make()
47
+ }),
48
+ )
49
+ .handle(
50
+ "mcp.connect",
51
+ Effect.fn(function* (ctx) {
52
+ const service = yield* Mcp.Service
53
+ yield* notFound(service.connect(ctx.params.server))
54
+ return HttpApiSchema.NoContent.make()
55
+ }),
56
+ )
57
+ .handle(
58
+ "mcp.disconnect",
59
+ Effect.fn(function* (ctx) {
60
+ const service = yield* Mcp.Service
61
+ yield* notFound(service.disconnect(ctx.params.server))
62
+ return HttpApiSchema.NoContent.make()
63
+ }),
64
+ )
65
+ .handle(
66
+ "mcp.resource.catalog",
67
+ Effect.fn(function* () {
68
+ const service = yield* Mcp.Service
69
+ return yield* response(service.resourceCatalog())
70
+ }),
71
+ )
72
+ .handle(
73
+ "mcp.clientToken",
74
+ Effect.fn(function* (ctx) {
75
+ // The custom header forces a CORS preflight, so cross-origin pages cannot mint tickets.
76
+ if (
77
+ ctx.headers[PTY_CONNECT_TOKEN_HEADER] !== PTY_CONNECT_TOKEN_HEADER_VALUE ||
78
+ !isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors)
79
+ )
80
+ return yield* new ForbiddenError({ message: "Invalid client MCP connect token request" })
81
+ const location = yield* Location.Service
82
+ return yield* response(
83
+ tickets.issue({
84
+ mcpClient: ctx.query.name,
85
+ directory: location.directory,
86
+ workspaceID: location.workspaceID,
87
+ }),
88
+ )
89
+ }),
90
+ )
91
+ .handleRaw(
92
+ "mcp.client",
93
+ Effect.fn("McpHandler.client")(function* (ctx) {
94
+ if (!isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors))
95
+ return HttpServerResponse.empty({ status: 403 })
96
+
97
+ const name = ctx.query.name
98
+ const ref = LocationServiceMap.canonical(requestRef(ctx.request))
99
+ if (
100
+ ctx.query.ticket &&
101
+ !(yield* tickets.consume({
102
+ ticket: ctx.query.ticket,
103
+ mcpClient: name,
104
+ directory: ref.directory,
105
+ workspaceID: ref.workspaceID,
106
+ }))
107
+ )
108
+ return HttpServerResponse.empty({ status: 403 })
109
+
110
+ return yield* Effect.gen(function* () {
111
+ const mcp = yield* Mcp.Service
112
+ const { McpSocketClient } = yield* Effect.promise(() => import("@zyro-sec/core/mcp/socket-client"))
113
+ const socket = yield* Effect.orDie(ctx.request.upgrade)
114
+ const outbox = yield* Queue.unbounded<Outbound>()
115
+ yield* holdLocation(outbox)
116
+ const state = { attached: false, disconnected: false }
117
+ const transport = McpSocketClient.make({
118
+ send: (text) => Queue.offerUnsafe(outbox, text),
119
+ // A failed attach closes the transport before reporting the error; ignore that close so the
120
+ // socket closes with 1011 below instead of a normal 1000.
121
+ close: (code, reason) => {
122
+ if (state.attached) Queue.offerUnsafe(outbox, new Socket.CloseEvent(code, reason))
123
+ },
124
+ })
125
+ const decoder = new TextDecoder()
126
+ // The attachment lives in this scope, so it ends with the socket.
127
+ yield* mcp.attach(name, transport).pipe(
128
+ Effect.tap(() =>
129
+ Effect.sync(() => {
130
+ state.attached = true
131
+ }),
132
+ ),
133
+ Effect.catch((error) =>
134
+ state.disconnected
135
+ ? Effect.logInfo("client MCP disconnected during initialize", { name, error: error.message })
136
+ : Effect.logError("client MCP attach failed", { name, error: error.message }).pipe(
137
+ Effect.andThen(
138
+ Effect.sync(() => Queue.offerUnsafe(outbox, new Socket.CloseEvent(1011, "attach failed"))),
139
+ ),
140
+ ),
141
+ ),
142
+ Effect.forkScoped,
143
+ )
144
+ yield* runPtySocket({
145
+ socket,
146
+ outbox,
147
+ // Frames should be text, but binary frames are accepted and decoded as UTF-8.
148
+ onMessage: (message) =>
149
+ Effect.sync(() => transport.deliver(typeof message === "string" ? message : decoder.decode(message))),
150
+ detach: () => {
151
+ state.disconnected = true
152
+ transport.ended()
153
+ },
154
+ })
155
+ return HttpServerResponse.empty()
156
+ }).pipe(Effect.scoped, Effect.provide(locations.get(ref)), locationErrors)
157
+ }),
158
+ )
159
+ }),
160
+ )
@@ -0,0 +1,44 @@
1
+ import { Database } from "@zyro-sec/core/database/database"
2
+ import { SessionBlob } from "@zyro-sec/core/session/blob"
3
+ import { FileNotFoundError } from "@zyro-sec/protocol/errors"
4
+ import { Effect } from "effect"
5
+ import { type HttpServerRequest, HttpServerResponse } from "effect/http"
6
+ import { ContentHeaders } from "../content-headers"
7
+
8
+ const INLINE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"])
9
+ const CACHE_CONTROL = "private, max-age=31536000, immutable"
10
+
11
+ /** `media.get` in the `server.experimental` group; serves only blobs a message or inbox item still references. */
12
+ export const makeMediaGet = Effect.gen(function* () {
13
+ const { db } = yield* Database.Service
14
+ return (hash: string, request: HttpServerRequest.HttpServerRequest) =>
15
+ Effect.gen(function* () {
16
+ const path = `/api/experimental/media/${hash}`
17
+ const blob = yield* SessionBlob.read(db, hash)
18
+ if (!blob) return yield* new FileNotFoundError({ path, message: `Media blob not found: ${hash}` })
19
+ const etag = `"${hash}"`
20
+ const inline = INLINE_IMAGE_MIMES.has(blob.mime)
21
+ const headers = {
22
+ "cache-control": CACHE_CONTROL,
23
+ etag,
24
+ "content-disposition": ContentHeaders.disposition(""),
25
+ "content-security-policy": ContentHeaders.CONTENT_SECURITY_POLICY,
26
+ "x-content-type-options": "nosniff",
27
+ }
28
+ if (matchesIfNoneMatch(request.headers["if-none-match"], etag))
29
+ return HttpServerResponse.empty({ status: 304, headers })
30
+ return HttpServerResponse.uint8Array(blob.data, {
31
+ status: 200,
32
+ contentType: inline ? blob.mime : "application/octet-stream",
33
+ headers,
34
+ })
35
+ })
36
+ })
37
+
38
+ function matchesIfNoneMatch(ifNoneMatch: string | undefined, etag: string) {
39
+ if (ifNoneMatch === undefined) return false
40
+ return ifNoneMatch.split(",").some((tag) => {
41
+ const trimmed = tag.trim()
42
+ return trimmed === "*" || trimmed.replace(/^w\//i, "") === etag
43
+ })
44
+ }
@@ -0,0 +1,82 @@
1
+ import { SessionMessage } from "@zyro-sec/core/session/message"
2
+ import { Session } from "@zyro-sec/core/session"
3
+ import { Effect, Option, Schema } from "effect"
4
+ import { HttpServerResponse } from "effect/http"
5
+ import { HttpApiBuilder } from "effect/http-api"
6
+ import { Api } from "../api"
7
+ import { wantsMediaRefs } from "../media-uri"
8
+ import { InvalidCursorError } from "@zyro-sec/protocol/errors"
9
+ import { SessionMediaMessagesResponse } from "@zyro-sec/protocol/groups/message"
10
+ import { failedMessageDecode, missingSession } from "./session-error"
11
+
12
+ const DefaultMessagesLimit = 50
13
+
14
+ const Cursor = Schema.Struct({
15
+ id: SessionMessage.ID,
16
+ order: Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")]),
17
+ direction: Schema.Union([Schema.Literal("previous"), Schema.Literal("next")]),
18
+ })
19
+
20
+ const decodeCursor = Schema.decodeUnknownOption(Schema.fromJsonString(Cursor))
21
+
22
+ const cursor = {
23
+ encode(message: { readonly id: SessionMessage.ID }, order: "asc" | "desc", direction: "previous" | "next") {
24
+ return Buffer.from(JSON.stringify({ id: message.id, order, direction })).toString("base64url")
25
+ },
26
+ decode(input: string) {
27
+ return decodeCursor(Buffer.from(input, "base64url").toString("utf8"))
28
+ },
29
+ }
30
+
31
+ export const MessageHandler = HttpApiBuilder.group(Api, "server.message", (handlers) =>
32
+ Effect.gen(function* () {
33
+ const session = yield* Session.Service
34
+
35
+ return handlers.handle(
36
+ "session.messages",
37
+ Effect.fn(function* (ctx) {
38
+ if (ctx.query.cursor && ctx.query.order !== undefined)
39
+ return yield* new InvalidCursorError({ message: "Cursor cannot be combined with order" })
40
+ const decoded = ctx.query.cursor
41
+ ? (Option.getOrUndefined(cursor.decode(ctx.query.cursor)) ??
42
+ (yield* new InvalidCursorError({ message: "Invalid cursor" })))
43
+ : undefined
44
+ const order = decoded?.order ?? ctx.query.order ?? "desc"
45
+ const input = {
46
+ sessionID: ctx.params.sessionID,
47
+ limit: ctx.query.limit ?? DefaultMessagesLimit,
48
+ order,
49
+ type: ctx.query.type,
50
+ cursor: decoded ? { id: decoded.id, direction: decoded.direction } : undefined,
51
+ }
52
+ const page = <Message extends { readonly id: SessionMessage.ID }>(messages: ReadonlyArray<Message>) => {
53
+ const first = messages[0]
54
+ const last = messages.at(-1)
55
+ return {
56
+ data: messages,
57
+ cursor: {
58
+ previous: first ? cursor.encode(first, order, "previous") : undefined,
59
+ next: last ? cursor.encode(last, order, "next") : undefined,
60
+ },
61
+ }
62
+ }
63
+ if (wantsMediaRefs(ctx.request)) {
64
+ const messages = yield* session
65
+ .messagesWithRefs(input)
66
+ .pipe(
67
+ Effect.catchTag("Session.NotFoundError", missingSession),
68
+ Effect.catchTag("Session.MessageDecodeError", failedMessageDecode),
69
+ )
70
+ return yield* HttpServerResponse.schemaJson(SessionMediaMessagesResponse)(page(messages)).pipe(Effect.orDie)
71
+ }
72
+ const messages = yield* session
73
+ .messages(input)
74
+ .pipe(
75
+ Effect.catchTag("Session.NotFoundError", missingSession),
76
+ Effect.catchTag("Session.MessageDecodeError", failedMessageDecode),
77
+ )
78
+ return page(messages)
79
+ }),
80
+ )
81
+ }),
82
+ )
@@ -0,0 +1,13 @@
1
+ import { V1Migration } from "@zyro-sec/core/database/v1-migration"
2
+ import { HttpApiBuilder } from "effect/http-api"
3
+ import { Effect } from "effect"
4
+ import { Api } from "../api"
5
+
6
+ export const MigrationHandler = HttpApiBuilder.group(Api, "server.migration", (handlers) =>
7
+ handlers.handle(
8
+ "migration.v1.status",
9
+ Effect.fn(function* () {
10
+ return yield* V1Migration.status()
11
+ }),
12
+ ),
13
+ )
@@ -0,0 +1,25 @@
1
+ import { Model } from "@zyro-sec/core/model"
2
+ import { Effect } from "effect"
3
+ import { HttpApiBuilder } from "effect/http-api"
4
+ import { Api } from "../api"
5
+ import { response } from "../location"
6
+
7
+ export const ModelHandler = HttpApiBuilder.group(Api, "server.model", (handlers) =>
8
+ Effect.gen(function* () {
9
+ return handlers
10
+ .handle(
11
+ "model.list",
12
+ Effect.fn(function* (ctx) {
13
+ const models = yield* Model.Service
14
+ return yield* response(models.available(ctx.query.types))
15
+ }),
16
+ )
17
+ .handle(
18
+ "model.default",
19
+ Effect.fn(function* () {
20
+ const models = yield* Model.Service
21
+ return yield* response(models.default())
22
+ }),
23
+ )
24
+ }),
25
+ )