Zum Inhalt springen

Dokumentation

1. Token im Backend erzeugen

Deine App hat einen Signaturschlüssel. Dein Backend weiß ohnehin, wer angemeldet ist, und signiert damit ein kurzlebiges Token, das diesen Nutzer benennt. Der Schlüssel gelangt nie in einen Browser.

import { createHmac } from 'node:crypto'

function mintToken(appId, userId, signingKey, ttlSeconds = 900) {
  const payload = {
    aid: appId,
    sub: userId,                                 // your own user id
    exp: Math.floor(Date.now() / 1000) + ttlSeconds,
    // tnt: workspaceId,                         // optional: one tenant's bell
  }
  const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url')
  const signature = createHmac('sha256', signingKey).update(encoded).digest('base64url')
  return `${encoded}.${signature}`
}

2. Die Glocke auf der Seite platzieren

<script src="https://notifybell.altixcode.com/embed/notify-bell.js" defer></script>

<notify-bell app-id="app_…" token="…" api-url="https://notifybell.altixcode.com"></notify-bell>

Es handelt sich um ein Custom Element – es funktioniert also in React, Vue, Svelte, Rails oder einer einfachen HTML-Seite gleich gut. Setze beim Erneuern einfach das Attribut token neu, und das Element verbindet sich von selbst wieder.

3. Aus dem Backend veröffentlichen

curl -X POST https://notifybell.altixcode.com/api/v1/apps/APP_ID/notifications \
  -H "Authorization: Bearer nb_…" \
  -H "Content-Type: application/json" \
  -d '{
    "subscriberId": "usr_99812",
    "title": "Deployment completed",
    "body": "Your production build v1.4.2 was deployed.",
    "category": "system",
    "actionUrl": "https://app.example.com/deployments/123",
    "dedupeKey": "deploy-123"
  }'

Der Abonnent wird beim ersten Veröffentlichen angelegt, ein Nutzerabgleich ist also nicht nötig. Übergib einen dedupeKey, und ein erneuter Versuch deines Job-Runners lässt die Glocke nicht zweimal klingeln.

Server- und React-SDKs

Lieber ein typisierter Client als rohes HTTP? @notifybell/node veröffentlicht, sendet Broadcasts und erstellt Abonnenten-Tokens, mit Wiederholung bei 429 und 5xx. @notifybell/react rendert die Glocke als Komponente und erneuert ihr Token, bevor es abläuft. Beide stehen unter MIT-Lizenz und sind auf npm.

npm install @notifybell/node @notifybell/react

// server
import { NotifyBell, mintSubscriberToken } from '@notifybell/node'
const app = new NotifyBell({ apiKey: process.env.NOTIFYBELL_API_KEY }).app('app_123')
await app.publish({ subscriberId: user.id, title: 'Your export is ready' })
const token = mintSubscriberToken({ appId: 'app_123', subscriberId: user.id, signingKey })

// React
import { NotifyBell } from '@notifybell/react'
<NotifyBell appId="app_123" token={token} getToken={fetchFreshToken} />

Gestaltung

Das Element wird in einen Shadow Root gerendert: Dein CSS kann es nicht versehentlich umgestalten, und seine Styles können nicht in deine Seite durchsickern. Drei Bereiche sind bewusst nach außen geöffnet:

notify-bell::part(bell)   { color: #64748b; }
notify-bell::part(badge)  { background: #2563eb; }
notify-bell::part(panel)  { border-radius: 4px; }

Sprache, Gestaltung und Ereignisse

Attribute: app-id, token, api-url, lang. Die Eigenschaft strings übersetzt jedes Wort (title, markAll, all, unread, archived, archive, restore, markRead, markUnread, empty, more, required …), strings.categories benennt Kategorien. Ereignisse: notify-bell:click und notify-bell:action sind abbrechbar – mit preventDefault() leiten Sie in der App weiter, statt einen Tab zu öffnen; notify-bell:token-expired fordert ein neues Token an. Das Theme kommt aus dem Dashboard; Ihre eigenen CSS-Variablen am Element (--nb-accent, --nb-badge, --nb-radius) und ::part(bell | badge | panel | toast) haben Vorrang.

const bell = document.querySelector('notify-bell')
bell.strings = {
  title: 'Benachrichtigungen',
  markAll: 'Alle gelesen',
  categories: { billing: 'Rechnungen' },
}
bell.addEventListener('notify-bell:click', (event) => {
  event.preventDefault()            // route in-app instead of opening a tab
  router.push(event.detail.data.path)
})
bell.addEventListener('notify-bell:token-expired', async () => {
  bell.setAttribute('token', await fetchFreshToken())
})

/* CSS */
notify-bell { --nb-accent: #0f766e; --nb-badge: #b91c1c; --nb-radius: 8px; }

Webhooks

Legen Sie auf der Seite „Webhooks“ einen Endpunkt pro App an, und NotifyBell sendet Ereignisse per POST: notification.created, notification.read, notification.seen, notification.clicked, notification.archived, notification.retracted, subscriber.erased. Jede Anfrage trägt NotifyBell-Signature (t=Zeitstempel,v1=HMAC-SHA256 von "Zeitstempel.Body" mit Ihrem Endpunkt-Geheimnis); weisen Sie alles ab, was nicht verifiziert oder älter als fünf Minuten ist. Eine Antwort außerhalb 2xx wird nach 1 Minute, 5 Minuten, 30 Minuten, 2 Stunden und 12 Stunden erneut versucht, dann als fehlgeschlagen markiert und für einen manuellen Neuversuch aufbewahrt. Zustellung mindestens einmal: deduplizieren Sie anhand der id im Payload.

import { createHmac, timingSafeEqual } from 'node:crypto'

// rawBody: the request body exactly as received, before JSON parsing.
function verify(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')))
  const age = Math.abs(Date.now() / 1000 - Number(parts.t))
  if (!parts.t || !parts.v1 || age > 300) return false
  const expected = createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest()
  const given = Buffer.from(parts.v1, 'hex')
  return given.length === expected.length && timingSafeEqual(given, expected)
}

API-Referenz

Backend-Endpunkte erwarten einen API-Schlüssel (Authorization: Bearer nb_…). Inbox-Endpunkte erwarten ein Abonnenten-Token, als Bearer-Header oder ?token=.

Ehrliche Grenzen