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
This commit is contained in:
Chris Scott committed 2026-10-24 19:26:21 -04:00
1 parent 5b0e629182
commit f8e4cfe136
79 files changed
+5398 -110

No files matched your search

+87 -18
View File
@@ -1,4 +1,9 @@
import { z } from "zod";
import {
DevicePairingCodeSchema,
RemoteAccessHeaderListSchema,
formatRemoteAccessHeaderParam,
} from "./device-pairing";
export const LOCAL_OPENCODE_SERVER_ID = "local";
export const OPENCODE_SERVER_USERNAME = "opencode";
@@ -77,6 +82,14 @@ export const OpenCodeServerLinkSchema = z.object({
pairing: OpenCodeServerPairingSchema,
});
export const ManagerAppLinkSchema = z.object({
kind: z.literal("manager"),
name: z.string().trim().min(1).max(100),
baseUrl: HttpUrlSchema,
code: DevicePairingCodeSchema,
headers: RemoteAccessHeaderListSchema,
});
export type OpenCodeServer = z.infer<typeof OpenCodeServerSchema>;
export type OpenCodeServerPairing = z.infer<typeof OpenCodeServerPairingSchema>;
export type CreateOpenCodeServerRequest = z.input<typeof CreateOpenCodeServerRequestSchema>;
@@ -85,33 +98,42 @@ export type TestOpenCodeServerRequest = z.input<typeof TestOpenCodeServerRequest
export type OpenCodeServerTestResult = z.infer<typeof OpenCodeServerTestResultSchema>;
export type OpenCodeServerStatus = z.infer<typeof OpenCodeServerStatusSchema>;
export type OpenCodeServerLink = z.infer<typeof OpenCodeServerLinkSchema>;
export type ManagerAppLink = z.infer<typeof ManagerAppLinkSchema>;
/** Builds the `ocm://link` URL encoded into a pairing QR code. */
export function buildOpenCodeServerLink(link: OpenCodeServerLink): string {
const params = new URLSearchParams({
v: OPENCODE_SERVER_LINK_VERSION,
kind: link.kind,
name: link.name,
url: link.baseUrl,
pair: link.pairing.pairUrl,
code: link.pairing.code,
});
return `${OPENCODE_SERVER_LINK_PROTOCOL}//link?${params.toString()}`;
const params = buildLinkParams(link);
params.set("pair", link.pairing.pairUrl);
params.set("code", link.pairing.code);
return buildLinkUrl(params);
}
/** Parses an `ocm://link` URL from a QR code or pasted text; returns null when it is not a valid link. */
export function parseOpenCodeServerLink(text: string): OpenCodeServerLink | null {
const url = parseOpenCodeServerLinkUrl(text);
if (!url) return null;
if (url.searchParams.get("v") !== OPENCODE_SERVER_LINK_VERSION) return null;
const parsed = OpenCodeServerLinkSchema.safeParse({
kind: url.searchParams.get("kind"),
name: url.searchParams.get("name"),
baseUrl: url.searchParams.get("url"),
return readLink(OpenCodeServerLinkSchema, text, (url) => ({
pairing: { pairUrl: url.searchParams.get("pair"), code: url.searchParams.get("code") },
}));
}
/** Builds the `ocm://link` URL for a manager app pairing QR code, including remote-access headers. */
export function buildManagerAppLink(link: ManagerAppLink): string {
const params = buildLinkParams(link);
params.set("code", link.code);
for (const header of link.headers) params.append("h", formatRemoteAccessHeaderParam(header));
return buildLinkUrl(params);
}
/** Parses an `ocm://link` manager app link; returns null when it is not a valid manager link. */
export function parseManagerAppLink(text: string): ManagerAppLink | null {
return readLink(ManagerAppLinkSchema, text, (url) => {
const headers: Array<{ name: string; value: string }> = [];
for (const raw of url.searchParams.getAll("h")) {
const separator = raw.indexOf(":");
if (separator < 0) return null;
headers.push({ name: raw.slice(0, separator), value: raw.slice(separator + 1) });
}
return { headers };
});
return parsed.success ? parsed.data : null;
}
/** Reads the `v` parameter of an `ocm://link` URL, or null when the text is not an `ocm://link` URL. */
@@ -130,6 +152,53 @@ function parseOpenCodeServerLinkUrl(text: string): URL | null {
return url;
}
type LinkQueryFields = {
kind: string | null;
name: string | null;
baseUrl: string | null;
code: string | null;
};
function buildLinkParams(link: { kind: string; name: string; baseUrl: string }): URLSearchParams {
return new URLSearchParams({
v: OPENCODE_SERVER_LINK_VERSION,
kind: link.kind,
name: link.name,
url: link.baseUrl,
});
}
function buildLinkUrl(params: URLSearchParams): string {
return `${OPENCODE_SERVER_LINK_PROTOCOL}//link?${params.toString()}`;
}
function readLinkQueryFields(text: string): { url: URL; fields: LinkQueryFields } | null {
const url = parseOpenCodeServerLinkUrl(text);
if (!url || url.searchParams.get("v") !== OPENCODE_SERVER_LINK_VERSION) return null;
return {
url,
fields: {
kind: url.searchParams.get("kind"),
name: url.searchParams.get("name"),
baseUrl: url.searchParams.get("url"),
code: url.searchParams.get("code"),
},
};
}
function readLink<T>(
schema: z.ZodType<T>,
text: string,
readDetails: (url: URL) => Record<string, unknown> | null,
): T | null {
const link = readLinkQueryFields(text);
if (!link) return null;
const details = readDetails(link.url);
if (!details) return null;
const parsed = schema.safeParse({ ...link.fields, ...details });
return parsed.success ? parsed.data : null;
}
const REMOTE_DIRECTORY_KEY_PATTERN = /^(srv_[A-Za-z0-9_-]+)\|(.+)$/s;
/** Builds the event-stream subscription key for a directory; local directories stay unchanged. */