All files index.ts

90% Statements 126/140
40.74% Branches 11/27
100% Functions 10/10
89.92% Lines 125/139

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                            1x                 4x   4x     4x 4x       4x 4x       4x 4x   4x 4x 4x   4x 4x 4x 4x   4x                     4x 4x 4x   4x 4x   4x 4x 4x   4x 4x 4x 4x   4x 4x 4x 4x 4x 4x   4x       18x 18x   18x 18x 18x   18x 10x   10x 10x   10x     10x   10x     10x 10x       10x 10x     10x   10x 10x   10x 10x   10x   10x       14x 14x 14x       14x   14x 14x       14x   14x       14x       4x 4x 4x   4x 4x 4x 4x             4x 4x   4x 4x 4x   4x 4x 4x 4x 4x 16x 16x 16x 16x 16x 16x 16x     16x 8x         4x     4x       4x   4x 4x 4x 4x 4x 4x         4x                     4x 4x     4x 4x     4x 4x     4x 4x 4x     4x       14x 14x         16x 12x   4x 4x 4x 4x 4x   4x 4x    
import {
    ABIDecoder,
    ABIEncoder,
    Bytes,
    Checksum256,
    KeyType,
    PublicKey,
    Signature,
} from '@wharfkit/antelope'
import {decode as cborDecode, decodeFirst} from 'cborg'
import elliptic from 'elliptic'
 
import {Decoder} from './decoder'
 
const {ec} = elliptic
 
export function createPublic(
    attestationResponse: {
        attestationObject: ArrayBuffer
        clientDataJSON: ArrayBuffer
    },
    logging = false
) {
    const clientData = decodeBinaryJson(attestationResponse.clientDataJSON)
    const origin = clientData.origin
    Iif (typeof origin !== 'string') {
        throw new Error('Missing origin in client data')
    }
    const originUrl = new URL(origin)
    Iif (originUrl.protocol !== 'https:') {
        throw new Error('WebAuthn keys require https')
    }
 
    const attestationObject = cborDecode(new Uint8Array(attestationResponse.attestationObject))
    Iif (!(attestationObject.authData instanceof Uint8Array)) {
        throw new Error('Missing auth data')
    }
 
    const authData = decodeAuthData(attestationObject.authData)
    const ecPoint = getECPoint(authData.credentialPublicKey)
 
    const compressed = new Uint8Array(33)
    compressed[0] = ecPoint.y[31] & 0x01 ? 0x03 : 0x02
    compressed.set(ecPoint.x, 1)
 
    const abiEncoder = new ABIEncoder()
    abiEncoder.writeArray(compressed)
    abiEncoder.writeByte(getUserDataFlag(authData.flags, logging))
    abiEncoder.writeString(originUrl.hostname)
 
    return new PublicKey(KeyType.WA, abiEncoder.getBytes())
}
 
export function createSignature(
    publicKey: PublicKey,
    assertionResponse: {
        signature: ArrayBuffer
        authenticatorData: ArrayBuffer
        clientDataJSON: ArrayBuffer
    }
) {
    const decoder = new Decoder(assertionResponse.signature).derDecoder(0x30)
    const r = fixPoint(decoder.readDer(0x02))
    const s = fixPoint(decoder.readDer(0x02))
 
    const authenticatorData = Bytes.from(assertionResponse.authenticatorData)
    const clientDataJSON = Bytes.from(assertionResponse.clientDataJSON)
 
    const message = new Bytes()
    message.append(authenticatorData)
    message.append(Checksum256.hash(clientDataJSON))
 
    const curve = new ec('p256')
    const pk = curve.keyFromPublic(publicKey.data.array.slice(0, 33)).getPublic()
    const m = Checksum256.hash(message).array
    const recid = (curve.getKeyRecoveryParam as any)(m, {r, s}, pk)
 
    const encoder = new ABIEncoder()
    encoder.writeByte(recid + 31)
    encoder.writeArray(r)
    encoder.writeArray(s)
    authenticatorData.toABI(encoder)
    clientDataJSON.toABI(encoder)
 
    return new Signature(KeyType.WA, encoder.getBytes())
}
 
export function recoverPublic(signature: Signature, message: Bytes, logging = false): PublicKey {
    const signatureData = signature.data.array
    const messageDigest = Checksum256.hash(message).array
 
    const recid = signatureData[0] - 31
    const r = signatureData.subarray(1, 33)
    const s = signatureData.subarray(33, 33 + 32)
    const curve = new ec('p256')
    const point = curve.recoverPubKey(messageDigest, {r, s}, recid)
    const compressedKeyPoint = new Uint8Array(point.encodeCompressed())
 
    const extraDataView = signatureData.subarray(65)
    const extraDataDecoder = new ABIDecoder(extraDataView)
 
    const authenticatorDataBytes = Bytes.fromABI(extraDataDecoder)
    const clientDataJSONBytes = Bytes.fromABI(extraDataDecoder)
 
    const clientData = decodeBinaryJson(clientDataJSONBytes.array.slice().buffer)
    const origin = clientData.origin
    Iif (typeof origin !== 'string') {
        throw new Error('Missing origin in client data during recovery')
    }
    const originUrl = new URL(origin)
    Iif (originUrl.protocol !== 'https:') {
        throw new Error('WebAuthn keys require https')
    }
 
    const authDataForFlagsDecoder = new Decoder(authenticatorDataBytes.array)
    Iif (!authDataForFlagsDecoder.canRead(32 + 1)) {
        throw new Error('Authenticator data is too short to read flags.')
    }
    authDataForFlagsDecoder.readArray(32)
 
    const abiEncoder = new ABIEncoder()
    abiEncoder.writeArray(compressedKeyPoint)
 
    const flags = authDataForFlagsDecoder.readByte()
    abiEncoder.writeByte(getUserDataFlag(flags, logging))
 
    abiEncoder.writeString(originUrl.hostname)
 
    return new PublicKey(KeyType.WA, abiEncoder.getBytes())
}
 
export function getUserDataFlag(flags: number, logging = false): number {
    let byte = 0x00
    if (flags & 0x01 /* user present */) {
        Iif (logging) {
            // eslint-disable-next-line no-console
            console.info('present flag', flags)
        }
        byte = 0x01
    }
    if (flags & 0x04 /* user verified */) {
        Iif (logging) {
            // eslint-disable-next-line no-console
            console.info('verified flag', flags)
        }
        byte = 0x02
    }
    Iif (logging) {
        // eslint-disable-next-line no-console
        console.info('final user data flag:', byte)
    }
    return byte
}
 
export function verifyPublic(signature: Signature, message: Bytes, publicKey: PublicKey) {
    const signatureData = signature.data.array
    const messageDigest = Checksum256.hash(message).array
    const publicKeyData = publicKey.getCompressedKeyBytes()
 
    const curve = new ec('p256')
    const r = signatureData.subarray(1, 33)
    const s = signatureData.subarray(33, 33 + 32)
    return curve.verify(messageDigest, {r, s}, publicKeyData as any)
}
 
export function recoverPotentialPublicKeysFromAssertion(
    assertionResponse: AuthenticatorAssertionResponse,
    logging = false
): PublicKey[] {
    const authenticatorData = Bytes.from(assertionResponse.authenticatorData)
    const clientDataJSON = Bytes.from(assertionResponse.clientDataJSON)
 
    const message = new Bytes()
    message.append(authenticatorData)
    message.append(Checksum256.hash(clientDataJSON))
 
    const decoder = new Decoder(assertionResponse.signature).derDecoder(0x30)
    const r = fixPoint(decoder.readDer(0x02))
    const s = fixPoint(decoder.readDer(0x02))
    const keys: PublicKey[] = []
    for (let recid = 0; recid < 4; recid++) {
        try {
            const encoder = new ABIEncoder()
            encoder.writeByte(recid + 31)
            encoder.writeArray(r)
            encoder.writeArray(s)
            authenticatorData.toABI(encoder)
            clientDataJSON.toABI(encoder)
 
            const signature = new Signature(KeyType.WA, encoder.getBytes())
            const key = recoverPublic(signature, message, logging)
            keys.push(key)
        } catch {
            // Ignore errors, try next recid
        }
    }
    Iif (!keys.length) {
        throw new Error('Unable to recover any potential public keys from signature')
    }
    return keys
}
 
function decodeAuthData(authData: Uint8Array) {
    const decoder = new Decoder(authData)
 
    const rpIdHash = decoder.readArray(32)
    const flags = decoder.readByte()
    const counter = decoder.readNum(4)
    const aaguid = decoder.readArray(16)
    const credentialId = decoder.readArray(decoder.readNum(2))
    const [credentialPublicKey] = decodeFirst(decoder.remainder(), {useMaps: true}) as [
        Map<number, any>,
        Uint8Array,
    ]
 
    return {
        rpIdHash,
        flags,
        counter,
        aaguid,
        credentialId,
        credentialPublicKey,
    }
}
 
function getECPoint(credentialPublicKey: Map<number, any>) {
    const kty = credentialPublicKey.get(1)
    Iif (kty !== 2 /* EC */) {
        throw new Error(`Unsupported key type: ${kty}`)
    }
    const alg = credentialPublicKey.get(3)
    Iif (alg !== -7 /* EC2 */) {
        throw new Error(`Unsupported key algorithm: ${alg}`)
    }
    const crv = credentialPublicKey.get(-1)
    Iif (crv !== 1 /*P-256*/) {
        throw new Error(`Unsupported ec key curve: ${crv}`)
    }
    const x = credentialPublicKey.get(-2)
    const y = credentialPublicKey.get(-3)
    Iif (!(x instanceof Uint8Array) || !(y instanceof Uint8Array)) {
        throw new Error('Invalid public key data')
    }
    return {x, y}
}
 
function decodeBinaryJson(data: ArrayBuffer) {
    const decoder = new TextDecoder()
    return JSON.parse(decoder.decode(data))
}
 
// chrome sometimes returns curve points that are not 32 bytes, so we need to make sure they are
function fixPoint(x: Uint8Array) {
    if (x.length === 32) {
        return x
    }
    const rv = new Uint8Array(32)
    rv.fill(0)
    let si = 0
    while (x[si] === 0 && si < x.length - 1) {
        si++
    }
    rv.set(x.slice(si), 32 - x.length + si)
    return rv
}