@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
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@zyro-sec/server",
4
- "version": "1.0.1",
4
+ "version": "1.0.3",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -12,6 +12,9 @@
12
12
  "publishConfig": {
13
13
  "access": "public"
14
14
  },
15
+ "exports": {
16
+ "./*": "./src/*.ts"
17
+ },
15
18
  "scripts": {
16
19
  "build": "bun run script/build.ts",
17
20
  "pack": "bun run script/pack.ts",
@@ -23,17 +26,17 @@
23
26
  "dependencies": {
24
27
  "@effect/platform-node": "4.1.0",
25
28
  "@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",
29
+ "@zyro-sec/core": "^1.0.3",
30
+ "@zyro-sec/protocol": "^1.0.3",
31
+ "@zyro-sec/schema": "^1.0.3",
32
+ "@zyro-sec/simulation": "^1.0.3",
33
+ "@zyro-sec/util": "^1.0.3",
31
34
  "effect": "4.1.0"
32
35
  },
33
36
  "devDependencies": {
34
37
  "@opencode/pty": "0.6.0",
35
- "@zyro-sec/client": "^1.0.1",
36
- "@zyro-sec/plugin": "^1.0.1",
38
+ "@zyro-sec/client": "^1.0.3",
39
+ "@zyro-sec/plugin": "^1.0.3",
37
40
  "@tsconfig/bun": "1.0.9",
38
41
  "@types/bun": "1.4.3",
39
42
  "@typescript/native": "npm:typescript@7.1.0-beta",
package/script/build.ts CHANGED
@@ -1,28 +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")
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 CHANGED
@@ -1,5 +1,5 @@
1
- #!/usr/bin/env bun
2
- import path from "node:path"
3
- import { pack } from "@zyro-sec/script/pack"
4
-
5
- await pack(path.resolve(import.meta.dir, ".."))
1
+ #!/usr/bin/env bun
2
+ import path from "node:path"
3
+ import { pack } from "@zyro-sec/script/pack"
4
+
5
+ await pack(path.resolve(import.meta.dir, ".."))
@@ -1,59 +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
- }
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 CHANGED
@@ -1,12 +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
- })
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 CHANGED
@@ -1,70 +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
- }
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
+ }
@@ -1,32 +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
- }
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 CHANGED
@@ -1,34 +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
- }
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
+ }