import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { safeJsonParse } from '../json/json-parse.mjs';
import { getCrypto } from '../nodejs/crypto.mjs';
import { getJose } from '../third-party/jose.mjs';

function decodeAuthorizationHeader(authorizationHeader, keyBytes) {
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var jose, dec, payload, exp;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          jose = getJose();
          _context.next = 1;
          return jose.compactDecrypt(authorizationHeader, keyBytes);
        case 1:
          dec = _context.sent;
          payload = safeJsonParse(new TextDecoder().decode(dec.plaintext));
          exp = new Date(payload.Expiration); // 检验 token 是否已经过期，增加3分钟缓冲，避免服务器时间差异
          if (!(Date.now() - 3 * 60 * 1000 > exp.getTime())) {
            _context.next = 2;
            break;
          }
          throw new Error('expired');
        case 2:
          return _context.abrupt("return", payload);
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function checkSignature(key, timestampSeconds, signature, extHeaders) {
  if (!timestampSeconds || isNaN(Number(timestampSeconds))) {
    return false;
  }
  if (!(Math.abs(parseInt(timestampSeconds, 10) * 1000 - Date.now()) <= 180000)) {
    // demo 为了正常运行，此处异常注释了，实际环境需要开启验证
    return false;
  }
  var crypto = getCrypto();
  var hash = crypto.createHash('sha256');
  hash.update(timestampSeconds + key + extHeaders.join(',') + timestampSeconds);
  return signature.toLowerCase() === hash.digest('hex').toLowerCase();
}
function getIdentityFromTOF(headers, key) {
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var extHeaders, keyBytes, taiIdentity, payload, result;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          extHeaders = [headers['x-rio-seq'], '', '', '']; // const key = process.env.MOBILE_WOA_TOF_TOKEN || ''; // real
          keyBytes = new Uint8Array(Buffer.from(key));
          if (checkSignature(key, headers.timestamp, headers.signature, extHeaders)) {
            _context2.next = 1;
            break;
          }
          throw new Error('check smartgate signature failed');
        case 1:
          taiIdentity = headers['x-tai-identity'];
          if (!taiIdentity) {
            _context2.next = 3;
            break;
          }
          _context2.next = 2;
          return decodeAuthorizationHeader(taiIdentity, keyBytes);
        case 2:
          payload = _context2.sent;
          return _context2.abrupt("return", {
            staffid: payload.StaffId,
            staffname: payload.LoginName
          });
        case 3:
          result = {
            staffid: parseInt(headers.staffid, 10) || 0,
            staffname: headers.staffname
          };
          return _context2.abrupt("return", result);
        case 4:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}

export { getIdentityFromTOF };
