token-discord-checker
Version:
A comprehensive Discord token validation and verification tool
232 lines • 8.55 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiscordTokenChecker = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const dotenv_1 = require("dotenv");
const format_validator_1 = require("./validators/format-validator");
const api_validator_1 = require("./validators/api-validator");
const token_types_1 = require("./types/token.types");
/**
* Main Discord Token Checker class
* Provides comprehensive token validation functionality
*/
class DiscordTokenChecker {
constructor(config = {}) {
const DEFAULT_USER_AGENT = 'DiscordTokenChecker/1.0.0';
this.config = {
checkApi: config.checkApi ?? true,
timeout: config.timeout ?? 10000,
includeUserInfo: config.includeUserInfo ?? true,
validateFormat: config.validateFormat ?? true,
userAgent: config.userAgent ?? DEFAULT_USER_AGENT,
};
}
/**
* Validate token from environment variable
* @param options - Environment validation options
* @returns Validation result
*/
async validateFromEnv(options = {}) {
const envPath = options.envPath || path_1.default.join(process.cwd(), '.env');
const tokenVar = options.tokenVar || 'DISCORD_TOKEN';
// Load environment variables
(0, dotenv_1.config)({ path: envPath });
// Check if .env file exists
if (!fs_1.default.existsSync(envPath)) {
throw new token_types_1.TokenValidationError(`.env file not found at ${envPath}`, token_types_1.TokenErrorType.FILE_NOT_FOUND);
}
// Get token from environment
const token = process.env[tokenVar];
if (!token) {
throw new token_types_1.TokenValidationError(`${tokenVar} not found in environment variables`, token_types_1.TokenErrorType.TOKEN_NOT_FOUND);
}
// Validate the token
const result = await this.validateToken(token, 'env');
return result;
}
/**
* Validate token from file
* @param options - File validation options
* @returns Validation result
*/
async validateFromFile(options) {
const { filePath, cleanup = false } = options;
// Check if file exists
if (!fs_1.default.existsSync(filePath)) {
throw new token_types_1.TokenValidationError(`Token file not found at ${filePath}`, token_types_1.TokenErrorType.FILE_NOT_FOUND);
}
try {
// Read token from file
const token = fs_1.default.readFileSync(filePath, 'utf8').trim();
if (!token) {
throw new token_types_1.TokenValidationError('Token file is empty', token_types_1.TokenErrorType.TOKEN_NOT_FOUND);
}
// Validate the token
const result = await this.validateToken(token, 'file');
// Clean up file if requested
if (cleanup) {
try {
fs_1.default.unlinkSync(filePath);
}
catch (cleanupError) {
// Add warning about cleanup failure
result.warnings.push(`Failed to clean up file: ${cleanupError}`);
}
}
return result;
}
catch (error) {
if (error instanceof token_types_1.TokenValidationError) {
throw error;
}
throw new token_types_1.TokenValidationError(`Failed to read token file: ${error}`, token_types_1.TokenErrorType.FILE_NOT_FOUND, { originalError: error });
}
}
/**
* Validate token directly
* @param token - The token to validate
* @param method - Validation method to use
* @returns Validation result
*/
async validateDirect(token, method = 'both') {
return this.validateToken(token, 'direct', method);
}
/**
* Internal token validation method
* @param token - The token to validate
* @param source - Token source
* @param method - Validation method
* @returns Validation result
*/
async validateToken(token, source, method = 'both') {
let result;
// Start with format validation
if (method === 'format' || method === 'both') {
result = format_validator_1.FormatValidator.validateFormat(token);
result.metadata.source = source;
// If format validation fails and we're only doing format validation, return early
if (!result.isValid && method === 'format') {
return result;
}
}
else {
// Create minimal result for API-only validation
result = {
isValid: true,
format: {
hasCorrectParts: true,
hasCorrectLength: true,
hasNoSpaces: true,
hasNoQuotes: true,
isNotBotToken: true,
},
errors: [],
warnings: [],
metadata: {
length: token.length,
parts: token.split('.').length,
source,
},
};
}
// Perform API validation if requested
if ((method === 'api' || method === 'both') && this.config.checkApi) {
try {
const apiResult = await api_validator_1.ApiValidator.validateWithApi(token, this.config);
const apiInfo = {
isActive: apiResult.success,
};
if (apiResult.userInfo) {
apiInfo.userInfo = apiResult.userInfo;
}
if (apiResult.error) {
apiInfo.error = apiResult.error;
}
result.api = apiInfo;
// If API validation fails, mark overall result as invalid
if (!apiResult.success) {
result.isValid = false;
if (apiResult.error) {
result.errors.push(`API validation failed: ${apiResult.error}`);
}
}
}
catch (error) {
result.api = {
isActive: false,
error: error instanceof Error ? error.message : 'Unknown API error',
};
result.isValid = false;
result.errors.push(`API validation error: ${result.api.error}`);
}
}
return result;
}
/**
* Quick token test (format only)
* @param token - The token to test
* @returns Simple boolean result
*/
static quickFormatCheck(token) {
try {
const result = format_validator_1.FormatValidator.validateFormat(token);
return result.isValid;
}
catch {
return false;
}
}
/**
* Quick API test
* @param token - The token to test
* @param timeout - Request timeout
* @returns Simple validation result
*/
static async quickApiCheck(token, timeout = 5000) {
return api_validator_1.ApiValidator.quickTest(token, timeout);
}
/**
* Extract user ID from token
* @param token - The token
* @returns User ID or null
*/
static extractUserId(token) {
return format_validator_1.FormatValidator.extractUserId(token);
}
/**
* Extract timestamp from token
* @param token - The token
* @returns Timestamp or null
*/
static extractTimestamp(token) {
return format_validator_1.FormatValidator.extractTimestamp(token);
}
/**
* Create a new token checker instance with custom config
* @param config - Custom configuration
* @returns New token checker instance
*/
static create(config = {}) {
return new DiscordTokenChecker(config);
}
/**
* Update checker configuration
* @param config - New configuration options
*/
updateConfig(config) {
this.config = { ...this.config, ...config };
}
/**
* Get current configuration
* @returns Current configuration
*/
getConfig() {
return { ...this.config };
}
}
exports.DiscordTokenChecker = DiscordTokenChecker;
//# sourceMappingURL=token-checker.js.map