Docs

Run a hub, pair, send

For senders: run a hub next to your backend, pair a person, send. About ten minutes from zero to a ringing phone.

Quickstart

You need a public HTTPS domain pointing at the hub: Hansho's relay checks that you control it before it forwards anything to the app.

The hub image is ghcr.io/recodive/hansho-hub; its source is in Recodive/hansho.

Shell
export HUB_MASTER_KEY=$(openssl rand -base64 32)   # keep this: it wraps stored pairing keys
export HUB_PUBLIC_URL=https://hub.example.com

docker volume create hub-data
alias hub='docker run --rm -v hub-data:/data -e HUB_MASTER_KEY -e HUB_PUBLIC_URL -e HUB_DISPLAY_NAME="Acme Ops" ghcr.io/recodive/hansho-hub:0.2'

1 Register with the relay

This creates the hub signing key in the volume and prints the two values to set next.

hub relay register
# HUB_ID=hub_...
# HUB_CHALLENGE_TOKEN=...

2 Run the hub, then verify the domain

Shell
docker run -d --name hub -p 8090:8090 -v hub-data:/data \
  -e HUB_MASTER_KEY -e HUB_PUBLIC_URL -e HUB_DISPLAY_NAME="Acme Ops" \
  -e HUB_ID=hub_... -e HUB_CHALLENGE_TOKEN=... \
  -e HUB_WEBHOOK_URL=https://backend.example.com/hansho-hook -e HUB_WEBHOOK_SECRET=change-me \
  ghcr.io/recodive/hansho-hub:0.2
# put TLS in front (reverse proxy) so https://hub.example.com reaches port 8090
curl https://hub.example.com/.well-known/hansho-challenge   # prints the token
docker exec hub /hub relay verify                             # verified

3 Create an API key

It is printed once; only its hash is stored.

docker exec hub /hub apikey create backend
export KEY=ck_...

4 Create a channel

A channel sets the default level and the highest level its messages may use.

curl
curl -X PUT https://hub.example.com/api/v1/channels/ops \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"name":"Operations","default_level":"active","max_level":"critical"}'

5 Pair a person

Render the returned qr string as a QR code and have the person scan it in the Hansho app. The ticket works once and is valid for 10 minutes. The app shows your display name and verified domain before they approve.

curl
curl -X POST https://hub.example.com/api/v1/pairing-tickets \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"external_user_id":"user-42"}'
# {"ticket":"...","qr":"hansho://pair?hub=https%3A%2F%2Fhub.example.com&t=...&fp=...","expires_at":"..."}

6 Send a message

curl
curl -X POST https://hub.example.com/api/v1/messages \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"external_user_id":"user-42","channel":"ops","title":"Disk full","body":"db-1 is at 97%"}'
# 202 {"message_id":"msg_...","level":"active","devices":1,"status":"queued","deliveries":[...]}

curl -H "Authorization: Bearer $KEY" https://hub.example.com/api/v1/messages/msg_...

That is a ringing phone. Next: send a page, design a template or hear back.

SDKs

8 official SDKs, all MIT, all tested against the same wire contract and the real hub. Everything else talks plain HTTPS and JSON, as in the curl examples above. Source: sdk/ on GitHub.

  • Node and TypeScriptNode 22 or newer. ESM and CommonJS builds, with types, no dependencies.
  • GoGo 1.26 or newer, standard library only.
  • PythonPython 3.9 or newer, standard library only, typed.
  • RubyRuby 3.1 or newer, standard library only.
  • PHPPHP 8.1 or newer, ext-curl and ext-json only.
  • Java and KotlinJava 17 or newer, java.net.http; Jackson for JSON.
  • .NET.NET 8 or newer, no package dependencies, async.
  • RustRust 1.85 or newer, blocking, on ureq with rustls.
Install
Node
# Not on npm yet: until then, build it from sdk/node in Recodive/hansho.
npm install @recodive/hansho
Channel, pairing, message, page
Node
import { Hansho } from "@recodive/hansho";

const hansho = new Hansho({ baseUrl: "https://hub.example.com", apiKey: process.env.HANSHO_API_KEY! });

await hansho.putChannel("ops", { name: "Operations", defaultLevel: "active", maxLevel: "critical" });

// Pairing: render ticket.qr as a QR code; the person scans it in the Hansho app.
const ticket = await hansho.createPairingTicket("user-42");

const res = await hansho.sendMessage({
  externalUserId: "user-42",
  channel: "ops",
  title: "Disk full",
  body: "db-1 is at 97%",
});
console.log(res.messageId, res.status); // msg_... queued

// A page repeats until someone acknowledges it on any device. The channel's
// max_level caps the level, so pages go to a channel that allows them.
await hansho.sendMessage({
  externalUserId: "user-42", channel: "oncall", level: "page",
  title: "Primary DB down", body: "Failover did not complete",
  page: { intervalSeconds: 60, maxRetries: 10 },
});

Levels and pages

  1. passiveLands in the inbox, no sound
  2. activeA normal notification
  3. time-sensitiveBreaks through Focus
  4. criticalSounds even on silent
  5. pageRings until someone acknowledges it on any device

Levels, lowest to highest: passive, active, time-sensitive, critical, page. The delivered level is min(requested ?? channel default, channel max), so send pages to a channel whose max_level is page:

curl -X PUT https://hub.example.com/api/v1/channels/oncall \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"name":"On call","default_level":"critical","max_level":"page"}'

A page is re-sent every interval_s (default 120 seconds) until it is acknowledged on any device; attempts counts those resends. After max_retries (default 5) resends it gets one more interval, then expires.

curl
curl -X POST https://hub.example.com/api/v1/messages \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"external_user_id":"user-42","channel":"oncall","level":"page",
       "title":"Primary DB down","body":"Failover did not complete",
       "page":{"interval_s":60,"max_retries":10}}'

Message status is one of queued, delivered, undeliverable (no reachable device), paging, acked, expired. Encrypted alert payloads above 4096 bytes are rejected with 413 payload_too_large.

Any message can ask for an acknowledgement: add an action with "ack": true, for example {"id":"ack","title":"Acknowledge","ack":true}. The hub reports the answer as message.acked or message.dismissed.

Templates

A template body is a tree of {"type": ...} nodes, at most 8 deep and 64 nodes. One renderer draws it in notifications, Live Activities, widgets and on the watch. Root-only properties: schema (optional; 1 is the only version), and tint and background as {"light":"#RRGGBB","dark":"#RRGGBB"}. Unknown properties are rejected with the field name.

ComponentProperties
vstack, hstackchildren (required), spacing 0-64, align leading/center/trailing, padding 0-32, radius 0-32, background (nested stacks; the root's is the card background)
dividercolor (a 1 pt hairline across the stack it sits in)
spacermin 0-256
texttext (at most 512 characters), style largeTitle/title/headline/body/caption/footnote, color, lines 1-10, align leading/center/trailing, weight regular/medium/semibold/bold
symbolname (SF Symbol), color, size 8-96
imageurl (https), width 0-512, height 0-512, fit fill/fit, radius 0-64
progressvalue 0-1, color, label
gaugevalue, min, max, label, color
timerto (unix seconds), mode countdown/countup, style largeTitle/title/headline/body/caption/footnote, color
badgetext, color, symbol
foreacheach (data path to an array, required), max 1-12, axis vertical/horizontal, spacing 0-64, body (one node, required)

style is one of largeTitle, title, headline, body, caption, footnote. Numeric properties take a literal or {"bind":"path"}. String properties may contain {{path}} placeholders (at most 16 per string). A path is dot-separated keys of [A-Za-z0-9_.-] resolved against the message data, and items.0.name indexes arrays. A missing path renders as empty. There are no expressions; if leaves a node out.

Want to see one drawn? Try it in the template builder: it validates with the hub's rules and previews the result as a notification, a Live Activity and a widget.

foreach

foreach repeats its body once per element of the array at each, at most max copies, laid out along axis. Inside the body, {{item.<path>}} and {"bind":"item.<path>"} read the current element ({{item}} itself for a string or number element) and {{index}} is its 0-based position. Every other path still reads the message data.

  • A missing or non-array each renders nothing.
  • The body may contain containers but not another foreach.
  • The body counts once towards the depth and node limits at save time; the app also caps the expanded result at 64 nodes and drops extra copies.
  • Values read from item are plain text: a placeholder inside a value is never expanded.
Template with foreach
{"type":"vstack","spacing":6,"children":[
  {"type":"text","text":"{{title}}","style":"headline"},
  {"type":"foreach","each":"items","max":5,"spacing":4,"body":
    {"type":"hstack","children":[
      {"type":"text","text":"{{item.title}}"},{"type":"spacer"},
      {"type":"text","text":"{{item.value}}","style":"caption"}]}}]}

Register a template with PUT /api/v1/templates/{id}, then send a message with template_id and data.

curl
# register the template (version must increase), then send data for it
curl -X PUT https://hub.example.com/api/v1/templates/status \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"version":1,"body":{"type":"text","style":"headline","text":"{{title}}"}}'

curl -X POST https://hub.example.com/api/v1/messages \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"external_user_id":"user-42","channel":"ops","template_id":"status",
       "title":"Uptime","body":"99.98%","data":{"title":"Uptime"}}'

Errors are {"error": "<code>"}, with field and message for validation failures, for example body.children[2].type.

Cards and if

On the root stack, padding and radius style the card itself (the defaults are 12 and 16). Any node may carry if: a data path, optionally prefixed with !, and the node is left out unless the value is truthy (with !, unless it is falsy). Falsy values for if are missing, null, false, 0, "", [] and {}; everything else is truthy. Inside a foreach body, if paths can read item.<path> and index. A hidden node and its subtree are dropped, and a hidden foreach copy does not use spare nodes. if adds no node.

Webhooks

Set HUB_WEBHOOK_URL and HUB_WEBHOOK_SECRET on the hub. It POSTs these events:

EventWhen
pairing.createdA person scanned the QR code and paired.
pairing.revokedA pairing was ended.
message.deliveredThe message reached a device.
message.undeliverableNo reachable device.
message.ackedA page, or a message with an ack action, was acknowledged on any device.
message.dismissedThe person dismissed a message that asked to be acknowledged, without acknowledging it.
message.expiredA page ran out of retries without an acknowledgement.
actionA button on a notification was pressed.
activity.endedA Live Activity ended.

The body is:

{"id":"...","event":"message.acked","created_at":"...","data":{...}}

Verify a signature

Each request carries a signature header. Verify it against the raw request body: a body you parsed and re-serialised will not match.

X-Hansho-Webhook-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, t + "." + body)>

A non-2xx answer is retried after 10 s x 2attempt, up to 8 attempts. The SDKs verify signatures in constant time, accept several v1= values for secret rotation, and reject timestamps more than 300 seconds old.

Webhook handler
Node
import express from "express";
import { verifyWebhook, WebhookError } from "@recodive/hansho";

// Verify the raw body: use express.raw before any express.json().
app.post("/hansho-hook", express.raw({ type: "*/*" }), (req, res) => {
  try {
    const event = verifyWebhook({
      secret: process.env.HANSHO_WEBHOOK_SECRET!,
      header: req.get("X-Hansho-Webhook-Signature")!,
      body: req.body, // a Buffer
    });
    switch (event.type) {
      case "message.acked": console.log("acknowledged:", event.data.messageId); break;
      case "action": console.log("button", event.data.actionId, "on", event.data.messageId); break;
    }
    res.sendStatus(200);
  } catch (e) {
    res.sendStatus(e instanceof WebhookError ? 400 : 500); // non-2xx: the hub retries
  }
});

Widget feeds

A feed is data you publish with PUT /api/v1/feeds/{id} for a Hansho widget to draw. In the app, under Settings, Widget feeds, a person picks you as the sender and then chooses from a list of the feeds you have for them. Give a feed a title and the list shows it instead of the id.

A person sees the feeds published for their own external_user_id plus the global ones, published without a user. A person's own feed wins over a global feed with the same id. A feed with no external_user_id is for everyone paired with your hub unless it has an audience, which limits it to some of them. The list is only names. The signed data still comes from the feed's own route, which answers the same people.

The app reads the list from GET /device/v1/feeds, which answers {"feeds":[{"feed_id","title?","updated_at"}]} sorted by id. A hub from before the list existed answers 404 or 405, and the app then asks for the feed id instead.

Audiences and groups

Every channel and every feed has an audience, the rule for who may use it. Give it as "audience": {"mode", "users", "groups"} when you create the channel or feed. mode is everyone (the default for a new channel or feed when you leave it out; a later PUT of a channel without an audience keeps the one it has), only (just the listed users and groups) or except (everyone but them). users are your external_user_ids, also people who have not paired yet; groups are group ids. A feed without its own audience uses its channel's.

A group is a named list of users that you keep yourself: PUT /api/v1/groups/{id} with {"members": [...]} replaces the whole list, GET reads it and DELETE removes it. A change to an audience or a group takes effect at once.

A person outside the audience does not see the channel or feed at all: the hub leaves it out of what the app syncs and out of the feed list, so nothing about it leaks, and the app drops it. Everything else the app does with it is refused with 403 {"error":"no_access"}, which is different from 401 pairing_revoked. Messages already in their inbox stay; widgets for a feed they lost show as unavailable.

A send can name specific users or the channel's audience. A user outside the audience gets the per-recipient result no_access and no message; the others are delivered.

To end a person's whole pairing, DELETE /api/v1/users/{external_user_id}/pairings as before. The app's next request then answers 401 {"error":"pairing_revoked","reason":"kicked"}; reason is left out when the person unpaired on their own device. The app tells the person once which sender ended it, with the verified domain.

Sender API

Every call sends Authorization: Bearer <api key>. Errors are {"error": "<code>"}.

EndpointPurpose
POST /api/v1/pairing-tickets{external_user_id} returns {ticket, qr, expires_at}
DELETE /api/v1/users/{external_user_id}/pairingsUnpair a user everywhere (a kick: the app tells the person once that you ended it)
PUT/GET/DELETE /api/v1/channels/{id}{name, default_level, max_level, sound?, template_id?, thread?, actions?, audience?}
PUT/GET/DELETE /api/v1/groups/{id}{members: [external_user_id]}; PUT replaces the whole list
GET /api/v1/channels, /groups, /templates, /soundsLists: an array of what the matching GET /{id} returns
PUT/GET/DELETE /api/v1/templates/{id}{version, body}; the version must increase; DELETE answers 409 in_use while a channel names it
PUT/GET/DELETE /api/v1/sounds/{id}PUT takes raw audio/x-caf, audio/wav or audio/aiff, at most 1 MB; WAV/AIFF shorter than 30 s. GET returns {id, content_type, bytes, sha256}; DELETE answers 409 in_use while a channel names it
POST /api/v1/messages{external_user_id, channel, level?, title, subtitle?, body, image_url?, template_id?, data?, sound?, actions?, collapse_id?, page?:{interval_s?, max_retries?}} returns 202
GET /api/v1/messages/{id}{status, level, attempts, deliveries, acked_at?}
POST /api/v1/activities, PATCH/DELETE /api/v1/activities/{id}Live Activities (content-state at most 4 KB; update priority 5 or 10)
PUT /api/v1/feeds/{id}{external_user_id?, template_id?, title?, audience?, data}; omit the user for a feed shared by all paired users; title (at most 64 bytes) is the name the app lists it by

Hub configuration

VariableRequiredMeaning
HUB_PUBLIC_URLyesPublic https:// base URL; its host is what the relay verifies and what the app shows
HUB_DISPLAY_NAMEyesSender name shown by the app
HUB_RELAY_URLno (default https://relay.hansho.app)The relay Hansho runs; override it only to test against another relay
HUB_MASTER_KEYyes32 random bytes, base64. Wraps pairing keys at rest; losing it makes stored pairings unusable
HUB_IDyeshub_id from hub relay register; run that command before the first start
HUB_CHALLENGE_TOKENuntil verifiedServed at /.well-known/hansho-challenge
HUB_WEBHOOK_URLnoWhere events are POSTed; empty disables webhooks
HUB_WEBHOOK_SECRETnoHMAC key for webhook signatures
HUB_LA_ENCRYPTno (default true)Encrypt Live Activity content as a blob; false sends plaintext
HUB_ADDRno (default :8090)Listen address
HUB_DB_PATHno (default ./hub.db, /data/hub.db in Docker)SQLite database
HUB_KEY_PATHno (default ./hub.key, /data/hub.key in Docker)Ed25519 hub key
HUB_LOGO_FILEnoPNG logo, 64 to 1024 px each way and at most 256 KB; the app shows it next to your name once someone has paired
HUB_LOGO_URLnoThe same logo from an https URL instead of a file. The hub downloads it once at start and serves it itself
HUB_HOME_URLno (default https://hansho.app)The project site the hub's status page at GET / links to
HUB_ADMINno (default false)true turns on the admin UI at /admin: pair a person, see and remove people, manage API keys, channels, groups, templates and sounds, see feeds and settings
HUB_ADMIN_PASSWORDwith HUB_ADMINThe one password for the admin UI, at least 12 characters; the hub refuses to start without it

Commands: hub serve, hub apikey create <name>, hub relay register, hub relay verify. Opening a hub's address in a browser shows a status page with its name, domain and public key fingerprint.