All files / src/sso/client misc.ts

82.86% Statements 29/35
75% Branches 9/12
100% Functions 3/3
82.86% Lines 29/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 641x 1x 1x   1x   1x                       1x 12x 12x       12x 12x 12x 1x   11x 11x 6x     5x     5x 5x 5x 5x               5x   5x 5x 5x     1x 1x 1x     1x 5x    
import dns from 'dns';
import dbg from 'debug';
import crypto from 'crypto';
 
import { sysinfo } from '../../../lib/api';
 
const debug = dbg('node-expose-sspi:client');
 
/**
 * Get the SPN the same way Chrome/Firefox or IE does.
 *
 * Links:
 * - getting the domain name: https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string
 * - algo of IE : https://support.microsoft.com/en-us/help/4551934/kerberos-failures-in-internet-explorer
 *
 * @param {string} url
 * @returns {string}
 */
export async function getSPNFromURI(url: string): Promise<string> {
  const msDomainName = sysinfo.GetComputerNameEx('ComputerNameDnsDomain');
  Iif (msDomainName.length === 0) {
    debug('Client running on a host that is not part of a Microsoft domain');
    return 'whatever';
  }
  const matches = /^https?:\/\/([^/:?#]+)(?:[/:?#]|$)/i.exec(url);
  const urlDomain = matches && matches[1];
  if (!urlDomain) {
    throw new Error('url is not well parsed. url=' + url);
  }
  debug('urlDomain: ', urlDomain);
  if (['localhost', '127.0.0.1'].includes(urlDomain)) {
    return 'HTTP/localhost';
  }
  // needs urlFQDN for the DNS resolver.
  const urlFQDN = urlDomain.includes('.')
    ? urlDomain
    : urlDomain + '.' + msDomainName;
  let hostname = urlFQDN;
  try {
    while (true) {
      const records = await dns.promises.resolve(hostname, 'CNAME');
      debug('records', records);
      if (records.length === 0) {
        break;
      }
      hostname = records[0];
    }
  } catch (e) {
    debug('DNS error', e);
  }
  const result = 'HTTP/' + hostname;
  debug('result: ', result);
  return result;
}
 
export function encodeBase64(str: string) {
  const buff = Buffer.from(str);
  return buff.toString('base64');
}
 
export function md5(str: string) {
  return crypto.createHash('md5').update(str).digest('hex');
}