Skip to content

nova ​

@c9up/nova: Web Push notifications for ream: VAPID signing, encrypted delivery to the browsers' push services, a subscription endpoint and a service worker scaffold. Guide: Push notifications.

Installation ​

bash
pnpm add @c9up/nova
ream configure @c9up/nova

ream configure @c9up/nova adds the provider and the nova:vapid:generate command, the NOVA_STORE and NOVA_VAPID_* variables to .env, and writes config/nova.ts, the push_subscriptions migration and public/sw.js. Optional peers: @c9up/ream (provider and routes), @c9up/atlas (the SQL store's connection), @c9up/quasar (a Redis store named by connection).

Entry points ​

ImportContents
@c9up/novaThe Nova sender, defineConfig, the stores factories and the store classes, the subscribe controller, VAPID key generation, the provider class and the error class.
@c9up/nova/providerNovaProvider (default export).
@c9up/nova/services/mainThe application's Nova (default export), usable once the provider booted.
@c9up/nova/clientBrowser helpers: register the service worker, subscribe, unsubscribe.
@c9up/nova/configureconfigure(codemods), run by ream configure @c9up/nova.
@c9up/nova/commandsThe command loader (getMetaData, getCommand) for nova:vapid:generate.
@c9up/nova/testingFakeNova, a test double that records pushes.

Exports ​

@c9up/nova ​

ExportKindDescription
NovaclassEncrypts and sends pushes to one subscription or to every subscription of a user.
PushPayloadinterfaceThe notification sent.
PushOptionsinterfacePer-push ttl, urgency, topic.
PushUrgencytype'very-low' | 'low' | 'normal' | 'high'.
PushResulttypeThe outcome of one push.
PushFailureReasontypeWhy a push was not delivered.
NovaDeliveryOptionsinterfaceHow pushes leave the server.
PushTargetPolicyinterfaceWhich hosts a push may go to.
PushHttpClientinterfaceThe client pushes go through.
DEFAULT_PUSH_SERVICESconstThe push services allowed by default.
defineConfigfunctionTypes the nova config.
NovaConfiginterfaceThe nova config.
NovaVapidConfiginterfaceThe VAPID identity.
NovaRouteMiddlewaretypeA middleware for the subscription routes.
storesconstFactories for the configured stores: memory, file, sql, redis.
SubscriptionStoreFactorytype() => SubscriptionStore.
SubscriptionStoreinterfaceWhere subscriptions are kept.
PushSubscriptioninterfaceA browser's subscription.
SaveSubscriptionOptionsinterface{ maxPerUser?: number }.
MemorySubscriptionDriverclassAn in-memory store.
FileSubscriptionStoreclassA store in one JSON file.
SqlSubscriptionStoreclassA store in the push_subscriptions table.
SqlSubscriptionStoreOptions, SubscriptionDatabase, SubscriptionDatabaseResolvertypeThe SQL store's options and connection.
RedisSubscriptionStoreclassA store in Redis.
RedisSubscriptionStoreOptions, SubscriptionRedisClient, SubscriptionRedisResolvertypeThe Redis store's options and client.
quasarConnectionfunctionA @c9up/quasar connection by name, checked for the commands the Redis store issues.
SubscribeControllerclassThe handler behind the subscription routes.
generateVapidKeysfunctionMints a VAPID key pair.
VapidKeyPairinterface{ publicKey: string; privateKey: string }, base64url.
NovaProviderproviderAlso the default export of @c9up/nova/provider.
NovaAppContextinterfaceWhat the provider reads of the application.
errorsnamespaceThe package's errors, one class per code, see Errors

Nova ​

MemberSignatureDescription
constructornew Nova(store: SubscriptionStore, vapidConfig: NovaVapidConfig | undefined, delivery?: NovaDeliveryOptions)
pushpush(subscription: PushSubscription, payload: PushPayload, options?: PushOptions): Promise<PushResult>Sends one push. An endpoint outside the allowed push services is refused; keys nothing can be encrypted for are deleted from the store; a payload over 3993 bytes once serialised is not sent (too-large). A subscription the push service reports gone is deleted (cleaned: true).
pushToUserpushToUser(userId: string | number | bigint, payload: PushPayload, options?: PushOptions): Promise<PushResult[]>Pushes to every subscription of userId (a number or bigint is looked up as its decimal text), at most concurrency at once; one result per subscription, and one failing device never stops the others.
PushPayload fieldTypeDescription
titlestringRequired.
body, icon, url, tagstringOptional.
dataRecord<string, unknown>Optional.
PushOptions fieldTypeDefaultDescription
ttlnumber60Time to live, in seconds.
urgencyPushUrgency'normal'The push service's urgency hint.
topicstringReplaces an undelivered notification with the same topic; at most 32 base64url characters.
ts
type PushFailureReason = 'refused' | 'gone' | 'rate-limited' | 'too-large' | 'rejected' | 'server-error'

type PushResult =
  | { ok: true; status: number; endpoint: string }
  | { ok: false; status: number; endpoint: string; reason: PushFailureReason; cleaned: boolean; retryAfter?: number }

retryAfter is the push service's Retry-After on a 429 or 503, in seconds, capped at a day.

SubscriptionStore ​

MemberSignatureDescription
savesave(userId: string, subscription: PushSubscription, options?: SaveSubscriptionOptions): Promise<void>Stores the subscription for userId, then evicts that user's oldest past maxPerUser (default 20).
listByUserlistByUser(userId: string): Promise<PushSubscription[]>The user's subscriptions.
deletedelete(endpoint: string): Promise<void>Forgets endpoint, whoever holds it.
deleteForUserdeleteForUser(userId: string, endpoint: string): Promise<boolean>Forgets endpoint only if userId holds it, in one step; answers whether it did.

PushSubscription is { endpoint: string; expirationTime: number | null; keys: { p256dh: string; auth: string } }.

StoreConstructorNotes
MemorySubscriptionDrivernew MemorySubscriptionDriver()Forgets everything on restart.
FileSubscriptionStorenew FileSubscriptionStore(path: string)One JSON file, absolute or relative to the process; single process.
SqlSubscriptionStorenew SqlSubscriptionStore(db: SubscriptionDatabaseResolver, options?: { table?: string })table defaults to 'push_subscriptions' and must be a plain identifier. db is a connection with execute and query (and dialect: 'postgres' for $1 placeholders), or a function answering one.
RedisSubscriptionStorenew RedisSubscriptionStore(redis: SubscriptionRedisResolver, options?: { prefix?: string })prefix defaults to 'nova:push' and may not contain a space. The client needs get, evalsha and script.

stores ​

FactorySignature
stores.memorymemory(): SubscriptionStoreFactory
stores.filefile(options: { path: string }): SubscriptionStoreFactory
stores.sqlsql(options: { connection: SubscriptionDatabaseResolver; table?: string }): SubscriptionStoreFactory
stores.redisredis(options: { connection: SubscriptionRedisResolver | string; prefix?: string }): SubscriptionStoreFactory

Factories are lazy: only the selected store is built. A string connection for redis names a @c9up/quasar connection.

FunctionSignatureDescription
quasarConnectionquasarConnection(name?: string): Promise<SubscriptionRedisClient>The named connection, once it carries get, evalsha and script.
generateVapidKeysgenerateVapidKeys(): VapidKeyPairA P-256 key pair: the public key as an uncompressed point, the private key as the raw 32-byte scalar, both base64url.
defineConfigdefineConfig(config: NovaConfig): NovaConfigReturns the config, typed.

SubscribeController ​

MemberSignatureDescription
constructornew SubscribeController(store: SubscriptionStore, options?: SubscribeOptions)options takes the PushTargetPolicy fields and maxSubscriptionsPerUser (default 20).
handlehandle(ctx: SubscribeContext): Promise<void>Validates the PushSubscription body and saves it for ctx.auth.user.id; answers 201.
unsubscribeunsubscribe(ctx: SubscribeContext): Promise<void>Removes the caller's own subscription named by { endpoint }; answers 200, or 404 when the user has no such subscription.

@c9up/nova/provider ​

ExportKindDescription
NovaProviderprovider (default)register() binds the store (an existing binding wins, then the configured store, then the in-memory one) and the Nova sender; boot() publishes the service; start() mounts POST and DELETE {routePrefix}/subscribe, with the configured guard and middleware.

@c9up/nova/services/main ​

ExportKindDescription
defaultconstThe application's Nova. Any property access before the provider booted throws.
ts
import push from '@c9up/nova/services/main'

await push.pushToUser(user.id, { title: 'New task', body: task.title })

@c9up/nova/client ​

ExportKindDescription
registerServiceWorkerfunctionRegisters the service worker.
subscribefunctionSubscribes the browser and posts the subscription to the server.
unsubscribefunctionDetaches the browser from the signed-in account.
urlBase64ToUint8ArrayfunctionA base64url VAPID public key as the Uint8Array applicationServerKey takes.
SubscribeOptionsinterfaceOptions of subscribe and unsubscribe.
RegisterServiceWorkerOptionsinterface{ scope?: string }, default '/'.
errorsnamespaceThe client's errors, one class per code, see Errors
FunctionSignatureDescription
registerServiceWorkerregisterServiceWorker(path?: string, options?: RegisterServiceWorkerOptions): Promise<ServiceWorkerRegistration>path defaults to '/sw.js'.
subscribesubscribe(vapidPublicKey: string, options?: SubscribeOptions): Promise<PushSubscription>Waits for the active service worker, subscribes with userVisibleOnly, and POSTs the subscription; throws E_NOVA_ENDPOINT_REJECTED on a non-2xx answer.
unsubscribeunsubscribe(options?: SubscribeOptions): Promise<boolean>DELETEs the subscription on the server, then drops it in the browser even when the server failed; false when the browser held none. Call it on logout.
urlBase64ToUint8ArrayurlBase64ToUint8Array(base64url: string): Uint8Array
SubscribeOptions fieldTypeDefaultDescription
endpointstring'/api/nova/subscribe'The subscription route.
credentialsRequestCredentials'include'Fetch credentials.
headersHeadersInitExtra headers, merged over content-type: application/json.
accessTokenstringShorthand for Authorization: Bearer <accessToken>; ignored when headers has an authorization.

E_NOVA_ENDPOINT_REJECTED carries the route's answer in status and responseBody.

@c9up/nova/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: what ream configure @c9up/nova runs.

@c9up/nova/commands ​

CommandDescription
nova:vapid:generateGenerates a VAPID key pair and writes the NOVA_VAPID_* variables into .env. Refuses to replace an existing private key without --force; a .env it creates is readable by its owner only.

@c9up/nova/testing ​

ExportKindDescription
FakeNovaclassRecords push and pushToUser calls; sends, encrypts and stores nothing.
CapturedPushtypeOne recorded call: kind: 'single' (with subscription) or kind: 'fan-out' (with userId), plus payload, options, timestamp.
FakeNovaPredicateinterfaceMatches on userId, endpoint, title, body, urgency, topic, or containing (a substring of the JSON payload).
FakeNovaPredicateArgtypeA FakeNovaPredicate or (captured: CapturedPush) => boolean.
FakeNova memberSignatureDescription
pushpush(subscription, payload, options?): Promise<PushResult>Records the call; answers { ok: true, status: 201 }.
pushToUserpushToUser(userId, payload, options?): Promise<PushResult[]>Records the call; answers []. Refuses an id Nova refuses.
getPushedgetPushed(): CapturedPush[]A copy of what was recorded.
resetreset(): voidForgets what was recorded.
assertPushedassertPushed(predicate: FakeNovaPredicateArg): voidThrows when no recorded push matches.
assertNotPushedassertNotPushed(predicate: FakeNovaPredicateArg): voidThrows when a recorded push matches.

Configuration ​

config/nova.ts, written by ream configure @c9up/nova:

OptionTypeDefaultDescription
routePrefixstring'/api/nova'Prefix of the subscription routes.
guardstring | null'jwt'The warden guard on the routes; null mounts them unguarded (tests only).
defaultstringThe name of the store to use, a key of stores. The generated config reads NOVA_STORE (default memory).
storesRecord<string, SubscriptionStoreFactory>The stores the app can use, by name.
storeSubscriptionStorein-memoryA ready-made store; used when stores does not name the selected one.
vapidNovaVapidConfigpublicKey, privateKey (base64url) and subject (mailto: or https://). Required for sending; the routes work without it.
delivery.timeoutnumber10000Deadline for one push request, in ms; past it the result is server-error with status 0.
delivery.concurrencynumber10Requests pushToUser keeps in flight at once.
delivery.httpPushHttpClientHttpClient from @c9up/ream/http-clientThe client pushes go through; the default refuses non-public addresses.
delivery.pushServicesreadonly string[]DEFAULT_PUSH_SERVICESHosts a push may go to, each with its subdomains. Checked when a subscription arrives and before each send.
delivery.allowHostsreadonly string[][]Exact host or host:port exemptions, for a push service next to the app in development.
maxSubscriptionsPerUsernumber20Subscriptions one user may hold; the oldest go past it.
middlewareNovaRouteMiddleware[][]Middleware run before the subscription routes' handler, such as a rate limit.

DEFAULT_PUSH_SERVICES is fcm.googleapis.com, push.services.mozilla.com, notify.windows.com, push.apple.com.

Container bindings ​

TokenResolves to
'nova.push'The Nova sender.
'nova.subscriptions'The SubscriptionStore.
'nova'The same Nova (earlier name, still bound).
'SubscriptionStore'The same store (earlier name, still bound).

The tokens are declared on ContainerBindings, so container.resolve('nova.push') is typed.

Errors ​

CodeRaised when
E_NOVA_INVALID_SUBSCRIPTIONThe subscribe or unsubscribe body is not a valid PushSubscription (HTTP 400).
E_NOVA_SUBSCRIPTION_CONFLICTAnother request was writing the same endpoint at the same time (HTTP 409).
E_NOVA_SUBSCRIPTION_NOT_FOUNDThe user has no such subscription (HTTP 404).
E_NOVA_MISSING_USERThe subscription handler ran without an authenticated user.
E_NOVA_INVALID_USER_IDThe user has no usable id (a non-empty string or an integer), or pushToUser received one that is not.
E_NOVA_VAPID_NOT_CONFIGUREDA push is sent without a VAPID key or subject.
E_NOVA_HTTP_CLIENT_MISSINGSending needs the outbound HTTP client of @c9up/ream and none is given.
E_NOVA_UNKNOWN_STOREdefault names a store stores does not declare, or stores has no default.
E_NOVA_INVALID_TABLEThe SQL store's table name is not a plain identifier.
E_NOVA_INVALID_PREFIXThe Redis store's key prefix contains a space.
E_NOVA_STORE_BUSYA subscription changed under every attempt to write it.
E_NOVA_STORE_FILE_UNREADABLEThe file store's file is not valid JSON.
E_NOVA_QUASAR_MISSINGA Redis store names a connection and @c9up/quasar is not installed.
E_NOVA_REDIS_INCOMPLETEThe quasar connection lacks a command the store issues.
E_NOVA_NOT_BOOTED@c9up/nova/services/main was used before NovaProvider.boot() ran.
E_NOVA_INVALID_OPTIONA delivery or store option is out of range: concurrency, timeout, a pushServices or allowHosts entry, maxSubscriptionsPerUser, maxPerUser, or a push's ttl or topic.
E_NOVA_ASSERTION_FAILEDFakeNova.assertPushed() or assertNotPushed() does not hold.
E_NOVA_INVALID_PREDICATEA FakeNova assertion was given an empty containing, which would match every push.
E_NOVA_INTERNALAn invariant of nova broke (the VAPID key pair Node generated has an unexpected shape). A bug: report it.

Raised by @c9up/nova/client, exported from its own errors:

CodeRaised when
E_NOVA_SERVICE_WORKER_UNSUPPORTEDThe environment has no navigator.serviceWorker.
E_NOVA_PUSH_SUBSCRIBE_FAILEDThe browser refused pushManager.subscribe(); the browser's error is the cause.
E_NOVA_ENDPOINT_REJECTEDThe subscription route answered subscribe() with other than 201, or unsubscribe() with an error other than 404. status and responseBody hold the answer.

Migration ​

  • Nova now needs @c9up/ream 0.2.32 or later: it recognises the HTTP client's failures by their E_HTTP_CLIENT_* code. Update both packages together.
  • NovaError and NovaTypeError are gone: test error.code, or error instanceof errors.E_NOVA_* with import { errors } from '@c9up/nova'. E_NOVA_INVALID_OPTION and E_NOVA_INVALID_USER_ID are no longer a TypeError.
  • error.hint is now error.help.
  • NovaClientError is gone: import { errors } from '@c9up/nova/client' and test E_NOVA_SERVICE_WORKER_UNSUPPORTED, E_NOVA_PUSH_SUBSCRIBE_FAILED or E_NOVA_ENDPOINT_REJECTED; the last keeps status and responseBody.

See also ​