Better Auth: Device authorization approve and deny accept any authenticated session while the user code is pending
Description
Am
I affected?
You are affected if all of the following are true:
- You use
better-authat a version>= 1.6.0, < 1.6.11. - The
deviceAuthorizationplugin is enabled in your auth config (deviceAuthorization()in yourpluginsarray). - A third party can observe a pending user code before the legitimate user completes verification.
The standard device-flow UX displays user codes to humans, so realistic exposure includes shoulder-surfing, screen-share, voice or video calls, support-chat transcripts, referrer headers, and shared logs.
If your application does not enable the deviceAuthorization plugin, you are not affected.
Fix:
- Upgrade to
better-auth@1.6.11or later. - If you cannot upgrade, see workarounds below.
Summary
Better Auth's deviceAuthorization plugin treated any authenticated session as the owner of any pending device code. The ownership gate on POST /device/approve and POST /device/deny short-circuited whenever the row's userId was unset, and the GET /device verification handler did not claim the row. An authenticated attacker who learned a valid user_code before the legitimate user completed approval could bind the polling device to the attacker's account or deny the legitimate flow.
Details
The device authorization flow binds the polling device to the user who entered the user code on the verification page. In affected versions, the plugin only created that binding at approve or deny time, with no claim at the verification step. The ownership check at approve and deny short-circuited when the owner was missing, accepting any authenticated caller instead of rejecting the request.
The fix changes GET /device to claim the pending row for the calling session. The approve and deny gates now require strict equality between the row's owner and the calling session. RFC 8628 §5.5 covers this risk class as Session Spying: a malicious party can hijack a session by completing authorization before the legitimate initiating user does.
Patches
Fixed in better-auth@1.6.11. After the patch, GET /device claims the pending row for the calling session, and POST /device/approve and POST /device/deny reject calls whose session does not match the claimed owner. Custom verification pages must serve GET /device to an authenticated session for the flow to succeed.
Workarounds
If you cannot upgrade immediately:
- Disable the plugin if you do not use the device flow: remove
deviceAuthorization()from yourpluginsarray. - **Add a
beforehook** onPOST /device/approveandPOST /device/denythat tracks which session calledGET /devicefor each user code, and rejects calls from a different session. - Shorten the pending lifetime of device codes via the
expiresInplugin option to reduce the exploitation window.
Impact
- Account takeover on the polling device: the attacker's session becomes the device's session, so the device operates as the attacker.
- Denial of the legitimate sign-in: the attacker can mark the code as denied, blocking the victim's flow.
Credit
Reported by Quikturn Security Team.
Affected products
2- Range: >=1.6.0,<1.6.11
Patches
199a254a79b59fix(device-authorization): bind approval to verifier session (#9573)
5 files changed · +404 −19
.changeset/device-auth-claim-at-verify.md+7 −0 added@@ -0,0 +1,7 @@ +--- +"better-auth": patch +--- + +fix(device-authorization): require verify-time ownership claim for approve/deny + +Pending device codes were not bound to the user who entered the code on the verification page until approval, leaving a window where any authenticated user could approve or deny another user's pending code by knowing the `user_code`. `GET /device` now claims the pending row for the calling session, and `POST /device/approve` and `POST /device/deny` require the calling session to match the claimed owner. Custom verification pages must be served to an authenticated session for the flow to succeed.
docs/content/docs/plugins/device-authorization.mdx+17 −7 modified@@ -206,18 +206,20 @@ pollForToken(); The user authorization flow requires two steps: -1. **Code Verification**: Check if the entered user code is valid -2. **Authorization**: User must be authenticated to approve/deny the device +1. **Code Verification**: Validate the user code via `GET /device`. The verification request claims the pending device code for the calling session. +2. **Authorization**: The session that claimed the code can approve or deny it. <Callout type="warn"> - Users must be authenticated before they can approve or deny device authorization requests. If not authenticated, redirect them to the login page with a return URL. + Users must be authenticated when calling `GET /device`, because the verification step binds the pending device code to that session. Only the same session can later approve or deny. If the user is not authenticated when entering the code, redirect them to the login page with a return URL and re-call `GET /device` after sign-in. </Callout> Create a page where users can enter their code: ```tsx title="app/device/page.tsx" export default function DeviceAuthorizationPage() { - const [userCode, setUserCode] = useState(""); + const { data: session } = authClient.useSession(); + const searchParams = useSearchParams(); + const [userCode, setUserCode] = useState(searchParams.get("user_code") || ""); const [error, setError] = useState(null); const handleSubmit = async (e) => { @@ -226,6 +228,13 @@ export default function DeviceAuthorizationPage() { try { // Format the code: remove dashes and convert to uppercase const formattedCode = userCode.trim().replace(/-/g, "").toUpperCase(); + const approvalPath = `/device/approve?user_code=${encodeURIComponent(formattedCode)}`; + + if (!session?.user) { + const verificationPath = `/device?user_code=${encodeURIComponent(formattedCode)}`; + window.location.href = `/login?redirect=${encodeURIComponent(verificationPath)}`; + return; + } // Check if the code is valid using GET /device endpoint const response = await authClient.device({ @@ -234,7 +243,7 @@ export default function DeviceAuthorizationPage() { if (response.data) { // Redirect to approval page - window.location.href = `/device/approve?user_code=${formattedCode}`; + window.location.href = approvalPath; } } catch (err) { setError("Invalid or expired code"); @@ -327,7 +336,8 @@ export default function DeviceApprovalPage() { if (!user) { // Redirect to login if not authenticated - window.location.href = `/login?redirect=/device/approve?user_code=${userCode}`; + const verificationPath = `/device?user_code=${encodeURIComponent(userCode || "")}`; + window.location.href = `/login?redirect=${encodeURIComponent(verificationPath)}`; return null; } @@ -545,7 +555,7 @@ authenticateCLI().catch((err) => { 3. **Client Validation**: Always validate client IDs in production to prevent unauthorized access 4. **HTTPS Only**: Always use HTTPS in production for device authorization 5. **User Code Format**: User codes use a limited character set (excluding similar-looking characters like 0/O, 1/I) to reduce typing errors -6. **Authentication Required**: Users must be authenticated before they can approve or deny device requests +6. **Authentication Required**: Users must be authenticated when calling `GET /device`. The verification step claims the pending device code for the calling session, and only that session can later approve or deny it ## Options
packages/better-auth/src/plugins/device-authorization/device-authorization.test.ts+337 −0 modified@@ -1,3 +1,8 @@ +import type { BetterAuthOptions } from "@better-auth/core"; +import { getAuthTables } from "@better-auth/core/db"; +import type { DBAdapter } from "@better-auth/core/db/adapter"; +import type { MemoryDB } from "@better-auth/memory-adapter"; +import { memoryAdapter } from "@better-auth/memory-adapter"; import { afterEach, describe, expect, it, vi } from "vitest"; import { getTestInstance } from "../../test-utils/test-instance"; import { deviceAuthorization, deviceAuthorizationOptionsSchema } from "."; @@ -290,6 +295,11 @@ describe("device authorization flow", async () => { }, }); + await auth.api.deviceVerify({ + query: { user_code }, + headers, + }); + // Approve the device const approveResponse = await auth.api.deviceApprove({ body: { userCode: user_code }, @@ -326,6 +336,11 @@ describe("device authorization flow", async () => { }, }); + await auth.api.deviceVerify({ + query: { user_code }, + headers, + }); + // Deny the device const denyResponse = await auth.api.deviceDeny({ body: { userCode: user_code }, @@ -418,6 +433,10 @@ describe("device authorization flow", async () => { client_id: "test-client", }, }); + await auth.api.deviceVerify({ + query: { user_code: userCode }, + headers, + }); await auth.api.deviceApprove({ body: { userCode }, headers, @@ -460,6 +479,11 @@ describe("device authorization flow", async () => { }, }); + await auth.api.deviceVerify({ + query: { user_code }, + headers, + }); + await auth.api.deviceApprove({ body: { userCode: user_code }, headers, @@ -508,6 +532,11 @@ describe("device authorization flow", async () => { }, }); + await auth.api.deviceVerify({ + query: { user_code }, + headers, + }); + // User approves - this should succeed const approveResponse = await auth.api.deviceApprove({ body: { userCode: user_code }, @@ -542,6 +571,314 @@ describe("device authorization flow", async () => { }); }); +describe("device authorization ownership gate", () => { + const ATTACKER_EMAIL = "attacker@example.test"; + const ATTACKER_PASSWORD = "attacker-password-123"; + type AdapterUpdateData = Parameters< + DBAdapter<BetterAuthOptions>["update"] + >[0]; + + /** + * @see https://github.com/better-auth/better-auth/security/advisories/GHSA-cq3f-vc6p-68fh + */ + it("rejects approve from a session that did not claim the pending code", async () => { + const { auth, client, db, signInWithUser } = await getTestInstance( + { + plugins: [ + deviceAuthorization({ + expiresIn: "5min", + interval: "2s", + }), + ], + }, + { + clientOptions: { + plugins: [deviceAuthorizationClient()], + }, + }, + ); + + await client.signUp.email({ + email: ATTACKER_EMAIL, + password: ATTACKER_PASSWORD, + name: "attacker", + }); + const { headers: attackerHeaders, res: attackerSession } = + await signInWithUser(ATTACKER_EMAIL, ATTACKER_PASSWORD); + const attackerId = attackerSession.user.id; + + const { device_code, user_code } = await auth.api.deviceCode({ + body: { client_id: "test-client" }, + }); + expect(device_code).toBeTruthy(); + expect(user_code).toBeTruthy(); + + await expect( + auth.api.deviceApprove({ + body: { userCode: user_code }, + headers: attackerHeaders, + }), + ).rejects.toMatchObject({ + body: { error: "invalid_request" }, + }); + + const rowAfter = await db.findOne<DeviceCode>({ + model: "deviceCode", + where: [{ field: "userCode", value: user_code }], + }); + expect(rowAfter?.userId).not.toBe(attackerId); + expect(rowAfter?.status).toBe("pending"); + + await expect( + auth.api.deviceToken({ + body: { + grant_type: "urn:ietf:params:oauth:grant-type:device_code", + device_code, + client_id: "test-client", + }, + }), + ).rejects.toMatchObject({ + body: { error: "authorization_pending" }, + }); + }); + + /** + * @see https://github.com/better-auth/better-auth/security/advisories/GHSA-cq3f-vc6p-68fh + */ + it("rejects deny from a session that did not claim the pending code", async () => { + const { auth, client, db, signInWithUser } = await getTestInstance( + { + plugins: [ + deviceAuthorization({ + expiresIn: "5min", + interval: "2s", + }), + ], + }, + { + clientOptions: { + plugins: [deviceAuthorizationClient()], + }, + }, + ); + + await client.signUp.email({ + email: ATTACKER_EMAIL, + password: ATTACKER_PASSWORD, + name: "attacker", + }); + const { headers: attackerHeaders, res: attackerSession } = + await signInWithUser(ATTACKER_EMAIL, ATTACKER_PASSWORD); + const attackerId = attackerSession.user.id; + + const { user_code } = await auth.api.deviceCode({ + body: { client_id: "test-client" }, + }); + + await expect( + auth.api.deviceDeny({ + body: { userCode: user_code }, + headers: attackerHeaders, + }), + ).rejects.toMatchObject({ + body: { error: "invalid_request" }, + }); + + const rowAfter = await db.findOne<DeviceCode>({ + model: "deviceCode", + where: [{ field: "userCode", value: user_code }], + }); + expect(rowAfter?.userId).not.toBe(attackerId); + expect(rowAfter?.status).toBe("pending"); + }); + + /** + * @see https://github.com/better-auth/better-auth/security/advisories/GHSA-cq3f-vc6p-68fh + */ + it("allows approve when the same session called verify first", async () => { + const { auth, signInWithTestUser } = await getTestInstance({ + plugins: [ + deviceAuthorization({ + expiresIn: "5min", + interval: "2s", + }), + ], + }); + + const { headers: legitHeaders } = await signInWithTestUser(); + + const { user_code } = await auth.api.deviceCode({ + body: { client_id: "test-client" }, + }); + + await auth.api.deviceVerify({ + query: { user_code }, + headers: legitHeaders, + }); + + const approve = await auth.api.deviceApprove({ + body: { userCode: user_code }, + headers: legitHeaders, + }); + expect(approve).toMatchObject({ success: true }); + }); + + /** + * @see https://github.com/better-auth/better-auth/security/advisories/GHSA-cq3f-vc6p-68fh + */ + it("rejects approve from a different user after another claimed the code", async () => { + const { auth, client, signInWithTestUser, signInWithUser } = + await getTestInstance( + { + plugins: [ + deviceAuthorization({ + expiresIn: "5min", + interval: "2s", + }), + ], + }, + { + clientOptions: { + plugins: [deviceAuthorizationClient()], + }, + }, + ); + + const { headers: claimerHeaders } = await signInWithTestUser(); + + await client.signUp.email({ + email: ATTACKER_EMAIL, + password: ATTACKER_PASSWORD, + name: "attacker", + }); + const { headers: attackerHeaders } = await signInWithUser( + ATTACKER_EMAIL, + ATTACKER_PASSWORD, + ); + + const { user_code } = await auth.api.deviceCode({ + body: { client_id: "test-client" }, + }); + + await auth.api.deviceVerify({ + query: { user_code }, + headers: claimerHeaders, + }); + + await expect( + auth.api.deviceApprove({ + body: { userCode: user_code }, + headers: attackerHeaders, + }), + ).rejects.toMatchObject({ + status: "FORBIDDEN", + body: { error: "access_denied" }, + }); + + await expect( + auth.api.deviceDeny({ + body: { userCode: user_code }, + headers: attackerHeaders, + }), + ).rejects.toMatchObject({ + status: "FORBIDDEN", + body: { error: "access_denied" }, + }); + }); + + it("does not overwrite a device code claimed after verify reads it", async () => { + let adapter: DBAdapter<BetterAuthOptions> | null = null; + let concurrentOwnerId: string | undefined; + let simulateConcurrentClaim = false; + + const database = ((options: BetterAuthOptions) => { + if (adapter) { + return adapter; + } + const tables = getAuthTables(options); + const memoryDB = Object.keys(tables).reduce<MemoryDB>((db, table) => { + db[table] = []; + return db; + }, {}); + const baseAdapter = memoryAdapter(memoryDB)(options); + adapter = { + ...baseAdapter, + update: async <T>(data: AdapterUpdateData) => { + if ( + simulateConcurrentClaim && + concurrentOwnerId && + data.model === "deviceCode" && + data.update.userId + ) { + simulateConcurrentClaim = false; + const deviceCodeId = data.where.find( + (where) => where.field === "id", + )?.value; + if (typeof deviceCodeId === "string") { + await baseAdapter.update<DeviceCode>({ + model: "deviceCode", + where: [{ field: "id", value: deviceCodeId }], + update: { userId: concurrentOwnerId }, + }); + } + } + return baseAdapter.update<T>(data); + }, + }; + return adapter; + }) satisfies BetterAuthOptions["database"]; + + const { auth, client, db, signInWithUser } = await getTestInstance({ + database, + plugins: [ + deviceAuthorization({ + expiresIn: "5min", + interval: "2s", + }), + ], + }); + + await client.signUp.email({ + email: "concurrent-owner@example.test", + password: "concurrent-owner-password-123", + name: "concurrent owner", + }); + const { res: concurrentOwnerSession } = await signInWithUser( + "concurrent-owner@example.test", + "concurrent-owner-password-123", + ); + concurrentOwnerId = concurrentOwnerSession.user.id; + + await client.signUp.email({ + email: "racer@example.test", + password: "racer-password-123", + name: "racer", + }); + const { headers: racerHeaders, res: racerSession } = await signInWithUser( + "racer@example.test", + "racer-password-123", + ); + + const { user_code } = await auth.api.deviceCode({ + body: { client_id: "test-client" }, + }); + + simulateConcurrentClaim = true; + await auth.api.deviceVerify({ + query: { user_code }, + headers: racerHeaders, + }); + + const rowAfter = await db.findOne<DeviceCode>({ + model: "deviceCode", + where: [{ field: "userCode", value: user_code }], + }); + expect(rowAfter?.userId).toBe(concurrentOwnerId); + expect(rowAfter?.userId).not.toBe(racerSession.user.id); + expect(rowAfter?.status).toBe("pending"); + }); +}); + describe("device authorization with custom options", async () => { it("should correctly store interval as milliseconds in database", async () => { const { auth, db } = await getTestInstance({
packages/better-auth/src/plugins/device-authorization/error-codes.ts+2 −0 modified@@ -8,6 +8,8 @@ export const DEVICE_AUTHORIZATION_ERROR_CODES = defineErrorCodes({ ACCESS_DENIED: "Access denied", INVALID_USER_CODE: "Invalid user code", DEVICE_CODE_ALREADY_PROCESSED: "Device code already processed", + DEVICE_CODE_NOT_CLAIMED: + "Device code has not been claimed by a verifying session; call `GET /device` with the `user_code` while signed in before approving or denying", POLLING_TOO_FREQUENTLY: "Polling too frequently", USER_NOT_FOUND: "User not found", FAILED_TO_CREATE_SESSION: "Failed to create session",
packages/better-auth/src/plugins/device-authorization/routes.ts+41 −12 modified@@ -146,6 +146,7 @@ Follow [rfc8628#section-3.2](https://datatracker.ietf.org/doc/html/rfc8628#secti data: { deviceCode, userCode, + userId: null, expiresAt, status: "pending", pollingInterval: ms(opts.interval), @@ -555,6 +556,27 @@ export const deviceVerify = createAuthEndpoint( }); } + const session = await getSessionFromCtx(ctx); + if ( + session?.user?.id && + !deviceCodeRecord.userId && + deviceCodeRecord.status === "pending" + ) { + const claimedDeviceCodeRecord = + await ctx.context.adapter.update<DeviceCode>({ + model: "deviceCode", + where: [ + { field: "id", value: deviceCodeRecord.id }, + { field: "status", value: "pending" }, + { field: "userId", operator: "eq", value: null }, + ], + update: { userId: session.user.id }, + }); + if (claimedDeviceCodeRecord) { + deviceCodeRecord.userId = session.user.id; + } + } + return ctx.json({ user_code: user_code, status: deviceCodeRecord.status, @@ -659,11 +681,15 @@ export const deviceApprove = createAuthEndpoint( }); } - // Check if userId is set and matches the current user - if ( - deviceCodeRecord.userId && - deviceCodeRecord.userId !== session.user.id - ) { + if (!deviceCodeRecord.userId) { + throw new APIError("BAD_REQUEST", { + error: "invalid_request", + error_description: + DEVICE_AUTHORIZATION_ERROR_CODES.DEVICE_CODE_NOT_CLAIMED.message, + }); + } + + if (deviceCodeRecord.userId !== session.user.id) { throw new APIError("FORBIDDEN", { error: "access_denied", error_description: @@ -788,19 +814,22 @@ export const deviceDeny = createAuthEndpoint( }); } - // Check if userId is set and matches the current user - if ( - deviceCodeRecord.userId && - deviceCodeRecord.userId !== session.user.id - ) { + if (!deviceCodeRecord.userId) { + throw new APIError("BAD_REQUEST", { + error: "invalid_request", + error_description: + DEVICE_AUTHORIZATION_ERROR_CODES.DEVICE_CODE_NOT_CLAIMED.message, + }); + } + + if (deviceCodeRecord.userId !== session.user.id) { throw new APIError("FORBIDDEN", { error: "access_denied", error_description: "You are not authorized to deny this device authorization", }); } - // Update device code with denied status and userId if not already set await ctx.context.adapter.update({ model: "deviceCode", where: [ @@ -811,7 +840,7 @@ export const deviceDeny = createAuthEndpoint( ], update: { status: "denied", - userId: deviceCodeRecord.userId || session.user.id, + userId: session.user.id, }, });
Vulnerability mechanics
No source-code context for this CVE — mechanics is only generated when we can read the actual fix diff. Without that, the four sections (root cause, attack vector, affected code, fix) would be speculation rather than analysis.
References
4News mentions
0No linked articles in our index yet.