feat: add Moalem MIC SMS provider with shared token cache

This commit is contained in:
SepehrYahyaee
2026-11-09 12:35:00 +03:30
parent 27bd9da54a
commit 8da8170787
16 changed files with 767 additions and 5 deletions
@@ -0,0 +1,282 @@
import { Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { of, throwError } from "rxjs";
import { MicSmsService, normalizeMicMobile } from "./mic-sms.service";
import { MoalemSmsGateway } from "./moalem-sms.gateway";
import { getSmsProvider } from "./sms-provider.config";
import { SmsGatewayService } from "./sms-gateway.service";
import { SmsProviderException } from "./sms-provider.exception";
const OK = { status: 200, data: { id: "delivery", isSuccessful: true } };
describe("MIC SMS adapter", () => {
let service: MicSmsService;
let post: jest.Mock;
let cache: any;
let rows: Map<string, any>;
let settings: Record<string, unknown>;
beforeEach(() => {
jest.useFakeTimers();
rows = new Map();
settings = {
MIC_SMS_CLIENT_ID: "test-client",
MIC_SMS_CLIENT_SECRET: "never-log-secret",
};
cache = {
findOne: jest.fn((filter: any) => ({
select: () => ({
lean: () => ({
exec: async () => {
const row = rows.get(filter.key);
return row && row.expiresAt > filter.expiresAt.$gt ? row : null;
},
}),
}),
})),
updateOne: jest.fn((filter: any, update: any) => ({
exec: async () => rows.set(filter.key, update.$set),
})),
deleteOne: jest.fn((filter: any) => ({
exec: async () => {
if (rows.get(filter.key)?.accessToken === filter.accessToken)
rows.delete(filter.key);
},
})),
};
post = jest.fn((url: string) =>
of(
url.includes("connect/token")
? {
status: 200,
data: { access_token: "never-log-token", expires_in: 86399 },
}
: OK,
),
);
service = new MicSmsService(
{ post } as never,
new ConfigService(settings),
cache,
);
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it.each([
"09120000000",
"9120000000",
"989120000000",
"+989120000000",
"۰۹۱۲۰۰۰۰۰۰۰",
])("normalizes %s", (input) => {
expect(normalizeMicMobile(input)).toBe("+989120000000");
});
it.each(["123", "08120000000", "091200000001", "+19120000000"])(
"rejects invalid %s",
(input) => {
expect(normalizeMicMobile(input)).toBeNull();
},
);
it("uses documented form/payload, caches across service instances, returns no token", async () => {
expect(await service.sendSms("09120000000", "متن تست")).toEqual({
success: true,
data: OK.data,
error: null,
});
const second = new MicSmsService(
{ post } as never,
new ConfigService(settings),
cache,
);
await second.sendSms("9120000000", "test 2");
expect(post).toHaveBeenCalledTimes(3);
const form = new URLSearchParams(post.mock.calls[0][1]);
expect(Object.fromEntries(form)).toEqual({
grant_type: "client_credentials",
client_id: "test-client",
client_secret: "never-log-secret",
scope: "sms_sender",
});
expect(post.mock.calls[1][1]).toEqual({
RecipientPhoneNumber: "+989120000000",
Body: "متن تست",
});
expect(post.mock.calls[1][2]).toMatchObject({
headers: { Authorization: "Bearer never-log-token" },
maxRedirects: 0,
timeout: 15000,
});
});
it("refreshes once on 401, even with one configured attempt", async () => {
settings.MIC_SMS_ATTEMPTS = 1;
post
.mockReset()
.mockReturnValueOnce(of({ status: 200, data: { access_token: "old" } }))
.mockReturnValueOnce(of({ status: 401 }))
.mockReturnValueOnce(of({ status: 200, data: { access_token: "fresh" } }))
.mockReturnValueOnce(of(OK));
expect((await service.sendSms("09120000000", "test")).success).toBe(true);
expect(post).toHaveBeenCalledTimes(4);
expect(cache.deleteOne).toHaveBeenCalledWith(
expect.objectContaining({ accessToken: "old" }),
);
expect(post.mock.calls[3][2].headers.Authorization).toBe("Bearer fresh");
});
it("stops after a repeated 401", async () => {
post
.mockReset()
.mockReturnValueOnce(of({ status: 200, data: { access_token: "old" } }))
.mockReturnValueOnce(of({ status: 401 }))
.mockReturnValueOnce(of({ status: 200, data: { access_token: "new" } }))
.mockReturnValueOnce(of({ status: 401 }));
expect((await service.sendSms("09120000000", "test")).success).toBe(false);
expect(post).toHaveBeenCalledTimes(4);
});
it.each([400, 403, 422, 429])(
"does not retry send HTTP %s",
async (status) => {
post.mockImplementation((url: string) =>
of(
url.includes("connect/token")
? { status: 200, data: { access_token: "token" } }
: { status, data: { access_token: "must-not-escape" } },
),
);
const result = await service.sendSms("09120000000", "test");
expect(result).toMatchObject({ success: false, data: null });
expect(post).toHaveBeenCalledTimes(2);
},
);
it("waits 500 ms before retrying a 5xx send and reuses token", async () => {
post
.mockReset()
.mockReturnValueOnce(of({ status: 200, data: { access_token: "token" } }))
.mockReturnValueOnce(of({ status: 503 }))
.mockReturnValueOnce(of(OK));
const result = service.sendSms("09120000000", "test");
await jest.advanceTimersByTimeAsync(499);
expect(post).toHaveBeenCalledTimes(2);
await jest.advanceTimersByTimeAsync(1);
expect((await result).success).toBe(true);
expect(post).toHaveBeenCalledTimes(3);
});
it("bounds transport retries and excludes raw errors/credentials", async () => {
const warn = jest
.spyOn(Logger.prototype, "warn")
.mockImplementation(() => {});
post.mockReturnValue(
throwError(() => new Error("never-log-secret never-log-token")),
);
const result = service.sendSms("09120000000", "test");
await jest.advanceTimersByTimeAsync(500);
const failure = await result;
expect(failure.success).toBe(false);
expect(JSON.stringify(failure)).not.toMatch(/never-log/);
expect(JSON.stringify(warn.mock.calls)).not.toMatch(/never-log/);
expect(post).toHaveBeenCalledTimes(2);
});
it("rejects isSuccessful false and malformed success bodies", async () => {
post
.mockReturnValueOnce(of({ status: 200, data: { access_token: "token" } }))
.mockReturnValueOnce(
of({
status: 200,
data: { isSuccessful: false, access_token: "must-not-escape" },
}),
);
expect(await service.sendSms("09120000000", "test")).toMatchObject({
success: false,
data: { isSuccessful: false },
});
expect((await service.sendSms("09120000000", "test")).success).toBe(true);
});
it("refreshes expired cached tokens", async () => {
await service.sendSms("09120000000", "test");
jest.setSystemTime(Date.now() + 86400 * 1000);
await service.sendSms("09120000000", "test");
expect(post).toHaveBeenCalledTimes(4);
});
it("does not call provider for invalid recipient or missing credentials", async () => {
expect((await service.sendSms("invalid", "test")).success).toBe(false);
delete settings.MIC_SMS_CLIENT_SECRET;
expect((await service.sendSms("09120000000", "test")).success).toBe(false);
expect(post).not.toHaveBeenCalled();
});
});
describe("Moalem gateway integration", () => {
const original = { ...process.env };
afterEach(() => {
process.env = { ...original };
});
it("selects moalem, accepts moallem alias and respects legacy SMS precedence", () => {
process.env.SMS = "";
process.env.SMS_PROVIDER = "moalem";
expect(getSmsProvider()).toBe("moalem");
process.env.SMS = "moallem";
expect(getSmsProvider()).toBe("moalem");
process.env.SMS = "parsian";
expect(getSmsProvider()).toBe("parsian");
});
it("sends existing OTP/link templates through MIC and records failure rather than success", async () => {
process.env.SMS = "moalem";
process.env.AUTH_SMS_TEMPLATE = "auth-otp";
process.env.AUTH_SMS_MESSAGE = "رمز: {token}";
const sendSms = jest.fn().mockResolvedValue({
success: true,
data: { isSuccessful: true },
error: null,
});
const moalem = new MoalemSmsGateway({ sendSms } as never);
const audit = {
recordGatewaySend: jest.fn(),
recordGatewayVerifyLookup: jest.fn(),
};
const gateway = new SmsGatewayService(
{} as never,
{} as never,
audit as never,
moalem,
);
await gateway.verifyLookUp({
receptor: "09120000000",
template: "auth-otp",
token: "12345",
});
expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345");
await gateway.verifyLookUp({
receptor: "09120000000",
template: "yara-claim-link",
token: "case",
token2: "https://example.test/user/v1/caseClaim?token=test",
});
expect(sendSms.mock.calls[1][1]).toContain(
"https://example.test/user/v1/caseClaim?token=test",
);
sendSms.mockResolvedValue({
success: false,
data: null,
error: "ارسال ناموفق",
});
await expect(
gateway.sendMessage({ receptor: "09120000000", message: "test" }),
).rejects.toBeInstanceOf(SmsProviderException);
expect(audit.recordGatewaySend).toHaveBeenLastCalledWith(
expect.objectContaining({ error: expect.any(SmsProviderException) }),
);
});
});