/src/validate.js

https://github.com/EOSIO/eosjs-keygen · JavaScript · 68 lines · 46 code · 12 blank · 10 comment · 4 complexity · f1766a216bce51096d8996fb284c6a24 MD5 · raw file

  1. const assert = require('assert')
  2. const {PrivateKey, PublicKey} = require('eosjs-ecc')
  3. module.exports = {
  4. keyType,
  5. path,
  6. isPath,
  7. isMasterKey
  8. }
  9. function isMasterKey(key) {
  10. return /^PW/.test(key) && PrivateKey.isWif(key.substring(2))
  11. }
  12. function keyType(key) {
  13. return isMasterKey(key) ? 'master' :
  14. PrivateKey.isWif(key) ? 'wif' :
  15. PrivateKey.isValid(key) ? 'privateKey' :
  16. PublicKey.isValid(key) ? 'pubkey' :
  17. null
  18. }
  19. function isPath(txt) {
  20. try {
  21. path(txt)
  22. return true
  23. } catch(e) {
  24. return false
  25. }
  26. }
  27. /**
  28. Static validation of a keyPath. Protect against common mistakes.
  29. @see [validate.test.js](./validate.test.js)
  30. @arg {keyPath} path
  31. @example path('owner')
  32. @example path('active')
  33. @example path('active/mypermission')
  34. */
  35. function path(path) {
  36. assert.equal(typeof path, 'string', 'path')
  37. assert(path !== '', 'path should not be empty')
  38. assert(path.indexOf(' ') === -1, 'remove spaces')
  39. assert(path.indexOf('\\') === -1, 'use forward slash')
  40. assert(path[0] !== '/', 'remove leading slash')
  41. assert(path[path.length - 1] !== '/', 'remove ending slash')
  42. assert(!/[A-Z]/.test(path), 'path should not have uppercase letters')
  43. assert(path !== 'owner/active', 'owner is implied, juse use active')
  44. const el = Array.from(path.split('/'))
  45. const unique = new Set()
  46. el.forEach(e => {unique.add(e)})
  47. assert(unique.size === el.length, 'duplicate path element')
  48. assert(el[0] === 'owner' || el[0] === 'active',
  49. 'path should start with owner or active')
  50. assert(!el.includes('owner') || el.indexOf('owner') === 0,
  51. 'owner is always first')
  52. assert(!el.includes('active') || el.indexOf('active') === 0,
  53. 'active is always first')
  54. }