forked from Yara724/api
feat: add Moalem MIC SMS provider with shared token cache
This commit is contained in:
@@ -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=<provided privately by MIC>
|
||||
MIC_SMS_CLIENT_SECRET=<provided privately by MIC>
|
||||
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.
|
||||
Reference in New Issue
Block a user