@zyro-sec/server 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/package.json +8 -8
  2. package/script/build.ts +28 -28
  3. package/script/pack.ts +5 -5
  4. package/script/workerd-probe.ts +59 -59
  5. package/src/api.ts +12 -12
  6. package/src/auth.ts +70 -70
  7. package/src/content-headers.ts +32 -32
  8. package/src/cors.ts +34 -34
  9. package/src/event-feed.ts +93 -93
  10. package/src/fetch.ts +67 -67
  11. package/src/handlers/agent.ts +23 -23
  12. package/src/handlers/artifact.ts +242 -242
  13. package/src/handlers/automation.ts +63 -63
  14. package/src/handlers/blob.ts +55 -55
  15. package/src/handlers/command.ts +8 -8
  16. package/src/handlers/config.ts +26 -26
  17. package/src/handlers/credential.ts +87 -87
  18. package/src/handlers/debug.ts +57 -57
  19. package/src/handlers/event.ts +38 -38
  20. package/src/handlers/form.ts +15 -15
  21. package/src/handlers/fs.ts +180 -180
  22. package/src/handlers/generate.ts +117 -117
  23. package/src/handlers/integration.ts +310 -310
  24. package/src/handlers/job.ts +29 -29
  25. package/src/handlers/location.ts +33 -33
  26. package/src/handlers/machine.ts +336 -336
  27. package/src/handlers/mcp.ts +160 -160
  28. package/src/handlers/media.ts +44 -44
  29. package/src/handlers/message.ts +82 -82
  30. package/src/handlers/migration.ts +13 -13
  31. package/src/handlers/model.ts +25 -25
  32. package/src/handlers/permission.ts +131 -131
  33. package/src/handlers/persistent-pty.ts +285 -285
  34. package/src/handlers/plugin.ts +97 -97
  35. package/src/handlers/project.ts +23 -23
  36. package/src/handlers/provider.ts +32 -32
  37. package/src/handlers/pty-socket.ts +47 -47
  38. package/src/handlers/pty.ts +181 -181
  39. package/src/handlers/push.ts +67 -67
  40. package/src/handlers/reference.ts +8 -8
  41. package/src/handlers/rpc.ts +31 -31
  42. package/src/handlers/server.ts +58 -58
  43. package/src/handlers/session-error.ts +47 -47
  44. package/src/handlers/session.ts +722 -722
  45. package/src/handlers/shell.ts +72 -72
  46. package/src/handlers/skill.ts +34 -34
  47. package/src/handlers/usage.ts +23 -23
  48. package/src/handlers/vcs.ts +104 -104
  49. package/src/handlers/voice.ts +50 -50
  50. package/src/handlers/websearch.ts +50 -50
  51. package/src/handlers/worktree.ts +60 -60
  52. package/src/handlers.ts +69 -69
  53. package/src/location.ts +86 -86
  54. package/src/media-uri.ts +13 -13
  55. package/src/middleware/authorization.ts +111 -111
  56. package/src/middleware/defect-response.ts +39 -39
  57. package/src/middleware/form-location.ts +44 -44
  58. package/src/middleware/schema-error.ts +49 -49
  59. package/src/middleware/session-location.ts +30 -30
  60. package/src/options.ts +61 -61
  61. package/src/pairing.ts +36 -36
  62. package/src/process.ts +274 -274
  63. package/src/range.ts +16 -16
  64. package/src/request-site.ts +36 -36
  65. package/src/request-tracing.ts +9 -9
  66. package/src/routes.ts +261 -261
  67. package/src/server-info.ts +41 -41
  68. package/src/service-status.ts +30 -30
  69. package/src/workerd.ts +184 -184
  70. package/test/fixture/mcp-starts.cjs +20 -20
  71. package/test/fixture/routes.ts +37 -37
  72. package/test/fixture/server.ts +20 -20
  73. package/test/fixture/worktree-delegate/index.ts +13 -13
  74. package/test/fixture/worktree-plugin/index.ts +47 -47
  75. package/tsconfig.build.json +15 -15
  76. package/tsconfig.json +11 -11
  77. package/test/artifact.test.ts +0 -224
  78. package/test/auth.test.ts +0 -24
  79. package/test/automation.test.ts +0 -315
  80. package/test/client-mcp.test.ts +0 -369
  81. package/test/codemode-api.test.ts +0 -88
  82. package/test/config.test.ts +0 -104
  83. package/test/cors.test.ts +0 -24
  84. package/test/defect-response.test.ts +0 -83
  85. package/test/event-feed.test.ts +0 -201
  86. package/test/fetch-option.test.ts +0 -104
  87. package/test/fetch.test.ts +0 -698
  88. package/test/flag-channel.test.ts +0 -126
  89. package/test/fs.test.ts +0 -439
  90. package/test/generate.test.ts +0 -132
  91. package/test/handler-policy.test.ts +0 -43
  92. package/test/heap-dump.test.ts +0 -137
  93. package/test/integration-policy.test.ts +0 -93
  94. package/test/job.test.ts +0 -186
  95. package/test/machine-iroh.test.ts +0 -259
  96. package/test/machine-link.test.ts +0 -1234
  97. package/test/machine-routes.test.ts +0 -198
  98. package/test/media.test.ts +0 -343
  99. package/test/message.test.ts +0 -105
  100. package/test/model.test.ts +0 -62
  101. package/test/options.test.ts +0 -42
  102. package/test/permission-saved.test.ts +0 -73
  103. package/test/persistent-pty.test.ts +0 -1007
  104. package/test/process.test.ts +0 -261
  105. package/test/provider.test.ts +0 -88
  106. package/test/pty-socket.property.test.ts +0 -240
  107. package/test/pty-socket.test.ts +0 -89
  108. package/test/pty-transport.test.ts +0 -200
  109. package/test/push-routes.test.ts +0 -157
  110. package/test/request-site.test.ts +0 -71
  111. package/test/request-tracing.test.ts +0 -87
  112. package/test/rpc-handler-errors.test.ts +0 -76
  113. package/test/schema-error.test.ts +0 -68
  114. package/test/service-status.test.ts +0 -34
  115. package/test/session-admit-location.test.ts +0 -92
  116. package/test/session-create.test.ts +0 -65
  117. package/test/session-diff.test.ts +0 -100
  118. package/test/session-form.test.ts +0 -50
  119. package/test/session-import.test.ts +0 -152
  120. package/test/session-instances.test.ts +0 -335
  121. package/test/session-unarchive.test.ts +0 -73
  122. package/test/session-update.test.ts +0 -66
  123. package/test/skill.test.ts +0 -57
  124. package/test/sse-failure.test.ts +0 -71
  125. package/test/usage.test.ts +0 -88
  126. package/test/vcs.test.ts +0 -356
  127. package/test/video-generate.test.ts +0 -131
  128. package/test/voice.test.ts +0 -170
  129. package/test/workerd.test.ts +0 -227
  130. package/test/worktree.test.ts +0 -333
@@ -1,111 +1,111 @@
1
- import { ServerAuth } from "../auth"
2
- import { UnauthorizedError } from "@zyro-sec/protocol/errors"
3
- import { Authorization } from "@zyro-sec/protocol/middleware/authorization"
4
- export { Authorization } from "@zyro-sec/protocol/middleware/authorization"
5
- import { PTY_CONNECT_PATH, PTY_CONNECT_TICKET_QUERY } from "@zyro-sec/protocol/groups/pty"
6
- import { PERSISTENT_PTY_CONNECT_PATH } from "@zyro-sec/protocol/groups/persistent-pty"
7
- import { MCP_CLIENT_PATH } from "@zyro-sec/protocol/groups/mcp"
8
- import { isWebSocketUpgrade, MACHINE_LINK_PATH } from "@zyro-sec/protocol/groups/machine"
9
- import { PAIRING_CONNECT_PATH } from "@zyro-sec/protocol/groups/server"
10
- import { Effect, Layer, Redacted } from "effect"
11
- import { Base64 } from "effect/encoding"
12
- import { HttpEffect, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
13
-
14
- const AUTH_TOKEN_QUERY = "auth_token"
15
- const WWW_AUTHENTICATE = 'Basic realm="Secure Area"'
16
-
17
- function emptyCredential() {
18
- return { username: "", password: Redacted.make("") }
19
- }
20
-
21
- function decodeCredential(input: string) {
22
- return Effect.fromResult(Base64.decodeString(input)).pipe(
23
- Effect.match({
24
- onFailure: emptyCredential,
25
- onSuccess: (header) => {
26
- const separator = header.indexOf(":")
27
- if (separator === -1) return emptyCredential()
28
- return { username: header.slice(0, separator), password: Redacted.make(header.slice(separator + 1)) }
29
- },
30
- }),
31
- )
32
- }
33
-
34
- function credentialFromRequest(request: HttpServerRequest.HttpServerRequest) {
35
- const url = new URL(request.url, "http://localhost")
36
- const token = url.searchParams.get(AUTH_TOKEN_QUERY)
37
- if (token) return decodeCredential(token)
38
- const match = /^Basic\s+(.+)$/i.exec(request.headers.authorization ?? "")
39
- if (match) return decodeCredential(match[1])
40
- return Effect.succeed(emptyCredential())
41
- }
42
-
43
- const UNAUTHORIZED_MESSAGE = "Authentication required"
44
-
45
- // Browsers show a native credentials prompt for a Basic challenge even on fetch, which would stall the web app
46
- // before it can show its own sign-in screen. Only non-browser clients and page navigations get the challenge.
47
- function challengeRequest(request: HttpServerRequest.HttpServerRequest) {
48
- const mode = request.headers["sec-fetch-mode"]
49
- return mode === undefined || mode === "navigate"
50
- }
51
-
52
- // Matches what the Authorization middleware encodes, for requests rejected before the HttpApi runs.
53
- export function unauthorizedResponse(request: HttpServerRequest.HttpServerRequest) {
54
- return HttpServerResponse.jsonUnsafe(
55
- { _tag: "UnauthorizedError", message: UNAUTHORIZED_MESSAGE },
56
- { status: 401, headers: challengeRequest(request) ? { "www-authenticate": WWW_AUTHENTICATE } : undefined },
57
- )
58
- }
59
-
60
- export function authorizedRequest(request: HttpServerRequest.HttpServerRequest, config: ServerAuth.Info) {
61
- return credentialFromRequest(request).pipe(
62
- Effect.map((credential) => ServerAuth.authorized(credential, config) || authorizedSessionCookie(request, config)),
63
- )
64
- }
65
-
66
- function authorizedSessionCookie(request: HttpServerRequest.HttpServerRequest, config: ServerAuth.Info) {
67
- const token = request.cookies[ServerAuth.sessionCookieName(request.headers.host)]
68
- if (!token) return false
69
- // Same-site pages on other ports still send this cookie, so only same-origin requests may use it.
70
- const origin = request.headers.origin
71
- if (origin !== undefined && URL.parse(origin)?.host !== request.headers.host) return false
72
- return ServerAuth.verifySession(token, config)
73
- }
74
-
75
- export const authorizationLayer = Layer.effect(
76
- Authorization,
77
- Effect.gen(function* () {
78
- const config = yield* ServerAuth.Config
79
- if (!ServerAuth.required(config)) return Authorization.of((effect) => effect)
80
- return Authorization.of((effect) =>
81
- Effect.gen(function* () {
82
- const request = yield* HttpServerRequest.HttpServerRequest
83
- const route = yield* HttpRouter.RouteContext
84
- // Ticketed PTY and client MCP connects (browsers cannot set headers on WebSocket upgrades) and pairing links
85
- // skip credential checks here; their handlers consume and validate the ticket or code. Use the
86
- // route selected by Effect so authorization and dispatch cannot disagree about the request path.
87
- const url = new URL(request.url, "http://localhost")
88
- if (
89
- ((route.route.path === PTY_CONNECT_PATH ||
90
- route.route.path === PERSISTENT_PTY_CONNECT_PATH ||
91
- route.route.path === MCP_CLIENT_PATH) &&
92
- !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)) ||
93
- route.route.path === PAIRING_CONNECT_PATH
94
- )
95
- return yield* effect
96
- // A machine's link takes no server password: a worker holding it could call the whole API. Only a WebSocket
97
- // upgrade to the route Effect selected passes here, and that is safe because the socket carries nothing until
98
- // the link's own handshake has proved a paired key or a valid join secret, as an SSH port does. Any other
99
- // request to the route is checked like the rest, and with machines off the handler answers the upgrade as an
100
- // unknown route.
101
- if (route.route.path === MACHINE_LINK_PATH && isWebSocketUpgrade(request)) return yield* effect
102
- if (yield* authorizedRequest(request, config)) return yield* effect
103
- if (challengeRequest(request))
104
- yield* HttpEffect.appendPreResponseHandler((_request, response) =>
105
- Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", WWW_AUTHENTICATE)),
106
- )
107
- return yield* new UnauthorizedError({ message: UNAUTHORIZED_MESSAGE })
108
- }),
109
- )
110
- }),
111
- )
1
+ import { ServerAuth } from "../auth"
2
+ import { UnauthorizedError } from "@zyro-sec/protocol/errors"
3
+ import { Authorization } from "@zyro-sec/protocol/middleware/authorization"
4
+ export { Authorization } from "@zyro-sec/protocol/middleware/authorization"
5
+ import { PTY_CONNECT_PATH, PTY_CONNECT_TICKET_QUERY } from "@zyro-sec/protocol/groups/pty"
6
+ import { PERSISTENT_PTY_CONNECT_PATH } from "@zyro-sec/protocol/groups/persistent-pty"
7
+ import { MCP_CLIENT_PATH } from "@zyro-sec/protocol/groups/mcp"
8
+ import { isWebSocketUpgrade, MACHINE_LINK_PATH } from "@zyro-sec/protocol/groups/machine"
9
+ import { PAIRING_CONNECT_PATH } from "@zyro-sec/protocol/groups/server"
10
+ import { Effect, Layer, Redacted } from "effect"
11
+ import { Base64 } from "effect/encoding"
12
+ import { HttpEffect, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
13
+
14
+ const AUTH_TOKEN_QUERY = "auth_token"
15
+ const WWW_AUTHENTICATE = 'Basic realm="Secure Area"'
16
+
17
+ function emptyCredential() {
18
+ return { username: "", password: Redacted.make("") }
19
+ }
20
+
21
+ function decodeCredential(input: string) {
22
+ return Effect.fromResult(Base64.decodeString(input)).pipe(
23
+ Effect.match({
24
+ onFailure: emptyCredential,
25
+ onSuccess: (header) => {
26
+ const separator = header.indexOf(":")
27
+ if (separator === -1) return emptyCredential()
28
+ return { username: header.slice(0, separator), password: Redacted.make(header.slice(separator + 1)) }
29
+ },
30
+ }),
31
+ )
32
+ }
33
+
34
+ function credentialFromRequest(request: HttpServerRequest.HttpServerRequest) {
35
+ const url = new URL(request.url, "http://localhost")
36
+ const token = url.searchParams.get(AUTH_TOKEN_QUERY)
37
+ if (token) return decodeCredential(token)
38
+ const match = /^Basic\s+(.+)$/i.exec(request.headers.authorization ?? "")
39
+ if (match) return decodeCredential(match[1])
40
+ return Effect.succeed(emptyCredential())
41
+ }
42
+
43
+ const UNAUTHORIZED_MESSAGE = "Authentication required"
44
+
45
+ // Browsers show a native credentials prompt for a Basic challenge even on fetch, which would stall the web app
46
+ // before it can show its own sign-in screen. Only non-browser clients and page navigations get the challenge.
47
+ function challengeRequest(request: HttpServerRequest.HttpServerRequest) {
48
+ const mode = request.headers["sec-fetch-mode"]
49
+ return mode === undefined || mode === "navigate"
50
+ }
51
+
52
+ // Matches what the Authorization middleware encodes, for requests rejected before the HttpApi runs.
53
+ export function unauthorizedResponse(request: HttpServerRequest.HttpServerRequest) {
54
+ return HttpServerResponse.jsonUnsafe(
55
+ { _tag: "UnauthorizedError", message: UNAUTHORIZED_MESSAGE },
56
+ { status: 401, headers: challengeRequest(request) ? { "www-authenticate": WWW_AUTHENTICATE } : undefined },
57
+ )
58
+ }
59
+
60
+ export function authorizedRequest(request: HttpServerRequest.HttpServerRequest, config: ServerAuth.Info) {
61
+ return credentialFromRequest(request).pipe(
62
+ Effect.map((credential) => ServerAuth.authorized(credential, config) || authorizedSessionCookie(request, config)),
63
+ )
64
+ }
65
+
66
+ function authorizedSessionCookie(request: HttpServerRequest.HttpServerRequest, config: ServerAuth.Info) {
67
+ const token = request.cookies[ServerAuth.sessionCookieName(request.headers.host)]
68
+ if (!token) return false
69
+ // Same-site pages on other ports still send this cookie, so only same-origin requests may use it.
70
+ const origin = request.headers.origin
71
+ if (origin !== undefined && URL.parse(origin)?.host !== request.headers.host) return false
72
+ return ServerAuth.verifySession(token, config)
73
+ }
74
+
75
+ export const authorizationLayer = Layer.effect(
76
+ Authorization,
77
+ Effect.gen(function* () {
78
+ const config = yield* ServerAuth.Config
79
+ if (!ServerAuth.required(config)) return Authorization.of((effect) => effect)
80
+ return Authorization.of((effect) =>
81
+ Effect.gen(function* () {
82
+ const request = yield* HttpServerRequest.HttpServerRequest
83
+ const route = yield* HttpRouter.RouteContext
84
+ // Ticketed PTY and client MCP connects (browsers cannot set headers on WebSocket upgrades) and pairing links
85
+ // skip credential checks here; their handlers consume and validate the ticket or code. Use the
86
+ // route selected by Effect so authorization and dispatch cannot disagree about the request path.
87
+ const url = new URL(request.url, "http://localhost")
88
+ if (
89
+ ((route.route.path === PTY_CONNECT_PATH ||
90
+ route.route.path === PERSISTENT_PTY_CONNECT_PATH ||
91
+ route.route.path === MCP_CLIENT_PATH) &&
92
+ !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)) ||
93
+ route.route.path === PAIRING_CONNECT_PATH
94
+ )
95
+ return yield* effect
96
+ // A machine's link takes no server password: a worker holding it could call the whole API. Only a WebSocket
97
+ // upgrade to the route Effect selected passes here, and that is safe because the socket carries nothing until
98
+ // the link's own handshake has proved a paired key or a valid join secret, as an SSH port does. Any other
99
+ // request to the route is checked like the rest, and with machines off the handler answers the upgrade as an
100
+ // unknown route.
101
+ if (route.route.path === MACHINE_LINK_PATH && isWebSocketUpgrade(request)) return yield* effect
102
+ if (yield* authorizedRequest(request, config)) return yield* effect
103
+ if (challengeRequest(request))
104
+ yield* HttpEffect.appendPreResponseHandler((_request, response) =>
105
+ Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", WWW_AUTHENTICATE)),
106
+ )
107
+ return yield* new UnauthorizedError({ message: UNAUTHORIZED_MESSAGE })
108
+ }),
109
+ )
110
+ }),
111
+ )
@@ -1,39 +1,39 @@
1
- import { StorageFailure } from "@zyro-sec/core/database/storage-failure"
2
- import { UnknownError } from "@zyro-sec/protocol/errors"
3
- import { Cause, Effect } from "effect"
4
- import { HttpRouter, HttpServerError, HttpServerRequest, HttpServerResponse } from "effect/http"
5
-
6
- const respond = HttpServerResponse.schemaJson(UnknownError)
7
-
8
- // Effect answers a failure it has no response for with an empty 500. Replace exactly that response's body, like the
9
- // encoding failure in schema-error.ts: the reason when it's one a person can act on (a storage failure), otherwise a
10
- // ref to find it in the server log. Every cause Effect already answers (declared errors, route-not-found, defects that
11
- // carry their own response, aborts) keeps its response.
12
- export const defectResponseLayer = HttpRouter.middleware(
13
- (effect) =>
14
- effect.pipe(
15
- Effect.catchCause((cause) =>
16
- Effect.gen(function* () {
17
- const [response] = yield* HttpServerError.causeResponse(cause)
18
- if (response.status !== 500 || response.body._tag !== "Empty") return yield* Effect.failCause(cause)
19
- const request = yield* HttpServerRequest.HttpServerRequest
20
- const ref = `err_${crypto.randomUUID().slice(0, 8)}`
21
- yield* Effect.logError("request failed", cause).pipe(
22
- Effect.annotateLogs({ ref, route: `${request.method} ${request.url}` }),
23
- )
24
- const body = yield* respond(
25
- new UnknownError({
26
- message:
27
- StorageFailure.message(cause) ?? "Server failed to handle the request. Check server logs for details.",
28
- ref,
29
- }),
30
- { status: 500 },
31
- ).pipe(Effect.orDie)
32
- // Fail with the response beside the original cause rather than succeed with it: Effect sends a response
33
- // found in a cause, and the request's span and response log still record the failure.
34
- return yield* Effect.failCause(Cause.combine(cause, Cause.die(body)))
35
- }),
36
- ),
37
- ),
38
- { global: true },
39
- )
1
+ import { StorageFailure } from "@zyro-sec/core/database/storage-failure"
2
+ import { UnknownError } from "@zyro-sec/protocol/errors"
3
+ import { Cause, Effect } from "effect"
4
+ import { HttpRouter, HttpServerError, HttpServerRequest, HttpServerResponse } from "effect/http"
5
+
6
+ const respond = HttpServerResponse.schemaJson(UnknownError)
7
+
8
+ // Effect answers a failure it has no response for with an empty 500. Replace exactly that response's body, like the
9
+ // encoding failure in schema-error.ts: the reason when it's one a person can act on (a storage failure), otherwise a
10
+ // ref to find it in the server log. Every cause Effect already answers (declared errors, route-not-found, defects that
11
+ // carry their own response, aborts) keeps its response.
12
+ export const defectResponseLayer = HttpRouter.middleware(
13
+ (effect) =>
14
+ effect.pipe(
15
+ Effect.catchCause((cause) =>
16
+ Effect.gen(function* () {
17
+ const [response] = yield* HttpServerError.causeResponse(cause)
18
+ if (response.status !== 500 || response.body._tag !== "Empty") return yield* Effect.failCause(cause)
19
+ const request = yield* HttpServerRequest.HttpServerRequest
20
+ const ref = `err_${crypto.randomUUID().slice(0, 8)}`
21
+ yield* Effect.logError("request failed", cause).pipe(
22
+ Effect.annotateLogs({ ref, route: `${request.method} ${request.url}` }),
23
+ )
24
+ const body = yield* respond(
25
+ new UnknownError({
26
+ message:
27
+ StorageFailure.message(cause) ?? "Server failed to handle the request. Check server logs for details.",
28
+ ref,
29
+ }),
30
+ { status: 500 },
31
+ ).pipe(Effect.orDie)
32
+ // Fail with the response beside the original cause rather than succeed with it: Effect sends a response
33
+ // found in a cause, and the request's span and response log still record the failure.
34
+ return yield* Effect.failCause(Cause.combine(cause, Cause.die(body)))
35
+ }),
36
+ ),
37
+ ),
38
+ { global: true },
39
+ )
@@ -1,44 +1,44 @@
1
- import { Instance } from "@zyro-sec/core/instance/service"
2
- import { LocationServiceMap } from "@zyro-sec/core/location-services"
3
- import { Session } from "@zyro-sec/core/session"
4
- import { LocationNotFoundError, InvalidRequestError, SessionNotFoundError } from "@zyro-sec/protocol/errors"
5
- import { Effect, Layer } from "effect"
6
- import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
7
- import { HttpApiMiddleware } from "effect/http-api"
8
- import { locationErrors, requestRef, sessionInfo, type LocationServices } from "../location"
9
-
10
- export class FormLocationMiddleware extends HttpApiMiddleware.Service<
11
- FormLocationMiddleware,
12
- { provides: LocationServices }
13
- >()("@zyro-sec/HttpApiFormLocation", {
14
- error: [InvalidRequestError, SessionNotFoundError, LocationNotFoundError],
15
- }) {}
16
-
17
- export const formLocationLayer = Layer.effect(
18
- FormLocationMiddleware,
19
- Effect.gen(function* () {
20
- const sessions = yield* Session.Service
21
- const instances = yield* Instance.Service
22
- const locations = yield* LocationServiceMap.Service
23
-
24
- return FormLocationMiddleware.of((effect, options) =>
25
- Effect.gen(function* () {
26
- const route = yield* HttpRouter.RouteContext
27
- if (route.params.sessionID === "global") {
28
- // Temporary MCP elicitation escape hatch. This is still Location-scoped; it only bypasses
29
- // the session row lookup because some MCP elicitations cannot currently be attributed to
30
- // a real session. Keep this undocumented and remove once elicitations carry session ownership.
31
- const request = yield* HttpServerRequest.HttpServerRequest
32
- return yield* effect.pipe(Effect.provide(locations.get(requestRef(request))), locationErrors)
33
- }
34
-
35
- const session = yield* sessionInfo(sessions, route.params.sessionID)
36
- // Forms live in memory, so a Session without live capabilities has none pending. Listing must
37
- // not boot its Location: clients poll whole subagent trees, including deleted worktrees.
38
- if (options.endpoint.identifier === "session.form.list" && instances.live && !(yield* instances.live(session)))
39
- return HttpServerResponse.jsonUnsafe({ data: [] })
40
- return yield* effect.pipe(instances.provide(session), locationErrors)
41
- }),
42
- )
43
- }),
44
- )
1
+ import { Instance } from "@zyro-sec/core/instance/service"
2
+ import { LocationServiceMap } from "@zyro-sec/core/location-services"
3
+ import { Session } from "@zyro-sec/core/session"
4
+ import { LocationNotFoundError, InvalidRequestError, SessionNotFoundError } from "@zyro-sec/protocol/errors"
5
+ import { Effect, Layer } from "effect"
6
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
7
+ import { HttpApiMiddleware } from "effect/http-api"
8
+ import { locationErrors, requestRef, sessionInfo, type LocationServices } from "../location"
9
+
10
+ export class FormLocationMiddleware extends HttpApiMiddleware.Service<
11
+ FormLocationMiddleware,
12
+ { provides: LocationServices }
13
+ >()("@zyro-sec/HttpApiFormLocation", {
14
+ error: [InvalidRequestError, SessionNotFoundError, LocationNotFoundError],
15
+ }) {}
16
+
17
+ export const formLocationLayer = Layer.effect(
18
+ FormLocationMiddleware,
19
+ Effect.gen(function* () {
20
+ const sessions = yield* Session.Service
21
+ const instances = yield* Instance.Service
22
+ const locations = yield* LocationServiceMap.Service
23
+
24
+ return FormLocationMiddleware.of((effect, options) =>
25
+ Effect.gen(function* () {
26
+ const route = yield* HttpRouter.RouteContext
27
+ if (route.params.sessionID === "global") {
28
+ // Temporary MCP elicitation escape hatch. This is still Location-scoped; it only bypasses
29
+ // the session row lookup because some MCP elicitations cannot currently be attributed to
30
+ // a real session. Keep this undocumented and remove once elicitations carry session ownership.
31
+ const request = yield* HttpServerRequest.HttpServerRequest
32
+ return yield* effect.pipe(Effect.provide(locations.get(requestRef(request))), locationErrors)
33
+ }
34
+
35
+ const session = yield* sessionInfo(sessions, route.params.sessionID)
36
+ // Forms live in memory, so a Session without live capabilities has none pending. Listing must
37
+ // not boot its Location: clients poll whole subagent trees, including deleted worktrees.
38
+ if (options.endpoint.identifier === "session.form.list" && instances.live && !(yield* instances.live(session)))
39
+ return HttpServerResponse.jsonUnsafe({ data: [] })
40
+ return yield* effect.pipe(instances.provide(session), locationErrors)
41
+ }),
42
+ )
43
+ }),
44
+ )
@@ -1,49 +1,49 @@
1
- import { Effect } from "effect"
2
- import { HttpServerResponse } from "effect/http"
3
- import { HttpApiMiddleware } from "effect/http-api"
4
- import { InvalidRequestError, UnknownError } from "@zyro-sec/protocol/errors"
5
- import { SchemaErrorMiddleware } from "@zyro-sec/protocol/middleware/schema-error"
6
- export { SchemaErrorMiddleware } from "@zyro-sec/protocol/middleware/schema-error"
7
-
8
- const REASON_LIMIT = 1024
9
-
10
- function truncateReason(reason: string) {
11
- if (reason.length <= REASON_LIMIT) return reason
12
- return reason.slice(0, REASON_LIMIT) + `... (${reason.length - REASON_LIMIT} more chars)`
13
- }
14
-
15
- export const schemaErrorLayer = HttpApiMiddleware.layerSchemaErrorTransform(
16
- SchemaErrorMiddleware,
17
- (error, context) => {
18
- const reason = truncateReason(error.cause.message)
19
- // Effect tags response encoding as Body or ResponseHeaders; request decoding uses Params, Headers, Query or Payload.
20
- if (error.kind === "Body" || error.kind === "ResponseHeaders") {
21
- const ref = `err_${crypto.randomUUID().slice(0, 8)}`
22
- return Effect.logError("failed to encode response").pipe(
23
- Effect.annotateLogs({
24
- ref,
25
- kind: error.kind,
26
- endpoint: `${context.group.identifier}.${context.endpoint.name}`,
27
- route: `${context.endpoint.method} ${context.endpoint.path}`,
28
- reason,
29
- }),
30
- // Respond directly rather than failing with a declared error, so every endpoint's contract stays unchanged
31
- // and this 500 reads like any other unexpected server failure.
32
- Effect.as(
33
- HttpServerResponse.jsonUnsafe(
34
- {
35
- _tag: "UnknownError",
36
- message: "Server failed to encode its response. Check server logs for details.",
37
- ref,
38
- } satisfies typeof UnknownError.Encoded,
39
- { status: 500 },
40
- ),
41
- ),
42
- )
43
- }
44
- return Effect.logWarning("schema rejection").pipe(
45
- Effect.annotateLogs({ kind: error.kind, reason }),
46
- Effect.andThen(Effect.fail(new InvalidRequestError({ message: reason, kind: error.kind }))),
47
- )
48
- },
49
- )
1
+ import { Effect } from "effect"
2
+ import { HttpServerResponse } from "effect/http"
3
+ import { HttpApiMiddleware } from "effect/http-api"
4
+ import { InvalidRequestError, UnknownError } from "@zyro-sec/protocol/errors"
5
+ import { SchemaErrorMiddleware } from "@zyro-sec/protocol/middleware/schema-error"
6
+ export { SchemaErrorMiddleware } from "@zyro-sec/protocol/middleware/schema-error"
7
+
8
+ const REASON_LIMIT = 1024
9
+
10
+ function truncateReason(reason: string) {
11
+ if (reason.length <= REASON_LIMIT) return reason
12
+ return reason.slice(0, REASON_LIMIT) + `... (${reason.length - REASON_LIMIT} more chars)`
13
+ }
14
+
15
+ export const schemaErrorLayer = HttpApiMiddleware.layerSchemaErrorTransform(
16
+ SchemaErrorMiddleware,
17
+ (error, context) => {
18
+ const reason = truncateReason(error.cause.message)
19
+ // Effect tags response encoding as Body or ResponseHeaders; request decoding uses Params, Headers, Query or Payload.
20
+ if (error.kind === "Body" || error.kind === "ResponseHeaders") {
21
+ const ref = `err_${crypto.randomUUID().slice(0, 8)}`
22
+ return Effect.logError("failed to encode response").pipe(
23
+ Effect.annotateLogs({
24
+ ref,
25
+ kind: error.kind,
26
+ endpoint: `${context.group.identifier}.${context.endpoint.name}`,
27
+ route: `${context.endpoint.method} ${context.endpoint.path}`,
28
+ reason,
29
+ }),
30
+ // Respond directly rather than failing with a declared error, so every endpoint's contract stays unchanged
31
+ // and this 500 reads like any other unexpected server failure.
32
+ Effect.as(
33
+ HttpServerResponse.jsonUnsafe(
34
+ {
35
+ _tag: "UnknownError",
36
+ message: "Server failed to encode its response. Check server logs for details.",
37
+ ref,
38
+ } satisfies typeof UnknownError.Encoded,
39
+ { status: 500 },
40
+ ),
41
+ ),
42
+ )
43
+ }
44
+ return Effect.logWarning("schema rejection").pipe(
45
+ Effect.annotateLogs({ kind: error.kind, reason }),
46
+ Effect.andThen(Effect.fail(new InvalidRequestError({ message: reason, kind: error.kind }))),
47
+ )
48
+ },
49
+ )
@@ -1,30 +1,30 @@
1
- import { Instance } from "@zyro-sec/core/instance/service"
2
- import { Session } from "@zyro-sec/core/session"
3
- import { Effect, Layer } from "effect"
4
- import { HttpRouter } from "effect/http"
5
- import { HttpApiMiddleware } from "effect/http-api"
6
- import { LocationNotFoundError, InvalidRequestError, SessionNotFoundError } from "@zyro-sec/protocol/errors"
7
- import { locationErrors, sessionInfo, type LocationServices } from "../location"
8
-
9
- export class SessionLocationMiddleware extends HttpApiMiddleware.Service<
10
- SessionLocationMiddleware,
11
- { provides: LocationServices }
12
- >()("@zyro-sec/HttpApiSessionLocation", {
13
- error: [InvalidRequestError, SessionNotFoundError, LocationNotFoundError],
14
- }) {}
15
-
16
- export const sessionLocationLayer = Layer.effect(
17
- SessionLocationMiddleware,
18
- Effect.gen(function* () {
19
- const sessions = yield* Session.Service
20
- const instances = yield* Instance.Service
21
-
22
- return SessionLocationMiddleware.of((effect) =>
23
- Effect.gen(function* () {
24
- const route = yield* HttpRouter.RouteContext
25
- const session = yield* sessionInfo(sessions, route.params.sessionID)
26
- return yield* effect.pipe(instances.provide(session), locationErrors)
27
- }),
28
- )
29
- }),
30
- )
1
+ import { Instance } from "@zyro-sec/core/instance/service"
2
+ import { Session } from "@zyro-sec/core/session"
3
+ import { Effect, Layer } from "effect"
4
+ import { HttpRouter } from "effect/http"
5
+ import { HttpApiMiddleware } from "effect/http-api"
6
+ import { LocationNotFoundError, InvalidRequestError, SessionNotFoundError } from "@zyro-sec/protocol/errors"
7
+ import { locationErrors, sessionInfo, type LocationServices } from "../location"
8
+
9
+ export class SessionLocationMiddleware extends HttpApiMiddleware.Service<
10
+ SessionLocationMiddleware,
11
+ { provides: LocationServices }
12
+ >()("@zyro-sec/HttpApiSessionLocation", {
13
+ error: [InvalidRequestError, SessionNotFoundError, LocationNotFoundError],
14
+ }) {}
15
+
16
+ export const sessionLocationLayer = Layer.effect(
17
+ SessionLocationMiddleware,
18
+ Effect.gen(function* () {
19
+ const sessions = yield* Session.Service
20
+ const instances = yield* Instance.Service
21
+
22
+ return SessionLocationMiddleware.of((effect) =>
23
+ Effect.gen(function* () {
24
+ const route = yield* HttpRouter.RouteContext
25
+ const session = yield* sessionInfo(sessions, route.params.sessionID)
26
+ return yield* effect.pipe(instances.provide(session), locationErrors)
27
+ }),
28
+ )
29
+ }),
30
+ )