# All files / src/auth userSession.js

46.81% Statements 22/47
48% Branches 12/25
38.89% Functions 7/18
46.81% Lines 22/47

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

    27x

    27x
    27x
    27x

    27x
    27x

    27x

    27x

    27x
    27x

    5x

    5x

    5x
    5x
    5x
    5x
    5x

    6x

    17x

    2x

    4x

    1x

     /* @flow */
    import queryString from 'query-string'
    import { AppConfig } from './appConfig'
    import type { SessionOptions } from './sessionData'
    import {
      LocalStorageStore,
      SessionDataStore,
      InstanceDataStore
    } from './sessionStore'
    import {
      redirectToSignInImpl,
      redirectToSignInWithAuthRequestImpl,
      handlePendingSignInImpl,
      loadUserDataImpl
    } from './authApp'

    import {
      makeAuthRequestImpl,
      generateTransitKey
    } from './authMessages'

    import {
      decryptContentImpl,
      encryptContentImpl,
      getFileImpl,
      putFileImpl,
      listFilesImpl,
      getFileUrlImpl
    } from '../storage'

    import type {
      PutFileOptions
    } from '../storage'

    import {
      nextHour
    } from '../utils'
    import {
      MissingParameterError,
      InvalidStateError
    } from '../errors'
    import { Logger } from '../logger'

    /**
     * Represents an instance of a signed in user for a particular app.
     *
     * A signed in user has access to two major pieces of information
     * about the user, the user's private key for that app and the location
     * of the user's gaia storage bucket for the app.
     *
     * A user can be signed in either directly through the interactive
     * sign in process or by directly providing the app private key.
     * @type {UserSession}
     */
    export class UserSession {
      appConfig: AppConfig

      store: SessionDataStore

      constructor(options?: {appConfig?: AppConfig,
        sessionStore?: SessionDataStore,
        sessionOptions?: SessionOptions }) {
        let runningInBrowser = true

        Eif (typeof window === 'undefined') {
          Logger.debug('UserSession: not running in browser')
          runningInBrowser = false
        }

        Eif (options && options.appConfig) {
          this.appConfig = options.appConfig
        } else if (runningInBrowser) {
          this.appConfig = new AppConfig()
        } else {
          throw new MissingParameterError('You need to specify options.appConfig')
        }

        Iif (options && options.sessionStore) {
          this.store = options.sessionStore
        } else Iif (runningInBrowser) {
          if (options) {
            this.store = new LocalStorageStore(options.sessionOptions)
          } else {
            this.store = new LocalStorageStore()
          }
        } else Eif (options) {
          this.store = new InstanceDataStore(options.sessionOptions)
        } else {
          this.store = new InstanceDataStore()
        }
      }

      /* AUTHENTICATION */

      /**
       * Generates an authentication request and redirects the user to the Blockstack
       * browser to approve the sign in request.
       *
       * Please note that this requires that the web browser properly handles the
       * `blockstack:` URL protocol handler.
       *
       * Most applications should use this
       * method for sign in unless they require more fine grained control over how the
       * authentication request is generated. If your app falls into this category,
       * use `generateAndStoreTransitKey`, `makeAuthRequest`,
       * and `redirectToSignInWithAuthRequest` to build your own sign in process.
       *
       * @return {void}
       */
      redirectToSignIn() {
        return redirectToSignInImpl(this)
      }

      /**
       * Redirects the user to the Blockstack browser to approve the sign in request
       * given.
       *
       * The user is redirected to the authenticator URL specified in the `AppConfig`
       * if the `blockstack:` protocol handler is not detected.
       * Please note that the protocol handler detection
       * does not work on all browsers.
       * @param  {String} authRequest - the authentication request generated by `makeAuthRequest`
       * @return {void}
       */
      redirectToSignInWithAuthRequest(authRequest: string) {
        return redirectToSignInWithAuthRequestImpl(this, authRequest)
      }

      /**
       * Generates an authentication request that can be sent to the Blockstack
       * browser for the user to approve sign in. This authentication request can
       * then be used for sign in by passing it to the `redirectToSignInWithAuthRequest`
       * method.
       *
       * *Note: This method should only be used if you want to roll your own authentication
       * flow. Typically you'd use `redirectToSignIn` which takes care of this
       * under the hood.*
       * @param {string} transitKey - hex-encoded transit key
       * @param {Number} expiresAt - the time at which this request is no longer valid
       * @param {Object} extraParams - Any extra parameters you'd like to pass to the authenticator.
       * Use this to pass options that aren't part of the Blockstack auth spec, but might be supported
       * by special authenticators.
       * @return {String} the authentication request
       * @private
       */
      makeAuthRequest(transitKey: string,
                      expiresAt: number = nextHour().getTime(),
                      extraParams: Object = {}): string {
        const appConfig = this.appConfig

        Iif (!appConfig) {
          throw new InvalidStateError('Missing AppConfig')
        }
        const redirectURI = appConfig.redirectURI()
        const manifestURI = appConfig.manifestURI()
        const scopes = appConfig.scopes
        const appDomain = appConfig.appDomain
        return makeAuthRequestImpl(transitKey, redirectURI, manifestURI,
                                   scopes, appDomain, expiresAt, extraParams)
      }

      /**
       * Generates a ECDSA keypair to
       * use as the ephemeral app transit private key
       * and store in the session
       * @return {String} the hex encoded private key
       *
       */
      generateAndStoreTransitKey(): string {
        const sessionData = this.store.getSessionData()
        const transitKey = generateTransitKey()
        sessionData.transitKey = transitKey
        this.store.setSessionData(sessionData)
        return transitKey
      }

      /**
       * Retrieve the authentication token from the URL query
       * @return {String} the authentication token if it exists otherwise `null`
       */
      getAuthResponseToken(): string {
        const queryDict = queryString.parse(location.search)
        return queryDict.authResponse ? queryDict.authResponse : ''
      }

      /**
       * Check if there is a authentication request that hasn't been handled.
       * @return {Boolean} `true` if there is a pending sign in, otherwise `false`
       */
      isSignInPending() {
        return !!this.getAuthResponseToken()
      }

      /**
       * Check if a user is currently signed in.
       * @return {Boolean} `true` if the user is signed in, `false` if not.
       */
      isUserSignedIn() {
        return !!this.store.getSessionData().userData
      }

      /**
       * Try to process any pending sign in request by returning a `Promise` that resolves
       * to the user data object if the sign in succeeds.
       *
       * @param {String} authResponseToken - the signed authentication response token
       * @return {Promise} that resolves to the user data object if successful and rejects
       * if handling the sign in request fails or there was no pending sign in request.
       */
      handlePendingSignIn(authResponseToken: string = this.getAuthResponseToken()) {
        return handlePendingSignInImpl(this, authResponseToken)
      }

      /**
       * Retrieves the user data object. The user's profile is stored in the key `profile`.
       * @return {Object} User data object.
       */
      loadUserData() {
        return loadUserDataImpl(this)
      }

      /**
       * Sign the user out
       * @return {void}
       */
      signUserOut() {
        this.store.deleteSessionData()
      }

      //
      //
      // /* PROFILES */
      // extractProfile
      // wrapProfileToken
      // signProfileToken
      // verifyProfileToken
      // validateProofs
      // lookupProfile

      /* STORAGE */

      /**
       * Encrypts the data provided with the app public key.
       * @param {String|Buffer} content - data to encrypt
       * @param {Object} [options=null] - options object
       * @param {String} options.publicKey - the hex string of the ECDSA public
       * key to use for encryption. If not provided, will use user's appPrivateKey.
       * @return {String} Stringified ciphertext object
       */
      encryptContent(content: string | Buffer,
                     options?: {publicKey?: string}) {
        return encryptContentImpl(this, content, options)
      }

      /**
       * Decrypts data encrypted with `encryptContent` with the
       * transit private key.
       * @param {String|Buffer} content - encrypted content.
       * @param {Object} [options=null] - options object
       * @param {String} options.privateKey - the hex string of the ECDSA private
       * key to use for decryption. If not provided, will use user's appPrivateKey.
       * @return {String|Buffer} decrypted content.
       */
      decryptContent(content: string, options?: {privateKey?: ?string}) {
        return decryptContentImpl(this, content, options)
      }

      /**
       * Stores the data provided in the app's data store to to the file specified.
       * @param {String} path - the path to store the data in
       * @param {String|Buffer} content - the data to store in the file
       * @param {Object} [options=null] - options object
       * @param {Boolean|String} [options.encrypt=true] - encrypt the data with the app private key
       *                                                  or the provided public key
       * @param {Boolean} [options.sign=false] - sign the data using ECDSA on SHA256 hashes with
       *                                         the app private key
       * @return {Promise} that resolves if the operation succeed and rejects
       * if it failed
       */
      putFile(path: string, content: string | Buffer, options?: PutFileOptions) {
        return putFileImpl(this, path, content, options)
      }

      /**
       * Retrieves the specified file from the app's data store.
       * @param {String} path - the path to the file to read
       * @param {Object} [options=null] - options object
       * @param {Boolean} [options.decrypt=true] - try to decrypt the data with the app private key
       * @param {String} options.username - the Blockstack ID to lookup for multi-player storage
       * @param {Boolean} options.verify - Whether the content should be verified, only to be used
       * when `putFile` was set to `sign = true`
       * @param {String} options.app - the app to lookup for multi-player storage -
       * defaults to current origin
       * @param {String} [options.zoneFileLookupURL=null] - The URL
       * to use for zonefile lookup. If falsey, this will use the
       * blockstack.js's getNameInfo function instead.
       * @returns {Promise} that resolves to the raw data in the file
       * or rejects with an error
       */
      getFile(path: string, options?: {
          decrypt?: boolean,
          verify?: boolean,
          username?: string,
          app?: string,
          zoneFileLookupURL?: ?string
        }) {
        return getFileImpl(this, path, options)
      }

      /**
       * Get the URL for reading a file from an app's data store.
       * @param {String} path - the path to the file to read
       * @param {Object} [options=null] - options object
       * @param {String} options.username - the Blockstack ID to lookup for multi-player storage
       * @param {String} options.app - the app to lookup for multi-player storage -
       * defaults to current origin
       * @param {String} [options.zoneFileLookupURL=null] - The URL
       * to use for zonefile lookup. If falsey, this will use the
       * blockstack.js's getNameInfo function instead.
       * @returns {Promise<string>} that resolves to the URL or rejects with an error
       */
      getFileUrl(path: string, options?: {
        username?: string,
        app?: string,
        zoneFileLookupURL?: ?string
      }): Promise<string> {
        return getFileUrlImpl(this, path, options)
      }

      /**
       * List the set of files in this application's Gaia storage bucket.
       * @param {function} callback - a callback to invoke on each named file that
       * returns `true` to continue the listing operation or `false` to end it
       * @return {Promise} that resolves to the number of files listed
       */
      listFiles(callback: (name: string) => boolean) : Promise<number> {
        return listFilesImpl(this, callback)
      }

      /**
       * Deletes the specified file from the app's data store. Currently not implemented.
       * @param {String} path - the path to the file to delete
       * @returns {Promise} that resolves when the file has been removed
       * or rejects with an error
       * @private
       */
      deleteFile(path: string) {
        Promise.reject(new Error(`Delete of ${path} not supported by gaia hubs`))
      }
    }