Skip to content

Commit

Permalink
Adds API endpoints for native whois lookup on domain
Browse files Browse the repository at this point in the history
  • Loading branch information
Lissy93 committed Jul 17, 2023
1 parent 20aaa77 commit c9cdd93
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
5 changes: 5 additions & 0 deletions netlify.toml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@
to = "/.netlify/functions/check-hsts"
status = 301
force = true
[[redirects]]
from = "/whois-lookup"
to = "/.netlify/functions/whois-lookup"
status = 301
force = true

# For router history mode, ensure pages land on index
[[redirects]]
Expand Down
96 changes: 96 additions & 0 deletions server/lambda/whois-lookup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const net = require('net');
const { URL } = require('url');

exports.handler = async function(event, context) {
let url = event.queryStringParameters.url;

if (!url) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'A url query parameter is required' }),
};
}

if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'http://' + url;
}

let hostname;
try {
hostname = new URL(url).hostname;
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'Invalid url provided' }),
};
}

return new Promise((resolve, reject) => {
const client = net.createConnection({ port: 43, host: 'whois.internic.net' }, () => {
client.write(hostname + '\r\n');
});

let data = '';
client.on('data', (chunk) => {
data += chunk;
});

client.on('end', () => {
try {
const parsedData = parseWhoisData(data);
resolve({
statusCode: 200,
body: JSON.stringify(parsedData),
});
} catch (error) {
resolve({
statusCode: 500,
body: JSON.stringify({ error: error.message }),
});
}
});

client.on('error', (err) => {
resolve({
statusCode: 500,
body: JSON.stringify({ message: err.message }),
});
});
});
};

const parseWhoisData = (data) => {
const lines = data.split('\r\n');
const parsedData = {};

let lastKey = '';

for (const line of lines) {
const index = line.indexOf(':');

// If this line is a continuation of the previous line
if (index === -1) {
if (lastKey !== '') {
parsedData[lastKey] += ' ' + line.trim();
}
continue;
}

let key = line.slice(0, index).trim();
const value = line.slice(index + 1).trim();

// Ignore lines that are not key-value pairs
if (value.length === 0) continue;

// Convert keys to format without spaces or special characters
key = key.replace(/\W+/g, '_');

// Store the key to handle multi-line values
lastKey = key;

parsedData[key] = value;
}

return parsedData;
};

0 comments on commit c9cdd93

Please sign in to comment.