FORVOUCHERCLUB- WORKERJS. FOR NORMAL USER : SCAM CHECK V1 - SUCCESS VERSION

 import { connect } from 'cloudflare:sockets';

var RSA_OID = [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01];
var SHA256_RSA = [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b];
var SHA384_RSA = [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0c];
var SHA512_RSA = [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0d];

function concat(parts) {
  var len = 0;
  var i;
  for (i = 0; i < parts.length; i++) len += parts[i].length;
  var out = new Uint8Array(len);
  var o = 0;
  for (i = 0; i < parts.length; i++) {
    out.set(parts[i], o);
    o += parts[i].length;
  }
  return out;
}

function u16(n) {
  return new Uint8Array([(n >> 8) & 255, n & 255]);
}

function u24(n) {
  return new Uint8Array([(n >> 16) & 255, (n >> 8) & 255, n & 255]);
}

function latin1(bytes) {
  var s = '';
  var i;
  for (i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
  return s;
}

function hasBytes(buf, start, end, needle) {
  var last = end - needle.length;
  var i;
  var j;
  for (i = start; i <= last; i++) {
    for (j = 0; j < needle.length; j++) {
      if (buf[i + j] !== needle[j]) break;
    }
    if (j === needle.length) return true;
  }
  return false;
}

function der(buf, offset) {
  if (offset + 2 > buf.length) throw new Error('certificate is truncated');
  var tag = buf[offset];
  var lenByte = buf[offset + 1];
  var pos = offset + 2;
  var len = lenByte;
  if (lenByte & 0x80) {
    var n = lenByte & 0x7f;
    if (n < 1 || n > 3) throw new Error('bad certificate length');
    len = 0;
    var i;
    for (i = 0; i < n; i++) len = (len * 256) + buf[pos++];
  }
  var end = pos + len;
  if (end > buf.length) throw new Error('certificate is truncated');
  return { tag: tag, header: offset, start: pos, end: end };
}

function children(buf, node) {
  var list = [];
  var p = node.start;
  while (p < node.end) {
    var child = der(buf, p);
    list.push(child);
    p = child.end;
  }
  return list;
}

function hashNameFromAlg(buf, node) {
  if (hasBytes(buf, node.header, node.end, SHA256_RSA)) return 'SHA-256';
  if (hasBytes(buf, node.header, node.end, SHA384_RSA)) return 'SHA-384';
  if (hasBytes(buf, node.header, node.end, SHA512_RSA)) return 'SHA-512';
  throw new Error('certificate uses an unsupported signature');
}

function tlsHashName(hashAlg) {
  if (hashAlg === 4) return 'SHA-256';
  if (hashAlg === 5) return 'SHA-384';
  if (hashAlg === 6) return 'SHA-512';
  throw new Error('unsupported tls hash ' + hashAlg);
}

function parseTime(buf, node) {
  var s = latin1(buf.subarray(node.start, node.end));
  var year;
  var rest;
  if (node.tag === 0x17) {
    year = parseInt(s.slice(0, 2), 10);
    year += year >= 50 ? 1900 : 2000;
    rest = s.slice(2);
  } else if (node.tag === 0x18) {
    year = parseInt(s.slice(0, 4), 10);
    rest = s.slice(4);
  } else {
    throw new Error('bad certificate date');
  }
  return Date.UTC(
    year,
    parseInt(rest.slice(0, 2), 10) - 1,
    parseInt(rest.slice(2, 4), 10),
    parseInt(rest.slice(4, 6), 10),
    parseInt(rest.slice(6, 8), 10),
    parseInt(rest.slice(8, 10), 10)
  );
}

function readNames(buf, node, into) {
  var p = node.start;
  while (p < node.end) {
    var child = der(buf, p);
    if (child.tag === 0x82 || child.tag === 0x13 || child.tag === 0x0c || child.tag === 0x16) {
      into.push(latin1(buf.subarray(child.start, child.end)));
    } else if ((child.tag & 0x20) === 0x20) {
      readNames(buf, child, into);
    }
    p = child.end;
  }
}

function hostMatches(name, host) {
  var dns = String(name || '').toLowerCase();
  var want = String(host || '').toLowerCase();
  if (!dns || !want) return false;
  if (dns === want) return true;
  if (dns.charAt(0) === '*' && dns.charAt(1) === '.') {
    var suffix = dns.slice(1);
    var head = want.slice(0, want.length - suffix.length);
    return want.length > suffix.length && want.slice(want.length - suffix.length) === suffix && head.indexOf('.') < 0 && head.length > 0;
  }
  return false;
}

function readCert(buf) {
  var cert = der(buf, 0);
  var top = children(buf, cert);
  if (top.length < 3) throw new Error('certificate is not X.509');
  var tbs = top[0];
  var fields = children(buf, tbs);
  var spki = null;
  var validity = null;
  var extensions = null;
  var i;
  for (i = 0; i < fields.length; i++) {
    var field = fields[i];
    if (field.tag === 0x30 && hasBytes(buf, field.header, field.end, RSA_OID)) spki = field;
    if (field.tag === 0xa3) extensions = field;
  }
  if (fields.length > 5 && fields[4].tag === 0x30) validity = fields[4];
  if (!spki) throw new Error('certificate has no RSA key');
  var times = validity ? children(buf, validity) : [];
  var names = [];
  var aiaUrls = [];
  if (extensions) {
    var extSeq = children(buf, extensions);
    var extList = extSeq.length === 1 && extSeq[0].tag === 0x30 ? children(buf, extSeq[0]) : extSeq;
    for (i = 0; i < extList.length; i++) {
      var ext = extList[i];
      var parts = children(buf, ext);
      var octet = null;
      var p;
      for (p = 0; p < parts.length; p++) if (parts[p].tag === 0x04) octet = parts[p];
      if (!octet) continue;
      if (hasBytes(buf, ext.header, ext.end, [0x55, 0x1d, 0x11])) {
        var sanBody = der(buf, octet.start);
        readNames(buf, sanBody, names);
      }
      if (hasBytes(buf, ext.header, ext.end, [0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01])) {
        var aiaBody = der(buf, octet.start);
        var urls = [];
        readNames(buf, aiaBody, urls);
        for (p = 0; p < urls.length; p++) {
          if (urls[p].indexOf('http://') === 0 || urls[p].indexOf('https://') === 0) aiaUrls.push(urls[p]);
        }
      }
    }
  }
  var sig = top[2];
  var unused = buf[sig.start];
  if (unused !== 0) throw new Error('certificate signature is not byte-aligned');
  return {
    tbs: buf.subarray(tbs.header, tbs.end),
    spki: buf.subarray(spki.header, spki.end),
    signature: buf.subarray(sig.start + 1, sig.end),
    hash: hashNameFromAlg(buf, top[1]),
    notBefore: times.length > 0 ? parseTime(buf, times[0]) : 0,
    notAfter: times.length > 1 ? parseTime(buf, times[1]) : 0,
    names: names,
    aiaUrls: aiaUrls
  };
}

function findPem(text) {
  var begin = text.indexOf('-----BEGIN');
  var end = text.indexOf('-----END');
  if (begin < 0 || end < 0) return '';
  var body = text.slice(begin, end).replace(/-----BEGIN[^-]+-----/, '');
  return body.replace(/[^A-Za-z0-9+/=]/g, '');
}

function b64ToBytes(text) {
  var clean = String(text || '').replace(/[^A-Za-z0-9+/=]/g, '');
  if (typeof atob === 'function') {
    var bin = atob(clean);
    var out = new Uint8Array(bin.length);
    var i;
    for (i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
    return out;
  }
  throw new Error('base64 decoder is missing');
}

function decodeCertBytes(bytes) {
  if (bytes[0] === 0x30) return bytes;
  var text = latin1(bytes);
  var b64 = findPem(text);
  if (!b64) throw new Error('certificate authority file is not a certificate');
  return b64ToBytes(b64);
}

async function sha256Hex(bytes) {
  var digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
  var hex = '';
  var i;
  for (i = 0; i < digest.length; i++) {
    var n = digest[i].toString(16);
    hex += n.length === 1 ? '0' + n : n;
  }
  return hex;
}

async function verifyRsa(spki, hash, signature, data) {
  var key = await crypto.subtle.importKey('spki', spki, { name: 'RSASSA-PKCS1-v1_5', hash: hash }, false, ['verify']);
  return crypto.subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, key, signature, data);
}

async function hmacSha256(keyBytes, data) {
  var key = await crypto.subtle.importKey('raw', keyBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  return new Uint8Array(await crypto.subtle.sign('HMAC', key, data));
}

async function prf(secret, label, seed, length) {
  var labelBytes = new TextEncoder().encode(label);
  var material = concat([labelBytes, seed]);
  var a = material;
  var out = new Uint8Array(0);
  while (out.length < length) {
    a = await hmacSha256(secret, a);
    var block = await hmacSha256(secret, concat([a, material]));
    out = concat([out, block]);
  }
  return out.slice(0, length);
}

function seqBytes(n) {
  var b = new Uint8Array(8);
  var x = n;
  var i;
  for (i = 7; i >= 0; i--) {
    b[i] = x & 255;
    x = Math.floor(x / 256);
  }
  return b;
}

function buildAad(seq, type, plainLength) {
  var aad = new Uint8Array(13);
  aad.set(seqBytes(seq), 0);
  aad[8] = type;
  aad[9] = 0x03;
  aad[10] = 0x03;
  aad[11] = (plainLength >> 8) & 255;
  aad[12] = plainLength & 255;
  return aad;
}

function hsMsg(type, body) {
  return concat([new Uint8Array([type]), u24(body.length), body]);
}

function ext(type, body) {
  return concat([u16(type), u16(body.length), body]);
}

function buildClientHello(host, random) {
  var hostBytes = new TextEncoder().encode(host);
  var serverName = concat([new Uint8Array([0]), u16(hostBytes.length), hostBytes]);
  var ciphers = new Uint8Array([0xc0, 0x2f]);
  var sigAlgs = new Uint8Array([0x04, 0x01, 0x05, 0x01, 0x06, 0x01]);
  var groups = new Uint8Array([0x00, 0x17]);
  var extensions = concat([
    ext(0, concat([u16(serverName.length), serverName])),
    ext(10, concat([u16(groups.length), groups])),
    ext(11, new Uint8Array([1, 0])),
    ext(13, concat([u16(sigAlgs.length), sigAlgs])),
    ext(43, new Uint8Array([2, 0x03, 0x03])),
    ext(0xff01, new Uint8Array([0]))
  ]);
  var body = concat([
    new Uint8Array([0x03, 0x03]),
    random,
    new Uint8Array([0]),
    concat([u16(ciphers.length), ciphers]),
    new Uint8Array([1, 0]),
    concat([u16(extensions.length), extensions])
  ]);
  return hsMsg(1, body);
}

function createBuffer(io) {
  var pending = new Uint8Array(0);
  async function pull(n) {
    while (pending.length < n) {
      var chunk = await io.read();
      if (!chunk || chunk.length === 0) throw new Error('semakmule closed the connection');
      var bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
      pending = concat([pending, bytes]);
    }
    var out = pending.slice(0, n);
    pending = pending.slice(n);
    return out;
  }
  async function readRecord() {
    var head = await pull(5);
    var type = head[0];
    var len = head[3] * 256 + head[4];
    if (len < 0 || len > 18432) throw new Error('tls record is too large');
    var payload = len ? await pull(len) : new Uint8Array(0);
    return { type: type, payload: payload };
  }
  return { readRecord: readRecord };
}

async function sendRecord(io, type, versionMinor, payload) {
  var head = new Uint8Array(5);
  head[0] = type;
  head[1] = 0x03;
  head[2] = versionMinor;
  head[3] = (payload.length >> 8) & 255;
  head[4] = payload.length & 255;
  await io.write(concat([head, payload]));
}

function takeHs(state) {
  var messages = [];
  while (state.hs.length >= 4) {
    var len = state.hs[1] * 65536 + state.hs[2] * 256 + state.hs[3];
    if (state.hs.length < 4 + len) break;
    var msg = state.hs.slice(0, 4 + len);
    state.hs = state.hs.slice(4 + len);
    messages.push(msg);
  }
  return messages;
}

async function importAes(bytes) {
  return crypto.subtle.importKey('raw', bytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
}

async function seal(key, iv, seq, type, plain) {
  var explicit = seqBytes(seq);
  var nonce = concat([iv, explicit]);
  var sealed = new Uint8Array(await crypto.subtle.encrypt({
    name: 'AES-GCM',
    iv: nonce,
    additionalData: buildAad(seq, type, plain.length),
    tagLength: 128
  }, key, plain));
  return concat([explicit, sealed]);
}

async function open(key, iv, seq, type, payload) {
  if (payload.length < 24) throw new Error('tls record is too short');
  var explicit = payload.slice(0, 8);
  var sealed = payload.slice(8);
  var plainLen = sealed.length - 16;
  var nonce = concat([iv, explicit]);
  try {
    var plain = await crypto.subtle.decrypt({
      name: 'AES-GCM',
      iv: nonce,
      additionalData: buildAad(seq, type, plainLen),
      tagLength: 128
    }, key, sealed);
    return new Uint8Array(plain);
  } catch (e) {
    throw new Error('tls decryption failed');
  }
}

function sameBytes(a, b) {
  if (a.length !== b.length) return false;
  var diff = 0;
  var i;
  for (i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
  return diff === 0;
}

async function tlsHttp(io, req) {
  var host = req.host;
  var clientRandom = new Uint8Array(32);
  crypto.getRandomValues(clientRandom);
  var transcript = [];
  var clientHello = buildClientHello(host, clientRandom);
  transcript.push(clientHello);
  await sendRecord(io, 22, 1, clientHello);

  var reader = createBuffer(io);
  var hs = new Uint8Array(0);
  var serverRandom = null;
  var leaf = null;
  var skeBody = null;
  var done = false;
  while (!done) {
    var rec = await reader.readRecord();
    if (rec.type === 21) throw new Error('semakmule refused the tls handshake (' + rec.payload[0] + '/' + rec.payload[1] + ')');
    if (rec.type !== 22) throw new Error('unexpected tls record ' + rec.type);
    hs = concat([hs, rec.payload]);
    var state = { hs: hs };
    var messages = takeHs(state);
    hs = state.hs;
    var m;
    for (m = 0; m < messages.length; m++) {
      var msg = messages[m];
      transcript.push(msg);
      var kind = msg[0];
      var body = msg.slice(4);
      if (kind === 2) {
        serverRandom = body.slice(2, 34);
        var sessionLen = body[34];
        var cipherAt = 35 + sessionLen;
        var cipher = body[cipherAt] * 256 + body[cipherAt + 1];
        if (cipher !== 0xc02f) throw new Error('semakmule chose an unsupported cipher ' + cipher.toString(16));
      } else if (kind === 11) {
        var listLen = body[0] * 65536 + body[1] * 256 + body[2];
        var certLen = body[3] * 65536 + body[4] * 256 + body[5];
        if (certLen < 64 || 6 + certLen > body.length) throw new Error('semakmule sent a bad certificate');
        leaf = body.slice(6, 6 + certLen);
        if (listLen > 3 + certLen) {
          // The server sent only the leaf on purpose. Extra certs are ignored.
        }
      } else if (kind === 12) {
        skeBody = body;
      } else if (kind === 14) {
        done = true;
      } else if (kind === 13) {
        throw new Error('semakmule asked for a client certificate');
      }
    }
  }
  if (!serverRandom || !leaf || !skeBody) throw new Error('semakmule tls handshake was incomplete');

  var info = readCert(leaf);
  var now = Date.now();
  if (info.notBefore && now + 300000 < info.notBefore) throw new Error('semakmule certificate is not valid yet');
  if (info.notAfter && now - 300000 > info.notAfter) throw new Error('semakmule certificate is expired');
  var named = false;
  var n;
  for (n = 0; n < info.names.length; n++) {
    if (hostMatches(info.names[n], host)) named = true;
  }
  if (!named) throw new Error('semakmule certificate name does not match');
  if (skeBody[0] !== 3) throw new Error('semakmule used an unsupported key exchange');
  var curve = skeBody[1] * 256 + skeBody[2];
  if (curve !== 0x0017) throw new Error('semakmule used an unsupported curve ' + curve.toString(16));
  var pointLen = skeBody[3];
  var serverPoint = skeBody.slice(4, 4 + pointLen);
  if (serverPoint[0] !== 4 || serverPoint.length !== 65) throw new Error('semakmule sent a bad public key');
  var hashAlg = skeBody[4 + pointLen];
  var sigAlg = skeBody[5 + pointLen];
  var skeSigLen = skeBody[6 + pointLen] * 256 + skeBody[7 + pointLen];
  var skeSig = skeBody.slice(8 + pointLen, 8 + pointLen + skeSigLen);
  if (sigAlg !== 1) throw new Error('semakmule used an unsupported signature');
  var signedParams = concat([clientRandom, serverRandom, skeBody.slice(0, 4 + pointLen)]);
  var skeOk = await verifyRsa(info.spki, tlsHashName(hashAlg), skeSig, signedParams);
  if (!skeOk) throw new Error('semakmule key exchange signature is invalid');

  var caUrl = info.aiaUrls.length ? info.aiaUrls[0] : 'http://secure.globalsign.com/cacert/gsgccr46ovtlsca2025.crt';
  if (!req.fetchCa) throw new Error('certificate loader is missing');
  var caBytes = decodeCertBytes(await req.fetchCa(caUrl));
  var caInfo = readCert(caBytes);
  if (req.pin) {
    var pin = await sha256Hex(caInfo.spki);
    if (pin !== req.pin) throw new Error('certificate authority does not match the expected GlobalSign key');
  }
  var certOk = await verifyRsa(caInfo.spki, info.hash, info.signature, info.tbs);
  if (!certOk) throw new Error('semakmule certificate was not signed by the expected authority');

  var serverKey = await crypto.subtle.importKey('raw', serverPoint, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
  var clientKeys = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']);
  var clientPoint = new Uint8Array(await crypto.subtle.exportKey('raw', clientKeys.publicKey));
  var shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: serverKey }, clientKeys.privateKey, 256));
  if (shared.length < 32) {
    var padded = new Uint8Array(32);
    padded.set(shared, 32 - shared.length);
    shared = padded;
  } else if (shared.length > 32) {
    shared = shared.slice(shared.length - 32);
  }
  var master = await prf(shared, 'master secret', concat([clientRandom, serverRandom]), 48);
  var keyBlock = await prf(master, 'key expansion', concat([serverRandom, clientRandom]), 40);
  var clientKey = await importAes(keyBlock.slice(0, 16));
  var serverAes = await importAes(keyBlock.slice(16, 32));
  var clientIv = keyBlock.slice(32, 36);
  var serverIv = keyBlock.slice(36, 40);

  var clientKx = hsMsg(16, concat([new Uint8Array([clientPoint.length]), clientPoint]));
  transcript.push(clientKx);
  await sendRecord(io, 22, 3, clientKx);
  await sendRecord(io, 20, 3, new Uint8Array([1]));

  var transcriptBytes = concat(transcript);
  var clientVerify = await prf(master, 'client finished', new Uint8Array(await crypto.subtle.digest('SHA-256', transcriptBytes)), 12);
  var clientFinished = hsMsg(20, clientVerify);
  transcript.push(clientFinished);
  var clientSeq = 0;
  await sendRecord(io, 22, 3, await seal(clientKey, clientIv, clientSeq, 22, clientFinished));
  clientSeq += 1;

  var serverSeq = 0;
  var serverFinished = null;
  while (!serverFinished) {
    var next = await reader.readRecord();
    if (next.type === 20) continue;
    var plain = await open(serverAes, serverIv, serverSeq, next.type, next.payload);
    serverSeq += 1;
    if (next.type === 22 && plain[0] === 20) serverFinished = plain;
    else throw new Error('expected semakmule handshake finished');
  }
  var beforeServer = concat(transcript);
  var expectServer = await prf(master, 'server finished', new Uint8Array(await crypto.subtle.digest('SHA-256', beforeServer)), 12);
  if (!sameBytes(expectServer, serverFinished.slice(4, 16))) throw new Error('semakmule handshake finished check failed');

  var headerLines = [
    req.method + ' ' + req.path + ' HTTP/1.1',
    'Host: ' + host,
    'Accept: application/json, text/plain, */*',
    'Origin: https://' + host,
    'Referer: https://' + host + '/',
    'User-Agent: Mozilla/5.0',
    'Connection: close'
  ];
  var bodyBytes = req.body ? (typeof req.body === 'string' ? new TextEncoder().encode(req.body) : req.body) : new Uint8Array(0);
  if (req.method !== 'GET' && req.method !== 'HEAD') {
    headerLines.push('Content-Type: application/json');
    headerLines.push('Content-Length: ' + bodyBytes.length);
  }
  var extra = req.headers || {};
  var name;
  for (name in extra) headerLines.push(name + ': ' + extra[name]);
  var http = new TextEncoder().encode(headerLines.join('\r\n') + '\r\n\r\n');
  if (bodyBytes.length) http = concat([http, bodyBytes]);
  await sendRecord(io, 23, 3, await seal(clientKey, clientIv, clientSeq, 23, http));
  clientSeq += 1;

  var app = new Uint8Array(0);
  var finishedRead = false;
  while (!finishedRead) {
    var appRec;
    try {
      appRec = await reader.readRecord();
    } catch (err) {
      if (app.length) break;
      throw err;
    }
    if (appRec.type === 20) continue;
    var appPlain = await open(serverAes, serverIv, serverSeq, appRec.type, appRec.payload);
    serverSeq += 1;
    if (appRec.type === 21) {
      if (appPlain.length > 1 && appPlain[1] === 0) break;
      throw new Error('semakmule tls alert ' + appPlain[0] + '/' + appPlain[1]);
    }
    if (appRec.type === 23) app = concat([app, appPlain]);
    if (httpComplete(app)) finishedRead = true;
  }
  return parseHttp(app);
}

function indexOfBytes(buf, pattern, from) {
  var last = buf.length - pattern.length;
  var i;
  var j;
  for (i = from; i <= last; i++) {
    for (j = 0; j < pattern.length; j++) if (buf[i + j] !== pattern[j]) break;
    if (j === pattern.length) return i;
  }
  return -1;
}

function headerValue(headerText, name) {
  var lines = headerText.split('\r\n');
  var want = name.toLowerCase();
  var i;
  for (i = 1; i < lines.length; i++) {
    var cut = lines[i].indexOf(':');
    if (cut > 0 && lines[i].slice(0, cut).trim().toLowerCase() === want) return lines[i].slice(cut + 1).trim();
  }
  return '';
}

function httpComplete(bytes) {
  var sep = indexOfBytes(bytes, [13, 10, 13, 10], 0);
  if (sep < 0) return false;
  var headerText = latin1(bytes.slice(0, sep));
  var body = bytes.slice(sep + 4);
  var lenText = headerValue(headerText, 'content-length');
  if (lenText) return body.length >= parseInt(lenText, 10);
  return false;
}

function decodeChunks(body) {
  var out = [];
  var i = 0;
  while (i < body.length) {
    var lineEnd = indexOfBytes(body, [13, 10], i);
    if (lineEnd < 0) break;
    var size = parseInt(latin1(body.slice(i, lineEnd)).split(';')[0], 16);
    if (!size) break;
    i = lineEnd + 2;
    out.push(body.slice(i, i + size));
    i += size + 2;
  }
  return out.length ? concat(out) : new Uint8Array(0);
}

function parseHttp(bytes) {
  var sep = indexOfBytes(bytes, [13, 10, 13, 10], 0);
  if (sep < 0) throw new Error('semakmule returned an incomplete http response');
  var headerText = latin1(bytes.slice(0, sep));
  var status = parseInt(headerText.split(' ')[1], 10);
  var body = bytes.slice(sep + 4);
  var lenText = headerValue(headerText, 'content-length');
  if (lenText) body = body.slice(0, parseInt(lenText, 10));
  else if (headerValue(headerText, 'transfer-encoding').toLowerCase().indexOf('chunked') >= 0) body = decodeChunks(body);
  return { status: status, body: new TextDecoder().decode(body) };
}

var HOST = 'semakmule.rmp.gov.my';
var INTERMEDIATE_PIN = '9d9e10b16c62bc172eb85908f1d5e07dad0f6f6a35b2367c84ac7a87eef6f71c';
var SEARCH_PATH = '/api/mule/get_search_data.php';
var STATS_PATH = '/api/mule/get_homepage_stats';
var LIVE_PATH = '/api/mule/get_latest_data.php';
var cachedCa = null;

function corsHeaders(request, extra) {
  var headers = {
    'Access-Control-Allow-Origin': request.headers.get('Origin') || '*',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Max-Age': '86400',
    'Vary': 'Origin'
  };
  if (extra) {
    Object.keys(extra).forEach(function (key) {
      headers[key] = extra[key];
    });
  }
  return headers;
}

function jsonResponse(request, body, status) {
  return new Response(JSON.stringify(body), {
    status: status,
    headers: corsHeaders(request, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
  });
}

function cleanPhone(value) {
  var text = String(value == null ? '' : value).trim();
  return (text.charAt(0) === '+' ? '+' : '') + text.replace(/[^0-9]/g, '');
}

function withTimeout(promise, ms, label) {
  return new Promise(function (resolve, reject) {
    var timer = setTimeout(function () { reject(new Error(label)); }, ms);
    promise.then(function (value) {
      clearTimeout(timer);
      resolve(value);
    }, function (err) {
      clearTimeout(timer);
      reject(err);
    });
  });
}

async function fetchCa(url) {
  if (cachedCa) return cachedCa;
  var resp = await fetch(url);
  if (!resp.ok) throw new Error('Could not download the certificate authority (HTTP ' + resp.status + ')');
  cachedCa = new Uint8Array(await resp.arrayBuffer());
  return cachedCa;
}

function openSocket(host) {
  var socket = connect({ hostname: host, port: 443 });
  var writer = null;
  var reader = null;
  return {
    write: function (bytes) {
      return withTimeout(socket.opened.then(function () {
        if (!writer) writer = socket.writable.getWriter();
        return writer.write(bytes);
      }), 20000, 'semakmule connection timed out');
    },
    read: function () {
      return withTimeout(socket.opened.then(function () {
        if (!reader) reader = socket.readable.getReader();
        return reader.read().then(function (result) {
          if (result.done) return null;
          return result.value;
        });
      }), 20000, 'semakmule connection timed out');
    },
    close: function () {
      return socket.close().catch(function () { return null; });
    }
  };
}

async function muleHttp(method, path, body) {
  var io = openSocket(HOST);
  try {
    var result = await tlsHttp(io, {
      host: HOST,
      method: method,
      path: path,
      body: body || '',
      headers: { apikey: 'j3j389#nklala2' },
      fetchCa: fetchCa,
      pin: INTERMEDIATE_PIN
    });
    var data = null;
    try { data = JSON.parse(result.body); } catch (e) { data = null; }
    return { httpStatus: result.status, data: data, raw: result.body };
  } finally {
    await io.close();
  }
}

async function relayGet(request, path, step) {
  try {
    var result = await muleHttp('GET', path, '');
    if (!result.data || result.data.status !== 1) {
      return jsonResponse(request, {
        ok: false,
        step: step,
        error: 'semakmule returned an unexpected reply (HTTP ' + result.httpStatus + ')',
        raw: String(result.raw || '').slice(0, 500)
      }, 502);
    }
    return jsonResponse(request, { ok: true, step: step, data: result.data.data, source: result.data }, 200);
  } catch (err) {
    return jsonResponse(request, { ok: false, step: step, error: 'Could not reach semakmule: ' + err.message }, 502);
  }
}

async function handleRequest(request) {
  if (request.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders(request) });
  }

  if (request.method === 'GET') {
    var action = new URL(request.url).searchParams.get('action') || '';
    if (action === 'stats') return relayGet(request, STATS_PATH, 'stats');
    if (action === 'live') return relayGet(request, LIVE_PATH, 'live');
    return jsonResponse(request, {
      ok: true,
      service: 'semakmule-phone',
      version: '2026-10-14-diagnostics',
      usage: 'GET ?action=stats | GET ?action=live | POST JSON {"phone":"0123456789"}'
    }, 200);
  }

  if (request.method !== 'POST') {
    return jsonResponse(request, { ok: false, error: 'Method not allowed' }, 405);
  }

  var input;
  try {
    input = await request.json();
  } catch (e) {
    return jsonResponse(request, { ok: false, step: 'input', error: 'Invalid JSON' }, 400);
  }

  var phone = cleanPhone(input && input.phone);
  if (phone.replace(/[^0-9]/g, '').length < 3) {
    return jsonResponse(request, { ok: false, step: 'input', error: 'Sila masukkan sekurang-kurangnya 3 aksara.', phone: phone }, 400);
  }
  if (!/^\+?[0-9]+$/.test(phone)) {
    return jsonResponse(request, { ok: false, step: 'input', error: 'Phone number can only contain digits', phone: phone }, 200);
  }
  if (phone.length < 3) {
    return jsonResponse(request, { ok: false, step: 'input', error: 'Sila masukkan sekurang-kurangnya 3 aksara.', phone: phone }, 200);
  }
  if (phone.length > 20) {
    return jsonResponse(request, { ok: false, step: 'input', error: 'Phone number is too long', phone: phone }, 200);
  }

  var payload = JSON.stringify({
    data: {
      category: 'telefon',
      bankAccount: '',
      telNo: phone,
      companyName: '',
      captcha: ''
    }
  });

  var result;
  try {
    result = await muleHttp('POST', SEARCH_PATH, payload);
  } catch (err) {
    return jsonResponse(request, { ok: false, step: 'search', error: 'Could not reach semakmule: ' + err.message, phone: phone }, 502);
  }

  if (!result.data) {
    return jsonResponse(request, {
      ok: false,
      step: 'search',
      error: 'semakmule did not return JSON (HTTP ' + result.httpStatus + ')',
      httpStatus: result.httpStatus,
      raw: String(result.raw || '').slice(0, 500),
      phone: phone
    }, 502);
  }

  var data = result.data;
  var success = result.httpStatus >= 200 && result.httpStatus < 300 && data.status === 1;
  var rows = Array.isArray(data.table_data) ? data.table_data : [];
  var headers = Array.isArray(data.table_header) ? data.table_header : [];
  var reports = 0;
  rows.forEach(function (row) { reports += Number(row[1]) || 0; });

  return jsonResponse(request, {
    ok: success,
    code: success ? 'OK' : 'UPSTREAM_REJECTED',
    error: success ? '' : (data.status_message || 'Semak Mule rejected the request.'),
    step: 'result',
    phone: phone,
    keyword: data.kw || phone,
    found: success ? rows.length > 0 : null,
    reports: reports,
    tableHeader: headers,
    tableData: rows,
    count: data.count,
    statusMessage: data.status_message || '',
    httpStatus: result.httpStatus,
    source: data
  }, 200);
}

export default {
  fetch: function (request) {
    return handleRequest(request);
  }
};