180 lines
6.9 KiB
TypeScript
180 lines
6.9 KiB
TypeScript
import { useMutation, useQuery } from "@tanstack/react-query"
|
|
import { createFileRoute, redirect } from "@tanstack/react-router"
|
|
import { Check, Copy } from "lucide-react"
|
|
import { useEffect } from "react"
|
|
|
|
import { ApiError, PanelsService } from "@/client"
|
|
import { Button } from "@/components/ui/button"
|
|
import { useCopyToClipboard } from "@/hooks/useCopyToClipboard"
|
|
import { apiToken, appPath, isPortal, openPortalSession } from "@/lib/portal"
|
|
|
|
/**
|
|
* The panel a credential in hand names, or "" when it names none.
|
|
*
|
|
* Two shapes say it, because two things mint one. This instance writes a
|
|
* `panel` claim; the hub, which knows nothing of this instance's users,
|
|
* puts the panel in `sub` and says so with `scope`. A local token carries no
|
|
* `scope` at all, so the two cannot be confused — and without the second shape
|
|
* a screen adopted through the portal named no panel, and asked the household
|
|
* for a fresh code on every single boot.
|
|
*
|
|
* Read rather than verified: this only decides where to send the browser, and
|
|
* the server still judges the credential on the first call it makes there.
|
|
*/
|
|
function pairedPanel(): string {
|
|
try {
|
|
const [, payload] = apiToken().split(".")
|
|
const claims = JSON.parse(
|
|
atob(payload.replace(/-/g, "+").replace(/_/g, "/")),
|
|
)
|
|
if (typeof claims.panel === "string") return claims.panel
|
|
if (claims.scope === "panel" && typeof claims.sub === "string") {
|
|
return claims.sub
|
|
}
|
|
return ""
|
|
} catch {
|
|
return ""
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adopting a screen that has no keyboard.
|
|
*
|
|
* A wall tablet cannot be asked to type an email address and a password, so it
|
|
* asks for a code instead and shows it. Somebody with an account types that
|
|
* code into the panels dialog to say which panel this device is, and the
|
|
* credential it mints arrives here on the next poll.
|
|
*
|
|
* Only once, though: a screen that already holds a credential goes straight to
|
|
* the panel it names, so a reboot comes back to the dashboard rather than
|
|
* asking the household for another code.
|
|
*
|
|
* Outside both shells like `/view/{name}`: until it is paired, this device has
|
|
* no session and there is nothing to put around it.
|
|
*
|
|
* Reached through the portal as well, for a screen hanging where this
|
|
* instance is not: the hub serves this one page without a session and
|
|
* forwards these two calls down the tunnel, because a device with no
|
|
* credential is what they are for.
|
|
*/
|
|
export const Route = createFileRoute("/panel/")({
|
|
component: PairPanel,
|
|
beforeLoad: () => {
|
|
// Nothing to mint a code for. A credential the server has since stopped
|
|
// honouring comes back here with storage cleared, so the next arrival
|
|
// pairs normally rather than bouncing.
|
|
const paired = pairedPanel()
|
|
if (paired) throw redirect({ to: "/panel/$id", params: { id: paired } })
|
|
},
|
|
head: () => ({ meta: [{ title: "Pair this panel - Fluksio" }] }),
|
|
})
|
|
|
|
function PairPanel() {
|
|
const [copied, copy] = useCopyToClipboard()
|
|
|
|
// A code lives ten minutes. Asking for one is the mount, and asking again is
|
|
// what happens when this one is no longer recognised.
|
|
const start = useMutation({
|
|
mutationFn: () => PanelsService.startPairing(),
|
|
// A screen hung while the link is down has nobody to tell, so it keeps
|
|
// asking rather than showing six dots until someone power-cycles it.
|
|
retry: true,
|
|
retryDelay: 5000,
|
|
})
|
|
const request = start.mutate
|
|
|
|
// biome-ignore lint/correctness/useExhaustiveDependencies: asked for once, when the screen goes up.
|
|
useEffect(() => {
|
|
request()
|
|
}, [])
|
|
|
|
const started = start.data
|
|
const { data: status, error } = useQuery({
|
|
queryKey: ["pairing", started?.code],
|
|
queryFn: () =>
|
|
PanelsService.pollPairing({
|
|
code: started?.code ?? "",
|
|
secret: started?.secret ?? "",
|
|
}),
|
|
enabled: Boolean(started),
|
|
refetchInterval: 3000,
|
|
// A 404 means this code is finished, not that the request failed.
|
|
retry: false,
|
|
})
|
|
|
|
// Expired, or collected already. Ask for another rather than leaving a
|
|
// number on the wall that no longer works — but only for that answer: over
|
|
// the tunnel a 502 or 503 is an ordinary hiccup, and changing the code on
|
|
// the wall while somebody is typing it is worse than waiting.
|
|
useEffect(() => {
|
|
if (error instanceof ApiError && error.status === 404) request()
|
|
}, [error, request])
|
|
|
|
useEffect(() => {
|
|
if (!status?.access_token || !status.panel) return
|
|
const token = status.access_token
|
|
const panel = status.panel
|
|
const land = () => {
|
|
// A full load rather than a route change: everything this page asked for
|
|
// was asked without a credential, and the socket has to dial again
|
|
// holding this one.
|
|
window.location.href = appPath(`/panel/${panel}`)
|
|
}
|
|
if (isPortal()) {
|
|
// Under the portal the credential belongs in the hub's own cookie: the
|
|
// page is served with its config injected, and localStorage is not read
|
|
// there. Landing anyway if it fails would loop on a page with nothing.
|
|
openPortalSession(token).then(land).catch(land)
|
|
return
|
|
}
|
|
localStorage.setItem("access_token", token)
|
|
land()
|
|
}, [status])
|
|
|
|
return (
|
|
<main className="grid h-svh w-full place-items-center p-8">
|
|
<div className="grid max-w-md gap-6 text-center">
|
|
<div className="grid gap-2">
|
|
<h1 className="text-2xl">Pair this panel</h1>
|
|
<p className="text-sm text-muted-foreground">
|
|
On a computer, open <span className="font-medium">Dashboards</span>{" "}
|
|
→ <span className="font-medium">Panels</span>, pick which panel this
|
|
is, and enter this code.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-center gap-4">
|
|
<p className="font-mono text-6xl font-medium tracking-[0.2em]">
|
|
<span data-testid="pairing-code" aria-hidden="true">
|
|
{started?.code ?? "······"}
|
|
</span>
|
|
{/* Spelled out, so a reader says the characters rather than trying
|
|
to pronounce them as a word. */}
|
|
<span className="sr-only">
|
|
{(started?.code ?? "").split("").join(" ")}
|
|
</span>
|
|
</p>
|
|
{/* Only where it would work: a panel served over plain http on the
|
|
LAN has no clipboard, and a button that silently does nothing is
|
|
worse than none. */}
|
|
{started?.code && navigator.clipboard ? (
|
|
<Button
|
|
variant="ghost"
|
|
size="icon-touch"
|
|
className="shrink-0 text-muted-foreground"
|
|
aria-label="Copy the code"
|
|
onClick={() => copy(started.code)}
|
|
>
|
|
{copied === started.code ? <Check /> : <Copy />}
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
|
|
<p className="text-sm text-muted-foreground">
|
|
The code lasts ten minutes; this screen replaces it when it runs out.
|
|
</p>
|
|
</div>
|
|
</main>
|
|
)
|
|
}
|