| 1 | "use client"; |
| 2 | |
| 3 | import type { |
| 4 | DeviceAuthorizationAuthClient, |
| 5 | DeviceAuthorizationLocalization, |
| 6 | } from "@better-auth-ui/core/plugins/device-authorization"; |
| 7 | import { useAuth, useAuthPlugin |
| 8 | import { |
| 9 | useApproveDevice, |
| 10 | useDenyDevice, |
| 11 | useVerifyDeviceCode, |
| 12 | } from "@better-auth-ui/react/plugins/device-authorization"; |
| 13 | import { useSelector } |
| 14 | import { REGEXP_ONLY_DIGITS_AND_CHARS } |
| 15 | import { CircleCheckIcon, CircleXIcon |
| 16 | import { |
| 17 | type ReactNode, |
| 18 | useCallback, |
| 19 | useEffect, |
| 20 | useReducer, |
| 21 | useRef, |
| 22 | useState, |
| 23 | } from "react"; |
| 24 | |
| 25 | import { Button } |
| 26 | import { |
| 27 | Card, |
| 28 | CardContent, |
| 29 | CardDescription, |
| 30 | CardFooter, |
| 31 | CardHeader, |
| 32 | CardTitle, |
| 33 | } from "@/components/ui/card"; |
| 34 | import { |
| 35 | Field, |
| 36 | FieldError, |
| 37 | FieldGroup, |
| 38 | FieldLabel, |
| 39 | } from "@/components/ui/field"; |
| 40 | import { |
| 41 | InputOTP, |
| 42 | InputOTPGroup, |
| 43 | InputOTPSeparator, |
| 44 | InputOTPSlot, |
| 45 | } from "@/components/ui/input-otp"; |
| 46 | import { deviceAuthorizationPlugin } |
| 47 | import { cn } |
| 48 | import { useAuthForm } |
| 49 | import { OauthApproval } |
| 50 | |
| 51 | type DeviceAuthorizationStep |
| 52 | |
| 53 | type DeviceRequest |
| 54 | clientId?: string |
| 55 | scope?: string |
| 56 | }; |
| 57 | |
| 58 | type DeviceAuthorizationState |
| 59 | step: DeviceAuthorizationStep |
| 60 | codeError: string |
| 61 | request: DeviceRequest |
| 62 | }; |
| 63 | |
| 64 | type DeviceAuthorizationAction |
| 65 | | { type |
| 66 | | { type |
| 67 | | { type |
| 68 | | { type |
| 69 | | { type |
| 70 | |
| 71 | const initialDeviceAuthorizationState: DeviceAuthorizationState |
| 72 | step: "code", |
| 73 | codeError: "", |
| 74 | request: {}, |
| 75 | }; |
| 76 | |
| 77 | function deviceAuthorizationReducer( |
| 78 | state: DeviceAuthorizationState |
| 79 | action: DeviceAuthorizationAction |
| 80 | ): DeviceAuthorizationState { |
| 81 | switch (action.type |
| 82 | case "codeChanged": |
| 83 | return state.codeError |
| 84 | case "verificationFailed": |
| 85 | return { step: |
| 86 | case "verificationSucceeded": |
| 87 | if (action.status |
| 88 | return { step: |
| 89 | } |
| 90 | if (action.status |
| 91 | return { step: |
| 92 | } |
| 93 | return { step: |
| 94 | case "approved": |
| 95 | return { ...state |
| 96 | case "denied": |
| 97 | return { ...state |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | function normalizeDeviceCode(value: |
| 102 | return value.replace |
| 103 | } |
| 104 | |
| 105 | function createDeviceCodeSlots(length: |
| 106 | return Array.from |
| 107 | id: `device-code-character-${String |
| 108 | index: slotIndex, |
| 109 | })); |
| 110 | } |
| 111 | |
| 112 | export type DeviceAuthorizationProps |
| 113 | className?: string |
| 114 | }; |
| 115 | |
| 116 | /** |
| 117 | * Render Better Auth's browser-side device authorization ceremony. |
| 118 | * |
| 119 | * The view accepts a user code, sends unauthenticated users through sign-in |
| 120 | * with a return URL, verifies and claims the code for the current session, |
| 121 | * and lets the user approve or deny the device. |
| 122 | * |
| 123 | * @param |
| 124 | */ |
| 125 | export function DeviceAuthorization({ |
| 126 | const { authClient, |
| 127 | const { |
| 128 | localization, |
| 129 | userCodeLength, |
| 130 | viewPaths: deviceAuthorizationViewPaths, |
| 131 | } = useAuthPlugin(deviceAuthorizationPlugin |
| 132 | const deviceAuthClient = |
| 133 | const { data: |
| 134 | useSession(deviceAuthClient); |
| 135 | const [userCode, |
| 136 | const [state, |
| 137 | deviceAuthorizationReducer, |
| 138 | initialDeviceAuthorizationState, |
| 139 | ); |
| 140 | const submittedCodeRef = |
| 141 | |
| 142 | const handleAuthorizationError = |
| 143 | dispatch({ |
| 144 | type: "verificationFailed", |
| 145 | message: localization.invalidDeviceCode |
| 146 | }); |
| 147 | }; |
| 148 | |
| 149 | useEffect(() => |
| 150 | const code = |
| 151 | if (!code) |
| 152 | |
| 153 | setUserCode( |
| 154 | normalizeDeviceCode(code) |
| 155 | .replace(/[^A-Z0-9 |
| 156 | .slice(0, userCodeLength |
| 157 | ); |
| 158 | }, [userCodeLength]); |
| 159 | |
| 160 | const { mutateAsync: |
| 161 | useVerifyDeviceCode(deviceAuthClient, { |
| 162 | onError: handleAuthorizationError, |
| 163 | onSuccess: ({ status |
| 164 | dispatch({ |
| 165 | type: "verificationSucceeded", |
| 166 | status, |
| 167 | request: { clientId: client_id |
| 168 | }); |
| 169 | }, |
| 170 | }); |
| 171 | |
| 172 | const { mutate: |
| 173 | deviceAuthClient, |
| 174 | { |
| 175 | onError: handleAuthorizationError, |
| 176 | onSuccess: () => |
| 177 | }, |
| 178 | ); |
| 179 | |
| 180 | const { mutate: |
| 181 | deviceAuthClient, |
| 182 | { |
| 183 | onError: handleAuthorizationError, |
| 184 | onSuccess: () => |
| 185 | }, |
| 186 | ); |
| 187 | |
| 188 | const submitCode = |
| 189 | async (completedCode: |
| 190 | const normalizedCode = |
| 191 | |
| 192 | if ( |
| 193 | isSessionPending || |
| 194 | isVerifying || |
| 195 | normalizedCode.length !== userCodeLength |
| 196 | normalizedCode === submittedCodeRef. |
| 197 | ) { |
| 198 | return; |
| 199 | } |
| 200 | |
| 201 | submittedCodeRef.current = |
| 202 | |
| 203 | if (!session) |
| 204 | const verificationPath = |
| 205 | const signInPath = |
| 206 | navigate({ to: |
| 207 | return; |
| 208 | } |
| 209 | |
| 210 | await verifyDeviceCode({ |
| 211 | query: { user_code: normalizedCode |
| 212 | }); |
| 213 | }, |
| 214 | [ |
| 215 | basePaths.auth, |
| 216 | deviceAuthorizationViewPaths.auth.deviceAuthorization |
| 217 | isSessionPending, |
| 218 | isVerifying, |
| 219 | navigate, |
| 220 | session, |
| 221 | userCodeLength, |
| 222 | verifyDeviceCode, |
| 223 | viewPaths.auth.signIn |
| 224 | ], |
| 225 | ); |
| 226 | |
| 227 | const handleSubmit = |
| 228 | async (code: |
| 229 | const normalizedCode = |
| 230 | if (normalizedCode.length |
| 231 | dispatch({ |
| 232 | type: "verificationFailed", |
| 233 | message: localization.invalidDeviceCode |
| 234 | }); |
| 235 | return; |
| 236 | } |
| 237 | await submitCode(normalizedCode |
| 238 | }, |
| 239 | [localization.invalidDeviceCode, |
| 240 | ); |
| 241 | |
| 242 | const authorizedCode = |
| 243 | |
| 244 | const cardClassName = |
| 245 | |
| 246 | if (state.step |
| 247 | return ( |
| 248 | <DeviceApproval |
| 249 | localization={localization} |
| 250 | userCode={authorizedCode} |
| 251 | request={state.request |
| 252 | user={session.user |
| 253 | isApproving={isApproving} |
| 254 | isDenying={isDenying} |
| 255 | onApprove={() => |
| 256 | onDeny={() => |
| 257 | /> |
| 258 | ); |
| 259 | } |
| 260 | |
| 261 | if (state.step |
| 262 | return ( |
| 263 | <DeviceAuthorizationResult |
| 264 | className={cardClassName} |
| 265 | localization={localization} |
| 266 | status={state.step |
| 267 | action={ |
| 268 | <Button |
| 269 | className="w-full" |
| 270 | onClick={() => |
| 271 | > |
| 272 | {localization.returnToApplication} |
| 273 | </Button> |
| 274 | } |
| 275 | /> |
| 276 | ); |
| 277 | } |
| 278 | |
| 279 | return ( |
| 280 | <DeviceCodeForm |
| 281 | className={cardClassName} |
| 282 | codeError={state.codeError |
| 283 | isSessionPending={isSessionPending} |
| 284 | isVerifying={isVerifying} |
| 285 | localization={localization} |
| 286 | initialUserCode={userCode} |
| 287 | userCodeLength={userCodeLength} |
| 288 | onCodeChange={() => |
| 289 | onSubmitCode={handleSubmit} |
| 290 | /> |
| 291 | ); |
| 292 | } |
| 293 | |
| 294 | type DeviceCodeFormProps |
| 295 | className: string |
| 296 | codeError: string |
| 297 | isSessionPending: boolean |
| 298 | isVerifying: boolean |
| 299 | localization: DeviceAuthorizationLocalization |
| 300 | initialUserCode: string |
| 301 | userCodeLength: number |
| 302 | onCodeChange: (value |
| 303 | onSubmitCode: (code |
| 304 | }; |
| 305 | |
| 306 | function DeviceCodeForm({ |
| 307 | className, |
| 308 | codeError, |
| 309 | isSessionPending, |
| 310 | isVerifying, |
| 311 | localization, |
| 312 | initialUserCode, |
| 313 | userCodeLength, |
| 314 | onCodeChange, |
| 315 | onSubmitCode, |
| 316 | }: DeviceCodeFormProps) |
| 317 | const slots = |
| 318 | const groupBreak = |
| 319 | const firstGroup = |
| 320 | const secondGroup = |
| 321 | const errorId = |
| 322 | const form = |
| 323 | defaultValues: { userCode: initialUserCode |
| 324 | onSubmit: async ( |
| 325 | await onSubmitCode(value |
| 326 | }, |
| 327 | }); |
| 328 | const userCodeComplete = |
| 329 | form.store, |
| 330 | (state) => |
| 331 | ); |
| 332 | |
| 333 | useEffect(() => |
| 334 | form.setFieldValue("userCode |
| 335 | if (initialUserCode.length |
| 336 | void onSubmitCode(initialUserCode) |
| 337 | } |
| 338 | }, [form.setFieldValue |
| 339 | |
| 340 | return ( |
| 341 | <Card className={ |
| 342 | <CardHeader> |
| 343 | <CardTitle className=" |
| 344 | {localization.deviceAuthorization} |
| 345 | </CardTitle> |
| 346 | <CardDescription> |
| 347 | {localization.deviceAuthorizationDescription} |
| 348 | </CardDescription> |
| 349 | </CardHeader> |
| 350 | |
| 351 | <CardContent> |
| 352 | <form.AppForm> |
| 353 | <form.AuthFormRoot aria-label={ |
| 354 | <FieldGroup> |
| 355 | <form.AppField name=" |
| 356 | {(field) => |
| 357 | <Field data-invalid={ |
| 358 | <FieldLabel htmlFor=" |
| 359 | {localization.deviceCode} |
| 360 | </FieldLabel> |
| 361 | |
| 362 | <InputOTP |
| 363 | id="device-code" |
| 364 | aria-describedby={codeError ? |
| 365 | aria-invalid={Boolean(codeError |
| 366 | autoComplete="one-time-code" |
| 367 | containerClassName="w-full justify-center" |
| 368 | disabled={isVerifying} |
| 369 | inputMode="text" |
| 370 | maxLength={userCodeLength} |
| 371 | name={field.name |
| 372 | pasteTransformer={normalizeDeviceCode} |
| 373 | pattern={REGEXP_ONLY_DIGITS_AND_CHARS} |
| 374 | value={field.state |
| 375 | onChange={(value) |
| 376 | const nextCode = |
| 377 | .replace(/[^A-Z0-9 |
| 378 | .slice(0, userCodeLength |
| 379 | field.handleChange(nextCode |
| 380 | onCodeChange(nextCode); |
| 381 | if (nextCode.length === |
| 382 | void onSubmitCode(nextCode) |
| 383 | }} |
| 384 | > |
| 385 | <InputOTPGroup> |
| 386 | {firstGroup.map(( |
| 387 | <InputOTPSlot key={ |
| 388 | ))} |
| 389 | </InputOTPGroup> |
| 390 | |
| 391 | {secondGroup.length > |
| 392 | <> |
| 393 | <InputOTPSeparator /> |
| 394 | <InputOTPGroup> |
| 395 | {secondGroup.map(( |
| 396 | <InputOTPSlot key={ |
| 397 | ))} |
| 398 | </InputOTPGroup> |
| 399 | </> |
| 400 | ) : null} |
| 401 | </InputOTP> |
| 402 | |
| 403 | <FieldError id={ |
| 404 | </Field> |
| 405 | )} |
| 406 | </form.AppField> |
| 407 | |
| 408 | <form.AuthFormSubmitButton |
| 409 | isPending={isVerifying} |
| 410 | className="w-full" |
| 411 | disabled={!userCodeComplete |
| 412 | type="submit" |
| 413 | > |
| 414 | {localization.continue} |
| 415 | </form.AuthFormSubmitButton> |
| 416 | </FieldGroup> |
| 417 | </form.AuthFormRoot> |
| 418 | </form.AppForm> |
| 419 | </CardContent> |
| 420 | </Card> |
| 421 | ); |
| 422 | } |
| 423 | |
| 424 | type DeviceApprovalProps |
| 425 | isApproving: boolean |
| 426 | isDenying: boolean |
| 427 | localization: DeviceAuthorizationLocalization |
| 428 | request: DeviceRequest |
| 429 | user: { |
| 430 | email: string |
| 431 | name: string |
| 432 | image?: string |
| 433 | }; |
| 434 | userCode: string |
| 435 | onApprove: () |
| 436 | onDeny: () |
| 437 | }; |
| 438 | |
| 439 | function DeviceApproval({ |
| 440 | isApproving, |
| 441 | isDenying, |
| 442 | localization, |
| 443 | request, |
| 444 | user, |
| 445 | userCode, |
| 446 | onApprove, |
| 447 | onDeny, |
| 448 | }: DeviceApprovalProps) |
| 449 | return ( |
| 450 | <OauthApproval |
| 451 | details={ |
| 452 | <div className="flex w-full flex-col items-center gap-1 rounded-lg border bg-muted/50 px-4 py-3 |
| 453 | <p className="text-xs text-muted-foreground |
| 454 | Check this code matches the one on your device |
| 455 | </p> |
| 456 | <p className="font-mono text-2xl font-semibold tracking-[0.3em] |
| 457 | {userCode} |
| 458 | </p> |
| 459 | </div> |
| 460 | } |
| 461 | clientId={request.clientId |
| 462 | scopes={request.scope |
| 463 | user={user} |
| 464 | approveLabel={localization.approve |
| 465 | denyLabel={localization.deny |
| 466 | isApproving={isApproving} |
| 467 | isDenying={isDenying} |
| 468 | onApprove={onApprove} |
| 469 | onDeny={onDeny} |
| 470 | /> |
| 471 | ); |
| 472 | } |
| 473 | |
| 474 | type DeviceAuthorizationResultProps |
| 475 | action: ReactNode |
| 476 | className: string |
| 477 | localization: DeviceAuthorizationLocalization |
| 478 | status: "approved |
| 479 | }; |
| 480 | |
| 481 | function DeviceAuthorizationResult({ |
| 482 | action, |
| 483 | className, |
| 484 | localization, |
| 485 | status, |
| 486 | }: DeviceAuthorizationResultProps) |
| 487 | const approved = |
| 488 | const Icon = |
| 489 | |
| 490 | return ( |
| 491 | <Card className={ |
| 492 | <CardHeader className=" |
| 493 | <Icon |
| 494 | aria-hidden="true" |
| 495 | className={cn( |
| 496 | "mb-1 size-10", |
| 497 | approved ? "text-primary" |
| 498 | )} |
| 499 | /> |
| 500 | <CardTitle className=" |
| 501 | {approved ? localization |
| 502 | </CardTitle> |
| 503 | <CardDescription> |
| 504 | {approved |
| 505 | ? localization.deviceApprovedDescription |
| 506 | : localization.deviceDeniedDescription} |
| 507 | </CardDescription> |
| 508 | </CardHeader> |
| 509 | |
| 510 | <CardFooter>{action} |
| 511 | </Card> |
| 512 | ); |
| 513 | } |