Add Providers
Adding an SMS provider: a walkthrough
Overview
This page walks a developer who is new to the codebase through adding a new SMS gateway (a "provider adapter") to notifications, from deciding whether you need code at all to sending a message through it on a local stack.
It is a tutorial. For how the pieces work and why, see providers.md, which this page links to instead of repeating:
How providers work
DIGIT's worker providers
Gateway notes
On a 2.12 deployment, which has no provider catalogue, follow Adding an SMS Gateway That Novu Does Not Ship instead. It wires the same worker provider in through the deployment's own files.
The example gateway, AcmeSMS, is fictional. Nothing about it exists in the repo. Every snippet below was applied to a scratch copy of develop, and all of its tests were run: worker, Java, Python and static.
Steps
0. Do you need a provider file at all?
Every provider an operator adds is a Novu integration. Novu's worker sends the message through a provider class, and novu-bridge never carries gateway code. So the question is whether a provider class for your gateway already exists.
Upstream Novu 2.3.0 already ships a provider for it
A catalog entry only: step 6, then steps 7–10. Leave it out of the "worker provider" lists.
Anything else, JSON gateways included
A DIGIT provider file (all steps)
To list the SMS provider IDs that Novu ships:
docker run --rm --entrypoint sh ghcr.io/novuhq/novu/worker:2.3.0 -c \
'cd /usr/src/app/apps/worker && node -e "console.log(Object.values(require(\"@novu/shared\").SmsProviderIdEnum).join(\" \"))"'Why not Novu's generic-sms? It posts its own fixed JSON body, decides success from the HTTP status alone, and reads the message ID from a JSON path. A gateway that rejects with HTTP 200, or replies in plain text, would then be recorded as sent (why the three DIGIT gateways need their own). The catalogue also refuses it: ProviderCatalogTest.noCatalogTypeRidesGenericSmsAnyMore fails if a type uses generic-sms. A provider file is about 80 lines, and it is the only way to read the gateway's own accept-or-reject answer.
A DeliveryProvider inside novu-bridge, which bypasses Novu, is the last resort. It loses Novu's credential store, the activity feed and operator management (providers.md).
The worked example: AcmeSMS (fictional)
Request
POST form-encoded to https://api.acmesms.example/v1/send: account, key, to (digits, no +), sender, text, encoding (gsm or ucs2)
Accepted
Plain-text body OK:<id>
Rejected
Plain-text body ERR:<reason>, with HTTP 200. An outage gives a 5xx HTML page that echoes the posted form.
Operator enters
Account id, API key, sender id, an optional send URL
That is the shape most hand-rolled gateways take: form in, text out, and a 200 that does not mean success. Ozeki shows the JSON variant (see ozeki.js).
1. Write the provider file
AcmeSMS needs the GSM-7 check that Jasmin already has. On develop, fitsGsm7 and toUcs2Hex are defined in jasmin.js, and novu.js does not export them. Do not import them from ./jasmin. That would tie AcmeSMS to the Jasmin provider: renaming or removing Jasmin would break AcmeSMS when the worker boots, and register.js would refuse to start the worker. Shared helpers belong in novu.js, which says so itself ("Shared by the providers below, kept here so the mounted file set stays fixed"). So move them first:
In
backend/novu-bridge/novu-worker-providers/, moveGSM_7_CHARACTERS,toUcs2HexandfitsGsm7(with their comments) fromjasmin.jsinto the shared section ofnovu.js, belowredactedSnippet.Add
fitsGsm7andtoUcs2Hextomodule.exportsinnovu.js.In
jasmin.js, take them from./novu. Keep them in itsmodule.exports, becausetest/jasmin.test.jsimportstoUcs2Hexfrom../jasmin:
Now create backend/novu-bridge/novu-worker-providers/acmesms.js. Copy the shape of smscountry.js or jasmin.js (form-encoded with a plain-text reply), or ozeki.js (JSON):
The rules this follows:
PROVIDER_IDis the NovuproviderId. It must not be one of Novu's own IDs (the command in step 0), becauseregister.jschecks DIGIT's handlers first and would shadow Novu's.Credential keys must be keys Novu's API stores. Novu drops any other key on save, so a made-up name arrives empty. The list is the
credentialsobject of Novu's integration schema, and includesuser,password,apiKey,secretKey,token,apiToken,from,baseUrl,host,portandregion. Put a secret inapiKey,apiToken,secretKey,token,passwordorserviceAccount: Novu encrypts only those keys at rest.Decide success from the body, not the status.
validateStatus: () => truesends every reply, 4xx and 5xx included, to your parser. The parser must throw for anything that is not a clear acceptance. That covers error strings, HTML pages, empty bodies and a bareOK:.Mask what you quote. The error message ends up in Novu's activity feed. Pass gateway text through
redactedSnippet(text, secrets)(orredactfor JSON fields, as inozeki.js), both from./novu. List the username first and the secret second, so that their Basic-auth token is masked too.Leave transport failures alone. On connection refused, reset, DNS failure or timeout,
register.jsturns the axios error into a plain, redactedError(step 4).Unicode. If the gateway needs a flag or a different coding for non-GSM text, decide it per message. Take
fitsGsm7from./novu, never from another provider's file. Jasmin shows the hex-encoded UCS-2 variant (toUcs2Hex).this.transform(bridgeProviderData, {...})merges Novu's_passthroughoverrides. Keep it, even if you think nothing will use it.
2. Register it in register.js
Add the handler to loadHandlers() in backend/novu-bridge/novu-worker-providers/register.js:
Nothing else in register.js changes. Every DIGIT provider gets the same treatment:
The
getHandlerpatch picks it up.The redaction boundary (
sealErrors) wraps itssendMessage.It joins the "registered" log line.
Two optional edits:
If the gateway uses a credential key that is not secret and is not in
PUBLIC_CREDENTIALS(from,baseUrl,senderName,host,port), add the key there. Otherwise, the boundary masks that key's value in error messages.The skip warning in
run()names the providers in prose. Update it if you want the new name to appear there.
3. Unit-test the provider
Create test/acmesms.test.js next to the others. stubHttp (in test/stub-http.js) swaps the provider's axios instance for a recorder:
Cover every reply shape the real gateway produces: success, error string, HTML error page, empty body and rejection with a 200, as well as non-GSM text.
Run the whole suite inside the stock worker image that the providers patch (needs Docker):
The output ends with # fail 0. Then check that each test can fail. Break the behaviour it guards, for example by making parseMessageId accept any body or by dropping the redactedSnippet call. Confirm the test goes red, then restore the file from a copy.
4. Add it to the error-boundary test
test/error-boundary.test.js sends through Novu's own SendMessageSms step against a refused port, a reset socket and an HTTP 500 that echoes the request. It then checks that nothing Novu would store contains a credential. Add the new id to its loop:
If your provider reads a secret from a key other than password, give that key its own value and add the value to LEAKS, so the test hunts for the secret your provider actually sends:
and, in sendThroughNovu():
Do not reuse PASSWORD as the key's value. The boundary masks every secret credential value, so with apiKey: PASSWORD the key would be masked through credentials.password, which a real AcmeSMS integration does not have. The test would then check a credential shape that no deployment has.
What guards what. Each of these was checked by breaking the code and watching the test go red:
The refused and reset cases prove that the boundary covers your provider. They turn red if
sealErrorsdoes not wrap it, because Novu would then store the axios error, posted form included.The HTTP 500 case stays green on your parser's own masking, and on
redact's rule that masks anykey=…pair. So it does not tell you whether the boundary treatsapiKeyas a secret.That is guarded by
anything a provider throws, not only axios errors, is redacted at the boundaryin the same file. It passes anapiKeyand goes red ifapiKeyis added toPUBLIC_CREDENTIALS. If your secret lives in another key (apiToken,secretKey,token), give that test's credentials that key with its own value, put the value in the message the test throws, and assert that it is masked, as the test already does fork-ZZ91.Your parser's masking of the key is guarded by your own unit test (
masks the credentials in an echoed error page).
test/register.test.js pins the registered set, so add acmesms there too:
the id list in
registers our providers on the factory the worker imports;the two sorted
['acmesms', 'jasmin', 'ozeki', 'smscountry']assertions.
Re-run run-tests.sh.
5. Copy the runtime files to the Helm chart
Helm can only read files inside the chart, so the chart carries a byte-identical copy. The tests stay behind, because they live in test/ and the glob below skips that folder:
local-setup/tests/static/deployment-contracts.test.ts fails if the copy drifts. It also pins the file list, in the runtimeFiles(PROVIDERS_SRC) expectation in the helm chart ships the same provider code and mounts + preloads it. runtimeFiles() returns the folder's .js files sorted, and the test compares with toEqual, so insert the new file in alphabetical order rather than appending it. For AcmeSMS it goes first:
To run it:
Compose needs nothing more: ./deploy.sh copies the whole folder to the box (How it is deployed).
6. Add the catalogue entry
backend/novu-bridge/src/main/java/org/egov/novubridge/service/provider/ProviderCatalog.java is what the Configurator's Add Provider form is built from (GET /novu-adapter/v1/providers/catalog), so the form needs no code change (but see the note on field labels below). Edit six places:
Add the form to
allTypes(). The order there is the order the Configurator offers:
The parts of that entry:
Field keys are the Novu credential keys that your handler's
buildProviderreads.toNovuCredentialscopies exactly the declared keys, and a blank optional field is left out, so the provider's default applies.CredentialField.text(key, label, required, placeholder, help),.password(key, label, required, help)and.checkbox(key, label, help)give the field kinds. Usepasswordfor every secret, because the form never echoes it.Put what an operator must know in
help, such as costs, encodings and which API variant. The Configurator shows it under the field.supportsVerify(true)enables Check status, which only checks that the integration exists and is active.supportsTestSend(true)enables Test, which sends a real message.
The Configurator overrides some field labels. ProviderCredentialFields.tsx renders each label as t(credLabelKey(f.key), { _: f.label }). The catalogue label is only the fallback for the translation key app.providers.cred.<key in snake_case>, and a translation always wins. The Configurator's bundled English (configurator/src/providers/i18nProvider.ts) defines that key for account_sid, token, from, host, port, user, password and secure. A configurator-ui localisation message overrides it again. The bundled English is the base for every language. So AcmeSMS's form shows SMTP User for user and From for from, not "Account ID" and "Sender ID". Only apiKey ("API key") and baseUrl ("Send URL") show the catalogue's label. SMSCountry, Ozeki and Jasmin have the same problem today: their user and password fields read SMTP User and SMTP Password.
The lookup is per credential key, not per type. You cannot give one type its own label for a shared key without changing
ProviderCredentialFields.tsx.A key with no translation (
apiKey,baseUrl,secretKey, …) shows the catalogue label. If you add a translation for it underapp.providers.credini18nProvider.ts, that label applies to every type that uses the key, and the catalogue labels for it stop showing.Put anything specific to your gateway in
helpandplaceholder. The Configurator shows those as the catalogue sends them.
For a provider that upstream Novu ships, edit every place above except place 2:
Leave the type out of
WORKER_NOVU_PROVIDERS. Only DIGIT's worker providers are hidden and refused whenNOVU_BRIDGE_DIGIT_WORKER_PROVIDERS=false, and an upstream provider works on every worker.The
NOVU_PROVIDER_*constant holds Novu's provider ID, which can differ from your type id. For example, Novu's ID for Africa's Talking isafricas-talking.Still add the
TYPE_BY_NOVU_SMS_PROVIDERentry, as Twilio has. Without it, an integration created outside the catalogue has no type marker in its identifier (one made in Novu's dashboard, say).deriveTypereturns null for it, and the Configurator cannot rotate it.Use Novu's credential keys. Read them from the handler file in
/usr/src/app/libs/application-generic/build/main/factories/sms/handlers/in the worker image.
7. Update the Java tests
Two test classes pin the catalogue, both under backend/novu-bridge/src/test/java/org/egov/novubridge/. What changes in them depends on whether the type is a DIGIT worker provider (AcmeSMS) or one that upstream Novu ships.
7a. A DIGIT worker provider (AcmeSMS)
In service/provider/ProviderCatalogTest.java:
In
theDigitGatewaysAreNovuProviders_withTheirIdsAndCredentialKeys, add the id and keys toproviderKeys, plus arequiredKeysassertion.Add the new type to the list in
noCatalogTypeRidesGenericSmsAnyMore, inallTypes()order.Add a test that the identifier reads back and the type derives:
In web/controllers/ProviderControllerGuardsTest.java:
In
withTheWorkerProvidersOff_theCatalogHidesThem, changeassertEquals(6, all.size(), …)to7. Leave theList.of("twilio-sms", "twilio-whatsapp", "smtp")assertion alone, because a worker provider is hidden while the worker providers are off.Add the type to the
List.of("smscountry", "ozeki", "jasmin")loop inwithTheWorkerProvidersOff_creatingOne_isRefused_inBothForms.
7b. A type upstream Novu ships
Such a type is neither hidden nor refused when the worker providers are off, so the worker-provider tests above would fail for it. Instead:
In
ProviderCatalogTest, add the type to the list innoCatalogTypeRidesGenericSmsAnyMore, inallTypes()order. LeavetheDigitGatewaysAreNovuProviders_withTheirIdsAndCredentialKeysalone: it covers DIGIT's gateways, and it asserts that the type id equals the Novu id.Add a test of its own. For example, for a type
africastalkingon Novu'safricas-talking(the class needs a static import ofAssertions.assertFalse):
In ProviderControllerGuardsTest.withTheWorkerProvidersOff_theCatalogHidesThem:
Add the type to the
List.of("twilio-sms", "twilio-whatsapp", "smtp")assertion, inallTypes()order, because it stays visible.Change
6to7.Do not add it to the refused loop in
withTheWorkerProvidersOff_creatingOne_isRefused_inBothForms.
Run the suite
Run the whole suite (Java 17), because more than one class pins the catalogue:
8. Mirror the type in the migration script
local-setup/scripts/migrate-notifications.py mirrors the catalogue for the 2.12 → 2.20 migration (migration.md). Under # ── The provider catalog, mirrored from novu-bridge's ProviderCatalog.java, add the type to:
CATALOG_CHANNEL,CATALOG_LABELandCATALOG_REQUIRED: the channel, the label, and the required keys;TYPES_LONGEST_FIRST: the same order as Java.type_from_identifier()andderive_type()read it.TYPE_BY_NOVU_SMS_PROVIDER, mapping the Novu provider id to the type, for every type, as in Java;MOUNTED_PROVIDER_TYPES, for a DIGIT worker provider only. With this entry, the script refuses to create such a provider whilenovu-workerdoes not preloadregister.js.
Add cases to the ProviderIdentifier tests in local-setup/tests/test_notification_seed_decisions.py: an "acmesms-…": "acmesms" identifier, and the id in the derive_type loop. That loop assumes the Novu id and the type id are the same. For an upstream type whose IDs differ, assert it separately, for example derive_type({"providerId": "africas-talking", "channel": "sms"}) == "africastalking". Then run:
9. Update the contract and docs
OpenAPI. Add the type to the
typeenums ofProviderTypeandProviderCreateFromCataloginbackend/novu-bridge/src/main/resources/contract/openapi.yaml(served byContractController). Make the same change in its published copy,docs/releases/2.20/notifications/contract/openapi.yaml. Keep the two files identical.contract/error-codes.md. Update the type list under
NB_UNKNOWN_PROVIDER_TYPE. For a worker provider, also update the "SMSCountry, Ozeki or Jasmin" wording underNB_PROVIDER_UNAVAILABLEandNB_PROVIDER_TYPE_UNAVAILABLE.providers.md. Add a row to the type table and a row to Gateway notes (request, "accepted when…", traps).
setup-guide.md §3. Add a row with the fields the operator fills in.
backend/novu-bridge/novu-worker-providers/README.md. Update the list of providers.Many comments and messages name "SMSCountry, Ozeki and Jasmin" in prose. Behaviour does not depend on them.
git grep -n -i jasminfinds them, so you can decide which should name the new gateway.
10. Try it end to end locally
On a local stack deployed with enable_novu: true (setup-guide.md §2):
Deploy your branch. Build the bridge and its migrator, and pin both in
local-setup/ansible/inventory/host_vars/<tenant>.yml:Use the
:localtag. The deploy's image plan reports a pin ending in:localas "built on this host".A
:localimage exists only on the machine that built it. This works only whendeploy.shtargets that same machine, as it does for a local stack. On any other host,compose pull --ignore-pull-failuresskips the missing image, andup -dthen fails withpull access denied for novu-bridge. To test on a remote box, push both images to a registry the box can pull from and pin those refs instead.Pin
novu_bridge_db_imagetoo. The bridge and its migrator must be the same build, and pinning only one makes the deploy warn. The warning still namespgr_services_image,pgr_services_db_image,digit_user_preferences_service_imageanddigit_user_preferences_service_db_imagewhile those follownotification_stack_tag. That is fine for this test if your branch is based on thedevelopcommit that tag was built from. Otherwise, build and pin those from your branch the same way.
The deploy copies
novu-worker-providers/from this checkout to/opt/digit/novu-worker-providersand restartsnovu-workerwhen the files change. While you only change the provider file, a faster loop is to copy the files there yourself and rundocker restart novu-worker.Check that the worker loaded it. Run
docker logs novu-worker 2>&1 | grep digit-novu-providers. The output should end… registered in the Novu worker: smscountry, jasmin, ozeki, acmesms. A[digit-novu-providers]error means the worker refused to boot; the line says why.Start a mock gateway on the stack's network. The network is
<basename of digit_dir>_egov-network, which isdigit_egov-networkfor/opt/digit. Save this asacme-mock.py:Add the provider. In the Configurator, go to Notifications → Providers → Add Provider and pick AcmeSMS. Fill in the fields as the form labels them (see the label note in step 6): any value for SMTP User (the
userkey, "Account id" in the catalogue),test-keyfor API key,CITYGOVfor From (thefromkey, "Sender id" in the catalogue) andhttp://acme-mock:8080/sendfor Send URL. Then click Create Provider. Log in to a state that owns the providers (who may manage providers).Test it. Use Test on the row, enter a phone number and a message, then Send Test. The button stays disabled until both are filled in.
docker logs acme-mockshows the request, withencoding=gsm.Read the result in the right place. Under View Notification Logs, set Test sends to Show test sends. The row reads Sent (accepted by transport), which means Novu accepted the trigger and nothing more. The gateway's answer is in Novu's activity feed (the Novu dashboard
/novu) and in the mock's log. Send to a number ending0000. The activity feed should showAcmeSMS request failed: number blocked, while the Logs row still reads Sent. Rotate the credentials to a wrong API key, and the feed should showinvalid keywith no key in it.Use it for real. Under Notifications → Channels, select AcmeSMS for SMS and Enable it (setup-guide.md §4). Then file a complaint, and the message appears in the mock's log. Non-GSM text, such as an Amharic template, should arrive with
encoding=ucs2.Clean up. Run
docker stop acme-mock, delete the provider, and remove thenovu_bridge_imageandnovu_bridge_db_imagepins.
Then repeat step 5 against the real gateway with real credentials. That is the only proof that the credentials work. If the gateway sends delivery receipts, see Delivery receipts for a new gateway.
Checklist
Last updated
Was this helpful?