diff --git a/backend/src/routes/device-pairing.ts b/backend/src/routes/device-pairing.ts
index e3128492..b4dcea0f 100644
--- a/backend/src/routes/device-pairing.ts
+++ b/backend/src/routes/device-pairing.ts
@@ -1,18 +1,26 @@
import { Hono } from 'hono'
-import { ENV, getTrustedOrigins, isTrustedOrigin } from '@opencode-manager/shared/config/env'
+import type { MiddlewareHandler } from 'hono'
+import { ENV, getTrustedOrigins } from '@opencode-manager/shared/config/env'
import { CreateDevicePairingLinksRequestSchema } from '@opencode-manager/shared/schemas'
-import { buildDevicePairingLinks, resolveAppLinkPolicy } from '../services/device-pairing-links'
+import {
+ buildDevicePairingLinks,
+ normalizeDevicePairingOrigin,
+ resolveAppLinkPolicy,
+ resolveDevicePairingAvailability,
+} from '../services/device-pairing-links'
import type { RemoteAccessHeadersService } from '../services/remote-access-headers'
import { logger } from '../utils/logger'
import { parseJsonBody } from '../utils/route-helpers'
-const MISSING_ORIGIN_MESSAGE =
- 'The request had no Origin header. Open the Manager at an address listed in AUTH_TRUSTED_ORIGINS to pair a device.'
const LINKS_FAILED_MESSAGE = 'Failed to create device pairing links'
+const MISSING_ORIGIN_QUERY_MESSAGE =
+ 'Add an origin query parameter, for example ?origin=https://manager.example.com.'
+const INVALID_ORIGIN_QUERY_MESSAGE =
+ 'The origin query parameter must be an absolute http or https URL.'
-function untrustedOriginMessage(origin: string | undefined): string {
- if (!origin) return MISSING_ORIGIN_MESSAGE
- return `This address (${origin}) is not in AUTH_TRUSTED_ORIGINS. Add it and restart the Manager to pair a device.`
+const noStore: MiddlewareHandler = async (c, next) => {
+ await next()
+ c.header('Cache-Control', 'no-store')
}
interface DevicePairingRouteDeps {
@@ -29,9 +37,22 @@ export function createDevicePairingRoutes(deps: DevicePairingRouteDeps) {
const resolveTrustedOrigins = deps.resolveTrustedOrigins ?? getTrustedOrigins
const isDevelopment = deps.isDevelopment ?? (() => ENV.SERVER.NODE_ENV === 'development')
- app.use('/links', async (c, next) => {
- await next()
- c.header('Cache-Control', 'no-store')
+ app.use('/links', noStore)
+ app.use('/availability', noStore)
+
+ app.get('/availability', (c) => {
+ const requestedOrigin = c.req.query('origin')
+ if (!requestedOrigin) return c.json({ error: MISSING_ORIGIN_QUERY_MESSAGE }, 400)
+
+ const origin = normalizeDevicePairingOrigin(requestedOrigin)
+ if (!origin) return c.json({ error: INVALID_ORIGIN_QUERY_MESSAGE }, 400)
+
+ return c.json(
+ resolveDevicePairingAvailability(origin, {
+ trustedOrigins: resolveTrustedOrigins(),
+ isDevelopment: isDevelopment(),
+ }),
+ )
})
app.post('/links', async (c) => {
@@ -39,15 +60,18 @@ export function createDevicePairingRoutes(deps: DevicePairingRouteDeps) {
if (!body.ok) return body.response
const origin = c.req.header('origin')
- if (!origin || !isTrustedOrigin(origin, { requireOrigin: true }, resolveTrustedOrigins())) {
- return c.json({ error: untrustedOriginMessage(origin) }, 400)
+ const availability = resolveDevicePairingAvailability(origin, {
+ trustedOrigins: resolveTrustedOrigins(),
+ isDevelopment: isDevelopment(),
+ })
+ if (!origin || !availability.available) {
+ return c.json({ error: availability.message, code: availability.reason }, 400)
}
try {
const originUrl = new URL(origin)
const policy = resolveAppLinkPolicy(originUrl, {
allowPrivateNetworkHttp: deps.readAllowPrivateNetworkHttp(),
- isDevelopment: isDevelopment(),
})
const stored = deps.remoteAccessHeaders.read()
const minted = await deps.mintPairingCode(c.req.raw.headers)
diff --git a/backend/src/services/device-pairing-links.ts b/backend/src/services/device-pairing-links.ts
index 893aa2ff..712fa9f4 100644
--- a/backend/src/services/device-pairing-links.ts
+++ b/backend/src/services/device-pairing-links.ts
@@ -1,39 +1,101 @@
+import { isTrustedOrigin } from '@opencode-manager/shared/config/env'
import {
buildManagerAppLink,
buildManagerBrowserPairingLink,
type AppLinkBlockedReason,
+ type DevicePairingAvailability,
type DevicePairingLinkWarning,
type DevicePairingLinksResponse,
+ type DevicePairingUnavailableReason,
type RemoteAccessHeader,
} from '@opencode-manager/shared/schemas'
import { isLoopbackHost, isPrivateNetworkHost } from '@opencode-manager/shared/utils'
+export const MISSING_ORIGIN_MESSAGE =
+ 'The request had no Origin header. Open the Manager at an address listed in AUTH_TRUSTED_ORIGINS to pair a device.'
+export const LOOPBACK_ORIGIN_MESSAGE =
+ 'This page is open on localhost, which other devices cannot reach. Open the Manager at its public or LAN address to pair a device.'
+export const INSECURE_ORIGIN_MESSAGE =
+ 'Pairing needs HTTPS on a public address. Serve the Manager over HTTPS, or open it at a private network address.'
+
type AppLinkPolicy = {
blockedReason: AppLinkBlockedReason | null
warnings: DevicePairingLinkWarning[]
}
+type DevicePairingAvailabilityOptions = {
+ trustedOrigins: string[]
+ isDevelopment: boolean
+}
+
+function untrustedOriginMessage(origin: string): string {
+ return `This address (${origin}) is not in AUTH_TRUSTED_ORIGINS. Add it and restart the Manager to pair a device.`
+}
+
+function unavailable(
+ reason: DevicePairingUnavailableReason,
+ message: string,
+): DevicePairingAvailability {
+ return { available: false, reason, message }
+}
+
+function parseHttpOrigin(value: string): URL | null {
+ let url: URL
+ try {
+ url = new URL(value)
+ } catch {
+ return null
+ }
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
+ return url
+}
+
+/** Normalises an address to its origin, or null when it is not an absolute http(s) URL. */
+export function normalizeDevicePairingOrigin(value: string): string | null {
+ return parseHttpOrigin(value)?.origin ?? null
+}
+
+/** Reports whether an origin can mint a pairing code, and why it cannot when blocked. */
+export function resolveDevicePairingAvailability(
+ origin: string | undefined,
+ options: DevicePairingAvailabilityOptions,
+): DevicePairingAvailability {
+ if (!origin) return unavailable('untrusted-origin', MISSING_ORIGIN_MESSAGE)
+ if (!isTrustedOrigin(origin, { requireOrigin: true }, options.trustedOrigins)) {
+ return unavailable('untrusted-origin', untrustedOriginMessage(origin))
+ }
+
+ const originUrl = parseHttpOrigin(origin)
+ if (!originUrl) return unavailable('untrusted-origin', untrustedOriginMessage(origin))
+
+ const isLoopback = isLoopbackHost(originUrl.hostname)
+ if (isLoopback && !options.isDevelopment) {
+ return unavailable('loopback', LOOPBACK_ORIGIN_MESSAGE)
+ }
+
+ if (originUrl.protocol === 'http:' && !isLoopback && !isPrivateNetworkHost(originUrl.hostname)) {
+ return unavailable('insecure-origin', INSECURE_ORIGIN_MESSAGE)
+ }
+
+ return { available: true, reason: null, message: null }
+}
+
/** Decides whether an origin can carry an app link and which warnings it raises. */
export function resolveAppLinkPolicy(
origin: URL,
- options: { allowPrivateNetworkHttp: boolean; isDevelopment: boolean },
+ options: { allowPrivateNetworkHttp: boolean },
): AppLinkPolicy {
const warnings: DevicePairingLinkWarning[] = []
const isPlainHttp = origin.protocol === 'http:'
+ const isLoopback = isLoopbackHost(origin.hostname)
if (isPlainHttp) warnings.push('plain-http')
+ if (isLoopback) warnings.push('loopback')
+ if (!isPlainHttp) return { blockedReason: null, warnings }
- if (isLoopbackHost(origin.hostname)) {
- warnings.push('loopback')
- return { blockedReason: options.isDevelopment ? null : 'loopback', warnings }
- }
-
- if (isPlainHttp) {
- const isAllowed = options.allowPrivateNetworkHttp && isPrivateNetworkHost(origin.hostname)
- return { blockedReason: isAllowed ? null : 'insecure-origin', warnings }
- }
-
- return { blockedReason: null, warnings }
+ const isAllowed =
+ isLoopback || (options.allowPrivateNetworkHttp && isPrivateNetworkHost(origin.hostname))
+ return { blockedReason: isAllowed ? null : 'insecure-origin', warnings }
}
/** Builds the pairing link response, dropping the app link when its origin is blocked. */
diff --git a/backend/test/routes/device-pairing.test.ts b/backend/test/routes/device-pairing.test.ts
index dc40b9f0..a583b641 100644
--- a/backend/test/routes/device-pairing.test.ts
+++ b/backend/test/routes/device-pairing.test.ts
@@ -2,9 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { Database } from 'bun:sqlite'
import { Hono } from 'hono'
import {
+ DevicePairingAvailabilitySchema,
DevicePairingLinksResponseSchema,
buildManagerBrowserPairingLink,
parseManagerAppLink,
+ type DevicePairingAvailability,
type DevicePairingLinksResponse,
} from '@opencode-manager/shared/schemas'
@@ -41,6 +43,10 @@ const MISSING_ORIGIN_ERROR =
'The request had no Origin header. Open the Manager at an address listed in AUTH_TRUSTED_ORIGINS to pair a device.'
const untrustedOriginError = (origin: string) =>
`This address (${origin}) is not in AUTH_TRUSTED_ORIGINS. Add it and restart the Manager to pair a device.`
+const LOOPBACK_ORIGIN_ERROR =
+ 'This page is open on localhost, which other devices cannot reach. Open the Manager at its public or LAN address to pair a device.'
+const INSECURE_ORIGIN_ERROR =
+ 'Pairing needs HTTPS on a public address. Serve the Manager over HTTPS, or open it at a private network address.'
const LINKS_FAILED_ERROR = 'Failed to create device pairing links'
const SENSITIVE_VALUES = [CODE, ...CLOUDFLARE_SECRET_VALUES]
@@ -57,6 +63,10 @@ async function readLinksBody(response: Response): Promise {
+ return DevicePairingAvailabilitySchema.parse(await response.json())
+}
+
describe('device pairing link routes', () => {
let db: Database
let remoteAccessHeaders: RemoteAccessHeadersService
@@ -103,12 +113,24 @@ describe('device pairing link routes', () => {
})
}
+ const getAvailability = (origin?: string) => {
+ const path =
+ origin === undefined
+ ? '/device-pairing/availability'
+ : `/device-pairing/availability?origin=${encodeURIComponent(origin)}`
+
+ return app.request(path, { headers: { cookie: COOKIE_HEADER } })
+ }
+
it('rejects a request without an origin', async () => {
const res = await postLinks()
expect(res.status).toBe(400)
expect(res.headers.get('Cache-Control')).toBe('no-store')
- await expect(res.json()).resolves.toEqual({ error: MISSING_ORIGIN_ERROR })
+ await expect(res.json()).resolves.toEqual({
+ error: MISSING_ORIGIN_ERROR,
+ code: 'untrusted-origin',
+ })
expect(mintPairingCode).not.toHaveBeenCalled()
})
@@ -117,9 +139,10 @@ describe('device pairing link routes', () => {
expect(res.status).toBe(400)
expect(res.headers.get('Cache-Control')).toBe('no-store')
- const body = await res.json() as { error: string }
+ const body = await res.json() as { error: string; code: string }
expect(body.error).toBe(untrustedOriginError('https://evil.example'))
expect(body.error).toContain('AUTH_TRUSTED_ORIGINS')
+ expect(body.code).toBe('untrusted-origin')
expect(mintPairingCode).not.toHaveBeenCalled()
})
@@ -127,7 +150,10 @@ describe('device pairing link routes', () => {
const res = await postLinks('null')
expect(res.status).toBe(400)
- await expect(res.json()).resolves.toEqual({ error: untrustedOriginError('null') })
+ await expect(res.json()).resolves.toEqual({
+ error: untrustedOriginError('null'),
+ code: 'untrusted-origin',
+ })
expect(mintPairingCode).not.toHaveBeenCalled()
})
@@ -195,11 +221,13 @@ describe('device pairing link routes', () => {
const res = await postLinks('http://203.0.113.5:5003')
- expect(res.status).toBe(200)
- const body = await readLinksBody(res)
-
- expect(body.appLink).toBeNull()
- expect(body.appLinkBlockedReason).toBe('insecure-origin')
+ expect(res.status).toBe(400)
+ expect(res.headers.get('Cache-Control')).toBe('no-store')
+ await expect(res.json()).resolves.toEqual({
+ error: INSECURE_ORIGIN_ERROR,
+ code: 'insecure-origin',
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
})
it('blocks a loopback origin outside development', async () => {
@@ -208,12 +236,12 @@ describe('device pairing link routes', () => {
const res = await postLinks('http://localhost:5173')
- expect(res.status).toBe(200)
- const body = await readLinksBody(res)
-
- expect(body.appLink).toBeNull()
- expect(body.appLinkBlockedReason).toBe('loopback')
- expect(body.warnings).toEqual(['plain-http', 'loopback'])
+ expect(res.status).toBe(400)
+ await expect(res.json()).resolves.toEqual({
+ error: LOOPBACK_ORIGIN_ERROR,
+ code: 'loopback',
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
})
it('allows a loopback origin in development', async () => {
@@ -226,6 +254,7 @@ describe('device pairing link routes', () => {
const body = await readLinksBody(res)
expect(parseManagerAppLink(body.appLink ?? '')?.baseUrl).toBe('http://localhost:5173')
+ expect(body.warnings).toEqual(['plain-http', 'loopback'])
})
it('reports unreadable stored headers', async () => {
@@ -257,4 +286,119 @@ describe('device pairing link routes', () => {
expectNoSecretsLogged(loggerMocks, SENSITIVE_VALUES)
})
+
+ describe('GET availability', () => {
+ it('reports a trusted https origin as available without minting', async () => {
+ const res = await getAvailability('https://m.example.com')
+
+ expect(res.status).toBe(200)
+ expect(res.headers.get('Cache-Control')).toBe('no-store')
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: true,
+ reason: null,
+ message: null,
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it('reports an untrusted origin', async () => {
+ const res = await getAvailability('https://evil.example')
+
+ expect(res.status).toBe(200)
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: false,
+ reason: 'untrusted-origin',
+ message: untrustedOriginError('https://evil.example'),
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it('reports a loopback origin outside development', async () => {
+ development = false
+
+ const res = await getAvailability('http://localhost:5173')
+
+ expect(res.status).toBe(200)
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: false,
+ reason: 'loopback',
+ message: LOOPBACK_ORIGIN_ERROR,
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it('reports a loopback origin in development as available', async () => {
+ development = true
+
+ const res = await getAvailability('http://localhost:5173')
+
+ expect(res.status).toBe(200)
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: true,
+ reason: null,
+ message: null,
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it('reports a public http origin as insecure', async () => {
+ allowPrivateNetwork = true
+
+ const res = await getAvailability('http://203.0.113.5:5003')
+
+ expect(res.status).toBe(200)
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: false,
+ reason: 'insecure-origin',
+ message: INSECURE_ORIGIN_ERROR,
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it('keeps a private network http origin available so the browser link can be shown', async () => {
+ const res = await getAvailability('http://192.168.1.20:5003')
+
+ expect(res.status).toBe(200)
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: true,
+ reason: null,
+ message: null,
+ })
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it('normalises the supplied address to its origin', async () => {
+ const res = await getAvailability('https://m.example.com/settings?tab=pairing')
+
+ expect(res.status).toBe(200)
+ await expect(readAvailabilityBody(res)).resolves.toEqual({
+ available: true,
+ reason: null,
+ message: null,
+ })
+ })
+
+ it('rejects a missing origin query parameter', async () => {
+ const res = await getAvailability()
+
+ expect(res.status).toBe(400)
+ expect(res.headers.get('Cache-Control')).toBe('no-store')
+ const body = await res.json() as { error: string }
+ expect(body.error).toContain('origin query parameter')
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['garbage text', 'not a url'],
+ ['a non-http scheme', 'ocm://link?v=2&kind=manager'],
+ ['a scheme-relative address', '//m.example.com'],
+ ])('rejects %s in the origin query parameter', async (_label, origin) => {
+ const res = await getAvailability(origin)
+
+ expect(res.status).toBe(400)
+ const body = await res.json() as { error: string }
+ expect(body.error).toContain('absolute http or https URL')
+ expect(mintPairingCode).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/backend/test/services/device-pairing-links.test.ts b/backend/test/services/device-pairing-links.test.ts
new file mode 100644
index 00000000..1e05160e
--- /dev/null
+++ b/backend/test/services/device-pairing-links.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest'
+import { resolveAppLinkPolicy, resolveDevicePairingAvailability } from '../../src/services/device-pairing-links'
+
+const TRUSTED_ORIGINS = [
+ 'https://m.example.com',
+ 'http://192.168.1.20:5003',
+ 'http://203.0.113.5:5003',
+ 'http://localhost:5173',
+]
+
+const production = { trustedOrigins: TRUSTED_ORIGINS, isDevelopment: false }
+const development = { trustedOrigins: TRUSTED_ORIGINS, isDevelopment: true }
+
+describe('resolveDevicePairingAvailability', () => {
+ it('allows a trusted https origin', () => {
+ expect(resolveDevicePairingAvailability('https://m.example.com', production)).toEqual({
+ available: true,
+ reason: null,
+ message: null,
+ })
+ })
+
+ it('rejects a missing origin', () => {
+ expect(resolveDevicePairingAvailability(undefined, production)).toEqual({
+ available: false,
+ reason: 'untrusted-origin',
+ message:
+ 'The request had no Origin header. Open the Manager at an address listed in AUTH_TRUSTED_ORIGINS to pair a device.',
+ })
+ })
+
+ it('rejects the null origin', () => {
+ expect(resolveDevicePairingAvailability('null', production)).toEqual({
+ available: false,
+ reason: 'untrusted-origin',
+ message:
+ 'This address (null) is not in AUTH_TRUSTED_ORIGINS. Add it and restart the Manager to pair a device.',
+ })
+ })
+
+ it('rejects a loopback origin outside development', () => {
+ expect(resolveDevicePairingAvailability('http://localhost:5173', production)).toEqual({
+ available: false,
+ reason: 'loopback',
+ message:
+ 'This page is open on localhost, which other devices cannot reach. Open the Manager at its public or LAN address to pair a device.',
+ })
+ })
+
+ it('allows a loopback origin in development', () => {
+ expect(resolveDevicePairingAvailability('http://localhost:5173', development).available).toBe(true)
+ })
+
+ it('rejects public plain http', () => {
+ expect(resolveDevicePairingAvailability('http://203.0.113.5:5003', production)).toEqual({
+ available: false,
+ reason: 'insecure-origin',
+ message:
+ 'Pairing needs HTTPS on a public address. Serve the Manager over HTTPS, or open it at a private network address.',
+ })
+ })
+
+ it('allows private network plain http', () => {
+ expect(resolveDevicePairingAvailability('http://192.168.1.20:5003', production).available).toBe(true)
+ })
+
+ it('rejects a trusted origin that is not an http url', () => {
+ const options = { trustedOrigins: ['ocm://link'], isDevelopment: false }
+
+ expect(resolveDevicePairingAvailability('ocm://link', options)).toEqual({
+ available: false,
+ reason: 'untrusted-origin',
+ message:
+ 'This address (ocm://link) is not in AUTH_TRUSTED_ORIGINS. Add it and restart the Manager to pair a device.',
+ })
+ })
+})
+
+describe('resolveAppLinkPolicy', () => {
+ it('allows an https origin without warnings', () => {
+ expect(resolveAppLinkPolicy(new URL('https://m.example.com'), { allowPrivateNetworkHttp: false })).toEqual({
+ blockedReason: null,
+ warnings: [],
+ })
+ })
+
+ it('blocks a private network http app link without the toggle', () => {
+ expect(
+ resolveAppLinkPolicy(new URL('http://192.168.1.20:5003'), { allowPrivateNetworkHttp: false }),
+ ).toEqual({
+ blockedReason: 'insecure-origin',
+ warnings: ['plain-http'],
+ })
+ })
+
+ it('allows a private network http app link with the toggle', () => {
+ expect(
+ resolveAppLinkPolicy(new URL('http://192.168.1.20:5003'), { allowPrivateNetworkHttp: true }),
+ ).toEqual({
+ blockedReason: null,
+ warnings: ['plain-http'],
+ })
+ })
+
+ it('warns about loopback without blocking the app link itself', () => {
+ expect(
+ resolveAppLinkPolicy(new URL('http://localhost:5173'), { allowPrivateNetworkHttp: true }),
+ ).toEqual({
+ blockedReason: null,
+ warnings: ['plain-http', 'loopback'],
+ })
+ })
+})
diff --git a/backend/test/shared/device-pairing-schemas.test.ts b/backend/test/shared/device-pairing-schemas.test.ts
index 5cade570..686ec6e3 100644
--- a/backend/test/shared/device-pairing-schemas.test.ts
+++ b/backend/test/shared/device-pairing-schemas.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
+ AppLinkBlockedReasonSchema,
+ DevicePairingAvailabilitySchema,
REMOTE_ACCESS_HEADERS_MAX_ENCODED_LENGTH,
REMOTE_ACCESS_HEADER_VALUE_MAX_LENGTH,
RedeemDevicePairingCodeResponseSchema,
@@ -171,6 +173,40 @@ describe('RemoteAccessHeaderDraftValueSchema', () => {
})
})
+describe('DevicePairingAvailabilitySchema', () => {
+ it('accepts an available origin', () => {
+ expect(
+ DevicePairingAvailabilitySchema.parse({ available: true, reason: null, message: null }),
+ ).toEqual({ available: true, reason: null, message: null })
+ })
+
+ it.each(['untrusted-origin', 'loopback', 'insecure-origin'])(
+ 'accepts the unavailable reason %s',
+ (reason) => {
+ expect(
+ DevicePairingAvailabilitySchema.parse({ available: false, reason, message: 'blocked' }),
+ ).toEqual({ available: false, reason, message: 'blocked' })
+ },
+ )
+
+ it('rejects an unknown reason', () => {
+ expect(
+ DevicePairingAvailabilitySchema.safeParse({ available: false, reason: 'no-origin', message: 'x' })
+ .success,
+ ).toBe(false)
+ })
+})
+
+describe('AppLinkBlockedReasonSchema', () => {
+ it('accepts an insecure origin', () => {
+ expect(AppLinkBlockedReasonSchema.parse('insecure-origin')).toBe('insecure-origin')
+ })
+
+ it('no longer accepts loopback, which now blocks pairing entirely', () => {
+ expect(AppLinkBlockedReasonSchema.safeParse('loopback').success).toBe(false)
+ })
+})
+
describe('RedeemDevicePairingCodeResponseSchema', () => {
it('parses the user returned by the redeem endpoint', () => {
const response = { user: { id: 'user_1', name: 'Chris', email: 'chris@example.com' } }
diff --git a/frontend/src/api/devicePairing.ts b/frontend/src/api/devicePairing.ts
index 77543f27..c6405bbe 100644
--- a/frontend/src/api/devicePairing.ts
+++ b/frontend/src/api/devicePairing.ts
@@ -1,5 +1,6 @@
import type {
CreateDevicePairingLinksRequest,
+ DevicePairingAvailability,
DevicePairingLinksResponse,
PairedDevice,
PairedDevicesResponse,
@@ -62,6 +63,16 @@ export async function createDevicePairingLinks(
})
}
+/** Reads whether the Manager can mint pairing codes for an address without minting one. */
+export async function getDevicePairingAvailability(
+ origin: string,
+): Promise {
+ return fetchWrapper(
+ `${API_BASE_URL}/api/device-pairing/availability`,
+ { params: { origin } },
+ )
+}
+
/** Lists the devices signed in to this account. */
export async function listPairedDevices(): Promise {
const response = await fetchWrapper(
diff --git a/frontend/src/components/settings/ConnectDeviceDialog.test.tsx b/frontend/src/components/settings/ConnectDeviceDialog.test.tsx
index a2574561..a0944810 100644
--- a/frontend/src/components/settings/ConnectDeviceDialog.test.tsx
+++ b/frontend/src/components/settings/ConnectDeviceDialog.test.tsx
@@ -90,27 +90,20 @@ describe('ConnectDeviceDialog', () => {
expect(await screen.findByAltText('Browser sign-in QR code')).toBeInTheDocument()
})
- it('explains a loopback block without showing the mobile app QR code', async () => {
+ it('warns about a localhost address while still showing the mobile app QR code', async () => {
mocks.createDevicePairingLinks.mockResolvedValue({
...BASE_LINKS,
- appLink: null,
- appLinkBlockedReason: 'loopback',
warnings: ['plain-http', 'loopback'],
})
renderDialog()
- expect(
- await screen.findByText(
- 'This page is open on localhost, which your phone cannot reach. Open the Manager at its public or LAN address to show the app QR code.',
- ),
- ).toBeInTheDocument()
- expect(screen.queryByAltText('Mobile app pairing QR code')).not.toBeInTheDocument()
- expect(
- screen.getByText('This address uses plain HTTP, so the sign-in code travels unencrypted.'),
- ).toBeInTheDocument()
+ expect(await screen.findByAltText('Mobile app pairing QR code')).toBeInTheDocument()
expect(
screen.getByText('This address is localhost; other devices cannot reach it.'),
).toBeInTheDocument()
+ expect(
+ screen.getByText('This address uses plain HTTP, so the sign-in code travels unencrypted.'),
+ ).toBeInTheDocument()
})
it('explains how to unblock a plain-HTTP app link', async () => {
diff --git a/frontend/src/components/settings/ConnectDeviceDialog.tsx b/frontend/src/components/settings/ConnectDeviceDialog.tsx
index cd4ed768..63871b33 100644
--- a/frontend/src/components/settings/ConnectDeviceDialog.tsx
+++ b/frontend/src/components/settings/ConnectDeviceDialog.tsx
@@ -24,9 +24,6 @@ const WARNING_MESSAGES: Record = {
'headers-unreadable': 'Stored remote access headers could not be decrypted and are not included.',
}
-const LOOPBACK_EXPLANATION =
- 'This page is open on localhost, which your phone cannot reach. Open the Manager at its public or LAN address to show the app QR code.'
-
const INSECURE_ORIGIN_EXPLANATION =
"The mobile app QR code needs HTTPS. Use an HTTPS address, or turn on 'Allow plain-HTTP app links on private networks' if this Manager uses a private IP address."
@@ -187,11 +184,7 @@ export function ConnectDeviceDialog({ open, onOpenChange }: ConnectDeviceDialogP
>
) : (
-
- {links.appLinkBlockedReason === 'loopback'
- ? LOOPBACK_EXPLANATION
- : INSECURE_ORIGIN_EXPLANATION}
-
+ {INSECURE_ORIGIN_EXPLANATION}
)}
diff --git a/frontend/src/components/settings/ConnectDeviceSettings.test.tsx b/frontend/src/components/settings/ConnectDeviceSettings.test.tsx
index 6690d2f4..92c9f52f 100644
--- a/frontend/src/components/settings/ConnectDeviceSettings.test.tsx
+++ b/frontend/src/components/settings/ConnectDeviceSettings.test.tsx
@@ -1,15 +1,19 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { render, screen } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { DEFAULT_USER_PREFERENCES } from '@opencode-manager/shared/schemas'
import { createUseSettingsMock } from '@/test/test-utils'
import { ConnectDeviceSettings } from './ConnectDeviceSettings'
+const UNAVAILABLE_MESSAGE =
+ 'This page is open on localhost, which other devices cannot reach. Open the Manager at its public or LAN address to pair a device.'
+
const mocks = vi.hoisted(() => ({
useSettings: vi.fn(),
updateSettings: vi.fn(),
createDevicePairingLinks: vi.fn(),
+ getDevicePairingAvailability: vi.fn(),
}))
vi.mock('@/hooks/useSettings', () => ({
@@ -18,6 +22,7 @@ vi.mock('@/hooks/useSettings', () => ({
vi.mock('@/api/devicePairing', () => ({
createDevicePairingLinks: mocks.createDevicePairingLinks,
+ getDevicePairingAvailability: mocks.getDevicePairingAvailability,
}))
function renderSettings() {
@@ -56,6 +61,11 @@ describe('ConnectDeviceSettings', () => {
headerNames: [],
warnings: [],
})
+ mocks.getDevicePairingAvailability.mockResolvedValue({
+ available: true,
+ reason: null,
+ message: null,
+ })
})
it('persists the private-network plain-HTTP preference', async () => {
@@ -75,8 +85,45 @@ describe('ConnectDeviceSettings', () => {
const user = userEvent.setup()
renderSettings()
- await user.click(screen.getByRole('button', { name: 'Show QR code' }))
+ const button = screen.getByRole('button', { name: 'Show QR code' })
+ await waitFor(() => expect(button).toBeEnabled())
+ await user.click(button)
expect(await screen.findByAltText('Mobile app pairing QR code')).toBeInTheDocument()
})
+
+ it('disables the QR code button while availability loads', async () => {
+ mocks.getDevicePairingAvailability.mockReturnValue(new Promise(() => undefined))
+ renderSettings()
+
+ expect(screen.getByRole('button', { name: 'Show QR code' })).toBeDisabled()
+ })
+
+ it('disables the QR code button and shows the reason when pairing is unavailable', async () => {
+ const user = userEvent.setup()
+ mocks.getDevicePairingAvailability.mockResolvedValue({
+ available: false,
+ reason: 'loopback',
+ message: UNAVAILABLE_MESSAGE,
+ })
+ renderSettings()
+
+ const button = screen.getByRole('button', { name: 'Show QR code' })
+ await screen.findByText(UNAVAILABLE_MESSAGE)
+ expect(button).toBeDisabled()
+
+ await user.click(button)
+
+ expect(screen.queryByAltText('Mobile app pairing QR code')).not.toBeInTheDocument()
+ expect(mocks.createDevicePairingLinks).not.toHaveBeenCalled()
+ })
+
+ it('keeps the QR code button enabled when the availability check fails', async () => {
+ mocks.getDevicePairingAvailability.mockRejectedValue(new Error('availability failed'))
+ renderSettings()
+
+ const button = screen.getByRole('button', { name: 'Show QR code' })
+ await waitFor(() => expect(button).toBeEnabled())
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ })
})
diff --git a/frontend/src/components/settings/ConnectDeviceSettings.tsx b/frontend/src/components/settings/ConnectDeviceSettings.tsx
index 80624a7d..58e8b195 100644
--- a/frontend/src/components/settings/ConnectDeviceSettings.tsx
+++ b/frontend/src/components/settings/ConnectDeviceSettings.tsx
@@ -1,6 +1,8 @@
import { useState } from 'react'
-import { QrCode } from 'lucide-react'
+import { AlertCircle, QrCode } from 'lucide-react'
+import { useDevicePairingAvailability } from '@/hooks/useDevicePairing'
import { useSettings } from '@/hooks/useSettings'
+import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
@@ -12,7 +14,11 @@ const ALLOW_PRIVATE_NETWORK_HTTP_LABEL = 'Allow plain-HTTP app links on private
export function ConnectDeviceSettings() {
const { preferences, updateSettings } = useSettings()
const [dialogOpen, setDialogOpen] = useState(false)
+ const availability = useDevicePairingAvailability()
const allowPrivateNetworkHttp = preferences?.devicePairing?.allowPrivateNetworkHttp ?? false
+ const isPairingAvailable = availability.data?.available !== false
+ const unavailableMessage =
+ availability.data?.available === false ? availability.data.message : null
return (
@@ -26,10 +32,22 @@ export function ConnectDeviceSettings() {
-