Skip to content

Commit

Permalink
feat: Add the ability to manage channels and send broadcasts (#164)
Browse files Browse the repository at this point in the history
  • Loading branch information
cbaker6 authored Feb 6, 2025
1 parent 2554634 commit ab234c9
Show file tree
Hide file tree
Showing 16 changed files with 3,946 additions and 354 deletions.
139 changes: 119 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ A Node.js module for interfacing with the Apple Push Notification service.
- [Connecting through an HTTP proxy](#connecting-through-an-http-proxy)
- [Using a pool of http/2 connections](#using-a-pool-of-http2-connections)
- [Sending a notification](#sending-a-notification)
- [Managing channels](#manage-channels)
- [Sending a broadcast notification](#sending-a-broadcast-notification)

# Features

Expand All @@ -36,7 +38,7 @@ $ npm install @parse/node-apn --save

# Quick Start

This readme is a brief introduction, please refer to the full [documentation](doc/apn.markdown) in `doc/` for more details.
This readme is a brief introduction; please refer to the full [documentation](doc/apn.markdown) in `doc/` for more details.

If you have previously used v1.x and wish to learn more about what's changed in v2.0, please see [What's New](doc/whats-new.markdown)

Expand All @@ -59,15 +61,20 @@ var options = {
production: false
};

var apnProvider = new apn.Provider(options);
const apnProvider = new apn.Provider(options);
```

By default, the provider will connect to the sandbox unless the environment variable `NODE_ENV=production` is set.

For more information about configuration options consult the [provider documentation](doc/provider.markdown).
For more information about configuration options, consult the [provider documentation](doc/provider.markdown).

Help with preparing the key and certificate files for connection can be found in the [wiki][certificateWiki]

> [!WARNING]
> You should only create one `Provider` per-process for each certificate/key pair you have. You do not need to create a new `Provider` for each notification. If you are only sending notifications to one app, there is no need for more than one `Provider`.
>
> If you are constantly creating `Provider` instances in your app, make sure to call `Provider.shutdown()` when you are done with each provider to release its resources and memory.
### Connecting through an HTTP proxy

If you need to connect through an HTTP proxy, you simply need to provide the `proxy: {host, port}` option when creating the provider. For example:
Expand All @@ -86,7 +93,7 @@ var options = {
production: false
};

var apnProvider = new apn.Provider(options);
const apnProvider = new apn.Provider(options);
```

The provider will first send an HTTP CONNECT request to the specified proxy in order to establish an HTTP tunnel. Once established, it will create a new secure connection to the Apple Push Notification provider API through the tunnel.
Expand All @@ -111,11 +118,11 @@ var options = {
production: false
};

var apnProvider = new apn.MultiProvider(options);
const apnProvider = new apn.MultiProvider(options);
```

## Sending a notification
To send a notification you will first need a device token from your app as a string
To send a notification, you will first need a device token from your app as a string.

```javascript
let deviceToken = "a9d0ed10e9cfd022a61cb08753f49c5a0b0dfb383697bf9f9d750a1003da19c7"
Expand All @@ -124,7 +131,7 @@ let deviceToken = "a9d0ed10e9cfd022a61cb08753f49c5a0b0dfb383697bf9f9d750a1003da1
Create a notification object, configuring it with the relevant parameters (See the [notification documentation](doc/notification.markdown) for more details.)

```javascript
var note = new apn.Notification();
let note = new apn.Notification();

note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
Expand All @@ -137,29 +144,32 @@ note.topic = "<your-app-bundle-id>";
Send the notification to the API with `send`, which returns a promise.

```javascript
apnProvider.send(note, deviceToken).then( (result) => {
try {
const result = apnProvider.send(note, deviceToken);
// see documentation for an explanation of result
});
} catch(error) {
// Handle error...
}
```

This will result in the the following notification payload being sent to the device
This will result in the following notification payload being sent to the device.

```json
{"messageFrom":"John Appelseed","aps":{"badge":3,"sound":"ping.aiff","alert":"\uD83D\uDCE7 \u2709 You have a new message"}}
```

Create a Live Activity notification object, configuring it with the relevant parameters (See the [notification documentation](doc/notification.markdown) for more details.)
Create a Live Activity notification object and configure it with the relevant parameters (See the [notification documentation](doc/notification.markdown) for more details.)

```javascript
var note = new apn.Notification();
let note = new apn.Notification();

note.topic = "<your-app-bundle-id>.push-type.liveactivity";
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.pushType = "liveactivity",
note.badge = 3;
note.sound = "ping.aiff";
note.alert = "\uD83D\uDCE7 \u2709 You have a new message";
note.payload = {'messageFrom': 'John Appleseed'};
note.topic = "<your-app-bundle-id>";
note.pushType = "liveactivity",
note.relevanceScore = 75,
note.timestamp = Math.floor(Date.now() / 1000); // Current time
note.staleDate = Math.floor(Date.now() / 1000) + (8 * 3600); // Expires 8 hour from now.
Expand All @@ -170,18 +180,107 @@ note.contentState = {}
Send the notification to the API with `send`, which returns a promise.

```javascript
apnProvider.send(note, deviceToken).then( (result) => {
// see documentation for an explanation of result
});
try {
const result = await apnProvider.send(note, deviceToken);
// see the documentation for an explanation of the result
} catch (error) {
// Handle error...
}
```

This will result in the the following notification payload being sent to the device
This will result in the following notification payload being sent to the device.


```json
{"messageFrom":"John Appleseed","aps":{"badge":3,"sound":"ping.aiff","alert":"\uD83D\uDCE7 \u2709 You have a new message", "relevance-score":75,"timestamp":1683129662,"stale-date":1683216062,"event":"update","content-state":{}}}
```

You should only create one `Provider` per-process for each certificate/key pair you have. You do not need to create a new `Provider` for each notification. If you are only sending notifications to one app then there is no need for more than one `Provider`.
## Manage Channels
Starting in iOS 18 and iPadOS 18 Live Activities can be used to broadcast push notifications over channels. To do so, you will need your apps' `bundleId`.

```javascript
let bundleId = "com.node.apn";
```

Create a notification object, configuring it with the relevant parameters (See the [notification documentation](doc/notification.markdown) for more details.)

```javascript
let note = new apn.Notification();

note.requestId = "0309F412-AA57-46A8-9AC6-B5AECA8C4594"; // Optional
note.payload = {'message-storage-policy': '1', 'push-type': 'liveactivity'}; // Required
```

Create a channel with `manageChannels` and the `create` action, which returns a promise.

```javascript
try {
const result = await apnProvider.manageChannels(note, bundleId, 'create');
// see the documentation for an explanation of the result
} catch (error) {
// Handle error...
}
```

If the channel is created successfully, the result will look like the following:
```javascript
{
apns-request-id: '0309F412-AA57-46A8-9AC6-B5AECA8C4594',
apns-channel-id: 'dHN0LXNyY2gtY2hubA==' // The new channel
}
```

Similarly, `manageChannels` has additional `action`s that allow you to `read`, `readAll`, and `delete` channels. The `read` and `delete` actions require similar information to the `create` example above, with the exception that they require `note.channelId` to be populated. To request all active channel id's, you can use the `readAll` action:

```javascript
try {
const result = await apnProvider.manageChannels(note, bundleId, 'readAll');
// see the documentation for an explanation of the result
} catch (error) {
// Handle error...
}
```

After the promise is fulfilled, `result` will look like the following:

```javascript
{
apns-request-id: 'some id value',
channels: ['dHN0LXNyY2gtY2hubA==', 'eCN0LXNyY2gtY2hubA==' ...] // A list of active channels
}
```

Further information about managing channels can be found in [Apple's documentation](https://developer.apple.com/documentation/usernotifications/sending-channel-management-requests-to-apns).

## Sending A Broadcast Notification
Starting in iOS 18 and iPadOS 18, after a channel is created using `manageChannels`, broadcast push notifications can be sent to any device subscribed to the respective `channelId` created for a `bundleId`. A broadcast notification looks similar to a standard Live Activity notification mentioned above but requires `note.channelId` to be populated. An example is below:

```javascript
let note = new apn.Notification();

note.channelId = "dHN0LXNyY2gtY2hubA=="; // Required
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.pushType = "liveactivity",
note.badge = 3;
note.sound = "ping.aiff";
note.alert = "\uD83D\uDCE7 \u2709 You have a new message";
note.payload = {'messageFrom': 'John Appleseed'};
note.relevanceScore = 75,
note.timestamp = Math.floor(Date.now() / 1000); // Current time
note.staleDate = Math.floor(Date.now() / 1000) + (8 * 3600); // Expires 8 hour from now.
note.event = "update"
note.contentState = {}
```

Send the broadcast notification to the API with `broadcast`, which returns a promise.

```javascript
try {
const result = await apnProvider.broadcast(note, bundleId);
// see documentation for an explanation of result
} catch (error) {
// Handle error...
}
```

If you are constantly creating `Provider` instances in your app, make sure to call `Provider.shutdown()` when you are done with each provider to release its resources and memory.
Further information about broadcast notifications can be found in [Apple's documentation](https://developer.apple.com/documentation/usernotifications/sending-broadcast-push-notification-requests-to-apns).
63 changes: 51 additions & 12 deletions doc/provider.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,34 @@ Options:

- `key` {Buffer|String} The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`)

- `ca` An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048).
- `ca` An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048)

- `pfx` {Buffer|String} File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above.
- `pfx` {Buffer|String} File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above

- `passphrase` {String} The passphrase for the connection key, if required

- `production` {Boolean} Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly)

- `rejectUnauthorized` {Boolean} Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`)

- `address` {String} The address of the APNs server to send notifications to. If not provided, will connect to standard APNs server

- `port` {Number} The port of the APNs server to send notifications to. (Defaults to 443)

- `manageChannelsAddress` {String} The address of the APNs channel management server to send notifications to. If not provided, will connect to standard APNs channel management server

- `manageChannelsPort` {Number} The port of the APNs channel management server to send notifications to. If not provided, will connect to standard APNs channel management port

- `proxy` {host: String, port: Number|String} Connect through an HTTP proxy when sending notifications

- `manageChannelsProxy` {host: String, port: Number|String} Connect through an HTTP proxy when managing channels

- `rejectUnauthorized` {Boolean} Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`)

- `connectionRetryLimit` {Number} The maximum number of connection failures that will be tolerated before `apn.Provider` will "give up". [See below.](#connection-retry-limit) (Defaults to: 3)

- `heartBeat` {Number} The delay interval in ms that apn will ping APNs servers. (Defaults to: 60000)

- `requestTimeout` {Number} The maximum time in ms that apn will wait for a response to a request. (Defaults to: 5000)

#### Provider Certificates vs. Authentication Tokens
Expand All @@ -47,31 +63,54 @@ The `Provider` can continue to be used for sending notifications and the counter

## Class: apn.Provider

`apn.Provider` provides a number of methods for sending notifications, broadcasting notifications, and managing channels. Calling any of the methods will return a `Promise` for each notification, which is discussed more in [Results from APN Provider Methods](#results-from-apnprovider-methods).

### connection.send(notification, recipients)

This is main interface for sending notifications. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering a copy of the notification to each recipient.
This is the main interface for sending notifications. Create a `Notification` object and pass it in, along with a single recipient or an array of them, and node-apn will take care of the rest, delivering a copy of the notification to each recipient.

> A "recipient" is a `String` containing the hex-encoded device token.
Calling `send` will return a `Promise`. The Promise will resolve after each notification (per token) has reached a final state. Each notification can end in one of three possible states:
Calling `send` will return a `Promise`. The Promise will resolve after each notification (per token) has reached a final state.

### connection.manageChannels(notification, bundleId, action)
This is the interface for managing broadcast channels. Create a single `Notification` object or an array of them and pass the notification(s) in, along with a bundleId, and an action (`create`, `read`, `readAll`, `delete`) and node-apn will take care of the rest, asking the APNs to perform the action using the criteria specified in each notification.

> A "bundleId" is a `String` containing the bundle identifier for the application.
> An "action" is a `String` containing: `create`, `read`, `readAll`, or `delete` and represents what action to perform with a channel (See more in [Apple Documentation](https://developer.apple.com/documentation/usernotifications/sending-channel-management-requests-to-apns)).
Calling `manageChannels` will return a `Promise`. The Promise will resolve after each notification has reached a final state.

### connection.broadcast(notification, bundleId)

This is the interface for broadcasting Live Activity notifications. Create a single `Notification` object or an array of them and pass the notification(s) in, along with a bundleId and node-apn will take care of the rest, asking the APNs to broadcast using the criteria specified in each notification.

> A "bundleId" is a `String` containing the bundle identifier for the application.
Calling `broadcast` will return a `Promise`. The Promise will resolve after each notification has reached a final state.

### Results from apn.Provider methods

Each notification can end in one of three possible states:

- `sent` - the notification was accepted by Apple for delivery to the given recipient
- `failed` (rejected) - the notification was rejected by Apple. A rejection has an associated `status` and `reason` which is included.
- `failed` (error) - a connection-level error occurred which prevented successful communication with Apple. In very rare cases it's possible that the notification was still delivered. However, this state usually results from a network problem.
- `failed` (rejected) - the notification was rejected by Apple. A rejection has an associated `status` and `reason` which are included.
- `failed` (error) - a connection-level error occurred, which prevented successful communication with Apple. In very rare cases, it's possible that the notification was still delivered. However, this state usually results from a network problem.

When the returned `Promise` resolves, its value will be an Object containing two properties

#### sent

An array of device tokens to which the notification was successfully sent and accepted by Apple.
An array of device tokens or bundle identifiers to which the notification was successfully sent and accepted by Apple.

Being `sent` does **not** guaranteed the notification will be _delivered_, other unpredictable factors - including whether the device is reachable - can ultimately prevent delivery.
Being `sent` does **not** guarantee the notification will be _delivered_, other unpredictable factors - including whether the device is reachable - can ultimately prevent delivery.

#### failed

An array of objects for each failed token. Each object will contain the device token which failed and details of the failure which will differ between rejected and errored notifications.
An array of objects for each failed token or bundle identifier. Each object will contain the device token or bundle identifier that failed and details of the failure, which will differ between rejected and errored notifications.

For **rejected** notifications the object will take the following form
For **rejected** notifications using `send()`, the object will take the following form

```javascript
{
Expand All @@ -85,7 +124,7 @@ For **rejected** notifications the object will take the following form

More details about the response and associated status codes can be found in the [HTTP/2 Response from APN documentation][http2-response].

If a failed notification was instead caused by an **error** then it will have an `error` property instead of `response` and `status`:
If a failed notification using `send()` was instead caused by an **error** then it will have an `error` property instead of `response` and `status`:

```javascript
{
Expand All @@ -103,7 +142,7 @@ If you wish to send notifications containing emoji or other multi-byte character

Indicate to node-apn that it should close all open connections when the queue of pending notifications is fully drained. This will allow your application to terminate.

**Note:** If notifications are pushed after the connection has started, an error will be thrown.
**Note:** If notifications are pushed after the shutdown has started, an error will be thrown.

[provider-api]: https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html
[provider-auth-tokens]: https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW1
Expand Down
Loading

0 comments on commit ab234c9

Please sign in to comment.