-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathpasskey.challenge.manager.ts
More file actions
279 lines (252 loc) · 9.72 KB
/
passkey.challenge.manager.ts
File metadata and controls
279 lines (252 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { Injectable, Inject, LoggerService } from '@nestjs/common';
import { LOGGER_PROVIDER } from '@fxa/shared/log';
import { StatsD, StatsDService } from '@fxa/shared/metrics/statsd';
import { Redis } from 'ioredis';
import { PasskeyConfig } from './passkey.config';
import { PASSKEY_CHALLENGE_REDIS } from './passkey.provider';
/**
* Discriminates between the three WebAuthn ceremony types.
*
* - 'registration': Attestation ceremony — adding a new passkey to an existing, verified
* account. UID is required when generating a registration challenge.
*
* - 'authentication': Assertion ceremony — discoverable credential sign-in. The server has
* NO uid when generating the challenge because `authenticationStart` is unauthenticated.
* The uid is only known after `authenticationVerify` resolves the credential ID.
*
* - 'upgrade': Assertion ceremony — PRF key-wrapping flow (`upgradeStart`/`upgradeVerify`).
* Typed separately from 'authentication' to prevent cross-ceremony attacks where an
* upgrade challenge could not be submitted to the sign-in verification endpoint and
* vice versa. UID is required when generating an upgrade challenge.
*/
export type ChallengeType = 'registration' | 'authentication' | 'upgrade';
/**
* The shape of a challenge record stored as a JSON value in Redis.
*
* Important notes:
* - `uid` is an optional hex string (not a Buffer) for clean JSON serialization.
* The Authentication (sign-in) challenges are generated before the user
* is identified and Registration and Upgrade challenges always include uid (both are
* MFA-gated and require an authenticated session), hence why it's optional.
* - `expiresAt` is informational; the Redis TTL is the authoritative expiry
* mechanism. However, the application may compare `expiresAt` against `Date.now()`
* if it receives a challenge that Redis has not yet evicted.
* - The `challenge` field (base64url-encoded 32 random bytes) is also the Redis key suffix,
* enabling direct lookup from the challenge bytes returned by the WebAuthn ceremony.
*/
export interface StoredChallenge {
/**
* Base64url-encoded 32 random bytes generated by crypto.randomBytes(32).
* This value is:
* 1. Included in the WebAuthn options returned to the client.
* 2. Signed by the authenticator and embedded in clientDataJSON.
* 3. Used as the Redis key suffix for lookup during verification.
*/
challenge: string;
/** The WebAuthn ceremony type. Validated during consumption. */
type: ChallengeType;
/**
* Hex-encoded user ID (16 bytes = 32 hex chars).
*
* Present for 'registration' and 'upgrade' challenges.
* Absent for 'authentication' challenges: sign-in uses discoverable credentials and
* authenticationStart is unauthenticated — the uid is only resolved after the ceremony.
*/
uid?: string;
/** Unix timestamp (milliseconds) when this challenge was created. */
createdAt: number;
/**
* Unix timestamp (milliseconds) when this challenge expires.
* Derived from `PasskeyConfig.challengeTimeout` (default: 300,000 ms / 5 minutes).
* Informational only — Redis TTL is the enforcement mechanism.
*/
expiresAt: number;
}
/**
* Input for generating a registration challenge.
*/
export interface CreateRegistrationChallengeInput {
uid: string;
}
/**
* Input for generating an upgrade challenge (PRF key-wrapping ceremony).
*/
export interface CreateUpgradeChallengeInput {
uid: string;
}
/**
* Manages the lifecycle of WebAuthn challenges stored in Redis.
*
* Challenges are:
* - Generated with 32 bytes of cryptographic randomness (base64url-encoded)
* - Stored in Redis with TTL-based automatic expiration
* - Single-use: atomically read and deleted during validation (GETDEL)
* - Typed to prevent cross-ceremony attacks (registration / authentication / upgrade)
*
* Redis key format: `passkey:challenge:{type}:{challengeBase64url}`
*
* @see libs/accounts/passkey/CHALLENGE_DESIGN.md
*/
@Injectable()
export class PasskeyChallengeManager {
constructor(
@Inject(PASSKEY_CHALLENGE_REDIS) private readonly redis: Redis,
private readonly config: PasskeyConfig,
@Inject(LOGGER_PROVIDER) private readonly log?: LoggerService,
@Inject(StatsDService) private readonly statsd?: StatsD
) {}
/**
* Generates a registration challenge for the WebAuthn attestation ceremony.
*
* @param uid - Hex-encoded uid of the user.
* @returns Base64url-encoded 32-byte challenge string.
*/
async storeRegistrationChallenge(
challenge: string,
uid: string
): Promise<void> {
await this.storeChallenge('registration', challenge, uid);
}
/**
* Generates an authentication challenge for the WebAuthn assertion ceremony.
*
* @returns Base64url-encoded 32-byte challenge string.
*/
async storeAuthenticationChallenge(challenge: string): Promise<void> {
await this.storeChallenge('authentication', challenge);
}
/**
* Generates an upgrade challenge for the WebAuthn PRF key-wrapping ceremony.
*
* @param uid - Hex-encoded uid of the user.
* @returns Base64url-encoded 32-byte challenge string.
*/
async storeUpgradeChallenge(challenge: string, uid: string): Promise<void> {
await this.storeChallenge('upgrade', challenge, uid);
}
/**
* Fetches and deletes a registration challenge from Redis.
*
* @param challenge - The base64url-encoded challenge string.
* @param uid - Hex-encoded uid of the user.
* @returns The stored challenge metadata or null if not found or expired.
*/
async consumeRegistrationChallenge(
challenge: string,
uid: string
): Promise<StoredChallenge | null> {
return this.consumeChallenge('registration', challenge, uid);
}
/**
* Fetches and deletes an authentication challenge from Redis.
*
* @param challenge The base64url-encoded challenge string.
* @returns The stored challenge metadata or null if not found or expired.
*/
async consumeAuthenticationChallenge(
challenge: string
): Promise<StoredChallenge | null> {
return this.consumeChallenge('authentication', challenge);
}
/**
* Fetches and deletes an upgrade challenge from Redis.
*
* @param challenge - The base64url-encoded challenge string.
* @param uid - Hex-encoded uid of the user.
* @returns The stored challenge metadata or null if not found or expired.
*/
async consumeUpgradeChallenge(
challenge: string,
uid: string
): Promise<StoredChallenge | null> {
return this.consumeChallenge('upgrade', challenge, uid);
}
/**
* Explicitly deletes a challenge from Redis.
*
* Intended for error-path cleanup (e.g., when a ceremony fails after the challenge
* has already been consumed). GETDEL in validateChallenge handles the normal case.
* This method succeeds silently even if the key does not exist.
*
* @param type - The challenge type (used to reconstruct the Redis key).
* @param challenge - The base64url-encoded challenge to delete.
* @param uid - The hex-encoded uid of the user.
*/
async deleteChallenge(
type: ChallengeType,
challenge: string,
uid: string
): Promise<void> {
const key = this.buildKey(type, challenge, uid);
await this.redis.del(key);
this.log?.debug?.('passkey.challenge.deleted', { type });
this.statsd?.increment('passkey.challenge.deleted', { type });
}
/**
* Atomically consumes a challenge from Redis.
*
* Uses GETDEL to read and delete the challenge in a single atomic
* operation, enforcing single-use semantics. Returns null if not found, expired,
* or if the stored value is invalid JSON.
*
* @param type - The expected challenge type (prevents cross-ceremony attacks).
* @param challenge - The base64url-encoded challenge from the WebAuthn ceremony.
* @param uid - Optional hex-encoded uid
* @returns The stored challenge metadata (uid, type, timestamps) or null if not found expired.
*/
private async consumeChallenge(
type: ChallengeType,
challenge: string,
uid?: string
): Promise<StoredChallenge | null> {
const key = this.buildKey(type, challenge, uid);
const raw = await this.redis.getdel(key);
if (raw === null) {
this.log?.warn('passkey.challenge.notFound', { type });
this.statsd?.increment('passkey.challenge.notFound', { type });
return null;
}
try {
const stored: StoredChallenge = JSON.parse(raw);
this.log?.debug?.('passkey.challenge.validated', { type });
this.statsd?.increment('passkey.challenge.validated', { type });
return stored;
} catch (err) {
this.log?.error('passkey.challenge.invalidJson', { type, error: err });
this.statsd?.increment('passkey.challenge.invalidJson', { type });
return null;
}
}
private async storeChallenge(
type: ChallengeType,
challenge: string,
uid?: string
): Promise<void> {
const now = Date.now();
const timeout = this.config.challengeTimeout;
const ttlSeconds = Math.ceil(timeout / 1000);
const stored: StoredChallenge = {
challenge,
type,
uid,
createdAt: now,
expiresAt: now + timeout,
};
const key = this.buildKey(type, challenge, uid);
await this.redis.set(key, JSON.stringify(stored), 'EX', ttlSeconds);
this.log?.debug?.('passkey.challenge.generated', { type, uid });
this.statsd?.increment('passkey.challenge.generated', { type });
}
private buildKey(
type: ChallengeType,
challenge: string,
uid?: string
): string {
return uid
? `passkey:challenge:${type}:${challenge}:${uid}`
: `passkey:challenge:${type}:${challenge}`;
}
}