All files / src id.js

83.23% Statements 134/161
76.39% Branches 55/72
84.78% Functions 39/46
83.75% Lines 134/160

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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630                                      3x 46x   46x   46x                     46x 46x   2x 2x 2x   44x     46x 46x   46x 46x 46x   46x 46x 46x     46x 46x       42x       4x       42x       4x       76x 76x                   57x 1x     56x 41x               56x                         3x 3x       6x 6x 6x 4x             2x                 63x                 3x                   10x 9x     1x                                                                           1x 1x   2x 2x 2x       1x                   9x 9x 8x     1x                     2x 1x     2x                         32x 32x     32x 2x     30x   30x 30x     30x     30x 30x       31x                   35x 32x     35x 1x     34x 34x       15x       3x                                   3x                       67x 64x 64x               64x       3x                 7x                 7x       7x             7x   7x                   9x 9x                 7x             2x 2x 2x               1x 1x 1x 1x               1x 1x 1x 1x 1x                   4x 4x                   3x 3x   3x 3x   3x                     9x       9x 9x 9x 9x   9x                                                                     7x 7x   7x                             7x 7x   7x   7x 28x     7x   7x                                                                                                                         9x 9x 9x 9x 9x 9x 9x 9x 9x               2x                          
import bsv from 'bsv';
import ECIES from 'bsv/ecies';
import Message from 'bsv/message';
import {
  MAX_INT,
  SIGNING_PATH_PREFIX,
  BAP_SERVER,
  BAP_BITCOM_ADDRESS,
  AIP_BITCOM_ADDRESS, ENCRYPTION_PATH,
} from './constants';
import { Utils } from './utils';
 
/**
 * BAP_ID class
 *
 * This class should be used in conjunction with the BAP class
 *
 * @type {BAP_ID}
 */
export const BAP_ID = class {
  #HDPrivateKey = null;
 
  #BAP_SERVER = BAP_SERVER;
 
  #BAP_TOKEN = '';
 
  #rootPath;
 
  #previousPath;
 
  #currentPath;
 
  #idSeed;
 
  constructor(HDPrivateKey, identityAttributes = {}, idSeed = '') {
    this.#idSeed = idSeed;
    if (idSeed) {
      // create a new HDPrivateKey based on the seed
      const seedHex = bsv.crypto.Hash.sha256(Buffer.from(idSeed)).toString('hex');
      const seedPath = Utils.getSigningPathFromHex(seedHex);
      this.#HDPrivateKey = HDPrivateKey.deriveChild(seedPath);
    } else {
      this.#HDPrivateKey = HDPrivateKey;
    }
 
    this.name = 'ID 1';
    this.description = '';
 
    this.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;
    this.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;
    this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;
 
    const rootChild = this.#HDPrivateKey.deriveChild(this.#rootPath);
    this.rootAddress = rootChild.privateKey.publicKey.toAddress().toString();
    this.identityKey = this.deriveIdentityKey(this.rootAddress);
 
    // unlink the object
    identityAttributes = { ...identityAttributes };
    this.identityAttributes = this.parseAttributes(identityAttributes);
  }
 
  set BAP_SERVER(bapServer) {
    this.#BAP_SERVER = bapServer;
  }
 
  get BAP_SERVER() {
    return this.#BAP_SERVER;
  }
 
  set BAP_TOKEN(token) {
    this.#BAP_TOKEN = token;
  }
 
  get BAP_TOKEN() {
    return this.#BAP_TOKEN;
  }
 
  deriveIdentityKey(address) {
    const rootAddressHash = bsv.crypto.Hash.sha256(Buffer.from(address));
    return bsv.encoding.Base58(bsv.crypto.Hash.ripemd160(rootAddressHash)).toString();
  }
 
  /**
   * Helper function to parse identity attributes
   *
   * @param identityAttributes
   * @returns {{}}
   */
  parseAttributes(identityAttributes) {
    if (typeof identityAttributes === 'string') {
      return this.parseStringUrns(identityAttributes);
    }
 
    Object.keys(identityAttributes).forEach((key) => {
      Iif (
        !identityAttributes[key].hasOwnProperty('value')
        || !identityAttributes[key].hasOwnProperty('nonce')
      ) {
        throw new Error('Invalid identity attribute');
      }
    });
 
    return identityAttributes || {};
  }
 
  /**
   * Parse a text of urn string into identity attributes
   *
   * urn:bap:id:name:John Doe:e2c6fb4063cc04af58935737eaffc938011dff546d47b7fbb18ed346f8c4d4fa
   * urn:bap:id:birthday:1990-05-22:e61f23cbbb2284842d77965e2b0e32f0ca890b1894ca4ce652831347ee3596d9
   * urn:bap:id:over18:1:480ca17ccaacd671b28dc811332525f2f2cd594d8e8e7825de515ce5d52d30e8
   *
   * @param urnIdentityAttributes
   */
  parseStringUrns(urnIdentityAttributes) {
    const identityAttributes = {};
    urnIdentityAttributes.replace(/^\s+/g, '').replace(/\r/gm, '')
      .split('\n')
      .forEach((line) => {
        // remove any whitespace from the string (trim)
        line = line.replace(/^\s+/g, '').replace(/\s+$/g, '');
        const urn = line.split(':');
        if (urn[0] === 'urn' && urn[1] === 'bap' && urn[2] === 'id' && urn[3] && urn[4] && urn[5]) {
          identityAttributes[urn[3]] = {
            value: urn[4],
            nonce: urn[5],
          };
        }
      });
 
    return identityAttributes;
  }
 
  /**
   * Returns the identity key
   *
   * @returns {*|string}
   */
  getIdentityKey() {
    return this.identityKey;
  }
 
  /**
   * Returns all the attributes in the identity
   *
   * @returns {*}
   */
  getAttributes() {
    return this.identityAttributes;
  }
 
  /**
   * Get the value of the given attribute
   *
   * @param attributeName
   * @returns {{}|null}
   */
  getAttribute(attributeName) {
    if (this.identityAttributes.hasOwnProperty(attributeName)) {
      return this.identityAttributes[attributeName];
    }
 
    return null;
  }
 
  /**
   * Set the value of the given attribute
   *
   * If an empty value ('' || null || false) is given, the attribute is removed from the ID
   *
   * @param attributeName
   * @param attributeValue
   * @returns {{}|null}
   */
  setAttribute(attributeName, attributeValue) {
    if (attributeValue) {
      if (this.identityAttributes.hasOwnProperty(attributeName)) {
        this.identityAttributes[attributeName].value = attributeValue;
      } else {
        this.addAttribute(attributeName, attributeValue);
      }
    }
  }
 
  /**
   * Unset the given attribute from the ID
   *
   * @param attributeName
   * @returns {{}|null}
   */
  unsetAttribute(attributeName) {
    delete this.identityAttributes[attributeName];
  }
 
  /**
   * Get all attribute urn's for this id
   *
   * @returns {string}
   */
  getAttributeUrns() {
    let urns = '';
    Object.keys(this.identityAttributes)
      .forEach((key) => {
        const urn = this.getAttributeUrn(key);
        Eif (urn) {
          urns += `${urn}\n`;
        }
      });
 
    return urns;
  }
 
  /**
   * Create an return the attribute urn for the given attribute
   *
   * @param attributeName
   * @returns {string|null}
   */
  getAttributeUrn(attributeName) {
    const attribute = this.identityAttributes[attributeName];
    if (attribute) {
      return `urn:bap:id:${attributeName}:${attribute.value}:${attribute.nonce}`;
    }
 
    return null;
  }
 
  /**
   * Add an attribute to this identity
   *
   * @param attributeName
   * @param value
   * @param nonce
   */
  addAttribute(attributeName, value, nonce = false) {
    if (!nonce) {
      nonce = Utils.getRandomString();
    }
 
    this.identityAttributes[attributeName] = {
      value,
      nonce,
    };
  }
 
  /**
   * This should be called with the last part of the signing path (/.../.../...)
   * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file
   *
   * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}
   */
  set rootPath(path) {
    Eif (path.split('/').length < 5) {
      path = `${SIGNING_PATH_PREFIX}${path}`;
    }
 
    if (!this.validatePath(path)) {
      throw new Error('invalid signing path given ' + path);
    }
 
    this.#rootPath = path;
 
    const derivedChild = this.#HDPrivateKey.deriveChild(path);
    this.rootAddress = derivedChild.publicKey.toAddress().toString();
    // Identity keys should be derivatives of the root address - this allows checking
    // of the creation transaction
    this.identityKey = this.deriveIdentityKey(this.rootAddress);
 
    // we also set this previousPath / currentPath to the root as we seem to be (re)setting this ID
    this.#previousPath = path;
    this.#currentPath = path;
  }
 
  get rootPath() {
    return this.#rootPath;
  }
 
  /**
   * This should be called with the last part of the signing path (/.../.../...)
   * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file
   *
   * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}
   */
  set currentPath(path) {
    if (path.split('/').length < 5) {
      path = `${SIGNING_PATH_PREFIX}${path}`;
    }
 
    if (!this.validatePath(path)) {
      throw new Error('invalid signing path given');
    }
 
    this.#previousPath = this.#currentPath;
    this.#currentPath = path;
  }
 
  get currentPath() {
    return this.#currentPath;
  }
 
  get previousPath() {
    return this.#previousPath;
  }
 
  /**
   * This can be used to break the deterministic way child keys are created to make it harder for
   * an attacker to steal the identites when the root key is compromised. This does however require
   * the seeds to be stored at all times. If the seed is lost, the identity will not be recoverable.
   */
  get idSeed() {
    return this.#idSeed;
  }
 
  /**
   * Increment current path to a new path
   *
   * @returns {*}
   */
  incrementPath() {
    this.currentPath = Utils.getNextPath(this.currentPath);
  }
 
  /**
   * Check whether the given path is a valid path for use with this class
   * The signing paths used here always have a length of 3
   *
   * @param path The last part of the signing path (example "/0/0/1")
   * @returns {boolean}
   */
  validatePath(path) {
    /* eslint-disable max-len */
    if (path.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)) {
      const pathValues = path.split('/');
      Eif (pathValues.length === 7
        && Number(pathValues[1].replace('\'', '')) <= MAX_INT
        && Number(pathValues[2].replace('\'', '')) <= MAX_INT
        && Number(pathValues[3].replace('\'', '')) <= MAX_INT
        && Number(pathValues[4].replace('\'', '')) <= MAX_INT
        && Number(pathValues[5].replace('\'', '')) <= MAX_INT
        && Number(pathValues[6].replace('\'', '')) <= MAX_INT
      ) {
        return true;
      }
    }
 
    return false;
  }
 
  /**
   * Get the OP_RETURN for the initial ID transaction (signed with root address)
   *
   * @returns {[]}
   */
  getInitialIdTransaction() {
    return this.getIdTransaction(this.#rootPath);
  }
 
  /**
   * Get the OP_RETURN for the ID transaction of the current address / path
   *
   * @returns {[]}
   */
  getIdTransaction(previousPath = false) {
    Iif (this.#currentPath === this.#rootPath) {
      throw new Error('Current path equals rootPath. ID was probably not initialized properly');
    }
 
    const opReturn = [
      Buffer.from(BAP_BITCOM_ADDRESS).toString('hex'),
      Buffer.from('ID').toString('hex'),
      Buffer.from(this.identityKey).toString('hex'),
      Buffer.from(this.getCurrentAddress()).toString('hex'),
    ];
 
    previousPath = previousPath || this.#previousPath;
 
    return this.signOpReturnWithAIP(opReturn, previousPath);
  }
 
  /**
   * Get address for given path
   *
   * @param path
   * @returns {*}
   */
  getAddress(path) {
    const derivedChild = this.#HDPrivateKey.deriveChild(path);
    return derivedChild.privateKey.publicKey.toAddress().toString();
  }
 
  /**
   * Get current signing address
   *
   * @returns {*}
   */
  getCurrentAddress() {
    return this.getAddress(this.#currentPath);
  }
 
  /**
   * Get the public key for encrypting data for this identity
   */
  getEncryptionPublicKey() {
    const HDPrivateKey = this.#HDPrivateKey.deriveChild(this.#rootPath);
    const encryptionKey = HDPrivateKey.deriveChild(ENCRYPTION_PATH).privateKey;
    return encryptionKey.publicKey.toString('hex');
  }
 
  /**
   * Encrypt the given string data with the identity encryption key
   * @param stringData
   */
  encrypt(stringData) {
    const publicKey = bsv.PublicKey.fromHex(this.getEncryptionPublicKey());
    const ecies = new ECIES();
    ecies.publicKey(publicKey);
    return ecies.encrypt(stringData).toString('base64');
  }
 
  /**
   * Decrypt the given ciphertext with the identity encryption key
   * @param ciphertext
   */
  decrypt(ciphertext) {
    const HDPrivateKey = this.#HDPrivateKey.deriveChild(this.#rootPath);
    const encryptionKey = HDPrivateKey.deriveChild(ENCRYPTION_PATH).privateKey;
    const ecies = new ECIES();
    ecies.privateKey(encryptionKey);
    return ecies.decrypt(Buffer.from(ciphertext, 'base64')).toString();
  }
 
  /**
   * Get an attestation string for the given urn for this identity
   *
   * @param urn
   * @returns {string}
   */
  getAttestation(urn) {
    const urnHash = bsv.crypto.Hash.sha256(Buffer.from(urn));
    return `bap:attest:${urnHash.toString('hex')}:${this.getIdentityKey()}`;
  }
 
  /**
   * Generate and return the attestation hash for the given attribute of this identity
   *
   * @param attribute Attribute name (name, email etc.)
   * @returns {string}
   */
  getAttestationHash(attribute) {
    const urn = this.getAttributeUrn(attribute);
    Iif (!urn) return null;
 
    const attestation = this.getAttestation(urn);
    const attestationHash = bsv.crypto.Hash.sha256(Buffer.from(attestation));
 
    return attestationHash.toString('hex');
  }
 
  /**
   * Sign a message with the current signing address of this identity
   *
   * @param message
   * @param signingPath
   * @returns {{address, signature}}
   */
  signMessage(message, signingPath = false) {
    Iif (!(message instanceof Buffer)) {
      message = Buffer.from(message);
    }
 
    signingPath = signingPath || this.#currentPath;
    const derivedChild = this.#HDPrivateKey.deriveChild(signingPath);
    const address = derivedChild.privateKey.publicKey.toAddress().toString();
    const signature = Message(message).sign(derivedChild.privateKey);
 
    return { address, signature };
  }
 
  /**
   * Sign a message using a key based on the given string seed
   *
   * This works by creating a private key from the root key of this identity. It will always
   * work with the rootPath / rootKey, to be deterministic. It will not change even if the keys
   * are rotated for this ID.
   *
   * This is used in for instance deterministic login systems, that do not support BAP.
   *
   * @param message
   * @param seed {string} String seed that will be used to generate a path
   */
  signMessageWithSeed(message, seed) {
    const pathHex = bsv.crypto.Hash.sha256(Buffer.from(seed)).toString('hex');
    const path = Utils.getSigningPathFromHex(pathHex);
 
    const HDPrivateKey = this.#HDPrivateKey.deriveChild(this.#rootPath);
    const derivedChild = HDPrivateKey.deriveChild(path);
    const address = derivedChild.privateKey.publicKey.toAddress().toString();
    const signature = Message(message).sign(derivedChild.privateKey);
 
    return { address, signature };
  }
 
  /**
   * Sign an op_return hex array with AIP
   * @param opReturn {array}
   * @param signingPath {string}
   * @param outputType {string}
   * @return {[]}
   */
  signOpReturnWithAIP(opReturn, signingPath = false, outputType = 'hex') {
    const aipMessageBuffer = this.getAIPMessageBuffer(opReturn);
    const { address, signature } = this.signMessage(aipMessageBuffer, signingPath);
 
    return opReturn.concat([
      Buffer.from('|').toString(outputType),
      Buffer.from(AIP_BITCOM_ADDRESS).toString(outputType),
      Buffer.from('BITCOIN_ECDSA').toString(outputType),
      Buffer.from(address).toString(outputType),
      Buffer.from(signature, 'base64').toString(outputType),
    ]);
  }
 
  /**
   * Construct an AIP buffer from the op return data
   * @param opReturn
   * @returns {Buffer}
   */
  getAIPMessageBuffer(opReturn) {
    const buffers = [];
    Eif (opReturn[0].replace('0x', '') !== '6a') {
      // include OP_RETURN in constructing the signature buffer
      buffers.push(Buffer.from('6a', 'hex'));
    }
    opReturn.forEach((op) => {
      buffers.push(Buffer.from(op.replace('0x', ''), 'hex'));
    });
    // add a trailing "|" - this is the AIP way
    buffers.push(Buffer.from('|'));
 
    return Buffer.concat([...buffers]);
  }
 
  /**
   * Get all signing keys for this identity
   */
  async getIdSigningKeys() {
    const signingKeys = await this.getApiData('/signing-keys', {
      idKey: this.identityKey,
    });
    console.log('getIdSigningKeys', signingKeys);
 
    return signingKeys;
  }
 
  /**
   * Get all attestations for the given attribute
   *
   * @param attribute
   */
  async getAttributeAttestations(attribute) {
    // This function needs to make a call to a BAP server to get all the attestations for this
    // identity for the given attribute
    const attestationHash = this.getAttestationHash(attribute);
 
    // get all BAP ATTEST records for the given attestationHash
    const attestations = await this.getApiData('/attestations', {
      hash: attestationHash,
    });
    console.log('getAttestations', attribute, attestationHash, attestations);
 
    return attestations;
  }
 
  /**
   * Helper function to get attestation from a BAP API server
   *
   * @param apiUrl
   * @param apiData
   * @returns {Promise<any>}
   */
  async getApiData(apiUrl, apiData) {
    const url = `${this.#BAP_SERVER}${apiUrl}`;
    const response = await fetch(url, {
      method: 'post',
      headers: {
        'Content-type': 'application/json; charset=utf-8',
        token: this.#BAP_TOKEN,
        format: 'json',
      },
      body: JSON.stringify(apiData),
    });
    return response.json();
  }
 
  /**
   * Import an identity from a JSON object
   *
   * @param identity{{}}
   */
  import(identity) {
    this.name = identity.name;
    this.description = identity.description || '';
    this.identityKey = identity.identityKey;
    this.#rootPath = identity.rootPath;
    this.rootAddress = identity.rootAddress;
    this.#previousPath = identity.previousPath;
    this.#currentPath = identity.currentPath;
    this.#idSeed = identity.idSeed || '';
    this.identityAttributes = this.parseAttributes(identity.identityAttributes);
  }
 
  /**
   * Export this identity to a JSON object
   * @returns {{}}
   */
  export() {
    return {
      name: this.name,
      description: this.description,
      identityKey: this.identityKey,
      rootPath: this.#rootPath,
      rootAddress: this.rootAddress,
      previousPath: this.#previousPath,
      currentPath: this.#currentPath,
      idSeed: this.#idSeed,
      identityAttributes: this.getAttributes(),
    };
  }
};