How to use @tanker/errors - 10 common examples

To help you get started, we’ve selected a few @tanker/errors examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github TankerHQ / sdk-js / packages / stream / cloud-storage / src / s3 / DownloadStream.js View on Github external
}, {
        retries: 2,
      });

      const { status, headers } = response;
      const body = await response.arrayBuffer();

      result = new Uint8Array(body);

      if (!this._totalLength) {
        // Partial content: file is incomplete (i.e. bigger than chunkSize)
        if (status === 206) {
          const header = headers.get('content-range'); // e.g. "bytes 786432-1048575/1048698"

          if (typeof header !== 'string' || !header.match(/^bytes +\d+-\d+\/\d+$/)) {
            throw new NetworkError(`S3 answered with status 206 but an invalid content-range header: ${header}`);
          }

          this._totalLength = parseInt(header.split('/')[1], 0);
        } else {
          this._totalLength = result.length;
        }

        this.log(`found total length ${this._totalLength}`);
      }

      this.log(`received chunk of size ${result.length} and status ${status}`);
      this._downloadedLength += result.length;
    } catch (e) {
      this.emit('error', e);
      return;
    }
github TankerHQ / sdk-js / packages / stream / cloud-storage / src / gcs / DownloadStream.js View on Github external
}, {
        retries: 2,
      });

      const { status, headers } = response;
      const body = await response.arrayBuffer();

      result = new Uint8Array(body);

      if (!this._totalLength) {
        // Partial content: file is incomplete (i.e. bigger than chunkSize)
        if (status === 206) {
          const header = headers.get('content-range'); // e.g. "bytes 786432-1048575/1048698"

          if (typeof header !== 'string' || !header.match(/^bytes +\d+-\d+\/\d+$/)) {
            throw new NetworkError(`GCS answered with status 206 but an invalid content-range header: ${header}`);
          }

          this._totalLength = parseInt(header.split('/')[1], 0);
        } else {
          this._totalLength = result.length;
        }

        this.log(`found total length ${this._totalLength}`);
      }

      this.log(`received chunk of size ${result.length} and status ${status}`);
      this._downloadedLength += result.length;
    } catch (e) {
      this.emit('error', e);
      return;
    }
github TankerHQ / sdk-js / packages / core / src / Trustchain / TrustchainVerifier.js View on Github external
async _unlockedVerifySingleUser(user: ?User, entry: UserEntry): Promise {
    switch (natureKind(entry.nature)) {
      case NATURE_KIND.device_creation: {
        // $FlowIKnow The type is checked by the switch
        const deviceEntry: DeviceCreationEntry = entry;
        return this._unlockedVerifySingleUserDeviceCreation(user, deviceEntry);
      }
      case NATURE_KIND.device_revocation: {
        // $FlowIKnow Type is checked by the switch
        const revocationEntry: UnverifiedDeviceRevocation = entry;
        return this._unlockedVerifySingleUserDeviceRevocation(user, revocationEntry);
      }
      default:
        throw new InternalError(`Assertion error: unexpected nature ${entry.nature}`);
    }
  }
github TankerHQ / sdk-js / packages / core / src / DataProtection / ProgressHandler.js View on Github external
constructor(options: { onProgress?: OnProgress } = {}) {
    // $FlowIKnow Use of Object.prototype
    if (!options || typeof options !== 'object' || Object.getPrototypeOf(options) !== Object.prototype)
      throw new InvalidArgument('options', 'object', options);

    if ('onProgress' in options) {
      const { onProgress } = options;

      if (typeof onProgress !== 'function')
        throw new InvalidArgument('options.onProgress', 'functions', onProgress);

      this._onProgress = onProgress;
    } else {
      // default to no-op
      this._onProgress = (report: ProgressReport) => {}; // eslint-disable-line no-unused-vars
    }
  }
github TankerHQ / sdk-js / packages / core / src / Tanker.js View on Github external
_parseIdentity(identityB64: b64string) {
    // Type verif arguments
    if (!identityB64 || typeof identityB64 !== 'string')
      throw new InvalidArgument('identity', 'b64string', identityB64);
    // End type verif
    const userData = extractUserData(identityB64);
    const userDataTrustchainId = utils.toBase64(userData.trustchainId);

    if (this.trustchainId !== userDataTrustchainId)
      throw new InvalidArgument(`The provided identity was not signed by the private key of the current trustchain: expected trustchain id "${this.trustchainId}", but got "${userDataTrustchainId}"`);
    return userData;
  }
github TankerHQ / sdk-js / packages / identity / src / identity.js View on Github external
export function _deserializePublicIdentity(identity: b64string): PublicIdentity { // eslint-disable-line no-underscore-dangle
  try {
    return utils.fromB64Json(identity);
  } catch (e) {
    throw new InvalidArgument(`Invalid public identity provided: ${identity}`);
  }
}
github TankerHQ / sdk-js / packages / core / src / DataProtection / DataProtector.js View on Github external
const encryptedSize = getDataLength(castEncryptedData);
    // $FlowIKnow Already checked we are using a simple encryption
    const clearSize = encryption.getClearSize(encryptedSize);
    const progressHandler = new ProgressHandler(progressOptions).start(clearSize);

    const resourceId = encryption.extractResourceId(castEncryptedData);
    const key = await this._resourceManager.findKeyFromResourceId(resourceId);

    let clearData;

    try {
    // $FlowIKnow Already checked we are using a simple encryption
      clearData = encryption.decrypt(key, encryption.unserialize(castEncryptedData));
    } catch (error) {
      const b64ResourceId = utils.toBase64(resourceId);
      throw new DecryptionFailed({ error, b64ResourceId });
    }

    const castClearData = await castData(clearData, outputOptions);

    progressHandler.report(clearSize);

    return castClearData;
  }
github TankerHQ / sdk-js / packages / core / src / DataProtection / DecryptorStream.js View on Github external
transform: (encryptedChunk, encoding, done) => {
        try {
          const clearData = encryptionV4.decrypt(key, this._state.index, encryptionV4.unserialize(encryptedChunk));
          this._decryptionStream.push(clearData);
        } catch (error) {
          return done(new DecryptionFailed({ error, b64ResourceId }));
        }
        this._state.lastEncryptedChunkSize = encryptedChunk.length;
        this._state.index += 1; // safe as long as index < 2^53

        done();
      },
github TankerHQ / sdk-js / packages / core / src / Tanker.js View on Github external
async getVerificationMethods(): Promise> {
    // Note: sadly this.assert() does not assert "one in a list"
    if ([statuses.READY, statuses.IDENTITY_VERIFICATION_NEEDED].indexOf(this.status) === -1) {
      const { name: ready } = statusDefs[statuses.READY];
      const { name: verification } = statusDefs[statuses.IDENTITY_VERIFICATION_NEEDED];
      const message = `Expected status ${ready} or ${verification} but got ${this.statusName} trying to get verification methods.`;
      throw new PreconditionFailed(message);
    }

    return this._session.getVerificationMethods();
  }
github TankerHQ / sdk-js / packages / stream / base / src / __tests__ / SlicerStream.spec.js View on Github external
testOptions.forEach(options => {
    const { source } = options;
    const classname = safePrintType(source);

    it(`can slice a ${classname}`, async () => {
      const stream = new SlicerStream({ ...options, outputSize });

      const output: Array = [];
      stream.on('data', (data) => { output.push(data); });

      const testPromise = new Promise((resolve, reject) => {
        stream.on('error', reject);
        stream.on('end', () => {
          try {
            expect(output).to.have.lengthOf(Math.ceil(bytes.length / outputSize));
            output.forEach((chunk, index) => {
              expect(chunk).to.be.an.instanceOf(Uint8Array);
              expect(chunk).to.deep.equal(bytes.subarray(index * outputSize, (index + 1) * outputSize));
            });