@zyro-sec/server 1.0.1 → 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 +11 -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,47 +1,47 @@
1
- import { Plugin, Worktree } from "@zyro-sec/plugin"
2
-
3
- export default Plugin.define({
4
- id: "test.worktree",
5
- async setup(ctx) {
6
- const id = typeof ctx.options.strategy === "string" ? ctx.options.strategy : "test-copy"
7
- await ctx.worktree.transform((editor) =>
8
- editor.add({
9
- id,
10
- async create(input, { signal }) {
11
- await git(
12
- input.sourceDirectory,
13
- ["worktree", "add", "--detach", "--", input.directory, input.branch ?? "HEAD"],
14
- signal,
15
- )
16
- await ctx.storage.set(`tree:${input.directory}`, input.sourceDirectory)
17
- return { directory: input.directory }
18
- },
19
- async remove(input, { signal }) {
20
- const source = await ctx.storage.get(`tree:${input.directory}`)
21
- if (typeof source !== "string") throw new Worktree.OperationError({ message: "Worktree source not found" })
22
- // Windows cannot remove the working directory of the Git process itself.
23
- await git(
24
- source,
25
- ["worktree", "remove", ...(input.force ? ["--force"] : []), input.directory],
26
- signal,
27
- !input.force,
28
- )
29
- await ctx.storage.remove(`tree:${input.directory}`)
30
- },
31
- async list(sourceDirectory, { signal }) {
32
- signal.throwIfAborted()
33
- const rows = await ctx.storage.scan({ prefix: "tree:" })
34
- return rows.entries
35
- .filter((row) => row.value === sourceDirectory)
36
- .map((row) => ({ directory: row.key.slice(5), type: "worktree" as const }))
37
- },
38
- }),
39
- )
40
- },
41
- })
42
-
43
- async function git(directory: string, args: string[], signal: AbortSignal, forceRequired = false) {
44
- const child = Bun.spawn(["git", "-C", directory, ...args], { stdout: "pipe", stderr: "pipe", signal })
45
- const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()])
46
- if (code !== 0) throw new Worktree.OperationError({ message: stderr, forceRequired })
47
- }
1
+ import { Plugin, Worktree } from "@zyro-sec/plugin"
2
+
3
+ export default Plugin.define({
4
+ id: "test.worktree",
5
+ async setup(ctx) {
6
+ const id = typeof ctx.options.strategy === "string" ? ctx.options.strategy : "test-copy"
7
+ await ctx.worktree.transform((editor) =>
8
+ editor.add({
9
+ id,
10
+ async create(input, { signal }) {
11
+ await git(
12
+ input.sourceDirectory,
13
+ ["worktree", "add", "--detach", "--", input.directory, input.branch ?? "HEAD"],
14
+ signal,
15
+ )
16
+ await ctx.storage.set(`tree:${input.directory}`, input.sourceDirectory)
17
+ return { directory: input.directory }
18
+ },
19
+ async remove(input, { signal }) {
20
+ const source = await ctx.storage.get(`tree:${input.directory}`)
21
+ if (typeof source !== "string") throw new Worktree.OperationError({ message: "Worktree source not found" })
22
+ // Windows cannot remove the working directory of the Git process itself.
23
+ await git(
24
+ source,
25
+ ["worktree", "remove", ...(input.force ? ["--force"] : []), input.directory],
26
+ signal,
27
+ !input.force,
28
+ )
29
+ await ctx.storage.remove(`tree:${input.directory}`)
30
+ },
31
+ async list(sourceDirectory, { signal }) {
32
+ signal.throwIfAborted()
33
+ const rows = await ctx.storage.scan({ prefix: "tree:" })
34
+ return rows.entries
35
+ .filter((row) => row.value === sourceDirectory)
36
+ .map((row) => ({ directory: row.key.slice(5), type: "worktree" as const }))
37
+ },
38
+ }),
39
+ )
40
+ },
41
+ })
42
+
43
+ async function git(directory: string, args: string[], signal: AbortSignal, forceRequired = false) {
44
+ const child = Bun.spawn(["git", "-C", directory, ...args], { stdout: "pipe", stderr: "pipe", signal })
45
+ const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()])
46
+ if (code !== 0) throw new Worktree.OperationError({ message: stderr, forceRequired })
47
+ }
@@ -1,15 +1,15 @@
1
- {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
- "extends": "./tsconfig.json",
4
- "compilerOptions": {
5
- "composite": false,
6
- "incremental": false,
7
- "rootDir": "src",
8
- "outDir": "dist",
9
- "noEmit": false,
10
- "declaration": true,
11
- "emitDeclarationOnly": true,
12
- "tsBuildInfoFile": null
13
- },
14
- "include": ["src"]
15
- }
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "./tsconfig.json",
4
+ "compilerOptions": {
5
+ "composite": false,
6
+ "incremental": false,
7
+ "rootDir": "src",
8
+ "outDir": "dist",
9
+ "noEmit": false,
10
+ "declaration": true,
11
+ "emitDeclarationOnly": true,
12
+ "tsBuildInfoFile": null
13
+ },
14
+ "include": ["src"]
15
+ }
package/tsconfig.json CHANGED
@@ -1,11 +1,11 @@
1
- {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
- "extends": "@tsconfig/bun/tsconfig.json",
4
- "compilerOptions": {
5
- "types": ["bun"],
6
- "noUnusedLocals": true,
7
- "lib": ["ESNext", "DOM", "DOM.Iterable"],
8
- "noUncheckedIndexedAccess": false
9
- },
10
- "references": [{ "path": "../core" }]
11
- }
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "@tsconfig/bun/tsconfig.json",
4
+ "compilerOptions": {
5
+ "types": ["bun"],
6
+ "noUnusedLocals": true,
7
+ "lib": ["ESNext", "DOM", "DOM.Iterable"],
8
+ "noUncheckedIndexedAccess": false
9
+ },
10
+ "references": [{ "path": "../core" }]
11
+ }
@@ -1,224 +0,0 @@
1
- import fs from "node:fs/promises"
2
- import path from "node:path"
3
- import { expect } from "bun:test"
4
- import { OpenCode } from "@zyro-sec/client"
5
- import { Effect } from "effect"
6
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
7
- import { it } from "../../core/test/lib/effect"
8
- import { serveRoutes } from "./fixture/routes"
9
-
10
- const client = (handler: (request: Request) => Promise<Response>) =>
11
- OpenCode.make({
12
- baseUrl: "http://opencode.local",
13
- fetch: Object.assign((input: string | URL | Request, init?: RequestInit) => handler(new Request(input, init)), {
14
- preconnect: fetch.preconnect,
15
- }),
16
- })
17
-
18
- it.live("manages local and plugin-backed artifacts through /api/experimental/artifacts when enabled", () =>
19
- Effect.gen(function* () {
20
- const dir = (yield* tmpdirScoped("opencode-artifact-api-")).path
21
- const global = path.join(dir, "global")
22
- const enabled = path.join(dir, "enabled")
23
- const enabledOther = path.join(dir, "enabled-other")
24
- const disabled = path.join(dir, "disabled")
25
- const pluginDir = path.join(dir, "custom-artifact-plugin")
26
-
27
- yield* Effect.promise(async () => {
28
- await Promise.all([global, enabled, enabledOther, disabled, pluginDir].map((item) => fs.mkdir(item, { recursive: true })))
29
- await fs.writeFile(
30
- path.join(pluginDir, "package.json"),
31
- JSON.stringify({ name: "custom-artifact-plugin", type: "module", exports: "./index.js" }),
32
- )
33
- await fs.writeFile(
34
- path.join(pluginDir, "index.js"),
35
- `
36
- const store = new Map()
37
- const decoder = new TextDecoder()
38
- const encoder = new TextEncoder()
39
- export default {
40
- id: "test-s3-artifacts",
41
- async setup(ctx) {
42
- await ctx.experimental.artifact.transform((editor) => {
43
- editor.add({
44
- id: "s3",
45
- name: "S3 Static",
46
- capabilities: ["static"],
47
- prompt: "Artifacts go to a static S3 bucket.",
48
- async create(input) {
49
- store.set(input.id, Object.fromEntries(Object.entries(input.files).map(([k, v]) => [k, decoder.decode(v)])))
50
- return { url: "https://artifacts.example.test/" + input.id + "/" }
51
- },
52
- async read(id) {
53
- const item = store.get(id) ?? {}
54
- return Object.fromEntries(Object.entries(item).map(([k, v]) => [k, encoder.encode(v)]))
55
- },
56
- async update(id, input) {
57
- store.set(id, Object.fromEntries(Object.entries(input.files).map(([k, v]) => [k, decoder.decode(v)])))
58
- return { url: "https://artifacts.example.test/" + id + "/" }
59
- },
60
- async delete(id) {
61
- store.delete(id)
62
- },
63
- })
64
- })
65
- },
66
- }
67
- `,
68
- )
69
- await fs.writeFile(
70
- path.join(enabled, "opencode.json"),
71
- JSON.stringify({
72
- plugins: [{ package: pluginDir }],
73
- experimental: { artifacts: true },
74
- }),
75
- )
76
- await fs.writeFile(
77
- path.join(enabledOther, "opencode.json"),
78
- JSON.stringify({
79
- experimental: { artifacts: true },
80
- }),
81
- )
82
- })
83
-
84
- const server = yield* serveRoutes({
85
- app: { version: "test" },
86
- database: { path: path.join(dir, "opencode.db") },
87
- config: { directory: global, project: true, claude: false },
88
- models: { fetch: false },
89
- fs: { filewatcher: false },
90
- })
91
- const handler = server.handler
92
- const api = client(handler)
93
- yield* server.pluginsLoaded(enabled)
94
-
95
- yield* Effect.promise(async () => {
96
- // Disabled location returns ForbiddenError
97
- await expect(
98
- api.experimental.artifacts.list({ location: { directory: disabled } }),
99
- ).rejects.toMatchObject({ _tag: "ForbiddenError" })
100
-
101
- // Providers list includes built-in local (default) and plugin-registered s3
102
- const providers = await api.experimental.artifacts.providers({ location: { directory: enabled } })
103
- expect(providers.data).toEqual([
104
- { id: "local", name: "Local", capabilities: ["static"], default: true },
105
- { id: "s3", name: "S3 Static", capabilities: ["static"], default: false },
106
- ])
107
-
108
- const session = await api.session.create({ location: { directory: enabled } })
109
-
110
- // Create local multi-file artifact linked to session
111
- const created = await api.experimental.artifacts.create({
112
- location: { directory: enabled },
113
- sessionID: session.id,
114
- title: "Wait stats",
115
- files: {
116
- "index.html": "<!doctype html><h1>v1</h1><script src='./assets/app.js'></script>",
117
- "assets/app.js": "window.VERSION = 1",
118
- },
119
- })
120
- expect(created.data).toMatchObject({
121
- provider: "local",
122
- sessionID: session.id,
123
- title: "Wait stats",
124
- entry: "index.html",
125
- url: `/api/experimental/artifacts/${encodeURIComponent(created.data.id)}/view/`,
126
- })
127
-
128
- // Redirects /view -> /view/ with 308 so relative "./assets/*" resolves
129
- const redirect = await handler(
130
- new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view`),
131
- )
132
- expect(redirect.status).toBe(308)
133
- expect(redirect.headers.get("location")).toBe(`/api/experimental/artifacts/${created.data.id}/view/`)
134
-
135
- // Serves entry HTML and relative JS in a sandboxed opaque origin without requiring location query
136
- const v1Html = await handler(
137
- new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view/`),
138
- )
139
- expect(v1Html.status).toBe(200)
140
- expect(v1Html.headers.get("content-type")).toContain("text/html")
141
- expect(v1Html.headers.get("content-security-policy")).toBe("sandbox allow-scripts")
142
- expect(await v1Html.text()).toContain("<h1>v1</h1>")
143
-
144
- // Sessionless SDK artifact also resolves its stored directory at /view/
145
- const sessionless = await api.experimental.artifacts.create({
146
- location: { directory: enabled },
147
- title: "Standalone report",
148
- files: { "index.html": "<h1>no-session</h1>" },
149
- })
150
- const sessionlessHtml = await handler(
151
- new Request(`http://opencode.local${sessionless.data.url}`),
152
- )
153
- expect(sessionlessHtml.status).toBe(200)
154
- expect(await sessionlessHtml.text()).toContain("<h1>no-session</h1>")
155
-
156
- // Another enabled project cannot list, read, update, or delete this project's artifacts
157
- const otherList = await api.experimental.artifacts.list({ location: { directory: enabledOther } })
158
- expect(otherList.data).toEqual([])
159
- await expect(
160
- api.experimental.artifacts.get({ artifactID: created.data.id, location: { directory: enabledOther } }),
161
- ).rejects.toMatchObject({ _tag: "ArtifactNotFoundError" })
162
- await expect(
163
- api.experimental.artifacts.delete({ artifactID: created.data.id, location: { directory: enabledOther } }),
164
- ).rejects.toMatchObject({ _tag: "ArtifactNotFoundError" })
165
-
166
- const v1Js = await handler(
167
- new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view/assets/app.js`),
168
- )
169
- expect(v1Js.status).toBe(200)
170
- expect(await v1Js.text()).toBe("window.VERSION = 1")
171
-
172
- // Update replaces files at the same ID and URL
173
- const updated = await api.experimental.artifacts.update({
174
- artifactID: created.data.id,
175
- files: {
176
- "index.html": "<!doctype html><h1>v2</h1>",
177
- },
178
- })
179
- expect(updated.data.url).toBe(created.data.url)
180
-
181
- const latestHtml = await handler(
182
- new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view/`),
183
- )
184
- expect(await latestHtml.text()).toContain("<h1>v2</h1>")
185
-
186
- // Per-request override to plugin-registered "s3" provider
187
- const remote = await api.experimental.artifacts.create({
188
- location: { directory: enabled },
189
- sessionID: session.id,
190
- provider: "s3",
191
- title: "Shared bundle",
192
- files: { "index.html": "<p>remote</p>" },
193
- })
194
- expect(remote.data).toMatchObject({
195
- provider: "s3",
196
- url: `https://artifacts.example.test/${remote.data.id}/`,
197
- })
198
-
199
- const fetchedRemote = await api.experimental.artifacts.get({
200
- artifactID: remote.data.id,
201
- location: { directory: enabled },
202
- })
203
- expect(fetchedRemote.data.files).toEqual({ "index.html": "<p>remote</p>" })
204
-
205
- const listedS3 = await api.experimental.artifacts.list({
206
- sessionID: session.id,
207
- provider: "s3",
208
- })
209
- expect(listedS3.data.map((item) => item.id)).toEqual([remote.data.id])
210
-
211
- // Delete removes record and returns 404 thereafter
212
- await api.experimental.artifacts.delete({ artifactID: created.data.id, location: { directory: enabled } })
213
- await expect(
214
- api.experimental.artifacts.get({ artifactID: created.data.id, location: { directory: enabled } }),
215
- ).rejects.toMatchObject({
216
- _tag: "ArtifactNotFoundError",
217
- })
218
- })
219
- }),
220
- // As the suite's first server boot, this test pays the process's cold load of the Location graph (built-in plugins,
221
- // the models catalog, lazily imported modules). sdk's first host boot shows that cost: 0.7-4s on Windows CI against
222
- // 0.25s on Linux. This test then boots three Locations and a local plugin.
223
- 30_000,
224
- )
package/test/auth.test.ts DELETED
@@ -1,24 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { ServerAuth } from "@zyro-sec/server/auth"
3
- import { Option, Redacted } from "effect"
4
-
5
- test("accepts only the fixed opencode username", () => {
6
- const config = { password: Option.some("secret"), username: "opencode" }
7
- expect(ServerAuth.authorized({ username: "opencode", password: Redacted.make("secret") }, config)).toBe(true)
8
- expect(ServerAuth.authorized({ username: "custom", password: Redacted.make("secret") }, config)).toBe(false)
9
- })
10
-
11
- test("session tokens expire, resist tampering, and are revoked by changing the password", () => {
12
- const config = { password: Option.some("secret"), username: "opencode" }
13
- const now = Date.now()
14
- const token = ServerAuth.issueSession(config, now)
15
- if (!token) throw new Error("Expected a session token")
16
- expect(ServerAuth.verifySession(token, config, now)).toBe(true)
17
- expect(ServerAuth.authorized({ username: "opencode", password: Redacted.make(token) }, config)).toBe(true)
18
- expect(ServerAuth.verifySession(token, config, now + ServerAuth.SESSION_TTL_SECONDS * 1000)).toBe(false)
19
- expect(ServerAuth.verifySession(`${token}x`, config, now)).toBe(false)
20
- const parts = token.split(".")
21
- expect(ServerAuth.verifySession(`${Number(parts[0]) + 1}.${parts[1]}`, config, now)).toBe(false)
22
- expect(ServerAuth.verifySession(token, { ...config, password: Option.some("rotated") }, now)).toBe(false)
23
- expect(ServerAuth.issueSession({ ...config, password: Option.none() })).toBeUndefined()
24
- })