import crypto from 'node:crypto'; /** * Сборка ответов устройства для тестов. Настоящего Face ID под рукой нет, * поэтому байты собираются здесь теми же средствами, что и в браузере: ключ * ES256, честная подпись, тот же порядок полей. Файл не участвует в работе * панели и не попадает в прогон тестов (имя без .test.js) - он общий помощник * для webauthn.test.js и auth-routes.test.js. */ export function cborBytes(buffer) { const length = buffer.length; if (length < 24) return Buffer.concat([Buffer.from([0x40 | length]), buffer]); if (length < 256) return Buffer.concat([Buffer.from([0x58, length]), buffer]); const head = Buffer.alloc(3); head[0] = 0x59; head.writeUInt16BE(length, 1); return Buffer.concat([head, buffer]); } export function cborText(text) { const bytes = Buffer.from(text, 'utf8'); return Buffer.concat([Buffer.from([0x60 | bytes.length]), bytes]); } /** Ключ устройства в том виде, в каком его присылает браузер. */ export function coseKey(jwk) { const x = Buffer.from(jwk.x, 'base64url'); const y = Buffer.from(jwk.y, 'base64url'); return Buffer.concat([ Buffer.from([0xa5]), // карта из пяти пар Buffer.from([0x01, 0x02]), // тип ключа: эллиптическая кривая Buffer.from([0x03, 0x26]), // способ подписи: ES256 Buffer.from([0x20, 0x01]), // кривая P-256 Buffer.from([0x21]), cborBytes(x), Buffer.from([0x22]), cborBytes(y), ]); } export function makeAuthData({ rpId, credentialId = null, jwk = null, signCount = 1, verified = true }) { const head = Buffer.concat([ crypto.createHash('sha256').update(rpId).digest(), Buffer.from([verified ? 0x45 : 0x01]), // присутствие + подтверждение личности + признак ключа Buffer.alloc(4), ]); head.writeUInt32BE(signCount, 33); if (!credentialId) { head[32] = verified ? 0x05 : 0x01; // без признака заведения ключа return head; } const idLength = Buffer.alloc(2); idLength.writeUInt16BE(credentialId.length, 0); return Buffer.concat([head, Buffer.alloc(16), idLength, credentialId, coseKey(jwk)]); } export function clientData(type, challenge, origin) { return Buffer.from(JSON.stringify({ type, challenge, origin, crossOrigin: false }), 'utf8'); } /** Заводит ключ так же, как это сделало бы устройство. */ export function newDevice() { const pair = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); const jwk = pair.publicKey.export({ format: 'jwk' }); const credentialId = crypto.randomBytes(32); return { pair, jwk, credentialId }; } /** Ответ устройства при заведении ключа: attestationObject целиком. */ export function attestationFor({ rpId, credentialId, jwk }) { const authData = makeAuthData({ rpId, credentialId, jwk }); return Buffer.concat([ Buffer.from([0xa3]), cborText('fmt'), cborText('none'), cborText('attStmt'), Buffer.from([0xa0]), cborText('authData'), cborBytes(authData), ]); }