diff --git a/.env.example b/.env.example index 5721f04..91243aa 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,7 @@ AI_DAMAGE_PRICE_MIN_SEVERITY=severe # --------------------------------------------- # 📩 SMS # --------------------------------------------- +# kavenegar | parsian | moalem (legacy SMS takes precedence when nonempty) SMS_PROVIDER = SMS_API_KEY = AUTH_SMS_TEMPLATE = @@ -106,3 +107,13 @@ TEJARAT_INQUIRY_PASSWORD = PARSIAN_API_KEY = PARSIAN_BASIC_TOKEN = PARSIAN_SMS_URL = + +# MIC / Moalem SMS (used only when SMS_PROVIDER=moalem or SMS=moalem) +MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token +MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send +MIC_SMS_CLIENT_ID= +MIC_SMS_CLIENT_SECRET= +MIC_SMS_TOKEN_TTL=86399 +# Total normal send attempts; a single 401 refresh/resend is additional. +MIC_SMS_ATTEMPTS=2 +MIC_SMS_TIMEOUT_MS=15000 diff --git a/README.md b/README.md index c1244ea..cc92271 100644 --- a/README.md +++ b/README.md @@ -6,3 +6,7 @@ - [AI damage detection and advisory prices — setup and testing](docs/ai-damage-companion.md) Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md). + +### Moalem SMS + +For MIC SMS environment settings, shared token-cache indexes and a test-send command, see [Moalem SMS adapter](docs/MIC/moalem-sms.md). diff --git a/docs/MIC/SMS - MIC SMS API.pdf b/docs/MIC/SMS - MIC SMS API.pdf new file mode 100644 index 0000000..a0391f6 Binary files /dev/null and b/docs/MIC/SMS - MIC SMS API.pdf differ diff --git a/docs/MIC/moalem-sms.md b/docs/MIC/moalem-sms.md new file mode 100644 index 0000000..2f6cd62 --- /dev/null +++ b/docs/MIC/moalem-sms.md @@ -0,0 +1,72 @@ +# MIC / Moalem SMS adapter + +The deployment selects `moalem` as its SMS provider. This is independent of the Fanavaran tenant selection. Existing OTP, invitation, signature, document and case-notification callers continue using `SmsGatewayService`. Moalem sends the same plain-text template bodies as Parsian, including the existing user-panel links. Kavenegar and Parsian remain available. + +## Production environment + +```dotenv +SMS_PROVIDER=moalem +MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token +MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send +MIC_SMS_CLIENT_ID= +MIC_SMS_CLIENT_SECRET= +MIC_SMS_TOKEN_TTL=86399 +MIC_SMS_ATTEMPTS=2 +MIC_SMS_TIMEOUT_MS=15000 +FAKE_OTP=false +``` + +- If the legacy `SMS` setting is nonempty, it overrides `SMS_PROVIDER`. Set it to `moalem` as well, or remove it. `moallem` is accepted as an alias; logs use `moalem`. +- Keep the existing `AUTH_SMS_TEMPLATE` and `AUTH_SMS_MESSAGE` settings for OTP text. Existing URL and `USER_BASE_PATH` settings continue controlling message links. +- Supply credentials privately through the server environment or secret store. The repository example contains no credentials. Restart API instances after changing configuration. +- Active Moalem deployments fail startup when required MIC credentials, HTTPS URLs or numeric settings are invalid. MIC settings do not block other SMS providers. +- Allow outbound HTTPS to `auth.mic.co.ir` and `api.mic.co.ir`. Redirects are disabled. The existing HTTP proxy configuration is reused. +- Existing MongoDB is used for the shared token cache, so no Redis or new infrastructure is required. All API instances must share that database. Cache reads explicitly reject expired entries. + +Production disables automatic Mongoose indexes. Have the database deployment create these indexes in the application database: + +```javascript +db.micSmsTokens.createIndex({key: 1}, {unique: true}); +db.micSmsTokens.createIndex({expiresAt: 1}, {expireAfterSeconds: 0}); +``` + +`micSmsTokens` contains server-only bearer tokens, hidden from normal model selection. Restrict database/backup access as for other credentials. Cache identity includes a SHA-256 fingerprint of endpoints and client credentials; credential changes select a new cache entry. Old entries expire. Token lifetime is the smaller of configured TTL and a positive provider `expires_in`, with an early-expiry safety margin. Requests within one process share an in-flight token fetch; simultaneous cold starts across replicas may each fetch a token. + +## Transport and failure contract + +`MicSmsService.sendSms(mobile, message)` is an awaited operation returning: + +```json +{"success": true, "data": {"isSuccessful": true, "id": "delivery-id"}, "error": null} +``` + +```json +{"success": false, "data": null, "error": "ارسال پیامک معلم انجام نشد. دوباره تلاش کنید."} +``` + +`data` contains only documented delivery-response fields, never the authentication response or raw HTTP error. `error` is a safe Persian explanation. Provider response `isSuccessful` must be exactly `true`: HTTP 2xx with `false`, a missing flag, or a malformed response is treated as failure. This deliberately tightens the old PHP behavior. + +The gateway unwraps successful delivery data and throws the existing `SmsProviderException` on failure. This preserves existing caller behavior, including failure auditing and OTP delivery errors. SMS audit records use provider `moalem`. + +- Token request: form-encoded `grant_type=client_credentials`, `client_id`, `client_secret`, `scope=sms_sender`. +- Send request: bearer authorization and exactly `RecipientPhoneNumber` / `Body` in JSON. +- Mobile numbers `0912…`, `912…`, `98912…`, `+98912…` normalize to `+98912…`. Persian/Arabic numerals are also accepted; invalid mobile numbers fail before any HTTP call. +- A send HTTP 401 evicts the rejected cached token conditionally, obtains a token and resends once. A second 401 fails. This recovery is allowed even when the normal attempt count is one. +- Other send HTTP 4xx responses, including 429, fail immediately. Negative/malformed HTTP 2xx delivery responses also fail immediately. +- Transport errors, token/cache failures and other non-success send statuses retry up to `MIC_SMS_ATTEMPTS` normal attempts, default 2. Delays are `500 * attempt` milliseconds. A single 401 refresh/resend can add one send request to that limit. +- Retryable timeouts can be ambiguous: MIC's document specifies no idempotency key, so a retry may duplicate a message that the provider already accepted. +- Logs include only fixed failure categories, HTTP status and attempt number. They exclude credentials, tokens, recipient/body and raw Axios errors. + +No asynchronous delivery path was introduced. Callers must await `sendSms()` or the existing gateway. If queued delivery is added later, use a durable queue/worker with separately awaited enqueue calls; do not use an untracked background promise. + +## Send a real test + +From the API repository with `.env` and MongoDB available: + +```bash +npm run sms:test:mic -- 09120000000 'پیام آزمایشی سامانه' +``` + +Use an authorized test recipient: this sends a real SMS. The helper starts only the configuration/database/SMS modules, prints the safe `{success,data,error}` result, closes connections and exits nonzero on failure. It does not start HTTP routes or application workers. Run it twice to exercise shared token reuse. No public test endpoint was added. + +Automated verification uses mocked HTTP and cache operations; no live MIC SMS is sent by tests. Coverage includes normalization, form/payload contracts, shared cache reuse, expiry, one-time 401 recovery, terminal 4xx, backoff, safe failures/logs, templates and audit integration. diff --git a/package.json b/package.json index 93fa772..d4ade58 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", + "sms:test:mic": "ts-node -r tsconfig-paths/register scripts/test-mic-sms.ts", "seed:parsian-tehran": "ts-node scripts/seed-parsian-tehran.ts", "seed:reports-fixtures": "ts-node scripts/seed-insurer-reports-fixtures.ts", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", diff --git a/scripts/test-mic-sms.ts b/scripts/test-mic-sms.ts new file mode 100644 index 0000000..d1a90ec --- /dev/null +++ b/scripts/test-mic-sms.ts @@ -0,0 +1,47 @@ +/** Send one real MIC SMS using .env. Does not start application workers or HTTP routes. */ +import "reflect-metadata"; +import { Module } from "@nestjs/common"; +import { NestFactory } from "@nestjs/core"; +import { ConfigModule } from "@nestjs/config"; +import { DatabaseModule } from "../src/core/database/database.module"; +import { SmsGatewayModule } from "../src/sms-orchestration/provider/sms-gateway.module"; +import { + MicSmsService, + normalizeMicMobile, +} from "../src/sms-orchestration/provider/mic-sms.service"; + +@Module({ + imports: [ + ConfigModule.forRoot({ isGlobal: true }), + DatabaseModule, + SmsGatewayModule, + ], +}) +class MicSmsTestModule {} + +async function main() { + const [mobile, message] = process.argv.slice(2); + if (!mobile || !normalizeMicMobile(mobile) || !message?.trim()) { + console.error('Usage: npm run sms:test:mic -- 09120000000 "پیام آزمایشی"'); + process.exitCode = 1; + return; + } + const app = await NestFactory.createApplicationContext(MicSmsTestModule, { + logger: false, + abortOnError: false, + }); + try { + const result = await app.get(MicSmsService).sendSms(mobile, message); + console.log(JSON.stringify(result, null, 2)); + if (!result.success) process.exitCode = 1; + } finally { + await app.close(); + } +} +main().catch(() => { + // Never print configuration, credentials, or raw connection/HTTP errors. + console.error( + "MIC SMS test could not start. Check database connectivity and MIC SMS environment settings.", + ); + process.exitCode = 1; +}); diff --git a/src/core/config/fanavaran-client.config.ts b/src/core/config/fanavaran-client.config.ts index 9b700b5..ca948d2 100644 --- a/src/core/config/fanavaran-client.config.ts +++ b/src/core/config/fanavaran-client.config.ts @@ -3,7 +3,7 @@ export type FanavaranClientKey = "parsian" | "tejaratno" | "moallem"; const FANAVARAN_API_ROOTS: Record = { parsian: "https://apimanager.iraneit.com/BimeApiManager/api", tejaratno: "https://apimanager.iraneit.com/BimeApiManager/api", - moallem: "https://api.inssw.ir/BimeApiManager/api", + moallem: "https://apimanager.iraneit.com/BimeApiManager/api", }; export function getFanavaranApiRoot(clientKey: FanavaranClientKey): string { diff --git a/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts b/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts index 3764625..234b1c0 100644 --- a/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts +++ b/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts @@ -92,4 +92,18 @@ describe("SmsSendLogService", () => { }), ); }); + it("records Moalem plain messages with the correct provider", async () => { + process.env.SMS_PROVIDER = "moalem"; + await service.recordGatewaySend({ + data: { receptor: "09123333333", message: "پیام تست" }, + startedAt: Date.now(), + result: { isSuccessful: true }, + }); + expect(createMock).toHaveBeenCalledWith( + expect.objectContaining({ + provider: SmsSendLogProvider.MOALEM, + status: SmsSendLogStatus.SUCCESS, + }), + ); + }); }); diff --git a/src/sms-orchestration/entities/db-service/sms-send-log.service.ts b/src/sms-orchestration/entities/db-service/sms-send-log.service.ts index 129251a..40d10d5 100644 --- a/src/sms-orchestration/entities/db-service/sms-send-log.service.ts +++ b/src/sms-orchestration/entities/db-service/sms-send-log.service.ts @@ -84,6 +84,7 @@ export class SmsSendLogService { } activeGatewayProvider(): SmsSendLogProvider { + if (getSmsProvider() === "moalem") return SmsSendLogProvider.MOALEM; return getSmsProvider() === "parsian" ? SmsSendLogProvider.PARSIAN : SmsSendLogProvider.KAVENEGAR; diff --git a/src/sms-orchestration/entities/schema/sms-send-log.schema.ts b/src/sms-orchestration/entities/schema/sms-send-log.schema.ts index b14e52f..d3a6525 100644 --- a/src/sms-orchestration/entities/schema/sms-send-log.schema.ts +++ b/src/sms-orchestration/entities/schema/sms-send-log.schema.ts @@ -5,6 +5,7 @@ import { HydratedDocument } from "mongoose"; export enum SmsSendLogProvider { KAVENEGAR = "kavenegar", PARSIAN = "parsian", + MOALEM = "moalem", TEJARATNO = "tejaratno", } diff --git a/src/sms-orchestration/provider/mic-sms-token.schema.ts b/src/sms-orchestration/provider/mic-sms-token.schema.ts new file mode 100644 index 0000000..b5e8ad3 --- /dev/null +++ b/src/sms-orchestration/provider/mic-sms-token.schema.ts @@ -0,0 +1,16 @@ +import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; + +/** Shared, server-only credential cache. Never expose through an API. */ +@Schema({ collection: "micSmsTokens", versionKey: false }) +export class MicSmsToken { + @Prop({ type: String, required: true, unique: true }) + key: string; + + @Prop({ type: String, required: true, select: false }) + accessToken: string; + + @Prop({ type: Date, required: true }) + expiresAt: Date; +} +export const MicSmsTokenSchema = SchemaFactory.createForClass(MicSmsToken); +MicSmsTokenSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); diff --git a/src/sms-orchestration/provider/mic-sms.service.spec.ts b/src/sms-orchestration/provider/mic-sms.service.spec.ts new file mode 100644 index 0000000..47191b9 --- /dev/null +++ b/src/sms-orchestration/provider/mic-sms.service.spec.ts @@ -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; + let settings: Record; + + 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) }), + ); + }); +}); diff --git a/src/sms-orchestration/provider/mic-sms.service.ts b/src/sms-orchestration/provider/mic-sms.service.ts new file mode 100644 index 0000000..fca8086 --- /dev/null +++ b/src/sms-orchestration/provider/mic-sms.service.ts @@ -0,0 +1,258 @@ +import { HttpService } from "@nestjs/axios"; +import { Injectable, Logger, OnModuleInit } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { InjectModel } from "@nestjs/mongoose"; +import { createHash } from "crypto"; +import { Model } from "mongoose"; +import { firstValueFrom } from "rxjs"; +import { MicSmsToken } from "./mic-sms-token.schema"; +import { getSmsProvider } from "./sms-provider.config"; + +export type MicSmsResult = { + success: boolean; + data: Record | null; + error: string | null; +}; + +export function normalizeMicMobile(value: string): string | null { + const digits = String(value) + .trim() + .replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 1776)) + .replace(/[٠-٩]/g, (c) => String(c.charCodeAt(0) - 1632)); + const local = digits.replace(/^(?:\+98|98|0)/, ""); + return /^9\d{9}$/.test(local) ? `+98${local}` : null; +} + +// Only documented delivery fields may leave this adapter or enter SMS audit logs. +function deliveryData(body: unknown): Record | null { + if (!body || typeof body !== "object" || Array.isArray(body)) return null; + const result: Record = {}; + for (const key of [ + "id", + "senderPhoneNumber", + "recipientPhoneNumber", + "sentAtUtc", + "responseId", + "enqueued", + "status", + "isSuccessful", + ]) { + const value = (body as Record)[key]; + if ( + typeof value === "string" || + typeof value === "boolean" || + typeof value === "number" + ) + result[key] = value; + } + return result; +} + +@Injectable() +export class MicSmsService implements OnModuleInit { + private readonly logger = new Logger(MicSmsService.name); + private pendingToken?: Promise; + + constructor( + private readonly http: HttpService, + private readonly config: ConfigService, + @InjectModel(MicSmsToken.name) private readonly tokens: Model, + ) {} + + onModuleInit() { + if (getSmsProvider() === "moalem") this.settings(); + } + + private settings() { + const tokenUrl = + this.config.get("MIC_SMS_TOKEN_URL") || + "https://auth.mic.co.ir/connect/token"; + const sendUrl = + this.config.get("MIC_SMS_SEND_URL") || + "https://api.mic.co.ir/sms/send"; + const clientId = this.config.get("MIC_SMS_CLIENT_ID")?.trim(); + const secret = this.config.get("MIC_SMS_CLIENT_SECRET"); + for (const value of [tokenUrl, sendUrl]) { + const url = new URL(value); + if (url.protocol !== "https:" || url.username || url.password) + throw new Error( + "MIC SMS URLs must use HTTPS without embedded credentials", + ); + } + if (!clientId || !secret?.trim()) + throw new Error( + "MIC_SMS_CLIENT_ID and MIC_SMS_CLIENT_SECRET are required for moalem SMS", + ); + const integer = (name: string, fallback: number, max: number) => { + const value = Number(this.config.get(name) ?? fallback); + if (!Number.isInteger(value) || value < 1 || value > max) + throw new Error(`${name} must be an integer between 1 and ${max}`); + return value; + }; + return { + tokenUrl, + sendUrl, + clientId, + secret, + ttl: integer("MIC_SMS_TOKEN_TTL", 86399, 86400 * 30), + attempts: integer("MIC_SMS_ATTEMPTS", 2, 5), + timeout: integer("MIC_SMS_TIMEOUT_MS", 15000, 120000), + key: createHash("sha256") + .update(JSON.stringify([tokenUrl, sendUrl, clientId, secret])) + .digest("hex"), + }; + } + + private async token(): Promise { + if (this.pendingToken) return this.pendingToken; + this.pendingToken = this.loadToken(); + try { + return await this.pendingToken; + } finally { + this.pendingToken = undefined; + } + } + + private async loadToken(): Promise { + const s = this.settings(); + const cached = await this.tokens + .findOne({ key: s.key, expiresAt: { $gt: new Date() } }) + .select("+accessToken") + .lean() + .exec(); + if (cached?.accessToken) return cached.accessToken; + const response = await firstValueFrom( + this.http.post( + s.tokenUrl, + new URLSearchParams({ + grant_type: "client_credentials", + client_id: s.clientId, + client_secret: s.secret, + scope: "sms_sender", + }).toString(), + { + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + timeout: s.timeout, + maxRedirects: 0, + validateStatus: () => true, + }, + ), + ); + if ( + response.status !== 200 || + typeof response.data?.access_token !== "string" || + !response.data.access_token.trim() + ) + throw new Error("MIC SMS token request failed"); + const expiresIn = Number(response.data.expires_in); + const ttl = Math.min( + s.ttl, + Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : s.ttl, + ); + // Expiry checked in queries as well as Mongo's asynchronous TTL cleanup. + const expiresAt = new Date( + Date.now() + Math.max(0, ttl - Math.min(30, ttl / 10)) * 1000, + ); + await this.tokens + .updateOne( + { key: s.key }, + { $set: { accessToken: response.data.access_token, expiresAt } }, + { upsert: true }, + ) + .exec(); + return response.data.access_token; + } + + /** Synchronous: callers must await this operation. No fire-and-forget promises. */ + async sendSms(receptor: string, message: string): Promise { + const mobile = normalizeMicMobile(receptor); + if (!mobile || !message?.trim()) + return { + success: false, + data: null, + error: "شماره همراه یا متن پیامک معتبر نیست.", + }; + let s: ReturnType; + try { + s = this.settings(); + } catch { + return this.failure("تنظیمات سرویس پیامک معلم کامل نیست."); + } + let refreshed = false; + for (let attempt = 1; attempt <= s.attempts; attempt++) { + try { + let token = await this.token(); + let response = await this.send(s, token, mobile, message); + if (response.status === 401 && !refreshed) { + refreshed = true; + // Conditional eviction avoids deleting a token another replica just refreshed. + await this.tokens + .deleteOne({ key: s.key, accessToken: token }) + .exec(); + token = await this.token(); + response = await this.send(s, token, mobile, message); + } + if (response.status >= 200 && response.status < 300) { + const data = deliveryData(response.data); + if (data?.isSuccessful === true) + return { success: true, data, error: null }; + return this.failure( + "سرویس پیامک معلم ارسال پیام را تأیید نکرد.", + response.status, + data, + ); + } + if (response.status >= 400 && response.status < 500) + return this.failure( + "سرویس پیامک معلم درخواست ارسال را نپذیرفت.", + response.status, + ); + this.logger.warn( + `MIC SMS send failed status=${response.status} attempt=${attempt}`, + ); + } catch { + // Never log Axios errors: they contain the bearer token and client secret. + this.logger.warn( + `MIC SMS transport/cache/token failure attempt=${attempt}`, + ); + } + if (attempt < s.attempts) + await new Promise((resolve) => setTimeout(resolve, 500 * attempt)); + } + return this.failure("ارسال پیامک معلم انجام نشد. دوباره تلاش کنید."); + } + + private send( + s: ReturnType, + token: string, + mobile: string, + message: string, + ) { + return firstValueFrom( + this.http.post( + s.sendUrl, + { RecipientPhoneNumber: mobile, Body: message }, + { + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, + timeout: s.timeout, + maxRedirects: 0, + validateStatus: () => true, + }, + ), + ); + } + + private failure( + error: string, + status?: number, + data: Record | null = null, + ): MicSmsResult { + this.logger.warn( + `MIC SMS delivery failed status=${status ?? "unavailable"}`, + ); + return { success: false, data, error }; + } +} diff --git a/src/sms-orchestration/provider/moalem-sms.gateway.ts b/src/sms-orchestration/provider/moalem-sms.gateway.ts new file mode 100644 index 0000000..a0852fc --- /dev/null +++ b/src/sms-orchestration/provider/moalem-sms.gateway.ts @@ -0,0 +1,42 @@ +import { Injectable } from "@nestjs/common"; +import { MicSmsService } from "./mic-sms.service"; +import { buildParsianTemplateMessage } from "./parsian-template-messages"; +import { SmsProviderException } from "./sms-provider.exception"; +import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types"; + +@Injectable() +export class MoalemSmsGateway { + constructor(private readonly mic: MicSmsService) {} + + sendMessage(data: SendMessage) { + return this.deliver(data.receptor, data.message, "send"); + } + + verifyLookUp(data: VerifyLookUpMessage) { + return this.deliver( + data.receptor, + buildParsianTemplateMessage(data), + "verifyLookup", + data.template, + ); + } + + private async deliver( + receptor: string, + message: string, + operation: "send" | "verifyLookup", + template?: string, + ) { + const result = await this.mic.sendSms(receptor, message); + if (!result.success) { + // Safe metadata only, never retain the HTTP error/config or token response. + throw new SmsProviderException(operation, { + receptor, + template, + providerBody: result.data, + normalized: { message: result.error, raw: JSON.stringify(result.data) }, + }); + } + return result.data; + } +} diff --git a/src/sms-orchestration/provider/sms-gateway.module.ts b/src/sms-orchestration/provider/sms-gateway.module.ts index 125a269..f68eeae 100644 --- a/src/sms-orchestration/provider/sms-gateway.module.ts +++ b/src/sms-orchestration/provider/sms-gateway.module.ts @@ -9,6 +9,9 @@ import { SmsSendLogSchema, } from "../entities/schema/sms-send-log.schema"; +import { MicSmsService } from "./mic-sms.service"; +import { MoalemSmsGateway } from "./moalem-sms.gateway"; +import { MicSmsToken, MicSmsTokenSchema } from "./mic-sms-token.schema"; import { KavenegarService } from "./kavenegar.service"; import { KavenegarSmsGateway } from "./kavenegar-sms.gateway"; import { ParsianSmsGateway } from "./parsian-sms.gateway"; @@ -24,15 +27,18 @@ import { SmsGatewayService } from "./sms-gateway.service"; ConfigModule, MongooseModule.forFeature([ { name: SmsSendLog.name, schema: SmsSendLogSchema }, + { name: MicSmsToken.name, schema: MicSmsTokenSchema }, ]), ], providers: [ + MicSmsService, + MoalemSmsGateway, KavenegarService, KavenegarSmsGateway, ParsianSmsGateway, SmsSendLogService, SmsGatewayService, ], - exports: [SmsGatewayService, SmsSendLogService], + exports: [SmsGatewayService, SmsSendLogService, MicSmsService], }) export class SmsGatewayModule {} diff --git a/src/sms-orchestration/provider/sms-gateway.service.ts b/src/sms-orchestration/provider/sms-gateway.service.ts index ace9098..7534c2e 100644 --- a/src/sms-orchestration/provider/sms-gateway.service.ts +++ b/src/sms-orchestration/provider/sms-gateway.service.ts @@ -1,6 +1,7 @@ import { Injectable, Logger, OnModuleInit } from "@nestjs/common"; 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 { getSmsProvider } from "./sms-provider.config"; import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types"; @@ -15,6 +16,7 @@ export class SmsGatewayService implements OnModuleInit { private readonly kavenegar: KavenegarSmsGateway, private readonly parsian: ParsianSmsGateway, private readonly smsSendLogService: SmsSendLogService, + private readonly moalem: MoalemSmsGateway, ) {} onModuleInit() { @@ -61,7 +63,11 @@ export class SmsGatewayService implements OnModuleInit { } } - private activeGateway(): KavenegarSmsGateway | ParsianSmsGateway { + private activeGateway(): + | KavenegarSmsGateway + | ParsianSmsGateway + | MoalemSmsGateway { + if (getSmsProvider() === "moalem") return this.moalem; return getSmsProvider() === "parsian" ? this.parsian : this.kavenegar; } } diff --git a/src/sms-orchestration/provider/sms-provider.config.ts b/src/sms-orchestration/provider/sms-provider.config.ts index 07e4c4a..59b85fe 100644 --- a/src/sms-orchestration/provider/sms-provider.config.ts +++ b/src/sms-orchestration/provider/sms-provider.config.ts @@ -1,14 +1,15 @@ -export type SmsProviderId = "kavenegar" | "parsian"; +export type SmsProviderId = "kavenegar" | "parsian" | "moalem"; /** Reads `SMS` (e.g. `parsian`) or `SMS_PROVIDER`; defaults to kavenegar. */ export function getSmsProvider(): SmsProviderId { const raw = ( - process.env.SMS ?? - process.env.SMS_PROVIDER ?? + process.env.SMS?.trim() || + process.env.SMS_PROVIDER?.trim() || "kavenegar" ) .trim() .toLowerCase(); + if (raw === "moalem" || raw === "moallem") return "moalem"; if (raw === "parsian") return "parsian"; return "kavenegar"; }