All files / src did.ts

0% Statements 0/43
0% Branches 0/16
0% Functions 0/9
0% Lines 0/42

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                                                                                                                                                                                                                                                                                                                                                                                                         
import * as base58 from 'base58-universal/main.js'
import { CryptoSystem, Msg } from 'keystore-idb/types'
 
import eccOperations from 'keystore-idb/ecc/operations'
import rsaOperations from 'keystore-idb/rsa/operations'
import utils from 'keystore-idb/utils'
 
import * as dns from './dns'
import * as keystore from './keystore'
import { arrbufs } from './common'
import { setup } from './setup/internal'
 
 
const ECC_DID_PREFIX: ArrayBuffer = new Uint8Array([ 0xed, 0x01 ]).buffer
const RSA_DID_PREFIX: ArrayBuffer = new Uint8Array([ 0x00, 0xf5, 0x02 ]).buffer
const BASE58_DID_PREFIX: string = 'did:key:z'
 
 
 
// KINDS
 
 
/**
 * Create a DID based on the exchange key-pair.
 */
export async function exchange(): Promise<string> {
  const ks = await keystore.get()
  const pubKeyB64 = await ks.publicReadKey()
 
  return publicKeyToDid(pubKeyB64, ks.cfg.type)
}
 
/**
 * Get the root write-key DID for a user.
 * Stored at `_did.${username}.${endpoints.user}`
 */
export async function root(
  username: string
): Promise<string> {
  const domain = setup.endpoints.user
 
  try {
    const maybeDid = await dns.lookupTxtRecord(`_did.${username}.${domain}`)
    if (maybeDid !== null) return maybeDid
  } catch (_err) {}
 
  throw new Error("Could not locate user DID in DNS.")
}
 
/**
 * Alias `write` to `ucan`
 */
export { write as ucan }
 
/**
 * Create a DID based on the write key-pair.
 */
export async function write(): Promise<string> {
  const ks = await keystore.get()
  const pubKeyB64 = await ks.publicWriteKey()
 
  return publicKeyToDid(pubKeyB64, ks.cfg.type)
}
 
 
 
// TRANSFORMERS
 
 
/**
 * Convert a base64 public key to a DID (did:key).
 */
export function publicKeyToDid(
  publicKey: string,
  type: CryptoSystem
): string {
  const pubKeyBuf = utils.base64ToArrBuf(publicKey)
 
  // Prefix public-write key
  const prefix = magicBytes(type) || new ArrayBuffer(0)
  const prefixedBuf = utils.joinBufs(prefix, pubKeyBuf)
 
  // Encode prefixed
  return BASE58_DID_PREFIX + base58.encode(new Uint8Array(prefixedBuf))
}
 
/**
 * Convert a DID (did:key) to a base64 public key.
 */
export function didToPublicKey(did: string): {
  publicKey: string,
  type: CryptoSystem
} {
  if (!did.startsWith(BASE58_DID_PREFIX)) {
    throw new Error("Please use a base58-encoded DID formatted `did:key:z...`")
  }
 
  const didWithoutPrefix = did.substr(BASE58_DID_PREFIX.length)
  const magicalBuf = base58.decode(didWithoutPrefix).buffer as ArrayBuffer
  const { keyBuffer, type } = parseMagicBytes(magicalBuf)
 
  return {
    publicKey: utils.arrBufToBase64(keyBuffer),
    type
  }
}
 
 
 
// VALIDATION
 
 
/**
 * Verify the signature of some data (string, ArrayBuffer or Uint8Array), given a DID.
 */
export async function verifySignedData({ charSize = 16, data, did, signature }: {
  charSize?: number,
  data: Msg,
  did: string
  signature: string
}): Promise<boolean> {
  try {
    const { type, publicKey } = didToPublicKey(did)
 
    switch (type) {
      case "ecc": return await eccOperations.verify(
        data,
        signature,
        publicKey,
        charSize
      )
 
      case "rsa": return await rsaOperations.verify(
        data,
        signature,
        publicKey,
        charSize
      )
 
      default: return false
    }
 
  } catch (_) {
    return false
 
  }
}
 
 
 
// ㊙️
 
 
/**
 * Magic bytes.
 */
function magicBytes(cryptoSystem: CryptoSystem): ArrayBuffer | null {
  switch (cryptoSystem) {
    case CryptoSystem.RSA: return RSA_DID_PREFIX;
    default: return null
  }
}
 
/**
 * Parse magic bytes on prefixed key-buffer
 * to determine cryptosystem & the unprefixed key-buffer.
 */
const parseMagicBytes = (prefixedKey: ArrayBuffer): {
  keyBuffer: ArrayBuffer
  type: CryptoSystem
} => {
  // RSA
  if (hasPrefix(prefixedKey, RSA_DID_PREFIX)) {
    return {
      keyBuffer: prefixedKey.slice(RSA_DID_PREFIX.byteLength),
      type: CryptoSystem.RSA
    }
 
  // ECC
  } else if (hasPrefix(prefixedKey, ECC_DID_PREFIX)) {
    return {
      keyBuffer: prefixedKey.slice(ECC_DID_PREFIX.byteLength),
      type: CryptoSystem.ECC
    }
 
  }
 
  throw new Error("Unsupported key algorithm. Try using RSA.")
}
 
/**
 * Determines if an ArrayBuffer has a given indeterminate length-prefix.
 */
const hasPrefix = (prefixedKey: ArrayBuffer, prefix: ArrayBuffer): boolean => {
  return arrbufs.equal(prefix, prefixedKey.slice(0, prefix.byteLength))
}