feat(web): zero-input pairing, a real QR, and no scanner or scopes

The console side of ADR 0001: a scanned link pairs itself, the status page
draws the daemon's actual symbol, and the second entry point for pairing
(the in-page camera scanner) is gone.

- `POST /api/v1/pair/redeem` replaced the dual-purpose `/api/v1/pair`; the
  redeem response is parsed strictly as `{token, device}` (the five-layer
  alias fallbacks for `deviceToken`/`payload.device`/… are deleted).
- `features/status/qr.ts` no longer invents "a deterministic fake QR from a
  seed" — it renders `pairCode.qr.rows` module by module (devicePixelRatio
  aware, square, token colours, redraws on theme/resize), and a mint without a
  matrix shows the link instead of a pattern that will not scan.
- `/pair/<CODE>` (daemon 302 or the SPA route) lands on
  `/connect?code=…&auto=1`, which redeems against its own origin with the
  localized device name and then navigates to `next`/`/workspaces`, dropping
  the code from the URL; a rejected code falls back to the prefilled form.
- The camera scanner (`features/connect/scan-dialog.tsx`) and its i18n keys are
  removed: phones scan with the system camera, desktops type the code. Paste a
  `pi2://pair?…` link or `/pair/CODE` still fills the form.
- Scope tracking disappears from the store, API types, device list and pairing
  metadata (`pi2-device-scopes` is no longer written or read).
- Stale default removed: link parsing falls back to the served origin's port,
  then 443/80, instead of a hard-coded 4321.
- `scripts/ui-{fixtures,mock-server,shots}.mjs` follow the new contract
  (mint carries `qr`/`bases`, redeem route, no scopes), so the visual harness
  exercises the real flow.

Verification: web typecheck clean, 299/299 tests, `vite build` green, visual
matrix 24/24 clean, and the i18n catalog has no missing keys.
This commit is contained in:
yuez committed 2026-10-27 10:44:54 +08:00
1 parent a57c874095
commit 3e35fb7ef3
20 files changed
+419 -946

No files matched your search

+56 -3
View File
@@ -7,7 +7,7 @@ import { Field, Input } from "@/components/ui/input";
import { toast } from "@/components/ui/toast";
import { ApiError, errorI18nKey } from "@/lib/api";
import { PAIR_CODE_LENGTH, isPairCode, normalizePairCode, parseEndpoint } from "./pairing";
import { PAIR_CODE_LENGTH, isPairCode, normalizePairCode, parseEndpoint, parsePairLink } from "./pairing";
export interface ManualConnectInput {
endpoint: string;
@@ -61,6 +61,8 @@ export function ManualConnectForm({
}: ManualConnectFormProps) {
const { t } = useTranslation();
const id = useId();
const [link, setLink] = useState("");
const [linkError, setLinkError] = useState<string | null>(null);
const [host, setHost] = useState(() => initialHost ?? "");
const [port, setPort] = useState(() => initialPort ?? defaultPort);
const [code, setCode] = useState(() => normalizePairCode(initialCode ?? ""));
@@ -93,7 +95,24 @@ export function ManualConnectForm({
setCodeError(null);
setFormError(null);
const parsed = parseEndpoint(host, port);
// 整段粘贴的配对链接(`pi2://pair?…` / `…/pair/CODE`)先拆成地址 + 端口 + 配对码,
// 拆不出内容时留在链接输入框上报错。
const pastedLink = parsePairLink(link) ?? parsePairLink(host);
if (link.trim() && !parsePairLink(link)) {
setLinkError(t("connect.invalidLink"));
return;
}
setLinkError(null);
const hostValue = pastedLink ? pastedLink.hostname : host;
const portValue = pastedLink ? String(pastedLink.port) : port;
const codeValue = pastedLink ? pastedLink.code : code;
if (pastedLink) {
setHost(pastedLink.hostname);
setPort(String(pastedLink.port));
setCode(pastedLink.code);
}
const parsed = parseEndpoint(hostValue, portValue);
if ("error" in parsed) {
if (parsed.error === "host") {
setHostError(t("connect.hostRequired"));
@@ -110,7 +129,7 @@ export function ManualConnectForm({
return;
}
const normalized = normalizePairCode(code);
const normalized = normalizePairCode(codeValue);
if (!normalized) {
setCodeError(t("connect.pairCodeRequired"));
return;
@@ -141,6 +160,40 @@ export function ManualConnectForm({
return (
<div className="cn-manual" id={formId} hidden={!expanded} data-testid="connect-manual-panel">
<form className="cn-form" noValidate onSubmit={(event) => void submit(event)}>
<Field
label={t("connect.pairingLink")}
htmlFor={`${id}-link`}
hint={t("connect.pasteHint", { defaultValue: "Paste the link from the QR code" })}
error={linkError}
>
<Input
id={`${id}-link`}
data-testid="connect-link"
type="text"
inputMode="url"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
placeholder={t("connect.pastePlaceholder")}
value={link}
onChange={(event) => {
const text = event.target.value;
setLink(text);
setLinkError(null);
// 能解析就立即回填,用户只需再按一次连接。
const target = parsePairLink(text);
if (!target) return;
setHost(target.hostname);
setPort(String(target.port));
setCode(target.code);
portEdited.current = true;
setHostError(null);
setPortError(null);
setCodeError(null);
}}
/>
</Field>
<div className="cn-row">
<Field label={t("connect.host")} htmlFor={`${id}-host`} error={hostError}>
<Input
+15 -51
View File
@@ -2,21 +2,16 @@ import { ApiError, apiRequest, type InfoResponse } from "@/lib/api";
import { NEXT_FALLBACK, safeNext } from "@/lib/routing";
export const PAIR_META_KEY = "pi2-pair-meta";
export const PAIR_SCOPES = ["read", "steer", "apply"] as const;
/** Public redeem endpoint: no bearer token required (docs/protocol.md §3.2). */
export const PAIR_REDEEM_PATH = "/api/v1/pair";
export const PAIR_REDEEM_PATH = "/api/v1/pair/redeem";
/** The daemon mints 8-character uppercase alphanumeric pairing codes. */
export const PAIR_CODE_LENGTH = 8;
export const PAIR_CODE_PATTERN = /^[A-Z0-9]{8}$/;
export const DEFAULT_PAIR_PORT = 4321;
/** Scope assumed when a paired device did not report any (older daemons). */
export const DEFAULT_DEVICE_SCOPES = ["read"] as const;
export type DeviceKind = "phone" | "laptop" | "tablet";
export interface PairMeta {
scopes: string[];
deviceName?: string;
kind?: DeviceKind;
server?: Partial<InfoResponse> & { name?: string; hostname?: string; version?: string; pluginVersion?: string };
@@ -33,12 +28,9 @@ export interface PairTarget {
export interface RedeemResult {
token: string;
scopes: string[];
deviceId?: string;
deviceName?: string;
kind?: DeviceKind;
server?: PairMeta["server"];
raw: unknown;
}
export interface ParsedEndpoint {
@@ -59,9 +51,6 @@ function firstString(...values: unknown[]): string | undefined {
return undefined;
}
function stringList(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
}
/**
* Uppercase and drop everything that is not `[A-Z0-9]` — pairing codes are
@@ -180,7 +169,9 @@ function parsePi2PairLink(text: string, fallbackEndpoint?: string | null): PairT
const hostParam = firstString(params.get("host"), params.get("hostname"), params.get("endpoint"));
const proto = firstString(params.get("proto"), params.get("protocol"))?.toLowerCase();
const portParam = firstString(params.get("port")) ?? String(DEFAULT_PAIR_PORT);
// A link without a port resolves against the port this console was served
// from, falling back to the scheme default — never a literal.
const portParam = firstString(params.get("port")) ?? defaultPairPort(proto === "https" ? "https" : "http");
let target: ParsedEndpoint | null = null;
if (hostParam) {
@@ -190,7 +181,7 @@ function parsePi2PairLink(text: string, fallbackEndpoint?: string | null): PairT
target = "error" in parsed ? null : parsed;
}
// A pi2:// link without a host only makes sense against a known endpoint
// (the scan dialog passes the stored one); never guess from the browser origin.
// (the caller passes the stored one); never guess from the browser origin.
target ??= endpointFrom(fallbackEndpoint);
if (!target) return null;
@@ -257,13 +248,14 @@ export function pairingOrigin(endpoint: string): string {
.replace(/\/+$/, "");
}
function normalizeScopes(values: string[]): string[] {
const unique = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
return unique.length ? unique : [...DEFAULT_DEVICE_SCOPES];
/** Port this console was served from, else the scheme default (`443`/`80`). */
function defaultPairPort(protocol: "http" | "https"): string {
if (typeof window !== "undefined" && window.location.port) return window.location.port;
return protocol === "https" ? "443" : "80";
}
/**
* Redeem a pairing code against the public `POST <origin>/api/v1/pair`
* Redeem a pairing code against the public `POST <origin>/api/v1/pair/redeem`
* endpoint: `{code,kind,deviceName}` → `{token,device}`.
*/
export async function redeemPairing(input: {
@@ -286,13 +278,10 @@ export async function redeemPairing(input: {
signal: input.signal,
});
const payload = asRecord(response.payload);
const result = asRecord(response.result);
// 文档契约只有 `{token,device:{id,name,kind}}`,不再兜底历史别名。
const body = asRecord(response) ?? {};
const device =
asRecord(body.device) ?? asRecord(result?.device) ?? asRecord(payload?.device) ?? asRecord(payload);
// `{token,device}` is the documented shape; keep the older aliases as a fallback.
const token = firstString(body.token, body.deviceToken, device?.token, result?.token, payload?.token);
const device = asRecord(body.device);
const token = firstString(body.token);
if (!token) {
throw new ApiError({
code: "E_UNAUTHORIZED",
@@ -301,22 +290,11 @@ export async function redeemPairing(input: {
});
}
const scopes = normalizeScopes([
...stringList(body.scopes),
...stringList(device?.scopes),
...stringList(result?.scopes),
]);
return {
token,
scopes,
deviceId: firstString(device?.id, body.deviceId, device?.deviceId, result?.deviceId),
deviceName: firstString(device?.name, deviceName),
deviceId: firstString(device?.id),
deviceName: firstString(device?.name) ?? deviceName,
kind: (firstString(device?.kind) as DeviceKind | undefined) ?? kind,
server:
(asRecord(body.server) as PairMeta["server"] | undefined) ??
(asRecord(result?.server) as PairMeta["server"] | undefined),
raw: response,
};
}
@@ -328,7 +306,6 @@ export function readPairMeta(): PairMeta | null {
const record = asRecord(parsed);
if (!record) return null;
return {
scopes: stringList(record.scopes),
deviceName: typeof record.deviceName === "string" ? record.deviceName : undefined,
kind: record.kind === "phone" || record.kind === "laptop" || record.kind === "tablet" ? record.kind : undefined,
server: asRecord(record.server) as PairMeta["server"] | undefined,
@@ -362,16 +339,3 @@ export function clearPairMeta(): void {
export function safePairNext(raw: string | null | undefined): string {
return safeNext(raw, NEXT_FALLBACK);
}
/** Ordered scope list for the paired summary: stored device scopes win over /info capabilities. */
export function scopesForIdentity(
meta: PairMeta | null,
info: InfoResponse | null | undefined,
storedScopes?: string[] | null,
): string[] {
if (storedScopes?.length) return storedScopes;
if (meta?.scopes.length) return meta.scopes;
const capabilities = Array.isArray(info?.capabilities) ? info.capabilities : [];
const derived = capabilities.filter((capability) => (PAIR_SCOPES as readonly string[]).includes(capability));
return derived.length ? derived : [...DEFAULT_DEVICE_SCOPES];
}
-252
View File
@@ -1,252 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { parsePairLink, type PairTarget } from "./pairing";
interface DetectedBarcode {
rawValue?: string;
}
interface BarcodeDetectorLike {
detect(source: CanvasImageSource): Promise<DetectedBarcode[]>;
}
type BarcodeDetectorCtor = new (options?: { formats?: string[] }) => BarcodeDetectorLike;
function barcodeDetectorCtor(): BarcodeDetectorCtor | undefined {
return (window as unknown as { BarcodeDetector?: BarcodeDetectorCtor }).BarcodeDetector;
}
export interface ScanDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onFound: (target: PairTarget) => void;
fallbackEndpoint?: string | null;
}
/**
* Camera preview + BarcodeDetector loop, with the design's paste-link fallback
* whenever the browser, permission or secure context cannot scan.
*/
export function ScanDialog({ open, onOpenChange, onFound, fallbackEndpoint }: ScanDialogProps) {
const { t } = useTranslation();
const [attempt, setAttempt] = useState(0);
const [live, setLive] = useState(false);
const [status, setStatus] = useState("");
const [pasteOpen, setPasteOpen] = useState(false);
const [paste, setPaste] = useState("");
const [pasteInvalid, setPasteInvalid] = useState(false);
const videoRef = useRef<HTMLVideoElement | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const detectorRef = useRef<BarcodeDetectorLike | null>(null);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const finishingRef = useRef(false);
useEffect(() => {
if (!open) return;
let cancelled = false;
finishingRef.current = false;
setPasteOpen(false);
setPasteInvalid(false);
setStatus(t("connect.startingCamera"));
function stopCamera() {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
const stream = streamRef.current;
if (stream) {
for (const track of stream.getTracks()) track.stop();
streamRef.current = null;
}
detectorRef.current = null;
if (videoRef.current) videoRef.current.srcObject = null;
setLive(false);
}
function finish(raw: string) {
const target = parsePairLink(raw, fallbackEndpoint);
if (!target) {
setPasteInvalid(true);
setStatus(t("connect.invalidLink"));
setPasteOpen(true);
return;
}
if (finishingRef.current) return;
finishingRef.current = true;
stopCamera();
onFound(target);
onOpenChange(false);
}
async function scanFrame() {
if (cancelled || finishingRef.current) return;
const detector = detectorRef.current;
const video = videoRef.current;
if (!detector || !video) return;
try {
const codes = await detector.detect(video);
const raw = codes[0]?.rawValue;
if (raw) finish(raw);
} catch {
/* a single failed frame should not stop the loop */
}
}
async function startCamera() {
stopCamera();
if (!window.isSecureContext) {
setStatus(t("connect.secureRequired"));
setPasteOpen(true);
return;
}
if (!navigator.mediaDevices?.getUserMedia) {
setStatus(t("connect.cameraUnsupported"));
setPasteOpen(true);
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: { facingMode: { ideal: "environment" } },
});
if (cancelled) {
for (const track of stream.getTracks()) track.stop();
return;
}
streamRef.current = stream;
const video = videoRef.current;
if (video) {
video.srcObject = stream;
await video.play().catch(() => undefined);
}
setLive(true);
const Ctor = barcodeDetectorCtor();
if (Ctor) {
try {
detectorRef.current = new Ctor({ formats: ["qr_code"] });
} catch {
detectorRef.current = null;
}
}
if (detectorRef.current) {
setStatus(t("connect.aim"));
timerRef.current = setInterval(() => void scanFrame(), 300);
} else {
setStatus(t("connect.noAutoDetect"));
setPasteOpen(true);
}
} catch (error) {
const denied =
error instanceof DOMException &&
(error.name === "NotAllowedError" || error.name === "SecurityError");
setStatus(t(denied ? "connect.permissionDenied" : "connect.cameraFailed"));
setPasteOpen(true);
}
}
void startCamera();
return () => {
cancelled = true;
stopCamera();
};
}, [attempt, fallbackEndpoint, onFound, onOpenChange, open, t]);
function identify() {
const target = parsePairLink(paste, fallbackEndpoint);
if (!target) {
setPasteInvalid(true);
setStatus(t("connect.invalidLink"));
setPasteOpen(true);
return;
}
setPasteInvalid(false);
onFound(target);
onOpenChange(false);
}
return (
<Modal
open={open}
onOpenChange={onOpenChange}
title={t("connect.scanTitle")}
size="wide"
footer={
<Button variant="ghost" onClick={() => onOpenChange(false)}>
{t("common.close")}
</Button>
}
>
<div className="cn-scan">
<div className={live ? "cn-scan__viewport is-live" : "cn-scan__viewport"}>
<video
ref={videoRef}
className="cn-scan__video"
autoPlay
playsInline
muted
aria-label={t("connect.cameraPreview")}
/>
<div className="cn-scan__placeholder">
<span className="cn-ico">
<Icon name="scan" size={28} />
</span>
<span>{t("connect.cameraPreview")}</span>
</div>
<div className="cn-scan__frame" aria-hidden="true" />
</div>
<div className="cn-scan__state" role="status" aria-live="polite">
{status}
</div>
<p className="cn-hint">{t("connect.scanHint")}</p>
<details
className="cn-fold"
open={pasteOpen}
onToggle={(event) => setPasteOpen(event.currentTarget.open)}
>
<summary>{t("connect.cantScan")}</summary>
<div className="cn-fold__body">
<Input
type="text"
autoComplete="off"
spellCheck={false}
className={pasteInvalid ? "is-invalid" : undefined}
placeholder={t("connect.pastePlaceholder")}
aria-label={t("connect.pairingLink")}
value={paste}
onChange={(event) => {
setPaste(event.target.value);
setPasteInvalid(false);
}}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
event.preventDefault();
identify();
}
}}
/>
<Button variant="primary" onClick={identify}>
{t("connect.identify")}
</Button>
</div>
</details>
<div className="cn-scan__actions">
<Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}>
<Icon name="refresh" />
{t("connect.retryCamera")}
</Button>
</div>
</div>
</Modal>
);
}
+38 -30
View File
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { KV } from "@/components/ui/kv";
import { toast } from "@/components/ui/toast";
@@ -54,28 +53,42 @@ function Address({ label, value }: { label: string; value: string }) {
);
}
function QrCanvas({ seed, label }: { seed: string; label: string }) {
/**
* 画 daemon 下发的真矩阵:`rows` 每行一串 `0`/`1`。主题切换和容器缩放时重绘。
*/
function QrCanvas({ rows, label }: { rows: string[]; label: string }) {
const ref = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = ref.current;
if (!canvas) return;
const draw = () => drawQr(canvas, seed);
const draw = () => drawQr(canvas, rows);
draw();
if (typeof MutationObserver === "undefined") return;
const observer = new MutationObserver(draw);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
return () => observer.disconnect();
}, [seed]);
window.addEventListener("resize", draw);
const observer =
typeof MutationObserver === "undefined" ? null : new MutationObserver(draw);
observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
return () => {
window.removeEventListener("resize", draw);
observer?.disconnect();
};
}, [rows]);
return <canvas ref={ref} className="qr-canvas" role="img" aria-label={label} />;
return (
<canvas
ref={ref}
className="qr-canvas"
role="img"
aria-label={label}
data-qr-size={rows.length}
/>
);
}
export interface ConnectionCardProps {
server: ServerIdentity;
deviceName: string;
scopes: string[];
connectedAt: number | null;
loading: boolean;
error: string | null;
@@ -95,15 +108,14 @@ export function pairMinutesLeft(expiresAt: number | null | undefined, now = Date
}
/**
* Card 7 — two internal columns: addresses / mDNS / endpoint / device / scopes
* / pairing code / security notes on the left, the square QR with the pairing
* hint and the expiry on the right. Both actions are non-primary (the status
* page carries 0 primary buttons).
* Card 7 — two internal columns: addresses / mDNS / endpoint / device / pairing
* code / security notes on the left, the QR with the pairing hint and the expiry
* on the right. Both actions are non-primary (the status page carries 0 primary
* buttons).
*/
export function ConnectionCard({
server,
deviceName,
scopes,
connectedAt,
loading,
error,
@@ -117,7 +129,10 @@ export function ConnectionCard({
const { t } = useTranslation();
const [confirmOpen, setConfirmOpen] = useState(false);
const code = String(pairCode?.code ?? "").trim();
const url = String(pairCode?.url ?? "").trim() || (code ? `${server.networkAddress}/#pair=${code}` : "");
// URL 由 daemon 决定(mint 时选好 base),客户端不再拼接。
const url = String(pairCode?.url ?? "").trim();
/** 真矩阵;URL 过长时 daemon 不下发 `qr`,此时只展示可点/可拷的链接。 */
const qrRows = Array.isArray(pairCode?.qr?.rows) ? pairCode.qr.rows : [];
const minutes = pairMinutesLeft(pairCode?.expiresAt);
return (
@@ -146,19 +161,6 @@ export function ConnectionCard({
<CopyButton value={server.endpoint} label={t("connect.endpoint")} />
</KV>
<KV label={t("connect.device")}>{deviceName || "—"}</KV>
<KV label={t("status.tokenScopes")} valueClassName="status-scopes__wrap">
{scopes.length ? (
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} className="badge--outline">
{scope}
</Badge>
))}
</span>
) : (
<span className="faint">—</span>
)}
</KV>
<KV label={t("status.lastConnected")}>
<RelativeTime ts={connectedAt} />
</KV>
@@ -192,7 +194,13 @@ export function ConnectionCard({
<div className="conn-right">
<div className="qr-wrap">
{code ? <QrCanvas seed={url || code} label={t("status.qrAria")} /> : null}
{qrRows.length ? (
<QrCanvas rows={qrRows} label={t("status.qrAria")} />
) : url ? (
<code className="qr-link mono" data-testid="pair-url">
{url}
</code>
) : null}
<div className="pair-hint faint">
<Icon name="phone" />
<span>{t("status.pairHint")}</span>
+2 -12
View File
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@/components/icons";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import type { DeviceEntry } from "@/features/status/queries";
@@ -34,7 +33,7 @@ export interface DevicesCardProps {
onRevoke: (device: DeviceEntry) => Promise<void>;
}
/** Card 6 — paired devices with kind icon, scopes, last active and confirm-revoke. */
/** Card 6 — paired devices with kind icon, last active and confirm-revoke. */
export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: DevicesCardProps) {
const { t } = useTranslation();
const [target, setTarget] = useState<DeviceEntry | null>(null);
@@ -61,7 +60,6 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
) : (
<div className="device-list">
{visible.map((device) => {
const scopes = Array.isArray(device.scopes) ? device.scopes : [];
return (
<div className="device-row" key={deviceKey(device)} data-device-id={deviceKey(device)}>
<span className="device-icon">
@@ -69,15 +67,7 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
</span>
<div className="grow device-main">
<div className="device-name truncate">{device.name}</div>
<div className="device-meta">
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} className="badge--outline">
{scope}
</Badge>
))}
</span>
</div>
<div className="device-meta faint">{device.kind}</div>
</div>
<span className="device-time faint">
<RelativeTime ts={deviceLastActive(device)} />
+54 -30
View File
@@ -1,9 +1,32 @@
/**
* Port of the prototype's `App.drawQR`: a deterministic fake QR derived from a
* seed string. Colors come from the design tokens only, so a theme switch
* redraws the same pattern with the dark surfaces.
* Renders the daemon's real QR matrix (`pairCode.qr.rows`, one `"0"`/`"1"`
* string per row) into a square canvas.
*
* 渲染要点:
* - `rows` 已是去掉静区的模块矩阵,渲染器自己负责留白和颜色;
* - 按 devicePixelRatio 放大位图(避免糊),CSS 宽度自适应容器且最多 200px;
* - 颜色只取 token:前景 `--foreground`、底色 `--card`,主题切换后重绘;
* - `rows` 为空或不是方阵时清空画布(不画任何占位图)。
*/
export function drawQr(canvas: HTMLCanvasElement, seed: string): void {
/** Upper bound of the CSS square; the container may be narrower. */
export const QR_MAX_CSS_SIZE = 200;
/** Quiet zone in modules, drawn on the card background. */
const QUIET_MODULES = 3;
function cssSize(canvas: HTMLCanvasElement): number {
const parent = canvas.parentElement;
const available = parent?.clientWidth || canvas.clientWidth || QR_MAX_CSS_SIZE;
return Math.max(0, Math.min(QR_MAX_CSS_SIZE, available));
}
function isMatrix(rows: string[]): boolean {
const size = rows.length;
if (!size) return false;
return rows.every((row) => typeof row === "string" && row.length === size && /^[01]+$/.test(row));
}
export function drawQr(canvas: HTMLCanvasElement, rows: string[]): void {
let context: CanvasRenderingContext2D | null = null;
try {
context = canvas.getContext("2d");
@@ -12,41 +35,42 @@ export function drawQr(canvas: HTMLCanvasElement, seed: string): void {
}
if (!context) return;
const n = 25;
const cell = 8;
canvas.width = n * cell;
canvas.height = n * cell;
// 空矩阵:清掉上一张码,不留伪图案。
if (!isMatrix(rows)) {
canvas.width = 0;
canvas.height = 0;
context.clearRect(0, 0, canvas.width, canvas.height);
return;
}
const size = rows.length;
const dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
const css = Math.round(cssSize(canvas)) || QR_MAX_CSS_SIZE;
canvas.width = Math.round(css * dpr);
canvas.height = Math.round(css * dpr);
const styles = getComputedStyle(document.documentElement);
const cardColor = styles.getPropertyValue("--card").trim() || "transparent";
const foregroundColor = styles.getPropertyValue("--foreground").trim() || "currentColor";
// 静区 + 模块网格都按 devicePixelRatio 缩放,保持正方形。
const total = size + QUIET_MODULES * 2;
const module = canvas.width / total;
context.fillStyle = cardColor;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = foregroundColor;
let state = 0;
for (const char of seed) state = (state * 31 + char.charCodeAt(0)) >>> 0;
const random = () => {
state = (state * 1103515245 + 12345) >>> 0;
return state / 4294967296;
};
const finder = (x: number, y: number) => {
context?.fillRect(x * cell, y * cell, 7 * cell, 7 * cell);
context?.clearRect((x + 1) * cell, (y + 1) * cell, 5 * cell, 5 * cell);
context?.fillRect((x + 2) * cell, (y + 2) * cell, 3 * cell, 3 * cell);
if (context) context.fillStyle = foregroundColor;
};
for (let y = 0; y < n; y += 1) {
for (let x = 0; x < n; x += 1) {
const inFinder = (x < 8 && y < 8) || (x > n - 9 && y < 8) || (x < 8 && y > n - 9);
if (!inFinder && random() > 0.52) context.fillRect(x * cell, y * cell, cell, cell);
for (let y = 0; y < size; y += 1) {
const row = rows[y] ?? "";
for (let x = 0; x < size; x += 1) {
if (row[x] !== "1") continue;
// 取整像素边界,避免相邻模块间的缝。
const left = Math.round((x + QUIET_MODULES) * module);
const top = Math.round((y + QUIET_MODULES) * module);
const right = Math.round((x + QUIET_MODULES + 1) * module);
const bottom = Math.round((y + QUIET_MODULES + 1) * module);
context.fillRect(left, top, right - left, bottom - top);
}
}
finder(0, 0);
finder(n - 7, 0);
finder(0, n - 7);
}
+6 -4
View File
@@ -20,7 +20,6 @@ export interface DeviceEntry {
deviceId?: string;
name: string;
kind: string;
scopes: string[];
/** `lastSeenAt` is the daemon field; `lastActiveAt` came from older builds. */
lastActiveAt?: number | null;
lastSeenAt?: number | null;
@@ -52,9 +51,10 @@ export async function fetchModels(workspaceId: string, signal?: AbortSignal): Pr
}
/**
* `/api/v1/pair` is public for redemption (`{code,…}`) and *authenticated* for
* minting: an authenticated `POST` with no `code` returns
* `{accepted,code,url,expiresAt,nonce}` (docs/protocol.md §3.2).
* `POST /api/v1/pair` is authenticated and mints a code:
* `{accepted,code,url,expiresAt,nonce,qr,bases}`, where `qr` carries the opaque
* matrix (version 1–10, EC level M, no quiet zone) and is absent when the URL
* is too long to encode (docs/protocol.md §3.2).
*/
export interface PairCodeResponse {
accepted?: boolean;
@@ -62,6 +62,8 @@ export interface PairCodeResponse {
url?: string;
expiresAt?: number;
nonce?: string;
qr?: { version: number; ecc: string; mask: number; size: number; rows: string[] };
bases?: { kind: string; name: string; address: string; url: string }[];
}
/** Pairing codes are short-lived; 10 minutes matches `auth.pairCreate`'s default. */