push

package
v0.280.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 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 is muster's own Web Push: the VAPID identity, the per-owner subscription store (migration 0013, under row-level security), and the Service that delivers one owner's notification to that owner's devices and prunes the ones the push service reports gone.

It is a port of the permission router's internal/push (Service, Pusher, redact), with two deliberate differences:

  • 🔴 SUBSCRIPTIONS ARE OWNED. The router's store is one flat set: every device got every notification, which is correct for a service with one operator and a cross-user leak for a service with members. Here the only send is SendTo(owner, …), and the only read it makes is that owner's rows.
  • 🔴 THE VAPID SUBJECT IS PASSED AS webpush-go WANTS IT, NOT AS CONFIGURED. webpush-go v1.4.0 prepends "mailto:" to any subject that does not start with "https:", so a configured "mailto:ops@example.com" is signed as "mailto:mailto:ops@example.com" — a malformed JWT `sub` that a strict push service (Apple's) refuses. See WebpushPusher.Send.

muster signs with its OWN keypair (MUSTER_VAPID_*), not the router's: a browser subscription is bound to the application-server key it was made with, and is per origin, so the router's subscriptions could never have been reused here anyway.

Index

Constants

View Source
const (
	EventReview    = "review"    // a task enters ready_for_review
	EventResolved  = "resolved"  // a task leaves review: clears its notification
	EventConnector = "connector" // an agent requests a connector
	EventAgent     = "agent"     // a task's agent is up and working
	EventCreated   = "created"   // a machine (producer) created tasks
	EventComment   = "comment"   // an external (machine) comment on a task
	EventPlugin    = "plugin"    // a plugin reply draft awaits its owner's approval, or the chief routed something to a session
	EventAttention = "attention" // something new in the attention queue: an agent's question, a session waiting
	// EventAgentOutcome: an agent started with a first turn finished, failed or
	// went quiet (internal/agentoutcome) — one push per change of its outcome.
	EventAgentOutcome = "agent_outcome"
	// EventPage: a viewer sent something through a shareable page's link
	// (internal/pages) — at most one push per page a minute.
	EventPage = "page"
	// EventPagePublished: an agent published a new page for its owner.
	EventPagePublished = "page_published"
	// EventPageShared: an agent made one of its owner's pages public without
	// asking (the owner's own opt-in). Its OWN toggle, apart from
	// page_published: muting "a page is ready" must never also hide the one
	// notice that a page went public.
	EventPageShared = "page_shared"
	// EventMorningReport: the morning report — once a day, only on a day
	// something happened (internal/morning) — counts only, tapping opens it.
	EventMorningReport = "morning_report"
	// EventPageUpdated: an agent published a NEW VERSION of one of its
	// owner's pages (page_update). Its OWN toggle, apart from page_published:
	// an agent iterating on a page publishes many versions, and an owner who
	// wants to hear of new pages may not want every revision — muting the
	// revisions must never also hide a new page (the page_shared precedent).
	EventPageUpdated = "page_updated"
	// EventAgentNotify: one of the owner's agents sent them a notification
	// of its own (the notify_owner tool, internal/api/notify_owner.go).
	EventAgentNotify = "agent_notify"
	// EventApp: one of the owner's `app` plugins asked muster to tell them
	// something from the fixed set whose text muster writes (POST
	// /plugin/v1/notify, internal/api/plugin_notify.go): v1's one kind is a
	// knock, someone waiting to join a meeting.
	EventApp = "app"
)

The notification events a user can receive, each with a toggle on /account.

🔴 EVERY ONE IS ON BY DEFAULT (operator decision): push_preferences stores what a user MUTED, so a user who never opened the page gets everything. That is also why a per-owner rate cap and muster_push_delivery_total ship with it rather than later — "everything on" is the amplification risk.

View Source
const (
	ActionAskAnswer  = "ask_answer"
	ActionAskDismiss = "ask_dismiss"
)

The action wire ids payload v2 may name: the app's table, exact strings (docs/design/android.md, "Action ids"). internal/api routes each (deviceActionRoutes) and its ledger test holds the two to the table.

View Source
const (
	MaxNativeTitle = 100
	MaxNativeBody  = 200
	MaxNativeChip  = 140
	MaxNativeChips = 3
)

MaxNativeTitle and MaxNativeBody are the longest title and body payload v2 carries, in characters (runes); MaxNativeChip the longest option or suggestion it carries as a chip, MaxNativeChips how many of each. Even with every character of the two lines JSON-escaped to six bytes they total (100 + 200) × 6 = 1800 bytes, inside NativeMaxPlaintext with room for the envelope — so the fit never has to shorten the question (TestTheWorstCaseAskStillFitsWithItsQuestion measures it).

⚠ MaxNativeBody IS THE ANDROID APP'S OWN CUT (muster-android PayloadV2.MAX_BODY = 200): a longer body would be cut again on the phone, so a question's options line, kept whole here, would be lost there. Raise both together.

View Source
const (
	ResultOK      = "ok"
	ResultExpired = "expired"
	ResultFailed  = "failed"
	// ResultDisallowed is a device whose endpoint is no longer on an allowed
	// push service: nothing is sent, and the row is pruned.
	ResultDisallowed = "disallowed"
	// ResultOversize is a native push refused before sending: its payload v2
	// would not fit in one 4096-byte encrypted body (ErrNativeTooLarge).
	ResultOversize = "oversize"
)

Delivery results, the closed label set of muster_push_delivery_total.

View Source
const (
	KindBrowser = "browser"
	KindAndroid = "android"
)

The subscription kinds (push_subscriptions.kind). A native device gets payload v2 and the silent "resolved" withdrawal; a browser gets what the service worker reads.

View Source
const MaxDevicesPerOwner = 20

MaxDevicesPerOwner bounds one user's subscriptions. Every send fans out to all of them, so the cap is also a bound on what one notification costs.

View Source
const (

	// NativeMaxPlaintext is the largest payload v2, in bytes, that encrypts
	// into nativeRecordSize: 4096 - 86 - 16 - 1 = 3993.
	NativeMaxPlaintext = nativeRecordSize - aes128gcmHeaderLen - aes128gcmTagLen - paddingDelimiter
)

The size of one native push, by RFC 8188 (aes128gcm) as webpush-go builds it: ONE record of nativeRecordSize bytes — the header (salt, record size, key-id length, the sender's P-256 public key), then the plaintext, its padding delimiter and zero padding up to the record, then the GCM tag. webpush-go pads every message to the full record, so EVERY native body is exactly nativeRecordSize bytes, and it refuses a plaintext over NativeMaxPlaintext itself (webpush.ErrMaxPadExceeded): TestTheEncryptedNativeBodyIsAtMost4096Bytes measures both.

⚠ SO NTFY'S TRUNCATION CANNOT HAPPEN TO A PUSH FROM HERE. ntfy accepts an `up*` message over its message-size-limit (4096 bytes by default) with 200 and silently truncates it (Phase 0, S9), which matters for a sender that does not pad to one record; with the record pinned at 4096, muster's bodies never exceed it. What the cap below adds is the ANSWER: an over-budget payload is refused BEFORE the pusher, named `oversize` in the log and the counter, and does not count against the device's fail_count as the library's encryption error would.

View Source
const TypeResolved = "resolved"

TypeResolved is the payload type the service worker reads as "close the notification with this tag and show nothing".

Variables

View Source
var ErrBadExtraHost = errors.New("push: an extra push host must be a bare DNS host name")

ErrBadExtraHost refuses a MUSTER_PUSH_EXTRA_HOSTS entry that is not a bare host name.

View Source
var ErrBadSubscription = errors.New("push: invalid subscription")

ErrBadSubscription is the refusal for a subscription muster will not store.

View Source
var ErrBadVAPID = errors.New("push: invalid VAPID configuration")

ErrBadVAPID is the refusal for a VAPID configuration that would sign messages no push service accepts.

View Source
var ErrDeviceGone = errors.New("push: the paired device is gone")

ErrDeviceGone refuses a native claim for a device that is not (or no longer) the owner's: removed, or revoked, between its request and the claim.

View Source
var ErrNativeEndpoint = errors.New("push: that endpoint belongs to a paired phone")

ErrNativeEndpoint refuses a browser claim of an endpoint a paired phone holds.

View Source
var ErrNativeTooLarge = fmt.Errorf("push: a native payload is larger than %d bytes, so it does not fit in one %d-byte record", NativeMaxPlaintext, nativeRecordSize)

ErrNativeTooLarge refuses a payload v2 that would not fit in one 4096-byte record.

View Source
var ErrPushServiceNotAllowed = errors.New("push: the endpoint is not on a known push service")

ErrPushServiceNotAllowed refuses an endpoint on a host that is not a known browser push service or a push host the operator named (MUSTER_PUSH_EXTRA_HOSTS).

View Source
var ErrRedirectRefused = errors.New("push: the push service answered with a redirect, which muster does not follow")

ErrRedirectRefused is a send the push service answered with a redirect. muster does not follow it, and the send counts as failed.

View Source
var ErrTooManyDevices = fmt.Errorf("push: a user may have at most %d devices; remove one on the account page", MaxDevicesPerOwner)

ErrTooManyDevices refuses a claim past MaxDevicesPerOwner.

View Source
var Events = []Event{
	{EventReview, "A task is ready for review"},
	{EventResolved, "Clear a task's notification when it leaves review"},
	{EventConnector, "An agent requests a connector"},
	{EventAgent, "A task's agent is up and working"},
	{EventCreated, "A machine created tasks"},
	{EventComment, "A machine commented on a task"},
	{EventPlugin, "A reply draft awaits your approval, or your chief routed something to a session"},
	{EventAttention, "An agent asks you something, or a session is waiting on you"},
	{EventAgentOutcome, "An agent you started finished, failed or went quiet"},
	{EventPage, "Someone sent a response through one of your pages' links"},
	{EventPagePublished, "An agent published a page for you"},
	{EventPageShared, "An agent shared one of your pages without asking (anyone with its link can open it)"},
	{EventMorningReport, "Your morning report: what happened while you were away"},
	{EventPageUpdated, "An agent published a new version of one of your pages"},
	{EventAgentNotify, "An agent sent you a notification"},
	{EventApp, "An app needs you"},
}

Events is the closed vocabulary, in the order /account shows it.

Functions

func CutClusters

func CutClusters(s string, n int) string

CutClusters cuts s to at most n runes, ending with "…" when it cut, without splitting what a reader sees as one character: it backs off over combining marks, variation selectors, skin-tone modifiers, emoji tag characters, a zero-width joiner on either side of the cut, and half a regional-indicator flag. A cheap approximation of Unicode grapheme clusters (no tables), for a notification line, not a text engine.

func EndpointHash

func EndpointHash(endpoint string) string

EndpointHash is the full hex sha256 of an endpoint. It is what the browser's device cookie carries (see api's push routes): enough to name this browser's subscription at logout without the cookie holding the capability itself.

func Fingerprint

func Fingerprint(endpoint string) string

Fingerprint is 8 hex characters of the endpoint's sha256: an identifier for logs and pages that does not reveal the endpoint.

func GenerateVAPIDKeys

func GenerateVAPIDKeys() (privateKey, publicKey string, err error)

GenerateVAPIDKeys returns a fresh base64url (unpadded) P-256 keypair.

func KnownEvent

func KnownEvent(name string) bool

KnownEvent reports whether name is in Events.

func ParseExtraHosts

func ParseExtraHosts(v string) ([]string, error)

ParseExtraHosts reads MUSTER_PUSH_EXTRA_HOSTS: host names separated by commas or white space. Each must be a bare DNS name — no scheme, port, path, wildcard, leading dot or IP literal — and is lower-cased. Empty is no hosts. A deployment that typed the variable wrong must fail to start rather than run with an allowlist it did not choose.

func Redact

func Redact(err error, endpoint string) string

Redact renders err for a log line with every occurrence of endpoint replaced by its Short form.

🔴 TRUNCATING THE ENDPOINT IN ONE Printf ARGUMENT DOES NOTHING IF THE NEXT ARGUMENT IS AN ERROR THAT EMBEDS IT. webpush-go returns http.Client.Do's error unwrapped; for a transport failure that is a *url.Error, whose Error() is `Post "<the whole endpoint>": …`. So every log line that interpolates an error goes through here, and it scrubs the STRING that reaches the output — agnostic to the error's type (a wrapped *url.Error, a driver error quoting a bind parameter). *url.Error prints the RE-SERIALISED URL, which can differ from the raw endpoint (escaping, normalisation), so that form is scrubbed too.

func Short

func Short(endpoint string) string

Short renders an endpoint for a log line or a page: the push service's host and a fingerprint, never the path.

🔴 A PUSH ENDPOINT IS A CAPABILITY, NOT A LONG STRING. Anyone holding one can make that device buzz with no further credential. The router's version kept the first 60 characters, which for an FCM endpoint (`https://fcm.googleapis.com/fcm/send/` is 36) is 24 characters of the device's token in every log line. The path is where the capability lives, so none of it is shown; the fingerprint (8 hex of its sha256) is enough to tell two devices apart in a log and correlate one across lines.

Types

type Allowlist

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

Allowlist is the set of hosts muster will POST a push to: the browser push services (pushServiceHosts) and the operator's own push hosts (MUSTER_PUSH_EXTRA_HOSTS), such as a self-hosted ntfy that serves UnifiedPush to the Android app (docs/design/android.md).

🔴 TWO QUESTIONS, TWO METHODS. AllowsBrowser is the browser push services alone: the only hosts a BROWSER subscription (Claim, /api/push/subscribe) may name, so a session can never point muster at an operator host. Allows adds the operator hosts: the paired phones' UnifiedPush endpoints (ClaimNative). SendTo re-checks every row with the method for its kind at send time, so removing a host from the configuration stops every POST to it on the next notification.

🔴 AN OPERATOR HOST MATCHES BY EXACT NAME ONLY. No suffix, no wildcard, no port: a member chooses only the PATH on a host the operator named. The https-only, default-port rule applies to it as to the browser hosts, and with redirects refused (pushHTTPClient) a send cannot be bounced from a listed host to an unlisted one. There is deliberately no check of the address the name resolves to: an in-cluster ntfy whose name resolves to a private address is a reasonable deployment (design doc, server change 21).

func NewAllowlist

func NewAllowlist(extra []string) Allowlist

NewAllowlist is the browser push services plus extra, which must already be clean (ParseExtraHosts).

func (Allowlist) Allows

func (a Allowlist) Allows(endpoint string) bool

Allows reports whether endpoint is an https URL on the default port whose host is a browser push service or, exactly, one of the operator's hosts.

func (Allowlist) AllowsBrowser

func (a Allowlist) AllowsBrowser(endpoint string) bool

AllowsBrowser reports whether endpoint is an https URL on the default port on a browser push service. The operator's hosts do not count.

func (Allowlist) ExtraHosts

func (a Allowlist) ExtraHosts() []string

ExtraHosts is the operator's hosts, in the order configured.

type Device

type Device struct {
	ID        int64
	OwnerID   int64
	Sub       Subscription
	UserAgent string
	CreatedAt time.Time
	LastOKAt  *time.Time
	FailCount int
	// Kind is KindBrowser for a browser's PushSubscription and KindAndroid for
	// a paired phone's UnifiedPush endpoint (migration 0039).
	Kind string
	// DeviceID is the paired device (internal/devices) a KindAndroid
	// subscription belongs to; 0 for a browser.
	DeviceID int64
}

Device is one stored subscription.

type Event

type Event struct {
	Name  string
	Label string
}

Event is one toggle.

type PGStore

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

PGStore is Store over Postgres (migration 0013).

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG builds the Postgres store. It admits the browser push services only; WithAllowlist adds the operator's hosts.

func (*PGStore) Allowlist

func (s *PGStore) Allowlist() Allowlist

Allowlist implements Store.

func (*PGStore) Claim

func (s *PGStore) Claim(ctx context.Context, owner int64, sub Subscription, userAgent string) (int64, error)

Claim stores sub as owner's, moving it from whoever held the endpoint before (the shared-device case: one browser, one subscription per origin, a second user signed in). It returns the previous owner when the endpoint moved, 0 otherwise.

🔴 owner COMES FROM THE CALLER'S PRINCIPAL, NEVER FROM THE REQUEST BODY — the handler passes requestOwner(ctx). It runs under System because the row it may have to move is invisible to the claimant under row-level security.

func (*PGStore) ClaimNative

func (s *PGStore) ClaimNative(ctx context.Context, owner, deviceID int64, sub Subscription, label string) error

ClaimNative implements Store. It runs under System because the device row it names is under row-level security and the push row may be another user's (an endpoint moved between phones); every statement is filtered by owner and device, both of which come from the device credential, never from the request body.

🔴 THE ALLOWLIST AND THE DEVICE CAP APPLY AS TO A BROWSER: the endpoint must be on an allowed push service (Allowlist), and the owner's subscriptions, browser and native together, stay at most MaxDevicesPerOwner.

func (*PGStore) Devices

func (s *PGStore) Devices(ctx context.Context) ([]Device, error)

Devices lists the CALLER's devices (row-level security).

func (*PGStore) ForOwner

func (s *PGStore) ForOwner(ctx context.Context, owner int64) ([]Device, error)

ForOwner lists owner's devices, for a send. System, filtered by owner.

func (*PGStore) ForgetDevice

func (s *PGStore) ForgetDevice(ctx context.Context, owner int64, endpointHash string) (bool, error)

ForgetDevice deletes owner's subscription whose endpoint hashes to endpointHash: the browser that is signing out (its device cookie). It runs under System because logout has no principal; it is filtered by owner, so a cookie naming another user's device deletes nothing.

func (*PGStore) ForgetNative

func (s *PGStore) ForgetNative(ctx context.Context, owner, deviceID int64) (bool, error)

ForgetNative implements Store.

func (*PGStore) MarkDelivered

func (s *PGStore) MarkDelivered(ctx context.Context, d Device) error

MarkDelivered stamps a successful delivery. Keyed by (id, owner) so a row that changed hands mid-send is not stamped for the new owner.

func (*PGStore) MarkFailed

func (s *PGStore) MarkFailed(ctx context.Context, d Device) error

MarkFailed counts a failed (non-expired) delivery.

func (*PGStore) Muted

func (s *PGStore) Muted(ctx context.Context, owner int64) ([]string, error)

Muted reads owner's muted events. System, filtered by owner. A user with no preference row has nothing muted: every event is on by default.

func (*PGStore) MyMuted

func (s *PGStore) MyMuted(ctx context.Context) ([]string, error)

MyMuted reads the CALLER's muted events (row-level security).

func (*PGStore) Prune

func (s *PGStore) Prune(ctx context.Context, d Device) (bool, error)

Prune deletes a device the push service reported gone (404/410). Keyed by (id, owner, endpoint): a row re-claimed by another user, or re-subscribed with a fresh endpoint, between the send and the prune is left alone.

func (*PGStore) Remove

func (s *PGStore) Remove(ctx context.Context, id int64) (bool, error)

Remove deletes one of the CALLER's devices by id (row-level security: another user's id matches nothing).

func (*PGStore) SetMuted

func (s *PGStore) SetMuted(ctx context.Context, muted []string) error

SetMuted replaces the CALLER's muted events. Names outside Events are dropped, so the stored set is always a subset of the vocabulary.

func (*PGStore) Unsubscribe

func (s *PGStore) Unsubscribe(ctx context.Context, endpoint string) (bool, error)

Unsubscribe deletes the CALLER's subscription for endpoint, if it holds it.

func (*PGStore) WithAllowlist

func (s *PGStore) WithAllowlist(a Allowlist) *PGStore

WithAllowlist sets the hosts a claimed endpoint may be on.

type Payload

type Payload struct {
	Type  string            `json:"type"`
	ID    string            `json:"id,omitempty"`
	Title string            `json:"title,omitempty"`
	Body  string            `json:"body,omitempty"`
	Tag   string            `json:"tag,omitempty"`
	Data  map[string]string `json:"data,omitempty"`
	Ask   *V2Ask            `json:"-"`
	// Update: this notification replaces one already shown under Tag (an ask's
	// suggested replies arrived). Payload v2 only; the browser worker replaces
	// by tag without renotifying anyway.
	Update bool `json:"-"`
	// AskActions: the server routes the signed ask actions, so payload v2
	// offers them (PayloadV2.Actions). Payload v2 only.
	AskActions bool `json:"-"`
	// Icon is the notification's icon URL: the instance logo's 192 px icon
	// when one is set, muster's own otherwise (internal/api sendPush stamps
	// it; docs/branding.md). The service worker draws it, falling back to
	// muster's icon when it is absent. BROWSER ONLY: payload v2 never carries
	// it — the Android app reads the logo from GET /api/instance itself.
	Icon string `json:"icon,omitempty"`
	// Silent: show this notification WITHOUT sound or vibration — a re-show
	// of one the device already alerted for (a session-state stop back from a
	// blip, internal/api session_push.go). The service worker passes it as the
	// Notifications API's `silent` (with `renotify: false`). 🔴 SENT ONLY TO
	// DEVICES THAT HONOUR IT (silentCapable): a native device's app as shipped
	// ignores payload v2's "update" and alerts on every post, and Safari
	// ignores `silent`; both are skipped — a missing re-show, never a buzz.
	Silent bool `json:"silent,omitempty"`
}

Payload is the JSON the service worker's `push` handler reads (web/static/sw.js): type "resolved" closes notifications by tag and shows nothing; any other type shows Title/Body and opens Data["url"] on a tap.

Ask is the NATIVE device's extra for an attention ask (its id, the asker's options and the suggested replies), carried in payload v2 only: the browser worker has no chips to draw (and keeps `actions: []`), so it is never in the browser's JSON.

func (Payload) V2

func (p Payload) V2() PayloadV2

V2 is p as a native device receives it. A "resolved" carries only its type, id and tag: it shows nothing.

type PayloadV2

type PayloadV2 struct {
	V     int    `json:"v"`
	Type  string `json:"type"`
	ID    string `json:"id,omitempty"`
	Tag   string `json:"tag,omitempty"`
	Title string `json:"title,omitempty"`
	Body  string `json:"body,omitempty"`
	URL   string `json:"url,omitempty"`
	Ask   *V2Ask `json:"ask,omitempty"`
	// Update: replace the notification shown under Tag without alerting again
	// (NotificationCompat's setOnlyAlertOnce); absent for a new one.
	Update bool `json:"update,omitempty"`
	// Actions are the ask's signed actions (see above); none otherwise.
	Actions []V2Action `json:"actions,omitempty"`
}

PayloadV2 is what a NATIVE device (KindAndroid) receives in place of Payload: the Android app's payload (docs/design/android.md, "Payload v2").

🔴 THE BROWSER PAYLOAD'S OWN LINES, CUT, PLUS THE ASK'S CHIPS. Title and Body are the browser payload's own lines, cut on a character-cluster boundary to MaxNativeTitle and MaxNativeBody. For an ask and a held question they carry the question and its options (operator decision "Full text always", which replaced "Summary only" for them: see docs/attention.md), so the phone is sent the same text the browser is. Every OTHER notification — a waiting session's included — still says WHO and WHERE only; that is each helper's own rule, not this type's. URL is where a tap opens, a path on muster.

Ask (an attention ask only) is what the app draws as chips: the ask's id, the asker's options and the suggested replies. A payload that does not fit NativeMaxPlaintext drops the suggestions first, then the options (nativeBody): the question outlives every chip.

Actions (an attention ask, where the server routes the signed actions) are the notification's buttons: each option and suggestion carried as a chip, an inline-reply Answer, and Dismiss — each naming a wire id from the app's fixed table (docs/design/android.md, "Action ids"), never a route, so the server cannot make the app POST anywhere else. They follow the chips: a chip the fit drops takes its action with it.

⚠ NO `conv` OR `state` YET. The state delta feeds the widgets (Phase 4), and sending a field no code reads would be a promise nothing keeps.

type Pusher

type Pusher interface {
	Send(ctx context.Context, sub Subscription, payload []byte) SendResult
}

Pusher sends one encrypted message to one subscription. An interface so a test never touches the network.

type Report

type Report struct {
	Devices   int
	Delivered int
	Expired   int
	Failed    int
}

Report is what one SendTo did. Devices is how many the owner had.

type SendResult

type SendResult struct {
	// StatusCode is the push service's status, or 0 when the request never
	// completed.
	StatusCode int
	// Expired: the push service says the subscription is gone (404/410); prune it.
	Expired bool
	Err     error
}

SendResult is one delivery attempt's outcome.

type Service

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

Service sends one owner's notifications to that owner's devices.

func NewService

func NewService(store Store, pusher Pusher, vapid VAPIDConfig, logger *log.Logger) *Service

NewService builds the Service. logger may be nil.

func (*Service) Allowlist

func (s *Service) Allowlist() Allowlist

Allowlist is the store's allowlist: the one source for what may be stored and what may be sent to.

func (*Service) Probe

func (s *Service) Probe(ctx context.Context, sub Subscription, payload []byte) SendResult

Probe sends payload to sub, a subscription that is NOT stored: the test push a paired device's registration must pass before it is kept (as UnifiedPush recommends). It settles nothing and touches no row; the caller reads the result.

func (*Service) PublicKey

func (s *Service) PublicKey() string

PublicKey is the VAPID public key browsers subscribe with.

func (*Service) SendTo

func (s *Service) SendTo(ctx context.Context, owner int64, p Payload) Report

SendTo delivers p to every device OWNER holds — and to nobody else's — in parallel, pruning devices the push service reports gone (404/410) and stamping last_ok_at / fail_count on the rest. It never returns an error: a notification is best-effort at every call site, so every failure is LOGGED (redacted) and COUNTED (muster_push_delivery_total) instead, which is what keeps a dead pipeline from looking like a quiet one.

func (*Service) Store

func (s *Service) Store() Store

Store is the subscription store (the HTTP handlers' reads and writes).

type Store

type Store interface {
	Claim(ctx context.Context, owner int64, sub Subscription, userAgent string) (previousOwner int64, err error)
	Devices(ctx context.Context) ([]Device, error)
	Remove(ctx context.Context, id int64) (bool, error)
	Unsubscribe(ctx context.Context, endpoint string) (bool, error)

	ForOwner(ctx context.Context, owner int64) ([]Device, error)
	MarkDelivered(ctx context.Context, d Device) error
	MarkFailed(ctx context.Context, d Device) error
	Prune(ctx context.Context, d Device) (bool, error)
	ForgetDevice(ctx context.Context, owner int64, endpointHash string) (bool, error)

	// ClaimNative stores sub as paired device deviceID's one subscription
	// (KindAndroid), replacing any it held; ForgetNative removes it. Both
	// System, filtered by owner AND device: the device credential's request
	// names both, and the device row is under row-level security.
	ClaimNative(ctx context.Context, owner, deviceID int64, sub Subscription, label string) error
	ForgetNative(ctx context.Context, owner, deviceID int64) (bool, error)

	// Muted is owner's muted events, for a send (System, filtered by owner).
	Muted(ctx context.Context, owner int64) ([]string, error)
	// Allowlist is the hosts a subscription may be on: the ONE allowlist,
	// which Claim enforces when a row is stored and push.Service re-checks at
	// every send.
	Allowlist() Allowlist
	// MyMuted / SetMuted are the CALLER's preferences (row-level security).
	MyMuted(ctx context.Context) ([]string, error)
	SetMuted(ctx context.Context, muted []string) error
}

Store is the subscription persistence.

🔴 TWO KINDS OF METHOD, AND WHICH IS WHICH IS THE WHOLE SECURITY STORY.

  • The REQUEST methods (Devices, Remove, Unsubscribe) run under the caller's principal: push_subscriptions is under FORCE row-level security (0013), so they see and change only that user's rows.
  • The SYSTEM methods (Claim, ForOwner, MarkDelivered, MarkFailed, Prune, ForgetDevice) run under authz.System through this package's one helper, sys, which is ledgered in internal/authz/ledger_test.go. Each exists because no principal can do its job: a send runs from loops and hooks with no request; a claim must see another user's row to move it; a logout has already ended its session. EACH ONE FILTERS ON AN EXPLICIT OWNER (or a row id it was handed with its owner) — under System that WHERE clause is the only isolation there is.

type Subscription

type Subscription struct {
	Endpoint string `json:"endpoint"`
	Keys     struct {
		P256dh string `json:"p256dh"`
		Auth   string `json:"auth"`
	} `json:"keys"`
}

Subscription is a browser PushSubscription as PushSubscription.toJSON() serialises it: the endpoint and the two client keys.

func (Subscription) Check

func (s Subscription) Check() error

Check refuses a subscription that cannot be sent to, or whose endpoint is not an https URL on a host (the push service). It does not decide WHICH push services are acceptable: browsers choose, and the set changes.

type V2Action

type V2Action struct {
	ID         string `json:"id"`
	Label      string `json:"label,omitempty"`
	Target     string `json:"target"`
	Option     *int   `json:"option,omitempty"`
	Suggestion *int   `json:"suggestion,omitempty"`
	Input      bool   `json:"input,omitempty"`
}

V2Action is one notification button. ID is a wire id; Target the ask's id (the route's {id}). An ask_answer button that sends a chip names it BY INDEX — Option into ask.options, or Suggestion into ask.suggestions — and its label and answer are that chip's text, exactly: each chip's text is in the push once, so the buttons cost the chips no room (TestButtonsCostTheChipsNothing). Input marks the inline-reply Answer the user types. Label is set only for a button with no chip (Answer, Dismiss).

type V2Ask

type V2Ask struct {
	ID          int64    `json:"id"`
	Options     []string `json:"options,omitempty"`
	Suggestions []string `json:"suggestions,omitempty"`
}

V2Ask is an attention ask's chips in payload v2. Each option and suggestion is WHOLE or absent — a chip whose text was cut would answer something the asker did not offer — so one longer than MaxNativeChip runes is left out of the chips (the body still lists it, cut, and the ask page shows it whole).

type VAPIDConfig

type VAPIDConfig struct {
	PublicKey  string
	PrivateKey string
	Subject    string
}

VAPIDConfig is the application-server identity. PublicKey is handed to browsers so they can subscribe; PrivateKey signs each message's JWT; Subject is the contact the JWT names: "mailto:<address>" or an https URL.

func (VAPIDConfig) Validate

func (c VAPIDConfig) Validate() error

Validate checks that the three values are a usable identity: both keys decode to a P-256 keypair, the private key DERIVES the public key, and the subject is a clean mailto: address or an https URL.

🔴 THE DERIVATION CHECK IS THE ONE THAT MATTERS. Two valid keys from two different generations pass every shape check, boot, hand browsers the public key, and then every message is signed by a key the subscription was not made with — the push service answers 401/403 for every send, forever, and the only symptom is silence. So is a pair pasted the wrong way round.

type WebpushPusher

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

WebpushPusher is the production Pusher (webpush-go).

func NewWebpushPusher

func NewWebpushPusher(vapid VAPIDConfig) *WebpushPusher

NewWebpushPusher builds a Pusher signing with vapid. Its HTTP client has a short timeout so a stuck push service cannot hold a fan-out open, and it never follows a redirect (pushHTTPClient).

func (*WebpushPusher) Send

func (p *WebpushPusher) Send(ctx context.Context, sub Subscription, payload []byte) SendResult

Send encrypts payload for sub and POSTs it. 2xx is success; 404/410 expire; a 3xx is a failed send (ErrRedirectRefused), never followed.

Jump to

Keyboard shortcuts

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