@zyro-sec/server 1.0.0 → 1.0.2

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 (130) hide show
  1. package/package.json +15 -18
  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
@@ -0,0 +1,261 @@
1
+ import { expect } from "bun:test"
2
+ import { Effect } from "effect"
3
+ import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"
4
+ import { it } from "../../core/test/lib/effect"
5
+ import { ServerProcess } from "../src/process"
6
+
7
+ it.live("authenticates API requests behind the frontend transform while allowing browser preflight", () =>
8
+ Effect.gen(function* () {
9
+ const fallback = "fallback".repeat(256)
10
+ const server = yield* ServerProcess.start<never, never>(
11
+ {
12
+ hostname: "127.0.0.1",
13
+ port: 0,
14
+ password: "secret",
15
+ cors: ["http://192.168.1.10:3001", "https://example.com"],
16
+ app: { version: "test-version" },
17
+ database: { path: ":memory:" },
18
+ },
19
+ undefined,
20
+ (api) =>
21
+ Effect.gen(function* () {
22
+ const request = yield* HttpServerRequest.HttpServerRequest
23
+ const url = new URL(request.url, "http://localhost")
24
+ if (url.pathname === "/api" || url.pathname.startsWith("/api/") || url.pathname === "/openapi.json")
25
+ return yield* api
26
+ return HttpServerResponse.raw(fallback, { contentType: "text/plain" })
27
+ }),
28
+ )
29
+ const response = yield* Effect.promise(() =>
30
+ fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
31
+ method: "OPTIONS",
32
+ headers: {
33
+ origin: "http://localhost:3000",
34
+ "access-control-request-method": "GET",
35
+ "access-control-request-headers": "authorization",
36
+ },
37
+ }),
38
+ )
39
+
40
+ expect(response.status).toBe(204)
41
+ expect(response.headers.get("access-control-allow-origin")).toBe("http://localhost:3000")
42
+ expect(response.headers.get("access-control-allow-headers")).toBe("authorization")
43
+
44
+ const status = yield* Effect.promise(() =>
45
+ fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
46
+ headers: {
47
+ authorization: `Basic ${btoa("opencode:secret")}`,
48
+ origin: "http://localhost:3000",
49
+ },
50
+ }),
51
+ )
52
+
53
+ expect(status.status).toBe(200)
54
+ expect(status.headers.get("access-control-allow-origin")).toBe("http://localhost:3000")
55
+ expect(yield* Effect.promise(() => status.json())).toMatchObject({ version: "test-version" })
56
+
57
+ yield* Effect.forEach(
58
+ ["http://192.168.1.10:3001", "https://example.com", "https://untrusted.example.com"],
59
+ (origin) =>
60
+ Effect.gen(function* () {
61
+ const allowed = origin === "https://untrusted.example.com" ? null : origin
62
+ const preflight = yield* Effect.promise(() =>
63
+ fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
64
+ method: "OPTIONS",
65
+ headers: {
66
+ origin,
67
+ "access-control-request-method": "GET",
68
+ "access-control-request-headers": "authorization",
69
+ },
70
+ }),
71
+ )
72
+ expect(preflight.status).toBe(204)
73
+ expect(preflight.headers.get("access-control-allow-origin")).toBe(allowed)
74
+
75
+ const status = yield* Effect.promise(() =>
76
+ fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
77
+ headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
78
+ }),
79
+ )
80
+ expect(status.status).toBe(200)
81
+ expect(status.headers.get("access-control-allow-origin")).toBe(allowed)
82
+ yield* Effect.promise(() => status.arrayBuffer())
83
+
84
+ const denied = yield* Effect.promise(() =>
85
+ fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), { headers: { origin } }),
86
+ )
87
+ expect(denied.status).toBe(401)
88
+ expect(denied.headers.get("access-control-allow-origin")).toBe(allowed)
89
+ yield* Effect.promise(() => denied.arrayBuffer())
90
+ }),
91
+ )
92
+
93
+ const event = yield* Effect.promise(() =>
94
+ fetch(new URL("/api/event", HttpServer.formatAddress(server.address)), {
95
+ headers: {
96
+ "accept-encoding": "br",
97
+ authorization: `Basic ${btoa("opencode:secret")}`,
98
+ },
99
+ }),
100
+ )
101
+ expect(event.status).toBe(200)
102
+ expect(event.headers.get("content-encoding")).toBeNull()
103
+ const body = event.body
104
+ if (!body) return yield* Effect.die(new Error("Event response has no body"))
105
+ const reader = body.getReader()
106
+ yield* Effect.promise(() => readUntil(reader, "server.connected"))
107
+ yield* server.updateAvailable("2.0.0")
108
+ yield* Effect.promise(() => readUntil(reader, "installation.update-available"))
109
+ yield* server.updated("2.0.0")
110
+ yield* Effect.promise(() => readUntil(reader, "installation.updated"))
111
+ yield* Effect.promise(() => reader.cancel())
112
+
113
+ const missing = yield* Effect.promise(() =>
114
+ fetch(new URL("/missing", HttpServer.formatAddress(server.address)), {
115
+ headers: {
116
+ "accept-encoding": "br",
117
+ authorization: `Basic ${btoa("opencode:secret")}`,
118
+ },
119
+ }),
120
+ )
121
+ expect(missing.status).toBe(200)
122
+ expect(missing.headers.get("content-encoding")).toBe("br")
123
+ expect(missing.headers.get("content-type")).toBe("text/plain")
124
+ expect(missing.headers.get("vary")?.toLowerCase()).toContain("accept-encoding")
125
+ expect(yield* Effect.promise(() => missing.text())).toBe(fallback)
126
+
127
+ yield* Effect.forEach(["/api", "/api/missing", "/openapi.json"], (pathname) =>
128
+ Effect.gen(function* () {
129
+ const response = yield* Effect.promise(() => fetch(new URL(pathname, HttpServer.formatAddress(server.address))))
130
+ expect(response.status).toBe(401)
131
+ expect(yield* Effect.promise(() => response.json())).toEqual({
132
+ _tag: "UnauthorizedError",
133
+ message: "Authentication required",
134
+ })
135
+ }),
136
+ )
137
+
138
+ yield* Effect.forEach(["/", "/workspace/example", "/_assets/app.js", "/icons/icon.svg", "/sw.js"], (pathname) =>
139
+ Effect.gen(function* () {
140
+ yield* Effect.forEach(["GET", "HEAD"], (method) =>
141
+ Effect.gen(function* () {
142
+ yield* Effect.forEach([undefined, `Basic ${btoa("opencode:wrong")}`], (authorization) =>
143
+ Effect.gen(function* () {
144
+ const response = yield* Effect.promise(() =>
145
+ fetch(new URL(pathname, HttpServer.formatAddress(server.address)), {
146
+ method,
147
+ headers: authorization ? { authorization } : undefined,
148
+ }),
149
+ )
150
+ expect(response.status).toBe(200)
151
+ expect(response.headers.get("www-authenticate")).toBeNull()
152
+ expect(yield* Effect.promise(() => response.text())).toBe(method === "HEAD" ? "" : fallback)
153
+ }),
154
+ )
155
+ const response = yield* Effect.promise(() =>
156
+ fetch(new URL(pathname, HttpServer.formatAddress(server.address)), {
157
+ method,
158
+ headers: { authorization: `Basic ${btoa("opencode:secret")}` },
159
+ }),
160
+ )
161
+ expect(response.status).toBe(200)
162
+ expect(yield* Effect.promise(() => response.text())).toBe(method === "HEAD" ? "" : fallback)
163
+ }),
164
+ )
165
+ }),
166
+ )
167
+ }),
168
+ )
169
+
170
+ it.live("pairing links sign in browsers with a cookie and API clients with a token", () =>
171
+ Effect.gen(function* () {
172
+ const server = yield* ServerProcess.start<never, never>({
173
+ hostname: "127.0.0.1",
174
+ port: 0,
175
+ password: "secret",
176
+ app: { version: "test-version" },
177
+ database: { path: ":memory:" },
178
+ })
179
+ const base = HttpServer.formatAddress(server.address)
180
+ const request = (pathname: string, init?: RequestInit) =>
181
+ Effect.promise(() => fetch(new URL(pathname, base), { redirect: "manual", ...init }))
182
+ const pair = Effect.gen(function* () {
183
+ const response = yield* request("/api/pair", {
184
+ method: "POST",
185
+ headers: { authorization: `Basic ${btoa("opencode:secret")}` },
186
+ })
187
+ expect(response.status).toBe(200)
188
+ return (yield* Effect.promise(() => response.json())) as { code: string; expires_in: number }
189
+ })
190
+
191
+ const rejected = yield* request("/api/pair", { method: "POST" })
192
+ expect(rejected.status).toBe(401)
193
+ expect(rejected.headers.get("www-authenticate")).toBe('Basic realm="Secure Area"')
194
+ // A Basic challenge on fetch makes browsers show a native prompt instead of the app's sign-in screen.
195
+ const fetched = yield* request("/api/info", { headers: { "sec-fetch-mode": "cors" } })
196
+ expect(fetched.status).toBe(401)
197
+ expect(fetched.headers.get("www-authenticate")).toBeNull()
198
+
199
+ const browser = yield* pair
200
+ expect(browser.expires_in).toBe(300)
201
+ const redirect = yield* request(`/auth/connect/${browser.code}`, { headers: { accept: "text/html" } })
202
+ expect(redirect.status).toBe(302)
203
+ expect(redirect.headers.get("location")).toBe("/")
204
+ const setCookie = redirect.headers.get("set-cookie") ?? ""
205
+ expect(setCookie).toContain(`opencode_session_${new URL(base).port}=`)
206
+ expect(setCookie).toContain("HttpOnly")
207
+ expect(setCookie).toContain("SameSite=Lax")
208
+ const cookie = setCookie.split(";")[0]
209
+
210
+ const reused = yield* request(`/auth/connect/${browser.code}`, { headers: { accept: "text/html" } })
211
+ expect(reused.status).toBe(401)
212
+ expect(yield* Effect.promise(() => reused.text())).toContain("opencode pair")
213
+
214
+ expect((yield* request("/api/info", { headers: { cookie } })).status).toBe(200)
215
+ expect((yield* request("/api/info", { headers: { cookie, origin: base } })).status).toBe(200)
216
+ expect((yield* request("/api/info", { headers: { cookie, origin: "http://127.0.0.1:1" } })).status).toBe(401)
217
+ expect((yield* request("/api/info", { headers: { cookie: `${cookie}x` } })).status).toBe(401)
218
+
219
+ const client = yield* pair
220
+ const redeemed = yield* request(`/auth/connect/${client.code}`)
221
+ expect(redeemed.status).toBe(200)
222
+ const session = (yield* Effect.promise(() => redeemed.json())) as { token: string }
223
+ expect(
224
+ (yield* request("/api/info", { headers: { authorization: `Basic ${btoa(`opencode:${session.token}`)}` } }))
225
+ .status,
226
+ ).toBe(200)
227
+ expect((yield* request(`/auth/connect/${client.code}`)).status).toBe(401)
228
+ expect((yield* request("/auth/connect/unknown")).status).toBe(401)
229
+ }),
230
+ )
231
+
232
+ async function readUntil(reader: ReadableStreamDefaultReader<Uint8Array>, expected: string) {
233
+ while (true) {
234
+ const next = await reader.read()
235
+ if (next.done) throw new Error(`Event stream ended before ${expected}`)
236
+ if (new TextDecoder().decode(next.value).includes(expected)) return
237
+ }
238
+ }
239
+
240
+ it.live("server info lists remote URLs alongside local addresses while they are available", () =>
241
+ Effect.gen(function* () {
242
+ const remote = { urls: ["https://example.opentunnel.xyz"] as ReadonlyArray<string> }
243
+ const server = yield* ServerProcess.start<never, never>(
244
+ { hostname: "127.0.0.1", port: 0, password: "secret", database: { path: ":memory:" } },
245
+ undefined,
246
+ undefined,
247
+ () => remote.urls,
248
+ )
249
+ const base = HttpServer.formatAddress(server.address)
250
+ const info = () =>
251
+ Effect.promise(() =>
252
+ fetch(new URL("/api/info", base), { headers: { authorization: `Basic ${btoa("opencode:secret")}` } }).then(
253
+ (response) => response.json() as Promise<{ urls: ReadonlyArray<string> }>,
254
+ ),
255
+ )
256
+
257
+ expect((yield* info()).urls).toEqual([base, "https://example.opentunnel.xyz"])
258
+ remote.urls = []
259
+ expect((yield* info()).urls).toEqual([base])
260
+ }),
261
+ )
@@ -0,0 +1,88 @@
1
+ import { expect } from "bun:test"
2
+ import { SdkPlugins } from "@zyro-sec/core/plugin/sdk"
3
+ import { Plugin } from "@zyro-sec/plugin/effect"
4
+ import { Context, Deferred, Effect, Layer } from "effect"
5
+ import { HttpEffect, HttpRouter, HttpServer } from "effect/http"
6
+ import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
7
+ import { it } from "../../core/test/lib/effect"
8
+ import { createRoutes } from "../src/routes"
9
+
10
+ it.live(
11
+ "catalog reads answer while plugins are still activating",
12
+ () =>
13
+ Effect.gen(function* () {
14
+ const tmp = yield* tmpdirScoped("opencode-provider-endpoints-")
15
+ const started = yield* Deferred.make<void>()
16
+ const release = yield* Deferred.make<void>()
17
+ const context = yield* Layer.build(
18
+ createRoutes({
19
+ password: "secret",
20
+ database: { path: ":memory:" },
21
+ models: { fetch: false },
22
+ fs: { filewatcher: false },
23
+ config: {
24
+ directory: tmp.path,
25
+ project: false,
26
+ content: JSON.stringify({
27
+ providers: {
28
+ custom: {
29
+ name: "Configured Custom Provider",
30
+ package: "@zyro-sec/ai/providers/openai-compatible",
31
+ settings: { apiKey: "secret" },
32
+ models: { chat: {} },
33
+ },
34
+ },
35
+ agents: { reviewer: { description: "Reviews changes" } },
36
+ }),
37
+ },
38
+ }).pipe(Layer.provide(HttpServer.layerServices)),
39
+ )
40
+ const sdk = Context.get(context, SdkPlugins.Service)
41
+ yield* sdk.register(
42
+ Plugin.define({
43
+ id: "slow-plugin",
44
+ effect: () =>
45
+ Effect.gen(function* () {
46
+ yield* Deferred.succeed(started, undefined)
47
+ yield* Deferred.await(release)
48
+ }),
49
+ }),
50
+ )
51
+ const handler = Context.get(context, HttpRouter.HttpRouter)
52
+ .asHttpEffect()
53
+ .pipe(HttpEffect.toWebHandlerWith(context))
54
+ const request = (method: "GET" | "POST", route: string) =>
55
+ Effect.promise((signal) => {
56
+ const url = new URL(route, "http://opencode.local")
57
+ url.searchParams.set("location[directory]", tmp.path)
58
+ return handler(
59
+ new Request(url, {
60
+ method,
61
+ headers: { authorization: `Basic ${btoa("opencode:secret")}` },
62
+ signal,
63
+ }),
64
+ )
65
+ })
66
+ // Config providers and agents activate after SDK plugins. Reads return the current snapshot without waiting,
67
+ // and clients refresh on the matching *.updated events.
68
+ yield* request("GET", "/api/provider").pipe(Effect.timeout("2 seconds"))
69
+ yield* Deferred.await(started)
70
+ for (const route of ["/api/provider", "/api/agent", "/api/model", "/api/skill", "/api/integration"]) {
71
+ const response = yield* request("GET", route).pipe(Effect.timeout("2 seconds"))
72
+ expect(response.status).toBe(200)
73
+ }
74
+ const list = yield* request("GET", "/api/provider").pipe(Effect.timeout("2 seconds"))
75
+ expect(yield* Effect.promise(() => list.json())).toMatchObject({
76
+ location: { directory: tmp.path },
77
+ data: expect.not.arrayContaining([expect.objectContaining({ id: "custom" })]),
78
+ })
79
+ const get = yield* request("GET", "/api/provider/custom").pipe(Effect.timeout("2 seconds"))
80
+ expect(get.status).toBe(404)
81
+ expect(yield* Effect.promise(() => get.json())).toMatchObject({
82
+ _tag: "ProviderNotFoundError",
83
+ providerID: "custom",
84
+ })
85
+ yield* Deferred.succeed(release, undefined)
86
+ }),
87
+ 15_000,
88
+ )
@@ -0,0 +1,240 @@
1
+ import { expect, test } from "bun:test"
2
+ import { Cause, Effect, Fiber, Queue } from "effect"
3
+ import { Socket } from "effect/socket"
4
+ import FastCheck from "fast-check"
5
+ import { type Outbound, runPtySocket } from "../src/handlers/pty-socket"
6
+
7
+ // Latencies are mostly scheduler yields so interleavings stay dense and fast; a few are real sleeps.
8
+ type Latency = { readonly yields: number } | { readonly millis: number }
9
+
10
+ type Step =
11
+ | { readonly type: "inbound"; readonly message: string | Uint8Array }
12
+ | { readonly type: "outbound"; readonly frame: string | Uint8Array }
13
+ | { readonly type: "serverClose"; readonly code: number }
14
+ | { readonly type: "clientClose"; readonly code: number }
15
+ | { readonly type: "readError" }
16
+ | { readonly type: "writeError" }
17
+ | { readonly type: "interrupt" }
18
+
19
+ type Scenario = {
20
+ readonly replay: ReadonlyArray<string | Uint8Array>
21
+ readonly steps: ReadonlyArray<{ readonly step: Step; readonly delay: Latency }>
22
+ readonly reader: Latency
23
+ readonly open: Latency | undefined
24
+ readonly message: ReadonlyArray<Latency>
25
+ readonly write: ReadonlyArray<Latency>
26
+ readonly batch: number
27
+ }
28
+
29
+ type Terminal = "close" | "readError" | "writeError" | "interrupt"
30
+
31
+ type Entry =
32
+ | { readonly type: "reader" | "openStart" | "openEnd" | "detach" }
33
+ | { readonly type: "messageStart" | "messageEnd"; readonly message: string | Uint8Array }
34
+ | { readonly type: "write"; readonly chunk: Outbound }
35
+ | { readonly type: "terminal"; readonly terminal: Terminal }
36
+
37
+ const latency: FastCheck.Arbitrary<Latency> = FastCheck.oneof(
38
+ { weight: 12, arbitrary: FastCheck.record({ yields: FastCheck.nat(6) }) },
39
+ { weight: 1, arbitrary: FastCheck.record({ millis: FastCheck.integer({ min: 1, max: 3 }) }) },
40
+ )
41
+ const payload = FastCheck.oneof(FastCheck.string({ maxLength: 8 }), FastCheck.uint8Array({ maxLength: 8 }))
42
+ const code = FastCheck.constantFrom(1000, 1001, 1006, 4404)
43
+ const step: FastCheck.Arbitrary<Step> = FastCheck.oneof(
44
+ { weight: 8, arbitrary: FastCheck.record({ type: FastCheck.constant("inbound"), message: payload }) },
45
+ { weight: 8, arbitrary: FastCheck.record({ type: FastCheck.constant("outbound"), frame: payload }) },
46
+ { weight: 1, arbitrary: FastCheck.record({ type: FastCheck.constant("serverClose"), code }) },
47
+ { weight: 1, arbitrary: FastCheck.record({ type: FastCheck.constant("clientClose"), code }) },
48
+ { weight: 1, arbitrary: FastCheck.record({ type: FastCheck.constant("readError") }) },
49
+ { weight: 1, arbitrary: FastCheck.record({ type: FastCheck.constant("writeError") }) },
50
+ { weight: 1, arbitrary: FastCheck.record({ type: FastCheck.constant("interrupt") }) },
51
+ )
52
+ const scenario: FastCheck.Arbitrary<Scenario> = FastCheck.record({
53
+ replay: FastCheck.array(payload, { maxLength: 4 }),
54
+ steps: FastCheck.array(FastCheck.record({ step, delay: latency }), { maxLength: 24 }),
55
+ reader: latency,
56
+ open: FastCheck.option(latency, { nil: undefined }),
57
+ message: FastCheck.array(latency, { minLength: 1, maxLength: 4 }),
58
+ write: FastCheck.array(latency, { minLength: 1, maxLength: 4 }),
59
+ batch: FastCheck.integer({ min: 1, max: 3 }),
60
+ })
61
+
62
+ const wait = (value: Latency) =>
63
+ Effect.gen(function* () {
64
+ if ("millis" in value) return yield* Effect.sleep(value.millis)
65
+ for (let i = 0; i < value.yields; i++) yield* Effect.yieldNow
66
+ })
67
+
68
+ const nonEmpty = <A>(values: ReadonlyArray<A>): values is readonly [A, ...Array<A>] => values.length > 0
69
+
70
+ const socketError = (reason: Socket.SocketError["reason"]) => new Socket.SocketError({ reason })
71
+
72
+ // Drives one connection through the scenario against an in-memory socket and records every observable event.
73
+ const simulate = (input: Scenario) =>
74
+ Effect.gen(function* () {
75
+ const inbound = yield* Queue.unbounded<string | Uint8Array, Socket.SocketError>()
76
+ const outbox = yield* Queue.unbounded<Outbound>()
77
+ const log: Entry[] = []
78
+ const sent: Array<string | Uint8Array> = []
79
+ const offered: Outbound[] = [...input.replay]
80
+ const state = { failNextWrite: false, writes: 0, messages: 0, detached: 0 }
81
+ yield* Queue.offerAll(outbox, input.replay)
82
+
83
+ const socket = Socket.make({
84
+ reader: wait(input.reader).pipe(
85
+ Effect.tap(() => Effect.sync(() => log.push({ type: "reader" }))),
86
+ Effect.as({
87
+ pull: Queue.takeBetween(inbound, 1, input.batch).pipe(
88
+ Effect.tapError((error) =>
89
+ Effect.sync(() =>
90
+ log.push({
91
+ type: "terminal",
92
+ terminal: error.reason._tag === "SocketCloseError" ? "close" : "readError",
93
+ }),
94
+ ),
95
+ ),
96
+ Effect.flatMap((batch) =>
97
+ nonEmpty(batch) ? Effect.succeed(batch) : Effect.die(new Error("empty batch")),
98
+ ),
99
+ ),
100
+ upgrade: Socket.SocketUpgradeError.unsupported,
101
+ }),
102
+ ),
103
+ writer: Effect.succeed({
104
+ write: (chunk: Outbound) =>
105
+ Effect.gen(function* () {
106
+ yield* wait(input.write[state.writes++ % input.write.length]!)
107
+ if (state.failNextWrite) {
108
+ state.failNextWrite = false
109
+ log.push({ type: "terminal", terminal: "writeError" })
110
+ return yield* socketError(new Socket.SocketWriteError({ cause: new Error("write failed") }))
111
+ }
112
+ log.push({ type: "write", chunk })
113
+ if (chunk instanceof Socket.CloseEvent) log.push({ type: "terminal", terminal: "close" })
114
+ }),
115
+ writeAll: () => Effect.die(new Error("runPtySocket writes frames one at a time")),
116
+ }),
117
+ })
118
+
119
+ const open = input.open
120
+ const run = yield* runPtySocket({
121
+ socket,
122
+ outbox,
123
+ onOpen:
124
+ open &&
125
+ Effect.gen(function* () {
126
+ log.push({ type: "openStart" })
127
+ yield* wait(open)
128
+ log.push({ type: "openEnd" })
129
+ }),
130
+ onMessage: (message) =>
131
+ Effect.gen(function* () {
132
+ log.push({ type: "messageStart", message })
133
+ yield* wait(input.message[state.messages++ % input.message.length]!)
134
+ log.push({ type: "messageEnd", message })
135
+ }),
136
+ detach: () => {
137
+ state.detached++
138
+ log.push({ type: "detach" })
139
+ },
140
+ }).pipe(Effect.scoped, Effect.forkChild({ startImmediately: true }))
141
+
142
+ for (const { step, delay } of input.steps) {
143
+ yield* wait(delay)
144
+ if (step.type === "inbound" && (yield* Queue.offer(inbound, step.message))) sent.push(step.message)
145
+ if (step.type === "outbound") {
146
+ offered.push(step.frame)
147
+ yield* Queue.offer(outbox, step.frame)
148
+ }
149
+ if (step.type === "serverClose") {
150
+ const close = new Socket.CloseEvent(step.code)
151
+ offered.push(close)
152
+ yield* Queue.offer(outbox, close)
153
+ }
154
+ if (step.type === "clientClose")
155
+ yield* Queue.fail(inbound, socketError(new Socket.SocketCloseError({ code: step.code })))
156
+ if (step.type === "readError")
157
+ yield* Queue.fail(inbound, socketError(new Socket.SocketReadError({ cause: new Error("reset") })))
158
+ if (step.type === "writeError") state.failNextWrite = true
159
+ if (step.type === "interrupt") {
160
+ log.push({ type: "terminal", terminal: "interrupt" })
161
+ // Fiber.interrupt waits for the run to finish, so a run that ignores interruption would stall here.
162
+ if ((yield* Fiber.interrupt(run).pipe(Effect.timeoutOption("2 seconds")))._tag === "None")
163
+ return yield* Effect.die(new Error("runPtySocket ignored interruption"))
164
+ }
165
+ }
166
+ // Every real connection eventually closes; this bounds runs whose scenario never ended them.
167
+ yield* Queue.fail(inbound, socketError(new Socket.SocketCloseError({ code: 1000 })))
168
+ const exit = yield* Fiber.await(run).pipe(Effect.timeoutOption("5 seconds"))
169
+ return { exit, log, sent, offered, state, hasOpen: open !== undefined }
170
+ })
171
+
172
+ function verify(result: Effect.Success<ReturnType<typeof simulate>>) {
173
+ // The run terminates within the scheduler bound.
174
+ if (result.exit._tag === "None") throw new Error("runPtySocket did not terminate")
175
+ const exit = result.exit.value
176
+ const log = result.log
177
+ const index = (predicate: (entry: Entry) => boolean) => log.findIndex(predicate)
178
+ const detach = index((entry) => entry.type === "detach")
179
+
180
+ // detach runs exactly once, whatever ended the connection.
181
+ expect(result.state.detached).toBe(1)
182
+
183
+ // Outbound frames are written in queue order and nothing follows a close frame or detach.
184
+ const written = log.flatMap((entry) => (entry.type === "write" ? [entry.chunk] : []))
185
+ expect(written.every((chunk, position) => chunk === result.offered[position])).toBeTrue()
186
+ const close = written.findIndex((chunk) => chunk instanceof Socket.CloseEvent)
187
+ if (close !== -1) expect(close).toBe(written.length - 1)
188
+ expect(log.slice(detach).some((entry) => entry.type === "write")).toBeFalse()
189
+
190
+ // Inbound messages reach onMessage one at a time, in order, after onOpen and before detach.
191
+ const started = log.flatMap((entry) => (entry.type === "messageStart" ? [entry.message] : []))
192
+ expect(started).toEqual(result.sent.slice(0, started.length))
193
+ const reader = index((entry) => entry.type === "reader")
194
+ const openStart = index((entry) => entry.type === "openStart")
195
+ const openEnd = index((entry) => entry.type === "openEnd")
196
+ if (openStart !== -1) expect(openStart).toBeGreaterThan(reader)
197
+ const firstMessage = index((entry) => entry.type === "messageStart")
198
+ if (firstMessage !== -1) {
199
+ expect(firstMessage).toBeGreaterThan(reader)
200
+ if (result.hasOpen) expect(firstMessage).toBeGreaterThan(openEnd)
201
+ expect(firstMessage).toBeLessThan(detach)
202
+ }
203
+ expect(log.slice(detach).some((entry) => entry.type === "messageStart")).toBeFalse()
204
+ let inFlight = 0
205
+ for (const entry of log) {
206
+ if (entry.type === "messageStart") inFlight++
207
+ if (entry.type === "messageEnd") inFlight--
208
+ expect(inFlight).toBeLessThanOrEqual(1)
209
+ }
210
+
211
+ // Clean closes succeed, socket failures die, and interruption is honored. The outcome follows the first
212
+ // close or failure the run observed; an interrupt that lands while the race settles may still win, but
213
+ // nothing observed after an interrupt may decide the outcome.
214
+ const terminals = log.flatMap((entry) => (entry.type === "terminal" ? [entry.terminal] : []))
215
+ if (exit._tag === "Failure" && Cause.hasInterrupts(exit.cause)) {
216
+ expect(terminals).toContain("interrupt")
217
+ return
218
+ }
219
+ const first = terminals[0]
220
+ if (first === "close") {
221
+ expect(exit._tag).toBe("Success")
222
+ return
223
+ }
224
+ if (first === "interrupt" || first === undefined) throw new Error(`Interrupt was not honored: ${exit._tag}`)
225
+ if (exit._tag !== "Failure" || !Cause.hasDies(exit.cause))
226
+ throw new Error(`Expected the run to die after ${first}, got ${exit._tag}`)
227
+ const defect = Cause.squash(exit.cause)
228
+ if (!Socket.isSocketError(defect)) throw new Error(`Expected a socket error defect, got ${String(defect)}`)
229
+ expect(defect.reason._tag).toBe(first === "readError" ? "SocketReadError" : "SocketWriteError")
230
+ }
231
+
232
+ test(
233
+ "runPtySocket preserves ordering, detaches once, and ends correctly under random interleavings",
234
+ () =>
235
+ FastCheck.assert(
236
+ FastCheck.asyncProperty(scenario, async (input) => verify(await Effect.runPromise(simulate(input)))),
237
+ { numRuns: 300 },
238
+ ),
239
+ 60_000,
240
+ )
@@ -0,0 +1,89 @@
1
+ import { expect } from "bun:test"
2
+ import { Effect, Exit, Fiber, Queue } from "effect"
3
+ import { Socket } from "effect/socket"
4
+ import { it } from "../../core/test/lib/effect"
5
+ import { type Outbound, runPtySocket } from "../src/handlers/pty-socket"
6
+
7
+ const connection = Effect.gen(function* () {
8
+ const inbound = yield* Queue.unbounded<string | Uint8Array, Socket.SocketError>()
9
+ const outbox = yield* Queue.unbounded<Outbound>()
10
+ const state = {
11
+ opened: false,
12
+ detached: false,
13
+ received: [] as Array<string | Uint8Array>,
14
+ written: [] as Outbound[],
15
+ }
16
+ const socket = Socket.make({
17
+ reader: Effect.succeed({
18
+ pull: Queue.take(inbound).pipe(Effect.map((message) => [message] as const)),
19
+ upgrade: Socket.SocketUpgradeError.unsupported,
20
+ }),
21
+ writer: Effect.succeed({
22
+ write: (chunk) => Effect.sync(() => void state.written.push(chunk)),
23
+ writeAll: (chunks) => Effect.sync(() => void state.written.push(...chunks)),
24
+ }),
25
+ })
26
+ const run = runPtySocket({
27
+ socket,
28
+ outbox,
29
+ onOpen: Effect.sync(() => {
30
+ state.opened = true
31
+ }),
32
+ onMessage: (message) =>
33
+ Effect.sync(() => {
34
+ expect(state.opened).toBeTrue()
35
+ state.received.push(message)
36
+ }),
37
+ detach: () => {
38
+ state.detached = true
39
+ },
40
+ })
41
+ return { inbound, outbox, state, run }
42
+ })
43
+
44
+ const fail = (reason: Socket.SocketError["reason"]) => new Socket.SocketError({ reason })
45
+
46
+ it.live("delivers input in order and detaches when the client closes", () =>
47
+ Effect.gen(function* () {
48
+ const pty = yield* connection
49
+ yield* Queue.offerAll(pty.inbound, ["a", "b"])
50
+ yield* Queue.fail(pty.inbound, fail(new Socket.SocketCloseError({ code: 1000 })))
51
+
52
+ expect(yield* Effect.exit(pty.run)).toEqual(Exit.void)
53
+ expect(pty.state.received).toEqual(["a", "b"])
54
+ expect(pty.state.detached).toBeTrue()
55
+ }),
56
+ )
57
+
58
+ it.live("writes queued output through the close frame and detaches", () =>
59
+ Effect.gen(function* () {
60
+ const pty = yield* connection
61
+ const close = new Socket.CloseEvent(1000)
62
+ yield* Queue.offerAll(pty.outbox, ["output", close, "after close"])
63
+
64
+ expect(yield* Effect.exit(pty.run)).toEqual(Exit.void)
65
+ expect(pty.state.written).toEqual(["output", close])
66
+ expect(pty.state.detached).toBeTrue()
67
+ }),
68
+ )
69
+
70
+ it.live("detaches when the socket fails while the outbox drain is blocked", () =>
71
+ Effect.gen(function* () {
72
+ const pty = yield* connection
73
+ yield* Queue.fail(pty.inbound, fail(new Socket.SocketReadError({ cause: new Error("reset") })))
74
+
75
+ expect(Exit.hasDies(yield* Effect.exit(pty.run))).toBeTrue()
76
+ expect(pty.state.detached).toBeTrue()
77
+ }),
78
+ )
79
+
80
+ it.live("detaches when interrupted", () =>
81
+ Effect.gen(function* () {
82
+ const pty = yield* connection
83
+ const fiber = yield* Effect.forkChild(pty.run, { startImmediately: true })
84
+ yield* Fiber.interrupt(fiber)
85
+
86
+ expect(pty.state.opened).toBeTrue()
87
+ expect(pty.state.detached).toBeTrue()
88
+ }),
89
+ )