'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var error = require('./error-0c1f634f.cjs');
var buffer = require('./buffer-3e750729.cjs');
var string = require('./string-fddc5f8b.cjs');
var json = require('./json-092190a1.cjs');
var ecdsa = require('./ecdsa.cjs');
var time = require('./time-d8438852.cjs');
require('./environment-1c97264d.cjs');
require('./map-24d263c0.cjs');
require('./conditions-f5c0c102.cjs');
require('./storage.cjs');
require('./function-314580f7.cjs');
require('./array-78849c95.cjs');
require('./set-5b47859e.cjs');
require('./object-c0c9435b.cjs');
require('./equality.cjs');
require('./math-96d5e8c4.cjs');
require('./encoding-1a745c43.cjs');
require('./number-1fb57bba.cjs');
require('./binary-ac8e39e2.cjs');
require('./decoding-76e75827.cjs');
require('lib0/webcrypto');
require('./common.cjs');
require('./metric.cjs');

/**
 * @param {Object} data
 */
const _stringify = data => buffer.toBase64UrlEncoded(string.encodeUtf8(json.stringify(data)));

/**
 * @param {string} base64url
 */
const _parse = base64url => json.parse(string.decodeUtf8(buffer.fromBase64UrlEncoded(base64url)));

/**
 * @param {CryptoKey} privateKey
 * @param {Object} payload
 */
const encodeJwt = (privateKey, payload) => {
  const { name: algName, namedCurve: algCurve } = /** @type {any} */ (privateKey.algorithm);
  /* c8 ignore next 3 */
  if (algName !== 'ECDSA' || algCurve !== 'P-384') {
    error.unexpectedCase();
  }
  const header = {
    alg: 'ES384',
    typ: 'JWT'
  };
  const jwt = _stringify(header) + '.' + _stringify(payload);
  return ecdsa.sign(privateKey, string.encodeUtf8(jwt)).then(signature =>
    jwt + '.' + buffer.toBase64UrlEncoded(signature)
  )
};

/**
 * @param {CryptoKey} publicKey
 * @param {string} jwt
 */
const verifyJwt = async (publicKey, jwt) => {
  const [headerBase64, payloadBase64, signatureBase64] = jwt.split('.');
  const verified = await ecdsa.verify(publicKey, buffer.fromBase64UrlEncoded(signatureBase64), string.encodeUtf8(headerBase64 + '.' + payloadBase64));
  /* c8 ignore next 3 */
  if (!verified) {
    throw new Error('Invalid JWT')
  }
  const payload = _parse(payloadBase64);
  if (payload.exp != null && time.getUnixTime() > payload.exp) {
    throw new Error('Expired JWT')
  }
  return {
    header: _parse(headerBase64),
    payload
  }
};

/**
 * Decode a jwt without verifying it. Probably a bad idea to use this. Only use if you know the jwt was already verified!
 *
 * @param {string} jwt
 */
const unsafeDecode = jwt => {
  const [headerBase64, payloadBase64] = jwt.split('.');
  return {
    header: _parse(headerBase64),
    payload: _parse(payloadBase64)
  }
};

exports.encodeJwt = encodeJwt;
exports.unsafeDecode = unsafeDecode;
exports.verifyJwt = verifyJwt;
//# sourceMappingURL=jwt.cjs.map
