@spot-meetings/utils
Version:
Spot's utility functions.
68 lines (67 loc) • 2.3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInstanceIp = exports.getPublicIp = exports.getAwsIp = exports.getContainerIp = exports.validateIpV4 = exports.IpType = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
const os_1 = __importDefault(require("os"));
var IpType;
(function (IpType) {
IpType["Public"] = "public";
IpType["Local"] = "local";
})(IpType = exports.IpType || (exports.IpType = {}));
const validateIpV4 = (ip) => /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/.test(ip);
exports.validateIpV4 = validateIpV4;
const getContainerIp = () => {
const [address] = Object.values(os_1.default.networkInterfaces())
.flat()
.filter(({ family, internal }) => family === 'IPv4' && !internal)
.map(({ address }) => address);
return address;
};
exports.getContainerIp = getContainerIp;
const getAwsIp = async (type = IpType.Local) => {
let ip;
const response = await node_fetch_1.default(`http://169.254.169.254/latest/meta-data/${type}-ipv4`, {
method: 'GET',
});
const body = await response.text();
if (exports.validateIpV4(body.trim())) {
ip = body.trim();
}
return ip;
};
exports.getAwsIp = getAwsIp;
const getPublicIp = async () => {
let ip;
const response = await node_fetch_1.default('http://checkip.amazonaws.com/', {
method: 'GET',
});
const body = await response.text();
if (exports.validateIpV4(body.trim())) {
ip = body.trim();
}
return ip;
};
exports.getPublicIp = getPublicIp;
const getInstanceIp = async (type = IpType.Local) => {
let ip;
if (type === IpType.Local) {
ip = await exports.getContainerIp();
}
else if (process.env.AWS_ENV) {
ip = await exports.getAwsIp(type); // node or public
}
else if (type === IpType.Public) {
ip = await exports.getPublicIp();
}
if (ip) {
ip = ip.trim();
}
if (!exports.validateIpV4(ip)) {
throw new Error(`IP "${ip}" is invalid`);
}
return ip;
};
exports.getInstanceIp = getInstanceIp;