@zero-server/auth 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,946 @@
1
+ /**
2
+ * @module auth/webauthn
3
+ * @description Zero-dependency WebAuthn/FIDO2/Passkeys implementation.
4
+ * Supports registration (attestation) and authentication (assertion)
5
+ * ceremonies using only Node.js built-in `crypto`.
6
+ *
7
+ * Implements:
8
+ * - Challenge generation (cryptographically random, ≥16 bytes)
9
+ * - Registration options & verification (none, packed, fido-u2f attestation)
10
+ * - Authentication options & verification with counter validation
11
+ * - CBOR decoding for attestation objects and authenticator data
12
+ * - COSE key parsing (EC2/P-256, RSA, OKP/Ed25519)
13
+ * - ES256, RS256, EdDSA signature verification
14
+ *
15
+ * @see https://www.w3.org/TR/webauthn-2/
16
+ *
17
+ * @example | Registration
18
+ * const { webauthn } = require('@zero-server/sdk');
19
+ * const options = webauthn.generateRegistrationOptions({
20
+ * rpName: 'My App', rpId: 'myapp.com',
21
+ * userId: user.id, userName: user.email,
22
+ * });
23
+ * // Send options to client, receive response from navigator.credentials.create()
24
+ * const result = await webauthn.verifyRegistration({
25
+ * response: clientResponse,
26
+ * expectedChallenge: storedChallenge,
27
+ * expectedOrigin: 'https://myapp.com',
28
+ * expectedRPID: 'myapp.com',
29
+ * });
30
+ *
31
+ * @example | Authentication
32
+ * const authOpts = webauthn.generateAuthenticationOptions({
33
+ * rpId: 'myapp.com',
34
+ * allowCredentials: user.credentials,
35
+ * });
36
+ * const authResult = await webauthn.verifyAuthentication({
37
+ * response: clientResponse,
38
+ * expectedChallenge: storedChallenge,
39
+ * expectedOrigin: 'https://myapp.com',
40
+ * expectedRPID: 'myapp.com',
41
+ * credential: storedCredential,
42
+ * });
43
+ */
44
+
45
+ const crypto = require('crypto');
46
+ const log = require('../debug')('zero:webauthn');
47
+
48
+ // -- CBOR Decoder (minimal, spec-compliant subset) --------
49
+
50
+ /**
51
+ * Minimal CBOR decoder supporting the types used in WebAuthn attestation objects.
52
+ * Handles: unsigned/negative ints, byte strings, text strings, arrays, maps, booleans, null.
53
+ * @private
54
+ */
55
+ const cbor = {
56
+ /**
57
+ * Decode a CBOR-encoded Buffer.
58
+ * @param {Buffer} buf
59
+ * @returns {*} Decoded value
60
+ */
61
+ decode(buf)
62
+ {
63
+ let offset = 0;
64
+
65
+ function readUint8() { return buf[offset++]; }
66
+
67
+ function readArgument(additionalInfo)
68
+ {
69
+ if (additionalInfo < 24) return additionalInfo;
70
+ if (additionalInfo === 24) { const v = buf[offset++]; return v; }
71
+ if (additionalInfo === 25) { const v = buf.readUInt16BE(offset); offset += 2; return v; }
72
+ if (additionalInfo === 26) { const v = buf.readUInt32BE(offset); offset += 4; return v; }
73
+ if (additionalInfo === 27)
74
+ {
75
+ const hi = buf.readUInt32BE(offset);
76
+ const lo = buf.readUInt32BE(offset + 4);
77
+ offset += 8;
78
+ // Return as Number if safe, otherwise BigInt
79
+ const val = hi * 0x100000000 + lo;
80
+ return val;
81
+ }
82
+ throw new Error('CBOR: unsupported additional info: ' + additionalInfo);
83
+ }
84
+
85
+ function decodeItem()
86
+ {
87
+ const initial = readUint8();
88
+ const majorType = initial >> 5;
89
+ const additionalInfo = initial & 0x1f;
90
+
91
+ switch (majorType)
92
+ {
93
+ case 0: // unsigned integer
94
+ return readArgument(additionalInfo);
95
+
96
+ case 1: // negative integer
97
+ return -1 - readArgument(additionalInfo);
98
+
99
+ case 2: // byte string
100
+ {
101
+ const len = readArgument(additionalInfo);
102
+ const bytes = buf.subarray(offset, offset + len);
103
+ offset += len;
104
+ return Buffer.from(bytes);
105
+ }
106
+
107
+ case 3: // text string
108
+ {
109
+ const len = readArgument(additionalInfo);
110
+ const text = buf.toString('utf8', offset, offset + len);
111
+ offset += len;
112
+ return text;
113
+ }
114
+
115
+ case 4: // array
116
+ {
117
+ const len = readArgument(additionalInfo);
118
+ const arr = [];
119
+ for (let i = 0; i < len; i++) arr.push(decodeItem());
120
+ return arr;
121
+ }
122
+
123
+ case 5: // map
124
+ {
125
+ const len = readArgument(additionalInfo);
126
+ const map = {};
127
+ for (let i = 0; i < len; i++)
128
+ {
129
+ const key = decodeItem();
130
+ const value = decodeItem();
131
+ map[key] = value;
132
+ }
133
+ return map;
134
+ }
135
+
136
+ case 6: // tag (skip tag number, decode value)
137
+ readArgument(additionalInfo);
138
+ return decodeItem();
139
+
140
+ case 7: // simple/float
141
+ {
142
+ if (additionalInfo === 20) return false;
143
+ if (additionalInfo === 21) return true;
144
+ if (additionalInfo === 22) return null;
145
+ if (additionalInfo === 23) return undefined;
146
+ if (additionalInfo === 25)
147
+ {
148
+ // float16 — not commonly used in WebAuthn but handle it
149
+ offset -= 0; // already read
150
+ return readArgument(additionalInfo);
151
+ }
152
+ if (additionalInfo === 26)
153
+ {
154
+ const fbuf = buf.subarray(offset, offset + 4);
155
+ offset += 4;
156
+ return fbuf.readFloatBE(0);
157
+ }
158
+ if (additionalInfo === 27)
159
+ {
160
+ const fbuf = buf.subarray(offset, offset + 8);
161
+ offset += 8;
162
+ return fbuf.readDoubleBE(0);
163
+ }
164
+ return additionalInfo;
165
+ }
166
+
167
+ default:
168
+ throw new Error('CBOR: unknown major type ' + majorType);
169
+ }
170
+ }
171
+
172
+ return decodeItem();
173
+ },
174
+ };
175
+
176
+ // -- COSE Key Parsing --------------------------------------
177
+
178
+ /**
179
+ * COSE key type identifiers.
180
+ * @private
181
+ */
182
+ const COSE_KEY_TYPE = { OKP: 1, EC2: 2, RSA: 3 };
183
+ const COSE_ALG = { ES256: -7, RS256: -257, EDDSA: -8 };
184
+ const COSE_CRV = { P256: 1, ED25519: 6 };
185
+
186
+ /**
187
+ * Convert a COSE public key (from attestation) to a Node.js crypto key object.
188
+ * @private
189
+ * @param {object} coseKey - COSE key map (numeric keys).
190
+ * @returns {{ key: crypto.KeyObject, algorithm: string }}
191
+ */
192
+ function _coseToPublicKey(coseKey)
193
+ {
194
+ const kty = coseKey[1]; // Key type
195
+ const alg = coseKey[3]; // Algorithm
196
+
197
+ if (kty === COSE_KEY_TYPE.EC2)
198
+ {
199
+ // EC2 key (P-256)
200
+ const x = coseKey[-2];
201
+ const y = coseKey[-3];
202
+ if (!x || !y) throw new Error('EC2 COSE key missing x or y coordinate');
203
+
204
+ // Uncompressed point: 0x04 || x || y
205
+ const publicKeyBuffer = Buffer.concat([Buffer.from([0x04]), x, y]);
206
+
207
+ // DER encode as SubjectPublicKeyInfo for P-256
208
+ const key = crypto.createPublicKey({
209
+ key: _ecPublicKeyToDER(publicKeyBuffer),
210
+ format: 'der',
211
+ type: 'spki',
212
+ });
213
+
214
+ return { key, algorithm: 'ES256' };
215
+ }
216
+
217
+ if (kty === COSE_KEY_TYPE.RSA)
218
+ {
219
+ const n = coseKey[-1]; // modulus
220
+ const e = coseKey[-2]; // exponent
221
+ if (!n || !e) throw new Error('RSA COSE key missing n or e');
222
+
223
+ const key = crypto.createPublicKey({
224
+ key: _rsaPublicKeyToDER(n, e),
225
+ format: 'der',
226
+ type: 'spki',
227
+ });
228
+
229
+ return { key, algorithm: 'RS256' };
230
+ }
231
+
232
+ if (kty === COSE_KEY_TYPE.OKP)
233
+ {
234
+ const crv = coseKey[-1];
235
+ const x = coseKey[-2];
236
+ if (!x) throw new Error('OKP COSE key missing x coordinate');
237
+
238
+ if (crv === COSE_CRV.ED25519)
239
+ {
240
+ const key = crypto.createPublicKey({
241
+ key: _ed25519PublicKeyToDER(x),
242
+ format: 'der',
243
+ type: 'spki',
244
+ });
245
+ return { key, algorithm: 'EdDSA' };
246
+ }
247
+ throw new Error('Unsupported OKP curve: ' + crv);
248
+ }
249
+
250
+ throw new Error('Unsupported COSE key type: ' + kty);
251
+ }
252
+
253
+ // -- DER Encoding Helpers ----------------------------------
254
+
255
+ /** @private ASN.1 DER sequence tag */
256
+ const ASN1_SEQUENCE = 0x30;
257
+ const ASN1_BIT_STRING = 0x03;
258
+ const ASN1_OID = 0x06;
259
+ const ASN1_INTEGER = 0x02;
260
+ const ASN1_NULL = 0x05;
261
+
262
+ /** @private P-256 OID: 1.2.840.10045.3.1.7 */
263
+ const EC_P256_OID = Buffer.from('2a8648ce3d030107', 'hex');
264
+ /** @private EC public key OID: 1.2.840.10045.2.1 */
265
+ const EC_PUB_OID = Buffer.from('2a8648ce3d0201', 'hex');
266
+ /** @private RSA OID: 1.2.840.113549.1.1.1 */
267
+ const RSA_OID = Buffer.from('2a864886f70d010101', 'hex');
268
+ /** @private Ed25519 OID: 1.3.101.112 */
269
+ const ED25519_OID = Buffer.from('06032b6570', 'hex'); // includes tag+length
270
+
271
+ /**
272
+ * Encode a length in DER format.
273
+ * @private
274
+ * @param {number} len
275
+ * @returns {Buffer}
276
+ */
277
+ function _derLength(len)
278
+ {
279
+ if (len < 0x80) return Buffer.from([len]);
280
+ if (len < 0x100) return Buffer.from([0x81, len]);
281
+ return Buffer.from([0x82, (len >> 8) & 0xff, len & 0xff]);
282
+ }
283
+
284
+ /**
285
+ * Wrap data in a DER sequence.
286
+ * @private
287
+ * @param {Buffer[]} items
288
+ * @returns {Buffer}
289
+ */
290
+ function _derSequence(...items)
291
+ {
292
+ const body = Buffer.concat(items);
293
+ return Buffer.concat([Buffer.from([ASN1_SEQUENCE]), _derLength(body.length), body]);
294
+ }
295
+
296
+ /**
297
+ * Create a DER bit string.
298
+ * @private
299
+ * @param {Buffer} data
300
+ * @returns {Buffer}
301
+ */
302
+ function _derBitString(data)
303
+ {
304
+ // Unused bits = 0
305
+ const body = Buffer.concat([Buffer.from([0x00]), data]);
306
+ return Buffer.concat([Buffer.from([ASN1_BIT_STRING]), _derLength(body.length), body]);
307
+ }
308
+
309
+ /**
310
+ * Create a DER OID element.
311
+ * @private
312
+ * @param {Buffer} oidBytes - Raw OID bytes (without tag/length).
313
+ * @returns {Buffer}
314
+ */
315
+ function _derOID(oidBytes)
316
+ {
317
+ return Buffer.concat([Buffer.from([ASN1_OID]), _derLength(oidBytes.length), oidBytes]);
318
+ }
319
+
320
+ /**
321
+ * Convert an EC P-256 uncompressed point to SubjectPublicKeyInfo DER.
322
+ * @private
323
+ * @param {Buffer} uncompressedPoint - 65 bytes (0x04 || x || y)
324
+ * @returns {Buffer}
325
+ */
326
+ function _ecPublicKeyToDER(uncompressedPoint)
327
+ {
328
+ const algorithmIdentifier = _derSequence(
329
+ _derOID(EC_PUB_OID),
330
+ _derOID(EC_P256_OID),
331
+ );
332
+ const subjectPublicKey = _derBitString(uncompressedPoint);
333
+ return _derSequence(algorithmIdentifier, subjectPublicKey);
334
+ }
335
+
336
+ /**
337
+ * Encode a positive integer with DER integer rules (prepend 0x00 if high bit set).
338
+ * @private
339
+ * @param {Buffer} buf
340
+ * @returns {Buffer}
341
+ */
342
+ function _derInteger(buf)
343
+ {
344
+ // Strip leading zeros but ensure non-negative
345
+ let start = 0;
346
+ while (start < buf.length - 1 && buf[start] === 0) start++;
347
+ let trimmed = buf.subarray(start);
348
+ if (trimmed[0] & 0x80) trimmed = Buffer.concat([Buffer.from([0x00]), trimmed]);
349
+ return Buffer.concat([Buffer.from([ASN1_INTEGER]), _derLength(trimmed.length), trimmed]);
350
+ }
351
+
352
+ /**
353
+ * Convert RSA n,e to SubjectPublicKeyInfo DER.
354
+ * @private
355
+ * @param {Buffer} n - Modulus
356
+ * @param {Buffer} e - Exponent
357
+ * @returns {Buffer}
358
+ */
359
+ function _rsaPublicKeyToDER(n, e)
360
+ {
361
+ const algorithmIdentifier = _derSequence(
362
+ _derOID(RSA_OID),
363
+ Buffer.from([ASN1_NULL, 0x00]),
364
+ );
365
+ const rsaPublicKey = _derSequence(_derInteger(n), _derInteger(e));
366
+ const subjectPublicKey = _derBitString(rsaPublicKey);
367
+ return _derSequence(algorithmIdentifier, subjectPublicKey);
368
+ }
369
+
370
+ /**
371
+ * Convert Ed25519 public key bytes to SubjectPublicKeyInfo DER.
372
+ * @private
373
+ * @param {Buffer} pubBytes - 32-byte public key
374
+ * @returns {Buffer}
375
+ */
376
+ function _ed25519PublicKeyToDER(pubBytes)
377
+ {
378
+ // AlgorithmIdentifier: SEQUENCE { OID 1.3.101.112 }
379
+ const algorithmIdentifier = _derSequence(ED25519_OID);
380
+ const subjectPublicKey = _derBitString(pubBytes);
381
+ return _derSequence(algorithmIdentifier, subjectPublicKey);
382
+ }
383
+
384
+ // -- Authenticator Data Parsing ----------------------------
385
+
386
+ /**
387
+ * Parse authenticator data buffer.
388
+ * @private
389
+ * @param {Buffer} authData
390
+ * @returns {object}
391
+ */
392
+ function _parseAuthData(authData)
393
+ {
394
+ let offset = 0;
395
+
396
+ // rpIdHash (32 bytes)
397
+ const rpIdHash = authData.subarray(offset, offset + 32);
398
+ offset += 32;
399
+
400
+ // flags (1 byte)
401
+ const flags = authData[offset++];
402
+ const userPresent = !!(flags & 0x01);
403
+ const userVerified = !!(flags & 0x04);
404
+ const attestedCredDataIncluded = !!(flags & 0x40);
405
+ const extensionDataIncluded = !!(flags & 0x80);
406
+
407
+ // signCount (4 bytes, big-endian)
408
+ const signCount = authData.readUInt32BE(offset);
409
+ offset += 4;
410
+
411
+ let aaguid = null;
412
+ let credentialId = null;
413
+ let credentialPublicKey = null;
414
+
415
+ if (attestedCredDataIncluded)
416
+ {
417
+ // AAGUID (16 bytes)
418
+ aaguid = authData.subarray(offset, offset + 16);
419
+ offset += 16;
420
+
421
+ // Credential ID length (2 bytes, big-endian)
422
+ const credIdLen = authData.readUInt16BE(offset);
423
+ offset += 2;
424
+
425
+ // Credential ID
426
+ credentialId = authData.subarray(offset, offset + credIdLen);
427
+ offset += credIdLen;
428
+
429
+ // Credential public key (CBOR-encoded COSE key)
430
+ credentialPublicKey = cbor.decode(authData.subarray(offset));
431
+ }
432
+
433
+ return {
434
+ rpIdHash,
435
+ flags,
436
+ userPresent,
437
+ userVerified,
438
+ signCount,
439
+ attestedCredDataIncluded,
440
+ extensionDataIncluded,
441
+ aaguid,
442
+ credentialId,
443
+ credentialPublicKey,
444
+ };
445
+ }
446
+
447
+ // -- Challenge Generation ---------------------------------
448
+
449
+ /**
450
+ * Generate a cryptographically random challenge.
451
+ * @private
452
+ * @param {number} [bytes=32] - Number of random bytes (minimum 16).
453
+ * @returns {Buffer}
454
+ */
455
+ function _generateChallenge(bytes = 32)
456
+ {
457
+ if (bytes < 16) throw new Error('Challenge must be at least 16 bytes');
458
+ return crypto.randomBytes(bytes);
459
+ }
460
+
461
+ // -- Base64URL Helpers ------------------------------------
462
+
463
+ /**
464
+ * @private
465
+ * @param {Buffer|string} data
466
+ * @returns {string}
467
+ */
468
+ function _toBase64Url(data)
469
+ {
470
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
471
+ return buf.toString('base64url');
472
+ }
473
+
474
+ /**
475
+ * @private
476
+ * @param {string} str
477
+ * @returns {Buffer}
478
+ */
479
+ function _fromBase64Url(str)
480
+ {
481
+ return Buffer.from(str, 'base64url');
482
+ }
483
+
484
+ // -- Registration (Attestation) ----------------------------
485
+
486
+ /**
487
+ * Generate options for `navigator.credentials.create()`.
488
+ *
489
+ * @param {object} opts - Registration options.
490
+ * @param {string} opts.rpName - Relying Party display name.
491
+ * @param {string} opts.rpId - Relying Party ID (effective domain, e.g. 'myapp.com').
492
+ * @param {string|Buffer} opts.userId - Opaque user handle.
493
+ * @param {string} opts.userName - User display name / email.
494
+ * @param {string} [opts.attestation='none'] - Attestation conveyance: 'none', 'direct', 'indirect'.
495
+ * @param {object} [opts.authenticatorSelection] - Authenticator selection criteria.
496
+ * @param {Array} [opts.excludeCredentials] - Credentials to exclude (prevent re-registration).
497
+ * @param {number} [opts.timeout=60000] - Timeout in milliseconds.
498
+ * @param {number} [opts.challengeBytes=32] - Challenge size in bytes.
499
+ * @returns {{ options: object, challenge: string }} Options and base64url-encoded challenge.
500
+ *
501
+ * @example
502
+ * const { options, challenge } = webauthn.generateRegistrationOptions({
503
+ * rpName: 'My App', rpId: 'myapp.com',
504
+ * userId: user.id, userName: user.email,
505
+ * });
506
+ * // Store challenge in session, send options to client
507
+ */
508
+ function generateRegistrationOptions(opts)
509
+ {
510
+ if (!opts || !opts.rpName || !opts.rpId || !opts.userId || !opts.userName)
511
+ throw new Error('generateRegistrationOptions requires rpName, rpId, userId, and userName');
512
+
513
+ const challenge = _generateChallenge(opts.challengeBytes || 32);
514
+ const challengeB64 = _toBase64Url(challenge);
515
+
516
+ const userIdBuf = Buffer.isBuffer(opts.userId) ? opts.userId : Buffer.from(String(opts.userId));
517
+
518
+ const options = {
519
+ rp: {
520
+ name: opts.rpName,
521
+ id: opts.rpId,
522
+ },
523
+ user: {
524
+ id: _toBase64Url(userIdBuf),
525
+ name: opts.userName,
526
+ displayName: opts.userDisplayName || opts.userName,
527
+ },
528
+ challenge: challengeB64,
529
+ pubKeyCredParams: [
530
+ { type: 'public-key', alg: COSE_ALG.ES256 },
531
+ { type: 'public-key', alg: COSE_ALG.RS256 },
532
+ { type: 'public-key', alg: COSE_ALG.EDDSA },
533
+ ],
534
+ timeout: opts.timeout || 60000,
535
+ attestation: opts.attestation || 'none',
536
+ authenticatorSelection: opts.authenticatorSelection || {
537
+ residentKey: 'preferred',
538
+ userVerification: 'required',
539
+ },
540
+ };
541
+
542
+ if (opts.excludeCredentials && opts.excludeCredentials.length > 0)
543
+ {
544
+ options.excludeCredentials = opts.excludeCredentials.map(cred => ({
545
+ type: 'public-key',
546
+ id: typeof cred.id === 'string' ? cred.id : _toBase64Url(cred.id),
547
+ transports: cred.transports || [],
548
+ }));
549
+ }
550
+
551
+ return { options, challenge: challengeB64 };
552
+ }
553
+
554
+ /**
555
+ * Verify a registration response from `navigator.credentials.create()`.
556
+ *
557
+ * @param {object} opts - Verification options.
558
+ * @param {object} opts.response - The credential response from the client.
559
+ * @param {string} opts.response.id - Credential ID (base64url).
560
+ * @param {string} opts.response.type - Must be 'public-key'.
561
+ * @param {object} opts.response.response - The AuthenticatorAttestationResponse.
562
+ * @param {string} opts.response.response.clientDataJSON - Base64url-encoded client data.
563
+ * @param {string} opts.response.response.attestationObject - Base64url-encoded attestation.
564
+ * @param {string} opts.expectedChallenge - The challenge sent during registration (base64url).
565
+ * @param {string} opts.expectedOrigin - Expected origin (e.g. 'https://myapp.com').
566
+ * @param {string} opts.expectedRPID - Expected RP ID.
567
+ * @returns {{ verified: boolean, credential: { id: string, publicKey: Buffer, counter: number, transports: string[] }|null, error: string|null }}
568
+ *
569
+ * @example
570
+ * const result = await webauthn.verifyRegistration({
571
+ * response: clientResponse,
572
+ * expectedChallenge: storedChallenge,
573
+ * expectedOrigin: 'https://myapp.com',
574
+ * expectedRPID: 'myapp.com',
575
+ * });
576
+ * if (result.verified) {
577
+ * // Store result.credential in database
578
+ * }
579
+ */
580
+ function verifyRegistration(opts)
581
+ {
582
+ try
583
+ {
584
+ const { response, expectedChallenge, expectedOrigin, expectedRPID } = opts;
585
+
586
+ if (!response || !response.response)
587
+ return { verified: false, credential: null, error: 'Missing response' };
588
+
589
+ // 1. Decode and validate clientDataJSON
590
+ const clientDataBuf = _fromBase64Url(response.response.clientDataJSON);
591
+ const clientData = JSON.parse(clientDataBuf.toString('utf8'));
592
+
593
+ if (clientData.type !== 'webauthn.create')
594
+ return { verified: false, credential: null, error: `Invalid type: ${clientData.type}` };
595
+
596
+ // Strict origin validation — exact match, no regex
597
+ if (clientData.origin !== expectedOrigin)
598
+ return { verified: false, credential: null, error: `Origin mismatch: ${clientData.origin}` };
599
+
600
+ // Challenge validation
601
+ if (clientData.challenge !== expectedChallenge)
602
+ return { verified: false, credential: null, error: 'Challenge mismatch' };
603
+
604
+ // 2. Decode attestation object
605
+ const attestationBuf = _fromBase64Url(response.response.attestationObject);
606
+ const attestationObject = cbor.decode(attestationBuf);
607
+
608
+ // 3. Parse authenticator data
609
+ const authData = _parseAuthData(attestationObject.authData);
610
+
611
+ // 4. Validate RP ID hash
612
+ const expectedRPIDHash = crypto.createHash('sha256').update(expectedRPID).digest();
613
+ if (!authData.rpIdHash.equals(expectedRPIDHash))
614
+ return { verified: false, credential: null, error: 'RP ID hash mismatch' };
615
+
616
+ // 5. User presence must be set
617
+ if (!authData.userPresent)
618
+ return { verified: false, credential: null, error: 'User not present' };
619
+
620
+ // 6. Must have attested credential data
621
+ if (!authData.attestedCredDataIncluded || !authData.credentialId)
622
+ return { verified: false, credential: null, error: 'No credential data in attestation' };
623
+
624
+ // 7. Verify attestation statement (format-specific)
625
+ const fmt = attestationObject.fmt;
626
+ const attStmt = attestationObject.attStmt || {};
627
+
628
+ if (fmt === 'none')
629
+ {
630
+ // No attestation — acceptable for 'none' conveyance
631
+ log.debug('registration with "none" attestation format');
632
+ }
633
+ else if (fmt === 'packed')
634
+ {
635
+ const verified = _verifyPackedAttestation(attStmt, authData, attestationObject.authData, clientDataBuf);
636
+ if (!verified)
637
+ return { verified: false, credential: null, error: 'Packed attestation verification failed' };
638
+ }
639
+ else if (fmt === 'fido-u2f')
640
+ {
641
+ const verified = _verifyFidoU2FAttestation(attStmt, authData, attestationObject.authData, clientDataBuf);
642
+ if (!verified)
643
+ return { verified: false, credential: null, error: 'FIDO U2F attestation verification failed' };
644
+ }
645
+ else
646
+ {
647
+ log.warn('unknown attestation format: %s — treating as none', fmt);
648
+ }
649
+
650
+ // 8. Extract public key from COSE format
651
+ const { key: publicKeyObj } = _coseToPublicKey(authData.credentialPublicKey);
652
+ const publicKeyDer = publicKeyObj.export({ type: 'spki', format: 'der' });
653
+
654
+ const credential = {
655
+ id: response.id || _toBase64Url(authData.credentialId),
656
+ publicKey: publicKeyDer,
657
+ counter: authData.signCount,
658
+ transports: response.response.transports || response.transports || [],
659
+ };
660
+
661
+ log.info('WebAuthn registration verified (credId=%s)', credential.id.substring(0, 16) + '...');
662
+ return { verified: true, credential, error: null };
663
+ }
664
+ catch (err)
665
+ {
666
+ log.error('WebAuthn registration verification error: %s', err.message);
667
+ return { verified: false, credential: null, error: err.message };
668
+ }
669
+ }
670
+
671
+ /**
672
+ * Verify a packed attestation signature (self-attestation).
673
+ * @private
674
+ */
675
+ function _verifyPackedAttestation(attStmt, parsedAuthData, rawAuthData, clientDataBuf)
676
+ {
677
+ const sig = attStmt.sig;
678
+ const alg = attStmt.alg;
679
+ if (!sig) return false;
680
+
681
+ // Hash of clientDataJSON
682
+ const clientDataHash = crypto.createHash('sha256').update(clientDataBuf).digest();
683
+
684
+ // Signed data = authData || clientDataHash
685
+ const signedData = Buffer.concat([rawAuthData, clientDataHash]);
686
+
687
+ if (attStmt.x5c && attStmt.x5c.length > 0)
688
+ {
689
+ // Full attestation with certificate chain
690
+ const certDer = attStmt.x5c[0];
691
+ try
692
+ {
693
+ const cert = new crypto.X509Certificate(certDer);
694
+ const pubKey = cert.publicKey;
695
+ const algName = _coseAlgToNodeAlg(alg);
696
+ return crypto.verify(algName, signedData, pubKey, sig);
697
+ }
698
+ catch (err)
699
+ {
700
+ log.warn('packed attestation cert verification failed: %s', err.message);
701
+ return false;
702
+ }
703
+ }
704
+ else
705
+ {
706
+ // Self-attestation — verify with the credential public key
707
+ const { key } = _coseToPublicKey(parsedAuthData.credentialPublicKey);
708
+ const algName = _coseAlgToNodeAlg(alg);
709
+ return crypto.verify(algName, signedData, key, sig);
710
+ }
711
+ }
712
+
713
+ /**
714
+ * Verify a FIDO U2F attestation.
715
+ * @private
716
+ */
717
+ function _verifyFidoU2FAttestation(attStmt, parsedAuthData, rawAuthData, clientDataBuf)
718
+ {
719
+ const sig = attStmt.sig;
720
+ const x5c = attStmt.x5c;
721
+ if (!sig || !x5c || x5c.length === 0) return false;
722
+
723
+ const clientDataHash = crypto.createHash('sha256').update(clientDataBuf).digest();
724
+
725
+ // Extract public key coordinates
726
+ const coseKey = parsedAuthData.credentialPublicKey;
727
+ const x = coseKey[-2];
728
+ const y = coseKey[-3];
729
+ const publicKeyU2F = Buffer.concat([Buffer.from([0x04]), x, y]);
730
+
731
+ // Verification data: 0x00 || rpIdHash || clientDataHash || credentialId || publicKeyU2F
732
+ const verificationData = Buffer.concat([
733
+ Buffer.from([0x00]),
734
+ parsedAuthData.rpIdHash,
735
+ clientDataHash,
736
+ parsedAuthData.credentialId,
737
+ publicKeyU2F,
738
+ ]);
739
+
740
+ try
741
+ {
742
+ const cert = new crypto.X509Certificate(x5c[0]);
743
+ return crypto.verify('SHA256', verificationData, cert.publicKey, sig);
744
+ }
745
+ catch (err)
746
+ {
747
+ log.warn('FIDO U2F attestation verification failed: %s', err.message);
748
+ return false;
749
+ }
750
+ }
751
+
752
+ /**
753
+ * Map COSE algorithm identifier to Node.js algorithm name.
754
+ * @private
755
+ * @param {number} alg
756
+ * @returns {string|null}
757
+ */
758
+ function _coseAlgToNodeAlg(alg)
759
+ {
760
+ switch (alg)
761
+ {
762
+ case COSE_ALG.ES256: return 'SHA256';
763
+ case COSE_ALG.RS256: return 'SHA256';
764
+ case COSE_ALG.EDDSA: return null; // Ed25519 doesn't use separate hash
765
+ default: return 'SHA256';
766
+ }
767
+ }
768
+
769
+ // -- Authentication (Assertion) ----------------------------
770
+
771
+ /**
772
+ * Generate options for `navigator.credentials.get()`.
773
+ *
774
+ * @param {object} opts - Authentication options.
775
+ * @param {string} opts.rpId - Relying Party ID.
776
+ * @param {Array} [opts.allowCredentials] - Allowed credentials.
777
+ * @param {string} [opts.userVerification='required'] - User verification requirement.
778
+ * @param {number} [opts.timeout=60000] - Timeout in milliseconds.
779
+ * @param {number} [opts.challengeBytes=32] - Challenge size in bytes.
780
+ * @returns {{ options: object, challenge: string }} Options and challenge.
781
+ *
782
+ * @example
783
+ * const { options, challenge } = webauthn.generateAuthenticationOptions({
784
+ * rpId: 'myapp.com',
785
+ * allowCredentials: user.credentials.map(c => ({ id: c.id, transports: c.transports })),
786
+ * });
787
+ */
788
+ function generateAuthenticationOptions(opts)
789
+ {
790
+ if (!opts || !opts.rpId)
791
+ throw new Error('generateAuthenticationOptions requires rpId');
792
+
793
+ const challenge = _generateChallenge(opts.challengeBytes || 32);
794
+ const challengeB64 = _toBase64Url(challenge);
795
+
796
+ const options = {
797
+ challenge: challengeB64,
798
+ rpId: opts.rpId,
799
+ timeout: opts.timeout || 60000,
800
+ userVerification: opts.userVerification || 'required',
801
+ };
802
+
803
+ if (opts.allowCredentials && opts.allowCredentials.length > 0)
804
+ {
805
+ options.allowCredentials = opts.allowCredentials.map(cred => ({
806
+ type: 'public-key',
807
+ id: typeof cred.id === 'string' ? cred.id : _toBase64Url(cred.id),
808
+ transports: cred.transports || [],
809
+ }));
810
+ }
811
+
812
+ return { options, challenge: challengeB64 };
813
+ }
814
+
815
+ /**
816
+ * Verify an authentication response from `navigator.credentials.get()`.
817
+ *
818
+ * @param {object} opts - Verification options.
819
+ * @param {object} opts.response - The credential response from the client.
820
+ * @param {string} opts.response.id - Credential ID (base64url).
821
+ * @param {object} opts.response.response - AuthenticatorAssertionResponse.
822
+ * @param {string} opts.response.response.clientDataJSON - Base64url client data.
823
+ * @param {string} opts.response.response.authenticatorData - Base64url authenticator data.
824
+ * @param {string} opts.response.response.signature - Base64url signature.
825
+ * @param {string} opts.expectedChallenge - Challenge (base64url).
826
+ * @param {string} opts.expectedOrigin - Expected origin.
827
+ * @param {string} opts.expectedRPID - Expected RP ID.
828
+ * @param {object} opts.credential - Stored credential from registration.
829
+ * @param {Buffer} opts.credential.publicKey - DER-encoded public key.
830
+ * @param {number} opts.credential.counter - Stored signature counter.
831
+ * @returns {{ verified: boolean, newCounter: number|null, error: string|null }}
832
+ *
833
+ * @example
834
+ * const result = await webauthn.verifyAuthentication({
835
+ * response: clientResponse,
836
+ * expectedChallenge: storedChallenge,
837
+ * expectedOrigin: 'https://myapp.com',
838
+ * expectedRPID: 'myapp.com',
839
+ * credential: storedCredential,
840
+ * });
841
+ * if (result.verified) {
842
+ * await db.updateCounter(credId, result.newCounter);
843
+ * }
844
+ */
845
+ function verifyAuthentication(opts)
846
+ {
847
+ try
848
+ {
849
+ const { response, expectedChallenge, expectedOrigin, expectedRPID, credential } = opts;
850
+
851
+ if (!response || !response.response)
852
+ return { verified: false, newCounter: null, error: 'Missing response' };
853
+
854
+ if (!credential || !credential.publicKey)
855
+ return { verified: false, newCounter: null, error: 'Missing stored credential' };
856
+
857
+ // 1. Decode and validate clientDataJSON
858
+ const clientDataBuf = _fromBase64Url(response.response.clientDataJSON);
859
+ const clientData = JSON.parse(clientDataBuf.toString('utf8'));
860
+
861
+ if (clientData.type !== 'webauthn.get')
862
+ return { verified: false, newCounter: null, error: `Invalid type: ${clientData.type}` };
863
+
864
+ // Strict origin match
865
+ if (clientData.origin !== expectedOrigin)
866
+ return { verified: false, newCounter: null, error: `Origin mismatch: ${clientData.origin}` };
867
+
868
+ if (clientData.challenge !== expectedChallenge)
869
+ return { verified: false, newCounter: null, error: 'Challenge mismatch' };
870
+
871
+ // 2. Parse authenticator data
872
+ const authDataBuf = _fromBase64Url(response.response.authenticatorData);
873
+ const authData = _parseAuthData(authDataBuf);
874
+
875
+ // 3. Validate RP ID hash
876
+ const expectedRPIDHash = crypto.createHash('sha256').update(expectedRPID).digest();
877
+ if (!authData.rpIdHash.equals(expectedRPIDHash))
878
+ return { verified: false, newCounter: null, error: 'RP ID hash mismatch' };
879
+
880
+ // 4. User presence
881
+ if (!authData.userPresent)
882
+ return { verified: false, newCounter: null, error: 'User not present' };
883
+
884
+ // 5. Counter validation — detect cloned authenticators
885
+ if (authData.signCount > 0 || credential.counter > 0)
886
+ {
887
+ if (authData.signCount <= credential.counter)
888
+ {
889
+ log.warn('WebAuthn counter rollback detected: received=%d, stored=%d (possible clone)',
890
+ authData.signCount, credential.counter);
891
+ return { verified: false, newCounter: null, error: 'Counter rollback detected (possible authenticator clone)' };
892
+ }
893
+ }
894
+
895
+ // 6. Verify signature
896
+ const clientDataHash = crypto.createHash('sha256').update(clientDataBuf).digest();
897
+ const signedData = Buffer.concat([authDataBuf, clientDataHash]);
898
+ const signature = _fromBase64Url(response.response.signature);
899
+
900
+ const publicKey = crypto.createPublicKey({
901
+ key: Buffer.isBuffer(credential.publicKey) ? credential.publicKey : Buffer.from(credential.publicKey),
902
+ format: 'der',
903
+ type: 'spki',
904
+ });
905
+
906
+ // Determine algorithm from key type
907
+ const keyDetail = publicKey.asymmetricKeyType;
908
+ let algName = 'SHA256';
909
+ if (keyDetail === 'ed25519') algName = null;
910
+
911
+ const verified = crypto.verify(algName, signedData, publicKey, signature);
912
+
913
+ if (!verified)
914
+ return { verified: false, newCounter: null, error: 'Signature verification failed' };
915
+
916
+ log.info('WebAuthn authentication verified (counter=%d)', authData.signCount);
917
+ return { verified: true, newCounter: authData.signCount, error: null };
918
+ }
919
+ catch (err)
920
+ {
921
+ log.error('WebAuthn authentication verification error: %s', err.message);
922
+ return { verified: false, newCounter: null, error: err.message };
923
+ }
924
+ }
925
+
926
+ // -- Exports -----------------------------------------------
927
+
928
+ const webauthn = {
929
+ generateRegistrationOptions,
930
+ verifyRegistration,
931
+ generateAuthenticationOptions,
932
+ verifyAuthentication,
933
+ };
934
+
935
+ module.exports = {
936
+ webauthn,
937
+ // Internal exports for testing
938
+ _cbor: cbor,
939
+ _parseAuthData,
940
+ _coseToPublicKey,
941
+ _coseAlgToNodeAlg,
942
+ _toBase64Url,
943
+ _fromBase64Url,
944
+ COSE_ALG,
945
+ COSE_KEY_TYPE,
946
+ };