@zyro-sec/server 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/package.json +15 -21
  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,242 @@
1
+ import { Artifact } from "@zyro-sec/core/artifact"
2
+ import { KV } from "@zyro-sec/core/kv"
3
+ import { Location } from "@zyro-sec/core/location"
4
+ import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
5
+ import { AbsolutePath } from "@zyro-sec/core/schema"
6
+ import { Session } from "@zyro-sec/core/session"
7
+ import {
8
+ ArtifactNotFoundError,
9
+ FileNotFoundError,
10
+ ForbiddenError,
11
+ InvalidRequestError,
12
+ ProviderNotFoundError,
13
+ ServiceUnavailableError,
14
+ } from "@zyro-sec/protocol/errors"
15
+ import { Effect } from "effect"
16
+ import { type HttpServerRequest, HttpServerResponse } from "effect/http"
17
+ import { HttpApiSchema } from "effect/http-api"
18
+ import { locationErrors, requestRef, response } from "../location"
19
+ import { missingSession } from "./session-error"
20
+
21
+ /** `artifacts.*` in the `server.experimental` group. Every route needs experimental.artifacts in the resolved Location. */
22
+ export const makeArtifact = Effect.gen(function* () {
23
+ const locations = yield* LocationServiceMap.Service
24
+ const sessions = yield* Session.Service
25
+ const kv = yield* KV.Service
26
+
27
+ const explicitDirectory = (
28
+ request: HttpServerRequest.HttpServerRequest,
29
+ location?: { readonly directory?: string; readonly workspace?: string },
30
+ ) => {
31
+ if (location?.directory !== undefined) return location.directory
32
+ const query = new URL(request.url, "http://localhost").searchParams.get("location[directory]")
33
+ if (query) return query
34
+ const header = request.headers["x-opencode-directory"]
35
+ if (!header) return undefined
36
+ try {
37
+ return decodeURIComponent(header)
38
+ } catch {
39
+ return header
40
+ }
41
+ }
42
+
43
+ const resolveLocation = (
44
+ request: HttpServerRequest.HttpServerRequest,
45
+ options: {
46
+ readonly location?: { readonly directory?: string; readonly workspace?: string }
47
+ readonly sessionID?: Session.ID
48
+ readonly artifactID?: Artifact.ID
49
+ },
50
+ ) =>
51
+ Effect.gen(function* () {
52
+ const requestedDir = explicitDirectory(request, options.location)
53
+ if (requestedDir !== undefined) {
54
+ return Location.Ref.make({ directory: AbsolutePath.make(requestedDir) })
55
+ }
56
+ if (options.sessionID !== undefined) {
57
+ const session = yield* sessions.get(options.sessionID).pipe(Effect.mapError(missingSession))
58
+ return session.location
59
+ }
60
+ if (options.artifactID !== undefined) {
61
+ const directory = yield* Artifact.locate(kv, options.artifactID)
62
+ if (directory !== undefined) {
63
+ return Location.Ref.make({ directory: AbsolutePath.make(directory) })
64
+ }
65
+ }
66
+ return requestRef(request)
67
+ })
68
+
69
+ const inLocation = <A, E>(
70
+ request: HttpServerRequest.HttpServerRequest,
71
+ options: {
72
+ readonly location?: { readonly directory?: string; readonly workspace?: string }
73
+ readonly sessionID?: Session.ID
74
+ readonly artifactID?: Artifact.ID
75
+ },
76
+ effect: Effect.Effect<A, E, Artifact.Service | Location.Service>,
77
+ ) =>
78
+ Effect.gen(function* () {
79
+ const ref = yield* resolveLocation(request, options)
80
+ return yield* effect.pipe(Effect.provide(locations.get(ref)), locationErrors)
81
+ })
82
+
83
+ const mapCommon = <A, E>(effect: Effect.Effect<A, E>) =>
84
+ effect.pipe(
85
+ Effect.catchTags({
86
+ "Artifact.DisabledError": (error: Artifact.DisabledError) =>
87
+ Effect.fail(new ForbiddenError({ message: error.message })),
88
+ "Artifact.NotFoundError": (error: Artifact.NotFoundError) =>
89
+ Effect.fail(new ArtifactNotFoundError({ artifactID: error.artifactID, message: error.message })),
90
+ "Artifact.ProviderNotFoundError": (error: Artifact.ProviderNotFoundError) =>
91
+ Effect.fail(new ProviderNotFoundError({ providerID: error.providerID, message: error.message })),
92
+ "Artifact.InvalidError": (error: Artifact.InvalidError) =>
93
+ Effect.fail(
94
+ new InvalidRequestError({ message: error.message, kind: "artifact_invalid", field: error.field }),
95
+ ),
96
+ "Artifact.ProviderError": (error: Artifact.ProviderError) =>
97
+ Effect.fail(new ServiceUnavailableError({ message: error.message, service: error.providerID })),
98
+ "Session.NotFoundError": (error: Session.NotFoundError) => Effect.fail(missingSession(error)),
99
+ } as never),
100
+ )
101
+
102
+ return {
103
+ providers: (
104
+ query: { readonly location?: { readonly directory?: string } },
105
+ request: HttpServerRequest.HttpServerRequest,
106
+ ) =>
107
+ inLocation(
108
+ request,
109
+ { location: query.location },
110
+ Effect.gen(function* () {
111
+ const artifacts = yield* Artifact.Service
112
+ return yield* response(artifacts.providers())
113
+ }),
114
+ ).pipe(mapCommon),
115
+
116
+ list: (
117
+ query: {
118
+ readonly location?: { readonly directory?: string }
119
+ readonly sessionID?: Session.ID
120
+ readonly provider?: Artifact.ProviderID
121
+ },
122
+ request: HttpServerRequest.HttpServerRequest,
123
+ ) =>
124
+ inLocation(
125
+ request,
126
+ { location: query.location, sessionID: query.sessionID },
127
+ Effect.gen(function* () {
128
+ const artifacts = yield* Artifact.Service
129
+ return yield* response(artifacts.list({ sessionID: query.sessionID, provider: query.provider }))
130
+ }),
131
+ ).pipe(mapCommon),
132
+
133
+ create: (
134
+ query: { readonly location?: { readonly directory?: string } },
135
+ payload: Artifact.CreateInput,
136
+ request: HttpServerRequest.HttpServerRequest,
137
+ ) =>
138
+ inLocation(
139
+ request,
140
+ { location: query.location, sessionID: payload.sessionID },
141
+ Effect.gen(function* () {
142
+ const artifacts = yield* Artifact.Service
143
+ return yield* response(artifacts.create(payload))
144
+ }),
145
+ ).pipe(mapCommon),
146
+
147
+ get: (
148
+ artifactID: Artifact.ID,
149
+ query: { readonly location?: { readonly directory?: string } },
150
+ request: HttpServerRequest.HttpServerRequest,
151
+ ) =>
152
+ inLocation(
153
+ request,
154
+ { location: query.location, artifactID },
155
+ Effect.gen(function* () {
156
+ const artifacts = yield* Artifact.Service
157
+ return yield* response(artifacts.get(artifactID))
158
+ }),
159
+ ).pipe(mapCommon),
160
+
161
+ update: (
162
+ artifactID: Artifact.ID,
163
+ query: { readonly location?: { readonly directory?: string } },
164
+ payload: Artifact.UpdateInput,
165
+ request: HttpServerRequest.HttpServerRequest,
166
+ ) =>
167
+ inLocation(
168
+ request,
169
+ { location: query.location, sessionID: payload.sessionID, artifactID },
170
+ Effect.gen(function* () {
171
+ const artifacts = yield* Artifact.Service
172
+ return yield* response(artifacts.update(artifactID, payload))
173
+ }),
174
+ ).pipe(mapCommon),
175
+
176
+ remove: (
177
+ artifactID: Artifact.ID,
178
+ query: { readonly location?: { readonly directory?: string } },
179
+ request: HttpServerRequest.HttpServerRequest,
180
+ ) =>
181
+ inLocation(
182
+ request,
183
+ { location: query.location, artifactID },
184
+ Effect.gen(function* () {
185
+ const artifacts = yield* Artifact.Service
186
+ yield* artifacts.remove(artifactID)
187
+ return HttpApiSchema.NoContent.make()
188
+ }),
189
+ ).pipe(mapCommon),
190
+
191
+ view: (
192
+ artifactID: Artifact.ID,
193
+ query: { readonly location?: { readonly directory?: string } },
194
+ request: HttpServerRequest.HttpServerRequest,
195
+ ) =>
196
+ inLocation(
197
+ request,
198
+ { location: query.location, artifactID },
199
+ Effect.gen(function* () {
200
+ const artifacts = yield* Artifact.Service
201
+ const parsed = new URL(request.url, "http://localhost")
202
+ const prefix = `/api/experimental/artifacts/${encodeURIComponent(artifactID)}/view`
203
+ if (parsed.pathname === prefix) {
204
+ yield* artifacts.info(artifactID)
205
+ return HttpServerResponse.empty({
206
+ status: 308,
207
+ headers: { location: `${prefix}/${parsed.search}` },
208
+ })
209
+ }
210
+ const subpath = extractViewSubpath(request.url, artifactID)
211
+ const file = yield* artifacts.readLocalFile(artifactID, subpath).pipe(
212
+ Effect.catchTag("Artifact.FileMissingError", (error) =>
213
+ Effect.fail(new FileNotFoundError({ path: error.path, message: error.message })),
214
+ ),
215
+ )
216
+ return HttpServerResponse.uint8Array(file.bytes, {
217
+ status: 200,
218
+ contentType: file.mime,
219
+ headers: {
220
+ "access-control-allow-origin": "*",
221
+ "cache-control": "private, no-cache",
222
+ "content-security-policy": "sandbox allow-scripts",
223
+ "x-content-type-options": "nosniff",
224
+ },
225
+ })
226
+ }),
227
+ ).pipe(mapCommon),
228
+ }
229
+ })
230
+
231
+ function extractViewSubpath(url: string, artifactID: Artifact.ID) {
232
+ const pathname = new URL(url, "http://localhost").pathname
233
+ const prefix = `/api/experimental/artifacts/${encodeURIComponent(artifactID)}/view/`
234
+ if (!pathname.startsWith(prefix)) return undefined
235
+ const raw = pathname.slice(prefix.length)
236
+ if (!raw) return undefined
237
+ try {
238
+ return decodeURIComponent(raw)
239
+ } catch {
240
+ return raw
241
+ }
242
+ }
@@ -0,0 +1,63 @@
1
+ import { Automation } from "@zyro-sec/core/automation"
2
+ import { Permission } from "@zyro-sec/core/permission"
3
+ import { AutomationNotFoundError, ForbiddenError, InvalidRequestError } from "@zyro-sec/protocol/errors"
4
+ import type { CreatePayload, ListQuery } from "@zyro-sec/protocol/groups/automation"
5
+ import { Effect } from "effect"
6
+ import { HttpApiSchema } from "effect/http-api"
7
+ import { missingSession } from "./session-error"
8
+
9
+ /** `automation.*` in the `server.experimental` group. Every route requires automations to be enabled where it runs. */
10
+ export const makeAutomation = Effect.gen(function* () {
11
+ const automations = yield* Automation.Service
12
+
13
+ return {
14
+ create: (payload: CreatePayload) =>
15
+ // Stateless HTTP callers have no guaranteed UI listener to answer an interactive ask, so settle asks unattended.
16
+ automations.create(payload).pipe(
17
+ Effect.provideService(Permission.Unattended, []),
18
+ Effect.map((data) => ({ data })),
19
+ Effect.catchTags({
20
+ "Automation.InvalidError": (error) =>
21
+ Effect.fail(new InvalidRequestError({ message: error.message, kind: "automation" })),
22
+ "Automation.DisabledError": () => Effect.fail(disabled()),
23
+ "Permission.BlockedError": (error) => Effect.fail(new ForbiddenError({ message: error.message })),
24
+ "Permission.CorrectedError": (error) => Effect.fail(new ForbiddenError({ message: error.feedback })),
25
+ "Session.NotFoundError": (error) => Effect.fail(missingSession(error)),
26
+ }),
27
+ ),
28
+ list: (query: ListQuery) =>
29
+ automations.list(query).pipe(
30
+ Effect.map((data) => ({ data })),
31
+ Effect.catchTags({
32
+ "Automation.InvalidError": (error) =>
33
+ Effect.fail(new InvalidRequestError({ message: error.message, kind: "automation" })),
34
+ "Automation.DisabledError": () => Effect.fail(disabled()),
35
+ "Session.NotFoundError": (error) => Effect.fail(missingSession(error)),
36
+ }),
37
+ ),
38
+ get: (id: Automation.ID) => managed(automations.get(id).pipe(Effect.map((data) => ({ data })))),
39
+ pause: (id: Automation.ID) => managed(automations.pause(id).pipe(Effect.map((data) => ({ data })))),
40
+ resume: (id: Automation.ID) => managed(automations.resume(id).pipe(Effect.map((data) => ({ data })))),
41
+ remove: (id: Automation.ID) => managed(automations.remove(id).pipe(Effect.as(HttpApiSchema.NoContent.make()))),
42
+ }
43
+ })
44
+
45
+ function managed<A>(effect: Effect.Effect<A, Automation.NotFoundError | Automation.DisabledError>) {
46
+ return effect.pipe(
47
+ Effect.catchTags({
48
+ "Automation.NotFoundError": (error) => Effect.fail(missingAutomation(error)),
49
+ "Automation.DisabledError": () => Effect.fail(disabled()),
50
+ }),
51
+ )
52
+ }
53
+
54
+ function missingAutomation(error: { readonly automationID: Automation.ID }) {
55
+ return new AutomationNotFoundError({
56
+ automationID: error.automationID,
57
+ message: `Automation not found: ${error.automationID}`,
58
+ })
59
+ }
60
+
61
+ function disabled() {
62
+ return new ForbiddenError({ message: new Automation.DisabledError().message })
63
+ }
@@ -0,0 +1,55 @@
1
+ import { BlobStore } from "@zyro-sec/core/blob-store"
2
+ import { BlobNotFoundError } from "@zyro-sec/protocol/errors"
3
+ import { FSUtil } from "@zyro-sec/util/fs-util"
4
+ import { Effect } from "effect"
5
+ import { type HttpServerRequest, HttpServerResponse } from "effect/http"
6
+ import { ContentHeaders } from "../content-headers"
7
+ import { ByteRange } from "../range"
8
+
9
+ /** `blob.get` in the `server.experimental` group. Raw, so it can stream the file and answer Range and 304 itself. */
10
+ export const makeBlobGet = Effect.gen(function* () {
11
+ const blobs = yield* BlobStore.Service
12
+ const fs = yield* FSUtil.Service
13
+ return (id: BlobStore.ID, request: HttpServerRequest.HttpServerRequest) =>
14
+ Effect.gen(function* () {
15
+ const blob = yield* blobs
16
+ .read(id)
17
+ .pipe(Effect.mapError((error) => new BlobNotFoundError({ blobID: error.id, message: error.message })))
18
+ // The ID names one immutable blob.
19
+ const etag = `"${id}"`
20
+ const headers = {
21
+ ...ContentHeaders.download({ mime: blob.mime }),
22
+ "cache-control": "private, max-age=31536000, immutable",
23
+ etag,
24
+ "accept-ranges": "bytes",
25
+ }
26
+ if (
27
+ request.headers["if-none-match"]
28
+ ?.split(",")
29
+ .some((tag) => tag.trim() === "*" || tag.trim().replace(/^w\//i, "") === etag)
30
+ )
31
+ return HttpServerResponse.empty({ status: 304, headers })
32
+ // If-Range takes only a strong match (RFC 9110 13.1.5); anything else serves the whole body.
33
+ const ifRange = request.headers["if-range"]
34
+ const range =
35
+ ifRange === undefined || ifRange.trim() === etag
36
+ ? ByteRange.parse(request.headers["range"], blob.bytes)
37
+ : undefined
38
+ if (range === "unsatisfiable")
39
+ return HttpServerResponse.empty({
40
+ status: 416,
41
+ headers: { ...headers, "content-range": `bytes */${blob.bytes}` },
42
+ })
43
+ const offset = range?.start ?? 0
44
+ const length = range === undefined ? blob.bytes : range.end - range.start + 1
45
+ return HttpServerResponse.stream(fs.stream(blob.path, { offset, bytesToRead: length }), {
46
+ status: range === undefined ? 200 : 206,
47
+ contentType: headers["content-type"],
48
+ contentLength: length,
49
+ headers:
50
+ range === undefined
51
+ ? headers
52
+ : { ...headers, "content-range": `bytes ${range.start}-${range.end}/${blob.bytes}` },
53
+ })
54
+ })
55
+ })
@@ -0,0 +1,8 @@
1
+ import { Command } from "@zyro-sec/core/command"
2
+ import { HttpApiBuilder } from "effect/http-api"
3
+ import { Api } from "../api"
4
+ import { response } from "../location"
5
+
6
+ export const CommandHandler = HttpApiBuilder.group(Api, "server.command", (handlers) =>
7
+ handlers.handle("command.list", () => response(Command.Service.use((command) => command.list()))),
8
+ )
@@ -0,0 +1,26 @@
1
+ import { Config } from "@zyro-sec/core/config"
2
+ import { ShellSelect } from "@zyro-sec/core/shell/select"
3
+ import { Effect } from "effect"
4
+ import { HttpApiBuilder } from "effect/http-api"
5
+ import { Api } from "../api"
6
+
7
+ export const ConfigHandler = HttpApiBuilder.group(Api, "server.config", (handlers) =>
8
+ handlers
9
+ .handle("config.get", () => Config.Service.use((config) => config.entries()))
10
+ .handle(
11
+ "config.update",
12
+ Effect.fn(function* (ctx) {
13
+ const config = yield* Config.Service
14
+ if (!config.update) return yield* Effect.die(new Error("Config updates are unavailable"))
15
+ return yield* config.update(ctx.payload).pipe(Effect.orDie)
16
+ }),
17
+ )
18
+ .handle(
19
+ "config.shells",
20
+ Effect.fn(function* () {
21
+ const shell = yield* ShellSelect.Service
22
+ if (!shell.list) return yield* Effect.die(new Error("Shell discovery is unavailable"))
23
+ return yield* shell.list()
24
+ }),
25
+ ),
26
+ )
@@ -0,0 +1,87 @@
1
+ import { Credential } from "@zyro-sec/core/credential"
2
+ import { FileSystem } from "@zyro-sec/core/filesystem"
3
+ import { Integration } from "@zyro-sec/core/integration"
4
+ import { Location } from "@zyro-sec/core/location"
5
+ import { LocationServiceMap } from "@zyro-sec/core/location-services"
6
+ import { AbsolutePath } from "@zyro-sec/core/schema"
7
+ import { ConflictError } from "@zyro-sec/protocol/errors"
8
+ import { Global } from "@zyro-sec/util/global"
9
+ import { Effect } from "effect"
10
+ import { HttpApiBuilder, HttpApiSchema } from "effect/http-api"
11
+ import { Api } from "../api"
12
+ import { requireConnectable } from "./integration"
13
+
14
+ export const CredentialHandler = HttpApiBuilder.group(Api, "server.credential", (handlers) =>
15
+ Effect.gen(function* () {
16
+ const global = yield* Global.Service
17
+ const locations = yield* LocationServiceMap.Service
18
+ // Credentials are global, so `integration.connect` is read from the global config Location, which carries managed
19
+ // policy, the Console document, and user config.
20
+ const services = locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) }))
21
+ return handlers
22
+ .handle(
23
+ "credential.list",
24
+ Effect.fn(function* () {
25
+ const credential = yield* Credential.Service
26
+ return { data: entries(yield* credential.all()) }
27
+ }),
28
+ )
29
+ .handle(
30
+ "credential.create",
31
+ Effect.fn(function* (ctx) {
32
+ yield* requireConnectable(ctx.payload.integrationID).pipe(
33
+ Effect.provide(services),
34
+ // The global config directory always exists.
35
+ Effect.catchIf((error) => error instanceof FileSystem.DirectoryNotFoundError, Effect.die),
36
+ )
37
+ const credential = yield* Credential.Service
38
+ if (ctx.payload.id && (yield* credential.get(ctx.payload.id)))
39
+ return yield* new ConflictError({
40
+ resource: ctx.payload.id,
41
+ message: `Credential already exists: ${ctx.payload.id}`,
42
+ })
43
+ const created = yield* credential.create(ctx.payload)
44
+ const entry = entries(yield* credential.list(created.integrationID)).find((item) => item.id === created.id)
45
+ return { data: entry ?? { ...created, active: false } }
46
+ }),
47
+ )
48
+ .handle(
49
+ "credential.update",
50
+ Effect.fn(function* (ctx) {
51
+ const credential = yield* Credential.Service
52
+ yield* credential.update(ctx.params.credentialID, { label: ctx.payload.label })
53
+ return HttpApiSchema.NoContent.make()
54
+ }),
55
+ )
56
+ .handle(
57
+ "credential.activate",
58
+ Effect.fn(function* (ctx) {
59
+ const credential = yield* Credential.Service
60
+ yield* credential.activate(ctx.params.credentialID)
61
+ return HttpApiSchema.NoContent.make()
62
+ }),
63
+ )
64
+ .handle(
65
+ "credential.remove",
66
+ Effect.fn(function* (ctx) {
67
+ // Removal goes through Integration so a sign-in method can revoke the credential remotely first.
68
+ // The global config directory always exists.
69
+ const integrations = yield* Integration.Service.pipe(Effect.provide(services), Effect.orDie)
70
+ yield* integrations.connection.remove(ctx.params.credentialID)
71
+ return HttpApiSchema.NoContent.make()
72
+ }),
73
+ )
74
+ }),
75
+ )
76
+
77
+ // Credential listings order each integration's selected credential last.
78
+ function entries(credentials: Credential.Info[]) {
79
+ const selected = new Map(credentials.map((item) => [item.integrationID, item.id]))
80
+ return credentials.map((item) => ({
81
+ id: item.id,
82
+ integrationID: item.integrationID,
83
+ label: item.label,
84
+ active: selected.get(item.integrationID) === item.id,
85
+ value: item.value,
86
+ }))
87
+ }
@@ -0,0 +1,57 @@
1
+ import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
2
+ import { InvalidRequestError, UnknownError } from "@zyro-sec/protocol/errors"
3
+ import { Global } from "@zyro-sec/util/global"
4
+ import { HeapSnapshot } from "@zyro-sec/util/heap-snapshot"
5
+ import { Effect, Option, RcMap } from "effect"
6
+ import { HttpApiBuilder } from "effect/http-api"
7
+ import path from "node:path"
8
+ import { Api } from "../api"
9
+ import { requestRef } from "../location"
10
+
11
+ export const DebugHandler = HttpApiBuilder.group(Api, "server.debug", (handlers) =>
12
+ Effect.gen(function* () {
13
+ const global = yield* Global.Service
14
+ return handlers
15
+ .handle(
16
+ "debug.heapDump",
17
+ Effect.fn("server.debug.heapDump")(function* (ctx) {
18
+ const directory = ctx.query.directory
19
+ if (directory !== undefined && !path.isAbsolute(directory))
20
+ return yield* new InvalidRequestError({ message: "directory must be an absolute path", field: "directory" })
21
+ return yield* HeapSnapshot.write(directory ?? global.log).pipe(
22
+ Effect.catch((cause) => {
23
+ const ref = `err_${crypto.randomUUID().slice(0, 8)}`
24
+ return Effect.logError("failed to write heap snapshot", { cause }).pipe(
25
+ Effect.annotateLogs({ ref }),
26
+ Effect.andThen(
27
+ // The reason (a missing permission, a file where the directory should be) is usually the caller's to fix.
28
+ Effect.fail(
29
+ new UnknownError({
30
+ message: `Failed to write heap snapshot: ${cause.cause instanceof Error ? cause.cause.message : cause.message}`,
31
+ ref,
32
+ }),
33
+ ),
34
+ ),
35
+ )
36
+ }),
37
+ )
38
+ }),
39
+ )
40
+ .handle(
41
+ "debug.location",
42
+ Effect.fn(function* () {
43
+ const locations = Option.getOrThrow(yield* Effect.serviceOption(LocationServiceMap.Service))
44
+ return Array.from(yield* RcMap.keys(locations.rcMap))
45
+ }),
46
+ )
47
+ .handle(
48
+ "debug.location.evict",
49
+ Effect.fn(function* (ctx) {
50
+ const locations = Option.getOrThrow(yield* Effect.serviceOption(LocationServiceMap.Service))
51
+ // Resolve through requestRef so the key matches the shape the location
52
+ // middleware cached the services under.
53
+ yield* locations.invalidate(requestRef(ctx.request))
54
+ }),
55
+ )
56
+ }),
57
+ )
@@ -0,0 +1,38 @@
1
+ import { Event } from "@zyro-sec/schema/event"
2
+ import { Effect, Stream } from "effect"
3
+ import { HttpServerResponse } from "effect/http"
4
+ import { HttpApiBuilder } from "effect/http-api"
5
+ import { Api } from "../api"
6
+ import { EventFeed } from "../event-feed"
7
+
8
+ export const EventHandler = HttpApiBuilder.group(Api, "server.event", (handlers) =>
9
+ Effect.gen(function* () {
10
+ const feed = yield* EventFeed.Service
11
+ return handlers.handleRaw("event.subscribe", (ctx) =>
12
+ Effect.gen(function* () {
13
+ const connected = {
14
+ id: Event.ID.create(),
15
+ type: "server.connected",
16
+ data: {},
17
+ } as const
18
+ const output = Stream.unwrap(
19
+ feed
20
+ .subscribe(ctx.query.types)
21
+ .pipe(Effect.map((live) => Stream.make(EventFeed.frame(connected)).pipe(Stream.concat(live)))),
22
+ )
23
+ const heartbeat = Stream.tick("15 seconds").pipe(Stream.map(() => ": heartbeat\n\n"))
24
+ return HttpServerResponse.stream(
25
+ output.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }), Stream.encodeText),
26
+ {
27
+ contentType: "text/event-stream",
28
+ headers: {
29
+ "Cache-Control": "no-cache, no-transform",
30
+ "X-Accel-Buffering": "no",
31
+ "X-Content-Type-Options": "nosniff",
32
+ },
33
+ },
34
+ )
35
+ }),
36
+ )
37
+ }),
38
+ )
@@ -0,0 +1,15 @@
1
+ import { Form } from "@zyro-sec/core/form"
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 FormHandler = HttpApiBuilder.group(Api, "server.form", (handlers) =>
8
+ handlers.handle(
9
+ "form.list",
10
+ Effect.fn(function* () {
11
+ const form = yield* Form.Service
12
+ return yield* response(form.list())
13
+ }),
14
+ ),
15
+ )