Notifications
The Notifications Module delivers multi-channel communications across email, SMS, mobile push, workspace chat (Slack, Discord, Telegram), outgoing signed webhooks, and in-app inboxes with built-in preference checking and template rendering.
Kirak currently launches with an initial set of 25+ built-in providers across these channels, with additional gateways and regional carriers continuously being integrated by both the core team and community contributors. Custom providers can also be plugged in seamlessly: see Adding a Custom Notification Provider.
All channels fire before_* and after_* hooks on success, trigger dedicated on_*_error hooks on delivery failure, and automatically check user preferences when a user_id is provided.
| Channel | Method | Currently Supported Providers |
|---|---|---|
send_email |
AWS SES, SendGrid, SMTP, Mailgun, Postmark, SparkPost, Brevo, Resend | |
| SMS | send_sms |
AWS SNS, Twilio, Vonage, Plivo, MessageBird, Africa’s Talking, Termii, FastSMS |
| Push | send_push |
Firebase (FCM v1), Apple Push (APNs), Huawei Push Kit, Expo |
Chat (im) |
send_im |
Slack, Discord, Telegram |
| Webhook | send_webhook |
Generic signed HTTP POST with HMAC-SHA256 signatures |
| In-app inbox | send_inbox |
Database-backed notifications model |
| Multi-channel | send_multi |
Broadcasts to any combination of the above in a single call |
Any other provider can be added without modifying the Kirak core: see Adding a Custom Notification Provider.
Installation & Setup
Section titled “Installation & Setup”Install provider-specific extras as needed:
pip install "kirak[notifications-ses]" # Amazon SES (boto3)pip install "kirak[notifications-sns]" # Amazon SNS (boto3)pip install "kirak[notifications-twilio]" # Twilio SMS SDKpip install "kirak[notifications-apn]" # Apple Push Notifications (aioapns)pip install "kirak[all-notifications]" # All notification providers and SDKsZero-Dependency Fast Path: SendGrid, SMTP, Mailgun, Postmark, SparkPost, Brevo, Resend, Vonage, Plivo, MessageBird, Africa’s Talking, Termii, FastSMS, Firebase, Huawei, Expo, Slack, Discord, Telegram, and generic Webhooks call HTTP/REST endpoints directly via
httpx(bundled with Kirak) and require no extra pip packages.
Enable the module in kirak.json:
{ "modules": ["notifications"]}Architectural Pipeline
Section titled “Architectural Pipeline”When an application invokes any notification method, Kirak processes the request through a standardized pipeline ensuring validation, security, preference enforcement, template rendering, and hook execution.
flowchart TD Start["Call send_email / send_sms / send_push / send_im / send_webhook"] --> ValInput["Validate Parameters & Prevent Injection<br/>(Header checks, template paths, attachments)"] ValInput --> HookBefore["Execute before_send_* Hook"] HookBefore --> CheckUser{"Is user_id<br/>provided?"}
CheckUser -- "No" --> ResolveContent["Resolve Content<br/>(Direct payload or Template compile)"] CheckUser -- "Yes" --> CheckEventPref{"Is event_type<br/>provided?"}
CheckEventPref -- "Yes" --> EvalEvent{"User opted out<br/>of event_type?"} EvalEvent -- "Opted Out" --> DenyPref["Raise KirakException<br/>(403 PREFERENCE_DENIED)"] EvalEvent -- "Allowed" --> EvalChannel{"User opted out<br/>of channel?"} CheckEventPref -- "No" --> EvalChannel
EvalChannel -- "Opted Out" --> DenyPref EvalChannel -- "Allowed" --> ResolveContent
ResolveContent --> BrandingInject["Inject Branding Defaults<br/>(company_logo, support_email, website_url)"] BrandingInject --> ProviderRes["Resolve Named Provider Instance<br/>(Read credentials from env vars)"] ProviderRes --> DispatchGate["Dispatch to External Gateway<br/>(AWS, SendGrid, Twilio, Firebase, etc.)"]
DispatchGate -- "Success" --> HookAfter["Execute after_send_* Hook"] HookAfter --> ReturnSuccess["Return Success Envelope<br/>(status=200, data.id)"]
DispatchGate -- "Failure / Exception" --> HookError["Execute on_send_*_error Hook<br/>(Audit logging / Dead-letter queues)"] HookError --> RaiseError["Raise KirakException<br/>(EMAIL_ERROR, SMS_ERROR, etc.)"]Quick Start
Section titled “Quick Start”# From any route, hook, or background task:
# 1. Email (Direct or Template)await kirak.notifications.send_email({ "to": "alice@example.com", "subject": "Welcome to Kirak!", "html_body": "<h1>Welcome aboard, Alice!</h1>", "text_body": "Welcome aboard, Alice!",})
# 2. SMSawait kirak.notifications.send_sms({ "to": "+14155552671", "message": "Your verification code is 482913",})
# 3. Mobile Pushawait kirak.notifications.send_push({ "to": "device-fcm-token-here", "title": "New message", "body": "You received a new message from Alice", "data": {"chat_id": 42},})
# 4. Workspace Chat / IMawait kirak.notifications.send_im({ "to": "C0123456789", # Slack channel id "text": "Deployment to production finished successfully.",})
# 5. Outgoing Signed Webhookawait kirak.notifications.send_webhook({ "event": "order.shipped", "data": {"order_id": 1234, "tracking_number": "TRK987654"},})
# 6. In-App User Inboxawait kirak.notifications.send_inbox({ "user_id": 42, "type": "success", "title": "Order Shipped!", "message": "Your order #1234 is on its way.", "data": {"order_id": 1234}, "link": "/orders/1234",})send_email
Section titled “send_email”The send_email method delivers emails via direct parameters or reusable Python templates.
result = await kirak.notifications.send_email({ # Required "to": "alice@example.com",
# Direct Mode (inline content) "subject": "Welcome to Acme", "html_body": "<p>Hello Alice!</p>", "text_body": "Hello Alice!",
# Template Mode (overrides direct content when template_name is set) # "template_name": "welcome", # "template_params": {"first_name": "Alice"},
# Attachments (optional) # "attachments": True, # "attachment_names": ["invoice.pdf"],
# Optional Preference & Sender Overrides "user_id": 42, # Enables preference checking "event_type": "welcome", # Enables event-level preference checking "from_email": "billing@acme.com", # Overrides email_from_address from kirak.json "provider": "smtp", # Explicit provider instance (default: channel default)})Security Validations
Section titled “Security Validations”Kirak performs strict input sanitization before dispatching email requests:
- Header Injection Prevention: Any carriage return (
\r) or newline (\n) detected into,from_email, orsubjectfails immediately with status400(INVALID_EMAIL_HEADER). This prevents malicious injection ofBcc:,Cc:, or alternate headers. - Template Path Traversal Protection: Passing a
template_namecontaining relative directory traversal tokens (e.g.../../secret) is trapped by the asset resolver and raises400(INVALID_TEMPLATE_NAME). - Attachment Path Confinement: Attachment names are resolved against
notifications.attachment_base_path. Any filename attempting to escape that directory raises400(INVALID_ATTACHMENT_PATHS).
Email Templates & Automatic Branding Injection
Section titled “Email Templates & Automatic Branding Injection”Templates are standalone Python .py files resolved through Asset Resolution. Kirak looks for {assets_path or "assets"}/notifications/templates/email/{template_name}.py in your project, falling back to core bundled templates.
from html import escape
def get_template(params: dict) -> dict: name = params.get("first_name", "there") company_logo = params.get("company_logo", "") support_email = params.get("support_email", "support@example.com")
return { "subject": f"Welcome to Acme, {name}!", "html_body": f""" <div style="font-family: sans-serif;"> <img src="{escape(company_logo)}" alt="Logo" width="120"/> <h1>Welcome aboard, {escape(name)}!</h1> <p>If you have any questions, reach out to {escape(support_email)}.</p> </div> """, "text_body": f"Welcome aboard, {name}! Need help? Email {support_email}.", }Automatic Branding Defaults: When
brandingis declared inkirak.json(branding.logo,branding.support_email,branding.website_url), Kirak automatically populatestemplate_paramswith:
company_logosupport_emailwebsite_urlAny value passed explicitly in
template_paramstakes precedence over thekirak.jsonbranding default.
Important Security Rule: Always escape dynamic values inserted into
html_bodyusinghtml.escape. Kirak does not auto-escape HTML because the same parameters are often used for unescaped plain-text bodies (text_body).
Configuring Providers
Section titled “Configuring Providers”Each notification channel (email, sms, push, im, webhook) supports multiple named provider instances configured in kirak.json. Secrets are never stored in kirak.json; they are read from environment variables matching KIRAK_NOTIFICATION_<CHANNEL>_<INSTANCE>_<FIELD>.
{ "notifications": { "email_from_address": "no-reply@acme.com", "email_from_name": "Acme Notifications", "sms_from_number": "+15551234567", "attachment_base_path": "assets/attachments",
"email": { "default_provider": "ses", "providers": { "ses": { "type": "aws_ses", "aws_region": "us-east-1" }, "smtp": { "type": "smtp", "smtp_host": "smtp.mailgun.org", "smtp_port": 587 } } }, "sms": { "default_provider": "sns", "providers": { "sns": { "type": "aws_sns", "aws_region": "us-east-1" }, "twilio": { "type": "twilio", "from_number": "+15559876543" } } }, "push": { "default_provider": "fcm", "providers": { "fcm": { "type": "firebase" }, "ios": { "type": "apn", "apn_key_path": "certs/AuthKey.p8", "apn_key_id": "ABC123DEFG", "apn_team_id": "TEAM123456", "apn_bundle_id": "com.acme.app" }, "huawei": { "type": "huawei", "app_id": "1234567" }, "expo": { "type": "expo" } } }, "im": { "default_provider": "ops_slack", "providers": { "ops_slack": { "type": "slack" }, "eng_discord": { "type": "discord" }, "alerts_tg": { "type": "telegram" } } }, "webhook": { "default_provider": "billing", "providers": { "billing": { "type": "generic", "url": "https://billing.internal/webhooks/kirak" } } } }}View All Supported Provider Types, Settings & Environment Variables
notifications key |
Type | Description |
|---|---|---|
email_from_address |
string or null | Sender address, e.g. no-reply@example.com. |
email_from_name |
string or null | Sender display name. |
sms_from_number |
string or null | SMS sender number or name, used when a provider instance sets none. |
attachment_base_path |
string or null | Directory email attachment paths are resolved from. |
email |
object | Email providers (e.g. aws_ses, sendgrid, smtp). |
sms |
object | SMS providers (e.g. aws_sns, twilio). |
push |
object | Push providers (e.g. firebase, apn, huawei). |
im |
object | Instant messaging providers (e.g. slack, discord, telegram). |
webhook |
object | Outgoing webhook providers (e.g. generic). |
<INSTANCE> is the provider instance’s name in kirak.json, upper-cased: an instance
named main reads ..._MAIN_....
email / aws_ses (pip install "kirak[notifications-ses]") – Email through Amazon SES.
Credential check (check()): GetSendQuota (also: is the account in the sandbox); a send-only IAM user cannot read it, so that result is unverified.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_region |
kirak.json | required | AWS region, e.g. us-east-1. |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_ACCESS_KEY |
environment | AWS access key ID. Optional: boto3’s default credential chain is used when unset. | |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_SECRET_KEY |
environment | AWS secret access key. Set together with the access key. |
email / sendgrid (no extra install) – Email through SendGrid.
Credential check (check()): GET /v3/scopes; mail.send must be granted.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_API_KEY |
environment | required | SendGrid API key (starts with SG.). |
email / smtp (no extra install) – Email through any SMTP server.
Credential check (check()): Connect, STARTTLS as configured, LOGIN, QUIT; nothing is sent.
| Name | Where | Required / default | Description |
|---|---|---|---|
smtp_host |
kirak.json | required | SMTP server host. |
smtp_port |
kirak.json | default 587 |
SMTP server port. |
smtp_use_tls |
kirak.json | default True |
Use STARTTLS. |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_USERNAME |
environment | SMTP username. Leave unset for a server without authentication. | |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_PASSWORD |
environment | SMTP password. |
email / mailgun (no extra install) – Email through Mailgun.
Credential check (check()): GET /v3/domains/
| Name | Where | Required / default | Description |
|---|---|---|---|
domain |
kirak.json | required | Sending domain, e.g. mg.example.com. |
region |
kirak.json | default us |
Account region: us or eu. |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_API_KEY |
environment | required | Mailgun API key. |
email / postmark (no extra install) – Email through Postmark.
Credential check (check()): GET /server.
| Name | Where | Required / default | Description |
|---|---|---|---|
message_stream |
kirak.json | default outbound |
Message stream to send through. |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_SERVER_TOKEN |
environment | required | Postmark server API token. |
email / sparkpost (no extra install) – Email through SparkPost.
Credential check (check()): GET /api/v1/account; a send-only key cannot read it, so that result is unverified.
| Name | Where | Required / default | Description |
|---|---|---|---|
region |
kirak.json | default us |
Account region: us or eu. |
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_API_KEY |
environment | required | SparkPost API key with the Transmissions: Read/Write permission. |
email / brevo (no extra install) – Email through Brevo (formerly Sendinblue).
Credential check (check()): GET /v3/account.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_API_KEY |
environment | required | Brevo API key (xkeysib-…). |
email / resend (no extra install) – Email through Resend.
Credential check (check()): GET /domains; a sending-only key is reported as valid.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_API_KEY |
environment | required | Resend API key (re_…). |
sms / aws_sns (pip install "kirak[notifications-sns]") – SMS through Amazon SNS.
Credential check (check()): GetSMSSandboxAccountStatus.
| Name | Where | Required / default | Description |
|---|---|---|---|
aws_region |
kirak.json | required | AWS region, e.g. us-east-1. |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_ACCESS_KEY |
environment | AWS access key ID. Optional: boto3’s default credential chain is used when unset. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_SECRET_KEY |
environment | AWS secret access key. Set together with the access key. |
sms / twilio (pip install "kirak[notifications-twilio]") – SMS through Twilio.
Credential check (check()): GET /2010-04-01/Accounts/
| Name | Where | Required / default | Description |
|---|---|---|---|
from_number |
kirak.json | Sender number. Default: notifications.sms_from_number. | |
messaging_service_sid |
kirak.json | Twilio Messaging Service to send from; wins over from_number. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_ACCOUNT_SID |
environment | required | Twilio account SID. |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_AUTH_TOKEN |
environment | required | Twilio auth token. |
sms / vonage (no extra install) – SMS through Vonage (formerly Nexmo).
Credential check (check()): GET /account/get-balance.
| Name | Where | Required / default | Description |
|---|---|---|---|
from_number |
kirak.json | Sender: a phone number, or an alphanumeric sender ID where the provider and country allow one. Default: notifications.sms_from_number. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_API_KEY |
environment | required | Vonage API key. |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_API_SECRET |
environment | required | Vonage API secret. |
sms / plivo (no extra install) – SMS through Plivo.
Credential check (check()): GET /v1/Account/<auth_id>/.
| Name | Where | Required / default | Description |
|---|---|---|---|
from_number |
kirak.json | Sender: a phone number, or an alphanumeric sender ID where the provider and country allow one. Default: notifications.sms_from_number. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_AUTH_ID |
environment | required | Plivo Auth ID. |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_AUTH_TOKEN |
environment | required | Plivo Auth Token. |
sms / messagebird (no extra install) – SMS through MessageBird (Bird).
Credential check (check()): GET /balance.
| Name | Where | Required / default | Description |
|---|---|---|---|
from_number |
kirak.json | Sender: a phone number, or an alphanumeric sender ID where the provider and country allow one. Default: notifications.sms_from_number. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_ACCESS_KEY |
environment | required | MessageBird access key. |
sms / africastalking (no extra install) – SMS through Africa’s Talking.
Credential check (check()): GET /version1/user (the account balance); username sandbox is test mode.
| Name | Where | Required / default | Description |
|---|---|---|---|
username |
kirak.json | required | Africa’s Talking app username; sandbox uses the sandbox API. |
from_number |
kirak.json | Registered short code or alphanumeric sender ID. Default: notifications.sms_from_number, else Africa’s Talking’s shared sender. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_API_KEY |
environment | required | Africa’s Talking API key. |
sms / termii (no extra install) – SMS through Termii.
Credential check (check()): GET /api/get-balance.
| Name | Where | Required / default | Description |
|---|---|---|---|
base_url |
kirak.json | default https://api.ng.termii.com |
Your account’s API base URL, shown on the Termii dashboard. |
channel |
kirak.json | default generic |
Route: generic (promotional) or dnd (transactional, e.g. OTPs; needs activation by Termii). |
from_number |
kirak.json | Sender: a phone number, or an alphanumeric sender ID where the provider and country allow one. Default: notifications.sms_from_number. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_API_KEY |
environment | required | Termii API key. |
sms / fastsms (no extra install) – SMS through FastSMS (UK).
Credential check (check()): Action=CheckCredits.
| Name | Where | Required / default | Description |
|---|---|---|---|
from_number |
kirak.json | Sender: a phone number, or an alphanumeric sender ID where the provider and country allow one. Default: notifications.sms_from_number. | |
KIRAK_NOTIFICATION_SMS_<INSTANCE>_TOKEN |
environment | required | FastSMS API token (NetMessenger account settings). |
push / firebase (no extra install) – Push notifications through Firebase Cloud Messaging.
Credential check (check()): An OAuth token for the service account, then a dry-run send to an invalid device token; nothing is delivered.
| Name | Where | Required / default | Description |
|---|---|---|---|
firebase_project_id |
kirak.json | Firebase project ID. Default: the project_id in the service account key. | |
KIRAK_NOTIFICATION_PUSH_<INSTANCE>_CREDENTIALS_JSON |
environment | required | Firebase service account key file contents (JSON, on one line). |
push / apn (pip install "kirak[notifications-apn]") – Push notifications to Apple devices through APNs.
Credential check (check()): A push to an invalid device token; nothing is delivered.
| Name | Where | Required / default | Description |
|---|---|---|---|
apn_key_path |
kirak.json | required | Path of the .p8 signing key file. |
apn_key_id |
kirak.json | required | Key ID of the signing key. |
apn_team_id |
kirak.json | required | Apple developer team ID. |
apn_bundle_id |
kirak.json | required | App bundle ID (the APNs topic). |
apn_use_sandbox |
kirak.json | default False |
Send through the APNs sandbox (development builds). |
push / huawei (no extra install) – Push notifications to Huawei devices through Push Kit.
Credential check (check()): POST the OAuth token URL (client credentials).
| Name | Where | Required / default | Description |
|---|---|---|---|
app_id |
kirak.json | required | Huawei app ID. |
KIRAK_NOTIFICATION_PUSH_<INSTANCE>_CLIENT_SECRET |
environment | required | Huawei app client secret. |
push / expo (no extra install) – Push notifications to Expo apps through the Expo push service.
Credential check (check()): None: Expo has no endpoint that checks an access token without sending.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_PUSH_<INSTANCE>_ACCESS_TOKEN |
environment | Expo access token, needed only when push security is enabled for the project. |
im / slack (no extra install) – Messages to Slack channels.
Credential check (check()): POST auth.test; the token must have chat:write.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_IM_<INSTANCE>_BOT_TOKEN |
environment | required | Bot token. |
im / discord (no extra install) – Messages to Discord channels.
Credential check (check()): GET /users/@me.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_IM_<INSTANCE>_BOT_TOKEN |
environment | required | Bot token. |
im / telegram (no extra install) – Messages to Telegram chats.
Credential check (check()): getMe.
| Name | Where | Required / default | Description |
|---|---|---|---|
KIRAK_NOTIFICATION_IM_<INSTANCE>_BOT_TOKEN |
environment | required | Bot token. |
webhook / generic (no extra install) – Signed HTTP POST to your own systems.
Credential check (check()): None: a receiver can only be tested by sending to it; the url is checked.
| Name | Where | Required / default | Description |
|---|---|---|---|
url |
kirak.json | Destination URL. | |
allow_url_override |
kirak.json | default False |
Let a call pass its own destination URL. |
timeout |
kirak.json | default 10.0 |
Request timeout in seconds. |
KIRAK_NOTIFICATION_WEBHOOK_<INSTANCE>_SECRET_KEY |
environment | HMAC signing key; requests are unsigned when unset. |
Error Handling & Failure Categories
Section titled “Error Handling & Failure Categories”When a notification gateway cannot deliver, Kirak raises a KirakException with the channel’s specific error code (EMAIL_ERROR, SMS_ERROR, PUSH_ERROR, IM_ERROR, WEBHOOK_ERROR).
The details.kind field categorizes the root cause:
details.kind |
HTTP Status | Meaning | Recovery / Action |
|---|---|---|---|
rejected |
400 | The provider rejected the payload (invalid email format, blocked bot, invalid phone number, unregistered push device tokens). | Do not retry automatically. Fix the recipient address or token. |
unavailable |
502 | Gateway is down, timed out, rate-limited, or provider account is exhausted / credentials invalid. | Safe to retry with exponential backoff via the Scheduler module. |
unexpected |
500 | Internal library or unexpected server exception. | Inspect application trace logs. |
send_sms
Section titled “send_sms”result = await kirak.notifications.send_sms({ "to": "+14155552671", # International E.164 format "message": "Your verification code is 482913. Expires in 10 minutes.", "user_id": 42, # Optional: checks user preference "event_type": "otp", # Optional: event-level preference check})SMS templates are loaded from assets/notifications/templates/sms/{template_name}.py:
# Using the built-in 'otp' templateawait kirak.notifications.send_sms({ "to": "+14155552671", "template_name": "otp", "template_params": {"otp": "482913", "expires_minutes": 10},})send_push
Section titled “send_push”Delivers mobile push notifications to Android, iOS, and cross-platform Expo apps:
result = await kirak.notifications.send_push({ "to": "fcm-registration-token-or-list", # Single token str or list of tokens "title": "New Order Received", "body": "Order #1234 has been confirmed.", "data": {"order_id": 1234, "status": "confirmed"}, "user_id": 42, "provider": "fcm", # Optional instance name})Every push provider (APNs, Firebase, Expo, Huawei) answers with the same keys:
{"data": { "message": "Push notification sent via Firebase FCM", "success_count": 1, "failure_count": 1, "ids": ["projects/my-app/messages/0:1712"], "failures": [ {"token": "dX9...", "error": "INVALID_TOKEN", "gateway_error": "UNREGISTERED", "invalid_token": true} ]}}ids: the provider’s message ids of the delivered sends. Huawei gives one id for the whole send.failures: one entry per token the provider reported as failed.erroris the same on every provider:INVALID_TOKEN(the token is malformed or no longer registered: delete it),UNAVAILABLE(the provider was not reached or throttled: retry later) orREJECTED(anything else).gateway_erroris the provider’s own code (Unregistered,UNREGISTERED,DeviceNotRegistered…). Huawei names only its illegal tokens, so itsfailure_countcan be larger than itsfailureslist.
If some tokens fail while others succeed, the send returns 200 OK with the counts. It raises PUSH_ERROR only when no token was delivered; the error’s details.failures then has the same entries, so an app can still delete the dead tokens:
try: await kirak.notifications.send_push({"user_id": 42, "title": "Hi", "body": "..."})except KirakException as e: dead = [f["token"] for f in (e.details or {}).get("failures", []) if f["invalid_token"]]send_im (Chat / Workspaces)
Section titled “send_im (Chat / Workspaces)”Posts messages to team chat platforms:
result = await kirak.notifications.send_im({ "to": "C0123456789", # Slack channel ID or Telegram chat ID "text": "Production deployment complete", # Plain-text message "blocks": [ # Optional Slack Block Kit blocks { "type": "section", "text": {"type": "mrkdwn", "text": "*Deploy Succeeded*\nVersion: `v1.2.0`"} } ], "provider": "ops_slack", # Target instance under notifications.im})send_webhook
Section titled “send_webhook”Dispatches signed HTTP POST events to external systems:
result = await kirak.notifications.send_webhook({ "event": "order.completed", "data": {"order_id": 1234, "total": 99.00}, "provider": "billing",})Webhook Signatures & Verification
Section titled “Webhook Signatures & Verification”When the webhook instance is configured with a secret key (KIRAK_NOTIFICATION_WEBHOOK_<INSTANCE>_SECRET_KEY), Kirak signs every payload and includes verification headers:
X-Kirak-Timestamp: Unix epoch timestamp in seconds.X-Kirak-Signature:sha256=followed by the hex HMAC-SHA256 signature calculated over"<timestamp>.<raw_body>".
Receiver Verification Example (Python):
import hashlibimport hmac
def verify_kirak_webhook(secret: str, timestamp: str, raw_body: bytes, signature_header: str) -> bool: payload_to_sign = f"{timestamp}.".encode("utf-8") + raw_body expected_sig = "sha256=" + hmac.new(secret.encode("utf-8"), payload_to_sign, hashlib.sha256).hexdigest() return hmac.compare_digest(expected_sig, signature_header)SSRF Protection: If
allow_url_override: trueis configured, callers can supply a custom destination via"to": "https://...". Kirak resolves the target domain before connecting and blocks private IP ranges (RFC 1918), localhost, loopback addresses, and link-local cloud metadata services (169.254.169.254) with status400(WEBHOOK_URL_NOT_ALLOWED).
Do not pass user input as
to. The check resolves the host once and does not pin the address it found, so a host can resolve to a public address during the check and to a private one when the request connects (DNS rebinding). Set the webhook URL inkirak.jsonor from server-side configuration.
send_inbox (Database In-App Inbox)
Section titled “send_inbox (Database In-App Inbox)”Stores in-app notifications in the database (the notifications model):
result = await kirak.notifications.send_inbox({ "user_id": 42, # Required recipient "type": "info", # "info", "warning", "success", "error", "custom" "title": "Welcome Bonus Applied", "message": "You received 50 free credits.", "data": {"credits": 50}, # Arbitrary JSON metadata "link": "/billing/credits", # Deep link in frontend "event_type": "rewards", # Enables event-level preference checks})user_id, title and message are required; any other key is refused (400 VALIDATION_ERROR).
The send fires before_send_inbox and after_send_inbox, as the other channels do. REST:
POST /notifications/send-inbox (admin or system).
Managing the Inbox Programmatically
Section titled “Managing the Inbox Programmatically”Access the inbox API via kirak.notifications.inbox:
inbox = kirak.notifications.inbox
# 1. Fetch unread notificationsunread = (await inbox.fetch_unread({"user_id": 42, "limit": 20}))["data"]
# 2. Fetch all notifications with paginationall_items = (await inbox.fetch_all({"user_id": 42, "limit": 20, "offset": 0}))["data"]
# 3. Get unread count for badge indicatorscount = (await inbox.count_unread({"user_id": 42}))["data"]["count"]
# 4. Mark notifications readawait inbox.mark_read({"notification_id": 99, "user_id": 42})await inbox.mark_all_read({"user_id": 42})
# 5. Delete notification (soft delete)await inbox.delete({"notification_id": 99, "user_id": 42})send_multi (Multi-Channel Broadcast)
Section titled “send_multi (Multi-Channel Broadcast)”send_multi broadcasts an alert across multiple channels simultaneously while enforcing event-level and channel-level preference checks.
flowchart TD Start["Call send_multi(channels=['email', 'sms', 'in_app'], event_type='order_shipped')"] --> EventCheck{"Is user opted out<br/>of event_type?"} EventCheck -- "Yes (Opted Out)" --> AbortAll["Abort Entire Request<br/>Raise 403 PREFERENCE_DENIED"] EventCheck -- "No (Allowed)" --> Loop["Iterate Over Requested Channels"]
Loop --> ChanPref{"Channel preference enabled?"} ChanPref -- "No (Opted Out)" --> SkipChan["results[channel] = 403 USER_OPTED_OUT<br/>(Continue loop)"] ChanPref -- "Yes" --> DispatchChan["Dispatch send_<channel>()"]
DispatchChan -- "Success" --> RecordSuccess["results[channel] = Success Envelope"] DispatchChan -- "Error" --> RecordError["results[channel] = Error Envelope"]
SkipChan --> CheckDone{"All channels processed?"} RecordSuccess --> CheckDone RecordError --> CheckDone
CheckDone -- "No" --> Loop CheckDone -- "Yes" --> EvalTotal{"Did at least ONE<br/>channel succeed?"}
EvalTotal -- "Yes" --> ReturnPartial["Return 200 OK<br/>data.results = {email: 200, sms: 403, ...}"] EvalTotal -- "No (All Failed)" --> RaiseTotal["Raise 500 MULTI_SEND_FAILED<br/>details.results contains all errors"]result = await kirak.notifications.send_multi({ "user_id": 42, "channels": ["email", "sms", "in_app"], "event_type": "security_alert", "data": { "email": { "to": "alice@example.com", "subject": "New sign-in from Chrome", "html_body": "<p>A new sign-in occurred on your account.</p>", }, "sms": { "to": "+14155552671", "message": "Acme Security: New sign-in detected on your account.", }, "in_app": { "type": "warning", "title": "New Sign-in", "message": "New sign-in detected from 192.0.2.1.", "link": "/security/sessions", }, },})Response Format on Partial Success:
{ "statusCode": 200, "status": "success", "data": { "results": { "email": { "statusCode": 200, "status": "success", "data": { "id": "ses-msg-12345" } }, "sms": { "statusCode": 403, "status": "error", "error": "USER_OPTED_OUT", "message": "User opted out of this channel" }, "in_app": { "statusCode": 200, "status": "success", "data": { "id": 105, "title": "New Sign-in" } } } }}User Preferences Engine
Section titled “User Preferences Engine”The Preferences Engine uses an opt-out model: all notifications are enabled by default until a user record is explicitly created in notification_preferences.
prefs = kirak.notifications.preferences
# 1. Query current channel statusis_email_on = (await prefs.is_channel_enabled({"user_id": 42, "channel": "email"}))["data"]["enabled"]
# 2. Query specific event type statusis_marketing_on = (await prefs.is_event_enabled({"user_id": 42, "event_type": "marketing"}))["data"]["enabled"]
# 3. Update preferencesawait prefs.set_channel_preference({"user_id": 42, "channel": "sms", "enabled": False})await prefs.set_event_preference({"user_id": 42, "event_type": "marketing", "enabled": False})
# 4. Fetch all user preferencesall_prefs = (await prefs.get_all_preferences({"user_id": 42}))["data"]
# 5. Reset preferences back to system defaultsawait prefs.reset_to_defaults({"user_id": 42})System Permission Elevation: When Kirak checks preferences during a send, it reads the preference table in system context (
as_system()). This ensures that background tasks, webhooks, or routes executed by other users can verify recipient preferences without being blocked by row-level access control.
Hooks & Error Interception
Section titled “Hooks & Error Interception”All notification channels fire lifecycle hooks allowing custom logging, auditing, and fallback handling:
# 1. Success Hook: Executes only after successful gateway delivery@kirak.notifications.hook("after_send_email")async def audit_email_delivery(result): message_id = result["data"]["id"] print(f"Email delivered with ID: {message_id}") return result
# 2. Error Hook: Executes when a provider fails or network fails@kirak.notifications.hook("on_send_email_error")async def handle_email_failure(payload): # payload contains: # - payload["params"]: Original send parameters # - payload["provider"]: Provider instance name # - payload["error"]: {"code", "message", "status_code", "details"} print(f"Email delivery to {payload['params'].get('to')} failed: {payload['error']}") # Enqueue fallback SMS or push alert here...The error hooks available across the channels are:
on_send_email_erroron_send_sms_erroron_send_push_erroron_send_im_erroron_send_webhook_error
HTTP REST Endpoints
Section titled “HTTP REST Endpoints”When "notifications" is enabled in kirak.json, the router exposes REST endpoints under /notifications:
Send Operations (Admin / System Role Required)
Section titled “Send Operations (Admin / System Role Required)”| Method | Path | Description |
|---|---|---|
POST |
/notifications/send-email |
Dispatches an email |
POST |
/notifications/send-sms |
Dispatches an SMS |
POST |
/notifications/send-push |
Dispatches a push notification |
POST |
/notifications/send-im |
Posts a chat message |
POST |
/notifications/send-webhook |
Sends a signed webhook |
POST |
/notifications/send-inbox |
Creates an in-app inbox notification |
POST |
/notifications/send-multi |
Broadcasts to multiple channels |
Inbox & Preferences Operations (Authenticated User Scoped to Own user_id)
Section titled “Inbox & Preferences Operations (Authenticated User Scoped to Own user_id)”| Method | Path | Query / Body | Description |
|---|---|---|---|
GET |
/notifications/inbox |
?user_id=42&limit=50&offset=0 |
Retrieve inbox items |
GET |
/notifications/inbox/unread |
?user_id=42&limit=50 |
Retrieve unread items |
GET |
/notifications/inbox/count/unread |
?user_id=42 |
Count unread items |
PUT |
/notifications/inbox/{id}/read |
?user_id=42 |
Mark single item as read |
PUT |
/notifications/inbox/read-all |
?user_id=42 |
Mark all items as read |
DELETE |
/notifications/inbox/{id} |
?user_id=42 |
Delete item (soft delete) |
GET |
/notifications/preferences |
?user_id=42 |
Retrieve all user preferences |
PUT |
/notifications/preferences/channel/{channel} |
{"user_id": 42, "enabled": false} |
Update channel opt-out |
PUT |
/notifications/preferences/event/{event_type} |
{"user_id": 42, "enabled": false} |
Update event opt-out |
POST |
/notifications/preferences/reset |
{"user_id": 42} |
Reset preferences to defaults |
Adding a Custom Notification Provider
Section titled “Adding a Custom Notification Provider”Create a custom provider by subclassing the base class for the channel (EmailProvider, SMSProvider, PushProvider, IMProvider, or WebhookProvider from kirak.notifications.providers.base):
import httpxfrom kirak.core.http import KIND_UNAVAILABLE, kind_for_status, provider_errorfrom kirak.notifications.providers.base import EmailProvider
class CustomMailProvider(EmailProvider): TYPE_NAME = "custom_mail" SECRET_FIELDS = ("api_key",) # Reads KIRAK_NOTIFICATION_EMAIL_<INSTANCE>_API_KEY
def __init__(self, config, notifications=None): super().__init__(config, notifications) self._require("api_key", "endpoint")
async def send(self, to_email, from_email, subject, html_body, text_body, attachments=None, **kwargs): try: async with httpx.AsyncClient() as client: res = await client.post( self.config["endpoint"], json={ "to": to_email, "from": from_email, "subject": subject, "html": html_body, "text": text_body, }, headers={"Authorization": f"Bearer {self.config['api_key']}"}, timeout=10.0, ) res.raise_for_status() data = res.json() return {"id": data.get("message_id")} except httpx.HTTPStatusError as e: raise provider_error( "EMAIL_ERROR", kind_for_status(e.response.status_code), reason=e.response.reason_phrase, provider_status=e.response.status_code, ) from e except httpx.TransportError as e: raise provider_error("EMAIL_ERROR", KIND_UNAVAILABLE, reason="Connection failed") from eRegister the provider in your application’s on_kirak_ready hook:
def on_kirak_ready(kirak): kirak.notifications.register_provider("email", "custom_mail", CustomMailProvider)Configure your custom instance in kirak.json:
{ "notifications": { "email": { "default_provider": "my_mail", "providers": { "my_mail": { "type": "custom_mail", "endpoint": "https://api.custom-mail.io/v1/send" } } } }}