From eae6b4816dd1cfbafb5f11ff078f2f96fddf4599 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:57:23 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=91=20fix:=20Refresh=20the=20Stored=20?= =?UTF-8?q?Passkey=20Backup=20State=20on=20Each=20Sign-In=20(#16255)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit verifyPasskeyAuthentication discarded credentialBackedUp, and recordPasskeyUse updated only the counter and lastUsedAt, so the stored backedUp flag kept its registration-time value and the Synced badge in account settings could go stale after an authenticator started or stopped syncing. Return the flag from the verification helper and persist it in the same compare-and-swap update that advances the counter, so a replayed assertion cannot flip it. --- packages/api/src/auth/passkey.spec.ts | 21 +++++++++++++++++-- packages/api/src/auth/passkey.ts | 8 ++++--- .../api/src/auth/passkey/handlers.spec.ts | 18 ++++++++++++++-- packages/api/src/auth/passkey/handlers.ts | 6 +++++- .../data-schemas/src/methods/passkey.spec.ts | 17 +++++++++++++++ packages/data-schemas/src/methods/passkey.ts | 14 ++++++++++--- 6 files changed, 73 insertions(+), 11 deletions(-) diff --git a/packages/api/src/auth/passkey.spec.ts b/packages/api/src/auth/passkey.spec.ts index 5da2cc1865..472819a678 100644 --- a/packages/api/src/auth/passkey.spec.ts +++ b/packages/api/src/auth/passkey.spec.ts @@ -41,9 +41,10 @@ const config: PasskeyConfig = { const user = { id: '65f0000000000000000000aa', email: 'user@example.com', name: 'Ada' }; -/** Authenticator data flags: user present, and user present plus user verified. */ +/** Authenticator data flags: user present, user present plus user verified, and backup eligible plus backed up. */ const FLAG_UP = 0x01; const FLAG_UP_UV = 0x05; +const FLAG_BE_BS = 0x18; /** * Builds a real ES256 authenticator so assertions are genuinely signed and the @@ -357,7 +358,23 @@ describe('verifyPasskeyAuthentication', () => { credential, }); - expect(result).toEqual({ newCounter: 1 }); + expect(result).toEqual({ newCounter: 1, backedUp: false }); + }); + + it('reports the backup state the authenticator asserts', async () => { + const store = createStore(); + const { assert, credential } = createAuthenticator(); + const { options, sessionId } = await createPasskeyAuthenticationOptions({ config, store }); + + const result = await verifyPasskeyAuthentication({ + config, + store, + sessionId, + response: assert({ challenge: options.challenge, flags: FLAG_UP_UV | FLAG_BE_BS }), + credential, + }); + + expect(result).toEqual({ newCounter: 1, backedUp: true }); }); it('rejects an assertion carrying only the user-present flag', async () => { diff --git a/packages/api/src/auth/passkey.ts b/packages/api/src/auth/passkey.ts index 399b831913..fe067d7984 100644 --- a/packages/api/src/auth/passkey.ts +++ b/packages/api/src/auth/passkey.ts @@ -298,7 +298,8 @@ export async function createPasskeyAuthenticationOptions({ /** * Verifies an assertion against the challenge issued for `sessionId`. - * Returns the authenticator's new signature counter on success, `null` otherwise. + * Returns the authenticator's new signature counter and current backup state on + * success, `null` otherwise. * * A passkey assertion is a complete single-factor login here, so user * verification is required: an assertion carrying only the user-present flag, @@ -316,7 +317,7 @@ export async function verifyPasskeyAuthentication({ sessionId: string; response: AuthenticationResponseJSON; credential: PasskeyCredential; -}): Promise<{ newCounter: number } | null> { +}): Promise<{ newCounter: number; backedUp: boolean } | null> { const expectedChallenge = await consumeChallenge(store, authenticationChallengeKey(sessionId)); if (!expectedChallenge) { return null; @@ -346,7 +347,8 @@ export async function verifyPasskeyAuthentication({ return null; } - return { newCounter: verification.authenticationInfo.newCounter }; + const { newCounter, credentialBackedUp } = verification.authenticationInfo; + return { newCounter, backedUp: credentialBackedUp }; } /** diff --git a/packages/api/src/auth/passkey/handlers.spec.ts b/packages/api/src/auth/passkey/handlers.spec.ts index b1916874f4..0a4ef319a1 100644 --- a/packages/api/src/auth/passkey/handlers.spec.ts +++ b/packages/api/src/auth/passkey/handlers.spec.ts @@ -164,7 +164,7 @@ beforeEach(async () => { ReturnType >); mockVerifyRegistration.mockResolvedValue(verifiedRegistration()); - mockVerifyAuthentication.mockResolvedValue({ newCounter: 1 }); + mockVerifyAuthentication.mockResolvedValue({ newCounter: 1, backedUp: false }); await mongoose.models.User.deleteMany({}); await mongoose.models.Passkey.deleteMany({}); @@ -826,7 +826,7 @@ describe('passkey sign-in', () => { const user = await createUser(); await createStoredPasskey(user); await methods.recordPasskeyUse('cred-1', 5); - mockVerifyAuthentication.mockResolvedValue({ newCounter: 3 }); + mockVerifyAuthentication.mockResolvedValue({ newCounter: 3, backedUp: false }); const req = loginReq(); const res = buildRes(); const next = jest.fn(); @@ -838,6 +838,20 @@ describe('passkey sign-in', () => { expect(res.status).toHaveBeenCalledWith(401); }); + it('persists the backup state the authenticator reports on sign-in', async () => { + const handlers = createPasskeyHandlers(buildDeps()); + const user = await createUser(); + await createStoredPasskey(user); + mockVerifyAuthentication.mockResolvedValue({ newCounter: 1, backedUp: true }); + const next = jest.fn(); + + await handlers.authenticatePasskey(loginReq(), buildRes(), next); + + expect(next).toHaveBeenCalledTimes(1); + const stored = await methods.findPasskeyByCredentialId('cred-1'); + expect(stored?.backedUp).toBe(true); + }); + it('answers 500 when a lookup throws', async () => { const handlers = createPasskeyHandlers( buildDeps({ findPasskeyByCredentialId: jest.fn().mockRejectedValue(new Error('down')) }), diff --git a/packages/api/src/auth/passkey/handlers.ts b/packages/api/src/auth/passkey/handlers.ts index 5caf194ab4..5e65e9f865 100644 --- a/packages/api/src/auth/passkey/handlers.ts +++ b/packages/api/src/auth/passkey/handlers.ts @@ -567,7 +567,11 @@ export function createPasskeyHandlers(deps: PasskeyHandlersDeps): PasskeyHandler * another assertion already consumed this counter value, so this one is a replay * or a clone even though the signature verified. */ - const counterAdvanced = await recordPasskeyUse(passkey.credentialId, result.newCounter); + const counterAdvanced = await recordPasskeyUse( + passkey.credentialId, + result.newCounter, + result.backedUp, + ); if (!counterAdvanced) { logger.warn( '[authenticatePasskey] Rejected an assertion that did not advance the signature counter', diff --git a/packages/data-schemas/src/methods/passkey.spec.ts b/packages/data-schemas/src/methods/passkey.spec.ts index 7eb142f7eb..eac73efef2 100644 --- a/packages/data-schemas/src/methods/passkey.spec.ts +++ b/packages/data-schemas/src/methods/passkey.spec.ts @@ -147,6 +147,23 @@ describe('recordPasskeyUse', () => { expect(updated?.lastUsedAt).toBeInstanceOf(Date); }); + it('refreshes the backup state alongside the counter', async () => { + await methods.createPasskey(passkeyData({ backedUp: false })); + + await expect(methods.recordPasskeyUse('credential-one', 7, true)).resolves.toBe(true); + expect((await methods.findPasskeyByCredentialId('credential-one'))?.backedUp).toBe(true); + + await expect(methods.recordPasskeyUse('credential-one', 8, false)).resolves.toBe(true); + expect((await methods.findPasskeyByCredentialId('credential-one'))?.backedUp).toBe(false); + }); + + it('leaves the backup state alone when the assertion loses the counter race', async () => { + await methods.createPasskey(passkeyData({ counter: 5, backedUp: false })); + + await expect(methods.recordPasskeyUse('credential-one', 3, true)).resolves.toBe(false); + expect((await methods.findPasskeyByCredentialId('credential-one'))?.backedUp).toBe(false); + }); + it('does not regress the counter when the new value is lower', async () => { await methods.createPasskey(passkeyData({ counter: 5 })); diff --git a/packages/data-schemas/src/methods/passkey.ts b/packages/data-schemas/src/methods/passkey.ts index ca6891a0af..67e94c4c53 100644 --- a/packages/data-schemas/src/methods/passkey.ts +++ b/packages/data-schemas/src/methods/passkey.ts @@ -8,7 +8,7 @@ export interface PasskeyMethods { findPasskeysByUser: (userId: string) => Promise; findPasskeyByCredentialId: (credentialId: string) => Promise; countPasskeysByUser: (userId: string) => Promise; - recordPasskeyUse: (credentialId: string, counter: number) => Promise; + recordPasskeyUse: (credentialId: string, counter: number, backedUp?: boolean) => Promise; renamePasskey: (passkeyId: string, userId: string, name: string) => Promise; deletePasskey: (passkeyId: string, userId: string) => Promise; deletePasskeysByUser: (userId: string) => Promise; @@ -107,7 +107,11 @@ export function createPasskeyMethods(mongoose: typeof import('mongoose')): Passk * cannot take this write cannot mint the session either. A counterless credential * has no signal to forfeit, so it is not held to the same bar. */ - async function recordPasskeyUse(credentialId: string, counter: number): Promise { + async function recordPasskeyUse( + credentialId: string, + counter: number, + backedUp?: boolean, + ): Promise { try { const Passkey = mongoose.models.Passkey; const filter = @@ -115,7 +119,11 @@ export function createPasskeyMethods(mongoose: typeof import('mongoose')): Passk ? { credentialId, counter: { $lt: counter } } : { credentialId, counter: { $lte: 0 } }; const result = await Passkey.updateOne(filter, { - $set: { counter, lastUsedAt: new Date() }, + $set: { + counter, + lastUsedAt: new Date(), + ...(backedUp === undefined ? {} : { backedUp }), + }, }).exec(); return result.matchedCount > 0; } catch (error) {