// A software passkey for the tests: an ES256 key that answers WebAuthn registration and // authentication options the way Apple's platform authenticator does (origin https://, // "none" attestation, user present and verified, counter 0). import { createHash, generateKeyPairSync, randomBytes, sign } from 'node:crypto'; import { isoBase64URL, isoCBOR } from '@simplewebauthn/server/helpers'; const b64 = (bytes) => isoBase64URL.fromBuffer(new Uint8Array(bytes)); const sha = (bytes) => createHash('sha256').update(bytes).digest(); const UP = 0x01, UV = 0x04, BE = 0x08, BS = 0x10, AT = 0x40; export class Authenticator { constructor({ rpID = 'jobley.ai', origin = `https://${rpID}`, verify = true } = {}) { this.rpID = rpID; this.origin = origin; this.verify = verify; this.credentialId = randomBytes(16); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }); this.privateKey = privateKey; const jwk = publicKey.export({ format: 'jwk' }); this.cose = isoCBOR.encode(new Map([[1, 2], [3, -7], [-1, 1], [-2, isoBase64URL.toBuffer(jwk.x)], [-3, isoBase64URL.toBuffer(jwk.y)]])); } get id() { return b64(this.credentialId); } flags(extra = 0) { return UP | (this.verify ? UV : 0) | BE | BS | extra; } clientData(type, challenge) { return Buffer.from(JSON.stringify({ type, challenge, origin: this.origin, crossOrigin: false })); } register(options) { this.userHandle = options.user.id; const clientDataJSON = this.clientData('webauthn.create', options.challenge); const idLength = Buffer.alloc(2); idLength.writeUInt16BE(this.credentialId.length); const authData = Buffer.concat([sha(this.rpID), Buffer.from([this.flags(AT)]), Buffer.alloc(4), Buffer.alloc(16), idLength, this.credentialId, Buffer.from(this.cose)]); const attestationObject = isoCBOR.encode(new Map([['fmt', 'none'], ['attStmt', new Map()], ['authData', new Uint8Array(authData)]])); return { id: this.id, rawId: this.id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform', response: { clientDataJSON: b64(clientDataJSON), attestationObject: b64(attestationObject), transports: ['internal', 'hybrid'] }, }; } login(options) { const clientDataJSON = this.clientData('webauthn.get', options.challenge); const authenticatorData = Buffer.concat([sha(this.rpID), Buffer.from([this.flags()]), Buffer.alloc(4)]); const signature = sign('sha256', Buffer.concat([authenticatorData, sha(clientDataJSON)]), this.privateKey); return { id: this.id, rawId: this.id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform', response: { clientDataJSON: b64(clientDataJSON), authenticatorData: b64(authenticatorData), signature: b64(signature), userHandle: this.userHandle }, }; } }