@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
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package.json",
|
|
2
3
|
"name": "@zyro-sec/server",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
4
|
+
"version": "1.0.1",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/anomalyco/opencode.git",
|
|
10
|
+
"directory": "packages/server"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "bun run script/build.ts",
|
|
17
|
+
"pack": "bun run script/pack.ts",
|
|
18
|
+
"test": "bun test --only-failures",
|
|
19
|
+
"typecheck": "bun check --no-script -b",
|
|
20
|
+
"typecheck:tsc": "tsc -b",
|
|
21
|
+
"probe:workerd": "bun run script/workerd-probe.ts"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@effect/platform-node": "4.1.0",
|
|
25
|
+
"@effect/platform-node-shared": "4.1.0",
|
|
26
|
+
"@zyro-sec/core": "^1.0.1",
|
|
27
|
+
"@zyro-sec/protocol": "^1.0.1",
|
|
28
|
+
"@zyro-sec/schema": "^1.0.1",
|
|
29
|
+
"@zyro-sec/simulation": "^1.0.1",
|
|
30
|
+
"@zyro-sec/util": "^1.0.1",
|
|
31
|
+
"effect": "4.1.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@opencode/pty": "0.6.0",
|
|
35
|
+
"@zyro-sec/client": "^1.0.1",
|
|
36
|
+
"@zyro-sec/plugin": "^1.0.1",
|
|
37
|
+
"@tsconfig/bun": "1.0.9",
|
|
38
|
+
"@types/bun": "1.4.3",
|
|
39
|
+
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
40
|
+
"fast-check": "4.9.0"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/script/build.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import { $ } from "bun"
|
|
4
|
+
import { rm } from "node:fs/promises"
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { fileURLToPath } from "node:url"
|
|
7
|
+
|
|
8
|
+
process.chdir(fileURLToPath(new URL("..", import.meta.url)))
|
|
9
|
+
|
|
10
|
+
await rm("dist", { recursive: true, force: true })
|
|
11
|
+
await $`bun tsc -p tsconfig.build.json`
|
|
12
|
+
const root = path.resolve("src")
|
|
13
|
+
const result = await Bun.build({
|
|
14
|
+
entrypoints: await Array.fromAsync(new Bun.Glob("**/*.ts").scan({ cwd: root, absolute: true })).then((files) =>
|
|
15
|
+
files.filter((file) => !file.endsWith(".d.ts")),
|
|
16
|
+
),
|
|
17
|
+
root,
|
|
18
|
+
outdir: "dist",
|
|
19
|
+
target: "node",
|
|
20
|
+
format: "esm",
|
|
21
|
+
packages: "external",
|
|
22
|
+
splitting: true,
|
|
23
|
+
naming: {
|
|
24
|
+
entry: "[dir]/[name].[ext]",
|
|
25
|
+
chunk: "chunks/[name]-[hash].[ext]",
|
|
26
|
+
},
|
|
27
|
+
})
|
|
28
|
+
if (!result.success) throw new AggregateError(result.logs, "Failed to build Server")
|
package/script/pack.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Bundle probe for the workerd profile: verifies the full module graph behind
|
|
4
|
+
* src/workerd.ts resolves under the `workerd` condition without any `bun:`
|
|
5
|
+
* builtins. `node:` builtins stay external (workerd provides them through
|
|
6
|
+
* nodejs_compat); the probe prints the surviving externals so the A4 boot
|
|
7
|
+
* spike knows exactly what the runtime must supply.
|
|
8
|
+
*/
|
|
9
|
+
import path from "node:path"
|
|
10
|
+
import { mkdtempSync } from "node:fs"
|
|
11
|
+
import os from "node:os"
|
|
12
|
+
|
|
13
|
+
const outdir = mkdtempSync(path.join(os.tmpdir(), "opencode-workerd-probe-"))
|
|
14
|
+
const result = await Bun.build({
|
|
15
|
+
entrypoints: [path.join(import.meta.dir, "../src/workerd.ts")],
|
|
16
|
+
conditions: ["workerd"],
|
|
17
|
+
target: "node",
|
|
18
|
+
outdir,
|
|
19
|
+
sourcemap: "none",
|
|
20
|
+
throw: false,
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
if (!result.success) {
|
|
24
|
+
console.error(`workerd bundle probe FAILED (${result.logs.length} issues)`)
|
|
25
|
+
for (const log of result.logs) console.error(String(log))
|
|
26
|
+
process.exit(1)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Everything in the graph is bundled, so any import specifier that survives in
|
|
30
|
+
// the output is an external the runtime must provide. A specifier reached only
|
|
31
|
+
// through `import()` is loaded lazily behind a runtime guard, so it costs
|
|
32
|
+
// nothing on a runtime that never takes that branch; a static import is
|
|
33
|
+
// evaluated on module load and must resolve.
|
|
34
|
+
const transpiler = new Bun.Transpiler({ loader: "js" })
|
|
35
|
+
const externals = new Map<string, { static: boolean }>()
|
|
36
|
+
const record = (specifier: string, isStatic: boolean) => {
|
|
37
|
+
const seen = externals.get(specifier)
|
|
38
|
+
externals.set(specifier, { static: (seen?.static ?? false) || isStatic })
|
|
39
|
+
}
|
|
40
|
+
for (const artifact of result.outputs) {
|
|
41
|
+
const text = await artifact.text()
|
|
42
|
+
for (const imported of transpiler.scanImports(text)) record(imported.path, imported.kind !== "dynamic-import")
|
|
43
|
+
for (const match of text.matchAll(/\brequire\(\s*"([^"]+)"\s*\)/g)) record(match[1], true)
|
|
44
|
+
}
|
|
45
|
+
const sorted = Array.from(externals.keys()).toSorted()
|
|
46
|
+
const isBun = (specifier: string) => specifier === "bun" || specifier.startsWith("bun:")
|
|
47
|
+
const leaked = sorted.filter((specifier) => isBun(specifier) && externals.get(specifier)!.static)
|
|
48
|
+
const bytes = result.outputs.reduce((total, artifact) => total + artifact.size, 0)
|
|
49
|
+
|
|
50
|
+
console.log(`workerd bundle probe OK: ${result.outputs.length} artifacts, ${(bytes / 1024 / 1024).toFixed(1)} MiB`)
|
|
51
|
+
console.log(`external builtins (${sorted.length}):`)
|
|
52
|
+
for (const specifier of sorted) {
|
|
53
|
+
const lazy = externals.get(specifier)!.static ? "" : " (lazy)"
|
|
54
|
+
console.log(` ${specifier}${lazy}`)
|
|
55
|
+
}
|
|
56
|
+
if (leaked.length > 0) {
|
|
57
|
+
console.error(`FAILED: bun builtins statically imported in the workerd graph: ${leaked.join(", ")}`)
|
|
58
|
+
process.exit(1)
|
|
59
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { makeDefaultApi } from "@zyro-sec/protocol/api"
|
|
2
|
+
import { LocationMiddleware } from "./location"
|
|
3
|
+
import { FormLocationMiddleware } from "./middleware/form-location"
|
|
4
|
+
import { SessionLocationMiddleware } from "./middleware/session-location"
|
|
5
|
+
|
|
6
|
+
export const Api = makeDefaultApi({
|
|
7
|
+
locationMiddleware: LocationMiddleware,
|
|
8
|
+
// FormLocationMiddleware contains the temporary `sessionID === "global"` MCP elicitation hack.
|
|
9
|
+
// Do not use that sentinel with general session APIs.
|
|
10
|
+
formLocationMiddleware: FormLocationMiddleware,
|
|
11
|
+
sessionLocationMiddleware: SessionLocationMiddleware,
|
|
12
|
+
})
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export * as ServerAuth from "./auth"
|
|
2
|
+
|
|
3
|
+
import { Context, Layer, Option, Redacted } from "effect"
|
|
4
|
+
import { createHmac, timingSafeEqual } from "node:crypto"
|
|
5
|
+
|
|
6
|
+
export type DecodedCredentials = {
|
|
7
|
+
readonly username: string
|
|
8
|
+
readonly password: Redacted.Redacted
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type Info = {
|
|
12
|
+
readonly password: Option.Option<string>
|
|
13
|
+
readonly username: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
|
|
17
|
+
|
|
18
|
+
export class Config extends Context.Service<Config, Info>()("@zyro-sec/ServerAuthConfig") {
|
|
19
|
+
static configLayer(input: Pick<Info, "password">) {
|
|
20
|
+
return Layer.succeed(this, this.of({ ...input, username: "zyrosec" }))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
static get layer() {
|
|
24
|
+
return this.configLayer({ password: Option.none() })
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function required(config: Info) {
|
|
29
|
+
return Option.isSome(config.password) && config.password.value !== ""
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Session tokens issued by pairing links are accepted anywhere the password is.
|
|
33
|
+
export function authorized(credentials: DecodedCredentials, config: Info) {
|
|
34
|
+
if (
|
|
35
|
+
Option.isNone(config.password) ||
|
|
36
|
+
(credentials.username !== config.username && credentials.username !== "opencode")
|
|
37
|
+
)
|
|
38
|
+
return false
|
|
39
|
+
const password = Redacted.value(credentials.password)
|
|
40
|
+
return password === config.password.value || verifySession(password, config)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Sessions are signed with a key derived from the server password, so rotating the password revokes every session.
|
|
44
|
+
export function issueSession(config: Info, now = Date.now()) {
|
|
45
|
+
if (Option.isNone(config.password)) return
|
|
46
|
+
const expires = String(Math.floor(now / 1000) + SESSION_TTL_SECONDS)
|
|
47
|
+
return `${expires}.${sign(config.password.value, expires)}`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function verifySession(token: string, config: Info, now = Date.now()) {
|
|
51
|
+
if (Option.isNone(config.password)) return false
|
|
52
|
+
const parts = token.split(".")
|
|
53
|
+
if (parts.length !== 2) return false
|
|
54
|
+
const expires = Number(parts[0])
|
|
55
|
+
if (!Number.isSafeInteger(expires) || expires * 1000 <= now) return false
|
|
56
|
+
const expected = Buffer.from(sign(config.password.value, parts[0]))
|
|
57
|
+
const actual = Buffer.from(parts[1])
|
|
58
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Browsers share cookies across ports on the same host, so the name carries the port to keep local servers apart.
|
|
62
|
+
export function sessionCookieName(host: string | undefined) {
|
|
63
|
+
const port = URL.parse(`http://${host ?? ""}`)?.port
|
|
64
|
+
return port ? `opencode_session_${port}` : "opencode_session"
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function sign(password: string, payload: string) {
|
|
68
|
+
const key = createHmac("sha256", password).update("opencode-session-v1").digest()
|
|
69
|
+
return createHmac("sha256", key).update(payload).digest("base64url")
|
|
70
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export * as ContentHeaders from "./content-headers"
|
|
2
|
+
|
|
3
|
+
import path from "path"
|
|
4
|
+
|
|
5
|
+
// Media elements still load the bytes; a browser that opens the response as a page gets a sandboxed, inert document.
|
|
6
|
+
export const CONTENT_SECURITY_POLICY = "default-src 'none'; img-src 'self'; media-src 'self'; sandbox"
|
|
7
|
+
|
|
8
|
+
const TEXT_TYPE = "text/plain; charset=utf-8"
|
|
9
|
+
|
|
10
|
+
/** Headers for raw file bytes: always a download, never rendered as a page on the server's origin. */
|
|
11
|
+
export function download(input: { readonly path?: string; readonly mime: string }) {
|
|
12
|
+
return {
|
|
13
|
+
// Clients read documents, scripts and XML (including SVG) as bytes and pick their own type from the path.
|
|
14
|
+
"content-type": /^(text\/html|text\/javascript|application\/(x-)?javascript)\b|[/+]xml\b/i.test(input.mime)
|
|
15
|
+
? TEXT_TYPE
|
|
16
|
+
: input.mime,
|
|
17
|
+
"content-disposition": disposition(input.path === undefined ? "" : path.basename(input.path)),
|
|
18
|
+
"content-security-policy": CONTENT_SECURITY_POLICY,
|
|
19
|
+
"x-content-type-options": "nosniff",
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// RFC 6266: an ASCII filename for older clients plus the exact UTF-8 name in filename*.
|
|
24
|
+
export function disposition(name: string) {
|
|
25
|
+
if (name === "") return "attachment"
|
|
26
|
+
const fallback = name.replace(/[^\x20-\x7e]|["\\%]/g, "_")
|
|
27
|
+
const encoded = encodeURIComponent(name).replace(
|
|
28
|
+
/['()*]/g,
|
|
29
|
+
(char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
|
|
30
|
+
)
|
|
31
|
+
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`
|
|
32
|
+
}
|
package/src/cors.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Context } from "effect"
|
|
2
|
+
|
|
3
|
+
const opencodeOrigin = /^https:\/\/([a-z0-9-]+\.)*opencode\.ai$/
|
|
4
|
+
|
|
5
|
+
export type CorsOptions = { readonly cors?: ReadonlyArray<string> }
|
|
6
|
+
|
|
7
|
+
export const CorsConfig = Context.Reference<CorsOptions | undefined>("@zyro-sec/ServerCorsConfig", {
|
|
8
|
+
defaultValue: () => undefined,
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
export function isAllowedCorsOrigin(input: string | undefined, opts?: CorsOptions) {
|
|
12
|
+
if (!input) return true
|
|
13
|
+
if (input.startsWith("http://localhost:")) return true
|
|
14
|
+
if (input.startsWith("http://127.0.0.1:")) return true
|
|
15
|
+
if (input.startsWith("oc://renderer")) return true
|
|
16
|
+
if (input === "tauri://localhost" || input === "http://tauri.localhost" || input === "https://tauri.localhost")
|
|
17
|
+
return true
|
|
18
|
+
if (opencodeOrigin.test(input)) return true
|
|
19
|
+
return opts?.cors?.includes(input) ?? false
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isAllowedRequestOrigin(input: string | undefined, host: string | undefined, opts?: CorsOptions) {
|
|
23
|
+
if (!input) return true
|
|
24
|
+
if (host && sameHost(input, host)) return true
|
|
25
|
+
return isAllowedCorsOrigin(input, opts)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sameHost(origin: string, host: string) {
|
|
29
|
+
try {
|
|
30
|
+
return new URL(origin).host === host
|
|
31
|
+
} catch {
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export * as EventFeed from "./event-feed"
|
|
2
|
+
|
|
3
|
+
import { Bus } from "@zyro-sec/core/bus"
|
|
4
|
+
import { Event } from "@zyro-sec/schema/event"
|
|
5
|
+
import { isOpenCodeEvent, type OpenCodeEvent } from "@zyro-sec/protocol/groups/event"
|
|
6
|
+
import { Cause, Context, Effect, Layer, Queue, Schema, Scope, Stream } from "effect"
|
|
7
|
+
|
|
8
|
+
export const SubscriberCapacity = 4_096
|
|
9
|
+
|
|
10
|
+
export class SubscriberOverflowError extends Schema.TaggedError<SubscriberOverflowError>()(
|
|
11
|
+
"EventFeed.SubscriberOverflow",
|
|
12
|
+
{ capacity: Schema.Int },
|
|
13
|
+
) {}
|
|
14
|
+
|
|
15
|
+
export class EncodingError extends Schema.TaggedError<EncodingError>()("EventFeed.EncodingError", {
|
|
16
|
+
eventID: Event.ID,
|
|
17
|
+
eventType: Schema.String,
|
|
18
|
+
cause: Schema.Defect(),
|
|
19
|
+
}) {}
|
|
20
|
+
|
|
21
|
+
export type Error = SubscriberOverflowError | EncodingError
|
|
22
|
+
|
|
23
|
+
export interface Interface {
|
|
24
|
+
readonly subscribe: (types?: ReadonlyArray<string>) => Effect.Effect<Stream.Stream<string, Error>, never, Scope.Scope>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class Service extends Context.Service<Service, Interface>()("@zyro-sec/server/EventFeed") {}
|
|
28
|
+
|
|
29
|
+
export function frame(event: OpenCodeEvent) {
|
|
30
|
+
return `data: ${JSON.stringify(event)}\n\n`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const make = Effect.fn("EventFeed.make")(function* (
|
|
34
|
+
observe: (subscriber: Bus.Subscriber) => Effect.Effect<Bus.Unsubscribe>,
|
|
35
|
+
options?: { readonly capacity?: number; readonly encode?: (event: OpenCodeEvent) => string },
|
|
36
|
+
) {
|
|
37
|
+
const capacity = options?.capacity ?? SubscriberCapacity
|
|
38
|
+
const render = options?.encode ?? frame
|
|
39
|
+
const subscribers = new Map<Queue.Queue<string, Error>, ReadonlySet<string> | undefined>()
|
|
40
|
+
|
|
41
|
+
const fail = (error: Error) =>
|
|
42
|
+
Effect.sync(() => {
|
|
43
|
+
const current = Array.from(subscribers.keys())
|
|
44
|
+
subscribers.clear()
|
|
45
|
+
for (const subscriber of current) Queue.failCauseUnsafe(subscriber, Cause.fail(error))
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const publish = Effect.fnUntraced(function* (event: Event.Payload) {
|
|
49
|
+
if (!isOpenCodeEvent(event)) return
|
|
50
|
+
let encoded: string | undefined
|
|
51
|
+
for (const [subscriber, types] of subscribers) {
|
|
52
|
+
if (types && !types.has(event.type)) continue
|
|
53
|
+
encoded ??= yield* Effect.try({
|
|
54
|
+
try: () => render(event),
|
|
55
|
+
catch: (cause) => new EncodingError({ eventID: event.id, eventType: event.type, cause }),
|
|
56
|
+
}).pipe(
|
|
57
|
+
Effect.catch((error) =>
|
|
58
|
+
Effect.logError("Failed to encode public event", {
|
|
59
|
+
eventID: error.eventID,
|
|
60
|
+
eventType: error.eventType,
|
|
61
|
+
cause: error.cause,
|
|
62
|
+
}).pipe(Effect.andThen(fail(error)), Effect.as(undefined)),
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
if (encoded === undefined) return
|
|
66
|
+
if (Queue.offerUnsafe(subscriber, encoded)) continue
|
|
67
|
+
subscribers.delete(subscriber)
|
|
68
|
+
Queue.failCauseUnsafe(subscriber, Cause.fail(new SubscriberOverflowError({ capacity })))
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
const unsubscribe = yield* observe(publish)
|
|
73
|
+
yield* Effect.addFinalizer(() => unsubscribe)
|
|
74
|
+
|
|
75
|
+
return Service.of({
|
|
76
|
+
subscribe: (types) =>
|
|
77
|
+
Effect.acquireRelease(
|
|
78
|
+
Queue.dropping<string, Error>(capacity).pipe(
|
|
79
|
+
Effect.tap((queue) => Effect.sync(() => subscribers.set(queue, types?.length ? new Set(types) : undefined))),
|
|
80
|
+
),
|
|
81
|
+
(queue) =>
|
|
82
|
+
Effect.sync(() => subscribers.delete(queue)).pipe(Effect.andThen(Queue.shutdown(queue)), Effect.asVoid),
|
|
83
|
+
).pipe(Effect.map(Stream.fromQueue)),
|
|
84
|
+
})
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
export const layer = Layer.effect(
|
|
88
|
+
Service,
|
|
89
|
+
Effect.gen(function* () {
|
|
90
|
+
const bus = yield* Bus.Service
|
|
91
|
+
return yield* make(bus.listen)
|
|
92
|
+
}),
|
|
93
|
+
)
|
package/src/fetch.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export * as ServerFetch from "./fetch"
|
|
2
|
+
|
|
3
|
+
import { Context, Effect, Layer } from "effect"
|
|
4
|
+
import { HttpEffect, HttpMiddleware, HttpRouter, HttpServer } from "effect/http"
|
|
5
|
+
import { SessionRestart } from "@zyro-sec/core/session/execution/restart"
|
|
6
|
+
import type { LayerNode } from "@zyro-sec/util/effect/layer-node"
|
|
7
|
+
import { isAllowedCorsOrigin } from "./cors"
|
|
8
|
+
import { RequestSite } from "./request-site"
|
|
9
|
+
import { withoutParentSpan } from "./request-tracing"
|
|
10
|
+
import { createRoutes } from "./routes"
|
|
11
|
+
import type { ServerOptions } from "./options"
|
|
12
|
+
|
|
13
|
+
export interface BootOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Runtime-profile service replacements, applied after the standard set so later entries
|
|
16
|
+
* win — swaps services the standard graph assumes are local. See `ServerWorkerd.replacements`.
|
|
17
|
+
*/
|
|
18
|
+
readonly overrides?: LayerNode.Replacements
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Internal entry for runtime profiles (such as `ServerWorkerd.create`) that also need the built service context. */
|
|
22
|
+
export const makeWithContext = Effect.fn("ServerFetch.makeWithContext")(function* (
|
|
23
|
+
options: ServerOptions = {},
|
|
24
|
+
boot: BootOptions = {},
|
|
25
|
+
) {
|
|
26
|
+
// Handlers capture the build context; without the caller's span, each request is its own trace.
|
|
27
|
+
const context = yield* Layer.build(
|
|
28
|
+
createRoutes(options, () => [], boot.overrides ?? []).pipe(Layer.provide(HttpServer.layerServices)),
|
|
29
|
+
).pipe(withoutParentSpan)
|
|
30
|
+
// Forked so the returned handler is never delayed; resumed drains are already
|
|
31
|
+
// logged and durably recorded by the execution layer.
|
|
32
|
+
yield* Effect.forkDetach(Context.get(context, SessionRestart.Service).resumeSuspendedSessions)
|
|
33
|
+
const handler = Context.get(context, HttpRouter.HttpRouter)
|
|
34
|
+
.asHttpEffect()
|
|
35
|
+
.pipe(
|
|
36
|
+
RequestSite.middleware(options),
|
|
37
|
+
HttpMiddleware.cors({ allowedOrigins: (origin) => isAllowedCorsOrigin(origin, options), maxAge: 86_400 }),
|
|
38
|
+
HttpEffect.toWebHandlerWith(context),
|
|
39
|
+
)
|
|
40
|
+
return { handler, context }
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Builds a web-standard fetch handler — `(request: Request) => Promise<Response>` — serving the
|
|
45
|
+
* same HttpApi routes as the Node server process without binding a port, owning a listener, or
|
|
46
|
+
* installing signal handlers. This is the entry for runtimes that hand requests to the embedder
|
|
47
|
+
* instead of letting it listen: workerd (Workers and Durable Objects), Deno.serve, Bun.serve, or
|
|
48
|
+
* a test harness.
|
|
49
|
+
*
|
|
50
|
+
* The application layer builds EAGERLY, inside the caller's `Scope`, before the handler is
|
|
51
|
+
* returned. Do not convert this to a lazy first-request build: on workerd, a first request that
|
|
52
|
+
* aborts mid-build interrupts the layer construction and wedges every subsequent request
|
|
53
|
+
* (Effect-TS/effect#6319 class). The embedder owns the lifecycle — closing the scope releases
|
|
54
|
+
* the application layer.
|
|
55
|
+
*
|
|
56
|
+
* Auth follows `createRoutes` semantics: `options.password` enforces Basic auth; omitting it
|
|
57
|
+
* serves unauthenticated, so an embedder without a password must front the handler with its own
|
|
58
|
+
* access control.
|
|
59
|
+
*
|
|
60
|
+
* Sessions whose execution claim was never released resume once the layer is built, exactly as
|
|
61
|
+
* the Node server process does: a runtime that dies without teardown — an evicted Durable
|
|
62
|
+
* Object leaves the same durable signature as a killed process — replays orphaned turns on the
|
|
63
|
+
* next boot, and the sweep is a no-op when nothing is suspended.
|
|
64
|
+
*/
|
|
65
|
+
export const make = Effect.fn("ServerFetch.make")(function* (options: ServerOptions = {}, boot: BootOptions = {}) {
|
|
66
|
+
return (yield* makeWithContext(options, boot)).handler
|
|
67
|
+
})
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Agent } from "@zyro-sec/core/agent"
|
|
2
|
+
import { Effect } from "effect"
|
|
3
|
+
import { HttpApiBuilder } from "effect/http-api"
|
|
4
|
+
import { Api } from "../api"
|
|
5
|
+
import { response } from "../location"
|
|
6
|
+
import { AgentNotFoundError } from "@zyro-sec/protocol/errors"
|
|
7
|
+
|
|
8
|
+
export const AgentHandler = HttpApiBuilder.group(Api, "server.agent", (handlers) =>
|
|
9
|
+
handlers
|
|
10
|
+
.handle("agent.list", () => response(Agent.Service.use((agent) => agent.list())))
|
|
11
|
+
.handle(
|
|
12
|
+
"agent.get",
|
|
13
|
+
Effect.fn(function* (ctx) {
|
|
14
|
+
const agent = yield* Agent.Service.use((service) => service.get(ctx.params.agentID))
|
|
15
|
+
if (!agent)
|
|
16
|
+
return yield* new AgentNotFoundError({
|
|
17
|
+
agentID: ctx.params.agentID,
|
|
18
|
+
message: `Agent not found: ${ctx.params.agentID}`,
|
|
19
|
+
})
|
|
20
|
+
return yield* response(Effect.succeed(agent))
|
|
21
|
+
}),
|
|
22
|
+
),
|
|
23
|
+
)
|