n8n-nodes-netbox
Version:
n8n community node for NetBox API integration with comprehensive DCIM, IPAM, Virtualization, Circuits, Wireless, and data center management operations
145 lines (144 loc) • 6.19 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiRequest = apiRequest;
exports.apiRequestAllItems = apiRequestAllItems;
const errorHandler_1 = require("./errorHandler");
const https = __importStar(require("https"));
const axios_1 = __importDefault(require("axios"));
/**
* Make an API request to NetBox
*/
async function apiRequest(method, endpoint, body = {}, query = {}, uri) {
const credentials = await this.getCredentials('netBoxApi');
// The URL should NOT have /api/ in it as we add it here
const baseUrl = credentials.url;
// Remove trailing slash if present
const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
// If the endpoint already starts with /api/, don't add it again
const apiEndpoint = endpoint.startsWith('/api/') ? endpoint : `/api${endpoint}`;
const url = uri || `${cleanBaseUrl}${apiEndpoint}`;
// Store original NODE_TLS_REJECT_UNAUTHORIZED value
const originalTLSReject = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
try {
console.log(`🚀 NetBox Node v1.2.4 - Making API request to: ${url}`);
console.log(`Method: ${method.toUpperCase()}`);
console.log(`SSL Verification credential: ${credentials.sslVerify} (type: ${typeof credentials.sslVerify})`);
// Handle SSL certificate bypass using global Node.js setting
const shouldBypassSSL = credentials.sslVerify === false || credentials.sslVerify === 'false' || !credentials.sslVerify;
if (shouldBypassSSL) {
console.log('🔓 GLOBAL SSL BYPASS ACTIVATED - Setting NODE_TLS_REJECT_UNAUTHORIZED=0');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
// Create axios configuration
const axiosConfig = {
method: method.toLowerCase(),
url: url,
headers: {
'Content-Type': 'application/json',
'Authorization': `Token ${credentials.token}`,
'Accept': 'application/json',
},
params: Object.keys(query).length > 0 ? query : undefined,
timeout: 30000,
};
// Add body for methods that support it
if (['POST', 'PUT', 'PATCH'].includes(method.toUpperCase()) && Object.keys(body).length > 0) {
axiosConfig.data = body;
console.log('Request body:', JSON.stringify(body, null, 2));
}
// Additional SSL bypass using HTTPS agent as backup
if (shouldBypassSSL) {
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
requestCert: false,
checkServerIdentity: () => undefined,
});
axiosConfig.httpsAgent = httpsAgent;
}
console.log('📋 Request config:', {
method: axiosConfig.method,
url: axiosConfig.url,
sslBypassActive: shouldBypassSSL,
nodeEnvBypass: process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0',
hasHTTPSAgent: !!axiosConfig.httpsAgent,
});
const response = await (0, axios_1.default)(axiosConfig);
console.log(`✅ API request successful, status: ${response.status}`);
return response.data;
}
catch (error) {
console.log('💥 API Request Error:', error);
console.log('Error code:', error.code);
console.log('Error message:', error.message);
throw (0, errorHandler_1.handleApiError)(error, endpoint);
}
finally {
// Restore original NODE_TLS_REJECT_UNAUTHORIZED setting
if (originalTLSReject !== undefined) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = originalTLSReject;
console.log(`🔄 Restored NODE_TLS_REJECT_UNAUTHORIZED to: ${originalTLSReject}`);
}
else {
delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
console.log('🔄 Removed NODE_TLS_REJECT_UNAUTHORIZED environment variable');
}
}
}
/**
* Make paginated requests to NetBox API and return all results
*/
async function apiRequestAllItems(method, endpoint, body = {}, query = {}) {
const returnData = [];
let responseData = {};
let uri;
do {
if (uri) {
// Use full next URI as-is, without body/query
responseData = await apiRequest.call(this, method, endpoint, {}, {}, uri);
}
else {
responseData = await apiRequest.call(this, method, endpoint, body, query);
}
uri = responseData.next;
if (responseData.results) {
returnData.push(...responseData.results);
}
} while (uri);
return returnData;
}