feat(api-keys): add api keys management and authentication for n8n workflows
Deploy Canina / deploy (push) Successful in 3m11s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 9s

This commit is contained in:
parsa aghaei committed 2026-09-08 12:57:32 +03:30
1 parent ba9472c938
commit 1fff11ee4f
24 files changed
+158204 -5768

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
import {
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateApiKeyDto } from './dto/api-key.dto';
import * as crypto from 'crypto';
@Injectable()
export class ApiKeysService {
constructor(private readonly prisma: PrismaService) {}
private hashKey(key: string): string {
return crypto.createHash('sha256').update(key).digest('hex');
}
async findAll() {
const keys = await this.prisma.apiKey.findMany({
orderBy: { createdAt: 'desc' },
select: {
id: true,
name: true,
keyPrefix: true,
scopes: true,
status: true,
description: true,
expiresAt: true,
lastUsedAt: true,
createdAt: true,
updatedAt: true,
},
});
return keys.map((k) => ({
...k,
scopes: k.scopes ? k.scopes.split(',').map((s) => s.trim()) : ['*'],
isExpired: k.expiresAt ? new Date(k.expiresAt) < new Date() : false,
}));
}
async create(dto: CreateApiKeyDto) {
// Generate secure random key: cn_live_<32 hex chars>
const randomBytes = crypto.randomBytes(24).toString('hex');
const rawKey = `cn_live_${randomBytes}`;
const keyPrefix = rawKey.substring(0, 12);
const keyHash = this.hashKey(rawKey);
const scopesStr = dto.scopes && dto.scopes.length > 0 ? dto.scopes.join(',') : '*';
const apiKey = await this.prisma.apiKey.create({
data: {
name: dto.name,
keyHash,
keyPrefix,
scopes: scopesStr,
description: dto.description || null,
expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
status: 'ACTIVE',
},
select: {
id: true,
name: true,
keyPrefix: true,
scopes: true,
status: true,
description: true,
expiresAt: true,
createdAt: true,
},
});
return {
apiKey: {
...apiKey,
scopes: apiKey.scopes.split(','),
},
rawKey, // Return raw secret only once upon creation
};
}
async toggleStatus(id: string) {
const key = await this.prisma.apiKey.findUnique({ where: { id } });
if (!key) {
throw new NotFoundException('کلید یافت نشد');
}
const nextStatus = key.status === 'ACTIVE' ? 'REVOKED' : 'ACTIVE';
const updated = await this.prisma.apiKey.update({
where: { id },
data: { status: nextStatus },
select: {
id: true,
name: true,
keyPrefix: true,
scopes: true,
status: true,
expiresAt: true,
},
});
return {
...updated,
scopes: updated.scopes.split(','),
};
}
async delete(id: string) {
const key = await this.prisma.apiKey.findUnique({ where: { id } });
if (!key) {
throw new NotFoundException('کلید یافت نشد');
}
await this.prisma.apiKey.delete({ where: { id } });
return { success: true };
}
async validateKey(rawKey: string) {
if (!rawKey || typeof rawKey !== 'string' || !rawKey.startsWith('cn_live_')) {
throw new UnauthorizedException('API Key نامعتبر است');
}
const keyHash = this.hashKey(rawKey);
const key = await this.prisma.apiKey.findUnique({
where: { keyHash },
});
if (!key) {
throw new UnauthorizedException('API Key یافت نشد یا معتبر نیست');
}
if (key.status !== 'ACTIVE') {
throw new UnauthorizedException('این API Key باطل یا غیرفعال شده است');
}
if (key.expiresAt && new Date(key.expiresAt) < new Date()) {
throw new UnauthorizedException('این API Key منقضی شده است');
}
// Update lastUsedAt asynchronously in background
this.prisma.apiKey
.update({
where: { id: key.id },
data: { lastUsedAt: new Date() },
})
.catch(() => {});
return {
id: key.id,
name: key.name,
role: 'ADMIN', // Grants admin level access for n8n automation
email: 'apikey-system@canina.ir',
scopes: key.scopes.split(',').map((s) => s.trim()),
isApiKey: true,
};
}
}