115 lines
5.3 KiB
JavaScript
115 lines
5.3 KiB
JavaScript
"use strict";
|
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
};
|
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
};
|
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
};
|
|
var AuthService_1;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.AuthService = void 0;
|
|
const common_1 = require("@nestjs/common");
|
|
const typeorm_1 = require("@nestjs/typeorm");
|
|
const typeorm_2 = require("typeorm");
|
|
const crypto_1 = require("crypto");
|
|
const api_key_entity_1 = require("./entities/api-key.entity");
|
|
const tenant_entity_1 = require("./entities/tenant.entity");
|
|
const redis_service_1 = require("../common/redis.service");
|
|
let AuthService = AuthService_1 = class AuthService {
|
|
apiKeyRepository;
|
|
tenantRepository;
|
|
redisService;
|
|
logger = new common_1.Logger(AuthService_1.name);
|
|
constructor(apiKeyRepository, tenantRepository, redisService) {
|
|
this.apiKeyRepository = apiKeyRepository;
|
|
this.tenantRepository = tenantRepository;
|
|
this.redisService = redisService;
|
|
}
|
|
async validateApiKey(key, origin, referer) {
|
|
const cacheKey = `auth:apikey:${key}`;
|
|
const cachedData = await this.redisService.get(cacheKey);
|
|
if (cachedData) {
|
|
this.validateRestrictions(cachedData.apiKey, origin, referer);
|
|
return cachedData;
|
|
}
|
|
const apiKey = await this.apiKeyRepository.findOne({
|
|
where: { key, isActive: true },
|
|
relations: ['tenant'],
|
|
});
|
|
if (!apiKey || !apiKey.tenant || !apiKey.tenant.isActive) {
|
|
throw new common_1.UnauthorizedException('Invalid or inactive API Key');
|
|
}
|
|
this.validateRestrictions(apiKey, origin, referer);
|
|
const result = {
|
|
tenant: apiKey.tenant,
|
|
apiKey: apiKey,
|
|
rateLimit: apiKey.rateLimit || 100,
|
|
};
|
|
await this.redisService.set(cacheKey, result, 3600);
|
|
this.apiKeyRepository.update(apiKey.id, { lastUsedAt: new Date() }).catch(err => this.logger.error(`Failed to update lastUsedAt for API key ${apiKey.id}: ${err.message}`));
|
|
return result;
|
|
}
|
|
validateRestrictions(apiKey, origin, referer) {
|
|
if (apiKey.allowedOrigins && apiKey.allowedOrigins.length > 0) {
|
|
if (!origin || !this.isDomainAllowed(origin, apiKey.allowedOrigins)) {
|
|
this.logger.warn(`Origin mismatch for API key ${apiKey.id}. Received: ${origin}`);
|
|
throw new common_1.UnauthorizedException('Request Origin not allowed for this API Key');
|
|
}
|
|
}
|
|
if (apiKey.allowedReferrers && apiKey.allowedReferrers.length > 0) {
|
|
if (!referer || !this.isDomainAllowed(referer, apiKey.allowedReferrers)) {
|
|
this.logger.warn(`Referer mismatch for API key ${apiKey.id}. Received: ${referer}`);
|
|
throw new common_1.UnauthorizedException('Request Referer not allowed for this API Key');
|
|
}
|
|
}
|
|
}
|
|
isDomainAllowed(domain, allowedList) {
|
|
const cleanDomain = domain.replace(/^https?:\/\//, '').split('/')[0];
|
|
return allowedList.some(allowed => {
|
|
if (allowed === '*')
|
|
return true;
|
|
const regex = new RegExp('^' + allowed.replace(/\*/g, '.*') + '$');
|
|
return regex.test(cleanDomain);
|
|
});
|
|
}
|
|
hashSecret(secret) {
|
|
return (0, crypto_1.createHash)('sha256').update(secret).digest('hex');
|
|
}
|
|
async seedDefaultKey(name, email, keyString) {
|
|
let tenant = await this.tenantRepository.findOne({ where: { email } });
|
|
if (!tenant) {
|
|
tenant = await this.tenantRepository.save({
|
|
name,
|
|
email,
|
|
isActive: true
|
|
});
|
|
}
|
|
const existingKey = await this.apiKeyRepository.findOne({ where: { key: keyString } });
|
|
if (!existingKey) {
|
|
await this.apiKeyRepository.save({
|
|
key: keyString,
|
|
secretHash: this.hashSecret(keyString),
|
|
name: 'Default Production Key',
|
|
isActive: true,
|
|
tenantId: tenant.id,
|
|
rateLimit: 1000
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.AuthService = AuthService;
|
|
exports.AuthService = AuthService = AuthService_1 = __decorate([
|
|
(0, common_1.Injectable)(),
|
|
__param(0, (0, typeorm_1.InjectRepository)(api_key_entity_1.ApiKey)),
|
|
__param(1, (0, typeorm_1.InjectRepository)(tenant_entity_1.Tenant)),
|
|
__metadata("design:paramtypes", [typeorm_2.Repository,
|
|
typeorm_2.Repository,
|
|
redis_service_1.RedisService])
|
|
], AuthService);
|
|
//# sourceMappingURL=auth.service.js.map
|