capgo icon indicating copy to clipboard operation
capgo copied to clipboard

feat(notifications): add AE native notifications

Open riderx opened this issue 6 months ago • 16 comments

Summary (AI generated)

  • Added the AE-only native notification backend: encrypted push-token registry rows in Cloudflare Analytics Engine, AE event stats, Cloudflare Queue fanout, FCM/APNs senders, invalid-token tombstones, and no per-device notification tables in Postgres.
  • Added low-cardinality Postgres control-plane tables for provider config, app notification settings, and campaign metadata.
  • Added @capgo/capacitor-notifications as a private workspace package with iOS/Android native push, badge, foreground/open/background events, deterministic registration, and silent update-check integration with @capgo/capacitor-updater.
  • Added the app Notifications UI, recipient lookup, stats, provider setup, campaign send/test controls, and a push-update setting that sends silent update-check notifications.
  • Added capgo notifications setup CLI scaffolding for customer apps.

Motivation (AI generated)

Capgo needs native notifications without creating a large per-device notification table in the primary database. This follows the existing device_info style by writing append-only Analytics Engine state and reading the latest active device state with argMax, while keeping Postgres limited to control-plane data.

Business Impact (AI generated)

This opens a new Capgo product surface for customer-to-user notifications, badge management, and push-triggered live update checks while keeping database cost and blast radius low. It also gives Capgo a first-party plugin and onboarding path instead of asking customers to assemble multiple lower-level notification pieces themselves.

Test Plan (AI generated)

  • [x] bun lint
  • [x] bun lint:backend
  • [x] bun typecheck
  • [x] bun run cli:build
  • [x] bun run --cwd packages/capacitor-notifications typecheck
  • [x] bun run --cwd packages/capacitor-notifications build
  • [x] bunx vitest run tests/native-notifications-ae.unit.test.ts
  • [x] bun test:backend
  • [x] bun test:front
  • [x] iOS plugin build with xcodebuild -scheme CapgoCapacitorNotifications -destination generic/platform=iOS
  • [x] Android plugin build/test with Gradle

Screenshots (AI generated)

Native notifications desktop

Native notifications mobile

Operational Notes (AI generated)

  • The package is configured as private/restricted. Publishing to npm failed with 402 Payment Required because the org/account needs private package billing enabled. I did not publish it publicly.
  • Silent update checks in this PR use the updater plugin public JS API so the Capgo app-level channel and next/set settings are honored. I also opened the follow-up updater PR for a native-owned trigger: https://github.com/Cap-go/capacitor-updater/pull/765.

Generated with AI

Summary by CodeRabbit

  • New Features

    • Native notifications (iOS APNs + Android FCM) with a Capacitor plugin and published package.
    • In-app Notifications dashboard: providers, campaigns, recipient lookup, stats, push-update controls, and test/send.
    • CLI "notifications setup" command and notification HTTP endpoints + background delivery workers.
    • Badge management, event tracking, and push update check triggering.
    • Database migration introducing notification tables and access policies.
  • Documentation

    • Plugin README and new i18n strings for notifications UI.
  • Tests

    • Unit tests for native notification processing and enhanced E2E login/API key tests.

Review Change Stack

riderx avatar May 11 '26 12:05 riderx

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements a comprehensive native notifications platform for Capgo. It introduces a new Capacitor plugin for iOS/Android devices to register with notification providers (FCM/APNs), a Supabase Edge Function API for managing notification campaigns and events, Cloudflare queue infrastructure for batch message delivery, PostgreSQL tables for control-plane data, a Vue frontend dashboard for notification management, and CLI automation for app setup.

Changes

Native Notifications Platform

Layer / File(s) Summary
Capacitor plugin package & build configuration
packages/capacitor-notifications/package.json, tsconfig.json, CapgoCapacitorNotifications.podspec, Package.swift, .gitignore, Android build files
Complete npm package with ESM configuration, iOS (Swift Package Manager, CocoaPods), and Android (Gradle) build systems.
Android plugin implementation
packages/capacitor-notifications/android/
Java-based Capacitor plugin integrating Firebase Cloud Messaging, handling permission flows, badge/channel/device management, and notification delivery with native bridge to web listeners.
iOS plugin implementation
packages/capacitor-notifications/ios/Sources/CapgoNotificationsPlugin/
Swift-based Capacitor plugin implementing UNUserNotificationCenter delegates for foreground/background handling, permission requests, badge/device/channel management, and remote notification forwarding.
Plugin TypeScript definitions and main bridge
packages/capacitor-notifications/src/definitions.ts, src/index.ts
TypeScript interfaces for all plugin types plus runtime state management, token lifecycle, update-check deduplication, device registration, event tracking, and updater integration.
Cloudflare and Supabase infrastructure setup
cloudflare_workers/api/wrangler.jsonc, supabase/config.toml, supabase/migrations/20260524140304_native_notifications_control_plane.sql
Cloudflare queue/dataset bindings, Supabase Edge Function configuration, database tables for provider configs, app settings, and campaigns with RLS and unique constraint on (owner_org, app_id).
Backend notification utilities and security primitives
supabase/functions/_backend/utils/nativeNotifications.ts
Identity derivation, AES-GCM token encryption, HMAC proof generation/verification, Cloudflare Analytics registry/event tracking, sharding by bucket/index, and queue message construction.
Notification delivery and queue processing
supabase/functions/_backend/utils/nativeNotificationSender.ts
FCM and APNs credential caching, token-specific message building, HTTP request sending with error classification (invalid-token vs transient), event emission, and batch queue processing with retry logic.
Cloudflare Workers utility updates
supabase/functions/_backend/utils/cloudflare.ts
Export escapeSqlString and runQueryToCFA, update Analytics Engine bindings to AnalyticsEngineDataset, add optional notification queue/registry/events bindings.
Supabase Edge Function API routes
supabase/functions/_backend/public/notifications/index.ts
Hono app exposing 14 API routes: device registration, event ingestion, recipient lookup/proof, settings CRUD, campaign management, provider configuration, badge/update-check/send operations with validation and RBAC.
Supabase Edge Function server initialization
supabase/functions/notifications/index.ts
Deno HTTP server startup with Hono app, error middleware, and function metadata.
Frontend notifications management dashboard
src/pages/app/[app].notifications.vue
Vue component with authenticated API client, concurrent data loading, race-safe refresh mechanism, provider/campaign/settings forms, recipient lookup, event stats display, test send controls, and app-not-found fallback.
Frontend routing and app navigation
src/constants/appTabs.ts, src/route-map.d.ts
Add notifications tab to app navigation with bell icon and /notifications route; extend typed route definitions.
CLI notifications setup command
cli/src/notifications/setup.ts
Command resolves app ID, configures Capacitor plugin, optionally installs notification packages, generates typed helper module, runs cap sync, and exports renderNotificationHelper function.
Native app integration points
ios/App/App/AppDelegate.swift, package.json
iOS remote notification handler forwarding to NotificationCenter, and monorepo workspace expansion from cli to ["cli", "packages/*"].
Internationalization, documentation, and API tests
messages/en.json, packages/capacitor-notifications/README.md, tests/native-notifications-ae.unit.test.ts
i18n keys for provider/campaign/settings UI; plugin README covering setup, iOS/Android integration, usage examples, and silent update-check behavior; unit tests for Analytics Engine queries, proof verification, and queue message processing.
Test infrastructure and end-to-end test updates
.github/workflows/tests.yml, playwright/support/commands.ts, playwright/e2e/apikeys.spec.ts, src/pages/ApiKeys.vue
Node.js v24 setup for Wrangler; login retry logic with schema-cache error handling; API key form interaction scoping and test updates; API key list prepending instead of appending.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Suggested labels

codex

coderabbitai[bot] avatar May 11 '26 12:05 coderabbitai[bot]

Merging this PR will not alter performance

✅ 43 untouched benchmarks
⏩ 2 skipped benchmarks[^skipped]


Comparing codex/native-notifications-ae (6b22d61) with main (c6692bf)

Open in CodSpeed

[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

codspeed[bot] avatar May 11 '26 13:05 codspeed[bot]

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai review

riderx avatar May 11 '26 14:05 riderx

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar May 11 '26 14:05 coderabbitai[bot]

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedis-wsl@​3.1.11001006980100
Addedmicromatch@​4.0.810010010083100

View full report

socket-security[bot] avatar May 11 '26 15:05 socket-security[bot]

The public event proof looks too broad for delivery analytics integrity. createNotificationEventProof() only signs appId, recipientKey, and deviceKey, but /notifications/events accepts that same long-lived proof for any event/campaign/notification tuple. After registration, any client holding its eventProof can post queued, sent, provider_accepted, failed, opened, etc. with arbitrary campaignId / notificationId / error, and those values are written straight to AE by trackNotificationEventCF(). That lets one device poison campaign delivery/open/failure stats for unrelated campaigns in the same app.

I would either bind the proof to the server-issued notification/campaign payload (or include an expiry/nonce and the allowed event class), or restrict the public endpoint to client-observable events and validate that the campaign/notification was actually targeted to that recipient/device. A regression should show that an event proof minted during registration cannot be reused to report failed/opened for an arbitrary campaign id.

digzrow-coder avatar May 13 '26 19:05 digzrow-coder

The public event proof looks too broad for delivery analytics integrity. createNotificationEventProof() only signs appId, recipientKey, and deviceKey, but /notifications/events accepts that same long-lived proof for any event/campaign/notification tuple. After registration, any client holding its eventProof can post queued, sent, provider_accepted, failed, opened, etc. with arbitrary campaignId / notificationId / error, and those values are written straight to AE by trackNotificationEventCF(). That lets one device poison campaign delivery/open/failure stats for unrelated campaigns in the same app.

I would either bind the proof to the server-issued notification/campaign payload (or include an expiry/nonce and the allowed event class), or restrict the public endpoint to client-observable events and validate that the campaign/notification was actually targeted to that recipient/device. A regression should show that an event proof minted during registration cannot be reused to report failed/opened for an arbitrary campaign id.

digzrow-coder avatar May 13 '26 19:05 digzrow-coder

There is a tag-targeting mismatch in the registry query path.

normalizeTags() stores registered tags after trimming, lowercasing, replacing unsupported characters with _, truncating to 64 chars, and wrapping the result with pipes. The send path does not apply the same normalization: resolveTargetDevices() forwards target.tag unchanged, and buildNotificationRegistryLookupQuery() only does params.tag.toLowerCase() before querying position('|...|' IN tags).

So a device registered with tags: ['Beta Users'] is stored as |beta_users|, but /notifications/send with target: { tag: 'Beta Users' } queries for |beta users| and targets zero devices. The same miss happens for punctuation or overlong tags.

Can this share a single normalizeNotificationTag helper between registration and tag filtering, or reject non-normalized target tags? A unit test for a tag with a space/punctuation would cover the regression.

albercr3 avatar May 14 '26 13:05 albercr3

@coderabbitai review

riderx avatar May 24 '26 14:05 riderx

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar May 24 '26 14:05 coderabbitai[bot]

Fixed the review blockers on the new head: client notification events now require delivery-scoped proofs bound to app/recipient/device/campaign/notification, server/provider events are rejected from /notifications/events, client error payloads are no longer persisted, tag targeting reuses registration normalization, and the Android library manifest documents host-owned backup policy for Sonar without forcing app-wide backup settings from the plugin.

riderx avatar May 24 '26 14:05 riderx

@coderabbitai review

riderx avatar May 24 '26 14:05 riderx

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar May 24 '26 14:05 coderabbitai[bot]

I checked the new event-proof split after the latest fix. Delivery events now require the delivery-scoped proof, but the device-event branch still forwards caller-supplied campaign fields.

Risk: a registered device can use its long-lived eventProof to write permission_changed rows against arbitrary campaignId / otificationId values. That no longer spoofs opened/sent, but it can still pollute campaign-scoped stats with device events.

Verification: CLIENT_NOTIFICATION_DEVICE_EVENTS contains permission_changed; /notifications/events verifies that branch with erifyNotificationEventProof, then passes campaignId and otificationId through to rackNotificationEventCF. I think device events should drop those fields, or any event carrying campaign/notification ids should require the delivery proof.

thefuturrjfhejh avatar May 26 '26 17:05 thefuturrjfhejh