feat: QR code phone pairing for Decky plugin + MangoHud guide revision + SteamOS version fix

- Add plugin_pairings table + migration (0028) for short-lived pairing sessions
- Add pairing API: POST /api/plugin/pair/initiate, GET /status/:token, POST /confirm
- Add /pair web page: user scans QR on phone, confirms, API key auto-created
- Plugin: 'Pair with Phone' button renders QR code (qrcode.react), polls for status, saves API key
- Plugin: new initiate_pair + check_pair_status Python RPCs
- Revise MangoHud Setup Guide into clean numbered steps
- Fix SteamOS version detection: read VERSION_ID + BUILD_ID (was just 'SteamOS')
This commit is contained in:
2026-06-28 22:09:39 +08:00
parent b637b55011
commit 1de08ed4ec
12 changed files with 3588 additions and 18 deletions
+291
View File
@@ -0,0 +1,291 @@
"use client"
import { useState, useEffect, Suspense } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import Link from "next/link"
import { useSession } from "@/lib/auth-client"
import {
QrCodeIcon,
CheckCircle2,
Loader2,
AlertCircle,
Gamepad2,
ShieldCheck,
ArrowRight,
} from "lucide-react"
import { motion } from "motion/react"
function PairContent() {
const searchParams = useSearchParams()
const router = useRouter()
const token = searchParams.get("token")
const { data: session, isPending } = useSession()
const [status, setStatus] = useState<"idle" | "confirming" | "success" | "error">("idle")
const [error, setError] = useState<string | null>(null)
const [checkedToken, setCheckedToken] = useState(false)
const [tokenValid, setTokenValid] = useState<boolean | null>(null)
// Validate the token exists on the server before showing the confirm UI
useEffect(() => {
if (!token) {
setCheckedToken(true)
setTokenValid(false)
return
}
let cancelled = false
fetch(`/api/plugin/pair/status/${encodeURIComponent(token)}`)
.then(async (res) => {
if (cancelled) return
const data = await res.json()
if (data.status === "pending") {
setTokenValid(true)
} else if (data.status === "confirmed") {
setTokenValid(false)
setError("This pairing link has already been used.")
} else {
setTokenValid(false)
setError(data.error || "This pairing link is invalid or expired.")
}
})
.catch(() => {
if (!cancelled) {
setTokenValid(false)
setError("Could not verify pairing link.")
}
})
.finally(() => {
if (!cancelled) setCheckedToken(true)
})
return () => {
cancelled = true
}
}, [token])
async function handleConfirm() {
if (!token) return
setStatus("confirming")
setError(null)
try {
const res = await fetch("/api/plugin/pair/confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
})
const data = await res.json()
if (!res.ok) {
setStatus("error")
setError(data.error || "Failed to link plugin.")
return
}
setStatus("success")
} catch {
setStatus("error")
setError("Network error. Please try again.")
}
}
// ── Loading ───────────────────────────────────────────────
if (isPending || !checkedToken) {
return (
<div className="min-h-[60vh] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-text/40" />
</div>
)
}
// ── No token ──────────────────────────────────────────────
if (!token || tokenValid === false) {
return (
<CenterCard>
<AlertCircle className="h-12 w-12 text-red-400 mx-auto mb-4" />
<h1 className="text-xl font-bold text-text mb-2">
Invalid Pairing Link
</h1>
<p className="text-sm text-text/60 mb-6">
{error ||
"This link is missing a token or has expired. Start a new pairing session from the DeckyVault plugin on your Steam Deck."}
</p>
<Link
href="/"
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
>
Go Home
</Link>
</CenterCard>
)
}
// ── Not logged in ─────────────────────────────────────────
if (!session) {
const callback = encodeURIComponent(`/pair?token=${token}`)
return (
<CenterCard>
<Gamepad2 className="h-12 w-12 text-primary mx-auto mb-4" />
<h1 className="text-xl font-bold text-text mb-2">
Log in to link your plugin
</h1>
<p className="text-sm text-text/60 mb-6">
You need to be logged in to DeckyVault so we can create an API
key for your account.
</p>
<div className="flex flex-col sm:flex-row gap-3 justify-center">
<Link
href={`/login?callbackUrl=${callback}`}
className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
>
Log In
<ArrowRight className="h-4 w-4" />
</Link>
<Link
href={`/signup?callbackUrl=${callback}`}
className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-border text-text text-sm font-medium hover:border-primary/40 transition-colors"
>
Create Account
</Link>
</div>
</CenterCard>
)
}
// ── Success ───────────────────────────────────────────────
if (status === "success") {
return (
<CenterCard>
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", stiffness: 200, damping: 15 }}
>
<CheckCircle2 className="h-16 w-16 text-green-400 mx-auto mb-4" />
</motion.div>
<h1 className="text-xl font-bold text-text mb-2">
Plugin Linked!
</h1>
<p className="text-sm text-text/60 mb-6">
Your DeckyVault plugin is now connected to{" "}
<span className="text-text font-medium">{session.user.name}</span>
&apos;s account. An API key named{" "}
<span className="font-mono text-primary">Decky Loader Plugin</span>{" "}
was created. You can close this page and return to your Steam Deck.
</p>
<Link
href="/profile/settings?tab=api-keys"
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
>
Manage API Keys
</Link>
</CenterCard>
)
}
// ── Confirm ───────────────────────────────────────────────
return (
<CenterCard>
<div className="flex items-center justify-center gap-3 mb-6">
<div className="flex items-center justify-center w-14 h-14 rounded-xl bg-primary/10 border border-primary/20">
<QrCodeIcon className="h-7 w-7 text-primary" />
</div>
<div className="flex items-center justify-center w-14 h-14 rounded-xl bg-text/5 border border-border">
<Gamepad2 className="h-7 w-7 text-text/60" />
</div>
</div>
<h1 className="text-xl font-bold text-text mb-2 text-center">
Link DeckyVault Plugin
</h1>
<p className="text-sm text-text/60 mb-6 text-center max-w-md">
Confirm to connect the DeckyVault plugin on your Steam Deck to your
account. We&apos;ll create an API key so the plugin can upload
performance entries on your behalf.
</p>
<div className="w-full rounded-xl border border-border bg-text/2 p-4 mb-6">
<div className="flex items-center gap-3">
{session.user.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={session.user.image}
alt=""
className="w-10 h-10 rounded-full"
/>
) : (
<div className="w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center text-primary font-medium">
{session.user.name?.[0]?.toUpperCase()}
</div>
)}
<div className="min-w-0">
<p className="text-sm font-medium text-text truncate">
{session.user.name}
</p>
<p className="text-xs text-text/50 truncate">
{session.user.email}
</p>
</div>
</div>
</div>
<div className="w-full flex items-start gap-2 text-xs text-text/50 mb-6">
<ShieldCheck className="h-4 w-4 shrink-0 mt-0.5 text-green-400" />
<span>
An API key (<span className="font-mono">Decky Loader Plugin</span>)
will be created for your account. You can revoke it anytime from
Settings API Keys.
</span>
</div>
{error && (
<div className="w-full text-sm text-red-400 flex items-center gap-2 mb-4 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/20">
<AlertCircle className="h-4 w-4 shrink-0" />
{error}
</div>
)}
<button
onClick={handleConfirm}
disabled={status === "confirming"}
className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
{status === "confirming" ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Linking
</>
) : (
<>
<CheckCircle2 className="h-4 w-4" />
Confirm & Link Plugin
</>
)}
</button>
</CenterCard>
)
}
function CenterCard({ children }: { children: React.ReactNode }) {
return (
<div className="min-h-[80vh] flex items-center justify-center px-4 py-12">
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="w-full max-w-md flex flex-col items-center rounded-2xl border border-border bg-card p-8"
>
{children}
</motion.div>
</div>
)
}
export default function PairPage() {
return (
<Suspense
fallback={
<div className="min-h-[60vh] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-text/40" />
</div>
}
>
<PairContent />
</Suspense>
)
}
@@ -0,0 +1,12 @@
CREATE TABLE "plugin_pairings" (
"token" text PRIMARY KEY NOT NULL,
"user_id" text,
"api_key_id" text,
"api_key" text,
"status" text DEFAULT 'pending' NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"confirmed_at" timestamp,
"expires_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE INDEX "plugin_pairings_userId_idx" ON "plugin_pairings" USING btree ("user_id");
File diff suppressed because it is too large Load Diff
+7
View File
@@ -197,6 +197,13 @@
"when": 1782593630361,
"tag": "0027_slimy_stryfe",
"breakpoints": true
},
{
"idx": 28,
"version": "7",
"when": 1782655457218,
"tag": "0028_thin_bloodstrike",
"breakpoints": true
}
]
}
+2
View File
@@ -52,6 +52,7 @@ import { eq } from "drizzle-orm"
import { mobileRoutes } from "@/lib/api/mobile"
import { gamesLookupRoutes } from "@/lib/api/games-lookup"
import { performanceImportRoutes } from "@/lib/api/performance-import"
import { pluginPairingRoutes } from "@/lib/api/plugin-pairing"
const betterAuth = new Elysia({ name: "better-auth" })
.mount(auth.handler)
@@ -245,6 +246,7 @@ export const app = new Elysia({ prefix: "/api" })
.use(screenshotRoutes)
.use(gamesLookupRoutes)
.use(mobileRoutes)
.use(pluginPairingRoutes)
)
// ── Write routes ───────────────────────────────────────────
.group("", (app) =>
+200
View File
@@ -0,0 +1,200 @@
import { Elysia, t } from "elysia"
import { randomBytes } from "node:crypto"
import { db } from "@/lib/db/index"
import { pluginPairing } from "@/lib/db/schema"
import { eq, and, lt } from "drizzle-orm"
import { auth } from "@/lib/auth"
const PAIRING_TTL_MS = 10 * 60 * 1000 // 10 minutes
function generatePairingToken(): string {
return "pair_" + randomBytes(24).toString("hex")
}
/**
* Build the public site origin used in the QR code URL.
* Prefers the configured BETTER_AUTH_URL, falls back to the request origin.
*/
function getSiteOrigin(request: Request): string {
const configured = process.env.BETTER_AUTH_URL
if (configured) return configured.replace(/\/$/, "")
const url = new URL(request.url)
return `${url.protocol}//${url.host}`
}
export const pluginPairingRoutes = new Elysia({
prefix: "/plugin",
detail: { tags: ["Plugin"] },
})
// ── Initiate: plugin requests a pairing token (no auth) ──────
.post(
"/pair/initiate",
async ({ request, set }) => {
const token = generatePairingToken()
const now = new Date()
const expiresAt = new Date(now.getTime() + PAIRING_TTL_MS)
const origin = getSiteOrigin(request)
await db.insert(pluginPairing).values({
token,
status: "pending",
createdAt: now,
expiresAt,
})
return {
token,
qrUrl: `${origin}/pair?token=${token}`,
expiresAt: expiresAt.toISOString(),
}
},
{
detail: {
summary: "Initiate Decky plugin pairing",
description:
"Creates a short-lived pairing token. The returned qrUrl should be shown as a QR code in the plugin for the user to scan with a logged-in phone.",
},
},
)
// ── Status: plugin polls until confirmed (no auth, token-gated) ──
.get(
"/pair/status/:token",
async ({ params, set }) => {
const [row] = await db
.select()
.from(pluginPairing)
.where(eq(pluginPairing.token, params.token))
.limit(1)
if (!row) {
set.status = 404
return { status: "invalid", error: "Pairing session not found" }
}
// Expired and not confirmed
if (row.expiresAt < new Date() && row.status !== "confirmed") {
set.status = 410
return { status: "expired", error: "Pairing session expired" }
}
if (row.status === "confirmed" && row.apiKey) {
// Hand over the plaintext key and clear it from the row so it
// can only be retrieved once.
const apiKey = row.apiKey
await db
.update(pluginPairing)
.set({ apiKey: null })
.where(eq(pluginPairing.token, params.token))
return {
status: "confirmed",
apiKey,
keyName: "Decky Loader Plugin",
}
}
return { status: "pending" }
},
{
detail: {
summary: "Check Decky plugin pairing status",
description:
"Polled by the plugin until the user confirms on their phone. Returns the plaintext API key once confirmed (one-time retrieval).",
},
},
)
// ── Confirm: user on phone confirms pairing (session auth) ────
.post(
"/pair/confirm",
async ({ body, request, set }) => {
const session = await auth.api.getSession({ headers: request.headers })
if (!session) {
set.status = 401
return { error: "You must be logged in to confirm pairing" }
}
const { token } = body
const [row] = await db
.select()
.from(pluginPairing)
.where(eq(pluginPairing.token, token))
.limit(1)
if (!row) {
set.status = 404
return { error: "Pairing session not found" }
}
if (row.expiresAt < new Date()) {
set.status = 410
return { error: "Pairing session expired. Start again on your Deck." }
}
if (row.status === "confirmed") {
set.status = 409
return { error: "This pairing session has already been confirmed" }
}
// Create an API key for this user via Better Auth (server-side).
// name is required by our api-key plugin config (requireName: true).
let created: { key: string; id: string } | null = null
try {
const result = (await auth.api.createApiKey({
body: {
name: "Decky Loader Plugin",
userId: session.user.id,
},
})) as unknown as { key: string; id: string }
created = { key: result.key, id: result.id }
} catch (err) {
console.error("[plugin-pairing] createApiKey failed:", err)
set.status = 500
return { error: "Failed to create API key" }
}
if (!created || !created.key) {
set.status = 500
return { error: "Failed to create API key" }
}
// Link the pairing session to the user + key
await db
.update(pluginPairing)
.set({
userId: session.user.id,
apiKeyId: created.id,
apiKey: created.key,
status: "confirmed",
confirmedAt: new Date(),
})
.where(eq(pluginPairing.token, token))
return {
success: true,
keyName: "Decky Loader Plugin",
}
},
{
body: t.Object({
token: t.String(),
}),
detail: {
summary: "Confirm Decky plugin pairing",
description:
"Called from the /pair page by a logged-in user. Creates an API key for the account and links it to the pairing token so the plugin can retrieve it.",
},
},
)
// ── Cleanup: periodically delete expired pairings ────────────
.post(
"/pair/cleanup",
async () => {
await db
.delete(pluginPairing)
.where(lt(pluginPairing.expiresAt, new Date()))
return { success: true }
},
{
detail: { hide: true },
},
)
+27
View File
@@ -178,3 +178,30 @@ export const apikeyRelations = relations(apikey, ({ one }) => ({
references: [user.id],
}),
}))
// ── Decky plugin pairing ────────────────────────────────────
// Short-lived pairing sessions that let a Steam Deck link to a
// user account by scanning a QR code on a logged-in phone.
export const pluginPairing = pgTable(
"plugin_pairings",
{
token: text("token").primaryKey(),
userId: text("user_id"),
apiKeyId: text("api_key_id"),
// Plaintext API key, only present between confirm and the plugin
// retrieving it. Cleared once the plugin has fetched it.
apiKey: text("api_key"),
status: text("status").default("pending").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
confirmedAt: timestamp("confirmed_at"),
expiresAt: timestamp("expires_at").notNull(),
},
(table) => [index("plugin_pairings_userId_idx").on(table.userId)],
)
export const pluginPairingRelations = relations(pluginPairing, ({ one }) => ({
user: one(user, {
fields: [pluginPairing.userId],
references: [user.id],
}),
}))