---
title: Centralized Notifications & Email Platform
category: API & Developer Reference
order: 10
badge: Notifications & Email
description: Complete guide and API reference for the centralized Ternis notification system, ecosystem dispatching, template registry, batch notifications, and user consent security.
---

# Centralized Notifications & Email Platform

The **Ternis Notifications & Email Platform** is the centralized communication infrastructure for the entire Ternis ecosystem (`ternis.net`, `ternis.org`, `ternis.dev`, `t-api.de`, `thosted.de`, `ternis.link`).

It delivers synchronized in-app notifications and branded transactional emails, backed by strict zero-spam security boundaries and granular user consent.

---

## 1. Architecture & Security Model

To protect users against unsolicited communications and phishing, any application attempting to send notifications or emails via Ternis Auth must satisfy **four mandatory security tiers**:

```
+-------------------------------------------------------------------+
| 1. Verified Official App Check (is_official == true)             |
+---------------------------------+---------------------------------+
                                  | Pass
+---------------------------------v---------------------------------+
| 2. OAuth Scope Authorization ([email:send] scope present)         |
+---------------------------------+---------------------------------+
                                  | Pass
+---------------------------------v---------------------------------+
| 3. Explicit User Permission (AppEmailPermission.is_allowed == true)|
+---------------------------------+---------------------------------+
                                  | Pass
+---------------------------------v---------------------------------+
| 4. User Channel Preferences (User.prefersEmailFor(category))      |
+---------------------------------+---------------------------------+
                                  | Pass
                        [ Dispatched & Audited ]
```

### Security Guardrails:
1. **Official Applications Only**: Unofficial / third-party sandbox clients cannot send emails under any circumstances (`403 Forbidden`).
2. **Explicit OAuth Scope**: The application token must include the `email:send` scope, requested during OAuth2 authorization.
3. **Explicit User Consent**: Users must explicitly grant email permissions to the application, manageable anytime from the [Notifications Center](/account/notifications) or [Connected Apps](/account/apps).
4. **Preference Filtering**: Even if an application is permitted, users can independently disable category delivery or master email dispatch without revoking token access.
5. **Audit Logging**: Every dispatched notification and email generates an immutable entry in `sso_audit_logs`.

---

## 2. OAuth Scopes

| Scope | Purpose | Who Can Request |
| :--- | :--- | :--- |
| `email:send` | Dispatch transactional notifications and emails to users | Official Ternis Applications |
| `notifications:read` | Read user notifications, statistics, and templates | Any authorized client |
| `ternis:admin` | Broadcast system-wide announcements to user segments | Platform Administrators |

---

## 3. Standard Ecosystem Templates Registry

The platform features pre-registered, localized notification templates. Applications can reference a `template_id` and pass dynamic `template_params` instead of constructing custom copy:

| Template ID | Default Category | Priority | Required Placeholders | Description |
| :--- | :--- | :--- | :--- | :--- |
| `security.login_alert` | `security` | `high` | `{location}`, `{ip_address}`, `{device}` | Alerts user of a new authentication session |
| `security.password_changed` | `security` | `high` | — | Confirmation of password reset or change |
| `security.session_revoked` | `security` | `normal` | `{device_name}` | Notification that an active session was closed |
| `oauth.app_connected` | `app` | `normal` | `{app_name}`, `{scopes}` | Sent when an application is newly authorized |
| `oauth.email_permission_granted` | `app` | `normal` | `{app_name}` | Confirmation of email sending consent |
| `oauth.email_permission_revoked` | `app` | `normal` | `{app_name}` | Sent when user blocks an app from emailing |
| `org.invitation` | `membership` | `high` | `{org_name}`, `{inviter_name}`, `{role}` | Team or organization invitation alert |
| `billing.invoice_ready` | `billing` | `normal` | `{invoice_number}`, `{amount}` | Customer billing notice & receipt availability |
| `platform.maintenance` | `platform` | `normal` | `{service_name}`, `{scheduled_time}`, `{duration}` | Scheduled infrastructure maintenance notice |
| `platform.announcement` | `announcement` | `normal` | `{title}`, `{announcement_body}` | Ecosystem-wide or portal broadcast |

---

## 4. API Endpoints Reference

All endpoints are prefixed with `/api/v1` and require an `Authorization: Bearer <token>` header.

### 4.1. List Available Templates

Retrieve the list of registered ecosystem templates and metadata.

- **Method**: `GET`
- **Path**: `/api/v1/notifications/templates`
- **Scope Required**: `notifications:read` or `email:send`

#### Response (`200 OK`):
```json
{
  "success": true,
  "count": 10,
  "templates": {
    "security.login_alert": {
      "subject": "Security Alert: New Sign-in to Your Account",
      "message": "A new sign-in was detected on your Ternis account from {location} using IP address {ip_address} on {device}. If this was not you, please secure your account immediately.",
      "category": "security",
      "priority": "high",
      "icon": "shield",
      "action_text": "Review Security Sessions",
      "action_url": "/account/security"
    }
  }
}
```

---

### 4.2. Send Single Notification & Email

Sends an in-app database notification and delivers an email if user preferences and consent allow.

- **Method**: `POST`
- **Path**: `/api/v1/notifications/send-email`
- **Scope Required**: `email:send`

#### Request Parameters:

| Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `recipient_id` | `uuid` | Optional | Recipient User UUID. Defaults to authenticated token owner. |
| `recipient_email` | `string` | Optional | Recipient email address (must match an existing user). |
| `template_id` | `string` | Optional | ID of registered template (e.g. `security.login_alert`). |
| `template_params` | `object` | Optional | Key-value mapping for template placeholders. |
| `subject` | `string` | Optional* | Custom subject line (*required if `template_id` omitted). |
| `message` | `string` | Optional* | Plain-text notification content (*required if `template_id` omitted). |
| `action_url` | `url` | Optional | Primary call-to-action button URL. |
| `action_text` | `string` | Optional | Label for primary button (default: `Open Link`). |
| `secondary_action_url` | `url` | Optional | Secondary link URL. |
| `secondary_action_text` | `string` | Optional | Label for secondary action. |
| `category` | `string` | Optional | `app`, `security`, `transactional`, `billing`, `platform`, `announcement` |
| `priority` | `string` | Optional | `low`, `normal`, `high`, `urgent` (default: `normal`). |
| `in_app_only` | `boolean` | Optional | When `true`, prevents email delivery and stores in-app only. |
| `client_id` | `string` | Optional | Passport Client UUID (automatically extracted from token). |

#### Request Example (Using Template):
```json
{
  "recipient_email": "jane@ternis.org",
  "template_id": "security.login_alert",
  "template_params": {
    "location": "Berlin, Germany",
    "ip_address": "194.12.80.5",
    "device": "Safari on macOS"
  }
}
```

#### Request Example (Custom Payload):
```json
{
  "recipient_email": "jane@ternis.org",
  "subject": "Your Ternis Cloud Cluster is Ready",
  "message": "Cluster `k8s-prod-eu1` has been provisioned and is ready for deployments.",
  "category": "app",
  "priority": "normal",
  "action_url": "https://cloud.ternis.net/clusters/k8s-prod-eu1",
  "action_text": "Launch Console",
  "secondary_action_url": "https://cloud.ternis.net/docs/quickstart",
  "secondary_action_text": "View Cluster Docs"
}
```

#### Response (`200 OK`):
```json
{
  "success": true,
  "message": "Notification and email dispatched successfully.",
  "client_id": "9d8e578c-0f9b-4392-8ec1-91a74239851e",
  "client_name": "Ternis Cloud",
  "recipient": {
    "id": "b2f6b897-4001-460d-8386-db93f1d8c1c4",
    "email": "jane@ternis.org",
    "name": "Jane Doe"
  },
  "notification": {
    "subject": "Your Ternis Cloud Cluster is Ready",
    "category": "app",
    "priority": "normal",
    "template_id": null
  },
  "delivered_via": ["database", "mail"],
  "sent_at": "2026-09-25T15:40:00+00:00"
}
```

---

### 4.3. Batch Notification Dispatch

Dispatches up to 100 notifications in a single request. Each item is individually validated and delivered.

- **Method**: `POST`
- **Path**: `/api/v1/notifications/batch`
- **Scope Required**: `email:send`

#### Request Body:
```json
{
  "notifications": [
    {
      "recipient_id": "b2f6b897-4001-460d-8386-db93f1d8c1c4",
      "template_id": "billing.invoice_ready",
      "template_params": {
        "invoice_number": "INV-2026-004",
        "amount": "€49.00"
      }
    },
    {
      "recipient_email": "admin@ternis.net",
      "subject": "Cluster Autoscaling Event",
      "message": "Autoscaler increased cluster size to 8 nodes.",
      "category": "platform"
    }
  ]
}
```

#### Response (`200 OK`):
```json
{
  "total": 2,
  "succeeded": 2,
  "failed": 0,
  "results": [
    {
      "success": true,
      "recipient_id": "b2f6b897-4001-460d-8386-db93f1d8c1c4",
      "recipient_email": "jane@ternis.org",
      "result": { "success": true, "delivered_via": ["database", "mail"] }
    },
    {
      "success": true,
      "recipient_id": "a1b2c3d4-0000-0000-0000-000000000001",
      "recipient_email": "admin@ternis.net",
      "result": { "success": true, "delivered_via": ["database"] }
    }
  ]
}
```

---

### 4.4. Ecosystem Broadcast (Admin Only)

Broadcasts announcements to specified user segments across the platform.

- **Method**: `POST`
- **Path**: `/api/v1/notifications/broadcast`
- **Scope Required**: `ternis:admin` (Caller must have administrative privileges)

#### Request Parameters:

| Field | Type | Required | Values |
| :--- | :--- | :--- | :--- |
| `target` | `string` | Required | `all`, `ternis_members`, `partners`, `customers`, `role` |
| `role` | `string` | Optional | Required if `target == role` (`admin`, `developer`, `member`, `user`) |
| `subject` | `string` | Required | Announcement headline |
| `message` | `string` | Required | Announcement body message |
| `action_url` | `url` | Optional | Relevant link for more details |
| `action_text` | `string` | Optional | Link text (default: `Read More`) |
| `priority` | `string` | Optional | `normal`, `high`, `urgent` |

#### Request Example:
```json
{
  "target": "ternis_members",
  "subject": "Platform Maintenance Scheduled for Sunday",
  "message": "Database migrations will be performed on Sunday between 02:00 and 03:00 UTC.",
  "action_url": "https://status.ternis.net",
  "action_text": "Check Status Page",
  "priority": "high"
}
```

---

### 4.5. Notification Analytics & Stats

Aggregates in-app notification metrics for the authenticated user.

- **Method**: `GET`
- **Path**: `/api/v1/user/notifications/stats`
- **Scope Required**: `notifications:read`

#### Response (`200 OK`):
```json
{
  "total": 42,
  "unread": 3,
  "read": 39,
  "pinned_count": 2,
  "archived_count": 5,
  "by_category": {
    "security": 12,
    "app": 18,
    "billing": 4,
    "platform": 8
  },
  "by_priority": {
    "normal": 35,
    "high": 6,
    "urgent": 1
  }
}
```

---

### 4.6. Notification Organization & In-App Management

| Method | Path | Description |
| :--- | :--- | :--- |
| `GET` | `/api/v1/user/notifications` | List user notifications with filtering (`unread_only`, `category`, `priority`, `limit`) |
| `POST` | `/api/v1/user/notifications/{id}/pin` | Pin or unpin notification to top of list (`pin: true/false`) |
| `POST` | `/api/v1/user/notifications/{id}/archive` | Move notification to archive or restore (`archive: true/false`) |
| `PATCH` | `/api/v1/user/notifications/{id}/read` | Mark individual notification as read |
| `POST` | `/api/v1/user/notifications/read-all` | Mark all unread notifications as read |
| `POST` | `/api/v1/user/notifications/clear-read` | Purge all read notifications permanently |
| `DELETE` | `/api/v1/user/notifications/{id}` | Permanently delete a notification |
| `GET` | `/api/v1/user/notifications/preferences` | Retrieve channel delivery preferences and granted app permissions |
| `PUT` | `/api/v1/user/notifications/preferences` | Update user preferences (`email_notifications`, `security_alerts`, `app_messages`) |
| `POST` | `/api/v1/user/apps/{clientId}/email-permission` | Grant or revoke email sending consent (`allow: true/false`) |

---

## 5. Code Examples

### 5.1. PHP / Laravel (Guzzle / Http Client)

```php
use Illuminate\Support\Facades\Http;

$response = Http::withToken($accessToken)
    ->acceptJson()
    ->post('https://auth.ternis.net/api/v1/notifications/send-email', [
        'recipient_email' => 'member@ternis.org',
        'template_id' => 'security.login_alert',
        'template_params' => [
            'location' => 'Hamburg, Germany',
            'ip_address' => request()->ip(),
            'device' => request()->userAgent(),
        ],
    ]);

if ($response->successful()) {
    $data = $response->json();
    logger()->info("Notification sent: {$data['notification']['subject']}");
} elseif ($response->status() === 403) {
    logger()->warning("Email permission not granted or application is not official.");
}
```

### 5.2. TypeScript / JavaScript (Axios / Fetch)

```typescript
import axios from 'axios';

interface NotificationResponse {
  success: boolean;
  message: string;
  delivered_via: string[];
  notification: {
    subject: string;
    category: string;
  };
}

async function sendAppAlert(token: string, userEmail: string): Promise<void> {
  try {
    const { data } = await axios.post<NotificationResponse>(
      'https://auth.ternis.net/api/v1/notifications/send-email',
      {
        recipient_email: userEmail,
        subject: 'Deployment Completed Successfully',
        message: 'Your static site ternis.link was deployed to the global edge network.',
        category: 'app',
        action_url: 'https://ternis.link/dash',
        action_text: 'Open Dashboard',
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: 'application/json',
        },
      }
    );

    console.log(`Delivered via: ${data.delivered_via.join(', ')}`);
  } catch (error: any) {
    if (error.response?.status === 403) {
      console.error('User has not granted email permission to this application.');
    } else {
      console.error('Failed to dispatch notification:', error.message);
    }
  }
}
```

---

## 6. Error Codes & Troubleshooting

| HTTP Status | Reason | Remedy |
| :--- | :--- | :--- |
| `400 Bad Request` | Missing `subject`/`message` and `template_id`, or unidentified OAuth client | Provide valid template or payload, ensure token contains `client_id` |
| `401 Unauthorized` | Missing, expired, or invalid OAuth Bearer token | Refresh token using OAuth refresh flow |
| `403 Forbidden` | App is not marked `is_official: true`, lacks `email:send` scope, or user revoked permission | Request `email:send` scope and direct user to grant permission in UI |
| `404 Not Found` | Specified `recipient_id` or `recipient_email` does not exist | Verify user identity identifier against UserInfo API |
| `422 Unprocessable` | Validation failed (e.g. invalid URL, invalid category/priority) | Review payload schemas against API documentation |
| `429 Too Many Requests`| Rate limit exceeded | Respect `Retry-After` header and backoff requests |
