@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.
- package/package.json +40 -4
- package/script/build.ts +28 -0
- package/script/pack.ts +5 -0
- package/script/workerd-probe.ts +59 -0
- package/src/api.ts +12 -0
- package/src/auth.ts +70 -0
- package/src/content-headers.ts +32 -0
- package/src/cors.ts +34 -0
- package/src/event-feed.ts +93 -0
- package/src/fetch.ts +67 -0
- package/src/handlers/agent.ts +23 -0
- package/src/handlers/artifact.ts +242 -0
- package/src/handlers/automation.ts +63 -0
- package/src/handlers/blob.ts +55 -0
- package/src/handlers/command.ts +8 -0
- package/src/handlers/config.ts +26 -0
- package/src/handlers/credential.ts +87 -0
- package/src/handlers/debug.ts +57 -0
- package/src/handlers/event.ts +38 -0
- package/src/handlers/form.ts +15 -0
- package/src/handlers/fs.ts +180 -0
- package/src/handlers/generate.ts +117 -0
- package/src/handlers/integration.ts +310 -0
- package/src/handlers/job.ts +29 -0
- package/src/handlers/location.ts +33 -0
- package/src/handlers/machine.ts +336 -0
- package/src/handlers/mcp.ts +160 -0
- package/src/handlers/media.ts +44 -0
- package/src/handlers/message.ts +82 -0
- package/src/handlers/migration.ts +13 -0
- package/src/handlers/model.ts +25 -0
- package/src/handlers/permission.ts +131 -0
- package/src/handlers/persistent-pty.ts +285 -0
- package/src/handlers/plugin.ts +97 -0
- package/src/handlers/project.ts +23 -0
- package/src/handlers/provider.ts +32 -0
- package/src/handlers/pty-socket.ts +47 -0
- package/src/handlers/pty.ts +181 -0
- package/src/handlers/push.ts +67 -0
- package/src/handlers/reference.ts +8 -0
- package/src/handlers/rpc.ts +31 -0
- package/src/handlers/server.ts +58 -0
- package/src/handlers/session-error.ts +47 -0
- package/src/handlers/session.ts +722 -0
- package/src/handlers/shell.ts +72 -0
- package/src/handlers/skill.ts +34 -0
- package/src/handlers/usage.ts +23 -0
- package/src/handlers/vcs.ts +104 -0
- package/src/handlers/voice.ts +50 -0
- package/src/handlers/websearch.ts +50 -0
- package/src/handlers/worktree.ts +60 -0
- package/src/handlers.ts +69 -0
- package/src/location.ts +86 -0
- package/src/media-uri.ts +13 -0
- package/src/middleware/authorization.ts +111 -0
- package/src/middleware/defect-response.ts +39 -0
- package/src/middleware/form-location.ts +44 -0
- package/src/middleware/schema-error.ts +49 -0
- package/src/middleware/session-location.ts +30 -0
- package/src/options.ts +61 -0
- package/src/pairing.ts +36 -0
- package/src/process.ts +274 -0
- package/src/range.ts +16 -0
- package/src/request-site.ts +36 -0
- package/src/request-tracing.ts +9 -0
- package/src/routes.ts +261 -0
- package/src/server-info.ts +41 -0
- package/src/service-status.ts +30 -0
- package/src/workerd.ts +184 -0
- package/test/artifact.test.ts +224 -0
- package/test/auth.test.ts +24 -0
- package/test/automation.test.ts +315 -0
- package/test/client-mcp.test.ts +369 -0
- package/test/codemode-api.test.ts +88 -0
- package/test/config.test.ts +104 -0
- package/test/cors.test.ts +24 -0
- package/test/defect-response.test.ts +83 -0
- package/test/event-feed.test.ts +201 -0
- package/test/fetch-option.test.ts +104 -0
- package/test/fetch.test.ts +698 -0
- package/test/fixture/mcp-starts.cjs +20 -0
- package/test/fixture/routes.ts +37 -0
- package/test/fixture/server.ts +20 -0
- package/test/fixture/worktree-delegate/index.ts +13 -0
- package/test/fixture/worktree-plugin/index.ts +47 -0
- package/test/flag-channel.test.ts +126 -0
- package/test/fs.test.ts +439 -0
- package/test/generate.test.ts +132 -0
- package/test/handler-policy.test.ts +43 -0
- package/test/heap-dump.test.ts +137 -0
- package/test/integration-policy.test.ts +93 -0
- package/test/job.test.ts +186 -0
- package/test/machine-iroh.test.ts +259 -0
- package/test/machine-link.test.ts +1234 -0
- package/test/machine-routes.test.ts +198 -0
- package/test/media.test.ts +343 -0
- package/test/message.test.ts +105 -0
- package/test/model.test.ts +62 -0
- package/test/options.test.ts +42 -0
- package/test/permission-saved.test.ts +73 -0
- package/test/persistent-pty.test.ts +1007 -0
- package/test/process.test.ts +261 -0
- package/test/provider.test.ts +88 -0
- package/test/pty-socket.property.test.ts +240 -0
- package/test/pty-socket.test.ts +89 -0
- package/test/pty-transport.test.ts +200 -0
- package/test/push-routes.test.ts +157 -0
- package/test/request-site.test.ts +71 -0
- package/test/request-tracing.test.ts +87 -0
- package/test/rpc-handler-errors.test.ts +76 -0
- package/test/schema-error.test.ts +68 -0
- package/test/service-status.test.ts +34 -0
- package/test/session-admit-location.test.ts +92 -0
- package/test/session-create.test.ts +65 -0
- package/test/session-diff.test.ts +100 -0
- package/test/session-form.test.ts +50 -0
- package/test/session-import.test.ts +152 -0
- package/test/session-instances.test.ts +335 -0
- package/test/session-unarchive.test.ts +73 -0
- package/test/session-update.test.ts +66 -0
- package/test/skill.test.ts +57 -0
- package/test/sse-failure.test.ts +71 -0
- package/test/usage.test.ts +88 -0
- package/test/vcs.test.ts +356 -0
- package/test/video-generate.test.ts +131 -0
- package/test/voice.test.ts +170 -0
- package/test/workerd.test.ts +227 -0
- package/test/worktree.test.ts +333 -0
- package/tsconfig.build.json +15 -0
- package/tsconfig.json +11 -0
- package/README.md +0 -3
|
@@ -0,0 +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
|
+
)
|
|
@@ -0,0 +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
|
+
)
|
|
@@ -0,0 +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
|
+
)
|
|
@@ -0,0 +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
|
+
)
|
|
@@ -0,0 +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
|
+
)
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Database } from "@zyro-sec/core/database/database"
|
|
2
|
+
import { ModelsDev } from "@zyro-sec/core/models-dev"
|
|
3
|
+
import { PersistentPty } from "@zyro-sec/core/persistent-pty"
|
|
4
|
+
import { Schema } from "effect"
|
|
5
|
+
import type { LayerNodePlatform } from "@zyro-sec/util/effect/app-node-platform"
|
|
6
|
+
|
|
7
|
+
export const ServerOptions = Schema.Struct({
|
|
8
|
+
app: Schema.optional(
|
|
9
|
+
Schema.Struct({
|
|
10
|
+
name: Schema.optional(Schema.String),
|
|
11
|
+
version: Schema.optional(Schema.String),
|
|
12
|
+
channel: Schema.optional(Schema.String),
|
|
13
|
+
}),
|
|
14
|
+
),
|
|
15
|
+
hostname: Schema.optional(Schema.String),
|
|
16
|
+
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(65_535))),
|
|
17
|
+
password: Schema.optional(Schema.String),
|
|
18
|
+
cors: Schema.optional(Schema.Array(Schema.String)),
|
|
19
|
+
simulation: Schema.optional(Schema.Boolean),
|
|
20
|
+
database: Schema.optional(Database.Options),
|
|
21
|
+
pty: Schema.optional(PersistentPty.Options),
|
|
22
|
+
events: Schema.optional(
|
|
23
|
+
Schema.Struct({
|
|
24
|
+
persist: Schema.optional(Schema.Boolean),
|
|
25
|
+
}),
|
|
26
|
+
),
|
|
27
|
+
models: Schema.optional(ModelsDev.Options),
|
|
28
|
+
/**
|
|
29
|
+
* Replaces `globalThis.fetch` for OpenCode's own HTTP requests: OpenCode Console config, model requests, web fetch
|
|
30
|
+
* and search, well-known config, and remote MCP servers. Agent code in Code Mode keeps `globalThis.fetch`. For
|
|
31
|
+
* example, a Cloudflare Worker can route requests through a Service Binding.
|
|
32
|
+
*/
|
|
33
|
+
fetch: Schema.optional(Schema.declare((input): input is LayerNodePlatform.Fetch => typeof input === "function")),
|
|
34
|
+
config: Schema.optional(
|
|
35
|
+
Schema.Struct({
|
|
36
|
+
directory: Schema.optional(Schema.String),
|
|
37
|
+
project: Schema.optional(Schema.Boolean),
|
|
38
|
+
claude: Schema.optional(Schema.Boolean),
|
|
39
|
+
file: Schema.optional(Schema.String),
|
|
40
|
+
content: Schema.optional(Schema.String),
|
|
41
|
+
}),
|
|
42
|
+
),
|
|
43
|
+
instructions: Schema.optional(
|
|
44
|
+
Schema.Struct({
|
|
45
|
+
// false skips the per-directory and ~/.claude/CLAUDE.md fallbacks.
|
|
46
|
+
claude: Schema.optional(Schema.Boolean),
|
|
47
|
+
}),
|
|
48
|
+
),
|
|
49
|
+
windows: Schema.optional(
|
|
50
|
+
Schema.Struct({
|
|
51
|
+
gitbash: Schema.optional(Schema.String),
|
|
52
|
+
}),
|
|
53
|
+
),
|
|
54
|
+
fs: Schema.optional(
|
|
55
|
+
Schema.Struct({
|
|
56
|
+
filewatcher: Schema.optional(Schema.Boolean),
|
|
57
|
+
fff: Schema.optional(Schema.Boolean),
|
|
58
|
+
}),
|
|
59
|
+
),
|
|
60
|
+
})
|
|
61
|
+
export type ServerOptions = typeof ServerOptions.Type
|
package/src/pairing.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export * as ServerPairing from "./pairing"
|
|
2
|
+
|
|
3
|
+
import { Cache, Context, Duration, Effect, Layer } from "effect"
|
|
4
|
+
import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
|
|
5
|
+
import { randomBytes } from "node:crypto"
|
|
6
|
+
|
|
7
|
+
const TTL = Duration.minutes(5)
|
|
8
|
+
|
|
9
|
+
export interface Interface {
|
|
10
|
+
readonly issue: () => Effect.Effect<{ readonly code: string; readonly expires_in: number }>
|
|
11
|
+
readonly consume: (code: string) => Effect.Effect<boolean>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class Service extends Context.Service<Service, Interface>()("@zyro-sec/ServerPairing") {}
|
|
15
|
+
|
|
16
|
+
// Codes are inserted via Cache.set and removed via invalidateWhen, so the lookup never runs.
|
|
17
|
+
const noLookup = () => Effect.die(new Error("ServerPairing cache must be used via set/invalidateWhen, never get"))
|
|
18
|
+
|
|
19
|
+
const layer = Layer.effect(
|
|
20
|
+
Service,
|
|
21
|
+
Effect.gen(function* () {
|
|
22
|
+
const cache = yield* Cache.make<string, true>({ capacity: 1_000, lookup: noLookup, timeToLive: TTL })
|
|
23
|
+
return Service.of({
|
|
24
|
+
issue: Effect.fn("ServerPairing.issue")(function* () {
|
|
25
|
+
const code = randomBytes(16).toString("base64url")
|
|
26
|
+
yield* Cache.set(cache, code, true)
|
|
27
|
+
return { code, expires_in: Duration.toSeconds(TTL) }
|
|
28
|
+
}),
|
|
29
|
+
consume: Effect.fn("ServerPairing.consume")(function* (code) {
|
|
30
|
+
return yield* Cache.invalidateWhen(cache, code, () => true)
|
|
31
|
+
}),
|
|
32
|
+
})
|
|
33
|
+
}),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
export const node = makeGlobalNode({ service: Service, layer, deps: [] })
|
package/src/process.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
export * as ServerProcess from "./process"
|
|
2
|
+
|
|
3
|
+
import { NodeHttpServer } from "@effect/platform-node"
|
|
4
|
+
import { Bus } from "@zyro-sec/core/bus"
|
|
5
|
+
import { SessionRestart } from "@zyro-sec/core/session/execution/restart"
|
|
6
|
+
import { Automation } from "@zyro-sec/core/automation"
|
|
7
|
+
import { SessionSearchBuild } from "@zyro-sec/core/session/search-build"
|
|
8
|
+
import { InstallationEvent } from "@zyro-sec/schema/installation-event"
|
|
9
|
+
import { hasPtyConnectTicketURL } from "@zyro-sec/protocol/groups/pty"
|
|
10
|
+
import { hasPersistentPtyConnectTicketURL } from "@zyro-sec/protocol/groups/persistent-pty"
|
|
11
|
+
import { hasMcpClientTicketURL } from "@zyro-sec/protocol/groups/mcp"
|
|
12
|
+
import { isMachineLinkUpgrade } from "@zyro-sec/protocol/groups/machine"
|
|
13
|
+
import { isPairingConnectURL } from "@zyro-sec/protocol/groups/server"
|
|
14
|
+
import { Global } from "@zyro-sec/util/global"
|
|
15
|
+
import { Cause, Context, Effect, Exit, Latch, Layer, Option, Ref, Scope } from "effect"
|
|
16
|
+
import { HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
|
|
17
|
+
import { NetAddress } from "effect/net"
|
|
18
|
+
import { createServer } from "node:http"
|
|
19
|
+
import { ServerAuth } from "./auth"
|
|
20
|
+
import { isAllowedCorsOrigin } from "./cors"
|
|
21
|
+
import { machinesEnabled } from "./handlers/machine"
|
|
22
|
+
import { authorizedRequest, unauthorizedResponse } from "./middleware/authorization"
|
|
23
|
+
import { withoutParentSpan } from "./request-tracing"
|
|
24
|
+
import { RequestSite } from "./request-site"
|
|
25
|
+
import { createRoutes } from "./routes"
|
|
26
|
+
import { ServerInfo } from "./server-info"
|
|
27
|
+
import { Status } from "./service-status"
|
|
28
|
+
import type { ServerOptions } from "./options"
|
|
29
|
+
|
|
30
|
+
export interface Lifecycle<E = never, R = never> {
|
|
31
|
+
readonly onListen: (
|
|
32
|
+
address: NetAddress.SocketAddress,
|
|
33
|
+
shutdown: Effect.Effect<void>,
|
|
34
|
+
) => Effect.Effect<Effect.Effect<void>, E, R>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type App = Effect.Effect<
|
|
38
|
+
HttpServerResponse.HttpServerResponse,
|
|
39
|
+
unknown,
|
|
40
|
+
HttpServerRequest.HttpServerRequest | Scope.Scope
|
|
41
|
+
>
|
|
42
|
+
|
|
43
|
+
export type Transform = (app: App) => App
|
|
44
|
+
|
|
45
|
+
const errorResponseLogger = HttpMiddleware.make((app) =>
|
|
46
|
+
HttpMiddleware.logger(
|
|
47
|
+
Effect.tap(app, (response) =>
|
|
48
|
+
response.status < 400 ? HttpMiddleware.withLoggerDisabled(Effect.void) : Effect.void,
|
|
49
|
+
),
|
|
50
|
+
),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
|
|
54
|
+
options: ServerOptions,
|
|
55
|
+
lifecycle?: Lifecycle<E, R>,
|
|
56
|
+
transform?: Transform,
|
|
57
|
+
remoteURLs?: () => ReadonlyArray<string>,
|
|
58
|
+
) {
|
|
59
|
+
const password = options.password
|
|
60
|
+
if (!password) return yield* Effect.fail(new Error("Missing server password"))
|
|
61
|
+
const hostname = options.hostname ?? "127.0.0.1"
|
|
62
|
+
const port = Option.fromNullishOr(options.port)
|
|
63
|
+
const shutdown = yield* Latch.make()
|
|
64
|
+
const status = yield* Status.make()
|
|
65
|
+
const bound = yield* listen({ hostname, port })
|
|
66
|
+
const localURLs = () => {
|
|
67
|
+
const address = bound.server.address()
|
|
68
|
+
if (address === null || typeof address === "string") return []
|
|
69
|
+
const host = address.family === "IPv6" ? `[${address.address}]` : address.address
|
|
70
|
+
return ServerInfo.connectionURLs(`http://${host}:${address.port}`, hostname)
|
|
71
|
+
}
|
|
72
|
+
const urls = () => [...localURLs(), ...(remoteURLs?.() ?? [])]
|
|
73
|
+
const application = yield* Ref.make(Option.none<App>())
|
|
74
|
+
// Off until the routes are up, which is when the flag can be read.
|
|
75
|
+
const machinesFlag = yield* Ref.make(Effect.succeed(false))
|
|
76
|
+
const app = dispatch(
|
|
77
|
+
password,
|
|
78
|
+
status,
|
|
79
|
+
application,
|
|
80
|
+
machinesFlag,
|
|
81
|
+
options.app?.version ?? "unknown",
|
|
82
|
+
urls,
|
|
83
|
+
Global.Path.tmp,
|
|
84
|
+
)
|
|
85
|
+
// Request fibers may continue inbound trace context, but must not inherit the server startup parent.
|
|
86
|
+
yield* bound.http
|
|
87
|
+
.serve(
|
|
88
|
+
(transform ? transform(app) : app).pipe(
|
|
89
|
+
RequestSite.middleware(options),
|
|
90
|
+
HttpMiddleware.compression(),
|
|
91
|
+
HttpMiddleware.cors({ allowedOrigins: (origin) => isAllowedCorsOrigin(origin, options), maxAge: 86_400 }),
|
|
92
|
+
),
|
|
93
|
+
errorResponseLogger,
|
|
94
|
+
)
|
|
95
|
+
.pipe(Effect.provide(NodeHttpServer.layerHttpServices), withoutParentSpan)
|
|
96
|
+
if (lifecycle)
|
|
97
|
+
yield* lifecycle.onListen(bound.http.address, shutdown.open.pipe(Effect.asVoid)).pipe(
|
|
98
|
+
Effect.flatMap((cleanup) =>
|
|
99
|
+
Effect.addFinalizer(() => Scope.close(bound.scope, Exit.void).pipe(Effect.andThen(cleanup))),
|
|
100
|
+
),
|
|
101
|
+
Effect.uninterruptible,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
const parentScope = yield* Scope.Scope
|
|
105
|
+
const applicationScope = yield* Scope.fork(parentScope)
|
|
106
|
+
yield* Effect.addFinalizer(() =>
|
|
107
|
+
status.beginStopping.pipe(
|
|
108
|
+
Effect.andThen(Ref.set(application, Option.none())),
|
|
109
|
+
Effect.andThen(Effect.sync(() => bound.server.closeAllConnections())),
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
// Built without the startup span: route handlers and background fibers capture this context, and would
|
|
114
|
+
// otherwise nest every request and session turn for the life of the process under one trace.
|
|
115
|
+
const boot = Effect.gen(function* () {
|
|
116
|
+
const context = yield* Layer.buildWithScope(
|
|
117
|
+
createRoutes(
|
|
118
|
+
{
|
|
119
|
+
...options,
|
|
120
|
+
password,
|
|
121
|
+
},
|
|
122
|
+
urls,
|
|
123
|
+
).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
|
|
124
|
+
applicationScope,
|
|
125
|
+
)
|
|
126
|
+
if (lifecycle) {
|
|
127
|
+
yield* installRestartContinuity(Context.get(context, SessionRestart.Service)).pipe(
|
|
128
|
+
Effect.provideService(Scope.Scope, applicationScope),
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
// Automations run from any server process (`service`, `opencode serve`, or `--standalone`); the table holds all their state.
|
|
132
|
+
yield* Effect.forkIn(Context.get(context, Automation.Service).run, applicationScope)
|
|
133
|
+
// Likewise the one-time session search build, once a location has sqlite_fts on.
|
|
134
|
+
yield* Effect.forkIn(Context.get(context, SessionSearchBuild.Service).run, applicationScope)
|
|
135
|
+
yield* Ref.set(machinesFlag, yield* machinesEnabled.pipe(Effect.provide(context)))
|
|
136
|
+
yield* Ref.set(application, Option.some(Context.get(context, HttpRouter.HttpRouter).asHttpEffect()))
|
|
137
|
+
yield* status.ready
|
|
138
|
+
const bus = Context.get(context, Bus.Service)
|
|
139
|
+
return {
|
|
140
|
+
address: bound.http.address,
|
|
141
|
+
shutdown: shutdown.await,
|
|
142
|
+
updateAvailable: (version: string) =>
|
|
143
|
+
bus.publish(InstallationEvent.UpdateAvailable, { version }).pipe(Effect.asVoid),
|
|
144
|
+
updated: (version: string) => bus.publish(InstallationEvent.Updated, { version }).pipe(Effect.asVoid),
|
|
145
|
+
}
|
|
146
|
+
}).pipe(
|
|
147
|
+
withoutParentSpan,
|
|
148
|
+
Effect.catchCause((cause) => {
|
|
149
|
+
if (!lifecycle || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause)
|
|
150
|
+
return status.fail.pipe(
|
|
151
|
+
Effect.andThen(
|
|
152
|
+
Scope.close(applicationScope, Exit.failCause(cause)).pipe(
|
|
153
|
+
Effect.catchCause((cleanupCause) =>
|
|
154
|
+
Effect.logError("failed to clean up background service boot", { cause: cleanupCause }),
|
|
155
|
+
),
|
|
156
|
+
),
|
|
157
|
+
),
|
|
158
|
+
Effect.andThen(Effect.logError("background service boot failed", { cause })),
|
|
159
|
+
Effect.andThen(Effect.never),
|
|
160
|
+
)
|
|
161
|
+
}),
|
|
162
|
+
)
|
|
163
|
+
if (!lifecycle) return yield* boot
|
|
164
|
+
return yield* Effect.raceFirst(boot, shutdown.await.pipe(Effect.andThen(Effect.interrupt)))
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
function listen(options: { readonly hostname: string; readonly port: Option.Option<number> }) {
|
|
168
|
+
if (Option.isSome(options.port)) return bind(options.hostname, options.port.value)
|
|
169
|
+
const next = (port: number): ReturnType<typeof bind> =>
|
|
170
|
+
bind(options.hostname, port).pipe(
|
|
171
|
+
Effect.catch((error) => (port < 65_535 && addressInUse(error) ? next(port + 1) : Effect.fail(error))),
|
|
172
|
+
)
|
|
173
|
+
return next(4096)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function bind(hostname: string, port: number) {
|
|
177
|
+
return Effect.gen(function* () {
|
|
178
|
+
const parentScope = yield* Scope.Scope
|
|
179
|
+
const serverScope = yield* Scope.fork(parentScope)
|
|
180
|
+
const server = createServer()
|
|
181
|
+
return yield* Effect.gen(function* () {
|
|
182
|
+
const http = yield* NodeHttpServer.make(() => server, { port, host: hostname })
|
|
183
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
|
|
184
|
+
return { http, server, scope: serverScope }
|
|
185
|
+
}).pipe(
|
|
186
|
+
Effect.provideService(Scope.Scope, serverScope),
|
|
187
|
+
Effect.onError((cause) => Scope.close(serverScope, Exit.failCause(cause))),
|
|
188
|
+
)
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function addressInUse(error: unknown) {
|
|
193
|
+
if (typeof error !== "object" || error === null || !("cause" in error)) return false
|
|
194
|
+
const cause = error.cause
|
|
195
|
+
return typeof cause === "object" && cause !== null && "code" in cause && cause.code === "EADDRINUSE"
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function dispatch(
|
|
199
|
+
password: string,
|
|
200
|
+
status: Status.Interface,
|
|
201
|
+
application: Ref.Ref<Option.Option<App>>,
|
|
202
|
+
machinesFlag: Ref.Ref<Effect.Effect<boolean>>,
|
|
203
|
+
version: string,
|
|
204
|
+
urls: () => ReadonlyArray<string>,
|
|
205
|
+
tmp: string,
|
|
206
|
+
): App {
|
|
207
|
+
const auth = ServerAuth.Config.of({ password: Option.some(password), username: "zyrosec" })
|
|
208
|
+
return Effect.gen(function* () {
|
|
209
|
+
const request = yield* HttpServerRequest.HttpServerRequest
|
|
210
|
+
const url = new URL(request.url, "http://localhost")
|
|
211
|
+
const state = yield* status.current
|
|
212
|
+
const app = yield* Ref.get(application)
|
|
213
|
+
const machines = yield* Ref.get(machinesFlag)
|
|
214
|
+
const ready = state.type === "ready" && Option.isSome(app)
|
|
215
|
+
if (request.method === "GET" && url.pathname === "/api/info" && !ready) {
|
|
216
|
+
if (!(yield* authorizedRequest(request, auth))) return unauthorizedResponse(request)
|
|
217
|
+
return yield* infoResponse(status, version, urls, tmp)
|
|
218
|
+
}
|
|
219
|
+
if (
|
|
220
|
+
!isPairingConnectURL(url) &&
|
|
221
|
+
(!ready ||
|
|
222
|
+
(!hasPtyConnectTicketURL(url) &&
|
|
223
|
+
!hasPersistentPtyConnectTicketURL(url) &&
|
|
224
|
+
!hasMcpClientTicketURL(url) &&
|
|
225
|
+
// With machines off the link's path is an unknown route, and gets this 401 like one.
|
|
226
|
+
!(isMachineLinkUpgrade(request) && (yield* machines)))) &&
|
|
227
|
+
!(yield* authorizedRequest(request, auth))
|
|
228
|
+
)
|
|
229
|
+
return unauthorizedResponse(request)
|
|
230
|
+
if (ready) return yield* app.value
|
|
231
|
+
return unavailable(state)
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const infoResponse = Effect.fnUntraced(function* (
|
|
236
|
+
status: Status.Interface,
|
|
237
|
+
version: string,
|
|
238
|
+
urls: () => ReadonlyArray<string>,
|
|
239
|
+
tmp: string,
|
|
240
|
+
) {
|
|
241
|
+
const state = yield* status.current
|
|
242
|
+
return HttpServerResponse.jsonUnsafe(
|
|
243
|
+
{ version, pid: process.pid, urls: urls(), paths: { tmp } },
|
|
244
|
+
{
|
|
245
|
+
status: state.type === "ready" ? 200 : state.type === "failed" ? 500 : 503,
|
|
246
|
+
headers: state.type === "starting" || state.type === "stopping" ? { "retry-after": "1" } : undefined,
|
|
247
|
+
},
|
|
248
|
+
)
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
function unavailable(status: Status.State) {
|
|
252
|
+
if (status.type === "failed")
|
|
253
|
+
return HttpServerResponse.jsonUnsafe(
|
|
254
|
+
{
|
|
255
|
+
code: "service_failed",
|
|
256
|
+
message: "The background service could not start.",
|
|
257
|
+
action: "Run `opencode service restart` after checking the service logs.",
|
|
258
|
+
},
|
|
259
|
+
{ status: 503 },
|
|
260
|
+
)
|
|
261
|
+
return HttpServerResponse.jsonUnsafe(
|
|
262
|
+
{ code: status.type === "stopping" ? "service_stopping" : "service_starting" },
|
|
263
|
+
{ status: 503, headers: { "retry-after": "1" } },
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The managed server owns restart continuity: at boot it resumes Sessions whose execution claim was
|
|
269
|
+
* never released. Claims are written when execution starts (see SessionExecution), so recovery covers
|
|
270
|
+
* graceful restarts and unclean deaths alike — no shutdown hook participates.
|
|
271
|
+
*/
|
|
272
|
+
const installRestartContinuity = Effect.fnUntraced(function* (restart: SessionRestart.Interface) {
|
|
273
|
+
yield* Effect.forkScoped(restart.resumeSuspendedSessions)
|
|
274
|
+
})
|
package/src/range.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export * as ByteRange from "./range"
|
|
2
|
+
|
|
3
|
+
/** A single `bytes=` range of a `size`-byte body, inclusive. Undefined serves the whole body. */
|
|
4
|
+
export function parse(header: string | undefined, size: number) {
|
|
5
|
+
const match = header === undefined ? null : /^bytes=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(header.trim())
|
|
6
|
+
if (match === null || (match[1] === "" && match[2] === "")) return undefined
|
|
7
|
+
if (match[1] === "") {
|
|
8
|
+
const suffix = Number(match[2])
|
|
9
|
+
if (suffix === 0 || size === 0) return "unsatisfiable"
|
|
10
|
+
return { start: Math.max(size - suffix, 0), end: size - 1 }
|
|
11
|
+
}
|
|
12
|
+
const start = Number(match[1])
|
|
13
|
+
const end = match[2] === "" ? size - 1 : Number(match[2])
|
|
14
|
+
if (start > end || start >= size) return "unsatisfiable"
|
|
15
|
+
return { start, end: Math.min(end, size - 1) }
|
|
16
|
+
}
|