2026-04-14-8 auth and commercial

This commit is contained in:
Hamza-Ayed
2026-04-14 20:14:48 +03:00
parent be7dcc2652
commit f5b3f9f790
430 changed files with 6074 additions and 751 deletions
+7 -1
View File
@@ -5,6 +5,8 @@ import { ScheduleModule } from '@nestjs/schedule';
import { TelemetryModule } from './telemetry/telemetry.module';
import { MapsModule } from './maps/maps.module';
import { GeocodingModule } from './geocoding/geocoding.module';
import { AuthModule } from './auth/auth.module';
import { ThrottlerModule } from '@nestjs/throttler';
@Module({
imports: [
@@ -20,9 +22,13 @@ import { GeocodingModule } from './geocoding/geocoding.module';
url: config.get('DATABASE_URL'),
autoLoadEntities: true,
synchronize: true, // Only for prototype! Use migrations for production.
// synchronize: true, // للمعاينة فقط؛ يفضل استخدام migrations للإنتاج
}),
}),
ThrottlerModule.forRoot([{
ttl: 60,
limit: 10, // Default fallback limit
}]),
AuthModule,
TelemetryModule,
MapsModule,
GeocodingModule,
+35
View File
@@ -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');
}
}
}
+127
View File
@@ -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[];
}
+30 -11
View File
@@ -4,23 +4,42 @@ import {
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AuthService } from '../../auth/auth.service';
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private configService: ConfigService) {}
constructor(private authService: AuthService) {}
canActivate(context: ExecutionContext): boolean {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const apiKeyHeader = request.headers['x-api-key'];
const validApiKey = this.configService.get<string>('MAP_API_KEY') || 'intaleq_premium_saas_2026_secure_key_x';
// Enforce API key match
if (apiKeyHeader !== validApiKey) {
console.error(`[ApiKeyGuard] Unauthorized. Expected: ${validApiKey}, Received: ${apiKeyHeader}`);
throw new UnauthorizedException('Invalid or missing API Key');
// Extract API key from custom header
const apiKeyHeader = request.headers['x-api-key'] || request.query['api_key'];
if (!apiKeyHeader) {
throw new UnauthorizedException('API Key (x-api-key) is missing');
}
return true;
// Extract Origin and Referer for domain-level security
const origin = request.headers['origin'];
const referer = request.headers['referer'];
try {
// Validate key via AuthService (includes Redis caching and domain checks)
const { tenant, apiKey, rateLimit } = await this.authService.validateApiKey(
apiKeyHeader,
origin,
referer,
);
// Attach tenant info to request for downstream controllers and rate limiters
request['tenant'] = tenant;
request['apiKey'] = apiKey;
request['rateLimit'] = rateLimit;
return true;
} catch (error) {
throw new UnauthorizedException(error.message || 'Invalid API Key');
}
}
}
@@ -0,0 +1,34 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { ThrottlerGuard, ThrottlerRequest } from '@nestjs/throttler';
@Injectable()
export class TenantThrottlerGuard extends ThrottlerGuard {
/**
* Resolve per-tenant and per-key rate limits dynamically
* تحديد حدود الاستخدام لكل مستخدم (Tenant) بشكل ديناميكي
*/
protected async getTracker(req: Record<string, any>): Promise<string> {
// Collect tracker info from the request (attached by ApiKeyGuard)
const apiKeyId = req['apiKey']?.id || req.ip;
return `throttler:key:${apiKeyId}`;
}
/**
* NestJS Throttler v6+: Override handleRequest to inject dynamic limits
*/
protected async handleRequest(
requestProps: ThrottlerRequest,
): Promise<boolean> {
const { context, limit } = requestProps;
const request = context.switchToHttp().getRequest();
// Read dynamic limit from request metadata (set in ApiKeyGuard)
const dynamicLimit = request['rateLimit'] || limit;
// Update the limit in the request properties before passing to super
requestProps.limit = dynamicLimit;
// Proceed with standard throttler logic
return super.handleRequest(requestProps);
}
}
@@ -0,0 +1,21 @@
import { IsNumber, IsNotEmpty, Min, Max } from 'class-validator';
import { Type } from 'class-transformer';
import { ApiProperty } from '@nestjs/swagger';
export class ReverseGeocodeDto {
@IsNotEmpty()
@IsNumber()
@Min(-90)
@Max(90)
@Type(() => Number)
@ApiProperty({ description: 'Latitude' })
lat: number;
@IsNotEmpty()
@IsNumber()
@Min(-180)
@Max(180)
@Type(() => Number)
@ApiProperty({ description: 'Longitude' })
lng: number;
}
@@ -0,0 +1,34 @@
import { IsString, IsNumber, IsOptional, IsEnum, Min, Max } from 'class-validator';
import { Type } from 'class-transformer';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class SearchQueryDto {
@IsString()
@ApiPropertyOptional({ description: 'Search query string' })
q: string;
@IsOptional()
@IsNumber()
@Type(() => Number)
@ApiPropertyOptional({ description: 'Latitude for proximity search' })
lat?: number;
@IsOptional()
@IsNumber()
@Type(() => Number)
@ApiPropertyOptional({ description: 'Longitude for proximity search' })
lng?: number;
@IsOptional()
@IsNumber()
@Min(0)
@Max(50000)
@Type(() => Number)
@ApiPropertyOptional({ description: 'Proximity radius in meters', default: 20000 })
radius?: number = 20000;
@IsOptional()
@IsEnum(['jordan', 'syria', 'egypt'])
@ApiPropertyOptional({ description: 'Country filter', enum: ['jordan', 'syria', 'egypt'] })
country?: string;
}
+14 -38
View File
@@ -1,14 +1,18 @@
import { Controller, Get, Post, Delete, Body, Query, UseGuards, HttpException, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { ApiTags, ApiOperation, ApiQuery, ApiHeader } from '@nestjs/swagger';
import { GeocodingService } from './geocoding.service';
import { AdminBoundariesService } from './admin-boundaries.service';
import { JordanResearchService } from './jordan-research.service';
import { AdministrativeLinkingService } from './administrative-linking.service';
import { ApiKeyGuard } from '../common/guards/api-key.guard';
import { TenantThrottlerGuard } from '../common/guards/rate-limiter.guard';
import { SearchQueryDto } from './dto/search-query.dto';
import { ReverseGeocodeDto } from './dto/reverse-geocode.dto';
@ApiTags('geocoding')
@ApiHeader({ name: 'x-api-key', description: 'Multi-tenant API Key', required: true })
@Controller('geocoding')
@UseGuards(ApiKeyGuard)
@UseGuards(ApiKeyGuard, TenantThrottlerGuard)
export class GeocodingController {
constructor(
private readonly geocodingService: GeocodingService,
@@ -19,46 +23,18 @@ export class GeocodingController {
@Get('search')
@ApiOperation({ summary: 'Search for locations (Forward Geocoding)' })
@ApiQuery({ name: 'q', required: true })
@ApiQuery({ name: 'lat', required: false, type: Number })
@ApiQuery({ name: 'lng', required: false, type: Number })
@ApiQuery({ name: 'radius', required: false, type: Number })
@ApiQuery({ name: 'country', required: false, enum: ['jordan', 'syria', 'egypt'] })
async search(
@Query('q') query: string,
@Query('lat') lat?: string,
@Query('lng') lng?: string,
@Query('radius') radius?: string,
@Query('country') country?: string,
) {
// NestJS @Query() always receives strings — must parse explicitly for numeric types
const parsedLat = lat !== undefined ? parseFloat(lat) : Number.NaN;
const parsedLng = lng !== undefined ? parseFloat(lng) : Number.NaN;
const parsedRadius = radius !== undefined ? parseFloat(radius) : 20000;
// Guard against malformed float values (NaN breaks PostGIS)
const safeLat = !isNaN(parsedLat) ? parsedLat : undefined;
const safeLng = !isNaN(parsedLng) ? parsedLng : undefined;
return this.geocodingService.searchPlaces(query, safeLat, safeLng, parsedRadius, country);
async search(@Query() queryDto: SearchQueryDto) {
const { q, lat, lng, radius, country } = queryDto;
// ValidationPipe with { transform: true } handles numeric conversion and defaults
return this.geocodingService.searchPlaces(q, lat, lng, radius, country);
}
@Get('reverse')
@ApiOperation({ summary: 'Reverse Geocoding (Lat/Lng to Address)' })
@ApiQuery({ name: 'lat', required: true })
@ApiQuery({ name: 'lng', required: true })
async reverse(
@Query('lat') lat: string,
@Query('lng') lng: string,
) {
const parsedLat = parseFloat(lat);
const parsedLng = parseFloat(lng);
if (isNaN(parsedLat) || isNaN(parsedLng)) {
throw new HttpException('Invalid lat/lng values', HttpStatus.BAD_REQUEST);
}
return this.geocodingService.reverseGeocode(parsedLat, parsedLng);
async reverse(@Query() reverseDto: ReverseGeocodeDto) {
const { lat, lng } = reverseDto;
return this.geocodingService.reverseGeocode(lat, lng);
}
@Post('places')
+18 -5
View File
@@ -1,24 +1,37 @@
import { NestFactory } from '@nestjs/core';
import { NestFactory, Reflector } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import helmet from 'helmet';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Enable CORS for frontend
// تفعيل تبادل الموارد مع الواجهة الأمامية
// 1. Modern Security Headers (Prevention of XSS, Clickjacking, etc.)
app.use(helmet());
// 2. Enable CORS with specific defaults (can be refined via Tenant settings)
app.enableCors();
// Set global API prefix
// 3. Global API prefix
app.setGlobalPrefix('api');
// 4. Global Validation Pipeline (Robust input validation)
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // Strip non-decorated properties
forbidNonWhitelisted: true, // Error on unknown properties
transform: true, // Automatically transform payloads to DTO instances
}));
// Swagger Documentation Setup
const config = new DocumentBuilder()
.setTitle('Jordan Map Platform API')
.setDescription('Backend API for map services, routing, and driver telemetry for Jordan')
.setVersion('1.0')
.addApiKey({ type: 'apiKey', name: 'x-api-key', in: 'header' }, 'x-api-key')
.addTag('maps')
.addTag('telemetry') // Corrected line to add 'telemetry' tag
.addTag('geocoding')
.addTag('telemetry')
.build();
const document = SwaggerModule.createDocument(app, config);