Files
opencode-manager/backend/test/helpers/websocket-server.ts
Chris Scott f8e4cfe136 feat(device-pairing): pair phones and browsers with a QR code
Settings -> Account gets "Connect a device", a paired-devices list, and a
remote access headers editor, so the mobile app and other browsers can sign
in without typing a password and pass a reverse proxy such as Cloudflare
Access.

- one-time pairing codes (3 min TTL) minted by a Better Auth plugin and
  redeemed into a new session that records the device name
- POST /api/device-pairing/links builds the ocm://link app link with the
  stored headers as h= parameters and a browser /pair link; plain-HTTP and
  loopback origins are blocked or warned about
- remote access headers are stored encrypted, returned by name only, and
  validated (8 headers, 512-char values, 1800 encoded characters, reserved
  transport names blocked); a Cloudflare Access service token preset fills
  CF-Access-Client-Id and CF-Access-Client-Secret
- login offers "Sign in with QR code" and /pair redeems a scanned code,
  returning to the login redirect target
- revoking a device deletes its session, closes its live connections and
  removes its push subscriptions; the current session cannot be revoked
2026-10-24 19:26:21 -04:00

44 lines
1.6 KiB
TypeScript

import type { Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { Hono } from 'hono'
import type { UpgradeWebSocket } from 'hono/ws'
import { serve } from '@hono/node-server'
import { createNodeWebSocket } from '@hono/node-ws'
export interface StartWebSocketServerOptions {
app: Hono<any, any, any>
register?: (app: Hono, upgradeWebSocket: UpgradeWebSocket) => void
injectWebSocket?: (server: Server) => void
}
export interface WebSocketTestServer {
server: Server
port: number
close: () => Promise<void>
}
/**
* Starts a Hono app on an ephemeral loopback port with WebSocket upgrades wired in.
* Creates its own node WebSocket binding unless the caller passes an existing `injectWebSocket`.
*/
export async function startWebSocketServer(options: StartWebSocketServerOptions): Promise<WebSocketTestServer> {
const owned = options.injectWebSocket ? undefined : createNodeWebSocket({ app: options.app })
if (owned && options.register) {
options.register(options.app, owned.upgradeWebSocket)
}
const server = await new Promise<Server>((resolve) => {
const started = serve({ fetch: options.app.fetch, port: 0, hostname: '127.0.0.1' }, () => resolve(started)) as unknown as Server
})
const injectWebSocket = options.injectWebSocket ?? owned?.injectWebSocket
if (!injectWebSocket) throw new Error('startWebSocketServer could not resolve an injectWebSocket')
injectWebSocket(server)
return {
server,
port: (server.address() as AddressInfo).port,
close: () => {
server.closeAllConnections()
return new Promise((resolve) => server.close(() => resolve()))
},
}
}