Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectDeviceApprovalSettings.tsx

187 lines7.1 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import type { AuthConnectDevice, EnvironmentId } from "@t3tools/contracts";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import * as DateTime from "effect/DateTime";
8import { msg, T, useGT, useMessages, Var } from "gt-react";
9import { useState } from "react";
10​
11import type { ServerPairingLinkRecord } from "~/environments/primary";
12import { authEnvironment } from "~/state/auth";
13import { m } from "~/i18n/messages";
14import { useAtomCommand } from "~/state/use-atom-command";
15import { useClientSettings } from "../../hooks/useSettings";
16import { Button } from "../ui/button";
17import { stackedThreadToast, toastManager } from "../ui/toast";
18import {
19 connectDeviceName,
20 describeConnectDeviceClient,
21 formatAccessTimestamp,
22} from "./ConnectionsSettings.logic";
23import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
24import { SettingsSection } from "./settingsLayout";
25​
26function reportFailure(title: string, result: Parameters<typeof isAtomCommandInterrupted>[0]) {
27 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
28 const error = squashAtomCommandFailure(result);
29 toastManager.add(
30 stackedThreadToast({
31 type: "error",
32 title,
33 description:
34 error instanceof Error
35 ? (thrownErrorMessage(error, m) ?? error.message)
36 : m(msg("An error occurred.")),
37 }),
38 );
40​
41export function ConnectDeviceApprovalSettings({
42 environmentId,
43 requests,
44 devices,
45 canWrite,
46 requestRevoke,
47}: {
48 readonly environmentId: EnvironmentId;
49 readonly requests: ReadonlyArray<ServerPairingLinkRecord>;
50 readonly devices: ReadonlyArray<AuthConnectDevice>;
51 readonly canWrite: boolean;
52 /** Revokes now, or first asks to turn approval on when it is off. */
53 readonly requestRevoke: (title: string, revoke: () => Promise<void>) => void;
54}) {
55 const gt = useGT();
56 const resolve = useMessages();
57 const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
58 const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });
59 const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });
60 const revoke = useAtomCommand(authEnvironment.revokeConnectDevice, { reportFailure: false });
61 const [busyId, setBusyId] = useState<string | null>(null);
62​
63 const run = async (id: string, action: () => Promise<void>) => {
64 setBusyId(id);
65 await action();
66 setBusyId(null);
67 };
68​
69 return (
70 <SettingsSection id="connect-devices" title={gt`T3 Connect devices`}>
71 {requests.map((request) => {
72 const connectRequest = request.connectDeviceRequest;
73 if (!connectRequest) return null;
74 const busy = busyId === request.id;
75 return (
76 <div key={request.id} className={ITEM_ROW_CLASSNAME}>
77 <div className={ITEM_ROW_INNER_CLASSNAME}>
78 <div className="min-w-0 flex-1 space-y-1">
79 <p className="text-sm font-medium text-foreground">
80 <T>
81 Waiting for approval ·{" "}
82 <span className="font-mono tabular-nums">
83 <Var>{connectRequest.verificationCode}</Var>
84 </span>
85 </T>
86 </p>
87 <p className="text-xs text-muted-foreground">
88 <T>
89 <Var>{describeConnectDeviceClient(connectRequest, resolve)}</Var>. Approve only
90 if the device in front of you shows this code.
91 </T>
92 </p>
93 </div>
94 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
95 <Button
96 size="xs"
97 variant="destructive-outline"
98 disabled={!canWrite || busy}
99 onClick={() =>
100 void run(request.id, async () =>
101 reportFailure(
102 gt`Could not deny the device`,
103 await deny({ environmentId, input: { id: request.id } }),
104 ),
105 )
106 }
107 >
108 <T>Deny</T>
109 </Button>
110 <Button
111 size="xs"
112 disabled={!canWrite || busy}
113 onClick={() =>
114 void run(request.id, async () =>
115 reportFailure(
116 gt`Could not approve the device`,
117 await approve({ environmentId, input: { pairingLinkId: request.id } }),
118 ),
119 )
120 }
121 >
122 {busy ? gt`Saving…` : gt`Approve`}
123 </Button>
124 </div>
125 </div>
126 </div>
127 );
128 })}
129 {devices.map((device) => {
130 const busy = busyId === device.proofKeyThumbprint;
131 return (
132 <div key={device.proofKeyThumbprint} className={ITEM_ROW_CLASSNAME}>
133 <div className={ITEM_ROW_INNER_CLASSNAME}>
134 <div className="min-w-0 flex-1 space-y-1">
135 <p className="text-sm font-medium text-foreground">
136 {describeConnectDeviceClient(device, resolve)}
137 </p>
138 <p className="text-xs text-muted-foreground">
139 <span className="font-mono tabular-nums">{device.verificationCode}</span>
140 <span aria-hidden> · </span>
141 <T>
142 Trusted since{" "}
143 <Var>
144 {formatAccessTimestamp(
145 DateTime.formatIso(device.approvedAt),
146 timestampFormat,
147 )}
148 </Var>
149 </T>
150 </p>
151 </div>
152 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
153 <Button
154 size="xs"
155 variant="destructive-outline"
156 disabled={!canWrite || busy}
157 onClick={() =>
158 requestRevoke(gt`Revoke ${{ name: connectDeviceName(device, resolve) }}?`, () =>
159 run(device.proofKeyThumbprint, async () =>
160 reportFailure(
161 gt`Could not revoke the device`,
162 await revoke({
163 environmentId,
164 input: { proofKeyThumbprint: device.proofKeyThumbprint },
165 }),
166 ),
167 ),
168 )
169 }
170 >
171 {busy ? gt`Revoking…` : gt`Revoke`}
172 </Button>
173 </div>
174 </div>
175 </div>
176 );
177 })}
178 {devices.length === 0 && requests.length === 0 ? (
179 <div className={ITEM_ROW_CLASSNAME}>
180 <p className="text-xs text-muted-foreground/60">
181 <T>No device has connected through T3 Connect yet.</T>
182 </p>
183 </div>
184 ) : null}
185 </SettingsSection>
186 );