@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,180 @@
1
+ import { Environment } from "@zyro-sec/core/environment/index"
2
+ import { FileSystem } from "@zyro-sec/core/filesystem"
3
+ import { FileWatch } from "@zyro-sec/core/filesystem/file-watch"
4
+ import { Location } from "@zyro-sec/core/location"
5
+ import { RelativePath } from "@zyro-sec/core/schema"
6
+ import { FileNotFoundError, ServiceUnavailableError } from "@zyro-sec/protocol/errors"
7
+ import { Effect, Option, Stream } from "effect"
8
+ import { type HttpServerRequest, HttpServerResponse } from "effect/http"
9
+ import { HttpApiBuilder } from "effect/http-api"
10
+ import path from "path"
11
+ import { Api } from "../api"
12
+ import { ContentHeaders } from "../content-headers"
13
+ import { response } from "../location"
14
+ import { ByteRange } from "../range"
15
+
16
+ export const FileSystemHandler = HttpApiBuilder.group(Api, "server.fs", (handlers) =>
17
+ Effect.gen(function* () {
18
+ const fileWatch = yield* FileWatch.Service
19
+ return handlers
20
+ .handleRaw("fs.read", (ctx) =>
21
+ Effect.gen(function* () {
22
+ const path = yield* decodeRequestPath(ctx.request.url)
23
+ const fs = yield* FileSystem.Service
24
+ const file = yield* fs
25
+ .read({ path })
26
+ .pipe(
27
+ Effect.mapError(
28
+ (error) => new FileNotFoundError({ path: error.path, message: `File not found: ${error.path}` }),
29
+ ),
30
+ )
31
+ return serveFile(ctx.request, file, ContentHeaders.download({ path, mime: file.mime }))
32
+ }),
33
+ )
34
+ .handle("fs.list", (ctx) =>
35
+ response(
36
+ Effect.gen(function* () {
37
+ const fs = yield* FileSystem.Service
38
+ return yield* fs
39
+ .list(ctx.query)
40
+ .pipe(
41
+ Effect.mapError(
42
+ (error) => new FileNotFoundError({ path: error.path, message: `Directory not found: ${error.path}` }),
43
+ ),
44
+ )
45
+ }),
46
+ ),
47
+ )
48
+ .handle("fs.find", (ctx) =>
49
+ response(
50
+ Effect.gen(function* () {
51
+ const fs = yield* FileSystem.Service
52
+ return yield* fs.find(ctx.query)
53
+ }),
54
+ ),
55
+ )
56
+ .handle("fs.write", (ctx) =>
57
+ response(
58
+ Effect.gen(function* () {
59
+ const fs = yield* FileSystem.Service
60
+ return yield* fs.write({ path: ctx.query.path, data: ctx.payload })
61
+ }),
62
+ ),
63
+ )
64
+ .handle("fs.watch", (ctx) =>
65
+ Effect.gen(function* () {
66
+ const environment = yield* Environment.Service
67
+ if (!environment.local)
68
+ return yield* new ServiceUnavailableError({
69
+ service: "filewatcher",
70
+ message: "File watching is not available for this location",
71
+ })
72
+ const fs = yield* FileSystem.Service
73
+ const location = yield* Location.Service
74
+ // Same confinement as read: the file must exist inside the location.
75
+ yield* fs
76
+ .read({ path: RelativePath.make(ctx.payload.path) })
77
+ .pipe(
78
+ Effect.mapError(
79
+ (error) => new FileNotFoundError({ path: error.path, message: `File not found: ${error.path}` }),
80
+ ),
81
+ )
82
+ yield* fileWatch
83
+ .watch({
84
+ location: { directory: location.directory, workspaceID: location.workspaceID },
85
+ file: path.resolve(location.directory, ctx.payload.path),
86
+ })
87
+ .pipe(
88
+ Effect.mapError(
89
+ (error) => new ServiceUnavailableError({ message: error.message, service: "filewatcher" }),
90
+ ),
91
+ )
92
+ }),
93
+ )
94
+ .handle("fs.unwatch", (ctx) =>
95
+ Effect.gen(function* () {
96
+ const environment = yield* Environment.Service
97
+ if (!environment.local) return
98
+ const location = yield* Location.Service
99
+ yield* fileWatch.unwatch({
100
+ location: { directory: location.directory, workspaceID: location.workspaceID },
101
+ file: path.resolve(location.directory, ctx.payload.path),
102
+ })
103
+ }),
104
+ )
105
+ }),
106
+ )
107
+
108
+ function decodeRequestPath(url: string) {
109
+ const raw = new URL(url, "http://localhost").pathname.slice(13)
110
+ return Effect.try({
111
+ try: () => RelativePath.make(decodeURIComponent(raw)),
112
+ catch: () => new FileNotFoundError({ path: raw, message: `File not found: ${raw}` }),
113
+ })
114
+ }
115
+
116
+ function serveFile(
117
+ request: HttpServerRequest.HttpServerRequest,
118
+ file: FileSystem.File,
119
+ content: ReturnType<typeof ContentHeaders.download>,
120
+ ) {
121
+ const etag = `W/"${file.size.toString(16)}-${Option.match(file.mtime, {
122
+ onNone: () => "0",
123
+ onSome: (mtime) => mtime.getTime().toString(16),
124
+ })}"`
125
+ const lastModified = Option.getOrUndefined(Option.map(file.mtime, (mtime) => mtime.toUTCString()))
126
+ // Clients must revalidate after agent edits; no-transform keeps compression from changing Content-Length.
127
+ const validators = {
128
+ "cache-control": "no-cache, no-transform",
129
+ etag,
130
+ ...(lastModified === undefined ? {} : { "last-modified": lastModified }),
131
+ }
132
+ if (isNotModified(request, etag, lastModified))
133
+ return HttpServerResponse.empty({ status: 304, headers: { ...validators, ...content } })
134
+
135
+ const rangeHeader = request.method === "GET" ? request.headers["range"] : undefined
136
+ const range =
137
+ rangeHeader !== undefined && matchesIfRange(request.headers["if-range"], etag, lastModified)
138
+ ? ByteRange.parse(rangeHeader, file.size)
139
+ : undefined
140
+ if (range === "unsatisfiable")
141
+ return HttpServerResponse.empty({
142
+ status: 416,
143
+ headers: { "accept-ranges": "bytes", "content-range": `bytes */${file.size}` },
144
+ })
145
+
146
+ const offset = range?.start ?? 0
147
+ const length = range === undefined ? file.size : range.end - range.start + 1
148
+ return HttpServerResponse.stream(length === 0 ? Stream.empty : file.stream({ offset, bytesToRead: length }), {
149
+ status: range === undefined ? 200 : 206,
150
+ contentLength: length,
151
+ headers: {
152
+ ...validators,
153
+ ...content,
154
+ "accept-ranges": "bytes",
155
+ ...(range === undefined ? {} : { "content-range": `bytes ${range.start}-${range.end}/${file.size}` }),
156
+ },
157
+ })
158
+ }
159
+
160
+ function isNotModified(request: HttpServerRequest.HttpServerRequest, etag: string, lastModified: string | undefined) {
161
+ const ifNoneMatch = request.headers["if-none-match"]
162
+ if (ifNoneMatch !== undefined)
163
+ return ifNoneMatch.split(",").some((tag) => tag.trim() === "*" || stripWeak(tag) === stripWeak(etag))
164
+ const ifModifiedSince = request.headers["if-modified-since"]
165
+ return (
166
+ ifModifiedSince !== undefined &&
167
+ lastModified !== undefined &&
168
+ Date.parse(lastModified) <= Date.parse(ifModifiedSince)
169
+ )
170
+ }
171
+
172
+ function matchesIfRange(ifRange: string | undefined, etag: string, lastModified: string | undefined) {
173
+ if (ifRange === undefined) return true
174
+ if (/^\s*(w\/)?"/i.test(ifRange)) return stripWeak(ifRange) === stripWeak(etag)
175
+ return lastModified !== undefined && Date.parse(ifRange) === Date.parse(lastModified)
176
+ }
177
+
178
+ function stripWeak(etag: string) {
179
+ return etag.trim().replace(/^w\//i, "")
180
+ }
@@ -0,0 +1,117 @@
1
+ import { Generate } from "@zyro-sec/core/generate"
2
+ import { VideoGeneration } from "@zyro-sec/core/video-generation"
3
+ import { Location } from "@zyro-sec/core/location"
4
+ import { LocationServiceMap } from "@zyro-sec/core/location-services"
5
+ import { AbsolutePath } from "@zyro-sec/core/schema"
6
+ import {
7
+ VideoNotFoundError,
8
+ InvalidRequestError,
9
+ ModelNotFoundError,
10
+ ProviderRequestError,
11
+ ServiceUnavailableError,
12
+ UnsupportedModelError,
13
+ } from "@zyro-sec/protocol/errors"
14
+ import type { DecisionRequest, VideoID, ImageRequest, VideoRequest } from "@zyro-sec/schema/generate"
15
+ import { Global } from "@zyro-sec/util/global"
16
+ import { Model } from "@zyro-sec/schema/model"
17
+ import { Effect } from "effect"
18
+ import { HttpApiBuilder } from "effect/http-api"
19
+ import { Api } from "../api"
20
+ import { locationErrors } from "../location"
21
+
22
+ export const GenerateHandler = HttpApiBuilder.group(Api, "server.generate", (handlers) =>
23
+ Effect.gen(function* () {
24
+ const global = yield* Global.Service
25
+ const locations = yield* LocationServiceMap.Service
26
+ const videos = yield* VideoGeneration.Service
27
+ const services = locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) }))
28
+ const text = Effect.fn("server.generate.text")(
29
+ function* (request: { readonly payload: { readonly prompt: string; readonly model?: Model.Ref } }) {
30
+ const generate = yield* Generate.Service
31
+ return { data: { text: yield* generate.text(request.payload).pipe(Effect.mapError(generateError)) } }
32
+ },
33
+ Effect.provide(services),
34
+ locationErrors,
35
+ )
36
+ const image = Effect.fn("server.generate.image")(
37
+ function* (request: { readonly payload: ImageRequest }) {
38
+ const generate = yield* Generate.Service
39
+ return { data: yield* generate.image(request.payload).pipe(Effect.mapError(generateError)) }
40
+ },
41
+ Effect.provide(services),
42
+ locationErrors,
43
+ )
44
+ const decisions = Effect.fn("server.generate.decisions")(
45
+ function* (request: { readonly payload: DecisionRequest }) {
46
+ const names = new Set(request.payload.questions.map((question) => question.name))
47
+ if (names.size !== request.payload.questions.length)
48
+ return yield* new InvalidRequestError({
49
+ message: "Decision question names must be unique",
50
+ field: "questions",
51
+ })
52
+ const generate = yield* Generate.Service
53
+ return { data: yield* generate.decisions(request.payload).pipe(Effect.mapError(generateError)) }
54
+ },
55
+ Effect.provide(services),
56
+ locationErrors,
57
+ )
58
+ const videoCreate = Effect.fn("server.generate.video.create")(
59
+ function* (request: { readonly payload: VideoRequest }) {
60
+ return {
61
+ data: yield* videos.start(Generate.videoInput(request.payload)).pipe(Effect.mapError(generateError)),
62
+ }
63
+ },
64
+ Effect.provide(services),
65
+ locationErrors,
66
+ )
67
+ const videoGet = Effect.fn("server.generate.video.get")(
68
+ function* (request: { readonly params: { readonly id: VideoID } }) {
69
+ const job = yield* videos
70
+ .get(request.params.id)
71
+ .pipe(Effect.mapError((error) => new VideoNotFoundError({ videoID: error.id, message: error.message })))
72
+ return { data: job }
73
+ },
74
+ Effect.provide(services),
75
+ locationErrors,
76
+ )
77
+ return handlers
78
+ .handle("generate.text", text)
79
+ .handle("generate.textLegacy", text)
80
+ .handle("generate.image", image)
81
+ .handle("generate.decisions", decisions)
82
+ .handle("generate.video.create", videoCreate)
83
+ .handle("generate.video.get", videoGet)
84
+ }),
85
+ )
86
+
87
+ function generateError(error: Generate.Error) {
88
+ switch (error._tag) {
89
+ case "Generate.ModelNotFoundError":
90
+ return new ModelNotFoundError({ providerID: error.providerID, modelID: error.modelID, message: error.message })
91
+ case "Generate.UnsupportedModelError":
92
+ return new UnsupportedModelError({
93
+ providerID: error.providerID,
94
+ modelID: error.modelID,
95
+ capability: error.capability,
96
+ message: error.message,
97
+ })
98
+ case "Generate.InvalidRequestError":
99
+ return new InvalidRequestError({
100
+ message: error.message,
101
+ ...(error.field === undefined ? {} : { field: error.field }),
102
+ })
103
+ case "Generate.ProviderRequestError":
104
+ return new ProviderRequestError({
105
+ providerID: error.providerID,
106
+ reason: error.reason,
107
+ message: error.message,
108
+ ...(error.status === undefined ? {} : { status: error.status }),
109
+ ...(error.retryAfterMs === undefined ? {} : { retryAfterMs: error.retryAfterMs }),
110
+ })
111
+ case "Generate.UnavailableError":
112
+ return new ServiceUnavailableError({
113
+ message: error.message,
114
+ ...(error.service === undefined ? {} : { service: error.service }),
115
+ })
116
+ }
117
+ }
@@ -0,0 +1,310 @@
1
+ import { Integration } from "@zyro-sec/core/integration"
2
+ import { Effect } from "effect"
3
+ import { HttpApiBuilder, HttpApiSchema } from "effect/http-api"
4
+ import { Api } from "../api"
5
+ import {
6
+ IntegrationAttemptNotFoundError,
7
+ IntegrationMethodNotFoundError,
8
+ IntegrationNotFoundError,
9
+ InvalidRequestError,
10
+ } from "@zyro-sec/protocol/errors"
11
+ import { response } from "../location"
12
+ import { WellKnown } from "@zyro-sec/core/wellknown"
13
+ import { Config } from "@zyro-sec/core/config"
14
+ import { ManagedPolicy } from "@zyro-sec/core/managed-policy"
15
+
16
+ const statements = Effect.fnUntraced(function* () {
17
+ const config = yield* Config.Service
18
+ return ManagedPolicy.statements(yield* config.entries())
19
+ })
20
+
21
+ // MCP OAuth logins skip integration policy: whether an MCP server is available at all is decided by `mcp.use` and by
22
+ // managed policy withholding the documents of denied integrations.
23
+ const isMcp = (integration: { readonly metadata?: { readonly source?: unknown } } | undefined) =>
24
+ integration?.metadata?.source === "mcp"
25
+
26
+ // `integration.connect` decides which integrations are listed and can be connected. Credential creation shares it.
27
+ export const requireConnectable = Effect.fnUntraced(function* (integrationID: Integration.ID) {
28
+ const integrations = yield* Integration.Service
29
+ if (isMcp(yield* integrations.get(integrationID))) return
30
+ const denied = ManagedPolicy.match(yield* statements(), "integration.connect", integrationID)
31
+ if (denied?.effect !== "deny") return
32
+ return yield* new InvalidRequestError({
33
+ message: `${denied.message}: connecting ${integrationID} is not allowed`,
34
+ kind: "integration_policy",
35
+ })
36
+ })
37
+
38
+ const authorize = <A, R>(effect: Effect.Effect<A, Integration.AuthorizationError, R>) =>
39
+ effect.pipe(
40
+ Effect.mapError(
41
+ (error) =>
42
+ new InvalidRequestError({
43
+ message:
44
+ error.cause instanceof Error && error.cause.message.trim() ? error.cause.message : "Authentication failed",
45
+ kind: "integration_authorization",
46
+ }),
47
+ ),
48
+ )
49
+
50
+ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration", (handlers) =>
51
+ Effect.gen(function* () {
52
+ return handlers
53
+ .handle(
54
+ "integration.list",
55
+ Effect.fn(function* () {
56
+ const service = yield* Integration.Service
57
+ const current = yield* statements()
58
+ return yield* response(
59
+ service
60
+ .list()
61
+ .pipe(
62
+ Effect.map((integrations) =>
63
+ integrations.filter(
64
+ (integration) =>
65
+ isMcp(integration) ||
66
+ ManagedPolicy.decision(current, "integration.connect", integration.id) !== "deny",
67
+ ),
68
+ ),
69
+ ),
70
+ )
71
+ }),
72
+ )
73
+ .handle(
74
+ "integration.get",
75
+ Effect.fn(function* (ctx) {
76
+ const service = yield* Integration.Service
77
+ const integration = yield* service.get(ctx.params.integrationID)
78
+ if (!integration)
79
+ return yield* new IntegrationNotFoundError({
80
+ integrationID: ctx.params.integrationID,
81
+ message: `Integration not found: ${ctx.params.integrationID}`,
82
+ })
83
+ return yield* response(Effect.succeed(integration))
84
+ }),
85
+ )
86
+ .handle(
87
+ "integration.wellknown.add",
88
+ Effect.fn(function* (ctx) {
89
+ const wellknown = yield* WellKnown.Service
90
+ const integration = yield* Integration.Service
91
+ // Well-known sources are integrations keyed by their origin as entered.
92
+ yield* requireConnectable(Integration.ID.make(ctx.payload.url.replace(/\/+$/, "")))
93
+ yield* wellknown
94
+ .add(ctx.payload.url)
95
+ .pipe(
96
+ Effect.mapError(
97
+ (error) => new InvalidRequestError({ message: error.message, kind: "well_known_discovery" }),
98
+ ),
99
+ )
100
+ yield* integration.reload()
101
+ return HttpApiSchema.NoContent.make()
102
+ }),
103
+ )
104
+ .handle(
105
+ "integration.connect.key",
106
+ Effect.fn(function* (ctx) {
107
+ yield* requireConnectable(ctx.params.integrationID)
108
+ const service = yield* Integration.Service
109
+ if (!(yield* service.get(ctx.params.integrationID)))
110
+ return yield* new IntegrationNotFoundError({
111
+ integrationID: ctx.params.integrationID,
112
+ message: `Integration not found: ${ctx.params.integrationID}`,
113
+ })
114
+ yield* authorize(
115
+ service.connection.key({
116
+ integrationID: ctx.params.integrationID,
117
+ key: ctx.payload.key,
118
+ answer: ctx.payload.answer,
119
+ label: ctx.payload.label,
120
+ }),
121
+ )
122
+ return HttpApiSchema.NoContent.make()
123
+ }),
124
+ )
125
+ .handle(
126
+ "integration.connect.external",
127
+ Effect.fn(function* (ctx) {
128
+ yield* requireConnectable(ctx.params.integrationID)
129
+ const service = yield* Integration.Service
130
+ if (!(yield* service.get(ctx.params.integrationID)))
131
+ return yield* new IntegrationNotFoundError({
132
+ integrationID: ctx.params.integrationID,
133
+ message: `Integration not found: ${ctx.params.integrationID}`,
134
+ })
135
+ yield* authorize(
136
+ service.connection.external({
137
+ integrationID: ctx.params.integrationID,
138
+ methodID: ctx.payload.methodID,
139
+ answer: ctx.payload.answer,
140
+ label: ctx.payload.label,
141
+ }),
142
+ )
143
+ return HttpApiSchema.NoContent.make()
144
+ }),
145
+ )
146
+ .handle(
147
+ "integration.oauth.connect",
148
+ Effect.fn(function* (ctx) {
149
+ yield* requireConnectable(ctx.params.integrationID)
150
+ const service = yield* Integration.Service
151
+ return yield* response(
152
+ authorize(
153
+ service.oauth.connect({
154
+ integrationID: ctx.params.integrationID,
155
+ methodID: ctx.payload.methodID,
156
+ answer: ctx.payload.answer,
157
+ label: ctx.payload.label,
158
+ }),
159
+ ),
160
+ )
161
+ }),
162
+ )
163
+ .handle(
164
+ "integration.oauth.status",
165
+ Effect.fn(function* (ctx) {
166
+ const service = yield* Integration.Service
167
+ if (!(yield* service.get(ctx.params.integrationID)))
168
+ return yield* new IntegrationNotFoundError({
169
+ integrationID: ctx.params.integrationID,
170
+ message: `Integration not found: ${ctx.params.integrationID}`,
171
+ })
172
+ return yield* response(
173
+ service.oauth
174
+ .status({
175
+ integrationID: ctx.params.integrationID,
176
+ attemptID: ctx.params.attemptID,
177
+ })
178
+ .pipe(
179
+ Effect.mapError(
180
+ (error) =>
181
+ new IntegrationAttemptNotFoundError({
182
+ integrationID: error.integrationID,
183
+ attemptID: error.attemptID,
184
+ message: `OAuth attempt not found: ${error.attemptID}`,
185
+ }),
186
+ ),
187
+ ),
188
+ )
189
+ }),
190
+ )
191
+ .handle(
192
+ "integration.oauth.complete",
193
+ Effect.fn(function* (ctx) {
194
+ const service = yield* Integration.Service
195
+ if (!(yield* service.get(ctx.params.integrationID)))
196
+ return yield* new IntegrationNotFoundError({
197
+ integrationID: ctx.params.integrationID,
198
+ message: `Integration not found: ${ctx.params.integrationID}`,
199
+ })
200
+ yield* service.oauth
201
+ .complete({
202
+ integrationID: ctx.params.integrationID,
203
+ attemptID: ctx.params.attemptID,
204
+ code: ctx.payload.code,
205
+ })
206
+ .pipe(
207
+ Effect.mapError((error) => {
208
+ if (error._tag === "Integration.AttemptNotFound")
209
+ return new IntegrationAttemptNotFoundError({
210
+ integrationID: error.integrationID,
211
+ attemptID: error.attemptID,
212
+ message: `OAuth attempt not found: ${error.attemptID}`,
213
+ })
214
+ if (error._tag === "Integration.CodeRequired")
215
+ return new InvalidRequestError({
216
+ message: "Authorization code is required",
217
+ kind: "integration_code_required",
218
+ })
219
+ return new InvalidRequestError({
220
+ message:
221
+ error.cause instanceof Error && error.cause.message.trim()
222
+ ? error.cause.message
223
+ : "Authentication failed",
224
+ kind: "integration_authorization",
225
+ })
226
+ }),
227
+ )
228
+ return HttpApiSchema.NoContent.make()
229
+ }),
230
+ )
231
+ .handle(
232
+ "integration.oauth.cancel",
233
+ Effect.fn(function* (ctx) {
234
+ const service = yield* Integration.Service
235
+ yield* service.oauth.cancel({
236
+ integrationID: ctx.params.integrationID,
237
+ attemptID: ctx.params.attemptID,
238
+ })
239
+ return HttpApiSchema.NoContent.make()
240
+ }),
241
+ )
242
+ .handle(
243
+ "integration.command.connect",
244
+ Effect.fn(function* (ctx) {
245
+ yield* requireConnectable(ctx.params.integrationID)
246
+ const service = yield* Integration.Service
247
+ const integration = yield* service.get(ctx.params.integrationID)
248
+ if (!integration)
249
+ return yield* new IntegrationNotFoundError({
250
+ integrationID: ctx.params.integrationID,
251
+ message: `Integration not found: ${ctx.params.integrationID}`,
252
+ })
253
+ if (!integration.methods.some((method) => method.type === "command" && method.id === ctx.payload.methodID))
254
+ return yield* new IntegrationMethodNotFoundError({
255
+ integrationID: ctx.params.integrationID,
256
+ methodID: ctx.payload.methodID,
257
+ message: `Integration method not found: ${ctx.payload.methodID}`,
258
+ })
259
+ return yield* response(
260
+ authorize(
261
+ service.command.connect({
262
+ integrationID: ctx.params.integrationID,
263
+ methodID: ctx.payload.methodID,
264
+ label: ctx.payload.label,
265
+ }),
266
+ ),
267
+ )
268
+ }),
269
+ )
270
+ .handle(
271
+ "integration.command.status",
272
+ Effect.fn(function* (ctx) {
273
+ const service = yield* Integration.Service
274
+ if (!(yield* service.get(ctx.params.integrationID)))
275
+ return yield* new IntegrationNotFoundError({
276
+ integrationID: ctx.params.integrationID,
277
+ message: `Integration not found: ${ctx.params.integrationID}`,
278
+ })
279
+ return yield* response(
280
+ service.command
281
+ .status({
282
+ integrationID: ctx.params.integrationID,
283
+ attemptID: ctx.params.attemptID,
284
+ })
285
+ .pipe(
286
+ Effect.mapError(
287
+ (error) =>
288
+ new IntegrationAttemptNotFoundError({
289
+ integrationID: error.integrationID,
290
+ attemptID: error.attemptID,
291
+ message: `Command attempt not found: ${error.attemptID}`,
292
+ }),
293
+ ),
294
+ ),
295
+ )
296
+ }),
297
+ )
298
+ .handle(
299
+ "integration.command.cancel",
300
+ Effect.fn(function* (ctx) {
301
+ const service = yield* Integration.Service
302
+ yield* service.command.cancel({
303
+ integrationID: ctx.params.integrationID,
304
+ attemptID: ctx.params.attemptID,
305
+ })
306
+ return HttpApiSchema.NoContent.make()
307
+ }),
308
+ )
309
+ }),
310
+ )
@@ -0,0 +1,29 @@
1
+ import { Job } from "@zyro-sec/core/job"
2
+ import { Session } from "@zyro-sec/core/session"
3
+ import { SessionBackground } from "@zyro-sec/core/session/background"
4
+ import type { ListQuery } from "@zyro-sec/protocol/groups/job"
5
+ import { Effect, Option } from "effect"
6
+ import { missingSession } from "./session-error"
7
+
8
+ /** `job.*` in the `server.experimental` group. */
9
+ export const makeJob = Effect.gen(function* () {
10
+ const jobs = yield* Job.Service
11
+ const sessions = yield* Session.Service
12
+ const lookup = {
13
+ get: (sessionID: Session.ID) => sessions.get(sessionID).pipe(Effect.option, Effect.map(Option.getOrUndefined)),
14
+ }
15
+
16
+ return {
17
+ list: Effect.fn("JobHandler.list")(function* (query: ListQuery) {
18
+ if (query.sessionID !== undefined) {
19
+ yield* sessions.get(query.sessionID).pipe(Effect.catchTag("Session.NotFoundError", missingSession))
20
+ }
21
+ return {
22
+ data: yield* SessionBackground.list(jobs, lookup, query),
23
+ }
24
+ }),
25
+ cancel: Effect.fn("JobHandler.cancel")(function* (id: string) {
26
+ yield* jobs.cancel(id)
27
+ }),
28
+ }
29
+ })
@@ -0,0 +1,33 @@
1
+ import { Location } from "@zyro-sec/core/location"
2
+ import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
3
+ import { ServiceUnavailableError } from "@zyro-sec/protocol/errors"
4
+ import { Cause, Effect } from "effect"
5
+ import { HttpApiBuilder } from "effect/http-api"
6
+ import { Api } from "../api"
7
+
8
+ export const LocationHandler = HttpApiBuilder.group(Api, "server.location", (handlers) =>
9
+ Effect.gen(function* () {
10
+ const locations = yield* LocationServiceMap.Service
11
+ return handlers
12
+ .handle(
13
+ "location.get",
14
+ Effect.fn(function* () {
15
+ const location = yield* Location.Service
16
+ return new Location.Info({
17
+ directory: location.directory,
18
+ project: location.project,
19
+ })
20
+ }),
21
+ )
22
+ .handle("location.reload", () =>
23
+ LocationServiceMap.reload().pipe(
24
+ Effect.provideService(LocationServiceMap.Service, locations),
25
+ Effect.catchCause((cause) =>
26
+ Cause.hasInterruptsOnly(cause)
27
+ ? Effect.failCause(Cause.fromReasons<never>(cause.reasons.filter(Cause.isInterruptReason)))
28
+ : Effect.fail(new ServiceUnavailableError({ message: Cause.pretty(cause), service: "location" })),
29
+ ),
30
+ ),
31
+ )
32
+ }),
33
+ )