All files / src/storage/get-file getters.ts

50% Statements 40/80
33.33% Branches 13/39
80% Functions 4/5
50.63% Lines 40/79

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 2543x 3x   3x         3x 3x 3x                               3x           3x   3x 3x 3x 3x 3x 3x                 3x                     3x         8x 3x             5x     8x     8x                   3x           2x   2x   2x 2x   2x 2x     2x                   3x               8x 8x           8x 8x     8x 8x 8x     8x           8x                             3x                                                                                                                                                                                          
import { publicKeyToBase58Address, verifyECDSA } from 'micro-stacks/crypto';
import { arrayBufferToUint8, fetchPrivate, utf8ToBytes } from 'micro-stacks/common';
 
import { SIGNATURE_FILE_SUFFIX } from '../common/constants';
import {
  DoesNotExist,
  getBlockstackErrorFromResponse,
  SignatureVerificationError,
} from '../gaia/errors';
import { getFullReadUrl } from '../gaia/hub';
import { lookupProfile } from '../lookup-profile';
 
import type { GaiaHubConfig } from '../gaia/types';
import type { GetFileOptions, GetFileUrlOptions } from '../common/types';
 
/**
 * Fetch the public read URL of a user file for the specified app.
 * @param {String} path - the path to the file to read
 * @param {String} username - The Blockstack ID of the user to look up
 * @param {String} appOrigin - The app origin
 * @param {String} [zoneFileLookupURL=null] - The URL
 * to use for zonefile lookup. If falsey, this will use the
 * blockstack.js's [[getNameInfo]] function instead.
 * @return {Promise<string>} that resolves to the public read URL of the file
 * or rejects with an error
 */
export async function getUserAppFileUrl(
  path: string,
  username: string,
  appOrigin: string,
  zoneFileLookupURL?: string
): Promise<string | undefined> {
  const profile = await lookupProfile({ username, zoneFileLookupURL });
  let bucketUrl: string | undefined;
  Iif (!profile) return;
  if (profile.hasOwnProperty('apps')) {
    if (profile.apps.hasOwnProperty(appOrigin)) {
      const url = profile.apps[appOrigin];
      const bucket = url.replace(/\/?(\?|#|$)/, '/$1');
      bucketUrl = `${bucket}${path}`;
    }
  } else IEif (profile.hasOwnProperty('appsMeta')) {
    Iif (profile.appsMeta.hasOwnProperty(appOrigin)) {
      const url = profile.appsMeta[appOrigin];
      const bucket = url.replace(/\/?(\?|#|$)/, '/$1');
      bucketUrl = `${bucket}${path}`;
    }
  }
  return bucketUrl;
}
 
/**
 * Get the URL for reading a file from an app's data store.
 *
 * @param {String} path - the path to the file to read
 * @param {GetFileUrlOptions} options - the options
 *
 * @returns {Promise<string>} that resolves to the URL or rejects with an error
 */
export async function getFileUrl(
  path: string,
  options: GetFileUrlOptions & { gaiaHubConfig: GaiaHubConfig }
): Promise<string> {
  let readUrl: string | undefined;
  if (options.username) {
    readUrl = await getUserAppFileUrl(
      path,
      options.username,
      options.app!,
      options.zoneFileLookupURL
    );
  } else {
    readUrl = await getFullReadUrl(path, options.gaiaHubConfig);
  }
 
  Iif (!readUrl) {
    throw new Error('Missing readURL');
  } else {
    return readUrl;
  }
}
 
/**
 * Get the gaia address used for servicing multiplayer reads for the given
 * (username, app) pair.
 * @private
 * @ignore
 */
export async function getGaiaAddress(options: {
  app: string;
  gaiaHubConfig?: GaiaHubConfig;
  username?: string;
  zoneFileLookupURL?: string;
}): Promise<string> {
  const { app, username, zoneFileLookupURL, gaiaHubConfig } = options;
  let fileUrl: string | undefined;
  Iif (username) {
    fileUrl = await getUserAppFileUrl('/', username!, app, zoneFileLookupURL);
  } else if (gaiaHubConfig) {
    fileUrl = await getFullReadUrl('/', gaiaHubConfig);
  }
  const matches = /([13][a-km-zA-HJ-NP-Z0-9]{26,35})/.exec(fileUrl!);
  Iif (!matches) {
    throw new Error('Failed to parse gaia address');
  }
  return matches[matches.length - 1];
}
 
/**
 * Handle fetching the contents from a given path. Handles both
 * multi-player reads and reads from own storage.
 *
 * @private
 * @ignore
 */
export async function getFileContents(options: {
  path: string;
  app: string;
  username: string | undefined;
  zoneFileLookupURL?: string;
  forceText: boolean;
  gaiaHubConfig: GaiaHubConfig;
}): Promise<string | Uint8Array | null> {
  const { path, forceText, app, username, zoneFileLookupURL, gaiaHubConfig } = options;
  const readUrl = await getFileUrl(path, {
    app,
    username,
    zoneFileLookupURL,
    gaiaHubConfig,
  });
  const response = await fetchPrivate(readUrl);
  Iif (!response.ok) {
    throw await getBlockstackErrorFromResponse(response, `getFile ${path} failed.`, null);
  }
  let contentType = response.headers.get('Content-Type');
  if (typeof contentType === 'string') {
    contentType = contentType.toLowerCase();
  }
 
  if (
    forceText ||
    contentType === null ||
    contentType.startsWith('text') ||
    contentType.startsWith('application/json')
  ) {
    return response.text();
  } else E{
    const arrayBuffer = await response.arrayBuffer();
    return arrayBufferToUint8(arrayBuffer);
  }
}
 
/**
 * Handle fetching an unencrypted file, its associated signature
 * and then validate it. Handles both multi-player reads and reads
 * from own storage.
 *
 * @private
 * @ignore
 */
export async function getFileSignedUnencrypted(path: string, options: GetFileOptions) {
  const { app, username, zoneFileLookupURL, gaiaHubConfig } = options;
  // future optimization note:
  //    in the case of _multi-player_ reads, this does a lot of excess
  //    profile lookups to figure out where to read files
  //    do browsers cache all these requests if Content-Cache is set?
  const sigPath = `${path}${SIGNATURE_FILE_SUFFIX}`;
  try {
    const [fileContents, signatureContents, gaiaAddress] = await Promise.all([
      getFileContents({
        path,
        app: app!,
        username,
        zoneFileLookupURL,
        forceText: false,
        gaiaHubConfig,
      }),
      getFileContents({
        path: sigPath,
        app: app!,
        username,
        zoneFileLookupURL,
        forceText: true,
        gaiaHubConfig,
      }),
      getGaiaAddress({
        app: app!,
        username,
        zoneFileLookupURL,
        gaiaHubConfig,
      }),
    ]);
 
    Iif (!fileContents) {
      return fileContents;
    }
    Iif (!gaiaAddress) {
      throw new SignatureVerificationError(
        'Failed to get gaia address for verification of: ' + `${path}`
      );
    }
    Iif (!signatureContents || typeof signatureContents !== 'string') {
      throw new SignatureVerificationError(
        'Failed to obtain signature for file: ' +
          `${path} -- looked in ${path}${SIGNATURE_FILE_SUFFIX}`
      );
    }
    let signature: string;
    let publicKey: string;
    try {
      const sigObject = JSON.parse(signatureContents);
      signature = sigObject.signature;
      publicKey = sigObject.publicKey;
    } catch (err) {
      if (err instanceof SyntaxError) {
        throw new Error(
          'Failed to parse signature content JSON ' +
            `(path: ${path}${SIGNATURE_FILE_SUFFIX})` +
            ' The content may be corrupted.'
        );
      } else {
        throw err;
      }
    }
    const signerAddress = publicKeyToBase58Address(publicKey);
    const msgHash = typeof fileContents === 'string' ? utf8ToBytes(fileContents) : fileContents;
 
    const verified = verifyECDSA({ signature, contents: msgHash, publicKey });
 
    if (gaiaAddress !== signerAddress) {
      throw new SignatureVerificationError(
        `Signer pubkey address (${signerAddress}) doesn't` + ` match gaia address (${gaiaAddress})`
      );
    } else if (!verified) {
      throw new SignatureVerificationError(
        'Contents do not match ECDSA signature: ' +
          `path: ${path}, signature: ${path}${SIGNATURE_FILE_SUFFIX}`
      );
    } else {
      return fileContents;
    }
  } catch (err) {
    // For missing .sig files, throw `SignatureVerificationError` instead of `DoesNotExist` error.
    if (err instanceof DoesNotExist && err.message.indexOf(sigPath) >= 0) {
      throw new SignatureVerificationError(
        'Failed to obtain signature for file: ' +
          `${path} -- looked in ${path}${SIGNATURE_FILE_SUFFIX}`
      );
    } else {
      throw err;
    }
  }
}