GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): honor OPENCODE_SERVER_USERNAME for serve and --server (#… · anomalyco/opencode@0749024

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • cli
      • src
        • env.ts
        • server-process.ts
        • services
          • server-connection.ts
      • test
        • server-connection.test.ts
    • server
      • src
        • auth.ts
        • options.ts
        • process.ts
        • routes.ts
      • test
        • auth.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/cli/src/env.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/env.ts
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ export const password = Config.Redacted("OPENCODE_PASSWORD").pipe(
1212
Config.withDefault(undefined),
1313
)
1414

15+
// The Basic auth username paired with the password above, for the same
16+
// clients and servers.
17+
export const username = Config.String("OPENCODE_SERVER_USERNAME").pipe(Config.withDefault("opencode"))
18+
1519
export function session() {
1620
return Object.fromEntries(
1721
Object.entries(process.env).filter(
Collapse file

‎packages/cli/src/server-process.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/server-process.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
109109
port,
110110
cors: options.cors ?? config.cors,
111111
password,
112+
// Service and stdio clients authenticate with the default username, so only a manually run server adopts it.
113+
username: options.mode === "default" ? yield* Env.username : undefined,
112114
pty: { handoff },
113115
simulation: truthy(process.env.OPENCODE_SIMULATE),
114116
database: {
Collapse file

‎packages/cli/src/services/server-connection.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/services/server-connection.ts
+4-2Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ export const resolve = Effect.fn("cli.server-connection.resolve")(function* (arg
3131
const password = yield* Env.password
3232
const endpoint = {
3333
url: server,
34-
auth: password ? { type: "basic" as const, username: "opencode", password: Redacted.value(password) } : undefined,
34+
auth: password
35+
? { type: "basic" as const, username: yield* Env.username, password: Redacted.value(password) }
36+
: undefined,
3537
} satisfies Endpoint
3638
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
3739
const health = yield* Effect.tryPromise({
@@ -94,7 +96,7 @@ function connectError(endpoint: Endpoint, cause: unknown) {
9496
return new Error(
9597
endpoint.auth === undefined
9698
? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`
97-
: `Server at ${endpoint.url} rejected the password`,
99+
: `Server at ${endpoint.url} rejected the username or password`,
98100
{ cause },
99101
)
100102
}
Collapse file

‎packages/cli/test/server-connection.test.ts‎

Copy file name to clipboardExpand all lines: packages/cli/test/server-connection.test.ts
+29-1Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { NodeFileSystem, NodeServices } from "@effect/platform-node"
22
import { Global } from "@opencode/util/global"
33
import { OPENCODE_VERSION } from "../src/version"
44
import { expect, test } from "bun:test"
5-
import { Console, Effect, FileSystem, Option, Scope } from "effect"
5+
import { ConfigProvider, Console, Effect, FileSystem, Option, Scope } from "effect"
66
import { Command } from "effect/cli"
77
import fs from "node:fs/promises"
88
import os from "node:os"
@@ -60,6 +60,34 @@ test("resolution groups Effect-native lifecycle operations only for the managed
6060
}
6161
})
6262

63+
test("--server authenticates with the configured username", async () => {
64+
const server = Bun.serve({
65+
port: 0,
66+
fetch(request) {
67+
if (request.headers.get("authorization") !== `Basic ${btoa("custom:secret")}`)
68+
return new Response(null, { status: 401 })
69+
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
70+
},
71+
})
72+
try {
73+
const resolved = await Effect.runPromise(
74+
ServerConnection.resolve({ server: server.url.toString() }).pipe(
75+
Effect.provide(
76+
ConfigProvider.layer(
77+
ConfigProvider.fromEnv({ env: { OPENCODE_PASSWORD: "secret", OPENCODE_SERVER_USERNAME: "custom" } }),
78+
),
79+
),
80+
Effect.provide(Global.layerWith({})),
81+
Effect.provide(NodeFileSystem.layer),
82+
Effect.scoped,
83+
),
84+
)
85+
expect(resolved.endpoint.auth).toEqual({ type: "basic", username: "custom", password: "secret" })
86+
} finally {
87+
await server.stop(true)
88+
}
89+
})
90+
6391
test("service options only require a matching version when requested", async () => {
6492
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-options-"))
6593
const layer = Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })
Collapse file

‎packages/server/src/auth.ts‎

Copy file name to clipboardExpand all lines: packages/server/src/auth.ts
+9-5Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ export type Info = {
1313
readonly username: string
1414
}
1515

16+
export const DEFAULT_USERNAME = "opencode"
17+
1618
export const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
1719

1820
export class Config extends Context.Service<Config, Info>()("@opencode/ServerAuthConfig") {
19-
static configLayer(input: Pick<Info, "password">) {
20-
return Layer.succeed(this, this.of({ ...input, username: "opencode" }))
21+
static configLayer(input: { readonly password: Option.Option<string>; readonly username?: string }) {
22+
return Layer.succeed(this, this.of({ password: input.password, username: input.username ?? DEFAULT_USERNAME }))
2123
}
2224

2325
static get layer() {
@@ -29,11 +31,13 @@ export function required(config: Info) {
2931
return Option.isSome(config.password) && config.password.value !== ""
3032
}
3133

32-
// Session tokens issued by pairing links are accepted anywhere the password is.
34+
// Session tokens issued by pairing links are accepted anywhere the password is. Clients holding a token do not know the
35+
// configured username, so tokens are checked without it.
3336
export function authorized(credentials: DecodedCredentials, config: Info) {
34-
if (Option.isNone(config.password) || credentials.username !== config.username) return false
37+
if (Option.isNone(config.password)) return false
3538
const password = Redacted.value(credentials.password)
36-
return password === config.password.value || verifySession(password, config)
39+
if (verifySession(password, config)) return true
40+
return credentials.username === config.username && password === config.password.value
3741
}
3842

3943
// Sessions are signed with a key derived from the server password, so rotating the password revokes every session.
Collapse file

‎packages/server/src/options.ts‎

Copy file name to clipboardExpand all lines: packages/server/src/options.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export const ServerOptions = Schema.Struct({
1414
hostname: Schema.optional(Schema.String),
1515
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(65_535))),
1616
password: Schema.optional(Schema.String),
17+
username: Schema.optional(Schema.String),
1718
cors: Schema.optional(Schema.Array(Schema.String)),
1819
simulation: Schema.optional(Schema.Boolean),
1920
database: Schema.optional(Database.Options),
Collapse file

‎packages/server/src/process.ts‎

Copy file name to clipboardExpand all lines: packages/server/src/process.ts
+6-3Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,11 @@ export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
6666
}
6767
const urls = () => [...localURLs(), ...(remoteURLs?.() ?? [])]
6868
const application = yield* Ref.make(Option.none<App>())
69-
const app = dispatch(password, status, application, options.app?.version ?? "unknown", urls, Global.Path.tmp)
69+
const auth = ServerAuth.Config.of({
70+
password: Option.some(password),
71+
username: options.username ?? ServerAuth.DEFAULT_USERNAME,
72+
})
73+
const app = dispatch(auth, status, application, options.app?.version ?? "unknown", urls, Global.Path.tmp)
7074
// Request fibers may continue inbound trace context, but must not inherit the server startup parent.
7175
yield* bound.http
7276
.serve(
@@ -172,14 +176,13 @@ function addressInUse(error: unknown) {
172176
}
173177

174178
function dispatch(
175-
password: string,
179+
auth: ServerAuth.Info,
176180
status: Status.Interface,
177181
application: Ref.Ref<Option.Option<App>>,
178182
version: string,
179183
urls: () => ReadonlyArray<string>,
180184
tmp: string,
181185
): App {
182-
const auth = ServerAuth.Config.of({ password: Option.some(password), username: "opencode" })
183186
return Effect.gen(function* () {
184187
const request = yield* HttpServerRequest.HttpServerRequest
185188
const url = new URL(request.url, "http://localhost")
Collapse file

‎packages/server/src/routes.ts‎

Copy file name to clipboardExpand all lines: packages/server/src/routes.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export function createRoutes(
8989
) {
9090
return makeRoutes(
9191
options.password
92-
? ServerAuth.Config.configLayer({ password: Option.some(options.password) })
92+
? ServerAuth.Config.configLayer({ password: Option.some(options.password), username: options.username })
9393
: ServerAuth.Config.layer,
9494
options,
9595
serviceURLs,
Collapse file

‎packages/server/test/auth.test.ts‎

Copy file name to clipboardExpand all lines: packages/server/test/auth.test.ts
+11-4Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,17 @@ import { expect, test } from "bun:test"
22
import { ServerAuth } from "@opencode/server/auth"
33
import { Option, Redacted } from "effect"
44

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)
5+
test("passwords require the configured username", () => {
6+
const config = { password: Option.some("secret"), username: "custom" }
7+
expect(ServerAuth.authorized({ username: "custom", password: Redacted.make("secret") }, config)).toBe(true)
8+
expect(ServerAuth.authorized({ username: "opencode", password: Redacted.make("secret") }, config)).toBe(false)
9+
})
10+
11+
test("session tokens are accepted with any username", () => {
12+
const config = { password: Option.some("secret"), username: "custom" }
13+
const token = ServerAuth.issueSession(config)
14+
if (!token) throw new Error("Expected a session token")
15+
expect(ServerAuth.authorized({ username: "opencode", password: Redacted.make(token) }, config)).toBe(true)
916
})
1017

1118
test("session tokens expire, resist tampering, and are revoked by changing the password", () => {

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.