mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(device-pairing): refuse to mint pairing codes from an address that cannot pair
A loopback origin in production or plain HTTP on a public address still minted a code and showed a browser QR no other device could use. - one availability rule decides untrusted, loopback and public plain-HTTP origins; POST /api/device-pairing/links checks it before minting - GET /api/device-pairing/availability reports the rule for the page origin without minting - Connect a device disables "Show QR code" and explains the fix when the address cannot pair - private-network plain HTTP keeps the browser QR; the app QR still needs the toggle
This commit is contained in:
1 parent
106e8f51fc
commit
b9d8d18124
12 files changed
+529
-64
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<DevicePairingLinksResp
|
||||
return DevicePairingLinksResponseSchema.parse(await response.json())
|
||||
}
|
||||
|
||||
async function readAvailabilityBody(response: Response): Promise<DevicePairingAvailability> {
|
||||
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()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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'],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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' } }
|
||||
|
||||
@@ -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<DevicePairingAvailability> {
|
||||
return fetchWrapper<DevicePairingAvailability>(
|
||||
`${API_BASE_URL}/api/device-pairing/availability`,
|
||||
{ params: { origin } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Lists the devices signed in to this account. */
|
||||
export async function listPairedDevices(): Promise<PairedDevice[]> {
|
||||
const response = await fetchWrapper<PairedDevicesResponse>(
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -24,9 +24,6 @@ const WARNING_MESSAGES: Record<DevicePairingLinkWarning, string> = {
|
||||
'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
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{links.appLinkBlockedReason === 'loopback'
|
||||
? LOOPBACK_EXPLANATION
|
||||
: INSECURE_ORIGIN_EXPLANATION}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{INSECURE_ORIGIN_EXPLANATION}</p>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<Card className="border-0 shadow-none">
|
||||
@@ -26,10 +32,22 @@ export function ConnectDeviceSettings() {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Button variant="outline" size="sm" onClick={() => setDialogOpen(true)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setDialogOpen(true)}
|
||||
disabled={availability.isLoading || !isPairingAvailable}
|
||||
>
|
||||
Show QR code
|
||||
</Button>
|
||||
|
||||
{unavailableMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{unavailableMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<Label htmlFor="allow-private-network-http" className="text-xs sm:text-sm">
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import {
|
||||
clearRemoteAccessHeaders,
|
||||
createDevicePairingLinks,
|
||||
getDevicePairingAvailability,
|
||||
getRemoteAccessHeaders,
|
||||
listPairedDevices,
|
||||
replaceRemoteAccessHeaders,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
|
||||
const REMOTE_ACCESS_HEADERS_QUERY_KEY = ['remote-access-headers']
|
||||
const PAIRED_DEVICES_QUERY_KEY = ['paired-devices']
|
||||
const DEVICE_PAIRING_AVAILABILITY_QUERY_KEY = ['device-pairing-availability']
|
||||
|
||||
export function useRemoteAccessHeaders() {
|
||||
const queryClient = useQueryClient()
|
||||
@@ -55,6 +57,15 @@ export function useCreateDevicePairingLinks() {
|
||||
})
|
||||
}
|
||||
|
||||
export function useDevicePairingAvailability() {
|
||||
const origin = window.location.origin
|
||||
|
||||
return useQuery({
|
||||
queryKey: [...DEVICE_PAIRING_AVAILABILITY_QUERY_KEY, origin],
|
||||
queryFn: () => getDevicePairingAvailability(origin),
|
||||
})
|
||||
}
|
||||
|
||||
export function usePairedDevices() {
|
||||
return useQuery({
|
||||
queryKey: PAIRED_DEVICES_QUERY_KEY,
|
||||
|
||||
@@ -128,8 +128,19 @@ export const RedeemDevicePairingCodeResponseSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const AppLinkBlockedReasonSchema = z.enum(["insecure-origin", "loopback"]);
|
||||
export const AppLinkBlockedReasonSchema = z.enum(["insecure-origin"]);
|
||||
export const DevicePairingLinkWarningSchema = z.enum(["plain-http", "loopback", "headers-unreadable"]);
|
||||
export const DevicePairingUnavailableReasonSchema = z.enum([
|
||||
"untrusted-origin",
|
||||
"loopback",
|
||||
"insecure-origin",
|
||||
]);
|
||||
|
||||
export const DevicePairingAvailabilitySchema = z.object({
|
||||
available: z.boolean(),
|
||||
reason: DevicePairingUnavailableReasonSchema.nullable(),
|
||||
message: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const CreateDevicePairingLinksRequestSchema = z.object({
|
||||
name: z.string().trim().min(1).max(100).optional(),
|
||||
@@ -170,6 +181,8 @@ export type RedeemDevicePairingCodeRequest = z.infer<typeof RedeemDevicePairingC
|
||||
export type RedeemDevicePairingCodeResponse = z.infer<typeof RedeemDevicePairingCodeResponseSchema>;
|
||||
export type AppLinkBlockedReason = z.infer<typeof AppLinkBlockedReasonSchema>;
|
||||
export type DevicePairingLinkWarning = z.infer<typeof DevicePairingLinkWarningSchema>;
|
||||
export type DevicePairingUnavailableReason = z.infer<typeof DevicePairingUnavailableReasonSchema>;
|
||||
export type DevicePairingAvailability = z.infer<typeof DevicePairingAvailabilitySchema>;
|
||||
export type CreateDevicePairingLinksRequest = z.infer<typeof CreateDevicePairingLinksRequestSchema>;
|
||||
export type DevicePairingLinksResponse = z.infer<typeof DevicePairingLinksResponseSchema>;
|
||||
export type PairedDevice = z.infer<typeof PairedDeviceSchema>;
|
||||
|
||||
Reference in new issue
Block a user