Documentation
¶
Index ¶
- Constants
- func BuildSend(keys DeviceKeys, handle string, n Notification, now time.Time) (body []byte, sig string, err error)
- func EnvelopeContenttext(keys DeviceKeys, n Notification, now time.Time, id string) ([]byte, error)
- func NormalizeRelayURL(raw string) (string, error)
- func SignSend(sendKey, body []byte) string
- func VoiceAuthKey(secret []byte) ([]byte, error)
- type CallInvite
- type DeviceKeys
- type Dispatcher
- type Envelope
- type EnvelopeContent
- type Kind
- type Level
- type NativeRegistration
- type NativeResult
- type NativeSender
- func (s *NativeSender) Deliver(ctx context.Context, n Notification) (delivered int)
- func (s *NativeSender) Forget(deviceID string) error
- func (s *NativeSender) LastResult(deviceID string) (NativeResult, bool)
- func (s *NativeSender) Notify(ctx context.Context, n Notification)
- func (s *NativeSender) RelayURL() string
- func (s *NativeSender) SetActive(fn func(deviceID string) bool)
- func (s *NativeSender) Store() *NativeStore
- type NativeStore
- type Notification
- type Policy
- type PolicyConfig
- type Sender
- type Senders
- type Signal
- type Store
- type Summaries
- type VAPID
Constants ¶
const ( // DefaultWindow is how long a summary waits for company: the last digest // of a project (or event of a source) goes after this much quiet, so a burst // of reports is one notification. DefaultWindow = 15 * time.Minute // DefaultDailyLimit caps the non-blocking notifications of a day. Every // notification reaches every subscribed device, so it is also the cap per // device. Questions and permissions are exempt. DefaultDailyLimit = 150 )
const DefaultGrace = 60 * time.Second
DefaultGrace is how long a question or permission someone is looking at on another device waits before it is sent anyway.
const DefaultRelayURL = "https://moa-push-relay.ealeixandre.workers.dev"
DefaultRelayURL is the relay the official app is built against. Whoever builds their own app with their own APNs key runs their own relay and sets push_relay_url to it.
Provisional: the relay runs on workers.dev until the letmoa.run zone is on Cloudflare. Then this becomes https://push.letmoa.run again, together with MOA_PUSH_RELAY_URL in the iOS project (the two must match byte for byte).
const ( // EnvelopeSize is the padded plaintext size: every envelope is the same // length, so its size says nothing about its content. EnvelopeSize = 2048 )
Variables ¶
This section is empty.
Functions ¶
func BuildSend ¶ added in v0.45.0
func BuildSend(keys DeviceKeys, handle string, n Notification, now time.Time) (body []byte, sig string, err error)
BuildSend returns the exact /v1/send body and its X-Moa-Sig header value.
func EnvelopeContenttext ¶ added in v0.45.0
func EnvelopeContenttext(keys DeviceKeys, n Notification, now time.Time, id string) ([]byte, error)
EnvelopeContenttext builds the padded JSON. Texts are cut on UTF-8 boundaries until the JSON fits: escaping can grow a string, so it is measured after marshalling, not before.
func NormalizeRelayURL ¶ added in v0.45.0
NormalizeRelayURL accepts an origin and nothing else: HTTPS, no userinfo, path, query or fragment. Plain HTTP is allowed only for a loopback host, so a relay running on the same machine (wrangler dev) can be tested.
func VoiceAuthKey ¶ added in v0.47.0
VoiceAuthKey is the narrow credential a VoIP destination's secret yields: it lets the app answer, decline and join the calls it is rung for while the iPhone is locked, and nothing else (Authorization: Moa-Voice).
Types ¶
type CallInvite ¶ added in v0.47.0
CallInvite names the invitation a VoIP push rings for: its ID is the CallKit UUID, and the envelope expires with the invitation.
type DeviceKeys ¶ added in v0.45.0
type DeviceKeys struct {
Enc []byte // AES-256-GCM key of the envelope
Send []byte // HMAC key that authorizes sends to this device
Collapse []byte // HMAC key of the opaque grouping ids
KID []byte // 8 bytes naming the key inside the envelope
}
DeviceKeys are derived from the 32-byte secret S the iPhone generated.
func DeriveDeviceKeys ¶ added in v0.45.0
func DeriveDeviceKeys(secret []byte) (DeviceKeys, error)
DeriveDeviceKeys expands S with HKDF-SHA256 (empty salt, label as info).
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher sends Web Push notifications to every stored subscription.
func NewDispatcher ¶
func NewDispatcher(store *Store, vapid VAPID, subscriber string) *Dispatcher
NewDispatcher builds a dispatcher over the given store and VAPID keys.
func (*Dispatcher) Notify ¶
func (d *Dispatcher) Notify(ctx context.Context, n Notification)
Notify fans n out to all subscriptions, pruning any the push service reports as gone (404/410). Best-effort: per-subscription failures are logged, not returned.
func (*Dispatcher) VAPIDPublicKey ¶
func (d *Dispatcher) VAPIDPublicKey() string
VAPIDPublicKey returns the public key browsers need to subscribe.
type Envelope ¶ added in v0.45.0
Envelope is the encrypted payload as it travels inside the relay request and the APNs payload.
func SealEnvelope ¶ added in v0.45.0
func SealEnvelope(keys DeviceKeys, n Notification, now time.Time) (Envelope, error)
SealEnvelope encrypts n for one device. now dates it; the envelope expires after envelopeTTL.
type EnvelopeContent ¶ added in v0.45.0
type EnvelopeContent struct {
V int `json:"v"`
ID string `json:"id"`
Exp int64 `json:"exp"`
Dest string `json:"d"`
Sess string `json:"s,omitempty"`
Kind Kind `json:"k"`
Level Level `json:"lvl"`
Thread string `json:"th"`
Title string `json:"t"`
Body string `json:"b"`
// Invite is the call invitation (and CallKit UUID) of a "call" envelope.
Invite string `json:"inv,omitempty"`
}
EnvelopeContent is what the NSE reads once the envelope authenticates. Field order is the marshalling order; the NSE does not depend on it.
func OpenEnvelope ¶ added in v0.45.0
func OpenEnvelope(keys DeviceKeys, env Envelope, now time.Time) (EnvelopeContent, error)
OpenEnvelope is the NSE side, here for tests and as a reference: it authenticates before reading anything.
type Kind ¶ added in v0.45.0
type Kind string
Kind says why a notification exists.
const ( KindAsk Kind = "ask" // ask_user: the agent is waiting for an answer KindPermission Kind = "permission" // a tool waits for approval KindSecret Kind = "secret" // a tool waits for a password for one action KindDone Kind = "done" // a run the user started finished KindFailed Kind = "failed" // a run errored KindDigest Kind = "digest" // an owner finished digesting a report KindEvent Kind = "event" // a wake-on-event source delivered something KindCall Kind = "call" // an incoming voice call invitation (VoIP destinations only) KindCallRequest Kind = "call_request" // an owner asks to talk (request_call); an ordinary urgent notification, never VoIP KindProblem Kind = "problem" // a session published a problem in For you › News )
type Level ¶ added in v0.45.0
type Level string
Level is how hard a notification should interrupt.
const ( // LevelUrgent is for what blocks the agent on you: sound, alerts again when // a newer one replaces it. LevelUrgent Level = "urgent" // LevelActive is an ordinary notification, with sound. LevelActive Level = "active" // LevelPassive arrives without sound and replaces the previous one of its // group quietly. LevelPassive Level = "passive" )
type NativeRegistration ¶ added in v0.45.0
type NativeRegistration struct {
DeviceID string `json:"device_id"`
RelayURL string `json:"relay_url"`
Handle string `json:"handle"`
ExpiresAt time.Time `json:"expires_at"`
Secret string `json:"secret"` // b64u(S); never logged or returned
Env string `json:"env"`
Provider string `json:"provider,omitempty"` // "apns" or "fcm"; empty (stored before FCM) means apns
RegisteredAt time.Time `json:"registered_at"`
}
NativeRegistration binds one paired device to the relay handle the relay issued it and the secret S its envelopes are sealed with.
func (NativeRegistration) ProviderName ¶ added in v0.46.0
func (r NativeRegistration) ProviderName() string
ProviderName is the push provider of the registration, never empty. The handle is opaque, so sending does not depend on it.
type NativeResult ¶ added in v0.45.0
type NativeResult struct {
At time.Time `json:"at"`
Result string `json:"result"` // ok, handle_expired, unregistered, rejected, failed
Reason string `json:"reason,omitempty"`
// contains filtered or unexported fields
}
NativeResult is the outcome of the last send to a device, for its status.
type NativeSender ¶ added in v0.45.0
type NativeSender struct {
// contains filtered or unexported fields
}
NativeSender delivers notifications to the paired iPhones through the relay. It is a Sender, next to the Web Push Dispatcher.
Sending and forgetting a device are ordered by mu: a send is admitted under it (the device is active and this registration is still the current one) and stays in flight until its HTTP call returns; Forget removes the registration, cancels the device's sends in flight and waits for them. So once Forget returns (a revoke, an expiry, a DELETE), no request for that registration is running or can start.
func NewNativeSender ¶ added in v0.45.0
func NewNativeSender(store *NativeStore, relayURL string) *NativeSender
NewNativeSender sends through relayURL (already normalized) only: a registration made against any other relay is never used.
func (*NativeSender) Deliver ¶ added in v0.47.0
func (s *NativeSender) Deliver(ctx context.Context, n Notification) (delivered int)
Deliver is Notify that reports how many devices the relay accepted it for.
func (*NativeSender) Forget ¶ added in v0.45.0
func (s *NativeSender) Forget(deviceID string) error
Forget drops a device: its registration and its last result. It cancels the device's sends in flight and returns once none is running.
func (*NativeSender) LastResult ¶ added in v0.45.0
func (s *NativeSender) LastResult(deviceID string) (NativeResult, bool)
LastResult reports the last send to the device's current registration.
func (*NativeSender) Notify ¶ added in v0.45.0
func (s *NativeSender) Notify(ctx context.Context, n Notification)
Notify sends n to every registered, still-paired device. Best-effort: a failure is recorded for the device's status and logged without content.
func (*NativeSender) RelayURL ¶ added in v0.45.0
func (s *NativeSender) RelayURL() string
RelayURL is the configured relay origin.
func (*NativeSender) SetActive ¶ added in v0.45.0
func (s *NativeSender) SetActive(fn func(deviceID string) bool)
SetActive installs the check, made when every send is admitted, that a device is still paired. Until it is set nothing is sent: a registration outlives its device only if the device lifecycle is unknown.
func (*NativeSender) Store ¶ added in v0.45.0
func (s *NativeSender) Store() *NativeStore
Store returns the registrations store.
type NativeStore ¶ added in v0.45.0
type NativeStore struct {
// contains filtered or unexported fields
}
NativeStore persists registrations by device id (push_native.json, 0600). It holds secrets: nothing in it is ever logged or served back.
func NewNativeStore ¶ added in v0.45.0
func NewNativeStore(path string) (*NativeStore, error)
NewNativeStore loads registrations from path (empty if it does not exist).
func (*NativeStore) All ¶ added in v0.45.0
func (s *NativeStore) All() []NativeRegistration
All returns a snapshot, ordered by device id.
func (*NativeStore) Get ¶ added in v0.45.0
func (s *NativeStore) Get(deviceID string) (NativeRegistration, bool)
Get returns a device's registration.
func (*NativeStore) Put ¶ added in v0.45.0
func (s *NativeStore) Put(r NativeRegistration) error
Put stores (or replaces) the registration of r.DeviceID.
func (*NativeStore) Remove ¶ added in v0.45.0
func (s *NativeStore) Remove(deviceID string) error
Remove deletes a device's registration. No-op if absent.
type Notification ¶
type Notification struct {
Title string `json:"title"`
Body string `json:"body,omitempty"`
SessionID string `json:"session_id,omitempty"`
Tag string `json:"tag,omitempty"` // coalesces same-session notifications on the device
// RequestID names the owner's call request of a call_request push, so a
// tap opens that request's card. Additive: absent on every other kind.
RequestID string `json:"request_id,omitempty"`
// Inbox asks the client to open the event inbox (pending events have no
// session to deep-link). The service worker turns this into /?inbox=1.
Inbox bool `json:"inbox,omitempty"`
// Kind and Level come from the policy. Level is how the device should
// present it: passive means no sound, replacing the previous one of its tag.
Kind Kind `json:"kind,omitempty"`
Level Level `json:"level,omitempty"`
// Call makes this an incoming call invitation. It is only ever sent to
// VoIP destinations, never through the notification policy.
Call *CallInvite `json:"-"`
}
Notification is the payload delivered (encrypted) to the service worker, which turns it into a system notification. Keep it minimal: it ends up on the lock screen, so no prompts, tool args, paths, diffs or final text — just a type and the session title.
type Policy ¶ added in v0.45.0
type Policy struct {
// contains filtered or unexported fields
}
Policy turns signals into notifications for a Sender. Its timers (grace periods, summary windows) live in memory only: a restart forgets them, as it already forgets the question they were about.
func NewPolicy ¶ added in v0.45.0
func NewPolicy(sender Sender, cfg PolicyConfig) *Policy
NewPolicy builds a policy delivering through sender.
func (*Policy) CancelSession ¶ added in v0.45.0
CancelSession drops every grace timer of a session that is going away, and the waiting summary whose latest notification points at it: its destination no longer exists.
func (*Policy) Close ¶ added in v0.45.0
func (p *Policy) Close()
Close stops every timer, drops what waits for delivery, cancels what is being delivered and makes the policy inert.
type PolicyConfig ¶ added in v0.45.0
type PolicyConfig struct {
Summaries Summaries
// Grace overrides DefaultGrace; Window, DefaultWindow; DailyLimit,
// DefaultDailyLimit.
Grace time.Duration
Window time.Duration
DailyLimit int
// After schedules f after d and returns a stop func; Now is the clock.
// Tests replace both.
After func(d time.Duration, f func()) (stop func() bool)
Now func() time.Time
// Inline delivers on the calling goroutine instead of through the delivery
// stage (see delivery.go). For tests that assert right after Handle.
Inline bool
}
PolicyConfig tunes a Policy.
type Sender ¶ added in v0.45.0
type Sender interface {
// Notify delivers n, giving up when ctx is cancelled.
Notify(ctx context.Context, n Notification)
}
Sender is a transport: it delivers a notification the policy already decided on. The Web Push Dispatcher is one.
type Senders ¶ added in v0.45.0
type Senders []Sender
Senders delivers through several transports, in order.
type Signal ¶ added in v0.45.0
type Signal struct {
Kind Kind
// SessionID is what tapping the notification opens; empty with Inbox.
SessionID string
Inbox bool
// Title is the session's title: the "which one", never the specifics.
Title string
// Headline replaces the default headline of the kind (events name their source).
Headline string
// Project groups digests: one notification per project, the next replacing
// the previous. Source does the same for events.
Project string
Source string
// RequestID identifies an ask or a permission for the grace period.
RequestID string
// Watched: somebody has this session visible right now.
Watched bool
// StillPending is asked when the grace period ends; false drops the
// notification (answered, cancelled, session gone). Nil means yes.
StillPending func() bool
}
Signal is something that happened, as the policy needs to know it.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a thread-safe, disk-backed set of Web Push subscriptions keyed by endpoint. Single-user personal use over the tailnet — no per-user identity; a subscription is one browser/device that opted in.
func (*Store) Add ¶
func (s *Store) Add(sub webpush.Subscription) error
Add stores (or replaces) a subscription by endpoint and persists. Idempotent.
func (*Store) All ¶
func (s *Store) All() []webpush.Subscription
All returns a snapshot slice of the current subscriptions.
type Summaries ¶ added in v0.45.0
type Summaries string
Summaries is how owner digests and events are announced. It is the one knob of the policy that is provisional: the owner will revisit it after using it.
func ParseSummaries ¶ added in v0.45.0
ParseSummaries maps a config value to a mode; anything unknown is the default.
type VAPID ¶
VAPID is the server's VAPID key pair (RFC 8292). The public key is shared with browsers (application server key); the private key signs the VAPID JWT and must stay secret (persisted 0600).
func LoadOrGenerateVAPID ¶
LoadOrGenerateVAPID reads the VAPID key pair from path, generating and persisting a new pair (0600) on first use. The pair is stable across restarts so existing browser subscriptions keep working.