forked from Yara724/api
fix(SMS): change the brand name of the sms
This commit is contained in:
@@ -29,6 +29,10 @@ export class EnvironmentVariables {
|
||||
@IsBooleanString({ message: "FAKE_OTP must be boolean" })
|
||||
FAKE_OTP?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
SMS_BRAND_NAME?: string;
|
||||
|
||||
// --------------------------------------------------------- //
|
||||
|
||||
@IsNumber(
|
||||
|
||||
@@ -47,7 +47,7 @@ describe("SmsSendLogService", () => {
|
||||
isOtp: true,
|
||||
template: "auth-otp",
|
||||
tokens: { token: "54321" },
|
||||
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 54321",
|
||||
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 54321\nیارا۷۲۴",
|
||||
});
|
||||
expect(doc.providerResponse).toEqual({ return: { status: 200 } });
|
||||
});
|
||||
@@ -67,7 +67,7 @@ describe("SmsSendLogService", () => {
|
||||
kind: SmsSendLogKind.SKIPPED,
|
||||
isOtp: true,
|
||||
tokens: { token: "12345" },
|
||||
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 12345",
|
||||
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 12345\nیارا۷۲۴",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -204,10 +204,12 @@ export class SmsSendLogService {
|
||||
otp: string;
|
||||
reason?: string;
|
||||
}): Promise<void> {
|
||||
const authMessage =
|
||||
process.env.AUTH_SMS_MESSAGE?.trim() ??
|
||||
"کاربر محترم رمز یکبار مصرف شما:\nCode: {token}";
|
||||
const messageText = authMessage.split("{token}").join(params.otp);
|
||||
const messageText = this.resolveMessageTextForLookup({
|
||||
receptor: params.receptor,
|
||||
template: process.env.AUTH_SMS_TEMPLATE?.trim() || "",
|
||||
token: params.otp,
|
||||
isOtp: true,
|
||||
});
|
||||
|
||||
await this.record({
|
||||
receptor: params.receptor,
|
||||
|
||||
@@ -13,6 +13,11 @@ import {
|
||||
} from "./sms-provider.exception";
|
||||
import { KAVENEGAR_SMS_SENDER } from "./kavenegar-sender";
|
||||
import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
||||
import { hasCustomSmsBrand } from "./sms-branding";
|
||||
import {
|
||||
buildParsianTemplateMessage,
|
||||
canRenderSmsTemplate,
|
||||
} from "./parsian-template-messages";
|
||||
|
||||
@Injectable()
|
||||
export class KavenegarSmsGateway {
|
||||
@@ -50,7 +55,16 @@ export class KavenegarSmsGateway {
|
||||
async verifyLookUp(data: VerifyLookUpMessage) {
|
||||
try {
|
||||
const { isOtp: _isOtp, ...providerPayload } = data;
|
||||
const body = await this.sender.verifyLookup(providerPayload);
|
||||
// Hosted templates cannot interpolate deployment branding without a
|
||||
// separate provider-side approval. Use local text for custom deployments.
|
||||
const body =
|
||||
hasCustomSmsBrand() && canRenderSmsTemplate(data)
|
||||
? await this.sender.send({
|
||||
sender: KAVENEGAR_SMS_SENDER,
|
||||
receptor: data.receptor,
|
||||
message: buildParsianTemplateMessage(data),
|
||||
})
|
||||
: await this.sender.verifyLookup(providerPayload);
|
||||
|
||||
if (!isKavenegarSuccess(body)) {
|
||||
const normalized = normalizeKavenegarBody(body);
|
||||
|
||||
@@ -257,7 +257,7 @@ describe("Moalem gateway integration", () => {
|
||||
template: "auth-otp",
|
||||
token: "12345",
|
||||
});
|
||||
expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345");
|
||||
expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345\nیارا۷۲۴");
|
||||
await gateway.verifyLookUp({
|
||||
receptor: "09120000000",
|
||||
template: "yara-claim-link",
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { VerifyLookUpMessage } from "./sms-gateway.types";
|
||||
|
||||
const TOKEN_KEYS = ["token", "token2", "token3", "token10"] as const;
|
||||
import { renderSmsText } from "./sms-branding";
|
||||
|
||||
/** Kavenegar template name → plain-text body for Parsian (placeholders: {token}, {token2}, …). */
|
||||
const PARSIAN_TEMPLATE_BODIES: Record<string, string> = {
|
||||
"yara724-invite-link":
|
||||
"کاربر محترم، لینک ورود به پرونده یارا724:\nشناسه: {token}\n{token2}",
|
||||
"کاربر محترم، لینک ورود به پرونده {brandName}:\nشناسه: {token}\n{token2}",
|
||||
"yara-field-expert-link":
|
||||
"کارشناس میدانی بیمه {token} ({token2}) پرونده شما را بررسی میکند.\nلینک: {token3}",
|
||||
"yara-blame-agreement":
|
||||
@@ -22,46 +21,34 @@ const PARSIAN_TEMPLATE_BODIES: Record<string, string> = {
|
||||
"کاربرگرامی پرونده شما به شماره {token} در سامانه فناوران با شناسه {token2} و شماره پرونده {token3} ثبت شده است. جهت پیگیری های آتی از این اطلاعات استفاده کنید.",
|
||||
};
|
||||
|
||||
function applyTokens(
|
||||
pattern: string,
|
||||
data: Pick<
|
||||
VerifyLookUpMessage,
|
||||
"token" | "token2" | "token3" | "token10"
|
||||
>,
|
||||
): string {
|
||||
let out = pattern;
|
||||
for (const key of TOKEN_KEYS) {
|
||||
const value = data[key];
|
||||
if (value != null && value !== "") {
|
||||
out = out.split(`{${key}}`).join(value);
|
||||
}
|
||||
|
||||
}
|
||||
return out.replace(/\{token\d*\}/g, "").trim();
|
||||
export function canRenderSmsTemplate(data: VerifyLookUpMessage): boolean {
|
||||
return (
|
||||
data.isOtp === true ||
|
||||
Boolean(
|
||||
process.env.AUTH_SMS_TEMPLATE?.trim() &&
|
||||
data.template === process.env.AUTH_SMS_TEMPLATE.trim(),
|
||||
) ||
|
||||
Object.prototype.hasOwnProperty.call(PARSIAN_TEMPLATE_BODIES, data.template)
|
||||
);
|
||||
}
|
||||
|
||||
export function buildParsianTemplateMessage(
|
||||
data: VerifyLookUpMessage,
|
||||
): string {
|
||||
export function buildParsianTemplateMessage(data: VerifyLookUpMessage): string {
|
||||
const authTemplate = process.env.AUTH_SMS_TEMPLATE?.trim();
|
||||
if (authTemplate && data.template === authTemplate) {
|
||||
if (data.isOtp || (authTemplate && data.template === authTemplate)) {
|
||||
const authMessage =
|
||||
process.env.AUTH_SMS_MESSAGE?.trim() ??
|
||||
process.env.AUTH_SMS_MESSAGE?.trim() ||
|
||||
"کاربر محترم رمز یکبار مصرف شما:\nCode: {token}";
|
||||
return applyTokens(authMessage, data);
|
||||
return renderSmsText(authMessage, data);
|
||||
}
|
||||
|
||||
const body = PARSIAN_TEMPLATE_BODIES[data.template];
|
||||
if (body) {
|
||||
return applyTokens(body, data);
|
||||
return renderSmsText(body, data);
|
||||
}
|
||||
|
||||
const parts = [
|
||||
`پیام سیستم (${data.template})`,
|
||||
data.token ? `کد: ${data.token}` : "",
|
||||
data.token2 ?? "",
|
||||
data.token3 ?? "",
|
||||
data.token10 ?? "",
|
||||
].filter(Boolean);
|
||||
return parts.join("\n");
|
||||
// Provider identifiers are technical metadata, not useful message text.
|
||||
return renderSmsText(
|
||||
"پیام سامانه\n{token}\n{token2}\n{token3}\n{token10}",
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { of } from "rxjs";
|
||||
import { SmsSendLogService } from "../entities/db-service/sms-send-log.service";
|
||||
import { KavenegarSmsGateway } from "./kavenegar-sms.gateway";
|
||||
import { MoalemSmsGateway } from "./moalem-sms.gateway";
|
||||
import { ParsianSmsGateway } from "./parsian-sms.gateway";
|
||||
import { buildParsianTemplateMessage } from "./parsian-template-messages";
|
||||
import { getSmsBrandName, renderSmsText } from "./sms-branding";
|
||||
import { SmsGatewayService } from "./sms-gateway.service";
|
||||
import { SmsProviderException } from "./sms-provider.exception";
|
||||
|
||||
const brand = "سامانه خسارت اپکس";
|
||||
const templates = [
|
||||
"auth-otp",
|
||||
"yara724-invite-link",
|
||||
"yara-field-expert-link",
|
||||
"yara-blame-agreement",
|
||||
"yara-claim-link",
|
||||
"yara-expert-lock",
|
||||
"yara-resend-documents",
|
||||
"yara-signature",
|
||||
"yara-fanavaran-claim",
|
||||
];
|
||||
const message = (template = "yara724-invite-link") => ({
|
||||
template,
|
||||
receptor: "09120000000",
|
||||
token: "12345",
|
||||
token2: "https://user.yara724.com/user/v1/user?token=case",
|
||||
token3: "کارشناس",
|
||||
token10: "https://user.yara724.com/user/v1/caseClaim?token=case",
|
||||
});
|
||||
|
||||
describe("deployment-specific SMS branding", () => {
|
||||
const originalEnv = { ...process.env };
|
||||
beforeEach(() => {
|
||||
delete process.env.SMS;
|
||||
process.env.SMS_BRAND_NAME = brand;
|
||||
process.env.AUTH_SMS_TEMPLATE = "auth-otp";
|
||||
process.env.AUTH_SMS_MESSAGE = "رمز ورود: {token}";
|
||||
});
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it.each([undefined, "", " "])(
|
||||
"defaults to یارا۷۲۴ when name is %s",
|
||||
(value) => {
|
||||
if (value === undefined) delete process.env.SMS_BRAND_NAME;
|
||||
else process.env.SMS_BRAND_NAME = value;
|
||||
expect(getSmsBrandName()).toBe("یارا۷۲۴");
|
||||
expect(buildParsianTemplateMessage(message())).toContain("یارا۷۲۴");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(templates)(
|
||||
"brands %s without showing its provider identifier",
|
||||
(template) => {
|
||||
const text = buildParsianTemplateMessage(message(template));
|
||||
expect(text).toContain(brand);
|
||||
expect(text.match(new RegExp(brand, "g"))).toHaveLength(1);
|
||||
expect(text).toContain("12345");
|
||||
expect(text).not.toContain(template);
|
||||
expect(text).not.toMatch(/یارا[۷7][۲2][۴4]/);
|
||||
expect(text).not.toMatch(/\{(?:brandName|token\d*)\}/);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["یارا724", "یارا۷۲۴", "یارا ۷۲۴", "Yara724"])(
|
||||
"updates legacy database/custom OTP pattern name %s",
|
||||
(legacyName) => {
|
||||
process.env.AUTH_SMS_MESSAGE = `${legacyName}: رمز {token}`;
|
||||
expect(buildParsianTemplateMessage(message("auth-otp"))).toBe(
|
||||
`${brand}: رمز 12345`,
|
||||
);
|
||||
expect(renderSmsText(`پیام پرونده از ${legacyName}`)).toBe(
|
||||
`پیام پرونده از ${brand}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("renders the brand placeholder once and leaves token data and URLs intact", () => {
|
||||
process.env.AUTH_SMS_MESSAGE = "رمز {token} در {brandName}";
|
||||
expect(buildParsianTemplateMessage(message("auth-otp"))).toBe(
|
||||
`رمز 12345 در ${brand}`,
|
||||
);
|
||||
const link =
|
||||
"https://user.yara724.com/یارا۷۲۴?data={token}&brand={brandName}";
|
||||
const text = buildParsianTemplateMessage({ ...message(), token2: link });
|
||||
expect(text).toContain(link);
|
||||
expect(renderSmsText(`پرونده\nhttps://user.yara724.com/یارا۷۲۴`)).toBe(
|
||||
`پرونده\nhttps://user.yara724.com/یارا۷۲۴\n${brand}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("uses a branded OTP fallback even without a configured template/pattern", () => {
|
||||
delete process.env.AUTH_SMS_TEMPLATE;
|
||||
process.env.AUTH_SMS_MESSAGE = " ";
|
||||
expect(buildParsianTemplateMessage({ ...message(""), isOtp: true })).toBe(
|
||||
`کاربر محترم رمز یکبار مصرف شما:\nCode: 12345\n${brand}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("brands the fallback without exposing unknown provider template IDs", () => {
|
||||
const text = buildParsianTemplateMessage(message("legacy-template-id"));
|
||||
expect(text).toContain(brand);
|
||||
expect(text).not.toContain("legacy-template-id");
|
||||
});
|
||||
|
||||
it.each(["parsian", "moalem"])(
|
||||
"delivers branded %s templates and plain database messages with matching audit text",
|
||||
async (provider) => {
|
||||
process.env.SMS_PROVIDER = provider;
|
||||
process.env.PARSIAN_SMS_URL = "https://sms.example.test/send?recipient";
|
||||
const captured: string[] = [];
|
||||
const get = jest.fn((url: string) => {
|
||||
captured.push(new URL(url).searchParams.get("Message")!);
|
||||
return of({ status: 200, data: { ok: true } });
|
||||
});
|
||||
const sendSms = jest.fn(async (_recipient: string, text: string) => {
|
||||
captured.push(text);
|
||||
return { success: true, data: { isSuccessful: true }, error: null };
|
||||
});
|
||||
const create = jest.fn().mockResolvedValue({});
|
||||
const audit = new SmsSendLogService({ create } as never);
|
||||
const gateway = new SmsGatewayService(
|
||||
{} as never,
|
||||
new ParsianSmsGateway({ get } as never),
|
||||
audit,
|
||||
new MoalemSmsGateway({ sendSms } as never),
|
||||
);
|
||||
for (const template of templates)
|
||||
await gateway.verifyLookUp(message(template));
|
||||
await gateway.sendMessage({
|
||||
receptor: "09120000000",
|
||||
message: "پرونده یارا724 آماده است.",
|
||||
});
|
||||
expect(captured).toHaveLength(templates.length + 1);
|
||||
for (let i = 0; i < captured.length; i++) {
|
||||
expect(captured[i]).toContain(brand);
|
||||
expect(create.mock.calls[i][0].messageText).toBe(captured[i]);
|
||||
}
|
||||
expect(captured[captured.length - 1]).toBe(`پرونده ${brand} آماده است.`);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps default Kavenegar hosted-template requests unchanged", async () => {
|
||||
delete process.env.SMS_BRAND_NAME;
|
||||
const verifyLookup = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ return: { status: 200 } });
|
||||
const send = jest.fn();
|
||||
const gateway = new KavenegarSmsGateway({ verifyLookup, send } as never);
|
||||
await gateway.verifyLookUp({ ...message("auth-otp"), isOtp: true });
|
||||
expect(verifyLookup).toHaveBeenCalledWith(message("auth-otp"));
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(templates)(
|
||||
"uses branded plain Kavenegar text for %s on custom deployments",
|
||||
async (template) => {
|
||||
const verifyLookup = jest.fn();
|
||||
const send = jest.fn().mockResolvedValue({ return: { status: 200 } });
|
||||
const gateway = new KavenegarSmsGateway({ verifyLookup, send } as never);
|
||||
await gateway.verifyLookUp(message(template));
|
||||
expect(verifyLookup).not.toHaveBeenCalled();
|
||||
expect(send).toHaveBeenCalledWith({
|
||||
receptor: "09120000000",
|
||||
sender: "10008663",
|
||||
message: buildParsianTemplateMessage(message(template)),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("continues reporting failed branded Kavenegar delivery as a failure", async () => {
|
||||
const send = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ return: { status: 403, message: "denied" } });
|
||||
const gateway = new KavenegarSmsGateway({ send } as never);
|
||||
await expect(gateway.verifyLookUp(message())).rejects.toBeInstanceOf(
|
||||
SmsProviderException,
|
||||
);
|
||||
});
|
||||
|
||||
it("records fake/skipped OTP with the same branding as delivered OTPs", async () => {
|
||||
const create = jest.fn().mockResolvedValue({});
|
||||
const audit = new SmsSendLogService({ create } as never);
|
||||
await audit.recordSkippedOtp({ receptor: "09120000000", otp: "12345" });
|
||||
expect(create.mock.calls[0][0].messageText).toBe(
|
||||
buildParsianTemplateMessage(message("auth-otp")),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { VerifyLookUpMessage } from "./sms-gateway.types";
|
||||
|
||||
export const DEFAULT_SMS_BRAND_NAME = "یارا۷۲۴";
|
||||
|
||||
export function getSmsBrandName(): string {
|
||||
return process.env.SMS_BRAND_NAME?.trim() || DEFAULT_SMS_BRAND_NAME;
|
||||
}
|
||||
|
||||
export function hasCustomSmsBrand(): boolean {
|
||||
return getSmsBrandName() !== DEFAULT_SMS_BRAND_NAME;
|
||||
}
|
||||
|
||||
type MessageTokens = Partial<
|
||||
Pick<VerifyLookUpMessage, "token" | "token2" | "token3" | "token10">
|
||||
>;
|
||||
|
||||
/** Render patterns only: never replace branding or placeholders inside token values. */
|
||||
export function renderSmsText(
|
||||
pattern: string,
|
||||
tokens: MessageTokens = {},
|
||||
): string {
|
||||
const brandName = getSmsBrandName();
|
||||
// Handle old database/config patterns without rewriting links embedded in them.
|
||||
let brandedPattern = pattern
|
||||
.split(/(https?:\/\/[^\s]+)/gi)
|
||||
.map((part) =>
|
||||
/^https?:\/\//i.test(part)
|
||||
? part
|
||||
: part.replace(
|
||||
/(^|[\s(«،؛:])(?:یارا[ \u200c]*[۷7][۲2][۴4]|yara[ \u200c]*724)(?=$|[\s)»،؛:.!?])/giu,
|
||||
"$1{brandName}",
|
||||
),
|
||||
)
|
||||
.join("");
|
||||
if (
|
||||
!brandedPattern.includes("{brandName}") &&
|
||||
!brandedPattern.includes(brandName)
|
||||
) {
|
||||
brandedPattern += "\n{brandName}";
|
||||
}
|
||||
return brandedPattern
|
||||
.replace(
|
||||
/\{(brandName|token|token2|token3|token10)\}/g,
|
||||
(_match, key: "brandName" | keyof MessageTokens) =>
|
||||
key === "brandName" ? brandName : (tokens[key] ?? ""),
|
||||
)
|
||||
.trim();
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { MoalemSmsGateway } from "./moalem-sms.gateway";
|
||||
import { ParsianSmsGateway } from "./parsian-sms.gateway";
|
||||
import { getSmsProvider } from "./sms-provider.config";
|
||||
import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
||||
import { renderSmsText } from "./sms-branding";
|
||||
|
||||
export type { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
||||
|
||||
@@ -24,6 +25,7 @@ export class SmsGatewayService implements OnModuleInit {
|
||||
}
|
||||
|
||||
async sendMessage(data: SendMessage) {
|
||||
data = { ...data, message: renderSmsText(data.message) };
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const result = await this.activeGateway().sendMessage(data);
|
||||
|
||||
Reference in New Issue
Block a user