push

package
v0.45.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 26 Imported by: ? 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

Index

Constants

View Source
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
)
View Source
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.

View Source
const DefaultRelayURL = "https://push.letmoa.run"

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.

View Source
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

func NormalizeRelayURL(raw string) (string, error)

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 SignSend added in v0.45.0

func SignSend(sendKey, body []byte) string

SignSend authorizes exactly these body bytes.

Types

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

type Envelope struct {
	V   int    `json:"v"`
	KID string `json:"k"`
	C   string `json:"c"`
}

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"`
}

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
	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
)

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"`
	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.

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) 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

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
	// 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"`
}

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

func (p *Policy) CancelSession(sessionID string)

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.

func (*Policy) Handle added in v0.45.0

func (p *Policy) Handle(s Signal)

Handle applies the policy to a signal.

func (*Policy) Resolved added in v0.45.0

func (p *Policy) Resolved(kind Kind, sessionID, requestID string)

Resolved drops the grace timer of a request that was answered.

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.

func (Senders) Notify added in v0.45.0

func (ss Senders) Notify(ctx context.Context, n Notification)

Notify hands n to each transport.

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 NewStore

func NewStore(path string) (*Store, error)

NewStore loads subscriptions from path (empty if the file does not exist yet).

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.

func (*Store) Len

func (s *Store) Len() int

Len reports how many subscriptions are stored.

func (*Store) Remove

func (s *Store) Remove(endpoint string) error

Remove deletes a subscription by endpoint and persists. No-op if absent.

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.

const (
	SummariesPassive Summaries = "passive" // default: silent, one per group, replaced by the next
	SummariesActive  Summaries = "active"  // as loud as a finished run
	SummariesOff     Summaries = "off"     // never notify
)

func ParseSummaries added in v0.45.0

func ParseSummaries(s string) Summaries

ParseSummaries maps a config value to a mode; anything unknown is the default.

type VAPID

type VAPID struct {
	Public  string `json:"public"`
	Private string `json:"private"`
}

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

func LoadOrGenerateVAPID(path string) (VAPID, error)

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.

Jump to

Keyboard shortcuts

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