# All files / src/storage hub.ts

77.78% Statements 49/63
52.94% Branches 9/17
85.71% Functions 6/7
77.78% Lines 49/63

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
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

    1x

    4x
    4x

    4x
    2x

    2x
    2x
    2x

    1x

    6x
    6x

    6x
    2x

    1x

    7x

    3x
    3x

    3x

    3x

    3x
    3x

    3x
    3x

    1x

    6x

    6x
    4x
    3x
    3x
    3x

    3x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    import { Transaction, script, ECPair } from 'bitcoinjs-lib'
    import { TokenSigner } from 'jsontokens'
    import { getBlockstackErrorFromResponse } from '../utils'
    import { fetchPrivate } from '../fetchUtil'
    import { getPublicKeyFromPrivate, ecPairToAddress, hexStringToECPair, } from '../keys'
    import { Logger } from '../logger'
    import { randomBytes } from '../encryption/cryptoRandom'
    import { hashSha256Sync } from '../encryption/sha2Hash'

    /**
     * @ignore
     */
    export const BLOCKSTACK_GAIA_HUB_LABEL = 'blockstack-gaia-hub-config'

    /**
     * The configuration for the user's Gaia storage provider.
     */
    export interface GaiaHubConfig {
      address: string,
      url_prefix: string,
      token: string,
      server: string
    }

    /**
     *
     * @param filename
     * @param contents
     * @param hubConfig
     * @param contentType
     *
     * @ignore
     */
    export async function uploadToGaiaHub(
      filename: string,
      contents: Blob | Buffer | ArrayBufferView | string,
      hubConfig: GaiaHubConfig,
      contentType: string = 'application/octet-stream'
    ): Promise<string> {
      Logger.debug(`uploadToGaiaHub: uploading ${filename} to ${hubConfig.server}`)
      const response = await fetchPrivate(
        `${hubConfig.server}/store/${hubConfig.address}/${filename}`, {
          method: 'POST',
          headers: {
            'Content-Type': contentType,
            Authorization: `bearer ${hubConfig.token}`
          },
          body: contents
        }
      )
      if (!response.ok) {
        throw await getBlockstackErrorFromResponse(response, 'Error when uploading to Gaia hub.')
      }
      const responseText = await response.text()
      const responseJSON = JSON.parse(responseText)
      return responseJSON.publicURL
    }

    export async function deleteFromGaiaHub(
      filename: string,
      hubConfig: GaiaHubConfig
    ): Promise<void> {
      Logger.debug(`deleteFromGaiaHub: deleting ${filename} from ${hubConfig.server}`)
      const response = await fetchPrivate(
        `${hubConfig.server}/delete/${hubConfig.address}/${filename}`, {
          method: 'DELETE',
          headers: {
            Authorization: `bearer ${hubConfig.token}`
          }
        }
      )
      if (!response.ok) {
        throw await getBlockstackErrorFromResponse(response, 'Error deleting file from Gaia hub.')
      }
    }

    /**
     *
     * @param filename
     * @param hubConfig
     *
     * @ignore
     */
    export function getFullReadUrl(filename: string,
                                   hubConfig: GaiaHubConfig): Promise<string> {
      return Promise.resolve(`${hubConfig.url_prefix}${hubConfig.address}/${filename}`)
    }

    /**
     *
     * @param challengeText
     * @param signerKeyHex
     *
     * @ignore
     */
    function makeLegacyAuthToken(challengeText: string, signerKeyHex: string): string {
      // only sign specific legacy auth challenges.
      let parsedChallenge
      try {
        parsedChallenge = JSON.parse(challengeText)
      } catch (err) {
        throw new Error('Failed in parsing legacy challenge text from the gaia hub.')
      }
      if (parsedChallenge[0] === 'gaiahub'
          && parsedChallenge[3] === 'blockstack_storage_please_sign') {
        const signer = hexStringToECPair(signerKeyHex
                                         + (signerKeyHex.length === 64 ? '01' : ''))
        const digest = hashSha256Sync(Buffer.from(challengeText))

        const signatureBuffer = signer.sign(digest)
        const signatureWithHash = script.signature.encode(
          signatureBuffer, Transaction.SIGHASH_NONE)

        // We only want the DER encoding so remove the sighash version byte at the end.
        // See: https://github.com/bitcoinjs/bitcoinjs-lib/issues/1241#issuecomment-428062912
        const signature = signatureWithHash.toString('hex').slice(0, -2)

        const publickey = getPublicKeyFromPrivate(signerKeyHex)
        const token = Buffer.from(JSON.stringify(
          { publickey, signature }
        )).toString('base64')
        return token
      } else {
        throw new Error('Failed to connect to legacy gaia hub. If you operate this hub, please update.')
      }
    }

    /**
     *
     * @param hubInfo
     * @param signerKeyHex
     * @param hubUrl
     * @param associationToken
     *
     * @ignore
     */
    function makeV1GaiaAuthToken(hubInfo: any,
                                 signerKeyHex: string,
                                 hubUrl: string,
                                 associationToken?: string): string {
      const challengeText = hubInfo.challenge_text
      const handlesV1Auth = (hubInfo.latest_auth_version
                             && parseInt(hubInfo.latest_auth_version.slice(1), 10) >= 1)
      const iss = getPublicKeyFromPrivate(signerKeyHex)

      Iif (!handlesV1Auth) {
        return makeLegacyAuthToken(challengeText, signerKeyHex)
      }

      const salt = randomBytes(16).toString('hex')
      const payload = {
        gaiaChallenge: challengeText,
        hubUrl,
        iss,
        salt,
        associationToken
      }
      const token = new TokenSigner('ES256K', signerKeyHex).sign(payload)
      return `v1:${token}`
    }

    /**
     *
     * @ignore
     */
    export async function connectToGaiaHub(
      gaiaHubUrl: string,
      challengeSignerHex: string,
      associationToken?: string
    ): Promise<GaiaHubConfig> {
      Logger.debug(`connectToGaiaHub: ${gaiaHubUrl}/hub_info`)

      const response = await fetchPrivate(`${gaiaHubUrl}/hub_info`)
      const hubInfo = await response.json()
      const readURL = hubInfo.read_url_prefix
      const token = makeV1GaiaAuthToken(hubInfo, challengeSignerHex, gaiaHubUrl, associationToken)
      const address = ecPairToAddress(hexStringToECPair(challengeSignerHex
                                        + (challengeSignerHex.length === 64 ? '01' : '')))
      return {
        url_prefix: readURL,
        address,
        token,
        server: gaiaHubUrl
      }
    }

    /**
     *
     * @param gaiaHubUrl
     * @param appPrivateKey
     *
     * @ignore
     */
    export async function getBucketUrl(gaiaHubUrl: string, appPrivateKey: string): Promise<string> {
      const challengeSigner = ECPair.fromPrivateKey(Buffer.from(appPrivateKey, 'hex'))
      const response = await fetchPrivate(`${gaiaHubUrl}/hub_info`)
      const responseText = await response.text()
      const responseJSON = JSON.parse(responseText)
      const readURL = responseJSON.read_url_prefix
      const address = ecPairToAddress(challengeSigner)
      const bucketUrl = `${readURL}${address}/`
      return bucketUrl
    }