Skip to content

Commit eccf0b3

Browse files
authored
feat(server): pair with one-time connect links (anomalyco#50970)
1 parent 808588e commit eccf0b3

25 files changed

Lines changed: 439 additions & 66 deletions

File tree

‎packages/app/src/runtime/i18n/en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,7 @@ export const dict = {
496496
"server.connect.scan": "Scan QR code",
497497
"server.connect.scan.description": "Point your camera at the QR code shown by opencode pair.",
498498
"server.connect.scan.invalid": "This is not an OpenCode pairing code. Scan the code shown by opencode pair.",
499+
"server.connect.link.expired": "This pairing link expired or was already used. Run opencode pair to get a new one.",
499500
"server.connect.camera": "Pairing camera",
500501
"server.connect.camera.starting": "Opening camera…",
501502
"server.connect.mixedContent":

‎packages/app/src/servers/connect/pairing.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, test } from "bun:test"
2-
import { decodePairingCode, decodePairingScan, decodePairingUrl, pairingUrl } from "./pairing"
2+
import { decodePairingCode, decodePairingScan, decodePairingUrl, pairingLink, pairingUrl } from "./pairing"
33

44
describe("pairing URL", () => {
55
test("pairs with the current origin using credentials without server URLs", () => {
@@ -93,3 +93,20 @@ describe("pairing scan", () => {
9393
expect(decodePairingScan("not a code")).toBeUndefined()
9494
})
9595
})
96+
97+
describe("pairing link", () => {
98+
test("reads the server address and code from opencode pair links", () => {
99+
expect(pairingLink(" http://192.168.1.2:49374/auth/connect/abc_DEF-123 ")).toEqual({
100+
url: "http://192.168.1.2:49374",
101+
code: "abc_DEF-123",
102+
})
103+
})
104+
105+
test("rejects other URLs", () => {
106+
expect(pairingLink("http://192.168.1.2:49374/auth/connect/")).toBeUndefined()
107+
expect(pairingLink("http://192.168.1.2:49374/auth/connect/abc/extra")).toBeUndefined()
108+
expect(pairingLink("http://192.168.1.2:49374/connect#abc")).toBeUndefined()
109+
expect(pairingLink("opencode-ios://auth/connect/abc")).toBeUndefined()
110+
expect(pairingLink("192.168.1.2:49374")).toBeUndefined()
111+
})
112+
})

‎packages/app/src/servers/connect/pairing.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Option, Schema } from "effect"
2+
import { OpenCode } from "@opencode/client/promise"
23
import { base64Encode } from "@opencode/util/encode"
34
import { normalizeServerUrl } from "@/runtime/server/registry"
45

@@ -59,3 +60,22 @@ export function decodePairingUrl(value: string, origin?: string) {
5960
)
6061
return decodePairingCode(new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))), origin)
6162
}
63+
64+
// Links printed by `opencode pair` carry a single-use code that the server exchanges for a session token.
65+
export function pairingLink(value: string) {
66+
const url = URL.parse(value.trim())
67+
if (!url || (url.protocol !== "http:" && url.protocol !== "https:")) return
68+
const code = /^\/auth\/connect\/([A-Za-z0-9_-]+)$/.exec(url.pathname)?.[1]
69+
const address = serverAddress(url.origin)
70+
if (!code || !address) return
71+
return { url: address, code }
72+
}
73+
74+
export function redeemPairingLink(link: { url: string; code: string }) {
75+
return OpenCode.make({ baseUrl: link.url })
76+
.server.connect({ code: link.code })
77+
.then(
78+
(session) => ({ urls: [link.url], password: session.token }),
79+
() => undefined,
80+
)
81+
}

‎packages/app/src/servers/connect/scanner.tsx‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { onCleanup, onMount, Show } from "solid-js"
33
import { createStore } from "solid-js/store"
44
import { Button } from "@opencode/ui/button"
55
import { useLanguage } from "@/runtime/i18n/language"
6-
import { decodePairingScan } from "./pairing"
6+
import { decodePairingScan, pairingLink, redeemPairingLink } from "./pairing"
77
import "./scanner.css"
88

99
export function PairingScanner(props: {
@@ -23,12 +23,21 @@ export function PairingScanner(props: {
2323
video,
2424
(result) => {
2525
const pairing = decodePairingScan(result.data)
26-
if (!pairing) {
26+
if (pairing) {
27+
scanner.stop()
28+
props.onScan(pairing)
29+
return
30+
}
31+
const link = pairingLink(result.data)
32+
if (!link) {
2733
setState("error", language.t("server.connect.scan.invalid"))
2834
return
2935
}
3036
scanner.stop()
31-
props.onScan(pairing)
37+
void redeemPairingLink(link).then((redeemed) => {
38+
if (redeemed) return props.onScan(redeemed)
39+
setState("error", language.t("server.connect.link.expired"))
40+
})
3241
},
3342
{ preferredCamera: "environment", maxScansPerSecond: 10, returnDetailedScanResult: true },
3443
)

‎packages/app/src/servers/connect/screen.tsx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { useLanguage } from "@/runtime/i18n/language"
88
import { usePlatform } from "@/runtime/platform/platform"
99
import { useCheckServerHealth } from "@/runtime/server/health"
1010
import { useServers } from "@/runtime/server/registry"
11-
import { serverAddress } from "./pairing"
11+
import { pairingLink, redeemPairingLink, serverAddress } from "./pairing"
1212
import type { decodePairingCode } from "./pairing"
1313
import { isMixedContent } from "./browser"
1414
import { createCameraAvailability } from "./camera"
@@ -39,6 +39,16 @@ export function ConnectServerScreen(
3939
)
4040
const request = useMutation(() => ({
4141
mutationFn: async () => {
42+
const link = pairingLink(state.url)
43+
if (link) {
44+
const redeemed = await redeemPairingLink(link)
45+
if (!redeemed) {
46+
setState("error", language.t("server.connect.link.expired"))
47+
return
48+
}
49+
// Keep the token in the form so a failed connection check can retry without the spent code.
50+
setState({ url: link.url, password: redeemed.password })
51+
}
4252
const url = serverAddress(state.url)
4353
if (!url) {
4454
setState("error", language.t("server.connect.address.invalid"))

‎packages/app/vite.pwa.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ export function serviceWorker(directory: string) {
1818
skipWaiting: false,
1919
inlineWorkboxRuntime: true,
2020
navigateFallback: "/index.html",
21-
navigateFallbackDenylist: [/^\/api(?:\/|$)/, /^\/(?:_assets|assets)(?:\/|$)/],
21+
// Pairing links must reach the server so it can set the session cookie.
22+
navigateFallbackDenylist: [/^\/(?:api|auth)(?:\/|$)/, /^\/(?:_assets|assets)(?:\/|$)/],
2223
// Include lazy chunks and non-JS dependencies, not just the startup bundle.
2324
globPatterns: ["**/*"],
2425
globIgnores: ["**/*.map", "_headers", "_redirects"],

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,10 +495,10 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
495495
},
496496
}),
497497
Spec.make("pair", {
498-
description: "Show server pairing information",
498+
description: "Print one-time links to connect a browser or app",
499499
params: {
500500
url: Flag.string("url").pipe(
501-
Flag.withDescription("Advertise an external HTTP(S) server URL in the pairing QR code"),
501+
Flag.withDescription("Use an external HTTP(S) server URL in pairing links"),
502502
Flag.mapTryCatch(
503503
(value) => {
504504
const url = new URL(value)

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

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import { EOL } from "os"
22
import { Effect, Option } from "effect"
33
import { Service } from "@opencode/client/effect/service"
44
import { OpenCode } from "@opencode/client/promise"
5-
import { base64Encode } from "@opencode/util/encode"
65
import { renderUnicodeCompact } from "uqr"
76
import { Commands } from "../commands"
87
import { Runtime } from "../../framework/runtime"
@@ -12,43 +11,43 @@ export default Runtime.handler(
1211
Commands.commands.pair,
1312
Effect.fn("cli.pair")(function* (input: Runtime.Input<typeof Commands.commands.pair>) {
1413
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
15-
const password = yield* ServiceConfig.password()
14+
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
1615
const urls = Option.isSome(input.url)
1716
? [input.url.value]
18-
: (yield* Effect.tryPromise(() =>
19-
OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.info(),
20-
)).urls
21-
const info = { urls, username: "opencode", password }
22-
const link = info.urls[0]
23-
? `${new URL("/connect", info.urls[0])}#${base64Encode(JSON.stringify({ username: info.username, password }))}`
24-
: undefined
17+
: (yield* Effect.tryPromise(() => client.server.info())).urls
18+
const pairing = yield* Effect.tryPromise(() => client.server.pair())
19+
const links = urls.map((url) => new URL(`/auth/connect/${pairing.code}`, url).href)
2520
process.stdout.write(
2621
[
2722
"",
28-
` URLs ${info.urls[0] ?? "(none)"}`,
29-
...info.urls.slice(1).map((url) => ` ${url}`),
30-
` Username ${info.username}`,
31-
` Password ${info.password}`,
32-
...(link
23+
` Open a link to connect. Links work once and expire in ${Math.round(pairing.expires_in / 60)} minutes.`,
24+
"",
25+
...(links.length ? links.map((link) => ` ${link}`) : [" (no server URLs)"]),
26+
...(links[0]
3327
? [
3428
"",
35-
" Scan to pair",
36-
"",
37-
renderUnicodeCompact(link, { border: 2 })
29+
renderUnicodeCompact(links[0], { border: 2 })
3830
.split(EOL)
3931
.map((line) => " " + line)
4032
.join(EOL),
41-
"",
42-
` Link ${link}`,
4333
]
4434
: []),
4535
"",
4636
].join(EOL) + EOL,
4737
)
4838

4939
if (Option.isSome(input.url)) return
50-
const hostname = new URL(endpoint.url).hostname
51-
if (!["localhost", "127.0.0.1", "[::1]"].includes(hostname)) return
52-
process.stderr.write(` Run \`opencode service set hostname 0.0.0.0\` to access the service remotely.${EOL}${EOL}`)
40+
const url = new URL(endpoint.url)
41+
if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) return
42+
process.stderr.write(
43+
[
44+
` Over SSH? Forward the port, then open the link on your machine:`,
45+
` ssh -L ${url.port}:${url.hostname}:${url.port} <host>`,
46+
` If port ${url.port} is busy locally, forward another port and use it in the link.`,
47+
"",
48+
" To connect from other devices, run `opencode service set hostname 0.0.0.0`.",
49+
"",
50+
].join(EOL) + EOL,
51+
)
5352
}),
5453
)

‎packages/cli/src/services/web-ui.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,12 @@ export const handler = Effect.fn("cli.web-ui.handler")(function* (options?: { re
1414
const request = yield* HttpServerRequest.HttpServerRequest
1515
const url = new URL(request.url, "http://localhost")
1616
// Serve the web shell before API authentication so /connect can load credentials in JavaScript.
17-
if (url.pathname === "/api" || url.pathname.startsWith("/api/") || url.pathname === "/openapi.json")
17+
if (
18+
url.pathname === "/api" ||
19+
url.pathname.startsWith("/api/") ||
20+
url.pathname.startsWith("/auth/") ||
21+
url.pathname === "/openapi.json"
22+
)
1823
return yield* api.pipe(
1924
Effect.catchIf(isRouteNotFound, () => Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
2025
)

‎packages/cli/test/web-ui.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,24 @@ describe("web UI", () => {
6868
)
6969
expect(response.status).toBe(200)
7070
expect(yield* Effect.promise(() => response.json())).toHaveProperty("pid")
71+
72+
const pairing = yield* Effect.promise(() =>
73+
fetch(new URL("/api/pair", origin), {
74+
method: "POST",
75+
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
76+
}).then((response) => response.json() as Promise<{ code: string }>),
77+
)
78+
const redirect = yield* Effect.promise(() =>
79+
fetch(new URL(`/auth/connect/${pairing.code}`, origin), {
80+
redirect: "manual",
81+
headers: { accept: "text/html" },
82+
}),
83+
)
84+
expect(redirect.status).toBe(302)
85+
const cookie = (redirect.headers.get("set-cookie") ?? "").split(";")[0]
86+
const authorized = yield* Effect.promise(() => fetch(new URL("/api/info", origin), { headers: { cookie } }))
87+
expect(authorized.status).toBe(200)
88+
yield* Effect.promise(() => authorized.arrayBuffer())
7189
}).pipe(Effect.provide(NodeFileSystem.layer)),
7290
)
7391

0 commit comments

Comments
 (0)