2026-04-14-8 auth and commercial
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { Module, Global, OnModuleInit } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthService } from './auth.service';
|
||||
import { Tenant } from './entities/tenant.entity';
|
||||
import { ApiKey } from './entities/api-key.entity';
|
||||
import { RedisModule } from '../common/redis.module';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Tenant, ApiKey]),
|
||||
RedisModule,
|
||||
],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule implements OnModuleInit {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Seed the default API key from environment to prevent breaking current integrations.
|
||||
* دمج مفتاح الأمان الافتراضي من الإعدادات لمنع توقف الرقابة الحالية
|
||||
*/
|
||||
async onModuleInit() {
|
||||
const defaultKey = this.configService.get<string>('MAP_API_KEY');
|
||||
if (defaultKey) {
|
||||
await this.authService.seedDefaultKey('Default System', 'admin@intaleq.xyz', defaultKey);
|
||||
console.log('✅ Default System API Key seeded successfully');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { createHash } from 'crypto';
|
||||
import { ApiKey } from './entities/api-key.entity';
|
||||
import { Tenant } from './entities/tenant.entity';
|
||||
import { RedisService } from '../common/redis.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ApiKey)
|
||||
private readonly apiKeyRepository: Repository<ApiKey>,
|
||||
@InjectRepository(Tenant)
|
||||
private readonly tenantRepository: Repository<Tenant>,
|
||||
private readonly redisService: RedisService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Validate an API key and check its restrictions (Origin/Referer).
|
||||
* التحقق من سلامة مفتاح الأمان والقيود المفروضة عليه
|
||||
*/
|
||||
async validateApiKey(key: string, origin?: string, referer?: string): Promise<{ tenant: Tenant; apiKey: ApiKey; rateLimit: number }> {
|
||||
// 1. Check Redis Cache first
|
||||
const cacheKey = `auth:apikey:${key}`;
|
||||
const cachedData = await this.redisService.get<{ tenant: Tenant; apiKey: ApiKey; rateLimit: number }>(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
this.validateRestrictions(cachedData.apiKey, origin, referer);
|
||||
return cachedData;
|
||||
}
|
||||
|
||||
// 2. Database Lookup
|
||||
const apiKey = await this.apiKeyRepository.findOne({
|
||||
where: { key, isActive: true },
|
||||
relations: ['tenant'],
|
||||
});
|
||||
|
||||
if (!apiKey || !apiKey.tenant || !apiKey.tenant.isActive) {
|
||||
throw new UnauthorizedException('Invalid or inactive API Key');
|
||||
}
|
||||
|
||||
// 3. Advanced Security Checks (Domain & Referer)
|
||||
this.validateRestrictions(apiKey, origin, referer);
|
||||
|
||||
const result = {
|
||||
tenant: apiKey.tenant,
|
||||
apiKey: apiKey,
|
||||
rateLimit: apiKey.rateLimit || 100, // Default 100 req/min
|
||||
};
|
||||
|
||||
// 4. Update Cache (TTL 1 hour)
|
||||
await this.redisService.set(cacheKey, result, 3600);
|
||||
|
||||
// 5. Update lastUsedAt asynchronously
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Domain-level security validation
|
||||
*/
|
||||
private validateRestrictions(apiKey: ApiKey, origin?: string, referer?: string): void {
|
||||
// Check Allowed Origins
|
||||
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 UnauthorizedException('Request Origin not allowed for this API Key');
|
||||
}
|
||||
}
|
||||
|
||||
// Check Allowed Referrers
|
||||
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 UnauthorizedException('Request Referer not allowed for this API Key');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private isDomainAllowed(domain: string, allowedList: string[]): boolean {
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to hash secrets (used during creation)
|
||||
*/
|
||||
hashSecret(secret: string): string {
|
||||
return createHash('sha256').update(secret).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal seeding helper to create a default tenant/key
|
||||
*/
|
||||
async seedDefaultKey(name: string, email: string, keyString: string): Promise<void> {
|
||||
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), // Pre-emptive hashing
|
||||
name: 'Default Production Key',
|
||||
isActive: true,
|
||||
tenantId: tenant.id,
|
||||
rateLimit: 1000 // High limit for default key
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, Index } from 'typeorm';
|
||||
import { Tenant } from './tenant.entity';
|
||||
|
||||
@Entity('api_keys')
|
||||
export class ApiKey {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ unique: true })
|
||||
@Index()
|
||||
key: string; // The masked/public key (e.g., is_live_...)
|
||||
|
||||
@Column()
|
||||
secretHash: string; // Hashed version for validation
|
||||
|
||||
@Column()
|
||||
name: string; // e.g., "Mobile App", "Production"
|
||||
|
||||
@Column({ default: true })
|
||||
isActive: boolean;
|
||||
|
||||
@Column({ nullable: true })
|
||||
rateLimit: number; // Requests per minute, overrides tenant default
|
||||
|
||||
@Column('simple-array', { nullable: true })
|
||||
allowedOrigins: string[];
|
||||
|
||||
@Column('simple-array', { nullable: true })
|
||||
allowedReferrers: string[];
|
||||
|
||||
@ManyToOne(() => Tenant, (tenant) => tenant.apiKeys)
|
||||
tenant: Tenant;
|
||||
|
||||
@Column()
|
||||
tenantId: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
lastUsedAt: Date;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
|
||||
import { ApiKey } from './api-key.entity';
|
||||
|
||||
export enum TenantPlan {
|
||||
FREE = 'FREE',
|
||||
PREMIUM = 'PREMIUM',
|
||||
ENTERPRISE = 'ENTERPRISE',
|
||||
}
|
||||
|
||||
@Entity('tenants')
|
||||
export class Tenant {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Column({ unique: true })
|
||||
email: string;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: TenantPlan,
|
||||
default: TenantPlan.FREE,
|
||||
})
|
||||
plan: TenantPlan;
|
||||
|
||||
@Column({ default: true })
|
||||
isActive: boolean;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
@OneToMany(() => ApiKey, (apiKey) => apiKey.tenant)
|
||||
apiKeys: ApiKey[];
|
||||
}
|
||||
Reference in New Issue
Block a user