This commit is contained in:
vfs committed 2026-05-10 10:49:20 +02:00
1 parent 136a1c34b3
commit cb87af4f3b
108 files changed
+49079 -41

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
/*.p12
/*.pem
/*.cer
/*.p8
.DS_Store
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 Adam Jones
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+216
View File
@@ -0,0 +1,216 @@
# APNS/2
APNS/2 is a go package designed for simple, flexible and fast Apple Push Notifications on iOS, OSX and Safari using the new HTTP/2 Push provider API.
[![Build Status](https://github.com/sideshow/apns2/actions/workflows/tests.yml/badge.svg)](https://github.com/sideshow/apns2/actions/workflows/tests.yml) [![Coverage Status](https://coveralls.io/repos/sideshow/apns2/badge.svg?branch=master&service=github)](https://coveralls.io/github/sideshow/apns2?branch=master) [![GoDoc](https://godoc.org/github.com/sideshow/apns2?status.svg)](https://godoc.org/github.com/sideshow/apns2)
## Features
- Uses new Apple APNs HTTP/2 connection
- Fast - See [notes on speed](https://github.com/sideshow/apns2/wiki/APNS-HTTP-2-Push-Speed)
- Works with go 1.7 and later
- Supports new Apple Token Based Authentication (JWT)
- Supports new iOS 10 features such as Collapse IDs, Subtitles and Mutable Notifications
- Supports new iOS 15 features interruptionLevel and relevanceScore
- Supports persistent connections to APNs
- Supports VoIP/PushKit notifications (iOS 8 and later)
- Modular & easy to use
- Tested and working in APNs production environment
## Install
- Make sure you have [Go](https://golang.org/doc/install) installed and have set your [GOPATH](https://golang.org/doc/code.html#GOPATH).
- Install apns2:
```sh
go get -u github.com/sideshow/apns2
```
If you are running the test suite you will also need to install testify:
```sh
go get -u github.com/stretchr/testify
```
## Example
```go
package main
import (
"log"
"fmt"
"github.com/sideshow/apns2"
"github.com/sideshow/apns2/certificate"
)
func main() {
cert, err := certificate.FromP12File("../cert.p12", "")
if err != nil {
log.Fatal("Cert Error:", err)
}
notification := &apns2.Notification{}
notification.DeviceToken = "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7"
notification.Topic = "com.sideshow.Apns2"
notification.Payload = []byte(`{"aps":{"alert":"Hello!"}}`) // See Payload section below
// If you want to test push notifications for builds running directly from XCode (Development), use
// client := apns2.NewClient(cert).Development()
// For apps published to the app store or installed as an ad-hoc distribution use Production()
client := apns2.NewClient(cert).Production()
res, err := client.Push(notification)
if err != nil {
log.Fatal("Error:", err)
}
fmt.Printf("%v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}
```
## JWT Token Example
Instead of using a `.p12` or `.pem` certificate as above, you can optionally use
APNs JWT _Provider Authentication Tokens_. First you will need a signing key (`.p8` file), Key ID and Team ID [from Apple](http://help.apple.com/xcode/mac/current/#/dev54d690a66). Once you have these details, you can create a new client:
```go
authKey, err := token.AuthKeyFromFile("../AuthKey_XXX.p8")
if err != nil {
log.Fatal("token error:", err)
}
token := &token.Token{
AuthKey: authKey,
// KeyID from developer account (Certificates, Identifiers & Profiles -> Keys)
KeyID: "ABC123DEFG",
// TeamID from developer account (View Account -> Membership)
TeamID: "DEF123GHIJ",
}
...
client := apns2.NewTokenClient(token)
res, err := client.Push(notification)
```
- You can use one APNs signing key to authenticate tokens for multiple apps.
- A signing key works for both the development and production environments.
- A signing key doesn’t expire but can be revoked.
## Notification
At a minimum, a _Notification_ needs a _DeviceToken_, a _Topic_ and a _Payload_.
```go
notification := &apns2.Notification{
DeviceToken: "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7",
Topic: "com.sideshow.Apns2",
Payload: []byte(`{"aps":{"alert":"Hello!"}}`),
}
```
You can also set an optional _ApnsID_, _Expiration_ or _Priority_.
```go
notification.ApnsID = "40636A2C-C093-493E-936A-2A4333C06DEA"
notification.Expiration = time.Now()
notification.Priority = apns2.PriorityLow
```
## Payload
You can use raw bytes for the `notification.Payload` as above, or you can use the payload builder package which makes it easy to construct APNs payloads.
```go
// {"aps":{"alert":"hello","badge":1},"key":"val"}
payload := payload.NewPayload().Alert("hello").Badge(1).Custom("key", "val")
notification.Payload = payload
client.Push(notification)
```
Refer to the [payload](https://godoc.org/github.com/sideshow/apns2/payload) docs for more info.
## Response, Error handling
APNS/2 draws the distinction between a valid response from Apple indicating whether or not the _Notification_ was sent or not, and an unrecoverable or unexpected _Error_;
- An `Error` is returned if a non-recoverable error occurs, i.e. if there is a problem with the underlying _http.Client_ connection or _Certificate_, the payload was not sent, or a valid _Response_ was not received.
- A `Response` is returned if the payload was successfully sent to Apple and a documented response was received. This struct will contain more information about whether or not the push notification succeeded, its _apns-id_ and if applicable, more information around why it did not succeed.
To check if a `Notification` was successfully sent;
```go
res, err := client.Push(notification)
if err != nil {
log.Println("There was an error", err)
return
}
if res.Sent() {
log.Println("Sent:", res.ApnsID)
} else {
fmt.Printf("Not Sent: %v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}
```
## Context & Timeouts
For better control over request cancellations and timeouts APNS/2 supports
contexts. Using a context can be helpful if you want to cancel all pushes when
the parent process is cancelled, or need finer grained control over individual
push timeouts. See the [Google post](https://blog.golang.org/context) for more
information on contexts.
```go
ctx, cancel = context.WithTimeout(context.Background(), 10 * time.Second)
res, err := client.PushWithContext(ctx, notification)
defer cancel()
```
## Speed & Performance
Also see the wiki page on [APNS HTTP 2 Push Speed](https://github.com/sideshow/apns2/wiki/APNS-HTTP-2-Push-Speed).
For best performance, you should hold on to an `apns2.Client` instance and not re-create it every push. The underlying TLS connection itself can take a few seconds to connect and negotiate, so if you are setting up an `apns2.Client` and tearing it down every push, then this will greatly affect performance. (Apple suggest keeping the connection open all the time).
You should also limit the amount of `apns2.Client` instances. The underlying transport has a http connection pool itself, so a single client instance will be enough for most users (One instance can potentially do 4,000+ pushes per second). If you need more than this then one instance per CPU core is a good starting point.
Speed is greatly affected by the location of your server and the quality of your network connection. If you're just testing locally, behind a proxy or if your server is outside USA then you're not going to get great performance. With a good server located in AWS, you should be able to get [decent throughput](https://github.com/sideshow/apns2/wiki/APNS-HTTP-2-Push-Speed).
## Command line tool
APNS/2 has a command line tool that can be installed with `go get github.com/sideshow/apns2/apns2`. Usage:
```
apns2 --help
usage: apns2 --certificate-path=CERTIFICATE-PATH --topic=TOPIC [<flags>]
Listens to STDIN to send notifications and writes APNS response code and reason to STDOUT.
The expected format is: <DeviceToken> <APNS Payload>
Example: aff0c63d9eaa63ad161bafee732d5bc2c31f66d552054718ff19ce314371e5d0 {"aps": {"alert": "hi"}}
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-c, --certificate-path=CERTIFICATE-PATH
Path to certificate file.
-t, --topic=TOPIC The topic of the remote notification, which is typically the bundle ID for your app
-m, --mode="production" APNS server to send notifications to. `production` or `development`. Defaults to `production`
--version Show application version.
```
## License
The MIT License (MIT)
Copyright (c) 2016 Adam Jones
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+238
View File
@@ -0,0 +1,238 @@
// Package apns2 is a go Apple Push Notification Service (APNs) provider that
// allows you to send remote notifications to your iOS, tvOS, and OS X
// apps, using the new APNs HTTP/2 network protocol.
package apns2
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"io"
"net"
"net/http"
"strconv"
"time"
"github.com/sideshow/apns2/token"
"golang.org/x/net/http2"
)
// Apple HTTP/2 Development & Production urls
const (
HostDevelopment = "https://api.sandbox.push.apple.com"
HostProduction = "https://api.push.apple.com"
)
// DefaultHost is a mutable var for testing purposes
var DefaultHost = HostDevelopment
var (
// HTTPClientTimeout specifies a time limit for requests made by the
// HTTPClient. The timeout includes connection time, any redirects,
// and reading the response body.
HTTPClientTimeout = 60 * time.Second
// ReadIdleTimeout is the timeout after which a health check using a ping
// frame will be carried out if no frame is received on the connection. If
// zero, no health check is performed.
ReadIdleTimeout = 15 * time.Second
// TCPKeepAlive specifies the keep-alive period for an active network
// connection. If zero, keep-alive probes are sent with a default value
// (currently 15 seconds)
TCPKeepAlive = 15 * time.Second
// TLSDialTimeout is the maximum amount of time a dial will wait for a connect
// to complete.
TLSDialTimeout = 20 * time.Second
)
// DialTLS is the default dial function for creating TLS connections for
// non-proxied HTTPS requests.
var DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: TLSDialTimeout,
KeepAlive: TCPKeepAlive,
}
return tls.DialWithDialer(dialer, network, addr, cfg)
}
// Client represents a connection with the APNs
type Client struct {
Host string
Certificate tls.Certificate
Token *token.Token
HTTPClient *http.Client
}
// A Context carries a deadline, a cancellation signal, and other values across
// API boundaries. Context's methods may be called by multiple goroutines
// simultaneously.
type Context interface {
context.Context
}
type connectionCloser interface {
CloseIdleConnections()
}
// NewClient returns a new Client with an underlying http.Client configured with
// the correct APNs HTTP/2 transport settings. It does not connect to the APNs
// until the first Notification is sent via the Push method.
//
// As per the Apple APNs Provider API, you should keep a handle on this client
// so that you can keep your connections with APNs open across multiple
// notifications; don’t repeatedly open and close connections. APNs treats rapid
// connection and disconnection as a denial-of-service attack.
//
// If your use case involves multiple long-lived connections, consider using
// the ClientManager, which manages clients for you.
func NewClient(certificate tls.Certificate) *Client {
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{certificate},
}
if len(certificate.Certificate) > 0 {
tlsConfig.BuildNameToCertificate()
}
transport := &http2.Transport{
TLSClientConfig: tlsConfig,
DialTLS: DialTLS,
ReadIdleTimeout: ReadIdleTimeout,
}
return &Client{
HTTPClient: &http.Client{
Transport: transport,
Timeout: HTTPClientTimeout,
},
Certificate: certificate,
Host: DefaultHost,
}
}
// NewTokenClient returns a new Client with an underlying http.Client configured
// with the correct APNs HTTP/2 transport settings. It does not connect to the APNs
// until the first Notification is sent via the Push method.
//
// As per the Apple APNs Provider API, you should keep a handle on this client
// so that you can keep your connections with APNs open across multiple
// notifications; don’t repeatedly open and close connections. APNs treats rapid
// connection and disconnection as a denial-of-service attack.
func NewTokenClient(token *token.Token) *Client {
transport := &http2.Transport{
DialTLS: DialTLS,
ReadIdleTimeout: ReadIdleTimeout,
}
return &Client{
Token: token,
HTTPClient: &http.Client{
Transport: transport,
Timeout: HTTPClientTimeout,
},
Host: DefaultHost,
}
}
// Development sets the Client to use the APNs development push endpoint.
func (c *Client) Development() *Client {
c.Host = HostDevelopment
return c
}
// Production sets the Client to use the APNs production push endpoint.
func (c *Client) Production() *Client {
c.Host = HostProduction
return c
}
// Push sends a Notification to the APNs gateway. If the underlying http.Client
// is not currently connected, this method will attempt to reconnect
// transparently before sending the notification. It will return a Response
// indicating whether the notification was accepted or rejected by the APNs
// gateway, or an error if something goes wrong.
//
// Use PushWithContext if you need better cancellation and timeout control.
func (c *Client) Push(n *Notification) (*Response, error) {
return c.PushWithContext(context.Background(), n)
}
// PushWithContext sends a Notification to the APNs gateway. Context carries a
// deadline and a cancellation signal and allows you to close long running
// requests when the context timeout is exceeded. Context can be nil, for
// backwards compatibility.
//
// If the underlying http.Client is not currently connected, this method will
// attempt to reconnect transparently before sending the notification. It will
// return a Response indicating whether the notification was accepted or
// rejected by the APNs gateway, or an error if something goes wrong.
func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error) {
payload, err := json.Marshal(n)
if err != nil {
return nil, err
}
url := c.Host + "/3/device/" + n.DeviceToken
request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return nil, err
}
if c.Token != nil {
c.setTokenHeader(request)
}
setHeaders(request, n)
response, err := c.HTTPClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
r := &Response{}
r.StatusCode = response.StatusCode
r.ApnsID = response.Header.Get("apns-id")
r.ApnsUniqueID = response.Header.Get("apns-unique-id")
decoder := json.NewDecoder(response.Body)
if err := decoder.Decode(r); err != nil && err != io.EOF {
return &Response{}, err
}
return r, nil
}
// CloseIdleConnections closes any underlying connections which were previously
// connected from previous requests but are now sitting idle. It will not
// interrupt any connections currently in use.
func (c *Client) CloseIdleConnections() {
c.HTTPClient.Transport.(connectionCloser).CloseIdleConnections()
}
func (c *Client) setTokenHeader(r *http.Request) {
bearer := c.Token.GenerateIfExpired()
r.Header.Set("authorization", "bearer "+bearer)
}
func setHeaders(r *http.Request, n *Notification) {
r.Header.Set("Content-Type", "application/json; charset=utf-8")
if n.Topic != "" {
r.Header.Set("apns-topic", n.Topic)
}
if n.ApnsID != "" {
r.Header.Set("apns-id", n.ApnsID)
}
if n.CollapseID != "" {
r.Header.Set("apns-collapse-id", n.CollapseID)
}
if n.Priority > 0 {
r.Header.Set("apns-priority", strconv.Itoa(n.Priority))
}
if n.Expiration.After(time.Unix(0, 0)) {
r.Header.Set("apns-expiration", strconv.FormatInt(n.Expiration.Unix(), 10))
}
if n.PushType != "" {
r.Header.Set("apns-push-type", string(n.PushType))
} else {
r.Header.Set("apns-push-type", string(PushTypeAlert))
}
}
+162
View File
@@ -0,0 +1,162 @@
package apns2
import (
"container/list"
"crypto/sha1"
"crypto/tls"
"sync"
"time"
)
type managerItem struct {
key [sha1.Size]byte
client *Client
lastUsed time.Time
}
// ClientManager is a way to manage multiple connections to the APNs.
type ClientManager struct {
// MaxSize is the maximum number of clients allowed in the manager. When
// this limit is reached, the least recently used client is evicted. Set
// zero for no limit.
MaxSize int
// MaxAge is the maximum age of clients in the manager. Upon retrieval, if
// a client has remained unused in the manager for this duration or longer,
// it is evicted and nil is returned. Set zero to disable this
// functionality.
MaxAge time.Duration
// Factory is the function which constructs clients if not found in the
// manager.
Factory func(certificate tls.Certificate) *Client
cache map[[sha1.Size]byte]*list.Element
ll *list.List
mu sync.Mutex
once sync.Once
}
// NewClientManager returns a new ClientManager for prolonged, concurrent usage
// of multiple APNs clients. ClientManager is flexible enough to work best for
// your use case. When a client is not found in the manager, Get will return
// the result of calling Factory, which can be a Client or nil.
//
// Having multiple clients per certificate in the manager is not allowed.
//
// By default, MaxSize is 64, MaxAge is 10 minutes, and Factory always returns
// a Client with default options.
func NewClientManager() *ClientManager {
manager := &ClientManager{
MaxSize: 64,
MaxAge: 10 * time.Minute,
Factory: NewClient,
}
manager.initInternals()
return manager
}
// Add adds a Client to the manager. You can use this to individually configure
// Clients in the manager.
func (m *ClientManager) Add(client *Client) {
m.initInternals()
m.mu.Lock()
defer m.mu.Unlock()
key := cacheKey(client.Certificate)
now := time.Now()
if ele, hit := m.cache[key]; hit {
item := ele.Value.(*managerItem)
item.client = client
item.lastUsed = now
m.ll.MoveToFront(ele)
return
}
ele := m.ll.PushFront(&managerItem{key, client, now})
m.cache[key] = ele
if m.MaxSize != 0 && m.ll.Len() > m.MaxSize {
m.mu.Unlock()
m.removeOldest()
m.mu.Lock()
}
}
// Get gets a Client from the manager. If a Client is not found in the manager
// or if a Client has remained in the manager longer than MaxAge, Get will call
// the ClientManager's Factory function, store the result in the manager if
// non-nil, and return it.
func (m *ClientManager) Get(certificate tls.Certificate) *Client {
m.initInternals()
m.mu.Lock()
defer m.mu.Unlock()
key := cacheKey(certificate)
now := time.Now()
if ele, hit := m.cache[key]; hit {
item := ele.Value.(*managerItem)
if m.MaxAge != 0 && item.lastUsed.Before(now.Add(-m.MaxAge)) {
c := m.Factory(certificate)
if c == nil {
return nil
}
item.client = c
}
item.lastUsed = now
m.ll.MoveToFront(ele)
return item.client
}
c := m.Factory(certificate)
if c == nil {
return nil
}
m.mu.Unlock()
m.Add(c)
m.mu.Lock()
return c
}
// Len returns the current size of the ClientManager.
func (m *ClientManager) Len() int {
if m.cache == nil {
return 0
}
m.mu.Lock()
defer m.mu.Unlock()
return m.ll.Len()
}
func (m *ClientManager) initInternals() {
m.once.Do(func() {
m.cache = map[[sha1.Size]byte]*list.Element{}
m.ll = list.New()
})
}
func (m *ClientManager) removeOldest() {
m.mu.Lock()
ele := m.ll.Back()
m.mu.Unlock()
if ele != nil {
m.removeElement(ele)
}
}
func (m *ClientManager) removeElement(e *list.Element) {
m.mu.Lock()
defer m.mu.Unlock()
m.ll.Remove(e)
delete(m.cache, e.Value.(*managerItem).key)
}
func cacheKey(certificate tls.Certificate) [sha1.Size]byte {
var data []byte
for _, cert := range certificate.Certificate {
data = append(data, cert...)
}
return sha1.Sum(data)
}
+162
View File
@@ -0,0 +1,162 @@
package apns2
import (
"encoding/json"
"time"
)
// EPushType defines the value for the apns-push-type header
type EPushType string
const (
// PushTypeAlert is used for notifications that trigger a user interaction —
// for example, an alert, badge, or sound. If you set this push type, the
// topic field must use your app’s bundle ID as the topic. If the
// notification requires immediate action from the user, set notification
// priority to 10; otherwise use 5. The alert push type is required on
// watchOS 6 and later. It is recommended on macOS, iOS, tvOS, and iPadOS.
PushTypeAlert EPushType = "alert"
// PushTypeBackground is used for notifications that deliver content in the
// background, and don’t trigger any user interactions. If you set this push
// type, the topic field must use your app’s bundle ID as the topic. Always
// use priority 5. Using priority 10 is an error. The background push type
// is required on watchOS 6 and later. It is recommended on macOS, iOS,
// tvOS, and iPadOS.
PushTypeBackground EPushType = "background"
// PushTypeLocation is used for notifications that request a user’s
// location. If you set this push type, the topic field must use your app’s
// bundle ID with .location-query appended to the end. The location push
// type is recommended for iOS and iPadOS. It isn’t available on macOS,
// tvOS, and watchOS. If the location query requires an immediate response
// from the Location Push Service Extension, set notification apns-priority
// to 10; otherwise, use 5. The location push type supports only token-based
// authentication.
PushTypeLocation EPushType = "location"
// PushTypeVOIP is used for notifications that provide information about an
// incoming Voice-over-IP (VoIP) call. If you set this push type, the topic
// field must use your app’s bundle ID with .voip appended to the end. If
// you’re using certificate-based authentication, you must also register the
// certificate for VoIP services. The voip push type is not available on
// watchOS. It is recommended on macOS, iOS, tvOS, and iPadOS.
PushTypeVOIP EPushType = "voip"
// PushTypeComplication is used for notifications that contain update
// information for a watchOS app’s complications. If you set this push type,
// the topic field must use your app’s bundle ID with .complication appended
// to the end. If you’re using certificate-based authentication, you must
// also register the certificate for WatchKit services. The complication
// push type is recommended for watchOS and iOS. It is not available on
// macOS, tvOS, and iPadOS.
PushTypeComplication EPushType = "complication"
// PushTypeFileProvider is used to signal changes to a File Provider
// extension. If you set this push type, the topic field must use your app’s
// bundle ID with .pushkit.fileprovider appended to the end. The
// fileprovider push type is not available on watchOS. It is recommended on
// macOS, iOS, tvOS, and iPadOS.
PushTypeFileProvider EPushType = "fileprovider"
// PushTypeMDM is used for notifications that tell managed devices to
// contact the MDM server. If you set this push type, you must use the topic
// from the UID attribute in the subject of your MDM push certificate.
PushTypeMDM EPushType = "mdm"
// PushTypeLiveActivity is used for Live Activities that display various
// real-time information. If you set this push type, the topic field must
// use your app’s bundle ID with `push-type.liveactivity` appended to the end.
// The live activity push supports only token-based authentication. This
// push type is recommended for iOS. It is not available on macOS, tvOS,
// watchOS and iPadOS.
PushTypeLiveActivity EPushType = "liveactivity"
// PushTypePushToTalk is used for notifications that provide information about the
// push to talk. If you set this push type, the apns-topic header field
// must use your app’s bundle ID with.voip-ptt appended to the end.
// The pushtotalk push type isn’t available on watchOS, macOS, and tvOS. It’s recommended on iOS and iPadOS.
PushTypePushToTalk EPushType = "pushtotalk"
)
const (
// PriorityLow will tell APNs to send the push message at a time that takes
// into account power considerations for the device. Notifications with this
// priority might be grouped and delivered in bursts. They are throttled,
// and in some cases are not delivered.
PriorityLow = 5
// PriorityHigh will tell APNs to send the push message immediately.
// Notifications with this priority must trigger an alert, sound, or badge
// on the target device. It is an error to use this priority for a push
// notification that contains only the content-available key.
PriorityHigh = 10
)
// Notification represents the the data and metadata for a APNs Remote Notification.
type Notification struct {
// An optional canonical UUID that identifies the notification. The
// canonical form is 32 lowercase hexadecimal digits, displayed in five
// groups separated by hyphens in the form 8-4-4-4-12. An example UUID is as
// follows:
//
// 123e4567-e89b-12d3-a456-42665544000
//
// If you don't set this, a new UUID is created by APNs and returned in the
// response.
ApnsID string
// A string which allows multiple notifications with the same collapse
// identifier to be displayed to the user as a single notification. The
// value should not exceed 64 bytes.
CollapseID string
// A string containing hexadecimal bytes of the device token for the target
// device.
DeviceToken string
// The topic of the remote notification, which is typically the bundle ID
// for your app. The certificate you create in the Apple Developer Member
// Center must include the capability for this topic. If your certificate
// includes multiple topics, you must specify a value for this header. If
// you omit this header and your APNs certificate does not specify multiple
// topics, the APNs server uses the certificate’s Subject as the default
// topic.
Topic string
// An optional time at which the notification is no longer valid and can be
// discarded by APNs. If this value is in the past, APNs treats the
// notification as if it expires immediately and does not store the
// notification or attempt to redeliver it. If this value is left as the
// default (ie, Expiration.IsZero()) an expiration header will not added to
// the http request.
Expiration time.Time
// The priority of the notification. Specify ether apns.PriorityHigh (10) or
// apns.PriorityLow (5) If you don't set this, the APNs server will set the
// priority to 10.
Priority int
// A byte array containing the JSON-encoded payload of this push notification.
// Refer to "The Remote Notification Payload" section in the Apple Local and
// Remote Notification Programming Guide for more info.
Payload interface{}
// The pushtype of the push notification. If this values is left as the
// default an apns-push-type header with value 'alert' will be added to the
// http request.
PushType EPushType
}
// MarshalJSON converts the notification payload to JSON.
func (n *Notification) MarshalJSON() ([]byte, error) {
switch payload := n.Payload.(type) {
case string:
return []byte(payload), nil
case []byte:
return payload, nil
default:
return json.Marshal(payload)
}
}
+164
View File
@@ -0,0 +1,164 @@
package apns2
import (
"net/http"
"strconv"
"time"
)
// StatusSent is a 200 response.
const StatusSent = http.StatusOK
// The possible Reason error codes returned from APNs. From table 4 in the
// Handling Notification Responses from APNs article
const (
// 400 The collapse identifier exceeds the maximum allowed size
ReasonBadCollapseID = "BadCollapseId"
// 400 The specified device token was bad. Verify that the request contains a
// valid token and that the token matches the environment.
ReasonBadDeviceToken = "BadDeviceToken"
// 400 The apns-expiration value is bad.
ReasonBadExpirationDate = "BadExpirationDate"
// 400 The apns-id value is bad.
ReasonBadMessageID = "BadMessageId"
// 400 The apns-priority value is bad.
ReasonBadPriority = "BadPriority"
// 400 The apns-topic was invalid.
ReasonBadTopic = "BadTopic"
// 400 The device token does not match the specified topic.
ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic"
// 400 One or more headers were repeated.
ReasonDuplicateHeaders = "DuplicateHeaders"
// 400 Idle time out.
ReasonIdleTimeout = "IdleTimeout"
// 400 The apns-push-type value is invalid.
ReasonInvalidPushType = "InvalidPushType"
// 400 The device token is not specified in the request :path. Verify that the
// :path header contains the device token.
ReasonMissingDeviceToken = "MissingDeviceToken"
// 400 The apns-topic header of the request was not specified and was
// required. The apns-topic header is mandatory when the client is connected
// using a certificate that supports multiple topics.
ReasonMissingTopic = "MissingTopic"
// 400 The message payload was empty.
ReasonPayloadEmpty = "PayloadEmpty"
// 400 Pushing to this topic is not allowed.
ReasonTopicDisallowed = "TopicDisallowed"
// 403 The certificate was bad.
ReasonBadCertificate = "BadCertificate"
// 403 The client certificate was for the wrong environment.
ReasonBadCertificateEnvironment = "BadCertificateEnvironment"
// 403 The provider token is stale and a new token should be generated.
ReasonExpiredProviderToken = "ExpiredProviderToken"
// 403 The specified action is not allowed.
ReasonForbidden = "Forbidden"
// 403 The provider token is not valid or the token signature could not be
// verified.
ReasonInvalidProviderToken = "InvalidProviderToken"
// 403 No provider certificate was used to connect to APNs and Authorization
// header was missing or no provider token was specified.
ReasonMissingProviderToken = "MissingProviderToken"
// 404 The request contained a bad :path value.
ReasonBadPath = "BadPath"
// 405 The specified :method was not POST.
ReasonMethodNotAllowed = "MethodNotAllowed"
// 410 The device token has expired.
ReasonExpiredToken = "ExpiredToken"
// 410 The device token is inactive for the specified topic.
ReasonUnregistered = "Unregistered"
// 413 The message payload was too large. See Creating the Remote Notification
// Payload in the Apple Local and Remote Notification Programming Guide for
// details on maximum payload size.
ReasonPayloadTooLarge = "PayloadTooLarge"
// 429 The provider token is being updated too often.
ReasonTooManyProviderTokenUpdates = "TooManyProviderTokenUpdates"
// 429 Too many requests were made consecutively to the same device token.
ReasonTooManyRequests = "TooManyRequests"
// 500 An internal server error occurred.
ReasonInternalServerError = "InternalServerError"
// 503 The service is unavailable.
ReasonServiceUnavailable = "ServiceUnavailable"
// 503 The server is shutting down.
ReasonShutdown = "Shutdown"
)
// Response represents a result from the APNs gateway indicating whether a
// notification was accepted or rejected and (if applicable) the metadata
// surrounding the rejection.
type Response struct {
// The HTTP status code returned by APNs.
// A 200 value indicates that the notification was successfully sent.
// For a list of other possible status codes, see table 6-4 in the Apple Local
// and Remote Notification Programming Guide.
StatusCode int
// The APNs error string indicating the reason for the notification failure (if
// any). The error code is specified as a string. For a list of possible
// values, see the Reason constants above.
// If the notification was accepted, this value will be "".
Reason string
// The APNs ApnsID value from the Notification. If you didn't set an ApnsID on the
// Notification, this will be a new unique UUID which has been created by APNs.
ApnsID string
// If the value of StatusCode is 410, this is the last time at which APNs
// confirmed that the device token was no longer valid for the topic.
Timestamp Time
// An identifier that is only available in the Developement enviroment. Use
// this to query Delivery Log information for the corresponding notification
// in Push Notifications Console.
ApnsUniqueID string
}
// Sent returns whether or not the notification was successfully sent.
// This is the same as checking if the StatusCode == 200.
func (c *Response) Sent() bool {
return c.StatusCode == StatusSent
}
// Time represents a device uninstall time
type Time struct {
time.Time
}
// UnmarshalJSON converts an epoch date into a Time struct.
func (t *Time) UnmarshalJSON(b []byte) error {
ts, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(ts/1000, 0)
return nil
}
+107
View File
@@ -0,0 +1,107 @@
package token
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"errors"
"os"
"sync"
"time"
"github.com/golang-jwt/jwt/v4"
)
const (
// TokenTimeout is the period of time in seconds that a token is valid for.
// If the timestamp for token issue is not within the last hour, APNs
// rejects subsequent push messages. This is set to under an hour so that
// we generate a new token before the existing one expires.
TokenTimeout = 3000
)
// Possible errors when parsing a .p8 file.
var (
ErrAuthKeyNotPem = errors.New("token: AuthKey must be a valid .p8 PEM file")
ErrAuthKeyNotECDSA = errors.New("token: AuthKey must be of type ecdsa.PrivateKey")
ErrAuthKeyNil = errors.New("token: AuthKey was nil")
)
// Token represents an Apple Provider Authentication Token (JSON Web Token).
type Token struct {
sync.Mutex
AuthKey *ecdsa.PrivateKey
KeyID string
TeamID string
IssuedAt int64
Bearer string
}
// AuthKeyFromFile loads a .p8 certificate from a local file and returns a
// *ecdsa.PrivateKey.
func AuthKeyFromFile(filename string) (*ecdsa.PrivateKey, error) {
bytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return AuthKeyFromBytes(bytes)
}
// AuthKeyFromBytes loads a .p8 certificate from an in memory byte array and
// returns an *ecdsa.PrivateKey.
func AuthKeyFromBytes(bytes []byte) (*ecdsa.PrivateKey, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, ErrAuthKeyNotPem
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
if pk, ok := key.(*ecdsa.PrivateKey); ok {
return pk, nil
}
return nil, ErrAuthKeyNotECDSA
}
// GenerateIfExpired checks to see if the token is about to expire and
// generates a new token.
func (t *Token) GenerateIfExpired() (bearer string) {
t.Lock()
defer t.Unlock()
if t.Expired() {
t.Generate()
}
return t.Bearer
}
// Expired checks to see if the token has expired.
func (t *Token) Expired() bool {
return time.Now().Unix() >= (t.IssuedAt + TokenTimeout)
}
// Generate creates a new token.
func (t *Token) Generate() (bool, error) {
if t.AuthKey == nil {
return false, ErrAuthKeyNil
}
issuedAt := time.Now().Unix()
jwtToken := &jwt.Token{
Header: map[string]interface{}{
"alg": "ES256",
"kid": t.KeyID,
},
Claims: jwt.MapClaims{
"iss": t.TeamID,
"iat": issuedAt,
},
Method: jwt.SigningMethodES256,
}
bearer, err := jwtToken.SignedString(t.AuthKey)
if err != nil {
return false, err
}
t.IssuedAt = issuedAt
t.Bearer = bearer
return true, nil
}