push

package
v0.252.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package push delivers notifications to people's phones through Apple's push service (APNs), and seals what a phone hands its server so that only the relay that sealed it can use it.

A TeaNode server never talks to Apple for its own phones unless it is the relay: Apple takes notifications for an app only from a key of the developer account that publishes it. The relay (internal/api/v1api/apipush) holds that key; every other server sends to the relay (relay_client.go), and what it sends is already encrypted for the phone (payload.go).

Index

Constants

View Source
const (
	ProductionHost = "https://api.push.apple.com"
	SandboxHost    = "https://api.sandbox.push.apple.com"
)

The two APNs hosts: production for App Store and TestFlight builds, the sandbox for builds installed from Xcode.

View Source
const (
	PushTypeAlert        = "alert"
	PushTypeLiveActivity = "liveactivity"
	PushTypeVoIP         = "voip"
)

Push types: an ordinary notification, an update to a Live Activity on the lock screen, or a VoIP push, which iOS hands to the app itself (PushKit) so that it can ring for an incoming call.

View Source
const (
	FCMDataSealed   = "sealed"
	FCMDataPushKind = "pushKind"
	FCMDataThreadID = "threadId"

	FCMPushKindNotification = "notification"
	FCMPushKindCall         = "call"
	// FCMPushKindTurn is a turn's state, for the notification of a turn left
	// running: it carries no sealed content, only the word and when it came.
	FCMPushKindTurn = "turn"

	// The data of a turn message: the state (one of activityStates), whether
	// it ends the turn, and when it came, in Unix seconds.
	FCMDataActivityState     = "activityState"
	FCMDataIsActivityEnded   = "isActivityEnded"
	FCMDataActivityChangedAt = "activityChangedAt"
)

Data keys of the message the app receives. The values of PushKind tell the app what to do with it before it decrypts anything: show a notification, or ring for an incoming call with a full-screen intent.

View Source
const (
	PlatformIOS     = "ios"
	PlatformAndroid = "android"
)

Platforms a registration is for: the phone's operating system, which says whether the relay reaches it through APNs or through Firebase Cloud Messaging.

View Source
const (
	PathRegistrations = api.PathPushRegistrations
	PathNotifications = api.PathPushNotifications
)

Paths of the relay's two endpoints, under the relay's address.

View Source
const (
	ErrorCodeGone      = "gone"
	ErrorCodeTooLarge  = "too_large"
	ErrorCodeRefused   = "refused"
	ErrorCodeLimited   = "limited"
	ErrorCodeUnreached = "unreached"
)

Error codes the relay answers with, which a sender maps back to errors.

View Source
const (
	LanguageEnglish  = "en"
	LanguageChinese  = "zh"
	LanguageJapanese = "ja"
)

The languages a notification's fixed words are written in, the app's and the dashboard's: English, Simplified Chinese and Japanese.

View Source
const FCMMessagesHost = "https://fcm.googleapis.com"

FCMMessagesHost is where FCM takes messages; the project is in the path.

View Source
const PhoneKeyBytes = 32

PhoneKeyBytes is the length of a phone's payload key.

Variables

View Source
var (
	// ErrGone is APNs saying the device token is no longer valid: the app
	// was deleted, or the phone gave the app a new token.
	ErrGone = errors.New("push: the phone is no longer registered for notifications")

	// ErrTooLarge is a payload over what APNs takes.
	ErrTooLarge = errors.New("push: the notification is too large")

	// ErrRefused is APNs refusing the request for a reason a retry will not
	// change, such as a topic the key does not cover.
	ErrRefused = errors.New("push: Apple refused the notification")
)

What a send can come to besides success. A caller acts on these: a gone device is deleted, the others are retried later or reported.

Functions

func ParseKey

func ParseKey(keyPEM string) (*ecdsa.PrivateKey, error)

ParseKey reads an APNs authentication key, a PKCS #8 P-256 key: the .p8 file Apple hands out, or the base64 between its first and last lines on one line, which is what a secret read from a pipe can carry.

func PhoneLanguage added in v0.195.11

func PhoneLanguage(tag string) string

PhoneLanguage is the language a notification is written in for a language tag: Chinese or Japanese for a tag of either ("zh-Hans-CN" is Chinese), and English for anything else, a tag of no language included.

Types

type APNs

type APNs struct {
	// contains filtered or unexported fields
}

APNs sends notifications to Apple with a token-based authentication key.

func NewAPNs

func NewAPNs(keyID, teamID, topic, keyPEM string) (*APNs, error)

NewAPNs builds a client from an APNs authentication key: its identifier, the team it belongs to, the app's bundle identifier, and the .p8 file.

func (*APNs) Send

func (self *APNs) Send(ctx context.Context, deviceToken string, isSandbox bool, notification *Notification) error

Send delivers one notification to one device.

func (*APNs) UseHosts

func (self *APNs) UseHosts(client *http.Client, productionHost, sandboxHost string)

UseHosts sends through client to the given hosts instead of Apple's: for a test standing in a server of its own.

type Button

type Button struct {
	Label string `json:"label"`

	// ButtonAction is what pressing it does: approve, deny, answer:<option
	// number>, reply or open.
	ButtonAction string `json:"buttonAction"`
}

Button is one action on a notification.

type Content

type Content struct {
	// NotificationKind is what this is: alert, herdr_question,
	// goal_needs_you, speak_first, feed, approval, question, answer, circle, chat,
	// skill_share_call, photo, location, shopping, journalEveningQuestion or test.
	NotificationKind string `json:"notificationKind"`

	ConversationID string `json:"conversationId,omitempty"`
	RunID          string `json:"runId,omitempty"`
	CallID         string `json:"callId,omitempty"`

	// LocationUserID is, for a location notification, the person whose
	// arrival or departure it is, so that the app opens Location with them.
	LocationUserID string `json:"locationUserId,omitempty"`

	// For a shopping notification: the store to open the shopping screen at,
	// or the list somebody started shopping.
	ShoppingStoreName string `json:"shoppingStoreName,omitempty"`
	ShoppingListID    string `json:"shoppingListId,omitempty"`

	// JournalDay is, for the journal's evening question, the day it asks
	// about, written YYYY-MM-DD in the person's own calendar. The phone puts
	// five mood buttons on the notification and sets that day's mood from the
	// one pressed.
	JournalDay string `json:"journalDay,omitempty"`

	Title string `json:"title"`
	Body  string `json:"body"`

	// Buttons are what can be pressed on the notification itself.
	Buttons []Button `json:"buttons,omitempty"`

	// ThreadID groups notifications on the lock screen.
	ThreadID string `json:"threadId,omitempty"`

	// FeedItemID is, for a feed notification (notificationKind feed), the
	// card to open. A decision's choices are its buttons, as feed:<choice
	// key>, which the phone sends to ChooseAgentFeedItem.
	FeedItemID string `json:"feedItemId,omitempty"`

	// IsQuiet says the notification is shown without sound, for a brief that
	// is ready rather than something that cannot wait.
	IsQuiet bool `json:"isQuiet,omitempty"`

	// For a coding session's question: where to send the answer.
	Computer            string `json:"computer,omitempty"`
	PaneID              string `json:"paneId,omitempty"`
	QuestionFingerprint string `json:"questionFingerprint,omitempty"`

	// Wording, when set, writes the title and body in the language of the
	// person the phone belongs to (see PhoneLanguage), on the copy made for
	// that phone by ForLanguage. Title and Body are then what it leaves them
	// as. It is never sent.
	Wording func(content *Content, language string) `json:"-"`
}

Content is a notification as the phone shows it, before encryption.

func DecryptContent

func DecryptContent(key []byte, sealed string) (*Content, error)

DecryptContent reverses EncryptContent's sealing, for tests and for anybody checking what a phone will see.

func (*Content) ForLanguage added in v0.195.11

func (self *Content) ForLanguage(language string) *Content

ForLanguage is the content as it is sent to a phone whose person reads a language: a copy, with its Wording applied and its buttons labeled in that language. The content itself is left as it is, since it may go to several phones at once.

func (*Content) Plain added in v0.236.4

func (self *Content) Plain() *Content

Plain is a copy of the content whose Title, Body and button labels are plain text, with no Markdown mark in them. A title and a label are one line, cut short after they are converted, so a cut never lands inside syntax. The body keeps its line breaks.

type DeliverRequest

type DeliverRequest struct {
	PushRegistration string    `json:"pushRegistration"`
	Delivery         *Delivery `json:"delivery"`
}

DeliverRequest is what a server sends the relay for one notification.

type Delivery

type Delivery struct {
	// Sealed is the content, encrypted for the phone.
	Sealed string `json:"sealed"`

	// ThreadID groups notifications on the lock screen, and CollapseID makes
	// a newer notification replace an older one. Both are hashed with the
	// phone's key, so Apple and the relay never see a conversation or a
	// card's identifier.
	ThreadID   string `json:"threadId,omitempty"`
	CollapseID string `json:"collapseId,omitempty"`

	// ExpiresAt is when Apple gives up on a phone it cannot reach; zero is
	// deliveryLifetime from now.
	ExpiresAt time.Time `json:"expiresAt,omitzero"`

	// ActivityState is, for a Live Activity, the one word it shows: one of
	// activityStates. A Live Activity's delivery carries nothing else.
	ActivityState string `json:"activityState,omitempty"`

	// IsActivityEnded ends the Live Activity, showing ActivityState.
	IsActivityEnded bool `json:"isActivityEnded,omitempty"`

	// ActivityChangedAt is when the turn came to ActivityState, on the
	// server's clock. iOS shows the update with the latest aps.timestamp, so
	// it is what orders a turn's states; the relay's own clock would order
	// them by when each reached it.
	ActivityChangedAt time.Time `json:"activityChangedAt,omitzero"`
}

Delivery is a notification as a server hands it to the relay: the content already encrypted for the phone, and the little Apple needs to route it. The relay writes everything Apple shows itself (relay.go), so a server holding a registration can make the phone show only an encrypted notification from the app, never words of its own.

func EncryptContent

func EncryptContent(key []byte, content *Content) (*Delivery, error)

EncryptContent seals content for the phone holding key, shortening the body when the payload the relay will make of it would be over what APNs takes.

It is the one place every notification passes, after any Wording has rewritten it for a language, so it is where Title, Body and the button labels are made plain text (Content.Plain): a notification never shows a Markdown mark, whoever composed it.

type ErrorResponse

type ErrorResponse struct {
	ErrorCode    string `json:"errorCode"`
	ErrorMessage string `json:"errorMessage"`
}

ErrorResponse is what the relay answers when it does not deliver.

type FCM added in v0.229.0

type FCM struct {
	// contains filtered or unexported fields
}

FCM sends messages to Android phones through Firebase Cloud Messaging.

func NewFCM added in v0.229.0

func NewFCM(serviceAccountJSON string) (*FCM, error)

NewFCM builds a client from a service account's JSON file, the one the Firebase console hands out under Project settings, Service accounts.

func (*FCM) Send added in v0.229.0

func (self *FCM) Send(ctx context.Context, deviceToken string, message *FCMMessage) error

Send delivers one message to one Android phone.

func (*FCM) UseHost added in v0.229.0

func (self *FCM) UseHost(client *http.Client, messagesHost string)

UseHost sends through client to host instead of Google's: for a test standing in a server of its own. The service account's token_uri is the other address, and a test puts its own in the file.

type FCMMessage added in v0.229.0

type FCMMessage struct {
	// Data is what the app receives. Every value is a string, as FCM
	// requires.
	Data map[string]string `json:"data"`

	// IsHighPriority wakes a phone that is dozing, as a chat message or a
	// ring needs. Android lowers a high priority message's app when it does
	// not show a notification for it, so only content the app shows is sent
	// this way.
	IsHighPriority bool `json:"isHighPriority"`

	// CollapseKey makes a newer message replace an older one that has not
	// been delivered yet.
	CollapseKey string `json:"collapseKey,omitempty"`

	// TimeToLive is how long FCM keeps trying a phone it cannot reach.
	TimeToLive time.Duration `json:"timeToLive"`
}

FCMMessage is what is delivered to an Android phone: data only, so that the app is woken to draw the notification itself after decrypting it, and how FCM should treat it.

type Notification

type Notification struct {
	// PushType is PushTypeAlert, PushTypeLiveActivity or PushTypeVoIP.
	PushType string `json:"pushType"`

	// Priority is 10 to deliver now, 5 to let the phone save power.
	Priority int `json:"priority,omitempty"`

	// CollapseID makes a newer notification replace an older one with the
	// same identifier, such as a coding session's latest state.
	CollapseID string `json:"collapseId,omitempty"`

	// ExpiresAt is when APNs should give up on a phone it cannot reach.
	// Zero delivers once or not at all.
	ExpiresAt time.Time `json:"expiresAt,omitzero"`

	// Payload is the JSON APNs delivers: the "aps" dictionary and anything
	// beside it.
	Payload json.RawMessage `json:"payload"`
}

Notification is what is delivered: the payload APNs passes to the phone, and how APNs should treat it.

type Phrase added in v0.195.11

type Phrase struct {
	English  string
	Chinese  string
	Japanese string
}

Phrase is fixed wording a notification shows, in each language. Each is a format for fmt: a language that orders the values its own way indexes its verbs (%[2]s).

func (Phrase) In added in v0.195.11

func (self Phrase) In(language string, values ...any) string

In is the phrase in a language, as PhoneLanguage names it, with the values put in.

type RegisterRequest

type RegisterRequest struct {
	DeviceToken string `json:"deviceToken"`
	IsSandbox   bool   `json:"isSandbox"`

	// PushType is PushTypeAlert, the phone itself, which is the default, or
	// PushTypeLiveActivity, one Live Activity's push token, or PushTypeVoIP,
	// the token PushKit gives the app for incoming calls.
	PushType string `json:"pushType,omitempty"`

	// Platform is PlatformIOS, which is the default and what a phone that
	// registered before Android was served is, or PlatformAndroid, whose
	// DeviceToken is the FCM registration token.
	Platform string `json:"platform,omitempty"`
}

RegisterRequest is what a phone sends the relay to register.

type RegisterResponse

type RegisterResponse struct {
	PushRegistration string `json:"pushRegistration"`
}

RegisterResponse is the sealed registration the phone hands its server.

type Registration

type Registration struct {
	DeviceToken string `json:"deviceToken"`
	IsSandbox   bool   `json:"isSandbox"`
	PushType    string `json:"pushType"`

	// Platform is PlatformIOS or PlatformAndroid. A registration sealed
	// before Android was served has none, and is an iPhone's.
	Platform  string    `json:"platform,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
}

Registration is what a sealed registration holds.

func (*Registration) ResolvedPlatform added in v0.229.0

func (self *Registration) ResolvedPlatform() string

ResolvedPlatform is Platform, or PlatformIOS when it is empty.

type Relay

type Relay struct {
	// contains filtered or unexported fields
}

Relay is what a relay does, whether asked over HTTP by another server (internal/api/v1api/apipush) or by its own server, which sends to itself without the network. It reaches iPhones through APNs, Android phones through Firebase Cloud Messaging, or both; a platform it has no client for is refused.

func NewRelay

func NewRelay(apns *APNs, fcm *FCM) (*Relay, error)

NewRelay builds a relay around its APNs client, its FCM client, or both; the one it does not have is nil. Registrations are sealed with a key made from the APNs client's key when there is one, so that a relay that gains Android keeps every registration the iPhones hold, and from the FCM client's otherwise.

func (*Relay) DeliverTo

func (self *Relay) DeliverTo(ctx context.Context, registration *Registration, delivery *Delivery, now time.Time) error

DeliverTo sends a delivery to an opened registration's phone: an alert to the phone, a state to one Live Activity, or a ring to the phone's VoIP token; on Android a data message for the app to draw, high priority and of the call kind when it rings.

func (*Relay) Open

func (self *Relay) Open(pushRegistration string, now time.Time) (*Registration, error)

Open reads the registration a server presents.

func (*Relay) Register

func (self *Relay) Register(deviceToken string, isSandbox bool, pushType, platform string, now time.Time) (string, error)

Register seals a phone's device token, one Live Activity's push token, or the token PushKit gives the app for incoming calls, into the registration it hands its server. An Android phone gives its FCM registration token with platform android, for its ordinary notifications (alert) and, as the same token, to be rung (voip); an empty platform is an iPhone.

A Live Activity's update is shown by iOS as it arrives, with no extension in between to decrypt it, so it crosses Apple and the relay readable. It therefore carries no words at all: the relay writes it from one of a few states (activityStates), and the app's widget says what each means. A VoIP push is handed to the app, which decrypts it with its own key like any other, so it carries the sealed content and nothing else. An Android phone's messages are all that way: data only, sealed, except a turn's state: an Android phone registers its token as a Live Activity too, and is told the same one word, in a data message for the app to show as the notification of a turn left running.

func (*Relay) Send

func (self *Relay) Send(ctx context.Context, pushRegistration string, delivery *Delivery) error

Send lets a server that is the relay send to itself.

type RelayClient

type RelayClient struct {
	// contains filtered or unexported fields
}

RelayClient sends notifications to a relay over HTTP.

func NewRelayClient

func NewRelayClient(baseURL string) *RelayClient

NewRelayClient sends to the relay at baseURL, such as https://mail.teanode.com.

func (*RelayClient) Send

func (self *RelayClient) Send(ctx context.Context, pushRegistration string, delivery *Delivery) error

Send asks the relay to deliver a notification.

type Sealer

type Sealer struct {
	// contains filtered or unexported fields
}

Sealer seals and opens registrations.

func NewSealer

func NewSealer(keyID string, key *ecdsa.PrivateKey) (*Sealer, error)

NewSealer builds a sealer from the relay's APNs key, the one secret only the relay has, rather than from the server secret, which an operator may rotate for reasons of their own. The key's identifier is written in front of every registration: a relay given another key answers the old registrations as gone, so servers clear them and the phones register again.

func NewSealerFromSecret added in v0.229.0

func NewSealerFromSecret(keyID string, secret []byte) (*Sealer, error)

NewSealerFromSecret builds a sealer from a secret only the relay has and the identifier written in front of every registration. A relay with an APNs key seals with it (NewSealer), so that adding Android to it leaves the iPhones' registrations valid; a relay for Android alone seals with its Firebase service account's key.

func (*Sealer) Open

func (self *Sealer) Open(sealed string, now time.Time) (*Registration, error)

Open reads a sealed registration. One sealed under another key, or past its lifetime, is ErrGone: the server should forget it and wait for the phone to register again. One that does not open is ErrRefused.

func (*Sealer) Seal

func (self *Sealer) Seal(registration *Registration) (string, error)

Seal writes a registration as the opaque text a phone hands its server.

type Sender

type Sender interface {
	Send(ctx context.Context, pushRegistration string, delivery *Delivery) error
}

Sender is how a server sends a notification for one of its phones: to the relay over HTTP, or to itself when it is the relay.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL