<commit_before>import {encrypt} from '../../kms';

export default async (req, res, next) => {
  const plaintext = req.body.secret;
  const keyObj = JSON.parse(req.body.kms_key);

  if (!keyObj) {
    return next(new Error('CMK not defined'));
  }

  if (!plaintext) {
    return next(new Error('Plaintext not entered'));
  }

  const region = keyObj.region;
  const key = keyObj.key;
  const params = {
    KeyId: key,
    Plaintext: plaintext,
    region
  };

  let data;

  try {
    data = await encrypt(params);
  } catch (err) {
    return {
      status: 'ERROR',
      region: key.region,
      text: err.message
    };
  }

  return res.json({
    status: 'SUCCESS',
    region: key.region,
    text: `$tokend:
type: kms
resource: /v1/kms/decrypt
region: ${key.region}
ciphertext: "${key.ciphertext}"
datakey: "${key.datakey}"`
  });
};<commit_msg>Resolved issue with kms endpoint body parsing and error handling behavior for output.<commit_after>import {encrypt} from '../../kms';

export default async (req, res, next) => {
  const plaintext = req.body.secret;
  let keyObj;

  try {
    keyObj = JSON.parse(req.body.key);
  } catch (err) {
    console.log(err);
    keyObj = null;
  }

  if (!keyObj) {
    return next(new Error('CMK not defined'));
  }

  if (!plaintext) {
    return next(new Error('Plaintext not entered'));
  }

  const region = keyObj.region;
  const key = keyObj.key;
  const params = {
    KeyId: key,
    Plaintext: plaintext,
    region
  };

  let data;

  try {
    data = await encrypt(params);
  } catch (err) {
    return next(err);
  }

  const resp = {
    region: data.region
  };

  if (data instanceof Error) {
    resp.status = 'ERROR';
    resp.text = data.message;
  } else {
    resp.status = 'SUCCESS';
    resp.text = `$tokend:
type: kms
resource: /v1/kms/decrypt
region: ${data.region}
ciphertext: "${data.ciphertext}"
datakey: "${data.datakey}"`;
  }

  return res.json(resp);
};
{'fraction_non_alphanumeric': 0.15400516795865632, 'fraction_numerical': 0.0010335917312661498, 'mean_word_length': 2.8642714570858283, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1277280', 'n_tokens_mistral': 695, 'n_tokens_neox': 678, 'n_words': 177}