Spusher API

Messages can easily be sent through the Spusher API.

To add a subscribe link, HMAC is used with SHA256 encrypted link signing.

You can create a QR code for non-mobile devices or link to it directly on mobile devices.

import { createHmac } from 'crypto'; import { URL } from 'url'; import { stringify } from 'querystring'; /** * Get a signed url for subscribing to a channel * @param {String} secret The secret for the channel * @param {String} channel The id of the channel * @param {String} [userId] Optionally link an id of the user for direct messaging * @param {Number} validTo The time until which this link will be valid in milliseconds elapsed since January 1, 1970 * @returns {String} */ function getSignedUrl({ secret, channel, userId, validTo }) { const params = { validTo, ...(userId ? { userId } : {}) }; const digest = createHmac('sha256', secret) .update(channel) .update(Object.keys(params) .filter(key => key !== 'digest') .sort((a, b) => a.localeCompare(b)) .map(key => params[key]) .join('') ) .digest('hex'); const url = new URL(`/channels/${channel}`, 'https://spusher.nl'); url.hash = '#' + stringify({ ...params, digest }); return url.toString(); }

Sending messages

Sending messages can be done by posting a JSON payload to the url

https://europe-west1-spusher-781ad.cloudfunctions.net/v1
import axios from 'axios'; async function sendMessage() { const channel = process.env.SPUSHER_CHANNEL; const secret = process.env.SPUSHER_SECRET; const api = axios.create({ baseURL: 'https://europe-west1-spusher-781ad.cloudfunctions.net/v1', headers: { authorization: `Bearer ${secret}` } }); try { await api.post(`/${channel}/post`, { body: 'Hello world!', link: '/' }); } catch (e) { if (e.isAxiosError) { throw `Axios request to ${e.config.url} failed with ${e.toString()}`; } else { throw e; } } }