All files / src/storage put-file.ts

58.06% Statements 36/62
63.33% Branches 19/30
66.66% Functions 2/3
58.06% Lines 36/62

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          3x   3x 3x 3x 3x       3x   3x         5x 5x 5x   5x 5x   5x 5x     5x                 5x                                   5x                                                                 5x     2x         3x 1x 2x   2x 2x       3x 3x             3x   3x 2x         2x           3x     5x 5x           5x       5x 5x                            
import {
  eciesGetJsonStringLength,
  signECDSA,
  encryptContent,
  getPublicKey,
} from 'micro-stacks/crypto';
 
import { uploadToGaiaHub } from './gaia/hub';
import { SIGNATURE_FILE_SUFFIX } from './common/constants';
import { FileContentLoader } from './common/file-content-loader';
import { isRecoverableGaiaError, megabytesToBytes, PayloadTooLargeError } from './gaia/errors';
 
import type { GaiaHubConfig } from './gaia/types';
import type { PutFileOptions } from './common/types';
import { bytesToHex } from 'micro-stacks/common';
 
export async function putFile(
  path: string,
  content: string | Uint8Array | ArrayBufferView | Blob,
  options: PutFileOptions
): Promise<string> {
  let { privateKey } = options;
  const { encrypt, sign: shouldSign, gaiaHubConfig, cipherTextEncoding } = options;
  let { contentType = '' } = options;
 
  const maxUploadBytes = megabytesToBytes(gaiaHubConfig.max_file_upload_size_megabytes);
  const hasMaxUpload = maxUploadBytes > 0;
 
  const contentLoader = new FileContentLoader(content, contentType);
  contentType = contentLoader.contentType;
 
  // When not encrypting the content length can be checked immediately.
  Iif (!encrypt && hasMaxUpload && contentLoader.contentByteLength > maxUploadBytes) {
    const sizeErrMsg = `The max file upload size for this hub is ${maxUploadBytes} bytes, the given content is ${contentLoader.contentByteLength} bytes`;
    const sizeErr = new PayloadTooLargeError(sizeErrMsg, null, maxUploadBytes);
    console.error(sizeErr);
    throw sizeErr;
  }
 
  // When encrypting, the content length must be calculated. Certain types like `Blob`s must
  // be loaded into memory.
  Iif (encrypt && hasMaxUpload && cipherTextEncoding) {
    const encryptedSize = eciesGetJsonStringLength({
      contentLength: contentLoader.contentByteLength,
      wasString: contentLoader.wasString,
      sign: !!shouldSign,
      cipherTextEncoding,
    });
    Iif (encryptedSize > maxUploadBytes) {
      const sizeErrMsg = `The max file upload size for this hub is ${maxUploadBytes} bytes, the given content is ${encryptedSize} bytes after encryption`;
      const sizeErr = new PayloadTooLargeError(sizeErrMsg, null, maxUploadBytes);
      console.error(sizeErr);
      throw sizeErr;
    }
  }
 
  let uploadFn: (hubConfig: GaiaHubConfig) => Promise<string>;
 
  // In the case of signing, but *not* encrypting, we perform two uploads.
  Iif (!encrypt && shouldSign) {
    const contents: string | Uint8Array = await contentLoader.load();
 
    if (typeof shouldSign === 'string') {
      privateKey = shouldSign;
    } else Iif (!privateKey) {
      throw Error('Need to pass private key');
    }
 
    const signatureResponse = await signECDSA({ contents, privateKey });
 
    uploadFn = async (hubConfig: GaiaHubConfig) => {
      const writeResponse = (
        await Promise.all([
          uploadToGaiaHub({
            filename: path,
            contents,
            hubConfig,
            contentType,
          }),
          uploadToGaiaHub({
            filename: `${path}${SIGNATURE_FILE_SUFFIX}`,
            contents: JSON.stringify(signatureResponse),
            hubConfig,
            contentType: 'application/json',
          }),
        ])
      )[0];
      return writeResponse.publicURL;
    };
  } else {
    // In all other cases, we only need one upload.
    let contentForUpload: string | Uint8Array | Blob;
    if (!encrypt && !shouldSign) {
      // If content does not need encrypted or signed, it can be passed directly
      // to the fetch request without loading into memory.
      contentForUpload = contentLoader.content;
    } else {
      // Use the `encrypt` key, otherwise the `sign` key, if neither are specified
      // then use the current user's app public key.
      let publicKey: string;
      if (typeof encrypt === 'string') {
        publicKey = encrypt;
      } else Iif (typeof shouldSign === 'string') {
        publicKey = bytesToHex(getPublicKey(shouldSign, true));
      } else if (privateKey) {
        publicKey = bytesToHex(getPublicKey(privateKey, true));
      } else E{
        throw new Error('No private key passed');
      }
      const contentData = await contentLoader.load();
      const cipherObject = await encryptContent(contentData, {
        publicKey,
        wasString: contentLoader.wasString,
        cipherTextEncoding,
        privateKey,
      });
 
      contentForUpload = JSON.stringify(cipherObject);
 
      if (privateKey) {
        const { signature, publicKey: signaturePublicKey } = await signECDSA({
          contents: cipherObject,
          privateKey: privateKey!,
        });
 
        contentForUpload = JSON.stringify({
          signature,
          publicKey: signaturePublicKey,
          cipherText: cipherObject,
        });
      }
      contentType = 'application/json';
    }
 
    uploadFn = async (hubConfig: GaiaHubConfig) => {
      const writeResponse = await uploadToGaiaHub({
        filename: path,
        contents: contentForUpload,
        hubConfig,
        contentType,
      });
      return writeResponse.publicURL;
    };
  }
 
  try {
    return await uploadFn(gaiaHubConfig);
  } catch (error: any) {
    // If the upload fails on first attempt, it could be due to a recoverable
    // error which may succeed by refreshing the config and retrying.
    // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
    if (isRecoverableGaiaError(error)) {
      console.error(error);
      console.error('Possible recoverable error during Gaia upload, retrying...');
      return await uploadFn(gaiaHubConfig);
    } else {
      throw error;
    }
  }
}