🔑 fix: Refresh the Stored Passkey Backup State on Each Sign-In (#16255)

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.
This commit is contained in:
Marco Beretta 2026-09-23 23:57:23 +02:00 • committed by GitHub
parent 59014b53c2
commit eae6b4816d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 73 additions and 11 deletions

View file

@ -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 () => {

View file

@ -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 };
}
/**

View file

@ -164,7 +164,7 @@ beforeEach(async () => {
ReturnType<typeof createPasskeyRegistrationOptions>
>);
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')) }),

View file

@ -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',

View file

@ -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 }));

View file

@ -8,7 +8,7 @@ export interface PasskeyMethods {
findPasskeysByUser: (userId: string) => Promise<IPasskey[]>;
findPasskeyByCredentialId: (credentialId: string) => Promise<IPasskey | null>;
countPasskeysByUser: (userId: string) => Promise<number>;
recordPasskeyUse: (credentialId: string, counter: number) => Promise<boolean>;
recordPasskeyUse: (credentialId: string, counter: number, backedUp?: boolean) => Promise<boolean>;
renamePasskey: (passkeyId: string, userId: string, name: string) => Promise<IPasskey | null>;
deletePasskey: (passkeyId: string, userId: string) => Promise<DeleteResult>;
deletePasskeysByUser: (userId: string) => Promise<DeleteResult>;
@ -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<boolean> {
async function recordPasskeyUse(
credentialId: string,
counter: number,
backedUp?: boolean,
): Promise<boolean> {
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) {