@dataunlocker/defender
Version:
DataUnlocker core module that protects your web app's analytics.
63 lines (62 loc) • 2.49 kB
JavaScript
import { access } from 'node:fs/promises';
import { getEnv } from './env.js';
import { fatalError } from './logs.js';
export const isFileExists = async (file) => {
try {
await access(file);
return true;
}
catch (e) {
return false;
}
};
export const isValidEndpoint = (endpoint) => {
if (!endpoint || endpoint.endsWith('/')) {
return false;
}
try {
new URL(`https://${endpoint}`);
return true;
}
catch (e) {
return false;
}
};
const DATAUNLOCKER_ID = await getEnv('DATAUNLOCKER_ID');
const _DATAUNLOCKER_ENV = await getEnv('DATAUNLOCKER_ENV');
const DATAUNLOCKER_ENV = _DATAUNLOCKER_ENV === 'prod' || _DATAUNLOCKER_ENV === 'production'
? ''
: _DATAUNLOCKER_ENV;
let ENDPOINT = await getEnv('DATAUNLOCKER_ENDPOINT'); // Format: "endpoint.example.com/example" (prefix)
const HOST_API = `api${DATAUNLOCKER_ENV && `.${DATAUNLOCKER_ENV}`}.dataunlocker.com`;
export const fetchModule = async () => {
if (!DATAUNLOCKER_ID) {
fatalError(`DATAUNLOCKER_ID is not specified. Please, set DATAUNLOCKER_ID environment variable or add it to .dataunlocker.json file before installing dependencies.\nSee https://docs.dataunlocker.com/setup/defender/install for more info.`);
}
if (ENDPOINT && !isValidEndpoint(ENDPOINT)) {
fatalError(`DATAUNLOCKER_ENDPOINT is invalid ("${ENDPOINT}").`);
}
const url = `https://${HOST_API}/domains/${DATAUNLOCKER_ID}/defender/module${ENDPOINT ? `endpoint=${encodeURIComponent(ENDPOINT)}` : ''}`;
let res;
let _data;
try {
res = await fetch(url);
_data = await res.json();
}
catch (e) {
fatalError(`Unable to fetch DataUnlocker's proxy endpoints from ${url}, ${e.message || e}`);
}
const data = _data;
if ('errorCode' in data) {
if (data.errorCode === 'ENDPOINT_NOT_HEALTHY') {
fatalError(`None of domain's transport endpoints are healthy! Domain's endpoints:\n${data.errorData.endpoints.map((e) => ` • ${e.endpoint} (${e.isHealthy ? 'healthy' : 'not healthy'})`).join('\n') || ' • (no endpoints)'}`);
}
else {
fatalError(`Unable to fetch ${url}, ${data.error} (${data.errorCode})${data.errorData ? ` ${JSON.stringify(data.errorData)}` : ''}`);
}
}
else if (!('files' in data)) {
fatalError(`Unexpected response from ${url}, ${JSON.stringify(data || null)}`);
}
return data; // Dumb TypeScript
};