Skip to content

Modern Docker Management, Designed for Everyone

feat: add native apple push notifications for the ios app (#3783)

Kyle Mendell4b1abefec6b9
diff --git a/backend/api/api.go b/backend/api/api.go
index ef1aeef64..494a30b42 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
"github.com/getarcaneapp/arcane/backend/v2/internal/apikey"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/apns"
"github.com/getarcaneapp/arcane/backend/v2/internal/appimages"
"github.com/getarcaneapp/arcane/backend/v2/internal/auth"
"github.com/getarcaneapp/arcane/backend/v2/internal/build"
@@ -252,6 +253,7 @@ type HandlerDeps struct {
Version *version.VersionService
Notification *notification.Module
ApiKey *apikey.Module
+ Apns *apns.Module
Federated *federated.FederatedCredentialService
GitRepository *gitrepo.Module
GitOpsSync *gitops.Module
@@ -435,6 +437,7 @@ func registerHandlersInternal(api huma.API, deps HandlerDeps, handlerAppCtx hand
network.RegisterNetworks(api, deps.Network, deps.Docker, deps.Activity.Service(), handlerAppCtx)
deps.Swarm.RegisterRoutes(api)
deps.Notification.RegisterRoutes(api)
+ deps.Apns.RegisterRoutes(api)
deps.Updater.RegisterRoutes(api, handlerAppCtx)
deps.Search.RegisterRoutes(api)
deps.System.RegisterRoutes(api, handlerAppCtx)
diff --git a/backend/internal/apns/handler.go b/backend/internal/apns/handler.go
new file mode 100644
index 000000000..3fcb61127
--- /dev/null
+++ b/backend/internal/apns/handler.go
@@ -0,0 +1,192 @@
+package apns
+
+import (
+ "context"
+ "net/http"
+
+ "emperror.dev/errors"
+ "github.com/danielgtaylor/huma/v2"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
+ apnstypes "github.com/getarcaneapp/arcane/types/v2/apns"
+ "github.com/getarcaneapp/arcane/types/v2/base"
+)
+
+type ApnsHandler struct {
+ service *ApnsService
+}
+
+type StatusOutput struct {
+ Body base.ApiResponse[apnstypes.Status]
+}
+
+type PairingTokenOutput struct {
+ Body base.ApiResponse[apnstypes.PairingToken]
+}
+
+type RegisterDeviceInput struct {
+ Body apnstypes.RegisterDeviceRequest
+}
+
+type DeviceOutput struct {
+ Body base.ApiResponse[apnstypes.Device]
+}
+
+type UpdateDeviceInput struct {
+ ID string `path:"id" doc:"Device ID"`
+ Body apnstypes.UpdateDeviceRequest
+}
+
+type DeviceIDInput struct {
+ ID string `path:"id" doc:"Device ID"`
+}
+
+type MessageOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+func RegisterApns(api huma.API, service *ApnsService) {
+ h := &ApnsHandler{service: service}
+ tags := []string{"Mobile Push"}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-apns-status",
+ Method: http.MethodGet,
+ Path: "/apns/status",
+ Summary: "Get mobile push status",
+ Description: "Whether mobile push is enabled and the caller's registered devices",
+ Tags: tags,
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.Status)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-apns-pairing-token",
+ Method: http.MethodPost,
+ Path: "/apns/pairing-token",
+ Summary: "Issue a pairing token",
+ Description: "Issue a short-lived signed token the mobile app presents to the push relay",
+ Tags: tags,
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.PairingToken)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "register-apns-device",
+ Method: http.MethodPost,
+ Path: "/apns/devices",
+ Summary: "Register a mobile device",
+ Tags: tags,
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.RegisterDevice)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-apns-device",
+ Method: http.MethodPatch,
+ Path: "/apns/devices/{id}",
+ Summary: "Update a mobile device",
+ Tags: tags,
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.UpdateDevice)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-apns-device",
+ Method: http.MethodDelete,
+ Path: "/apns/devices/{id}",
+ Summary: "Remove a mobile device",
+ Tags: tags,
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.DeleteDevice)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "test-apns-device",
+ Method: http.MethodPost,
+ Path: "/apns/devices/{id}/test",
+ Summary: "Send a test push",
+ Tags: tags,
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.TestDevice)
+}
+
+func apnsHTTPErrorInternal(err error) error {
+ switch {
+ case errors.Is(err, common.ErrApnsDisabled):
+ return huma.Error403Forbidden(err.Error())
+ case errors.Is(err, common.ErrApnsDeviceNotFound):
+ return huma.Error404NotFound(err.Error())
+ case errors.Is(err, common.ErrApnsDeviceConflict):
+ return huma.Error409Conflict(err.Error())
+ case errors.Is(err, common.ErrApnsRelay):
+ return huma.Error502BadGateway(err.Error())
+ default:
+ return huma.Error500InternalServerError(err.Error())
+ }
+}
+
+func (h *ApnsHandler) Status(ctx context.Context, _ *struct{}) (*StatusOutput, error) {
+ user, err := handlerutil.RequireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ status, err := h.service.Status(ctx, user.ID)
+ if err != nil {
+ return nil, apnsHTTPErrorInternal(err)
+ }
+ return &StatusOutput{Body: base.ApiResponse[apnstypes.Status]{Success: true, Data: status}}, nil
+}
+
+func (h *ApnsHandler) PairingToken(ctx context.Context, _ *struct{}) (*PairingTokenOutput, error) {
+ if _, err := handlerutil.RequireUser(ctx); err != nil {
+ return nil, err
+ }
+ token, err := h.service.IssuePairingToken(ctx)
+ if err != nil {
+ return nil, apnsHTTPErrorInternal(err)
+ }
+ return &PairingTokenOutput{Body: base.ApiResponse[apnstypes.PairingToken]{Success: true, Data: token}}, nil
+}
+
+func (h *ApnsHandler) RegisterDevice(ctx context.Context, input *RegisterDeviceInput) (*DeviceOutput, error) {
+ user, err := handlerutil.RequireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ device, err := h.service.RegisterDevice(ctx, user.ID, input.Body)
+ if err != nil {
+ return nil, apnsHTTPErrorInternal(err)
+ }
+ return &DeviceOutput{Body: base.ApiResponse[apnstypes.Device]{Success: true, Data: device}}, nil
+}
+
+func (h *ApnsHandler) UpdateDevice(ctx context.Context, input *UpdateDeviceInput) (*DeviceOutput, error) {
+ user, err := handlerutil.RequireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ device, err := h.service.UpdateDevice(ctx, user.ID, input.ID, input.Body)
+ if err != nil {
+ return nil, apnsHTTPErrorInternal(err)
+ }
+ return &DeviceOutput{Body: base.ApiResponse[apnstypes.Device]{Success: true, Data: device}}, nil
+}
+
+func (h *ApnsHandler) DeleteDevice(ctx context.Context, input *DeviceIDInput) (*MessageOutput, error) {
+ user, err := handlerutil.RequireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if err := h.service.DeleteDevice(ctx, user.ID, input.ID); err != nil {
+ return nil, apnsHTTPErrorInternal(err)
+ }
+ return &MessageOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Device removed"}}}, nil
+}
+
+func (h *ApnsHandler) TestDevice(ctx context.Context, input *DeviceIDInput) (*MessageOutput, error) {
+ user, err := handlerutil.RequireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if err := h.service.TestDevice(ctx, user.ID, input.ID); err != nil {
+ return nil, apnsHTTPErrorInternal(err)
+ }
+ return &MessageOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Test notification queued"}}}, nil
+}
diff --git a/backend/internal/apns/model.go b/backend/internal/apns/model.go
new file mode 100644
index 000000000..112dbba96
--- /dev/null
+++ b/backend/internal/apns/model.go
@@ -0,0 +1,36 @@
+package apns
+
+import (
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+)
+
+type Device struct {
+ database.BaseModel
+
+ UserID string `json:"userId" gorm:"column:user_id;not null;index"`
+ RecipientID string `json:"recipientId" gorm:"column:recipient_id;not null;uniqueIndex"`
+ Label string `json:"label" gorm:"column:label;not null;default:''"`
+ Events map[string]bool `json:"events" gorm:"column:events;serializer:json"`
+ EnvironmentIDs database.StringSlice `json:"environmentIds" gorm:"column:environment_ids;type:text"`
+ LastSeenAt *time.Time `json:"lastSeenAt,omitempty" gorm:"column:last_seen_at"`
+}
+
+func (Device) TableName() string {
+ return "apns_devices"
+}
+
+type OutboxEntry struct {
+ database.BaseModel
+
+ EventID string `gorm:"column:event_id;not null"`
+ Envelope string `gorm:"column:envelope;not null"`
+ Attempts int `gorm:"column:attempts;not null;default:0"`
+ NextAttemptAt time.Time `gorm:"column:next_attempt_at;not null;index"`
+ LastError *string `gorm:"column:last_error"`
+}
+
+func (OutboxEntry) TableName() string {
+ return "apns_outbox"
+}
diff --git a/backend/internal/apns/module.go b/backend/internal/apns/module.go
new file mode 100644
index 000000000..dea88c9bc
--- /dev/null
+++ b/backend/internal/apns/module.go
@@ -0,0 +1,27 @@
+// Package apns owns mobile push device pairing, the relay outbox, and its HTTP routes.
+package apns
+
+import "github.com/danielgtaylor/huma/v2"
+
+type Module struct {
+ service *ApnsService
+}
+
+func New(service *ApnsService) *Module {
+ return &Module{service: service}
+}
+
+func (m *Module) Service() *ApnsService {
+ if m == nil {
+ return nil
+ }
+ return m.service
+}
+
+func (m *Module) RegisterRoutes(api huma.API) {
+ if m == nil {
+ RegisterApns(api, nil)
+ return
+ }
+ RegisterApns(api, m.service)
+}
diff --git a/backend/internal/apns/service.go b/backend/internal/apns/service.go
new file mode 100644
index 000000000..a2d03508f
--- /dev/null
+++ b/backend/internal/apns/service.go
@@ -0,0 +1,638 @@
+package apns
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/mldsa"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json/v2"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+ "uuid"
+
+ "emperror.dev/errors"
+ "go.getarcane.app/sys/crypto"
+ "gorm.io/gorm"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/role"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"
+ apnstypes "github.com/getarcaneapp/arcane/types/v2/apns"
+)
+
+const (
+ FeatureName = "mobile-push-v1"
+ signatureHeader = "X-Arcane-Signature"
+ pairingFormatV1 = "arcane-pair-v1"
+ pairingTokenLifetime = 5 * time.Minute
+ maxOutboxAttempts = 10
+ outboxBatchSize = 50
+ maxTitleLen = 120
+ maxBodyLen = 500
+)
+
+type ApnsService struct {
+ db *database.DB
+ config *config.Config
+ settings *settings.SettingsService
+ roles *role.RoleService
+ events *event.EventService
+ httpClient *http.Client
+
+ drainMu sync.Mutex
+ drainPending atomic.Bool
+}
+
+func NewApnsService(db *database.DB, cfg *config.Config, settingsService *settings.SettingsService, roleService *role.RoleService, eventService *event.EventService, httpClient *http.Client) *ApnsService {
+ return &ApnsService{db: db, config: cfg, settings: settingsService, roles: roleService, events: eventService, httpClient: httpClient}
+}
+
+func (s *ApnsService) Enabled(ctx context.Context) bool {
+ return s.config != nil && !s.config.AgentMode && s.settings.GetBoolSetting(ctx, "apnsEnabled", false)
+}
+
+type signerInternal struct {
+ algorithm string
+ sign func([]byte) ([]byte, error)
+ publicKey []byte
+}
+
+func (s *ApnsService) signerInternal(ctx context.Context) (*signerInternal, error) {
+ stored := s.settings.GetStringSetting(ctx, "apnsSigningKey", "")
+ algorithm := strings.ToLower(s.config.ApnsKeyAlgorithm)
+ var seed []byte
+ if stored != "" {
+ decrypted, err := crypto.Decrypt(stored)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to decrypt push signing key")
+ }
+ alg, encoded, ok := strings.Cut(decrypted, ":")
+ if !ok {
+ return nil, errors.New("push signing key is malformed")
+ }
+ seed, err = base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to decode push signing key")
+ }
+ algorithm = alg
+ } else {
+ seed = make([]byte, 32)
+ if _, err := io.ReadFull(rand.Reader, seed); err != nil {
+ return nil, errors.WrapIf(err, "failed to generate push signing key")
+ }
+ encrypted, err := crypto.Encrypt(algorithm + ":" + base64.StdEncoding.EncodeToString(seed))
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to encrypt push signing key")
+ }
+ if err := s.settings.UpdateSetting(ctx, "apnsSigningKey", encrypted); err != nil {
+ return nil, err
+ }
+ }
+
+ switch algorithm {
+ case "ed25519":
+ key := ed25519.NewKeyFromSeed(seed)
+ return &signerInternal{
+ algorithm: algorithm,
+ publicKey: []byte(key[ed25519.SeedSize:]),
+ sign: func(msg []byte) ([]byte, error) { return ed25519.Sign(key, msg), nil },
+ }, nil
+ case "ml-dsa-87":
+ key, err := mldsa.NewPrivateKey(mldsa.MLDSA87(), seed)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to load push signing key")
+ }
+ return &signerInternal{
+ algorithm: algorithm,
+ publicKey: key.PublicKey().Bytes(),
+ sign: func(msg []byte) ([]byte, error) { return key.Sign(nil, msg, nil) },
+ }, nil
+ default:
+ return nil, errors.Errorf("unsupported push signing key algorithm %q", algorithm)
+ }
+}
+
+func (s *ApnsService) relayRequestInternal(ctx context.Context, method, path string, body []byte, signer *signerInternal) (int, []byte, error) {
+ req, err := http.NewRequestWithContext(ctx, method, s.config.ApnsRelayUrl+path, bytes.NewReader(body))
+ if err != nil {
+ return 0, nil, errors.WrapIf(err, "failed to build push relay request")
+ }
+ req.Header.Set("Content-Type", "application/json")
+ if signer != nil {
+ sig, err := signer.sign(body)
+ if err != nil {
+ return 0, nil, errors.WrapIf(err, "failed to sign push relay request")
+ }
+ req.Header.Set(signatureHeader, base64.StdEncoding.EncodeToString(sig))
+ }
+ resp, err := s.httpClient.Do(req)
+ if err != nil {
+ return 0, nil, errors.WrapIf(common.ErrApnsRelay, err.Error())
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
+ if err != nil {
+ return 0, nil, errors.WrapIf(common.ErrApnsRelay, err.Error())
+ }
+ return resp.StatusCode, respBody, nil
+}
+
+func (s *ApnsService) EnsureChannel(ctx context.Context) (string, error) {
+ if !s.Enabled(ctx) {
+ return "", common.ErrApnsDisabled
+ }
+ if channelID := s.settings.GetStringSetting(ctx, "apnsChannelId", ""); channelID != "" {
+ return channelID, nil
+ }
+ signer, err := s.signerInternal(ctx)
+ if err != nil {
+ return "", err
+ }
+ body, err := json.Marshal(map[string]string{"algorithm": signer.algorithm, "publicKey": base64.StdEncoding.EncodeToString(signer.publicKey)})
+ if err != nil {
+ return "", errors.WrapIf(err, "failed to marshal channel registration")
+ }
+ status, respBody, err := s.relayRequestInternal(ctx, http.MethodPost, "/v1/channels", body, nil)
+ if err != nil {
+ return "", err
+ }
+ if status != http.StatusCreated && status != http.StatusOK {
+ return "", errors.WrapIff(common.ErrApnsRelay, "channel registration returned %d: %s", status, strings.TrimSpace(string(respBody)))
+ }
+ var parsed struct {
+ ChannelID string `json:"channelId"`
+ }
+ if err := json.Unmarshal(respBody, &parsed); err != nil || parsed.ChannelID == "" {
+ return "", errors.WrapIf(common.ErrApnsRelay, "channel registration returned no channel id")
+ }
+ if err := s.settings.UpdateSetting(ctx, "apnsChannelId", parsed.ChannelID); err != nil {
+ return "", err
+ }
+ slog.InfoContext(ctx, "Registered push relay channel", "channelId", parsed.ChannelID, "algorithm", signer.algorithm)
+ return parsed.ChannelID, nil
+}
+
+func (s *ApnsService) ApplyEnabledUpdates(ctx context.Context, updates []libarcane.SettingUpdate, rescheduleOutbox func() error) {
+ if s == nil {
+ return
+ }
+ for _, update := range updates {
+ if update.Value == "true" {
+ if _, err := s.EnsureChannel(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to register push relay channel", "error", err)
+ }
+ continue
+ }
+ if err := s.RevokeChannel(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to revoke push relay channel", "error", err)
+ }
+ }
+ if err := rescheduleOutbox(); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule push outbox job", "error", err)
+ }
+}
+
+func (s *ApnsService) RevokeChannel(ctx context.Context) error {
+ channelID := s.settings.GetStringSetting(ctx, "apnsChannelId", "")
+ if channelID != "" {
+ signer, err := s.signerInternal(ctx)
+ if err != nil {
+ return err
+ }
+ body, err := json.Marshal(map[string]any{"channelId": channelID, "issuedAt": time.Now().UTC(), "nonce": uuid.New().String()})
+ if err != nil {
+ return errors.WrapIf(err, "failed to marshal channel revocation")
+ }
+ status, respBody, err := s.relayRequestInternal(ctx, http.MethodDelete, "/v1/channels/"+channelID, body, signer)
+ if err != nil {
+ return err
+ }
+ if status != http.StatusNoContent && status != http.StatusNotFound && status != http.StatusGone {
+ return errors.WrapIff(common.ErrApnsRelay, "channel revocation returned %d: %s", status, strings.TrimSpace(string(respBody)))
+ }
+ if err := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); err != nil {
+ return err
+ }
+ slog.InfoContext(ctx, "Revoked push relay channel", "channelId", channelID)
+ }
+ if err := s.db.WithContext(ctx).Where("1 = 1").Delete(&Device{}).Error; err != nil {
+ return errors.WrapIf(err, "failed to delete push devices")
+ }
+ return errors.WrapIf(s.db.WithContext(ctx).Where("1 = 1").Delete(&OutboxEntry{}).Error, "failed to clear push outbox")
+}
+
+func (s *ApnsService) IssuePairingToken(ctx context.Context) (apnstypes.PairingToken, error) {
+ channelID, err := s.EnsureChannel(ctx)
+ if err != nil {
+ return apnstypes.PairingToken{}, err
+ }
+ signer, err := s.signerInternal(ctx)
+ if err != nil {
+ return apnstypes.PairingToken{}, err
+ }
+ now := time.Now()
+ expiresAt := now.Add(pairingTokenLifetime)
+ payload, err := json.Marshal(struct {
+ ChannelID string `json:"channelId"`
+ Subject string `json:"sub"`
+ IssuedAt int64 `json:"iat"`
+ ExpiresAt int64 `json:"exp"`
+ Nonce string `json:"nonce"`
+ }{channelID, uuid.New().String(), now.Unix(), expiresAt.Unix(), uuid.New().String()})
+ if err != nil {
+ return apnstypes.PairingToken{}, errors.WrapIf(err, "failed to marshal pairing token")
+ }
+ sig, err := signer.sign(payload)
+ if err != nil {
+ return apnstypes.PairingToken{}, errors.WrapIf(err, "failed to sign pairing token")
+ }
+ token := pairingFormatV1 + "." + base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(sig)
+ return apnstypes.PairingToken{Token: token, ChannelID: channelID, ExpiresAt: expiresAt}, nil
+}
+
+func deviceDTOInternal(d Device) apnstypes.Device {
+ events := d.Events
+ if events == nil {
+ events = map[string]bool{}
+ }
+ envs := []string(d.EnvironmentIDs)
+ if envs == nil {
+ envs = []string{}
+ }
+ return apnstypes.Device{ID: d.ID, Label: d.Label, Events: events, EnvironmentIDs: envs, CreatedAt: d.CreatedAt, LastSeenAt: d.LastSeenAt}
+}
+
+func (s *ApnsService) Status(ctx context.Context, userID string) (apnstypes.Status, error) {
+ status := apnstypes.Status{Enabled: s.Enabled(ctx), RelayURL: s.config.ApnsRelayUrl, Devices: []apnstypes.Device{}}
+ if status.Enabled {
+ status.ChannelID = s.settings.GetStringSetting(ctx, "apnsChannelId", "")
+ }
+ var devices []Device
+ if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("created_at ASC").Find(&devices).Error; err != nil {
+ return status, errors.WrapIf(err, "failed to list push devices")
+ }
+ for _, d := range devices {
+ status.Devices = append(status.Devices, deviceDTOInternal(d))
+ }
+ return status, nil
+}
+
+func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apnstypes.RegisterDeviceRequest) (apnstypes.Device, error) {
+ if !s.Enabled(ctx) {
+ return apnstypes.Device{}, common.ErrApnsDisabled
+ }
+ events := req.Events
+ if events == nil {
+ events = map[string]bool{}
+ for _, t := range []notifications.NotificationEventType{notifications.NotificationEventImageUpdate, notifications.NotificationEventContainerUpdate, notifications.NotificationEventVulnerabilityFound, notifications.NotificationEventPruneReport, notifications.NotificationEventAutoHeal} {
+ events[string(t)] = true
+ }
+ }
+ environmentIDs := database.StringSlice(req.EnvironmentIDs)
+ if environmentIDs == nil {
+ environmentIDs = database.StringSlice{}
+ }
+ now := time.Now()
+ var existing Device
+ err := s.db.WithContext(ctx).Where("recipient_id = ?", req.RecipientID).First(&existing).Error
+ switch {
+ case err == nil && existing.UserID != userID:
+ return apnstypes.Device{}, common.ErrApnsDeviceConflict
+ case err == nil:
+ existing.Label = strings.TrimSpace(req.Label)
+ existing.Events = events
+ existing.EnvironmentIDs = environmentIDs
+ existing.LastSeenAt = &now
+ if err := s.db.WithContext(ctx).Save(&existing).Error; err != nil {
+ return apnstypes.Device{}, errors.WrapIf(err, "failed to update push device")
+ }
+ return deviceDTOInternal(existing), nil
+ case !errors.Is(err, gorm.ErrRecordNotFound):
+ return apnstypes.Device{}, errors.WrapIf(err, "failed to load push device")
+ }
+ device := Device{UserID: userID, RecipientID: req.RecipientID, Label: strings.TrimSpace(req.Label), Events: events, EnvironmentIDs: environmentIDs, LastSeenAt: &now}
+ if err := s.db.WithContext(ctx).Create(&device).Error; err != nil {
+ return apnstypes.Device{}, errors.WrapIf(err, "failed to register push device")
+ }
+ return deviceDTOInternal(device), nil
+}
+
+func (s *ApnsService) deviceInternal(ctx context.Context, userID, id string) (*Device, error) {
+ var device Device
+ if err := s.db.WithContext(ctx).Where("id = ? AND user_id = ?", id, userID).First(&device).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, common.ErrApnsDeviceNotFound
+ }
+ return nil, errors.WrapIf(err, "failed to load push device")
+ }
+ return &device, nil
+}
+
+func (s *ApnsService) UpdateDevice(ctx context.Context, userID, id string, req apnstypes.UpdateDeviceRequest) (apnstypes.Device, error) {
+ device, err := s.deviceInternal(ctx, userID, id)
+ if err != nil {
+ return apnstypes.Device{}, err
+ }
+ if req.Label != nil {
+ device.Label = strings.TrimSpace(*req.Label)
+ }
+ if req.Events != nil {
+ device.Events = *req.Events
+ }
+ if req.EnvironmentIDs != nil {
+ device.EnvironmentIDs = database.StringSlice(*req.EnvironmentIDs)
+ if device.EnvironmentIDs == nil {
+ device.EnvironmentIDs = database.StringSlice{}
+ }
+ }
+ device.LastSeenAt = new(time.Now())
+ if err := s.db.WithContext(ctx).Save(device).Error; err != nil {
+ return apnstypes.Device{}, errors.WrapIf(err, "failed to update push device")
+ }
+ return deviceDTOInternal(*device), nil
+}
+
+func (s *ApnsService) DeleteDevice(ctx context.Context, userID, id string) error {
+ device, err := s.deviceInternal(ctx, userID, id)
+ if err != nil {
+ return err
+ }
+ return errors.WrapIf(s.db.WithContext(ctx).Delete(device).Error, "failed to delete push device")
+}
+
+func (s *ApnsService) TestDevice(ctx context.Context, userID, id string) error {
+ device, err := s.deviceInternal(ctx, userID, id)
+ if err != nil {
+ return err
+ }
+ channelID, err := s.EnsureChannel(ctx)
+ if err != nil {
+ return err
+ }
+ signer, err := s.signerInternal(ctx)
+ if err != nil {
+ return err
+ }
+ body, err := json.Marshal(map[string]any{
+ "channelId": channelID,
+ "issuedAt": time.Now().UTC(),
+ "nonce": strings.ReplaceAll(uuid.New().String(), "-", ""),
+ "recipientId": device.RecipientID,
+ })
+ if err != nil {
+ return errors.WrapIf(err, "failed to marshal test push")
+ }
+ status, respBody, err := s.relayRequestInternal(ctx, http.MethodPost, "/v1/test", body, signer)
+ if err != nil {
+ return err
+ }
+ if status != http.StatusAccepted && status != http.StatusOK {
+ return errors.WrapIff(common.ErrApnsRelay, "test push returned %d: %s", status, strings.TrimSpace(string(respBody)))
+ }
+ return nil
+}
+
+func truncateInternal(s string, limit int) string {
+ r := []rune(strings.TrimSpace(s))
+ if len(r) <= limit {
+ return string(r)
+ }
+ return string(r[:limit-1]) + "…"
+}
+
+func (s *ApnsService) Enqueue(ctx context.Context, environmentID, environmentName string, eventType notifications.NotificationEventType, subject string, metadata database.JSON) error {
+ if !s.Enabled(ctx) {
+ return nil
+ }
+ recipients, err := s.recipientsInternal(ctx, environmentID, eventType)
+ if err != nil || len(recipients) == 0 {
+ return err
+ }
+
+ batchCount := 0
+ if batch, _ := metadata["batch"].(bool); batch {
+ switch n := metadata["updateCount"].(type) {
+ case int:
+ batchCount = n
+ case float64:
+ batchCount = int(n)
+ }
+ }
+ title, body, severity := "Arcane notification", subject, "info"
+ route := apnstypes.Route{Kind: "environment", EnvironmentID: environmentID}
+ switch eventType {
+ case notifications.NotificationEventImageUpdate:
+ title, body = "Image update available", fmt.Sprintf("%s in %s", subject, environmentName)
+ if batchCount > 1 {
+ title = fmt.Sprintf("%d image updates available", batchCount)
+ }
+ case notifications.NotificationEventContainerUpdate:
+ title, body = "Container updated", fmt.Sprintf("%s in %s", subject, environmentName)
+ if batchCount > 1 {
+ title = fmt.Sprintf("%d containers updated", batchCount)
+ }
+ case notifications.NotificationEventVulnerabilityFound:
+ title, severity = "Vulnerability found", "warning"
+ body = fmt.Sprintf("%v in %s (%s)", metadata["cveId"], subject, environmentName)
+ case notifications.NotificationEventPruneReport:
+ title, body = "Prune completed", "System prune finished in "+environmentName
+ case notifications.NotificationEventAutoHeal:
+ title, severity = "Container restarted", "warning"
+ body = fmt.Sprintf("%s was restarted by auto-heal in %s", subject, environmentName)
+ if containerID, _ := metadata["containerID"].(string); containerID != "" {
+ route = apnstypes.Route{Kind: "container", EnvironmentID: environmentID, ID: containerID}
+ }
+ }
+ envelope := apnstypes.Envelope{
+ Version: 1,
+ EventID: uuid.New().String(),
+ OccurredAt: time.Now().UTC(),
+ Type: string(eventType),
+ Severity: severity,
+ EnvironmentID: environmentID,
+ EnvironmentName: truncateInternal(environmentName, 100),
+ Title: truncateInternal(title, maxTitleLen),
+ Body: truncateInternal(body, maxBodyLen),
+ Route: route,
+ RecipientIDs: recipients,
+ }
+ raw, err := json.Marshal(envelope)
+ if err != nil {
+ return errors.WrapIf(err, "failed to marshal push envelope")
+ }
+ entry := OutboxEntry{EventID: envelope.EventID, Envelope: string(raw), NextAttemptAt: time.Now()}
+ if err := s.db.WithContext(ctx).Create(&entry).Error; err != nil {
+ return errors.WrapIf(err, "failed to enqueue push notification")
+ }
+ go s.DrainOutbox(context.WithoutCancel(ctx))
+ return nil
+}
+
+func (s *ApnsService) recipientsInternal(ctx context.Context, environmentID string, eventType notifications.NotificationEventType) ([]string, error) {
+ var devices []Device
+ if err := s.db.WithContext(ctx).Find(&devices).Error; err != nil {
+ return nil, errors.WrapIf(err, "failed to list push devices")
+ }
+ permissions := map[string]*authz.PermissionSet{}
+ var recipients []string
+ for _, d := range devices {
+ if !d.Events[string(eventType)] {
+ continue
+ }
+ if len(d.EnvironmentIDs) > 0 && !slices.Contains(d.EnvironmentIDs, environmentID) {
+ continue
+ }
+ ps, ok := permissions[d.UserID]
+ if !ok {
+ resolved, err := s.roles.ResolveUserPermissionsInDB(ctx, s.db.WithContext(ctx), d.UserID)
+ if err != nil {
+ slog.WarnContext(ctx, "Skipping push device: cannot resolve permissions", "userId", d.UserID, "error", err)
+ continue
+ }
+ ps = resolved
+ permissions[d.UserID] = ps
+ }
+ if !ps.Allows(authz.PermContainersList, environmentID) {
+ continue
+ }
+ recipients = append(recipients, d.RecipientID)
+ }
+ return recipients, nil
+}
+
+func (s *ApnsService) DrainOutbox(ctx context.Context) {
+ s.drainPending.Store(true)
+ if !s.drainMu.TryLock() {
+ return
+ }
+ defer s.drainMu.Unlock()
+ for s.drainPending.Swap(false) {
+ s.drainOutboxInternal(ctx)
+ }
+}
+
+func (s *ApnsService) drainOutboxInternal(ctx context.Context) {
+ if !s.Enabled(ctx) {
+ return
+ }
+ var entries []OutboxEntry
+ if err := s.db.WithContext(ctx).Where("next_attempt_at <= ?", time.Now()).Order("next_attempt_at ASC").Limit(outboxBatchSize).Find(&entries).Error; err != nil {
+ slog.ErrorContext(ctx, "Failed to load push outbox", "error", err)
+ return
+ }
+ if len(entries) == 0 {
+ return
+ }
+ channelID, err := s.EnsureChannel(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "Push outbox drain skipped", "error", err)
+ return
+ }
+ signer, err := s.signerInternal(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "Push outbox drain skipped", "error", err)
+ return
+ }
+ for _, entry := range entries {
+ if channelRevoked := s.sendOutboxEntryInternal(ctx, entry, channelID, signer); channelRevoked {
+ return
+ }
+ }
+}
+
+func (s *ApnsService) sendOutboxEntryInternal(ctx context.Context, entry OutboxEntry, channelID string, signer *signerInternal) bool {
+ var envelope apnstypes.Envelope
+ if err := json.Unmarshal([]byte(entry.Envelope), &envelope); err != nil {
+ s.finishOutboxInternal(ctx, entry, envelope, "invalid envelope: "+err.Error())
+ return false
+ }
+ envelope.ChannelID = channelID
+ envelope.OccurredAt = time.Now().UTC()
+ raw, err := json.Marshal(envelope)
+ if err != nil {
+ s.finishOutboxInternal(ctx, entry, envelope, "marshal: "+err.Error())
+ return false
+ }
+ status, respBody, err := s.relayRequestInternal(ctx, http.MethodPost, "/v1/events", raw, signer)
+ switch {
+ case err == nil && (status == http.StatusAccepted || status == http.StatusOK):
+ var parsed struct {
+ UnknownRecipientIDs []string `json:"unknownRecipientIds"`
+ }
+ if json.Unmarshal(respBody, &parsed) == nil && len(parsed.UnknownRecipientIDs) > 0 {
+ if err := s.db.WithContext(ctx).Where("recipient_id IN ?", parsed.UnknownRecipientIDs).Delete(&Device{}).Error; err != nil {
+ slog.WarnContext(ctx, "Failed to prune stale push devices", "error", err)
+ }
+ }
+ s.finishOutboxInternal(ctx, entry, envelope, "")
+ case err == nil && status == http.StatusGone:
+ if err := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); err != nil {
+ slog.WarnContext(ctx, "Failed to clear revoked push channel", "error", err)
+ }
+ if err := s.db.WithContext(ctx).Where("1 = 1").Delete(&Device{}).Error; err != nil {
+ slog.WarnContext(ctx, "Failed to remove push devices after channel revocation", "error", err)
+ }
+ s.finishOutboxInternal(ctx, entry, envelope, "relay channel revoked; devices must pair again")
+ return true
+ case err == nil && status >= 400 && status < 500 && status != http.StatusTooManyRequests:
+ s.finishOutboxInternal(ctx, entry, envelope, fmt.Sprintf("relay returned %d: %s", status, strings.TrimSpace(string(respBody))))
+ default:
+ reason := fmt.Sprintf("relay returned %d", status)
+ if err != nil {
+ reason = err.Error()
+ }
+ s.retryOutboxInternal(ctx, entry, envelope, reason, min(time.Duration(1<<uint(entry.Attempts+1))*5*time.Second, 15*time.Minute))
+ }
+ return false
+}
+
+func (s *ApnsService) retryOutboxInternal(ctx context.Context, entry OutboxEntry, envelope apnstypes.Envelope, reason string, backoff time.Duration) {
+ entry.Attempts++
+ if entry.Attempts >= maxOutboxAttempts {
+ s.finishOutboxInternal(ctx, entry, envelope, "gave up after "+reason)
+ return
+ }
+ entry.NextAttemptAt = time.Now().Add(backoff)
+ entry.LastError = new(reason)
+ if err := s.db.WithContext(ctx).Save(&entry).Error; err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule push outbox entry", "error", err)
+ }
+}
+
+func (s *ApnsService) finishOutboxInternal(ctx context.Context, entry OutboxEntry, envelope apnstypes.Envelope, failure string) {
+ if err := s.db.WithContext(ctx).Delete(&entry).Error; err != nil {
+ slog.WarnContext(ctx, "Failed to delete push outbox entry", "error", err)
+ }
+ if failure == "" || s.events == nil {
+ return
+ }
+ resourceType, resourceName := "notification", "mobile-push"
+ envID := envelope.EnvironmentID
+ if _, err := s.events.CreateEvent(ctx, event.CreateEventRequest{
+ Type: event.EventTypeNotificationSend,
+ Severity: event.EventSeverityError,
+ Title: "Notification failed via mobile push",
+ Description: fmt.Sprintf("%s: %s", envelope.Title, failure),
+ ResourceType: &resourceType,
+ ResourceName: &resourceName,
+ EnvironmentID: &envID,
+ Metadata: database.JSON{"provider": "mobile-push", "status": "failed", "eventType": envelope.Type},
+ }); err != nil {
+ slog.WarnContext(ctx, "Failed to log push failure event", "error", err)
+ }
+}
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 33cf73872..739f1f66c 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
"github.com/getarcaneapp/arcane/backend/v2/internal/actors"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/apns"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/environment"
"github.com/getarcaneapp/arcane/backend/v2/internal/gitops"
@@ -80,6 +81,7 @@ type registerJobsParams struct {
Volume *volume.VolumeService
SystemBackup *systembackup.SystemBackupService
Admission *actors.Gate[actors.AdmissionKey]
+ Apns *apns.ApnsService
AutoUpdate *scheduler.AutoUpdateJob
ImageUpdateWatcher *scheduler.ImageUpdateWatcher
@@ -96,6 +98,7 @@ type registerJobsParams struct {
ActivitySweep *scheduler.ActivitySweepJob
UploadSessionsCleanup *scheduler.UploadSessionsCleanupJob
GitCloneCleanup *scheduler.GitCloneCleanupJob
+ ApnsOutbox *scheduler.ApnsOutboxJob
}
func registerJobs(params registerJobsParams) error {
@@ -139,6 +142,7 @@ func registerJobs(params registerJobsParams) error {
params.ActivitySweep,
params.UploadSessionsCleanup,
params.GitCloneCleanup,
+ params.ApnsOutbox,
} {
if err := params.Scheduler.RegisterJob(job); err != nil {
return err
@@ -180,6 +184,8 @@ func registerJobs(params registerJobsParams) error {
VulnerabilityScan: params.VulnerabilityScan,
AutoPatch: params.AutoPatch,
AutoHeal: params.AutoHeal,
+ Apns: params.Apns,
+ ApnsOutbox: params.ApnsOutbox,
}); err != nil {
return err
}
@@ -259,6 +265,8 @@ type settingsSubscriptionsParams struct {
VulnerabilityScan *scheduler.VulnerabilityScanJob
AutoPatch *scheduler.AutoPatchJob
AutoHeal *scheduler.AutoHealJob
+ Apns *apns.ApnsService
+ ApnsOutbox *scheduler.ApnsOutboxJob
}
type settingsChangeSubscriberInternal interface {
@@ -294,6 +302,12 @@ func setupSettingsSubscriptionsInternal(params settingsSubscriptionsParams) erro
}
})
+ subscribe([]string{"apnsEnabled"}, func(updates []libarcane.SettingUpdate) {
+ params.Apns.ApplyEnabledUpdates(params.LifecycleCtx, updates, func() error {
+ return params.Scheduler.RescheduleJob(params.LifecycleCtx, params.ApnsOutbox)
+ })
+ })
+
subscribe([]string{"autoUpdate", "autoUpdateInterval"}, func(_ []libarcane.SettingUpdate) {
if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.AutoUpdate); err != nil {
slog.WarnContext(params.LifecycleCtx, "Failed to reschedule auto-update job", "error", err)
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 6523b8813..c5b59987a 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -68,6 +68,10 @@ var (
ErrTemplateNotFound = Classify(ErrNotFound, errors.Sentinel("Template not found"))
ErrInvalidEnvKey = Classify(ErrValidation, errors.Sentinel("Invalid environment key"))
ErrGlobalVariableNotFound = Classify(ErrNotFound, errors.Sentinel("Global variable not found"))
+ ErrApnsDisabled = Classify(ErrForbidden, errors.Sentinel("Mobile push notifications are disabled"))
+ ErrApnsDeviceNotFound = Classify(ErrNotFound, errors.Sentinel("Mobile push device not found"))
+ ErrApnsDeviceConflict = Classify(ErrConflict, errors.Sentinel("Mobile push device is already registered"))
+ ErrApnsRelay = Classify(ErrUnavailable, errors.Sentinel("Push relay request failed"))
ErrGlobalVariableConflict = Classify(ErrConflict, errors.Sentinel("Global variable already exists"))
ErrGlobalVariableScopeRequired = Classify(ErrValidation, errors.Sentinel("At least one environment is required when a variable is not scoped to all environments"))
ErrGlobalVariableSecretValueRequired = Classify(ErrValidation, errors.Sentinel("A new value is required when making a secret variable readable"))
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index e0c3a24d4..bce6a8572 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -45,6 +45,8 @@ type Config struct {
JWTRefreshExpiry time.Duration `env:"JWT_REFRESH_EXPIRY" default:"168h"`
EncryptionKey string `env:"ENCRYPTION_KEY" default:"arcane-dev-key-32-characters!!!" options:"file"`
AdminStaticAPIKey string `env:"ADMIN_STATIC_API_KEY" default:"" options:"file"`
+ ApnsRelayUrl string `env:"APNS_RELAY_URL" default:"https://apns.getarcane.app" options:"trimTrailingSlash"`
+ ApnsKeyAlgorithm string `env:"APNS_KEY_ALGORITHM" default:"ed25519" options:"toLower"`
OidcEnabled bool `env:"OIDC_ENABLED" default:"false"`
OidcClientID string `env:"OIDC_CLIENT_ID" default:"" options:"file"`
diff --git a/backend/internal/config/schema/schema_test.go b/backend/internal/config/schema/schema_test.go
index 97835eef0..5005c365f 100644
--- a/backend/internal/config/schema/schema_test.go
+++ b/backend/internal/config/schema/schema_test.go
@@ -200,6 +200,8 @@ var expectedEnvConfigVars = []string{
"ALLOW_CLI_PASSWORD_RESET",
"ALLOW_DOWNGRADE",
"ANALYTICS_DISABLED",
+ "APNS_KEY_ALGORITHM",
+ "APNS_RELAY_URL",
"APP_URL",
"ARCANE_BACKUP_VOLUME_NAME",
"AUTO_LOGIN_PASSWORD",
@@ -273,6 +275,7 @@ var expectedEnvConfigVars = []string{
var expectedSettingOverrideKeys = []string{
"activityHistoryMaxEntries",
"activityHistoryRetentionDays",
+ "apnsEnabled",
"authLocalEnabled",
"authPasswordPolicy",
"authSessionTimeout",
diff --git a/backend/internal/di/di.go b/backend/internal/di/di.go
index bf5b67469..c5d8ecd2d 100644
--- a/backend/internal/di/di.go
+++ b/backend/internal/di/di.go
@@ -3,6 +3,7 @@ package di
import (
"github.com/getarcaneapp/arcane/backend/v2/internal/actors"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/apns"
"github.com/getarcaneapp/arcane/backend/v2/internal/appimages"
"github.com/getarcaneapp/arcane/backend/v2/internal/build"
"github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics"
@@ -64,6 +65,8 @@ var ServiceOptions = fx.Options(
environment.NewEnvironmentService,
provideEnvironmentModuleInternal,
provideSettingsModuleInternal,
+ apns.NewApnsService,
+ apns.New,
notification.NewNotificationService,
notification.New,
vulnerability.NewVulnerabilityService,
@@ -143,5 +146,6 @@ var JobOptions = fx.Options(
scheduler.NewActivitySweepJob,
scheduler.NewUploadSessionsCleanupJob,
scheduler.NewGitCloneCleanupJob,
+ scheduler.NewApnsOutboxJob,
),
)
diff --git a/backend/internal/imageupdate/service_test.go b/backend/internal/imageupdate/service_test.go
index 3f8cb986a..4b080f427 100644
--- a/backend/internal/imageupdate/service_test.go
+++ b/backend/internal/imageupdate/service_test.go
@@ -1731,7 +1731,7 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *te
},
}).Error)
- notif := notification.NewNotificationService(db, nil, nil, nil)
+ notif := notification.NewNotificationService(db, nil, nil, nil, nil)
svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
rec := ImageUpdateRecord{
@@ -1770,7 +1770,7 @@ func TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnn
db := setupImageUpdateTestDB(t)
require.NoError(t, db.AutoMigrate(&notification.NotificationSettings{}))
- notif := notification.NewNotificationService(db, nil, nil, nil)
+ notif := notification.NewNotificationService(db, nil, nil, nil, nil)
svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
rec := ImageUpdateRecord{
@@ -1822,7 +1822,7 @@ func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotif
}).Error)
}
- notif := notification.NewNotificationService(db, nil, nil, nil)
+ notif := notification.NewNotificationService(db, nil, nil, nil, nil)
svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
rec := ImageUpdateRecord{
diff --git a/backend/internal/notification/notification.go b/backend/internal/notification/notification.go
index 644ee921b..595e399c3 100644
--- a/backend/internal/notification/notification.go
+++ b/backend/internal/notification/notification.go
@@ -18,6 +18,7 @@ import (
"emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/apns"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
@@ -64,6 +65,7 @@ type NotificationService struct {
config *config.Config
environmentSvc *environment.EnvironmentService
eventSvc *event.EventService
+ apnsSvc *apns.ApnsService
httpClient *http.Client
}
@@ -85,12 +87,13 @@ func (s *NotificationService) ResolveNotificationTarget(ctx context.Context, env
return s.resolveNotificationTargetInternal(ctx, environmentID)
}
-func NewNotificationService(db *database.DB, cfg *config.Config, environmentSvc *environment.EnvironmentService, eventSvc *event.EventService) *NotificationService {
+func NewNotificationService(db *database.DB, cfg *config.Config, environmentSvc *environment.EnvironmentService, eventSvc *event.EventService, apnsSvc *apns.ApnsService) *NotificationService {
return &NotificationService{
db: db,
config: cfg,
environmentSvc: environmentSvc,
eventSvc: eventSvc,
+ apnsSvc: apnsSvc,
httpClient: &http.Client{Timeout: 15 * time.Second},
}
}
@@ -599,6 +602,12 @@ func (s *NotificationService) notifyEnabledProvidersInternal(
s.logNotification(ctx, target.EnvironmentID, setting.Provider, logRef, status, errMsg, metadata)
}
+ if s.apnsSvc != nil {
+ if err := s.apnsSvc.Enqueue(ctx, target.EnvironmentID, target.EnvironmentName, eventType, logRef, metadata); err != nil {
+ slog.WarnContext(ctx, "Failed to enqueue mobile push notification", "error", err)
+ }
+ }
+
if len(errs) > 0 {
return delivered, errors.Errorf("notification errors: %s", strings.Join(errs, "; "))
}
diff --git a/backend/internal/notification/service_test.go b/backend/internal/notification/service_test.go
index 49890f60d..5caa1572b 100644
--- a/backend/internal/notification/service_test.go
+++ b/backend/internal/notification/service_test.go
@@ -63,7 +63,7 @@ func setupNotificationTestServiceInternal(t *testing.T) (*database.DB, *environm
AppUrl: "http://localhost:3552",
}
- return db, envSvc, NewNotificationService(db, cfg, envSvc, event.NewEventService(db, cfg, nil))
+ return db, envSvc, NewNotificationService(db, cfg, envSvc, event.NewEventService(db, cfg, nil), nil)
}
func newNotificationTestUpdateInfoInternal() *imageupdate.Response {
@@ -249,7 +249,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMa
AgentMode: true,
AgentToken: "agent-token",
ManagerApiUrl: server.URL,
- }, envSvc, nil)
+ }, envSvc, nil, nil)
delivered, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", newNotificationTestUpdateInfoInternal(), notifications.NotificationEventImageUpdate)
require.NoError(t, err)
@@ -296,7 +296,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeUsesManag
AgentMode: true,
AgentToken: "agent-token",
ManagerApiUrl: server.URL,
- }, envSvc, nil)
+ }, envSvc, nil, nil)
delivered, err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{
"nginx:latest": newNotificationTestUpdateInfoInternal(),
@@ -316,7 +316,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdate
svc := NewNotificationService(db, &config.Config{
AppUrl: "http://localhost:3552",
AgentMode: true,
- }, envSvc, nil)
+ }, envSvc, nil, nil)
_, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", nil, notifications.NotificationEventImageUpdate)
require.Error(t, err)
@@ -340,7 +340,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOp
AgentMode: true,
AgentToken: "agent-token",
ManagerApiUrl: server.URL,
- }, envSvc, nil)
+ }, envSvc, nil, nil)
t.Run("empty updates", func(t *testing.T) {
delivered, err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{})
@@ -554,7 +554,7 @@ func TestNotificationCredentialInternal_LeavesEmptyValuesEmpty(t *testing.T) {
func TestNotificationService_CreateOrUpdateSettingsEncryptsCredentialFieldsInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, nil)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
_, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderDiscord, true, database.JSON{
"webhookId": "123456789",
@@ -577,7 +577,7 @@ func TestNotificationService_CreateOrUpdateSettingsEncryptsCredentialFieldsInter
func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhenEmptyInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, nil)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
_, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{
"host": "gotify.example",
@@ -605,7 +605,7 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhen
func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStoredCredentialInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, nil)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
created, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{
"host": "gotify.example",
@@ -640,7 +640,7 @@ func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStored
func TestNotificationService_CreateOrUpdateSettingsClearsEmailPasswordWhenAuthModeNoneInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, nil)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
_, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderEmail, true, database.JSON{
"smtpHost": "smtp.example",
@@ -664,7 +664,7 @@ func TestNotificationService_CreateOrUpdateSettingsClearsEmailPasswordWhenAuthMo
func TestNotificationService_CreateOrUpdateSettingsPreservesCredentialAcrossDisableInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, nil)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
_, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{
"host": "gotify.example",
@@ -695,7 +695,7 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesCredentialAcrossDisa
func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, nil)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
_, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderNtfy, true, database.JSON{
"host": "ntfy.example",
@@ -731,7 +731,7 @@ func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledIntern
func TestNotificationService_NotifyEnabledProvidersInternal_SkipsFiltersAndAggregatesInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{}, nil, event.NewEventService(db, nil, nil))
+ svc := NewNotificationService(db, &config.Config{}, nil, event.NewEventService(db, nil, nil), nil)
rows := []NotificationSettings{
{Provider: notifications.NotificationProviderDiscord, Enabled: false, Config: database.JSON{}},
@@ -823,7 +823,7 @@ func TestNotificationService_DispatchNotificationForEnvironment_ResolvesTunnelSe
func TestNotificationService_AgentDispatchWithoutHTTPConfigFallsBackToTunnel(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
- svc := NewNotificationService(db, &config.Config{AgentMode: true}, nil, event.NewEventService(db, &config.Config{AgentMode: true}, nil))
+ svc := NewNotificationService(db, &config.Config{AgentMode: true}, nil, event.NewEventService(db, &config.Config{AgentMode: true}, nil), nil)
// No MANAGER_API_URL/AGENT_TOKEN and no active tunnel: the error must point
// at both options instead of only the HTTP env vars (#3002).
@@ -842,7 +842,7 @@ func TestNotificationService_AgentDispatchHTTPFailureFallsBackToTunnel(t *testin
ctx := context.Background()
db := setupNotificationTestDB(t)
cfg := &config.Config{AgentMode: true, ManagerApiUrl: "http://127.0.0.1:0", AgentToken: "token"}
- svc := NewNotificationService(db, cfg, nil, event.NewEventService(db, cfg, nil))
+ svc := NewNotificationService(db, cfg, nil, event.NewEventService(db, cfg, nil), nil)
// HTTP dispatch fails and no tunnel is connected either: the fallback must
// not mask the HTTP transport error.
diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.go
index f6a9a60e1..1adf8e20e 100644
--- a/backend/internal/settings/model.go
+++ b/backend/internal/settings/model.go
@@ -170,6 +170,10 @@ type Settings struct {
// Notifications category (placeholder for category metadata only - actual settings managed via notification service)
NotificationsCategoryPlaceholder SettingVariable `key:"notificationsCategory,internal" meta:"label=Notifications;type=internal;keywords=notifications,alerts,email,discord,webhooks,events,messages;category=notifications;description=Configure notification providers and alerts" catmeta:"id=notifications;title=Notifications;icon=bell;url=/settings/notifications;description=Configure email and Discord notifications for container and image updates"`
+ ApnsEnabled SettingVariable `key:"apnsEnabled,authrequired" meta:"label=Mobile Push Notifications;type=boolean;keywords=apns,push,mobile,ios,notifications,relay;category=notifications;description=Let users receive native push notifications in the Arcane mobile app"`
+ ApnsChannelID SettingVariable `key:"apnsChannelId,internal"`
+ ApnsSigningKey SettingVariable `key:"apnsSigningKey,internal,sensitive"`
+
AgentToken SettingVariable `key:"agentToken,internal,sensitive"`
InstanceID SettingVariable `key:"instanceId,internal"`
diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.go
index f5299d1f5..4b2149bac 100644
--- a/backend/internal/settings/service.go
+++ b/backend/internal/settings/service.go
@@ -297,6 +297,10 @@ func DefaultSettingsConfig() *Settings {
DepotProjectId: SettingVariable{Value: ""},
DepotToken: SettingVariable{Value: ""},
+ ApnsEnabled: SettingVariable{Value: "false"},
+ ApnsChannelID: SettingVariable{Value: ""},
+ ApnsSigningKey: SettingVariable{Value: ""},
+
InstanceID: SettingVariable{Value: ""},
}
}
diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.go
index d51293f15..a20862da8 100644
--- a/backend/internal/updater/service_test.go
+++ b/backend/internal/updater/service_test.go
@@ -529,7 +529,7 @@ func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(t
},
}).Error)
- notif := notification.NewNotificationService(db, nil, nil, nil)
+ notif := notification.NewNotificationService(db, nil, nil, nil, nil)
imageUpdates := imageupdate.NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
svc, svcErr := NewUpdaterService(db, nil, nil, nil, imageUpdates, nil, nil, nil, notif, nil, nil)
require.NoError(t, svcErr)
@@ -560,7 +560,7 @@ func TestUpdaterService_PendingImageUpdatesNoProvidersLeavesUnnotifiedInternal(t
db := setupProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}, &notification.NotificationSettings{}))
- notif := notification.NewNotificationService(db, nil, nil, nil)
+ notif := notification.NewNotificationService(db, nil, nil, nil, nil)
imageUpdates := imageupdate.NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
svc, svcErr := NewUpdaterService(db, nil, nil, nil, imageUpdates, nil, nil, nil, notif, nil, nil)
require.NoError(t, svcErr)
diff --git a/backend/internal/version/service.go b/backend/internal/version/service.go
index f41708c29..64dee726c 100644
--- a/backend/internal/version/service.go
+++ b/backend/internal/version/service.go
@@ -18,6 +18,7 @@ import (
"golang.org/x/mod/semver"
"github.com/getarcaneapp/arcane/backend/v2/buildables"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/apns"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/docker"
"github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"
@@ -296,7 +297,7 @@ func (s *VersionService) GetAppVersionInfo(ctx context.Context) *version.Info {
GoVersion: config.GoVersion(),
NodeVersion: config.NodeVersion,
SvelteKitVersion: config.SvelteKitVersion,
- EnabledFeatures: parseEnabledFeatures(),
+ EnabledFeatures: append(parseEnabledFeatures(), apns.FeatureName),
BuildTime: config.BuildTime,
IsSemverVersion: isSemver,
UpdateAvailable: false,
diff --git a/backend/pkg/scheduler/apns_outbox_job.go b/backend/pkg/scheduler/apns_outbox_job.go
new file mode 100644
index 000000000..0c8a663af
--- /dev/null
+++ b/backend/pkg/scheduler/apns_outbox_job.go
@@ -0,0 +1,35 @@
+package scheduler
+
+import (
+ "context"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/apns"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"
+)
+
+const ApnsOutboxJobName = "apns-outbox"
+
+type ApnsOutboxJob struct {
+ service *apns.ApnsService
+ config *config.Config
+}
+
+func NewApnsOutboxJob(service *apns.ApnsService, cfg *config.Config) *ApnsOutboxJob {
+ return &ApnsOutboxJob{service: service, config: cfg}
+}
+
+func (j *ApnsOutboxJob) Name() string {
+ return ApnsOutboxJobName
+}
+
+func (j *ApnsOutboxJob) Schedule(_ context.Context) string {
+ return "0 */5 * * * *"
+}
+
+func (j *ApnsOutboxJob) ShouldSchedule(ctx context.Context) bool {
+ return (j.config == nil || !j.config.AgentMode) && j.service.Enabled(ctx)
+}
+
+func (j *ApnsOutboxJob) Run(ctx context.Context) {
+ j.service.DrainOutbox(ctx)
+}
diff --git a/backend/resources/migrations/postgres/077_add_apns.sql b/backend/resources/migrations/postgres/077_add_apns.sql
new file mode 100644
index 000000000..f99805e9a
--- /dev/null
+++ b/backend/resources/migrations/postgres/077_add_apns.sql
@@ -0,0 +1,35 @@
+-- +goose Up
+CREATE TABLE IF NOT EXISTS apns_devices (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ recipient_id TEXT NOT NULL,
+ label TEXT NOT NULL DEFAULT '',
+ events JSONB NOT NULL DEFAULT '{}',
+ environment_ids JSONB NOT NULL DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ,
+ last_seen_at TIMESTAMPTZ
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_apns_devices_recipient ON apns_devices(recipient_id);
+CREATE INDEX IF NOT EXISTS idx_apns_devices_user ON apns_devices(user_id);
+
+CREATE TABLE IF NOT EXISTS apns_outbox (
+ id TEXT PRIMARY KEY,
+ event_id TEXT NOT NULL,
+ envelope TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL,
+ last_error TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ
+);
+
+CREATE INDEX IF NOT EXISTS idx_apns_outbox_next_attempt ON apns_outbox(next_attempt_at);
+
+-- +goose Down
+DROP INDEX IF EXISTS idx_apns_outbox_next_attempt;
+DROP TABLE IF EXISTS apns_outbox;
+DROP INDEX IF EXISTS idx_apns_devices_user;
+DROP INDEX IF EXISTS idx_apns_devices_recipient;
+DROP TABLE IF EXISTS apns_devices;
diff --git a/backend/resources/migrations/sqlite/077_add_apns.sql b/backend/resources/migrations/sqlite/077_add_apns.sql
new file mode 100644
index 000000000..48f800c53
--- /dev/null
+++ b/backend/resources/migrations/sqlite/077_add_apns.sql
@@ -0,0 +1,35 @@
+-- +goose Up
+CREATE TABLE IF NOT EXISTS apns_devices (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ recipient_id TEXT NOT NULL,
+ label TEXT NOT NULL DEFAULT '',
+ events TEXT NOT NULL DEFAULT '{}',
+ environment_ids TEXT NOT NULL DEFAULT '[]',
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ last_seen_at DATETIME
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_apns_devices_recipient ON apns_devices(recipient_id);
+CREATE INDEX IF NOT EXISTS idx_apns_devices_user ON apns_devices(user_id);
+
+CREATE TABLE IF NOT EXISTS apns_outbox (
+ id TEXT PRIMARY KEY,
+ event_id TEXT NOT NULL,
+ envelope TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at DATETIME NOT NULL,
+ last_error TEXT,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE INDEX IF NOT EXISTS idx_apns_outbox_next_attempt ON apns_outbox(next_attempt_at);
+
+-- +goose Down
+DROP INDEX IF EXISTS idx_apns_outbox_next_attempt;
+DROP TABLE IF EXISTS apns_outbox;
+DROP INDEX IF EXISTS idx_apns_devices_user;
+DROP INDEX IF EXISTS idx_apns_devices_recipient;
+DROP TABLE IF EXISTS apns_devices;
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 098990666..833375f5b 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -2320,6 +2320,14 @@
"system": "System",
"notifications_title": "Notifications",
"notifications_description": "Configure notifications for container updates",
+ "notifications_mobile_push_label": "Mobile push notifications",
+ "notifications_mobile_push_description": "Let users receive native push notifications in the Arcane mobile app.",
+ "notifications_mobile_push_tab": "Mobile Push",
+ "notifications_mobile_devices": "Your mobile devices",
+ "notifications_mobile_devices_empty": "No devices paired. Enable push notifications in the Arcane mobile app settings.",
+ "notifications_mobile_test_sent": "Test notification sent to {device}",
+ "notifications_mobile_device_removed": "{device} removed",
+ "notifications_mobile_push_external_warning": "This sends notification titles and messages through Arcane's hosted push relay (apns.getarcane.app) and Apple's servers. Your server address, users, and credentials are never sent.",
"notifications_discord_title": "Discord",
"notifications_telegram_title": "Telegram",
"notifications_telegram_description": "Send notifications via Telegram bot",
diff --git a/frontend/src/lib/services/apns-service.ts b/frontend/src/lib/services/apns-service.ts
new file mode 100644
index 000000000..c59e71aa2
--- /dev/null
+++ b/frontend/src/lib/services/apns-service.ts
@@ -0,0 +1,18 @@
+import BaseAPIService from './api-service';
+import type { ApnsStatus } from '#lib/types/apns';
+
+class ApnsService extends BaseAPIService {
+ async getStatus(): Promise<ApnsStatus> {
+ return this.handleResponse(this.api.get('/apns/status'));
+ }
+
+ async testDevice(id: string): Promise<void> {
+ await this.api.post(`/apns/devices/${id}/test`);
+ }
+
+ async deleteDevice(id: string): Promise<void> {
+ await this.api.delete(`/apns/devices/${id}`);
+ }
+}
+
+export const apnsService = new ApnsService();
diff --git a/frontend/src/lib/types/apns.ts b/frontend/src/lib/types/apns.ts
new file mode 100644
index 000000000..7ad6ca8ea
--- /dev/null
+++ b/frontend/src/lib/types/apns.ts
@@ -0,0 +1,15 @@
+export interface ApnsDevice {
+ id: string;
+ label: string;
+ events: Record<string, boolean>;
+ environmentIds: string[];
+ createdAt: string;
+ lastSeenAt?: string;
+}
+
+export interface ApnsStatus {
+ enabled: boolean;
+ channelId?: string;
+ relayUrl: string;
+ devices: ApnsDevice[];
+}
diff --git a/frontend/src/lib/types/settings.ts b/frontend/src/lib/types/settings.ts
index 004b953db..20fe469a3 100644
--- a/frontend/src/lib/types/settings.ts
+++ b/frontend/src/lib/types/settings.ts
@@ -55,6 +55,7 @@ export type Settings = {
baseServerUrl: string;
enableGravatar: boolean;
experimentalFeaturesEnabled: boolean;
+ apnsEnabled?: boolean;
avatarMaxUploadSizeMb: number;
uiConfigDisabled: boolean;
defaultShell: string;
diff --git a/frontend/src/lib/utils/settings.ts b/frontend/src/lib/utils/settings.ts
index e821209de..3defdb89a 100644
--- a/frontend/src/lib/utils/settings.ts
+++ b/frontend/src/lib/utils/settings.ts
@@ -7,6 +7,7 @@ export type LocalSettings = {
edgeMTLSManagerCAAvailable?: boolean;
avatarMaxUploadSizeMb: number;
experimentalFeaturesEnabled?: boolean;
+ apnsEnabled?: boolean;
};
const LOCAL_SETTING_KEYS = new Set([
@@ -27,7 +28,8 @@ const LOCAL_SETTING_KEYS = new Set([
'oidcProviderName',
'oidcProviderLogoUrl',
'edgeMTLSManagerCAAvailable',
- 'experimentalFeaturesEnabled'
+ 'experimentalFeaturesEnabled',
+ 'apnsEnabled'
]);
export function isLocalSetting(key: string): boolean {
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index ee9d0bd0e..35fd5dd2e 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -1,6 +1,9 @@
<script lang="ts">
import * as Tabs from '#lib/components/ui/tabs';
import * as Dialog from '#lib/components/ui/dialog';
+ import * as Alert from '#lib/components/ui/alert';
+ import { Switch } from '#lib/components/ui/switch/index.js';
+ import SettingsRow from '#lib/components/settings/settings-row.svelte';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { toast } from 'svelte-sonner';
import { getContext, onMount } from 'svelte';
@@ -10,7 +13,10 @@
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';
import { notificationService } from '#lib/services/notification-service';
import { type NotificationProviderKey, NOTIFICATION_PROVIDER_KEYS } from '#lib/types/notifications';
- import { NotificationsIcon } from '#lib/icons';
+ import { AlertIcon, NotificationsIcon } from '#lib/icons';
+ import { settingsService } from '#lib/services/settings-service';
+ import type { Settings } from '#lib/types/settings';
+ import { hasPermission } from '#lib/utils/auth';
import { TabBar, type TabItem } from '#lib/components/tab-bar';
import { BuiltInProviderForm } from './providers';
import {
@@ -23,7 +29,10 @@
type NotificationSettingsByProvider,
updateNotificationProviderFormState
} from '#lib/utils/notification-providers';
- import { extractApiErrorMessage } from '#lib/utils/api';
+ import { extractApiErrorMessage, handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api';
+ import { apnsService } from '#lib/services/apns-service';
+ import type { ApnsDevice } from '#lib/types/apns';
+ import { formatRelativeTime } from '#lib/utils/formatting';
let { data } = $props();
@@ -32,20 +41,30 @@
let isTesting = $state(false);
let showUnsavedDialog = $state(false);
let pendingTestAction: (() => Promise<void>) | null = $state(null);
- const urlTab = useUrlTab<NotificationProviderKey>({
- validTabs: () => NOTIFICATION_PROVIDER_KEYS,
+ type NotificationTab = NotificationProviderKey | 'mobile';
+ const NOTIFICATION_TABS: readonly NotificationTab[] = [...NOTIFICATION_PROVIDER_KEYS, 'mobile'];
+ const urlTab = useUrlTab<NotificationTab>({
+ validTabs: () => NOTIFICATION_TABS,
defaultTab: () => 'email'
});
const providerTab = $derived(urlTab.value);
- const providerTabItems = NOTIFICATION_PROVIDER_KEYS.map(
- (provider) =>
- ({
- value: provider,
- label: getNotificationProviderDefinition(provider).label()
- }) satisfies TabItem
- );
+ const tabItems: TabItem[] = [
+ ...NOTIFICATION_PROVIDER_KEYS.map(
+ (provider) =>
+ ({
+ value: provider,
+ label: getNotificationProviderDefinition(provider).label()
+ }) satisfies TabItem
+ ),
+ { value: 'mobile', label: m.notifications_mobile_push_tab() }
+ ];
const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
+ const canToggleMobilePush = $derived(hasPermission('settings:write'));
+ const mobilePushEnabled = $derived($settingsStore?.apnsEnabled === true);
+ let savingMobilePush = $state(false);
+ let mobileDevices = $state<ApnsDevice[]>([]);
+ let testingDeviceId = $state<string | null>(null);
type SettingsFormState = {
hasChanges: boolean;
@@ -85,6 +104,7 @@
savedSettings = createNotificationSettingsByProvider(data?.notificationSettings ?? []);
providerValues = createNotificationProviderFormState(savedSettings);
providerBaselines = cloneNotificationProviderFormState(providerValues);
+ if (mobilePushEnabled) void loadMobileDevices();
});
async function onSubmit() {
@@ -126,6 +146,49 @@
}
}
+ async function handleMobilePushToggle(enabled: boolean) {
+ handleApiResultWithCallbacks<Settings>({
+ result: await tryCatch(settingsService.updateSettings({ apnsEnabled: enabled })),
+ message: m.common_update_failed({ resource: m.settings() }),
+ setLoadingState: (value) => (savingMobilePush = value),
+ onSuccess: async (updated) => {
+ settingsStore.set(updated);
+ if (enabled) {
+ await loadMobileDevices();
+ } else {
+ mobileDevices = [];
+ }
+ toast.success(m.common_update_success({ resource: m.settings() }));
+ }
+ });
+ }
+
+ async function loadMobileDevices() {
+ const { data } = await tryCatch(apnsService.getStatus());
+ mobileDevices = data?.devices ?? [];
+ }
+
+ async function testMobileDevice(device: ApnsDevice) {
+ testingDeviceId = device.id;
+ const { error } = await tryCatch(apnsService.testDevice(device.id));
+ testingDeviceId = null;
+ if (error) {
+ toast.error(extractApiErrorMessage(error));
+ return;
+ }
+ toast.success(m.notifications_mobile_test_sent({ device: device.label || device.id }));
+ }
+
+ async function removeMobileDevice(device: ApnsDevice) {
+ const { error } = await tryCatch(apnsService.deleteDevice(device.id));
+ if (error) {
+ toast.error(extractApiErrorMessage(error));
+ return;
+ }
+ toast.success(m.notifications_mobile_device_removed({ device: device.label || device.id }));
+ await loadMobileDevices();
+ }
+
function resetForm() {
providerValues = cloneNotificationProviderFormState(providerBaselines);
}
@@ -175,7 +238,7 @@
{#snippet mainContent()}
<fieldset disabled={isReadOnly} class="relative w-full min-w-0">
<Tabs.Root value={providerTab} class="flex min-h-0 w-full min-w-0 flex-col">
- <TabBar items={providerTabItems} value={providerTab} onValueChange={urlTab.select} class="self-start" />
+ <TabBar items={tabItems} value={providerTab} onValueChange={urlTab.select} class="self-start" />
{#each NOTIFICATION_PROVIDER_KEYS as provider (provider)}
<Tabs.Content value={provider} class="mt-4 space-y-4">
@@ -192,6 +255,54 @@
/>
</Tabs.Content>
{/each}
+ <Tabs.Content value="mobile" class="mt-4 space-y-4">
+ <SettingsRow
+ label={m.notifications_mobile_push_label()}
+ description={m.notifications_mobile_push_description()}
+ layout="inline"
+ >
+ <Switch
+ id="apnsEnabled"
+ checked={mobilePushEnabled}
+ disabled={isReadOnly || !canToggleMobilePush || savingMobilePush}
+ onCheckedChange={(checked) => void handleMobilePushToggle(checked)}
+ />
+ </SettingsRow>
+ {#if mobilePushEnabled}
+ <div class="space-y-2">
+ <p class="text-sm font-medium">{m.notifications_mobile_devices()}</p>
+ {#if mobileDevices.length === 0}
+ <p class="text-xs text-muted-foreground">{m.notifications_mobile_devices_empty()}</p>
+ {:else}
+ <ul class="divide-y divide-border/40">
+ {#each mobileDevices as device (device.id)}
+ <li class="flex items-center justify-between gap-3 py-2">
+ <div class="min-w-0">
+ <p class="truncate text-sm">{device.label || device.id}</p>
+ {#if device.lastSeenAt}
+ <p class="text-xs text-muted-foreground">{formatRelativeTime(device.lastSeenAt)}</p>
+ {/if}
+ </div>
+ <div class="flex shrink-0 items-center gap-2">
+ <ArcaneButton
+ action="test"
+ size="sm"
+ loading={testingDeviceId === device.id}
+ onclick={() => testMobileDevice(device)}
+ />
+ <ArcaneButton action="remove" size="sm" onclick={() => removeMobileDevice(device)} />
+ </div>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+ {/if}
+ <Alert.Root variant="warning" class="py-2 [&>svg]:top-2">
+ <AlertIcon class="size-4" />
+ <Alert.Description class="text-xs">{m.notifications_mobile_push_external_warning()}</Alert.Description>
+ </Alert.Root>
+ </Tabs.Content>
</Tabs.Root>
</fieldset>
{/snippet}
diff --git a/types/apns/apns.go b/types/apns/apns.go
new file mode 100644
index 000000000..f18f5991d
--- /dev/null
+++ b/types/apns/apns.go
@@ -0,0 +1,67 @@
+package apns
+
+import "time"
+
+type Device struct {
+ ID string `json:"id"`
+ Label string `json:"label"`
+ Events map[string]bool `json:"events"`
+ EnvironmentIDs []string `json:"environmentIds"`
+ CreatedAt time.Time `json:"createdAt"`
+ LastSeenAt *time.Time `json:"lastSeenAt,omitempty"`
+}
+
+type Status struct {
+ Enabled bool `json:"enabled"`
+ ChannelID string `json:"channelId,omitempty"`
+ RelayURL string `json:"relayUrl"`
+ Devices []Device `json:"devices"`
+}
+
+type PairingToken struct {
+ Token string `json:"token"`
+ ChannelID string `json:"channelId"`
+ ExpiresAt time.Time `json:"expiresAt"`
+}
+
+type RegisterDeviceRequest struct {
+ RecipientID string `json:"recipientId" minLength:"1" maxLength:"128"`
+ Label string `json:"label" maxLength:"100"`
+ Events map[string]bool `json:"events,omitzero"`
+ EnvironmentIDs []string `json:"environmentIds,omitzero"`
+}
+
+type UpdateDeviceRequest struct {
+ Label *string `json:"label,omitzero" maxLength:"100"`
+ Events *map[string]bool `json:"events,omitzero"`
+ EnvironmentIDs *[]string `json:"environmentIds,omitzero"`
+}
+
+type Resource struct {
+ Kind string `json:"kind"`
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+}
+
+type Route struct {
+ Kind string `json:"kind"`
+ Tab string `json:"tab,omitempty"`
+ EnvironmentID string `json:"environmentId,omitempty"`
+ ID string `json:"id,omitempty"`
+}
+
+type Envelope struct {
+ Version int `json:"v"`
+ EventID string `json:"eventId"`
+ OccurredAt time.Time `json:"occurredAt"`
+ Type string `json:"type"`
+ Severity string `json:"severity"`
+ EnvironmentID string `json:"environmentId"`
+ EnvironmentName string `json:"environmentName"`
+ Resource *Resource `json:"resource,omitempty"`
+ Title string `json:"title"`
+ Body string `json:"body"`
+ Route Route `json:"route"`
+ ChannelID string `json:"channelId"`
+ RecipientIDs []string `json:"recipientIds"`
+}
diff --git a/types/settings/settings.go b/types/settings/settings.go
index c60606b0d..8c64e7117 100644
--- a/types/settings/settings.go
+++ b/types/settings/settings.go
@@ -516,4 +516,9 @@ type Update struct {
//
// Required: false
DepotToken *string `json:"depotToken,omitzero"`
+
+ // ApnsEnabled lets users pair the mobile app for native push notifications.
+ //
+ // Required: false
+ ApnsEnabled *string `json:"apnsEnabled,omitzero"`
}