Skip to content

Commit 19fb891

Browse files
authored
fix(cli): serve remote access on a random unguessable subdomain (#53962)
1 parent a67cf4c commit 19fb891

6 files changed

Lines changed: 115 additions & 37 deletions

File tree

‎packages/cli/src/commands/handlers/pair.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export default Runtime.handler(
1919
if (input.remote && Option.isSome(input.url))
2020
return yield* Effect.fail(new Error("--remote cannot be combined with --url"))
2121
// Changing the setting restarts the service, and the ensure below starts it again with the tunnel.
22-
if (input.remote && config.remote !== true) yield* ServiceConfig.set("remote", "true")
22+
if (input.remote && config.remote === undefined) yield* ServiceConfig.set("remote", "true")
2323
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
2424
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
2525
const urls = yield* pairingURLs(client, input)
@@ -77,7 +77,8 @@ const pairingURLs = Effect.fnUntraced(function* (
7777
// The service attaches the tunnel in the background, so wait for its URL to appear in server info.
7878
const remoteURL = Effect.fnUntraced(function* (client: ReturnType<typeof OpenCode.make>) {
7979
const tunnelURL = Effect.gen(function* () {
80-
const hostname = yield* RemoteTunnel.hostname()
80+
const route = (yield* ServiceConfig.read()).remote?.route
81+
const hostname = route === undefined ? undefined : yield* RemoteTunnel.hostname(route)
8182
const info = yield* Effect.tryPromise(() => client.server.info())
8283
const url = info.urls.find((candidate) => hostname !== undefined && new URL(candidate).hostname === hostname)
8384
if (url === undefined) return yield* Effect.fail(new Error("Remote tunnel is not ready"))

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,12 +173,13 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
173173
}),
174174
)
175175
if (server === undefined) return
176-
if (serviceOptions !== undefined && config.remote === true && server.address._tag === "TcpAddress") {
176+
if (serviceOptions !== undefined && config.remote !== undefined && server.address._tag === "TcpAddress") {
177177
const bound = server.address.hostname
178178
// A wildcard bind also listens on loopback, which is all the tunnel needs to reach.
179179
const host = bound === "0.0.0.0" || bound === "::" ? "127.0.0.1" : bound.includes(":") ? `[${bound}]` : bound
180180
yield* Effect.forkScoped(
181181
RemoteTunnel.run({
182+
route: config.remote.route,
182183
target: `${host}:${server.address.port}`,
183184
onURL: (url) => {
184185
remote.urls = url === undefined ? [] : [url]

‎packages/cli/src/services/remote-tunnel.ts‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,16 @@ export * as RemoteTunnel from "./remote-tunnel"
33
import type { OpenTunnelError } from "@opentunnel/client/effect"
44
import { Cause, Effect, Schedule } from "effect"
55
import { EOL } from "os"
6-
import { OPENCODE_CHANNEL } from "../version"
76

87
// OpenTunnel keeps one tunnel per device in its default profile, shared by the opentunnel CLI and every app
9-
// using the SDK; each claims its own routes. The service claims a subdomain rather than the tunnel hostname,
10-
// which the CLI may route, and each channel's service gets its own subdomain.
11-
export function route(channel = OPENCODE_CHANNEL) {
12-
if (channel === "latest") return "opencode"
13-
return `opencode-${channel.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`.slice(0, 63).replace(/-+$/, "")
14-
}
8+
// using the SDK; each claims its own routes. The service claims a subdomain (its route) rather than the tunnel
9+
// hostname, which the CLI may route. Tunnel hostnames appear in public certificate logs but the certificate
10+
// covers subdomains with a wildcard, so a random route keeps the service's address unguessable.
1511

1612
// Holds the route for the life of the service. The SDK reconnects through network failures itself, so only
1713
// setup failures reach the retry here; a rejected token or failed certificate stops it for good.
1814
export const run = Effect.fnUntraced(function* (input: {
15+
readonly route: string
1916
readonly target: string
2017
readonly onURL: (url: string | undefined) => void
2118
}) {
@@ -25,8 +22,8 @@ export const run = Effect.fnUntraced(function* (input: {
2522
(error.cause instanceof OpenTunnelAttachError || error.message.startsWith("Certificate issuance failed"))
2623
yield* Effect.gen(function* () {
2724
const client = yield* OpenTunnelClient
28-
const connection = yield* client.tunnel.connect({ routes: { [route()]: input.target } })
29-
input.onURL(`https://${route()}.${connection.tunnel.hostname}`)
25+
const connection = yield* client.tunnel.connect({ routes: { [input.route]: input.target } })
26+
input.onURL(`https://${input.route}.${connection.tunnel.hostname}`)
3027
yield* connection.closed
3128
}).pipe(
3229
Effect.scoped,
@@ -55,7 +52,7 @@ export const ensure = Effect.fnUntraced(function* () {
5552
const client = yield* OpenTunnelClient
5653
if ((yield* client.tunnel.get()) === undefined)
5754
process.stderr.write("Setting up remote access; this can take a minute..." + EOL)
58-
return `${route()}.${(yield* client.tunnel.ensure()).hostname}`
55+
return (yield* client.tunnel.ensure()).hostname
5956
}).pipe(
6057
Effect.provide(OpenTunnelClient.layer()),
6158
Effect.timeoutOrElse({
@@ -66,8 +63,8 @@ export const ensure = Effect.fnUntraced(function* () {
6663
})
6764

6865
// The tunnel hostname is persisted once the certificate is ready, so this is undefined until then.
69-
export const hostname = Effect.fnUntraced(function* () {
66+
export const hostname = Effect.fnUntraced(function* (route: string) {
7067
const { OpenTunnelStorage } = yield* Effect.promise(() => import("@opentunnel/client/effect"))
7168
const identity = yield* OpenTunnelStorage.xdg().load("default")
72-
return identity === undefined ? undefined : `${route()}.${identity.hostname}`
69+
return identity === undefined ? undefined : `${route}.${identity.hostname}`
7370
})

‎packages/cli/src/services/service-config.ts‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import { RemoteTunnel } from "./remote-tunnel"
1414

1515
export const Info = Schema.Struct({
1616
disabled: Schema.optional(Schema.Boolean),
17-
remote: Schema.optional(Schema.Boolean),
17+
// Present when remote access is on. The route is generated, never user-set: the secret subdomain the service is
18+
// served on.
19+
remote: Schema.optional(Schema.Struct({ route: Schema.String })),
1820
hostname: Schema.optional(Schema.String),
1921
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),
2022
password: Schema.optional(Schema.String),
@@ -27,6 +29,10 @@ const keys = ["disabled", "remote", "hostname", "port", "password", "cors", "env
2729
type Key = (typeof keys)[number]
2830

2931
const decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))
32+
// Earlier builds stored remote access as a boolean.
33+
const decodeLegacy = Schema.decodeUnknownOption(
34+
Schema.fromJsonString(Schema.Struct({ ...Info.fields, remote: Schema.Boolean })),
35+
)
3036
const decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))
3137

3238
export function filename(channel = OPENCODE_CHANNEL) {
@@ -130,12 +136,24 @@ export const options = Effect.fnUntraced(function* (input: { readonly checkVersi
130136
export const read = Effect.fn("cli.service-config.read")(function* () {
131137
const { fs, configFile, legacyConfigFile } = yield* paths
132138
if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile)
133-
return yield* fs.readFileString(configFile).pipe(
134-
Effect.flatMap(decodeInfo),
135-
Effect.orElseSucceed(() => ({}) as Info),
136-
)
139+
const text = yield* fs.readFileString(configFile).pipe(Effect.option)
140+
if (Option.isNone(text)) return {} as Info
141+
const info = yield* decodeInfo(text.value).pipe(Effect.option)
142+
if (Option.isSome(info)) return info.value
143+
const legacy = decodeLegacy(text.value)
144+
if (Option.isNone(legacy)) return {} as Info
145+
// Repair the file in place so every reader sees the same route.
146+
const { remote: enabled, ...rest } = legacy.value
147+
const repaired: Info = enabled ? { ...rest, remote: { route: route() } } : rest
148+
yield* write(repaired)
149+
return repaired
137150
})
138151

152+
// 64 random bits as 16 hex characters, a valid DNS label.
153+
function route() {
154+
return randomBytes(8).toString("hex")
155+
}
156+
139157
const write = Effect.fn("cli.service-config.write")(function* (value: Info) {
140158
const { fs, configFile } = yield* paths
141159
const temp = configFile + ".tmp"
@@ -155,10 +173,20 @@ export const password = Effect.fn("cli.service-config.password")(function* (valu
155173
return next
156174
})
157175

176+
// Turns remote access on and returns its route, created once and kept so the remote URL survives restarts.
177+
export const remote = Effect.fn("cli.service-config.remote")(function* () {
178+
const existing = yield* read()
179+
if (existing.remote) return existing.remote.route
180+
const next = route()
181+
yield* write({ ...existing, remote: { route: next } })
182+
return next
183+
})
184+
158185
export const get = Effect.fn("cli.service-config.get")(function* (key?: string, name?: string) {
159186
if (key === undefined) {
160187
const { password: _password, ...safe } = yield* read()
161-
return JSON.stringify(safe, null, 2)
188+
// The route is as sensitive as the password: it is the unguessable half of the remote address.
189+
return JSON.stringify(safe.remote === undefined ? safe : { ...safe, remote: {} }, null, 2)
162190
}
163191
const selected = configKey(key)
164192
if (selected !== "env" && name !== undefined) throw new Error(`Usage: opencode service get ${selected}`)
@@ -167,7 +195,7 @@ export const get = Effect.fn("cli.service-config.get")(function* (key?: string,
167195
return String((yield* read()).disabled ?? false)
168196
}
169197
case "remote": {
170-
return String((yield* read()).remote ?? false)
198+
return String((yield* read()).remote !== undefined)
171199
}
172200
case "hostname": {
173201
return (yield* read()).hostname ?? ""
@@ -206,7 +234,13 @@ export const set = Effect.fn("cli.service-config.set")(function* (key: string, v
206234
// A tunnel that cannot be created leaves remote access off instead of a service that keeps retrying.
207235
if (value === "true") yield* RemoteTunnel.ensure()
208236
yield* Service.stop(yield* options())
209-
yield* write({ ...(yield* read()), remote: value === "true" })
237+
if (value === "true") {
238+
yield* remote()
239+
return
240+
}
241+
// Disabling forgets the address, so enabling again issues a new unguessable one.
242+
const { remote: _remote, ...next } = yield* read()
243+
yield* write(next)
210244
return
211245
}
212246
case "hostname": {

‎packages/cli/test/remote-tunnel.test.ts‎

Lines changed: 0 additions & 13 deletions
This file was deleted.

‎packages/cli/test/service.test.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { NodeFileSystem } from "@effect/platform-node"
2+
import { validateRoutes } from "@opentunnel/client/effect"
23
import { Service, type Info } from "@opencode/client/effect/service"
34
import { Global } from "@opencode/util/global"
45
import { OPENCODE_VERSION } from "../src/version"
@@ -54,15 +55,72 @@ test("service remote accepts only booleans and persists across set and unset", a
5455
await expect(run(ServiceConfig.set("remote", "on"))).rejects.toThrow("Remote must be true or false")
5556
expect(await run(ServiceConfig.read())).toEqual({})
5657
await run(ServiceConfig.set("remote", "false"))
57-
expect(await run(ServiceConfig.read())).toEqual({ remote: false })
58+
expect(await run(ServiceConfig.read())).toEqual({})
59+
expect(await run(ServiceConfig.get("remote"))).toBe("false")
60+
await run(ServiceConfig.unset("remote"))
61+
expect(await run(ServiceConfig.read())).toEqual({})
62+
} finally {
63+
await fs.rm(root, { recursive: true, force: true })
64+
}
65+
})
66+
67+
test("remote access route is random, stable once created, hidden, and forgotten when remote is turned off", async () => {
68+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-remote-route-"))
69+
const layer = Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })
70+
const run = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem>) =>
71+
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer)))
72+
try {
73+
const route = await run(ServiceConfig.remote())
74+
// The SDK rejects invalid route names, which would keep the service from ever attaching.
75+
expect(() => validateRoutes({ [route]: "127.0.0.1:4096" })).not.toThrow()
76+
expect(route).toMatch(/^[0-9a-f]{16}$/)
77+
expect(await run(ServiceConfig.read())).toEqual({ remote: { route } })
78+
expect(await run(ServiceConfig.remote())).toBe(route)
79+
expect(await run(ServiceConfig.get("remote"))).toBe("true")
80+
expect(await run(ServiceConfig.get())).not.toContain(route)
81+
82+
await run(ServiceConfig.set("remote", "false"))
83+
expect(await run(ServiceConfig.read())).toEqual({})
5884
expect(await run(ServiceConfig.get("remote"))).toBe("false")
85+
expect(await run(ServiceConfig.remote())).not.toBe(route)
86+
5987
await run(ServiceConfig.unset("remote"))
6088
expect(await run(ServiceConfig.read())).toEqual({})
6189
} finally {
6290
await fs.rm(root, { recursive: true, force: true })
6391
}
6492
})
6593

94+
test("reading a config with remote access stored as a boolean repairs it in place and keeps other settings", async () => {
95+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-remote-legacy-"))
96+
const layer = Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })
97+
const run = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem>) =>
98+
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer)))
99+
const file = path.join(root, "config", ServiceConfig.filename())
100+
try {
101+
await fs.mkdir(path.dirname(file), { recursive: true })
102+
103+
await Bun.write(file, JSON.stringify({ remote: true, password: "kept", env: { A: "1" } }))
104+
const enabled = await run(ServiceConfig.read())
105+
const route = enabled.remote?.route ?? ""
106+
expect(route).toMatch(/^[0-9a-f]{16}$/)
107+
expect(enabled).toEqual({ remote: { route }, password: "kept", env: { A: "1" } })
108+
expect(await Bun.file(file).json()).toEqual(enabled)
109+
expect(await run(ServiceConfig.read())).toEqual(enabled)
110+
111+
await Bun.write(file, JSON.stringify({ remote: false, password: "kept" }))
112+
expect(await run(ServiceConfig.read())).toEqual({ password: "kept" })
113+
expect(await Bun.file(file).json()).toEqual({ password: "kept" })
114+
115+
const current = JSON.stringify({ remote: { route: "0123456789abcdef" }, password: "kept" })
116+
await Bun.write(file, current)
117+
expect(await run(ServiceConfig.read())).toEqual({ remote: { route: "0123456789abcdef" }, password: "kept" })
118+
expect(await Bun.file(file).text()).toBe(current)
119+
} finally {
120+
await fs.rm(root, { recursive: true, force: true })
121+
}
122+
})
123+
66124
test("local channel stores service config with the local service filename", async () => {
67125
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-"))
68126
try {

0 commit comments

Comments
 (0)