Files
api/src/auth/remote-sms-auth.guard.ts
T

253 lines
6.9 KiB
TypeScript
Raw Normal View History

import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHmac, timingSafeEqual } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
const MAX_SKEW_SECONDS = 300;
type TenantHostRow = {
id: string;
nameFa: string;
domain: string | null;
domains: unknown;
adminUrl?: string | null;
appUrl?: string | null;
nodeServer?: string | null;
product: string;
isActive: boolean;
};
/**
* Auth for product → SuperAdmin SMS / plugin-store:
* 1) Preferred: shared HMAC + domain headers
* 2) Fallback: Authorization Bearer {Tenant.remoteApiToken}
*/
@Injectable()
export class RemoteSmsAuthGuard implements CanActivate {
constructor(
private readonly prisma: PrismaService,
private readonly config: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
const shared = String(
this.config.get<string>('SMS_REMOTE_SHARED_SECRET') || '',
).trim();
const domainHeader = String(
req.headers['x-abshode-domain'] || '',
).trim();
const tsHeader = String(
req.headers['x-abshode-timestamp'] || '',
).trim();
const sigHeader = String(
req.headers['x-abshode-signature'] || '',
).trim();
if (shared && domainHeader && tsHeader && sigHeader) {
req.remoteTenant = await this.authByHmac(
req,
shared,
domainHeader,
tsHeader,
sigHeader,
);
return true;
}
const bearerTenant = await this.authByBearer(req);
if (bearerTenant) {
req.remoteTenant = bearerTenant;
return true;
}
throw new UnauthorizedException(
'احراز هویت ریموت نامعتبر است (HMAC دامنه یا Bearer توکن)',
);
}
private async authByHmac(
req: any,
sharedSecret: string,
domainRaw: string,
tsRaw: string,
sigRaw: string,
) {
const timestamp = Number(tsRaw);
if (!Number.isFinite(timestamp)) {
throw new UnauthorizedException('timestamp نامعتبر است');
}
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - timestamp) > MAX_SKEW_SECONDS) {
throw new UnauthorizedException('timestamp منقضی است');
}
const domain = this.normalizeHost(domainRaw);
if (!domain) {
throw new UnauthorizedException('دامنه نامعتبر است');
}
const method = String(req.method || 'GET').toUpperCase();
const pathOnly = String(req.originalUrl || req.url || '')
.split('?')[0]
.replace(/\/+$/, '');
const canonicalPath = pathOnly.startsWith('/api/')
? pathOnly
: pathOnly.startsWith('/remote/')
? `/api${pathOnly}`
: pathOnly || '/api/remote/sms/status';
const payload = `${timestamp}.${method}.${canonicalPath}.${domain}`;
const expected = createHmac('sha256', sharedSecret)
.update(payload, 'utf8')
.digest('hex');
if (!this.equalHex(expected, sigRaw)) {
throw new UnauthorizedException('امضای درخواست نامعتبر است');
}
const tenant = await this.findTenantByDomain(domain);
if (!tenant) {
throw new UnauthorizedException('نسخه‌ای با این دامنه یافت نشد');
}
return tenant;
}
private async authByBearer(req: any) {
const header = String(req.headers?.authorization || '');
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
const token = match?.[1]?.trim();
if (!token || token.length < 16) return null;
return this.prisma.tenant.findFirst({
where: { remoteApiToken: token, isActive: true },
select: {
id: true,
nameFa: true,
domain: true,
product: true,
isActive: true,
},
});
}
private async findTenantByDomain(host: string) {
const normalizedHost = this.normalizeHost(host);
if (!normalizedHost) return null;
const tenants = await this.prisma.tenant.findMany({
where: { isActive: true },
select: {
id: true,
nameFa: true,
domain: true,
domains: true,
adminUrl: true,
appUrl: true,
nodeServer: true,
product: true,
isActive: true,
},
});
let best: { row: TenantHostRow; score: number } | null = null;
for (const row of tenants) {
const score = this.scoreHostMatch(row, normalizedHost);
if (score <= 0) continue;
if (!best || score > best.score) {
best = { row, score };
}
}
if (!best) return null;
return {
id: best.row.id,
nameFa: best.row.nameFa,
domain: best.row.domain,
product: best.row.product,
isActive: best.row.isActive,
};
}
/**
* امتیاز بالاتر = هویت دقیق‌تر نسخه.
* nodeServer ضعیف است چون چند نسخه ممکن است یک API مشترک داشته باشند.
*/
private scoreHostMatch(tenant: TenantHostRow, host: string): number {
const hostNoWww = host.replace(/^www\./, '');
const eq = (raw?: string | null) => {
const normalized = this.normalizeHost(raw);
if (!normalized) return false;
return (
normalized === host || normalized.replace(/^www\./, '') === hostNoWww
);
};
if (eq(tenant.domain)) return 100;
for (const alias of this.readDomains(tenant.domains)) {
if (eq(alias)) return 90;
}
if (eq(tenant.appUrl)) return 80;
// adminUrl گاهی موبایل است؛ فقط اگر شبیه میزبان باشد
if (this.looksLikeHostname(tenant.adminUrl) && eq(tenant.adminUrl)) {
return 50;
}
if (eq(tenant.nodeServer)) return 10;
return 0;
}
private looksLikeHostname(value?: string | null) {
const normalized = this.normalizeHost(value);
if (!normalized || !normalized.includes('.')) return false;
if (/^\d+(\.\d+)*$/.test(normalized)) return false;
if (/^09\d{9}$/.test(normalized)) return false;
return true;
}
private readDomains(raw: unknown): string[] {
if (!raw) return [];
if (Array.isArray(raw)) return raw.map(String);
if (typeof raw === 'string') {
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed.map(String) : [];
} catch {
return [];
}
}
return [];
}
private normalizeHost(value?: string | null) {
if (!value) return '';
return String(value)
.trim()
.toLowerCase()
.replace(/^https?:\/\//, '')
.split('/')[0]
.split(':')[0];
}
private equalHex(a: string, b: string) {
try {
const left = Buffer.from(String(a).toLowerCase(), 'utf8');
const right = Buffer.from(String(b).toLowerCase(), 'utf8');
if (left.length !== right.length) return false;
return timingSafeEqual(left, right);
} catch {
return false;
}
}
}