Compare commits

...
130 Commits
Author SHA1 Message Date
trentlarson d7f915d7ad bump to version 1.4.7, including increase of minSdkVersion to 24 which requires Android 7+ 2026-10-10 18:57:25 -06:00
trentlarson e96f501ec0 add 'npm run dev' for a quick dev-startup command 2026-10-10 07:46:34 -06:00
trentlarson 7af00aff6f allow changing of the image API server URL 2026-10-10 07:41:07 -06:00
trentlarson adffef6a50 fix messaging on redirect page & remove the remaining isDevelopment check 2026-10-10 07:40:16 -06:00
trentlarson 824d77e267 guard the in-app notifications with showGeneralAdvanced (not build isDev) 2026-10-10 07:40:16 -06:00
Jose Olarte III 1d1801e9b5 bump version and add '-beta' 2026-10-09 10:35:00 -04:00
Jose Olarte III 07cb1feddf Tie the in-app New Activity toggle to AlertSearch authorization so turning it on uploads the batch and turning it off deletes it without unregistering the FCM device. 2026-10-08 15:50:55 -04:00
Jose Olarte III b0292d3f04 Send AlertSearch authorization with POST so the upload matches the notify API.
PUT /notifications/alert-authorization no longer exists on notification-wakeup-service, so the debug-panel upload received 404.
2026-10-05 09:22:08 -04:00
Jose Olarte III 70a4a8c9fe Merge branch 'master' into retire-legacy-notification 2026-10-04 10:11:35 -04:00
trentlarson a03ed849c4 bump version and add '-beta' 2026-09-27 21:45:40 -06:00
trentlarson 6183afc29c bump version to 1.4.6 2026-09-27 21:45:09 -06:00
trentlarson 1afe5461b2 put package.json scripts in alphabetical order (no logic changes) 2026-09-27 21:22:14 -06:00
trentlarson 4bb0e4d4f9 make a fix for running in an emulator, plus doc changes 2026-09-27 21:17:36 -06:00
Claude CodeandClaude Opus 5.5 2fd5549098 fix(android): skip push registration in builds without Firebase, which crashed the app at launch
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 21:06:35 -06:00
Claude CodeandClaude Opus 5.5 28ee81b9d3 fix(build): fail --prod builds with test server defaults; sync web assets before Gradle assembles
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 21:06:34 -06:00
trentlarson 38af28154e bump version and add '-beta' 2026-09-26 16:11:15 -06:00
trentlarson 70372a113a bump version to 1.4.5 2026-09-26 16:09:35 -06:00
trentlarson 9e88cf056c fix asset copying (which weren't allowing iOS to build) 2026-09-26 16:08:56 -06:00
trentlarson db13332dd6 add migration note for clarification 2026-09-24 14:31:06 -06:00
Jose Olarte III c84cce54af Document the retired WAKEUP_PING refresh path as inactive and drop unused refresh auth helpers.
Guides and the debug panel still described /notifications/refresh and api_* scheduling as current after Phase 5; keep Phase 4 cleanup and FCM send-wakeup diagnostics.
2026-09-24 22:35:48 +08:00
Jose Olarte III 4f339eba32 Raise leftover iOS deployment targets from 14.0 to 15.5 so Xcode 27 can build.
Align the project, Share Extension, and CocoaPods `post_install` with the existing 15.5 minimum. Also refresh the CocoaPods embed-frameworks phase and package-lock peer metadata.
2026-09-24 17:17:08 +08:00
Jose Olarte III eb2240b901 Retire WAKEUP_PING refresh consumption and clear leftover api_* schedules on upgrade.
Stop the app from scheduling via the legacy refresh pipeline, and add a one-time Preferences-gated startup cleanup that calls clearApiNotifications() so upgraded installs shed persisted api_* residue without touching daily reminder, dual, AlertSearch, or FCM.
2026-09-22 20:59:23 +08:00
Jose Olarte III 724131d9a8 Retire app consumption of WAKEUP_PING → /notifications/refresh → api_* scheduling.
Phase 2 of legacy notification retirement: drop the production push refresh chain and dead debug/composable paths while keeping FCM registration, AlertSearch, daily reminder, and dual notifications intact.
2026-09-22 20:39:37 +08:00
trentlarson e77d08e3a8 Merge branch 'fix/shared-photo-deeplink' 2026-09-21 18:57:00 -06:00
trentlarson ef476bbb57 fix problem with project ID for "given to" project links, fix deep-link redirect for web, update browserslist DB 2026-09-21 07:55:08 -06:00
trentlarson 2bbf230312 adjust the URL for sharing a photo with the app (since it was going to the root "/" home route for sharing and that caused conflicts when we actually want to deep-link to the home page) 2026-09-20 21:35:52 -06:00
trentlarson 45503f568a fix more types and make more code consistent (mobile test seems to hang) 2026-09-20 16:10:36 -06:00
trentlarson e350feb132 add some other deep links for useful pages, and fix a UI test 2026-09-20 15:17:58 -06:00
trentlarson 7e3f2aa004 add deep-links for "" (base), new-activity, and QR-scan pages 2026-09-20 14:26:05 -06:00
Jose Olarte III de951543c7 Merge branch 'notify-api_endpoint-query' 2026-09-17 14:46:01 +08:00
Jose Olarte III 7604a92f60 Hide the in-app notification channel on Account unless running a development build. 2026-09-16 17:26:04 +08:00
trentlarson 4bf2fc1009 fix potential build problems (Claude recommendations) 2026-09-14 13:06:19 -06:00
trentlarson 97f4f59eff make the background-search JWTs in the pool all unique, removing problematic jti 2026-09-14 12:33:52 -06:00
trentlarson 6baf2a98ac reconcile & fix changes in FCM & SMS notifications 2026-09-14 10:23:06 -06:00
trentlarson 44695a51cc Merge branch 'notify-api_endpoint-query_merge' into notify-api_endpoint-query 2026-09-14 08:09:49 -06:00
trentlarson 044344026c Merge commit '0c400b87' into notify-api_endpoint-query 2026-09-13 18:47:53 -06:00
trentlarson fe9a2f0cbb Merge branch 'notify-api-sms' into notify-api_endpoint-query 2026-09-13 18:45:36 -06:00
trentlarson 240c3c5a76 Consolidate notify-api JWT minting; add wire types (WIP before SMS merge) 2026-09-13 17:08:23 -06:00
Jose Olarte III 4fcc9a40d0 Align AlertSearch authorization uploads with the wakeup-service contract: UTC-day delegated JWTs and required notifyHourUtc/notifyMinuteUtc. 2026-09-10 22:07:00 +08:00
Jose Olarte III 2afe748292 Send the ngrok skip-browser-warning header only when the Notification Debug Panel backend override is set.
WebView fetch to free ngrok was blocked by the interstitial (no CORS ACAO). Keep production notify-api requests unchanged.
2026-09-03 21:12:05 +08:00
Jose Olarte III 34a8c51d2f Add a manual debug-panel action to mint and PUT the 100-day AlertSearch authorization batch.
Reuse the existing delegated JWT minting and notification API auth so a signed-in ethr identity can upload the batch to the configured notify backend without changing production defaults or sending it automatically.
2026-09-02 15:34:03 +08:00
trentlarson 59993cb96a fix husky git hooks (because it was complaining about those lines) 2026-08-30 17:59:01 -06:00
trentlarson 940e851d3c adjust the UX for SMS text opt-in, to show terms immediately 2026-08-30 17:55:23 -06:00
trentlarson 0c400b8797 fix spacing in a doc diagram 2026-08-30 11:07:36 -06:00
Jose Olarte III d5bcdbae3f Mint 100 per-local-day delegated notification JWTs for notify-api without touching the native background pool.
Each token is signed with the existing Endorser path and bounded by the user’s timezone midnight, so the next phase can submit the batch without changing prefetch JWTs or notification scheduling.
2026-08-26 16:05:51 +08:00
Jose Olarte III 46a2e0aaf5 Add typed alertSearch API contract and response models without implementing the daily search flow.
This prepares the app for endorser and partner alertSearch by capturing the known buckets, cursor ULID semantics, and JWT kinds, without changing notification scheduling or the background JWT pool.
2026-08-26 15:25:19 +08:00
trentlarson b02a1b29c5 add T&C/privacy link for notification help 2026-08-22 13:01:48 -06:00
trentlarson 3f291b0d63 add a more comprehensive demo UI workflow for SMS signup 2026-08-13 09:45:16 -06:00
jose 6b65ad8554 Merge pull request 'New Giftopia App Icons and Splashes' (#236) from giftopia-app-icon into master
Reviewed-on: #236
2026-07-29 12:08:44 +00:00
Jose Olarte III d5c357b291 Document dedicated Notification API URL configuration.
Describe VITE_DEFAULT_NOTIFY_API_SERVER / DEFAULT_NOTIFY_API_SERVER,
the debug-override resolution order, and replace outdated APP_SERVER
assumptions in build and notification testing docs.
2026-07-22 20:56:20 +08:00
Jose Olarte III 86611fe50d Update notification debug panel default URL hint.
Replace the outdated APP_SERVER placeholder with DEFAULT_NOTIFY_API_SERVER
so the UI matches centralized notify-api base URL resolution.
2026-07-22 18:02:34 +08:00
Jose Olarte III 4152012838 Point notification API base URL at DEFAULT_NOTIFY_API_SERVER.
Keep debug localStorage overrides first; fall back to the dedicated
notify-api default instead of APP_SERVER.
2026-07-22 17:45:10 +08:00
Jose Olarte III 25110e3eea Align DEFAULT_NOTIFY_API_SERVER with other backend service defaults.
Drop getDefaultNotifyApiServer and the Endorser-based fallback so notify
config uses the same env-or-prod pattern as image, partner, and push.
2026-07-22 17:39:48 +08:00
Jose Olarte III 0ecd4c6dd7 Add dedicated Notification API URL config for prod and test.
Introduce PROD/TEST notify-api constants, DEFAULT_NOTIFY_API_SERVER, and
VITE_DEFAULT_NOTIFY_API_SERVER in env files so notification traffic can
target notify-api hosts independently of APP_SERVER.
2026-07-22 17:35:37 +08:00
trentlarson ee8fb80cfe start the SMS notifications, beginning with the UI 2026-07-19 20:23:34 -06:00
trentlarson cdf5c721a5 update some iOS settings per Xcode recommendation 2026-07-18 15:40:34 -06:00
trentlarson 974002fa90 tweak scripts & docs for iOS build on new device 2026-07-18 15:39:24 -06:00
Jose Olarte III f23fe65078 docs(notifications): document debug panel auth settings and bypassAuth
Add doc/notification-debug-panel.md as the canonical panel reference.
Update ngrok guides, README, and analysis doc to describe independent
Backend URL, Test Mode, and Skip JWT Authentication settings, including
recommended configs for hosted test servers vs local ngrok.
2026-07-07 19:21:18 +08:00
Jose Olarte III 82380b3d35 fix(notifications): decouple JWT bypass from backend URL override
Add an explicit notificationDebug.bypassAuth setting (default off) so
custom backend URLs and test mode no longer skip authentication. Expose
the toggle in the Notification Debug Panel for local ngrok workflows;
hosted test servers receive JWT-authenticated requests by default.
2026-07-07 19:00:42 +08:00
Jose Olarte III 6a7f341990 docs(android): document Send Real WAKEUP_PING debug panel flow
Add §6 coverage for the full backend→FCM→refresh pipeline, expected
Logcat lines, and troubleshooting that distinguishes backend success
from end-to-end delivery; cross-link checklist, workflow, and §14.
2026-06-12 18:23:19 +08:00
Jose Olarte III 693bfacc1e feat(notifications): include refresh source in completion and failure logs
Thread options.source through logRefreshSuccess and logRefreshFailure so
WAKEUP_PING and debug-panel refreshes are grep-friendly end-to-end in
Logcat and the Event Log without changing refresh behavior.
2026-06-12 17:12:21 +08:00
Jose Olarte III 3d6ac2ab53 feat(dev): test full WAKEUP_PING pipeline from debug panel
Add Send Real WAKEUP_PING via /debug/send-wakeup and rename the local
refresh shortcut to Simulate WAKEUP_PING (Local).
2026-06-11 17:01:28 +08:00
Jose Olarte III cd32895281 refactor(notifications): use clearApiNotifications and scheduleApiNotifications
Update the refresh replacement flow for the renamed plugin APIs and remove
the obsolete clearPredictiveNotifications type augmentation.
2026-06-09 19:39:50 +08:00
Jose Olarte III a1f94300ad refactor(notifications): rename predictive terminology to API notifications
Update app logs, comments, and debug inspector labels to use API
notification wording while keeping clearPredictiveNotifications plugin
calls unchanged. Align the iOS pending-notification inspector with the
plugin's api_ identifier prefix.
2026-06-09 17:49:08 +08:00
Jose Olarte III 58b61471b5 fix(notifications): use clearPredictiveNotifications on refresh
Avoid cancelAllNotifications during schedule replacement so Daily
Reminder schedules are not cleared.
2026-06-08 19:42:48 +08:00
Jose Olarte III 55ef36be06 fix(notifications): send deviceId on refresh to match backend contract
The /notifications/refresh endpoint now requires deviceId or fcmToken.
Reuse the stable device ID from registration so refresh no longer returns 400.
2026-06-05 19:14:07 +08:00
Jose Olarte III 00abd5277f fix(dev): refresh Backend Status URL after save in debug panel
activeBackendUrl was a computed with no reactive deps, so it stayed stale
until the panel remounted. Use a ref and update it in syncBackendState().
2026-06-03 17:53:54 +08:00
Jose Olarte III 227ae85bb7 build(android): wire Capacitor Preferences and Firebase for push testing
Register @capacitor/preferences in the Android Capacitor project so
notification deviceId storage matches iOS. Replace the placeholder
google-services.json with the production Firebase client config for FCM.
Refresh package-lock after native sync / install.
2026-06-03 17:53:31 +08:00
Jose Olarte III e0a3f7094f docs(notifications): add Android local ngrok testing guide
Add local-android-testing-ngrok.md for FCM wakeup, debug panel, Firebase
setup, platform/battery notes, troubleshooting, verification checklist, and
end-to-end QA flow. Add local-android-testing-analysis.md as planning
notes mapping reuse from the iOS ngrok guide.
2026-06-02 21:33:23 +08:00
Jose Olarte III 2dd76878ba build(ios): enable push and remote background notification capabilities
Add AppDebug.entitlements with development aps-environment for Debug builds, point Debug signing at it, and add remote-notification to UIBackgroundModes.
2026-05-27 17:26:33 +08:00
Jose Olarte III 4fb8f048cd build(ios): add GoogleService-Info.plist to Xcode resources
Also clarify the ngrok iOS guide steps for dragging the plist into the correct App folder/target.
2026-05-27 17:01:35 +08:00
Jose Olarte III c97defef11 build(ios): add CapacitorPreferences pod for notification deviceId
Wire @capacitor/preferences into the iOS Capacitor Podfile so stable
deviceId persistence works on native builds. Refresh package-lock.json.
2026-05-25 17:06:07 +08:00
Jose Olarte III 2c0992ba8b docs(notifications): put Xcode workspace before Firebase in ngrok guide
Reorder first-time setup so Capacitor/Xcode workspace generation (section 4)
precedes Firebase and APNs steps that require Xcode. Update cross-links and
skip targets; no change to Firebase/APNs technical instructions.
2026-05-25 16:59:17 +08:00
Jose Olarte III 964cdb4509 docs(notifications): add from-scratch Firebase and APNs setup to ngrok guide
Document first-time FCM/APNs configuration (project, plist, .p8 key,
Admin credentials, Xcode capabilities) before the iOS build step, and
renumber later sections so the checklist references the new flow.
2026-05-24 17:33:01 +08:00
Jose Olarte III 656de5eba3 docs(notifications): clarify ngrok guide so backend starts once
Consolidate first-run backend setup in section 1 and reframe section 2
as verification only, so local iPhone testing does not look like two
separate startup steps.
2026-05-24 10:21:10 +08:00
Jose Olarte III 0d7586865c feat(notifications): allow auth bypass for local debug and ngrok testing
Add shouldBypassNotificationAuth() when test mode or a backend URL override
is set so register/refresh can proceed without DID/Bearer headers. Production
paths still require auth when bypass is off; log bypass vs authenticated
request modes for easier WAKEUP_PING and panel smoke testing.
2026-05-20 19:34:46 +08:00
Jose Olarte III 5bc030125a feat(notifications): defer FCM registration until auth is ready
Queue token registration when Bearer auth is unavailable at startup,
with bounded exponential backoff retries. Flush the pending token when
identity is set, the app resumes, or the native fetcher configures.
Skip refresh API calls when auth is missing and log lifecycle events
for registration wait and refresh skip.
2026-05-20 15:54:36 +08:00
Jose Olarte III 8cd8727a84 feat(notifications): authenticate register and refresh API calls
Use getHeaders(activeDid) for POST /notifications/register and
/notifications/refresh so requests include Authorization: Bearer tokens
like the rest of the app. Add notificationApiAuth helper for shared header
resolution, auth logging, and graceful handling when identity or token
is missing or the server returns 401/403.
2026-05-20 15:45:46 +08:00
Jose Olarte III 8864a2049b docs(notifications): add local iOS ngrok testing guide for wakeup service
Document Mac backend + ngrok + physical iPhone setup, debug panel overrides,
Firebase/APNs checklist, curl examples, and troubleshooting for WAKEUP_PING flows.
2026-05-18 21:22:53 +08:00
Jose Olarte III 63f5c4ecc7 feat(notifications): add structured observability for push wake and refresh flows
Introduce NotificationDebugEvents and [Notifications] console/panel logging for push
handlers, token registration, refresh timing, schedule replacement, and WAKEUP_PING.
2026-05-18 18:46:16 +08:00
Jose Olarte III a4453c0b1b feat(dev): extend Notification Debug Panel for backend testing
Add backend URL, test mode, token re-register, refresh diagnostics, FCM token display,
and a capped event log; expose refreshNotificationsWithDiagnostics and reregisterFcmTokenNow.
2026-05-18 16:28:21 +08:00
Jose Olarte III 794b48f0d7 feat(notifications): add localStorage debug config for notification API base URL
Introduce NotificationDebugConfig so register/refresh use getNotificationApiBaseUrl()
(APP_SERVER by default, optional LAN/ngrok override) and configurable testMode without rebuilds.
2026-05-18 15:06:52 +08:00
Jose Olarte III 4c97c578bb fix(notifications): fall back when crypto.randomUUID is missing
If randomUUID is unavailable (older WebViews), generate a one-time ID
with Date.now + random segment, log a single DeviceId warning, and
persist it as before so registration still works.
2026-05-13 20:57:14 +08:00
Jose Olarte III 6a9f34a516 feat(notifications): persist stable deviceId for FCM registration
Add getOrCreateDeviceId() backed by Capacitor Preferences so one UUID
survives app restarts and token refreshes. Include deviceId in POST
/notifications/register alongside fcmToken, platform, and testMode.
Add @capacitor/preferences and lightweight DeviceId logs (no token/ID values).
2026-05-13 18:41:10 +08:00
Jose Olarte III 5a40075ab1 fix(dev): pending inspector stable times and refreshPending without nested busy
Expose wall-clock fire targets from the iOS NotificationInspector
(scheduled_time userInfo and predictive_<epochMs> ids) so the debug
panel is not misleading when nextTriggerDate resamples for interval
triggers. Extend TS types and show the scheduled target in the UI,
with a note when iOS nextTriggerDate diverges.

Make refreshPending a plain fetch so mock refresh, wakeup ping, flood
test, and clear notifications can refresh the pending list while an
outer withBusy guard is already active.
2026-05-11 13:50:52 +08:00
Jose Olarte III 48637ae9a8 docs(readme): document Notification Debug Panel for dev builds 2026-05-11 11:16:43 +08:00
Jose Olarte III a55dce6f3d fix(dev): align notification debug with non-production Capacitor builds
Add includeDevToolkitRoutes (vite dev or MODE !== production) and use it
from the router, AccountViewView, and NotificationDebugView so the debug
screen matches dev-notifications registration after vite build.

Update the gated banner copy to refer to production Vite builds.
2026-05-08 20:02:34 +08:00
Jose Olarte III d7d5e401b8 fix: dev notification debug on Capacitor and iOS compile
Register the dev-notifications route whenever the bundle is non-production
(DEV or Vite MODE !== production), matching the account screen so RouterLink
to Notification Debug does not throw after vite build.

Align AccountViewView isDev with that rule and document the coupling.

Add NotificationInspectorPlugin.swift to the App target compile sources so
AppDelegate can register the plugin.
2026-05-08 17:54:00 +08:00
Jose Olarte III 19427c2817 fix(account): avoid import.meta in AccountViewView template
Vue’s template compiler treats bindings as non-module JS, so
`import.meta.env.DEV` in `v-if` broke the Capacitor/Vite build.
Expose a readonly `isDev` from the script instead.
2026-05-08 16:34:17 +08:00
Jose Olarte III d4ac0acd01 chore: bump @timesafari/daily-notification-plugin to 3.0.2 2026-05-08 16:31:52 +08:00
Jose Olarte III 1ef3f32b9e fix(dev): clarify Android pending inspector and harden debug entry guard
- Report UNIMPLEMENTED from Android NotificationInspector instead of empty pending
- Surface iOS-only inspector message in NotificationDebugPanel without noisy errors
- Gate Account debug link with import.meta.env.DEV and document intent
- Add architecture comments on NotificationDebugService, inspector plugin, and native exports
2026-05-07 20:40:09 +08:00
Jose Olarte III fd0b8ce6d0 feat(dev): add notification debug panel and native pending inspector
Add a dev-only Notification Debug Panel at /dev/notifications for testing
predictive refresh and WAKEUP_PING without a backend.

- Gate route and Advanced Settings entry on import.meta.env.DEV
- NotificationDebugService drives mock refresh, flood test, clear, and
  wake simulation via existing handleCapacitorPushNotificationReceived and
  applyNotificationRefreshPayload (shared with refreshNotifications)
- Add NotificationInspector Capacitor plugin: iOS lists pending
  UNNotificationRequest identifiers and next trigger; Android stub returns
  empty pending for safe registration
2026-05-07 18:52:59 +08:00
Jose Olarte III 320e55912b fix(notifications): apply backend timestamps via scheduleNotifications API
Stop converting backend timestamps to HH:mm/recurring schedules and remove
createSchedule/updateSchedule reconciliation. After a successful refresh payload,
clear existing notifications and schedule exact timestamps via the plugin
scheduleNotifications API (with back-compat clear fallback) to prevent drift.
2026-05-06 17:56:55 +08:00
Jose Olarte III 6bbade2a29 feat(notifications): refresh on mount and resume with debounce
Trigger refreshNotifications on composable mount and document resume, using a
debounced/in-flight guarded wrapper to avoid rapid duplicate refresh calls.
Expose the debounced refresh function from useNotifications.
2026-05-06 17:11:10 +08:00
Jose Olarte III 1cd329c720 fix(notifications): clear scheduled notifications before refresh apply
Cancel all native notifications before applying the backend-provided schedule so
refreshNotifications always performs a full replacement and never leaves stale
entries behind.
2026-05-06 16:45:56 +08:00
Jose Olarte III 7c8ef284c2 feat(notifications): apply backend refresh schedule to native plugin
Update refreshNotifications to POST /notifications/refresh and map returned
nextNotifications timestamps to clockTime schedules, upserting them via the
DailyNotification schedule APIs (with deterministic IDs) after refreshing native
fetcher credentials.
2026-05-06 16:17:50 +08:00
Jose Olarte III 35a1b92559 feat(notifications): refresh native fetcher on WAKEUP_PING silent push
Add refreshNotifications (configureNativeFetcherIfReady) and
handleCapacitorPushNotificationReceived for data.type WAKEUP_PING; invoke from
Capacitor pushNotificationReceived without UI.
2026-05-06 16:04:01 +08:00
Jose Olarte III c523c14d96 feat(notifications): register FCM tokens with backend
Add registerToken POST to /notifications/register (platform, testMode).
Call it from Capacitor registration and Firebase getToken with deduped
registerRetrievedToken; expose registerToken via barrel and useNotifications
as registerFcmToken.
2026-05-06 15:40:00 +08:00
Jose Olarte III 162158066f feat(notifications): initialize Firebase Messaging and Capacitor push on native
Add firebaseMessagingClient to ensure the Firebase app is created from VITE_FIREBASE_*,
wire PushNotifications (listeners, requestPermissions, register) before token work,
and call getMessaging/getToken/onMessage when firebase/messaging is supported. Hook
startup from main.capacitor and set PushNotifications presentationOptions in
capacitor.config. Depend on firebase and @capacitor/push-notifications.
2026-05-06 15:30:46 +08:00
Jose Olarte III 1643bab18b Merge branch 'notify-api_android' into notify-api 2026-04-23 16:08:05 +08:00
Jose Olarte III ce078862e7 chore: sync package-lock and Podfile.lock (TimesafariDailyNotificationPlugin 3.0.1) 2026-04-20 17:44:00 +08:00
Jose Olarte III b9f19d3898 fix(notifications): set dual-schedule fallbackBehavior to skip
Avoid showing default New Activity copy when dual content is missing or
outside contentTimeout, per PLUGIN_NOTIFICATION_FIX_ANDROID.md.
2026-04-16 21:21:37 +08:00
Jose Olarte III 24957e0c6f docs(notifications): add Android plugin handout for empty-fetch dual schedule
Document PLUGIN_NOTIFICATION_FIX_ANDROID diagnosis and recommended changes in
the daily-notification-plugin repo, verified against plugin 3.0.0.
2026-04-10 21:12:11 +08:00
Jose Olarte III 954500cf9d fix(ios): static SQLCipher pods, strip system SQLite, refresh deps
- Podfile: use static frameworks; post_install/post_integrate hooks to
  avoid mixing Apple libsqlite3/SQLite headers with SQLCipher (including
  stripping aggregate Pods-App xcconfig flags for Swift explicit modules).
- Xcode: enable CLANG_ENABLE_MODULES; replace CocoaPods “Embed Pods
  Frameworks” phase with “Copy Pods Resources”; minor project file hygiene.
- Pods: SQLCipher 4.10.0, ZIPFoundation patch bump; Podfile.lock updated.
- package.json: allow patch updates for @capacitor-community/sqlite (^6.0.2);
  regenerate package-lock.json.
- Info.plist: reorder keys only (same URL scheme, background modes, BG tasks,
  notification alert style).
2026-04-09 21:46:32 +08:00
Jose Olarte III 73d595046a docs(readme): expand Setup & Building quick start for all platforms
Restructure the quick start with Web, Android, and iOS subheadings; put
each npm command in its own code block; fold the test-page step into the
Web section. Document Android (build:android:test:run + ADB, link to
BUILDING.md) and iOS (build:ios:studio + Xcode prerequisites).
2026-04-02 19:03:58 +08:00
Jose Olarte III cf9d207895 fix(ios): make build-ios.sh work on current simulators and trim xcodebuild noise
Use generic/platform=iOS Simulator instead of a fixed device name so CLI builds
do not fail when that simulator is not installed (e.g. newer Xcode runtimes).

Pass -quiet to xcodebuild and enable SWIFT_SUPPRESS_WARNINGS plus
GCC_WARN_INHIBIT_ALL_WARNINGS for scripted builds and IPA archive/export so
terminal output stays smaller; full diagnostics remain available in Xcode.
2026-04-02 19:03:58 +08:00
Jose Olarte III 7d87a746f9 feat(ios): register Swift TimeSafariNativeFetcher for New Activity notifications
Add TimeSafariNativeFetcher (plansLastUpdatedBetween parity with Android) and
call DailyNotificationPlugin.registerNativeFetcher from AppDelegate before JS
configureNativeFetcher; broaden DailyNotificationDelivered scheduled_time types
in willPresent. Wire the new file into the App target; normalize PBX object IDs
to 24-char hex.

Document plugin ≥3 handoff (consuming-app-handoff-ios-native-fetcher-chained-dual),
refresh iOS/Android parity and notification-from-api-call file tables.
2026-04-02 19:02:48 +08:00
Jose Olarte III 90e6603d52 docs: add plugin-repo handoff section to iOS/Android New Activity parity guide
Add §6 with reference file table, Endorser contract summary aligned to
TimeSafariNativeFetcher, likely plugin touchpoints, and suggested implementation
order; renumber acceptance checklist to §7.
2026-04-02 17:51:51 +08:00
Jose Olarte III 8290943b53 docs: add New Activity iOS/Android parity guide and refine follow-ups
Add doc/new-activity-notifications-ios-android-parity.md covering dual-schedule
and Endorser API parity, plugin vs app work, Android dual-path notes, prefetch
vs notify ordering on iOS (§3.3), and clarified Phase B JWT pool status on
both platforms. Link the guide from doc/notification-from-api-call.md under the
iOS checklist.
2026-04-01 20:49:02 +08:00
Jose Olarte III 8ba84888ee feat(android): improve New Activity notification copy in TimeSafariNativeFetcher
Aggregate API rows into one notification with Starred Project Update(s) titles,
plan names in typographic quotes, and "+ N more have been updated." for multiples.
Stop emitting the empty-data "No Project Updates" fallback. Sync internal docs.
2026-03-31 19:50:14 +08:00
Jose Olarte III 230dc52974 feat(notifications): sync starred plans to native plugin on star/unstar
Add syncStarredPlansToNativePlugin() and call it from AccountViewView
(schedule + initializeState) and ProjectViewView.toggleStar when New
Activity is enabled so Android prefetch uses the current starred list.

Update notification-from-api-call.md with the helper and file references.
2026-03-31 15:57:22 +08:00
Jose Olarte III 2c8aa21fa5 feat(notifications): mint JWT pool for native fetcher; log API response
- Mint BACKGROUND_JWT_POOL_SIZE (90 + 10) distinct background JWTs with
  unique jti; pass jwtTokens from nativeFetcherConfig into configureNativeFetcher.
- Android TimeSafariNativeFetcher: overload configure with jwtTokenPool;
  select bearer via epoch day mod pool size; fall back to primary jwtToken.
- Log truncated plansLastUpdatedBetween response at DEBUG for prefetch debugging.
2026-03-30 17:25:50 +08:00
Jose Olarte III 9f44a53047 feat(notifications): mint long-lived JWT for native New Activity prefetch (Phase A)
Add BACKGROUND_JWT_EXPIRY_DAYS/SECONDS and accessTokenForBackgroundNotifications
via createEndorserJwtForDid; configureNativeFetcher uses it instead of getHeaders
so WorkManager prefetch is not stuck with a 60s access token. Interactive API
calls unchanged.
2026-03-27 21:33:46 +08:00
Jose Olarte III c9ea2e4120 docs: plan background JWT pool/expiry and plugin configureNativeFetcher handoff
Add plan-background-jwt-pool-and-expiry.md (Phase A/B, expiryDays + buffer sizing,
pool size 100). Add plugin-feedback-daily-notification-configureNativeFetcher-jwt-pool.md
for daily-notification-plugin: optional jwtTokens on configureNativeFetcher. Link plan
to plugin doc and endorser-jwt-background-prefetch-options.md.
2026-03-27 14:57:54 +08:00
Jose Olarte III 43c9b95c14 docs: add Endorser JWT options for background New Activity prefetch
Document expired-token causes, client limits, and server-side options (TTL,
scoped tokens, refresh, BFF) plus questions for Endorser maintainers.
2026-03-26 18:16:54 +08:00
Jose Olarte III f4ee507918 fix(notifications): refresh native fetcher on resume and log API error bodies
Call configureNativeFetcherIfReady when the app becomes active so getHeaders can
supply a new JWT before the next background prefetch when users return from
background.

In TimeSafariNativeFetcher, read HttpURLConnection#getErrorStream for non-200
responses and log a capped body snippet (including on retryable errors) to
diagnose JWT_VERIFY_FAILED and other API failures.
2026-03-26 18:16:08 +08:00
Jose Olarte III 0ebad3b497 fix(android): skip sync on cap run after restore-local-plugins
`npx cap run android` runs `sync` by default, which regenerated
`capacitor.plugins.json` and removed SafeArea and SharedImage entries
after `restore-local-plugins.js` had already run. Use `--no-sync` in
`build-android.sh` (auto-run) and `auto-run.sh` so the launch step does
not overwrite the restored plugin list.
2026-03-26 15:50:35 +08:00
Jose Olarte III aaee3bbbd2 Add plugin feedback doc for Android dual schedule native fetch and timing
Document how the daily-notification-plugin dual path uses FetchWorker mock/URL
fetch instead of NativeNotificationContentFetcher, schedules fetch immediately
rather than at contentFetch cron, and why DualScheduleHelper shows useCache=false.
Includes acceptance criteria and file pointers for maintainers fixing the plugin.
2026-03-24 22:05:30 +08:00
Jose Olarte III d4cdee0698 Add verbose INFO logging to TimeSafariNativeFetcher for dual-notification debugging
Log configure-time starred plan count, fetchContent entry (trigger, scheduledTime,
thread), worker start, POST summary (plan count, truncated afterId), and HTTP
status at INFO so logcat shows clearly when the native fetcher runs versus
plugin-only DNP-FETCH paths.
2026-03-24 21:19:39 +08:00
Jose Olarte III 178dcec5b8 docs: expand New Activity testing (starred plans, Endorser URL)
Add an Android-focused procedure for verifying API-driven copy when a
starred plan has updates via plansLastUpdatedBetween, including expected
notification text, prefetch timing, repeatability, and logcat. Clarify
that iOS parity is documented separately and that the native fetcher uses
Account API Server URL (test Endorser is valid), not the Partner API URL.
2026-03-23 18:56:10 +08:00
Jose Olarte III e121db5fcf fix(notifications): align dual schedule config with Android plugin + bump DNP
- buildDualScheduleConfig: set contentFetch timeout/retryAttempts/retryDelay
  (match capacitor DailyNotification networkConfig), userNotification.vibration,
  return type DualScheduleConfiguration
- @timesafari/daily-notification-plugin 2.1.1 → 2.1.3 (package-lock)
- doc: plugin feedback (contentFetch JSON, parseUserNotificationConfig optional
  fields) and Android DailyNotificationWorker duplicate scheduleId note
2026-03-20 21:13:50 +08:00
Jose Olarte III 1389a166fa fix(ios): New Activity dual notification – handle updateStarredPlans and BGTaskScheduler errors
- Treat updateStarredPlans as optional: catch UNIMPLEMENTED and continue to
  scheduleDualNotification so missing native method no longer blocks scheduling.
- Show specific toast when BGTaskSchedulerErrorDomain error 1 occurs (e.g.
  Simulator): explain that a real device and Background App Refresh are required.
- Add PluginHeaders diagnostic in AccountViewView and main.capacitor.ts to debug
  UNIMPLEMENTED (log DNP methods at call time and at launch).
- Fix main.capacitor.ts build: use CapacitorWindow type and safe cap assignment
  so vite build --mode capacitor succeeds.
- Docs: add UNIMPLEMENTED troubleshooting and updateStarredPlans note in
  plugin-feedback-ios-scheduleDualNotification.md; add section 8.3 in
  notification-new-activity-lay-of-the-land.md.
- Lockfile updates (package-lock.json, Podfile.lock).
2026-03-19 19:26:59 +08:00
Jose Olarte III 3c262c9eeb docs: add plugin feedback doc for iOS scheduleDualNotification
Add plugin-feedback-ios-scheduleDualNotification.md for the
daily-notification-plugin repo: config shape from the app, expected
behavior, and acceptance criteria so iOS can implement or fix
scheduleDualNotification (currently returns UNIMPLEMENTED).
2026-03-17 21:05:06 +08:00
Jose Olarte III e155e55e49 fix(notifications): New Activity vs Daily Reminder separation and copy
- PushNotificationPermission: show "Turn on New Activity Notifications"
  when enabling New Activity; use NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY for
  success toast so copy says "New Activity notifications are now enabled."
- App.vue: on native, turnOffNotifications invokes the modal's callback
  only (fixes turn-off not updating state); add comment that callback is
  per notification type.
- AccountViewView: handle plugin UNIMPLEMENTED for scheduleDualNotification
  on iOS with friendlier message; add New Activity time block and "Edit
  New Activity Notification…"; rename Daily Reminder button to "Edit Daily
  Reminder…".
- Constants: add NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY. Reminder IDs and
  Option A (skip single reminder for New Activity) from earlier commit.
2026-03-17 19:23:40 +08:00
Jose Olarte III 263b12c37e fix(notifications): New Activity dual-only; separate reminder IDs (Option A + 6.3)
- PushNotificationPermission: on native, when enabling New Activity
  (DAILY_CHECK_TITLE), skip scheduleDailyNotification so only
  AccountViewView's scheduleNewActivityDualNotification runs (dual
  schedule only). Daily Reminder still uses single reminder path.
- Add reminderIds.ts with REMINDER_ID_DAILY_REMINDER and
  REMINDER_ID_NEW_ACTIVITY; NativeNotificationService uses the former.
- Export reminder IDs from notifications index. Fixes "always fires /
  can't turn off" by avoiding a second, uncancellable single reminder
  for New Activity.
2026-03-17 16:11:06 +08:00
Jose Olarte III 1df47f17c4 docs: add plugin-repo alignment section to New Activity lay-of-the-land
Document how daily-notification-plugin aligns with app usage (APIs,
dual vs single schedules, native fetcher, exact alarm). Note attention
items: cancelDailyReminder argument shape, INTEGRATION_GUIDE scope, and
iOS use of app-provided id for scheduleDailyNotification.
2026-03-16 21:16:10 +08:00
Jose Olarte III 6f066a7e23 docs: add device testing section and note exact alarm disabled on Android
Expand notification-new-activity-lay-of-the-land.md with section 7 on
testing New Activity on real iOS/Android devices (prerequisites, enable/
disable flows, what to verify before and after fix). Update Android
device notes to state this app has exact alarm disabled (no
SCHEDULE_EXACT_ALARM) and that delivery may be inexact or batched.
2026-03-16 19:05:53 +08:00
Jose Olarte III 9a23e2beba docs: expand proper-fix section in New Activity lay-of-the-land
Add section 6 with Option A (skip single reminder when dialog is for New
Activity), Option B (cancel single reminder on disable, with caveats),
and optional cleanup notes. For team discussion and implementation.
2026-03-16 18:12:04 +08:00
trentlarson 8ac6dd6ce0 make an attempt at new notifications using an API (fires always, can't turn off) 2026-03-15 19:34:30 -06:00
trentlarson c0678385df bump version for this branch, and enhance logging with times 2026-03-15 19:33:43 -06:00
176 changed files with 16472 additions and 3588 deletions
+2
View File
@@ -18,4 +18,6 @@ VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000
#VITE_DEFAULT_PUSH_SERVER... can't be set up with localhost domain
# Using shared test notify API (no local notify server by default).
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
+1
View File
@@ -11,3 +11,4 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://notify-api.timesafari.app
+1
View File
@@ -15,4 +15,5 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
-2
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
#
# Husky Commit Message Hook
# Validates commit message format using commitlint
#
. "$(dirname -- "$0")/_/husky.sh"
# Run commitlint but don't fail the commit (|| true)
# This provides helpful feedback without blocking commits
-2
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
#
# Husky Pre-commit Hook
# Runs lint-fix and Build Architecture Guard on staged files
#
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Running pre-commit hooks..."
-2
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
#
# Husky Pre-push Hook
# Runs Build Architecture Guard to check commits being pushed
#
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Running Build Architecture Guard (pre-push)..."
+1 -1
View File
@@ -13,7 +13,7 @@ This guard is in `android/app/build.gradle`. Do NOT change this conditional to a
`google-services.json` is intentionally excluded from git (`android/.gitignore`). Never commit it.
Full details, incident history, and F-Droid notes: `doc/development/android-firebase-gms.md`
Full details, incident history, and F-Droid notes: `doc/android-firebase-gms.md`
## Android Build — MLKit Barcode Scanner
+80 -48
View File
@@ -10,7 +10,7 @@ This guide explains how to build TimeSafari for different platforms using the co
# 🖥️ Web Development
npm install # setup -- and pkgx.dev `dev` command before this will set environment with npm, etc
npm run build:web:serve -- --test # Start with test endorser server
npm run build:web:dev # Start development server with hot reload with local endorser server
npm run dev # Start development server with hot reload with local endorser server
npm run build:web:prod # Production build
# 📱 Mobile Development
@@ -44,7 +44,7 @@ npm run test:web # Run web tests to verify setup
```bash
# Start web development server
npm run build:web:dev # Opens http://localhost:8080
npm run dev # Opens http://localhost:8080
# For mobile development
npm run build:ios # Opens Xcode with iOS project
@@ -164,6 +164,7 @@ cp .env.example .env.development
# - VITE_DEFAULT_ENDORSER_API_SERVER
# - VITE_DEFAULT_PARTNER_API_SERVER
# - VITE_DEFAULT_IMAGE_API_SERVER
# - VITE_DEFAULT_NOTIFY_API_SERVER
```
#### Platform-Specific Development
@@ -224,7 +225,7 @@ npm install
```bash
# Local development
npm run build:web:dev # Start development server with hot reload
npm run dev # Start development server with hot reload (shortcut for `build:web:dev`)
# Web builds
npm run build:web # Development build (starts dev server with hot reload)
@@ -240,7 +241,7 @@ npm run build:web:docker:prod # Production build with Docker containerizat
### Local Development
Start the development server using `npm run build:web:dev` or `npm run build:web` (both start the development server with hot reload).
Start the development server using `npm run dev` (a shortcut for `npm run build:web:dev`) or `npm run build:web` (both start the development server with hot reload).
### Web Build for Server
@@ -1083,6 +1084,11 @@ npm run build:ios:assets # Generate assets only
npm run build:ios:deploy # Build and deploy to connected device
```
The iOS asset command reads source artwork from `resources/` explicitly. It
generates the default 1024×1024 App Store icon, from which Xcode derives the
required device sizes, and installs any available appearance variants under
`ios/App/App/Assets.xcassets/AppIcon.appiconset/`.
#### Automated Build Script
The recommended way to build for iOS is using the automated build script:
@@ -1126,7 +1132,7 @@ If you need to build manually or want to understand the individual steps:
##### 0. First time (or if dependencies change)
- `pkgx +rubygems.org zsh`
- `pkgx +rubygems.org +pod /bin/zsh`
- ... and you may have to fix these, especially with pkgx:
@@ -1140,7 +1146,7 @@ export GEM_PATH=$shortened_path
##### 1. Bump the version in package.json & CHANGELOG.md for `MARKETING_VERSION`, then `grep CURRENT_PROJECT_VERSION ios/App/App.xcodeproj/project.pbxproj` and add 1 for the numbered version here:
```bash
cd ios/App && xcrun agvtool new-version 70 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.4.4;/g" App.xcodeproj/project.pbxproj && cd -
cd ios/App && xcrun agvtool new-version 72 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.4.6;/g" App.xcodeproj/project.pbxproj && cd -
# Unfortunately this edits Info.plist directly.
#xcrun agvtool new-marketing-version 0.4.5
```
@@ -1153,20 +1159,28 @@ Here's prod. Also available: test, dev
npm run build:ios:prod
```
- The first time, it may complain about a bundler install for "missing gems", and you'll want to run the "install" command it gives you.
3.1. Use Xcode to build and run on simulator or device.
- Select Product -> Destination with some Simulator version. Then click the run arrow.
3.2. Use Xcode to release.
- Someday: Under "General" we want to rename a bunch of things to "Time Safari"
- Someday: Under "General" we want to rename a bunch of things to "Giftopia"
- Choose Product -> Destination -> Any iOS Device
- Choose Product -> Archive
- This will trigger a build and take time, needing user's "login" keychain
password (user's login password), repeatedly.
- Required password entry 26 times.
- It can get stuck on uploading SPI; try canceling and restarting.
- If it fails with `building for 'iOS', but linking in dylib
(.../.pkgx/zlib.net/v1.3.0/lib/libz.1.3.dylib) built for 'macOS'` then run
XCode outside that terminal (ie. not with `npx cap open ios`).
- Before distributing, confirm the archive carries production server
defaults. Xcode packages whatever web bundle is in `ios/App/App/public`,
even one from a `--test` build:
`./scripts/check-prod-bundle.sh ios/App/App/public`
- Click Distribute -> App Store Connect
- In AppStoreConnect, add the build to the distribution. You may have to remove
the current build with the "-" when you hover over it, then "Add Build" with the
@@ -1316,6 +1330,7 @@ npm run build:android:prod # Production build (builds for production e
# Auto-run builds
npm run build:android:test:run # Test build with auto-run (builds then runs on emulator)
npm run build:android:prod:run # Production build with auto-run (builds then runs on emulator)
# Auto-run targets the one connected device; with none or several it prompts, or exits 9 without a terminal
# Debug and release builds
npm run build:android:debug # Debug build (builds debug APK)
@@ -1419,8 +1434,8 @@ The recommended way to build for Android is using the automated build script:
##### 1. Bump the version in package.json, then update these versions & run:
```bash
perl -p -i -e 's/versionCode .*/versionCode 70/g' android/app/build.gradle
perl -p -i -e 's/versionName .*/versionName "1.4.4"/g' android/app/build.gradle
perl -p -i -e 's/versionCode .*/versionCode 73/g' android/app/build.gradle
perl -p -i -e 's/versionName .*/versionName "1.4.7"/g' android/app/build.gradle
```
##### 2. Build
@@ -1431,42 +1446,45 @@ perl -p -i -e 's/versionName .*/versionName "1.4.4"/g' android/app/build.gradle
npm run build:android:prod
```
##### 3. Open the project in Android Studio
##### 2.1. (Optional) Open the project in Android Studio
```bash
npx cap open android
```
##### 4. Use Android Studio to build and run on emulator or device
##### 3. Use Android Studio to build and run on emulator or device
## Android Build from the console
#### Android Build from the console
`cd android`
* Note that this currently fails: `./gradlew build`
To create a signed `aab` release:
- Setup by adding the app/gradle.properties.secrets file (see properties at top
of app/build.gradle) and the app/time-safari-upload-key-pkcs12.jks file
- Then `bundleRelease` or `bundleDebug`:
```bash
cd android
./gradlew clean
./gradlew build -Dlint.baselines.continue=true
cd -
# if you use pkgx: pkgx +openjdk.org /bin/zsh
./gradlew bundleRelease -Dlint.baselines.continue=true -PfirebaseEnabled
```
... or, to create the `aab` file, `bundle` instead of `build`:
... and find your `aab` file at app/build/outputs/bundle/release
To create an unsigned debugging bundle (not usable in Play Store):
```bash
./gradlew bundleDebug -Dlint.baselines.continue=true
```
... or, to create a signed release:
- Setup by adding the app/gradle.properties.secrets file (see properties at top
of app/build.gradle) and the app/time-safari-upload-key-pkcs12.jks file
- Then `bundleRelease`:
```bash
cd android
./gradlew bundleRelease -Dlint.baselines.continue=true -PfirebaseEnabled
cd -
```
... and find your `aab` file at app/build/outputs/bundle/release
* Gradle packages whatever web bundle was last synced into
`android/app/src/main/assets/public`, even one from a `--test` build. Before
uploading, confirm it has production server defaults:
`./scripts/check-prod-bundle.sh android/app/build/outputs/bundle/release/app-release.aab`
* `build-android.sh` runs `./gradlew clean`, which deletes any earlier `aab`, so
run `bundleRelease` after the build script finishes.
* Note that F-Droid builds should omit `-PfirebaseEnabled`.
@@ -1604,10 +1622,13 @@ Use the commands above to check and fix code quality issues.
4. **Native Build**: Platform-specific compilation
5. **Package Creation**: APK/IPA generation
`resources/` is the canonical source for app icons and splash screens.
Do not keep a legacy top-level `assets/` directory unless it is intentionally
used: `@capacitor/assets` prioritizes `assets/` over `resources/`, which can
prevent the canonical assets from being discovered.
`resources/` is the canonical source for app icons and splash screens. Build
scripts select it explicitly with `--assetPath resources`. Use the same option
when invoking the generator directly:
```bash
npx capacitor-assets generate --assetPath resources
```
## Architecture Environment Configuration
@@ -1654,6 +1675,7 @@ The build system supports multiple environment file patterns for different scena
VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://notify-api.timesafari.app
# Platform Configuration
VITE_PLATFORM=web|electron|capacitor
@@ -1673,6 +1695,7 @@ VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZY
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_APP_SERVER=http://localhost:8080
```
@@ -1683,6 +1706,7 @@ VITE_APP_SERVER=http://localhost:8080
VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch
VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_APP_SERVER=https://test.timesafari.app
```
@@ -1693,6 +1717,7 @@ VITE_APP_SERVER=https://test.timesafari.app
VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://notify-api.timesafari.app
VITE_APP_SERVER=https://timesafari.app
```
@@ -1720,20 +1745,10 @@ VITE_APP_SERVER=https://timesafari.app
fi
```
2. **Platform-Specific Overrides**
2. **Environment File Loading**
```bash
# scripts/build-android.sh
if [ "$BUILD_MODE" = "development" ]; then
export VITE_DEFAULT_ENDORSER_API_SERVER="http://10.0.2.2:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://10.0.2.2:3000"
fi
```
3. **Environment File Loading**
```bash
# scripts/build-web.sh
# scripts/build-web.sh, build-android.sh, build-ios.sh, build-electron.sh
local env_file=".env.$BUILD_MODE" # .env.development, .env.test, .env.production
if [ -f "$env_file" ]; then
load_env_file "$env_file"
@@ -1745,6 +1760,18 @@ VITE_APP_SERVER=https://timesafari.app
fi
```
3. **Platform-Specific Overrides**
These run last so the platform address wins over the `.env` files.
```bash
# scripts/build-android.sh
if [ "$BUILD_MODE" = "development" ]; then
export VITE_DEFAULT_ENDORSER_API_SERVER="http://10.0.2.2:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://10.0.2.2:3000"
fi
```
4. **Application Usage**
```typescript
@@ -1813,7 +1840,7 @@ npm run build:android:assets
- Configure signing keys
- Check device/emulator setup
## Additional Resources
## Additional Documentation
- [Electron Build Patterns](doc/electron-build-patterns.md)
- [iOS Build Scripts](doc/ios-build-scripts.md)
@@ -1950,6 +1977,7 @@ The build system supports multiple environment file patterns:
VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://notify-api.timesafari.app
# Platform Configuration
VITE_PLATFORM=web|electron|capacitor
@@ -2202,6 +2230,8 @@ command chaining, following DRY principles.
- `7` - Asset generation failed
- `8` - Android Studio launch failed
- `9` - Resource check failed
- `10` - Production bundle has test/dev server defaults (`--prod` only; see
`scripts/check-prod-bundle.sh`)
### A.4 build-ios.sh
@@ -2262,6 +2292,8 @@ command chaining, following DRY principles.
- **Clean Build**: Removes Xcode build artifacts and DerivedData
- **Asset Generation**: Creates platform-specific assets
- **Simulator Support**: Launches iOS Simulator for testing
- **Production Bundle Check**: With `--prod`, exits with code `10` if the synced
web bundle has test/dev server defaults (`scripts/check-prod-bundle.sh`)
### A.5 common.sh
@@ -2375,7 +2407,7 @@ npm run clean:electron # Electron only
# Clean and rebuild
npm run clean:all
npm install
npm run build:web:dev
npm run dev
```
## Appendix B: Vite Configuration Files Reference
+19
View File
@@ -6,6 +6,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.4.6] - 2026.09.27
### Fixed
- Incorrect 'test' server URLs on production.
## [1.4.5] - 2026.09.24
### Added
- Full flow for setting up SMS notifications: phone registration and code
verification, delegated alertSearch JWT batches with a send hour, and
revocation to stop the texts
- Notification debug panel action to mint and upload a push-channel alertSearch
authorization, built on the same batch minter as the SMS channel (hidden by dev flag)
### Fixed
- Native build scripts set NODE_ENV, so `import.meta.env.DEV` matches the build
mode instead of always reporting a production build
- Android and iOS development builds keep their emulator and `--api-ip` API
addresses, which the `.env` files had been overwriting
## [1.4.4] - 2026.06.21
### Changed
- More checks for Firebase so that it won't break, eg in Aurora store.
+75 -6
View File
@@ -20,7 +20,7 @@ npm install
### Web
```bash
npm run build:web:dev
npm run dev
```
Then go to [the test page](http://localhost:8080/test) and click "Become User 0" to take action on the platform.
@@ -33,6 +33,45 @@ npm run build:android:test:run
Assumes ADB is installed; see [Android Build](BUILDING.md#android-build) for SDK, emulator, and `PATH` setup.
#### Building an APK for Android 6 (API 23)
App versions up to 1.4.6 support Android 6.0 (API 23); later versions require Android 7.0 (API 24) or newer. To run the app on an Android 6 device, build your own APK from the 1.4.6 release commit (`6183afc2`, "bump version to 1.4.6").
Prerequisites: git, Node.js 20 (see `.nvmrc`), Java 21, and the Android SDK with `ANDROID_HOME` set (see [Android Emulator Without Android Studio](BUILDING.md#android-emulator-without-android-studio-command-line-only) for an SDK setup that skips Android Studio). With [pkgx](https://pkgx.dev), prefix the commands with `pkgx`, e.g. `pkgx npm ci`.
1. Get the 1.4.6 source:
```bash
git clone https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa.git
cd crowd-funder-for-time-pwa
git checkout 6183afc2
```
2. Confirm the minimum SDK is 23:
```bash
grep minSdkVersion android/variables.gradle # expect: minSdkVersion = 23
```
3. Install dependencies and build a production APK:
```bash
npm ci
npm run build:android:prod -- --apk
```
`npm ci` installs the exact dependency versions locked for 1.4.6. `build:android:prod -- --apk` builds the web app with production server settings, syncs it into the Android project, and runs `./gradlew assembleDebug`. The result is signed with your local Android debug key, so it installs on any device without a release keystore.
4. Find the APK at `android/app/build/outputs/apk/debug/app-debug.apk` and install it, either with `adb install android/app/build/outputs/apk/debug/app-debug.apk` (USB debugging enabled on the phone) or by copying the file to the phone and opening it (allow "Install unknown apps" for the file manager).
Notes:
* **Back up your identity first.** A self-built APK has a different signature from the Play Store app, so Android refuses to install it over the store version. Uninstalling the store version deletes the app's local data, including your identifier keys. Back up your seed phrase (Profile page → "Backup Identifier Seed") before uninstalling, then import it into the self-built app.
* This build has Firebase disabled, so push notifications through Google's FCM service are off.
* The daily notification plugin calls `java.time`, which Android provides only from 8.0 (API 26). On Android 6, scheduling a daily reminder can crash the app; leave daily reminders off. See [doc/plugin-feedback-android-6-api23-zoneid-fix.md](doc/plugin-feedback-android-6-api23-zoneid-fix.md).
* Barcode scanning uses Google Play Services; on devices without them, scanning fails while the rest of the app works.
* A self-built APK does not auto-update.
### iOS
```bash
@@ -43,6 +82,15 @@ Assumes Xcode and Xcode Command Line Tools are installed.
See [BUILDING.md](BUILDING.md) for comprehensive build instructions for all platforms (Web, Electron, iOS, Android, Docker).
## Tests
```
npm run test:web
# ... or do every check:
npm run test:all
```
## 🛡️ Build Architecture Guard
This project uses **Husky Git hooks** to protect the build system
@@ -89,16 +137,16 @@ TimeSafari supports configurable logging levels via the `VITE_LOG_LEVEL` environ
```bash
# Show only errors
VITE_LOG_LEVEL=error npm run build:web:dev
VITE_LOG_LEVEL=error npm run dev
# Show warnings and errors
VITE_LOG_LEVEL=warn npm run build:web:dev
VITE_LOG_LEVEL=warn npm run dev
# Show info, warnings, and errors (default)
VITE_LOG_LEVEL=info npm run build:web:dev
VITE_LOG_LEVEL=info npm run dev
# Show all log levels including debug
VITE_LOG_LEVEL=debug npm run build:web:dev
VITE_LOG_LEVEL=debug npm run dev
```
### Available Levels
@@ -110,6 +158,27 @@ VITE_LOG_LEVEL=debug npm run build:web:dev
See [Logging Configuration Guide](doc/logging-configuration.md) for complete details.
## Notification Debug Panel (dev builds)
In non-production bundles (for example `vite dev` or a Vite build whose mode is not `production`), the **Notification Debug Panel** at `/dev/notifications` helps you test FCM token registration, AlertSearch authorization upload, FCM wakeup delivery (`/debug/send-wakeup`), and local schedule inspection on native builds. The app no longer consumes `WAKEUP_PING` to call `/notifications/refresh` or schedule `api_*` notifications.
**Access:** **Account** → enable **Show All General Advanced Functions** → **Notification Debug Panel**.
Key configuration (independent settings):
- **Notification Backend URL** — which notification server receives API calls
- **Test Mode** — `testMode` sent in JSON request bodies (default on)
- **Skip JWT Authentication (Local Development Only)** — omit JWT headers for local unauthenticated backends (default off)
See [doc/notification-debug-panel.md](doc/notification-debug-panel.md) for controls, recommended settings (hosted test server vs local ngrok), and troubleshooting.
Platform-specific end-to-end guides:
- [doc/local-android-testing-ngrok.md](doc/local-android-testing-ngrok.md)
- [doc/local-ios-testing-ngrok.md](doc/local-ios-testing-ngrok.md)
## Database Clearing (development)
### Quick Usage
```bash
# Run the database clearing script
@@ -117,7 +186,7 @@ See [Logging Configuration Guide](doc/logging-configuration.md) for complete det
# Then restart your development server
npm run build:electron:dev # For Electron
npm run build:web:dev # For Web
npm run dev # For Web
```
### What It Does
+2 -2
View File
@@ -37,8 +37,8 @@ android {
applicationId "app.timesafari.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 70
versionName "1.4.4"
versionCode 73
versionName "1.4.7"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
+2
View File
@@ -15,6 +15,8 @@ dependencies {
implementation project(':capacitor-camera')
implementation project(':capacitor-clipboard')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-preferences')
implementation project(':capacitor-push-notifications')
implementation project(':capacitor-share')
implementation project(':capacitor-status-bar')
implementation project(':capawesome-capacitor-file-picker')
+46 -7
View File
@@ -1,13 +1,13 @@
{
"project_info": {
"project_number": "123456789000",
"project_id": "timesafari-app",
"storage_bucket": "timesafari-app.appspot.com"
"project_number": "1094643115061",
"project_id": "pc-api-7249509642322112640-286",
"storage_bucket": "pc-api-7249509642322112640-286.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:123456789000:android:1234567890abcdef",
"mobilesdk_app_id": "1:1094643115061:android:f11bd26f6bd2fcdc887d7c",
"android_client_info": {
"package_name": "app.timesafari.app"
}
@@ -15,7 +15,45 @@
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyDummyKeyForBuildPurposesOnly12345"
"current_key": "AIzaSyCFLYeLfGQqh7ErvzXgy74H0Gx3yQAMEw8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:1094643115061:android:354e70007466b006887d7c",
"android_client_info": {
"package_name": "ch.endorser.mobile"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyCFLYeLfGQqh7ErvzXgy74H0Gx3yQAMEw8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:1094643115061:android:40b63cb5851f34ac887d7c",
"android_client_info": {
"package_name": "com.veramo_react_native"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyCFLYeLfGQqh7ErvzXgy74H0Gx3yQAMEw8"
}
],
"services": {
@@ -24,5 +62,6 @@
}
}
}
]
}
],
"configuration_version": "1"
}
@@ -16,6 +16,13 @@
]
}
},
"PushNotifications": {
"presentationOptions": [
"badge",
"sound",
"alert"
]
},
"SplashScreen": {
"launchShowDuration": 3000,
"launchAutoHide": true,
@@ -23,6 +23,14 @@
"pkg": "@capacitor/filesystem",
"classpath": "com.capacitorjs.plugins.filesystem.FilesystemPlugin"
},
{
"pkg": "@capacitor/preferences",
"classpath": "com.capacitorjs.plugins.preferences.PreferencesPlugin"
},
{
"pkg": "@capacitor/push-notifications",
"classpath": "com.capacitorjs.plugins.pushnotifications.PushNotificationsPlugin"
},
{
"pkg": "@capacitor/share",
"classpath": "com.capacitorjs.plugins.share.SharePlugin"
@@ -46,5 +54,9 @@
{
"pkg": "SharedImage",
"classpath": "app.timesafari.sharedimage.SharedImagePlugin"
},
{
"pkg": "NotificationInspector",
"classpath": "app.timesafari.notifications.NotificationInspectorPlugin"
}
]
@@ -16,6 +16,7 @@ import android.webkit.WebViewClient;
import com.getcapacitor.BridgeActivity;
import app.timesafari.safearea.SafeAreaPlugin;
import app.timesafari.sharedimage.SharedImagePlugin;
import app.timesafari.notifications.NotificationInspectorPlugin;
//import com.getcapacitor.community.sqlite.SQLite;
import android.content.SharedPreferences;
@@ -29,6 +30,7 @@ public class MainActivity extends BridgeActivity {
private static final String KEY_BASE64 = "shared_image_base64";
private static final String KEY_FILE_NAME = "shared_image_file_name";
private static final String KEY_READY = "shared_image_ready";
private static final Uri SHARED_PHOTO_DEEP_LINK = Uri.parse("timesafari://shared-photo");
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -66,10 +68,17 @@ public class MainActivity extends BridgeActivity {
// Register SharedImage plugin
registerPlugin(SharedImagePlugin.class);
// Register NotificationInspector plugin (dev tooling; safe no-op on Android)
registerPlugin(NotificationInspectorPlugin.class);
// Register DailyNotification plugin
// Plugin is written in Kotlin but compiles to Java-compatible bytecode
registerPlugin(org.timesafari.dailynotification.DailyNotificationPlugin.class);
// Register native content fetcher for API-driven daily notifications (Endorser.ch)
org.timesafari.dailynotification.DailyNotificationPlugin.setNativeFetcher(
new TimeSafariNativeFetcher(this));
// Initialize SQLite
//registerPlugin(SQLite.class);
@@ -113,7 +122,9 @@ public class MainActivity extends BridgeActivity {
}
if (imageUri != null) {
String fileName = intent.getStringExtra(Intent.EXTRA_TEXT);
processSharedImage(imageUri, fileName);
if (processSharedImage(imageUri, fileName)) {
notifySharedPhotoDeepLink();
}
handled = true;
}
}
@@ -130,7 +141,9 @@ public class MainActivity extends BridgeActivity {
imageUris = uris;
}
if (imageUris != null && !imageUris.isEmpty()) {
processSharedImage(imageUris.get(0), null);
if (processSharedImage(imageUris.get(0), null)) {
notifySharedPhotoDeepLink();
}
handled = true;
}
}
@@ -149,10 +162,12 @@ public class MainActivity extends BridgeActivity {
}
/**
* Process a shared image: read it, convert to base64, and write to temp file
* Process a shared image: read it, convert to base64, and write it to SharedPreferences
* Uses try-with-resources to ensure proper stream cleanup and prevent network issues
*
* @return true when the image is available to the SharedImage plugin
*/
private void processSharedImage(Uri imageUri, String fileName) {
private boolean processSharedImage(Uri imageUri, String fileName) {
// Extract filename from URI or use default (do this before opening streams)
String actualFileName = fileName;
if (actualFileName == null || actualFileName.isEmpty()) {
@@ -175,7 +190,7 @@ public class MainActivity extends BridgeActivity {
if (inputStream == null) {
Log.e(TAG, "Failed to open input stream for shared image");
return;
return false;
}
// Read image bytes
@@ -191,21 +206,36 @@ public class MainActivity extends BridgeActivity {
String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
// Store in SharedPreferences for plugin to read
storeSharedImageInPreferences(base64String, actualFileName);
if (!storeSharedImageInPreferences(base64String, actualFileName)) {
return false;
}
Log.d(TAG, "Successfully processed shared image: " + actualFileName);
return true;
} catch (IOException e) {
Log.e(TAG, "Error processing shared image", e);
return false;
} catch (Exception e) {
Log.e(TAG, "Unexpected error processing shared image", e);
return false;
}
}
/**
* Deliver an App-plugin URL event after the shared image is ready. The App plugin retains
* URL-open events until JavaScript registers its listener, covering both cold and warm starts.
*/
private void notifySharedPhotoDeepLink() {
Intent deepLinkIntent = new Intent(Intent.ACTION_VIEW, SHARED_PHOTO_DEEP_LINK);
getBridge().onNewIntent(deepLinkIntent);
Log.d(TAG, "Delivered shared-photo deep link to Capacitor");
}
/**
* Store shared image data in SharedPreferences for plugin to read
* Plugin will read and clear the data when called
*/
private void storeSharedImageInPreferences(String base64, String fileName) {
private boolean storeSharedImageInPreferences(String base64, String fileName) {
try {
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
@@ -215,9 +245,11 @@ public class MainActivity extends BridgeActivity {
editor.apply();
Log.d(TAG, "Stored shared image data in SharedPreferences");
return true;
} catch (Exception e) {
Log.e(TAG, "Error storing shared image in SharedPreferences", e);
return false;
}
}
}
}
@@ -1,61 +1,405 @@
package app.timesafari;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.timesafari.dailynotification.FetchContext;
import org.timesafari.dailynotification.NativeNotificationContentFetcher;
import org.timesafari.dailynotification.NotificationContent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* Native content fetcher for API-driven daily notifications.
* Calls Endorser.ch plansLastUpdatedBetween with configured credentials and
* starred plan IDs (from plugin's updateStarredPlans), then returns notification content.
*/
public class TimeSafariNativeFetcher implements NativeNotificationContentFetcher {
private static final String TAG = "TimeSafariNativeFetcher";
private final Context context;
private static final String ENDORSER_ENDPOINT = "/api/v2/report/plansLastUpdatedBetween";
private static final int CONNECT_TIMEOUT_MS = 10000;
private static final int READ_TIMEOUT_MS = 15000;
private static final int MAX_RETRIES = 3;
/** Max chars of response body logged at DEBUG (avoids huge log lines). */
private static final int MAX_RESPONSE_BODY_LOG_CHARS = 4096;
private static final int RETRY_DELAY_MS = 1000;
// Must match plugin's SharedPreferences name and keys (DailyNotificationPlugin / TimeSafariIntegrationManager)
private static final String PREFS_NAME = "daily_notification_timesafari";
private static final String KEY_STARRED_PLAN_IDS = "starredPlanIds";
private static final String KEY_LAST_ACKED_JWT_ID = "last_acked_jwt_id";
private final Gson gson = new Gson();
private final Context appContext;
private final SharedPreferences prefs;
// Configuration from TypeScript (set via configure())
private volatile String apiBaseUrl;
private volatile String activeDid;
private volatile String jwtToken;
/** Distinct JWTs from configureNativeFetcher `jwtTokens`; null = use jwtToken only. */
@Nullable
private List<String> jwtTokenPool;
public TimeSafariNativeFetcher(Context context) {
this.context = context;
this.appContext = context.getApplicationContext();
this.prefs = appContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
@Override
public void configure(String apiBaseUrl, String activeDid, String jwtToken) {
configure(apiBaseUrl, activeDid, jwtToken, null);
}
@Override
public void configure(
String apiBaseUrl,
String activeDid,
String jwtToken,
@Nullable List<String> jwtTokenPool) {
this.apiBaseUrl = apiBaseUrl;
this.activeDid = activeDid;
this.jwtToken = jwtToken;
Log.i(TAG, "Fetcher configured with API: " + apiBaseUrl + ", DID: " + activeDid);
this.jwtTokenPool =
jwtTokenPool != null && !jwtTokenPool.isEmpty()
? new ArrayList<>(jwtTokenPool)
: null;
int starredCount = getStarredPlanIds().size();
Log.i(
TAG,
"Configured with API: "
+ apiBaseUrl
+ ", starredPlanIds count="
+ starredCount
+ (this.jwtTokenPool != null
? ", jwtPoolSize=" + this.jwtTokenPool.size()
: ""));
}
/**
* Picks the pool entry whose validity window covers today, falling back to the
* primary jwtToken when no pool is configured.
*
* <p>Each pooled JWT carries nbf/exp spanning exactly one UTC day, and the minter
* (mintBackgroundJwtTokenPool) files the token for a given day at index
* {@code epochDay % size}. That is why the index below is the raw epoch day rather
* than a count from when the pool arrived: this side keeps no mint date, and the
* same arithmetic on both ends is what lines the slot up with the day it covers.
* A token read from the wrong slot is outside its window and Endorser rejects it.
*/
private String selectBearerTokenForRequest() {
List<String> pool = jwtTokenPool;
if (pool == null || pool.isEmpty()) {
return jwtToken;
}
long epochDay = System.currentTimeMillis() / (24L * 60 * 60 * 1000);
int idx = (int) (epochDay % pool.size());
String t = pool.get(idx);
if (t == null || t.isEmpty()) {
return jwtToken;
}
Log.i(TAG, "Bearer from JWT pool: index=" + idx + " of " + pool.size());
return t;
}
@NonNull
@Override
public CompletableFuture<List<NotificationContent>> fetchContent(@NonNull FetchContext fetchContext) {
Long scheduled = fetchContext.scheduledTime;
Log.i(
TAG,
"fetchContent START trigger="
+ fetchContext.trigger
+ " scheduledTime="
+ (scheduled != null ? scheduled : "null")
+ " callerThread="
+ Thread.currentThread().getName());
Log.d(TAG, "Fetching notification content, trigger: " + fetchContext.trigger);
return fetchContentWithRetry(fetchContext, 0);
}
private CompletableFuture<List<NotificationContent>> fetchContentWithRetry(
@NonNull FetchContext context, int retryCount) {
return CompletableFuture.supplyAsync(() -> {
try {
// TODO: Implement actual content fetching for TimeSafari
// This should query the TimeSafari API for notification content
// using the configured apiBaseUrl, activeDid, and jwtToken
Log.i(TAG, "fetchContent worker thread=" + Thread.currentThread().getName());
String bearer = selectBearerTokenForRequest();
if (apiBaseUrl == null || activeDid == null || bearer == null || bearer.isEmpty()) {
Log.e(TAG, "Not configured. Call configureNativeFetcher() from TypeScript first.");
return Collections.emptyList();
}
// Not implemented yet: return no content rather than fabricating a
// placeholder notification (previously hardcoded "Check your starred
// projects for updates!", which showed on every app startup).
Log.d(TAG, "Content fetching not yet implemented; returning no notifications");
return Collections.<NotificationContent>emptyList();
String urlString = apiBaseUrl + ENDORSER_ENDPOINT;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
connection.setReadTimeout(READ_TIMEOUT_MS);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + bearer);
connection.setDoOutput(true);
Map<String, Object> requestBody = new HashMap<>();
List<String> planIds = getStarredPlanIds();
requestBody.put("planIds", planIds);
String afterId = getLastAcknowledgedJwtId();
if (afterId == null || afterId.isEmpty()) {
afterId = "0";
}
requestBody.put("afterId", afterId);
Log.i(
TAG,
"POST "
+ ENDORSER_ENDPOINT
+ " planCount="
+ planIds.size()
+ " afterId="
+ (afterId.length() > 12 ? afterId.substring(0, 12) + "…" : afterId));
String jsonBody = gson.toJson(requestBody);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
Log.i(TAG, "HTTP response code: " + responseCode);
if (responseCode == 200) {
StringBuilder response = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
String responseBody = response.toString();
String snippet =
responseBody.length() <= MAX_RESPONSE_BODY_LOG_CHARS
? responseBody
: responseBody.substring(0, MAX_RESPONSE_BODY_LOG_CHARS) + "…";
Log.d(
TAG,
"plansLastUpdatedBetween response len="
+ responseBody.length()
+ " body="
+ snippet);
List<NotificationContent> contents = parseApiResponse(responseBody, context);
if (!contents.isEmpty()) {
updateLastAckedJwtIdFromResponse(responseBody);
}
Log.i(TAG, "Fetched " + contents.size() + " notification(s)");
return contents;
}
if (retryCount < MAX_RETRIES && (responseCode >= 500 || responseCode == 429)) {
int delayMs = RETRY_DELAY_MS * (1 << retryCount);
String errBody = readHttpErrorBodySnippet(connection);
Log.w(
TAG,
"Retryable error "
+ responseCode
+ (errBody.isEmpty() ? "" : " body: " + errBody)
+ ", retrying in "
+ delayMs
+ "ms");
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return Collections.emptyList();
}
return fetchContentWithRetry(context, retryCount + 1).join();
}
String errBody = readHttpErrorBodySnippet(connection);
if (errBody.isEmpty()) {
Log.e(TAG, "API error " + responseCode);
} else {
Log.e(TAG, "API error " + responseCode + " body: " + errBody);
}
return Collections.emptyList();
} catch (Exception e) {
Log.e(TAG, "Fetch failed", e);
if (retryCount < MAX_RETRIES) {
try {
Thread.sleep(RETRY_DELAY_MS * (1 << retryCount));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return Collections.emptyList();
}
return fetchContentWithRetry(context, retryCount + 1).join();
}
return Collections.emptyList();
}
});
}
/**
* Reads error response body for logging (HttpURLConnection puts 4xx/5xx bodies on
* {@link HttpURLConnection#getErrorStream()}).
*/
private static String readHttpErrorBodySnippet(HttpURLConnection connection) {
InputStream stream = connection.getErrorStream();
if (stream == null) {
return "";
}
final int maxChars = 4096;
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (sb.length() > 0) {
sb.append('\n');
}
if (sb.length() + line.length() > maxChars) {
sb.append(line, 0, Math.max(0, maxChars - sb.length()));
sb.append("…");
break;
}
sb.append(line);
}
return sb.toString().trim();
} catch (IOException e) {
return "(read error body failed: " + e.getMessage() + ")";
}
}
private List<String> getStarredPlanIds() {
try {
String idsJson = prefs.getString(KEY_STARRED_PLAN_IDS, "[]");
if (idsJson == null || idsJson.isEmpty() || "[]".equals(idsJson)) {
return new ArrayList<>();
}
JsonArray arr = JsonParser.parseString(idsJson).getAsJsonArray();
List<String> list = new ArrayList<>();
for (int i = 0; i < arr.size(); i++) {
list.add(arr.get(i).getAsString());
}
return list;
} catch (Exception e) {
Log.e(TAG, "Error loading starred plan IDs", e);
return new ArrayList<>();
}
}
private String getLastAcknowledgedJwtId() {
return prefs.getString(KEY_LAST_ACKED_JWT_ID, null);
}
private void updateLastAckedJwtIdFromResponse(String responseBody) {
try {
JsonObject root = JsonParser.parseString(responseBody).getAsJsonObject();
if (!root.has("data")) return;
JsonArray dataArray = root.getAsJsonArray("data");
if (dataArray == null || dataArray.size() == 0) return;
JsonObject lastItem = dataArray.get(dataArray.size() - 1).getAsJsonObject();
String jwtId = null;
if (lastItem.has("jwtId")) {
jwtId = lastItem.get("jwtId").getAsString();
} else if (lastItem.has("plan")) {
JsonObject plan = lastItem.getAsJsonObject("plan");
if (plan.has("jwtId")) {
jwtId = plan.get("jwtId").getAsString();
}
}
if (jwtId != null && !jwtId.isEmpty()) {
prefs.edit().putString(KEY_LAST_ACKED_JWT_ID, jwtId).apply();
}
} catch (Exception e) {
Log.w(TAG, "Could not extract JWT ID from response", e);
}
}
/**
* Display title for a plansLastUpdatedBetween row; prefers {@code plan.name}, else "Unnamed Project".
*/
private String extractProjectDisplayTitle(JsonObject item) {
if (item.has("plan")) {
JsonObject plan = item.getAsJsonObject("plan");
if (plan.has("name") && !plan.get("name").isJsonNull()) {
String name = plan.get("name").getAsString();
if (name != null && !name.trim().isEmpty()) {
return name.trim();
}
}
}
return "Unnamed Project";
}
@Nullable
private String extractJwtIdFromItem(JsonObject item) {
if (item.has("plan")) {
JsonObject plan = item.getAsJsonObject("plan");
if (plan.has("jwtId") && !plan.get("jwtId").isJsonNull()) {
return plan.get("jwtId").getAsString();
}
}
if (item.has("jwtId") && !item.get("jwtId").isJsonNull()) {
return item.get("jwtId").getAsString();
}
return null;
}
private List<NotificationContent> parseApiResponse(String responseBody, FetchContext context) {
List<NotificationContent> contents = new ArrayList<>();
try {
JsonObject root = JsonParser.parseString(responseBody).getAsJsonObject();
JsonArray dataArray = root.has("data") ? root.getAsJsonArray("data") : null;
if (dataArray == null || dataArray.size() == 0) {
return contents;
}
JsonObject firstItem = dataArray.get(0).getAsJsonObject();
String firstTitle = extractProjectDisplayTitle(firstItem);
String jwtId = extractJwtIdFromItem(firstItem);
NotificationContent content = new NotificationContent();
content.setId("endorser_" + (jwtId != null ? jwtId : ("batch_" + System.currentTimeMillis())));
int n = dataArray.size();
String quotedFirst = "\u201C" + firstTitle + "\u201D";
if (n == 1) {
content.setTitle("Starred Project Update");
content.setBody(quotedFirst + " has been updated.");
} else {
content.setTitle("Starred Project Updates");
int more = n - 1;
content.setBody(quotedFirst + " + " + more + " more have been updated.");
}
content.setScheduledTime(
context.scheduledTime != null
? context.scheduledTime
: (System.currentTimeMillis() + 3600000));
content.setPriority("default");
content.setSound(true);
contents.add(content);
} catch (Exception e) {
Log.e(TAG, "Error parsing API response", e);
}
return contents;
}
}
@@ -0,0 +1,32 @@
package app.timesafari.notifications;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "NotificationInspector")
public class NotificationInspectorPlugin extends Plugin {
@PluginMethod
public void getPendingNotifications(PluginCall call) {
call.unimplemented(
"Pending notification inspection is currently implemented on iOS only");
}
/**
* Whether this build carries a Firebase config, i.e. was built with
* -PfirebaseEnabled. Without it, PushNotifications.register() throws on the
* Capacitor plugin thread and kills the app, so JS must check this first.
* The google-services Gradle plugin generates the google_app_id resource,
* which is what Firebase's own auto-initialization looks for.
*/
@PluginMethod
public void isFirebaseConfigured(PluginCall call) {
int resId = getContext().getResources().getIdentifier(
"google_app_id", "string", getContext().getPackageName());
JSObject ret = new JSObject();
ret.put("configured", resId != 0);
call.resolve(ret);
}
}
+6
View File
@@ -20,6 +20,12 @@ project(':capacitor-clipboard').projectDir = new File('../node_modules/@capacito
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
include ':capacitor-preferences'
project(':capacitor-preferences').projectDir = new File('../node_modules/@capacitor/preferences/android')
include ':capacitor-push-notifications'
project(':capacitor-push-notifications').projectDir = new File('../node_modules/@capacitor/push-notifications/android')
include ':capacitor-share'
project(':capacitor-share').projectDir = new File('../node_modules/@capacitor/share/android')
+1 -1
View File
@@ -1,5 +1,5 @@
ext {
minSdkVersion = 23
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.8.0'
+3
View File
@@ -18,6 +18,9 @@ const config: CapacitorConfig = {
]
}
},
PushNotifications: {
presentationOptions: ['badge', 'sound', 'alert']
},
SplashScreen: {
launchShowDuration: 3000,
launchAutoHide: true,
+2 -4
View File
@@ -61,16 +61,14 @@ The app depends on:
"@timesafari/daily-notification-plugin": "git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git#master"
```
If the fixes were only made in a **different** clone (e.g. `daily-notification-plugin_test`) and never pushed to that gitea `master`, then:
If the fixes were only made in a **local clone** and never pushed to **gitea** `master`, then:
- `npm install` / `npm update` in the app would not pull the fixes.
- The app’s `node_modules` would only have the fixes if they were copied/linked from the fixed repo.
**Do this:**
- If the fixes live in another clone: either **push** the fixed plugin to gitea `master` and run `npm update @timesafari/daily-notification-plugin` (then `npx cap sync android`, then clean build), **or** point the app at the fixed plugin locally, e.g. in **app** `package.json`:
- `"@timesafari/daily-notification-plugin": "file:../daily-notification-plugin"`
(adjust path to your fixed plugin repo), then `npm install`, `npx cap sync android`, clean build and reinstall.
- **Push** the fixed plugin to the official gitea repo (`trent_larson/daily-notification-plugin`), then in this app run `npm update @timesafari/daily-notification-plugin` (or set `package.json` to the branch/tag/commit you need), `npm install`, `npx cap sync android`, clean build and reinstall. The app should always depend on the published git remote, not a local `file:` path.
### 3. Fallback text from native fetcher (Bug 2 only)
+40
View File
@@ -125,6 +125,35 @@ view: "details"
All deep links follow the format: `timesafari://<route>/<param>?<query>`
### App Routes
These take no parameters.
- `timesafari://` — no route at all opens the app at the home feed.
- `timesafari://account`
- `timesafari://discover`
- Query params, all optional:
- `searchText`: prefills the search box
- `searchPeople`: any value switches to the people tab
- `hideOnboarding`: "true" suppresses the onboarding prompt
- `timesafari://invite-one`
- `timesafari://new-activity`
- `timesafari://onboard-meeting-list`
- `timesafari://projects`
- `timesafari://recent-offers-to-user`
- `timesafari://recent-offers-to-user-projects`
- `timesafari://search-area`
- `timesafari://share-my-contact-info`
- `timesafari://statistics`
### Help Routes
- `timesafari://help`
- `timesafari://help-notifications`
- `timesafari://help-notification-types`
- `timesafari://help-onboarding`
- `timesafari://help-terms`
### Claim Routes
- `timesafari://claim/:id`
@@ -143,6 +172,17 @@ All deep links follow the format: `timesafari://<route>/<param>?<query>`
- `timesafari://contact-import/:jwt`
- Query params:
- `contacts`: JSON array of contacts
- `timesafari://contact-qr` and `timesafari://contact-qr-scan-full`
Both open the page that displays your contact QR code, scans someone else's,
and prompts you to set your name if your identity does not carry one. The
destination view is chosen by platform, not by which of the two paths was
used: a full-screen camera view where a native scanner is available, an
ordinary page where the in-page web reader is used.
Prefer `contact-qr` when publishing a link. The same path is appended to the
web address by `/deep-link/<path>`, and `/contact-qr` is the web route that
serves this page in a browser.
### Project Routes
+129
View File
@@ -0,0 +1,129 @@
# Android plugin: New Activity notification when API has no activities
**Audience:** Maintainers of `@timesafari/daily-notification-plugin` (Android / Kotlin).
**Host app:** TimeSafari (`crowd-funder-for-time-pwa`) — this file lives in the **app** repo only as a handoff; apply changes in the **plugin** repo.
**Problem (product):** “New Activity” should notify only when the API reports new/updated activity. The host’s native fetcher (`TimeSafariNativeFetcher`) returns an **empty** `List<NotificationContent>` when the API’s `data` array is empty. Users still see a **daily** local notification.
**Version note:** This diagnosis was first written against older plugin builds (e.g. **2.1.x / 2.2.x**). After upgrading the host to **`@timesafari/daily-notification-plugin` 3.0.0**, the Android files below were **re-read** from `node_modules`. The relevant logic is **unchanged** in 3.0.0: the same two mechanisms still explain unwanted daily notifications when the API returns no rows. If you maintain the plugin, re-verify after each major release.
**Root cause (Android, confirmed in plugin v3.0.0 sources under `node_modules`):** Two mechanisms interact:
1. **`FetchWorker.kt` — empty native fetch is converted to synthetic JSON instead of “skip”**
When the dual prefetch runs with the native fetcher and the list is empty, `notificationContentsToDualPayloadBytes` **replaces** the empty list with a JSON payload `"No updates"` / `"No new content"`, and the work unit still completes successfully. The dual path then **always** arms the chained notify alarm when `isDual && nextNotifyAt > 0L` — so a notification is still scheduled for the notify window.
Reference (plugin):
```kotlin
// FetchWorker.kt — notificationContentsToDualPayloadBytes (~371–374 in v3.0.0)
if (contents.isEmpty()) {
return """{"title":"No updates","body":"No new content"}""".toByteArray(Charsets.UTF_8)
}
```
```kotlin
// FetchWorker.kt — doWork(), tail of success path (~306–309 in v3.0.0)
if (isDual && nextNotifyAt > 0L) {
DualScheduleNotifyScheduler.scheduleChainedNotifyAlarm(applicationContext, nextNotifyAt)
DualScheduleFetchRecovery.enqueueFromPersistedConfig(applicationContext)
}
```
2. **`DualScheduleHelper.kt` — `fallbackBehavior: "show_default"` uses `userNotification` defaults**
At display time, if there is **no** fresh dual-scope cache within `relationship.contentTimeout`, the helper falls back to the **persisted** `userNotification.title` / `userNotification.body` when `fallbackBehavior` is `"show_default"`. The host app sets those defaults to copy such as “New Activity” / “Check your starred projects…”, so the user sees that **even when the API had nothing**, if the cache path doesn’t supply something else.
Reference (plugin):
```kotlin
// DualScheduleHelper.kt — resolveDualContentBlocking (simplified; ~31–57 in v3.0.0)
val fallbackBehavior = relationship?.optString("fallbackBehavior", "show_default") ?: "show_default"
val defaultTitle = userNotification.optString("title", "Daily Notification")
val defaultBody = userNotification.optString("body", "Your daily update is ready")
// ...
} else {
if (fallbackBehavior != "show_default") return null
Pair(defaultTitle, defaultBody)
}
```
**TypeScript contract (plugin `src/definitions.ts` in v3.0.0 — `DualScheduleConfiguration.relationship`):**
```ts
relationship?: {
autoLink: boolean;
contentTimeout: number;
fallbackBehavior: 'skip' | 'show_default' | 'retry';
};
```
`skip` is only partially useful on Android **with the current fetch implementation**: it avoids the **default title/body** branch in `DualScheduleHelper` when cache is missing/stale, but it does **not** by itself stop a notification if the fetch path still materializes content (including the synthetic `"No updates"` payload) or if chained notify is already armed.
**3.0.0 vs 2.2.x:** Plugin **3.0.0** advertises broader features (e.g. TTL-at-fire, observability). Those do **not** replace the dual-fetch pipeline inspected here: `FetchWorker` still maps an empty native list to JSON and still schedules the chained notify on success; `DualScheduleHelper` still applies `show_default` vs defaults when cache is absent or outside `contentTimeout`. Revisit this doc if a future release changes `notificationContentsToDualPayloadBytes` or the dual notify gate.
---
## Recommended plugin changes (Android)
### 1) Treat empty native fetch as “no notification” (primary)
**File:** `android/src/main/java/org/timesafari/dailynotification/FetchWorker.kt`
**Issue:** `notificationContentsToDualPayloadBytes` must not turn an empty list into a non-empty payload if the product contract is “no rows in API → no notification.”
**Direction:**
- **Before:** Empty list → JSON `No updates` / `No new content` → success → chained notify scheduled.
- **After (one of):**
- **A)** Return a dedicated sentinel payload (e.g. `{ "skipNotification": true }`) and teach **`NotifyReceiver` / worker** that resolves dual content to **not post** when that sentinel is present; **or**
- **B)** On empty list, **do not** call `DualScheduleNotifyScheduler.scheduleChainedNotifyAlarm` for this cycle (and optionally persist “last fetch had no content” for the helper); **or**
- **C)** Store an empty/marker cache row that `DualScheduleHelper.resolveDualContentBlocking` interprets as “return null” (no notification).
Pick one strategy and keep behavior consistent with `relationship.fallbackBehavior`:
- If `fallbackBehavior == "skip"`: skip notification when fetch returns empty or when sentinel indicates skip.
- If `fallbackBehavior == "show_default"`: keep current default-title/body behavior **only** when the product intends it (may be wrong for TimeSafari).
### 2) Honor `relationship.fallbackBehavior` end-to-end
**Files:** `FetchWorker.kt`, `DualScheduleHelper.kt`, any worker/receiver that posts the dual notification.
**Issue:** `DualScheduleHelper` reads `fallbackBehavior`, but the fetch path does not use the same semantics for “empty API result.”
**Direction:** When persisting dual config, pass `fallbackBehavior` into the fetch success path so that **empty fetch + `skip`** never schedules or displays a notification.
### 3) Tests
- Dual fetch + native fetcher returns **empty list** → **no** notification posted (or no chained alarm), matching host expectation.
- Non-empty list → notification with fetcher-provided title/body.
- Optional: `fallbackBehavior` matrix (`skip` / `show_default`) with stale cache vs fresh cache.
---
## Host app follow-up (separate PR in `crowd-funder-for-time-pwa`)
After the plugin implements empty-fetch semantics, set in `buildDualScheduleConfig` (`src/services/notifications/dualScheduleConfig.ts`):
```ts
relationship: {
autoLink: true,
contentTimeout: 5 * 60 * 1000,
fallbackBehavior: "skip", // was "show_default"
},
```
Only do this once Android behavior matches the contract (otherwise users may get **no** notification even when you would want defaults on network failure — product decision).
---
## References in this repo (context only)
- Host native fetcher returns no content when API `data` is empty: `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` (`parseApiResponse`).
- Host dual config today uses `fallbackBehavior: "show_default"`: `src/services/notifications/dualScheduleConfig.ts`.
---
## Plugin version verification
- **Last verified against:** `@timesafari/daily-notification-plugin` **3.0.0** (`node_modules/.../package.json`).
- **Prior builds:** Behavior matched the earlier **2.1.x** analysis; **2.2.0 → 3.0.0** did not remove the empty-list → synthetic JSON mapping or the chained-notify success path in the inspected sources.
- Re-verify line numbers after rebasing or patching the plugin repo.
+16
View File
@@ -42,6 +42,16 @@ This means a single Play Store AAB (`bundleRelease -PfirebaseEnabled`) covers bo
**F-Droid** is stricter: their build policy rejects any APK with GMS dependencies at the binary level, even with graceful degradation. F-Droid submission would require a separate `assembleRelease` build (no flag) and a dedicated F-Droid listing.
## Push registration in builds without Firebase
A build without `-PfirebaseEnabled` contains the `@capacitor/push-notifications` plugin, but no Firebase config. In that build, `PushNotifications.register()` throws `Default FirebaseApp is not initialized` on the Capacitor plugin thread, which kills the app; a JS `try/catch` cannot intercept it.
The JS therefore asks native code first. `NotificationInspector.isFirebaseConfigured()` (`android/app/src/main/java/app/timesafari/notifications/NotificationInspectorPlugin.java`) reports whether the `google_app_id` string resource exists; the google-services Gradle plugin generates that resource only when Firebase is enabled, and it is the same signal Firebase's auto-initialization uses. `firebaseMessagingClient.ts` skips `register()` on Android when it is absent (or when the check fails), logging `No Firebase config in this Android build; skipping push registration`. Listener setup and the notification permission request run either way, since local daily notifications need that permission.
`NotificationInspector` must be listed in `scripts/restore-local-plugins.js`: `MainActivity` registers plugins after the Capacitor bridge is built, so a plugin missing from `capacitor.plugins.json` reports "not implemented on android" and the check falls back to skipping push.
Any code that calls `PushNotifications.register()` or other `FirebaseMessaging` APIs on Android must go through the same check.
## The `google-services.json` file
- Gitignored (`android/.gitignore` line 80) — never commit it
@@ -64,3 +74,9 @@ This is an accepted trade-off. Removing it would require either forking the plug
Jose Olarte III's `notify-api` branch placed a production `google-services.json` in `android/` to test Firebase Cloud Messaging. The branch was never merged to `master`, but because the file is gitignored it persisted on disk after switching branches. At the time, the Gradle conditional activated Firebase based on file presence alone (no opt-in flag), so all subsequent local builds embedded Firebase and required Google Play Services. This silently broke APK/Aurora/Zapstore distribution.
**Fix applied:** deleted `google-services.json` from disk, changed the Gradle conditional to require `-PfirebaseEnabled`, and documented the rule in `AGENTS.md`.
## Incident: September 2026
After the June fix, local builds without `-PfirebaseEnabled` (including every `scripts/build-android.sh` build and the FOSS APKs from v1.4.4 on) crashed at launch as soon as notification permission was granted, because startup code called `PushNotifications.register()` unconditionally. Found while running `npm run build:android:prod:run` on an emulator.
**Fix applied:** the `isFirebaseConfigured()` gate described in "Push registration in builds without Firebase", plus adding `NotificationInspector` to `scripts/restore-local-plugins.js` so the check is reachable on Android.
+17 -6
View File
@@ -128,18 +128,29 @@ Your Android device and computer **must be on the same Wi-Fi network** for the d
### Step 3: Configure API Endpoints
Create or edit `.env.development` with your computer's IP:
Pass your computer's IP to the build with `--api-ip`. The build script points
the claim and partner APIs at that address:
```bash
# .env.development - for physical device testing
VITE_DEFAULT_ENDORSER_API_SERVER=http://192.168.1.100:3000
VITE_DEFAULT_PARTNER_API_SERVER=http://192.168.1.100:3000
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_APP_SERVER=http://192.168.1.100:8080
npm run build:android:dev -- --api-ip 192.168.1.100
```
**Important**: Replace `192.168.1.100` with your actual IP address.
Without `--api-ip`, a development build uses `10.0.2.2:3000`, which reaches the
host machine from an emulator but not from a physical device.
The build script applies `--api-ip` after loading `.env.development`, so the
flag wins for the claim and partner APIs. Other addresses come from that file,
which development web builds share:
```bash
# .env.development
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_APP_SERVER=http://192.168.1.100:8080
```
### Step 4: Start Your Local Server
If testing against local API servers, ensure they're accessible from the network:
+155
View File
@@ -0,0 +1,155 @@
# Background New Activity JWT pool
How the app credentials native background prefetch for New Activity.
## 1. What the pool is for
Background prefetch runs in WorkManager on Android and a background task on iOS,
with no JavaScript executing. It calls Endorser directly and needs a Bearer JWT
that was minted while the app was awake, possibly days earlier.
The app mints a pool of `BACKGROUND_JWT_POOL_SIZE` JWTs and hands them to the
plugin through `configureNativeFetcher`. Each covers one UTC day, and the native
fetcher picks the one matching the day it runs.
Source: `src/libs/crypto/backgroundJwtPool.ts`,
`src/services/notifications/nativeFetcherConfig.ts`,
`src/constants/backgroundJwt.ts`.
## 2. Token shape
Each token in the pool carries:
| Claim | Value |
|-------|-------|
| `iss` | the minting DID |
| `iat` | mint time |
| `nbf` | its day's opening midnight, minus `BACKGROUND_JWT_WINDOW_SLACK_SECONDS` |
| `exp` | its day's closing midnight, plus `BACKGROUND_JWT_WINDOW_SLACK_SECONDS` |
The slack widens the window at both ends for clock skew between the device and
Endorser. Widening is safe; narrowing can leave a prefetch inside the day with
no usable token.
Two properties follow from the day windows, and both are load-bearing:
- **Each token grants one day.** A token read from a log line or a captured
header buys one day of Endorser access rather than the whole grant.
- **The tokens are distinct.** ES256K signing is deterministic, so JWTs built
from identical payloads are byte-identical. Differing windows are what keep
the pool from collapsing into one string repeated `POOL_SIZE` times, which
would defeat any duplicate-token rule the server applies.
## 3. Slot ordering
Both native fetchers select with `pool[epochDay % pool.size()]` and hold no
record of when the pool was minted. The minter therefore files the token
covering a given UTC day at index `epochDay % BACKGROUND_JWT_POOL_SIZE`.
Any `POOL_SIZE` consecutive days hit every index exactly once, so the array is
dense whatever day minting starts on.
This is a contract across three languages. Changing the index arithmetic on one
side without the others produces tokens presented outside their windows, which
Endorser rejects with no local error. `src/test/backgroundJwtPool.test.ts`
asserts the invariant by replaying the native selector against the minted pool.
Implementations: `TimeSafariNativeFetcher.selectBearerTokenForRequest` in
`android/app/src/main/java/app/timesafari/` and `ios/App/App/`.
## 4. Identities that can mint
Seed-phrase (`did:ethr`) identities only.
Passkey (`did:peer`) identities raise
`BackgroundJwtUnsupportedIdentityError`. Each of their signatures is a WebAuthn
assertion, so minting a pool would raise one biometric prompt per token, and
`createJwtNavigator` overrides the day window with a one-minute `exp` — the
tokens would expire long before the prefetch they were minted for.
`configureNativeFetcherIfReady` catches the error and leaves prefetch
unconfigured.
The delegated alertSearch batch rejects the same identities, with the
notify-api answering `DELEGATED_JWT_UNSUPPORTED_IDENTITY`.
## 5. Lifecycle
| Event | Action |
|-------|--------|
| App foreground, startup, notification-time change | `configureNativeFetcherIfReady` mints a pool and configures the fetcher |
| Active identity changes (`$setActiveDid`) | `clearNativeFetcherPool` drops the pool the fetcher holds |
The identity is decrypted once per mint and reused for every signature.
Decrypting per token costs seconds on a phone, and minting runs on every
foreground.
## 6. What the pool bounds
The grant is `BACKGROUND_JWT_POOL_SIZE` days wide and each token inside it is
one day wide.
`clearNativeFetcherPool` is custody, not revocation. Endorser exposes no
revocation mechanism, so a token that left the device before the clear stays
valid until its window closes. What the clear bounds is the ordinary case — an
account switch, a sign-out, a shared or lost handset — where no copy was taken
and the device's own store is the only remaining exposure.
Anti-replay in the strict sense is unavailable on this path. It would require
either a server-side one-time-use store, which Endorser does not offer, or
per-request signing, which would put the private key in native code. Day-scoped
windows narrow the exposure instead of eliminating it.
## 7. Constants
All in `src/constants/backgroundJwt.ts`.
| Constant | Meaning |
|----------|---------|
| `BACKGROUND_JWT_POOL_SIZE` | Consecutive UTC days the pool covers, one token each. The whole forward grant a user authorizes per mint. |
| `BACKGROUND_JWT_WINDOW_SLACK_SECONDS` | Padding on each end of a day window, for clock skew. |
| `BACKGROUND_JWT_SECONDS_PER_DAY` | The day frame each slot is cut from. |
| `BACKGROUND_JWT_EXPIRY_DAYS` / `_SECONDS` | Lifetime for the single-token background path. |
Past the last covered day the pool carries no credential and prefetch stops
until the app opens again.
## 8. A different credential
The notify-api's delegated alertSearch batch
(`src/services/notifications/alertAuthorizationBatch.ts`) is a separate
credential with a separate inventory. It authorizes the notification service to
run a user's daily alertSearch server-side; this pool authorizes the user's own
device to prefetch. They share the day-window shape and nothing else. See
`notification-wakeup-service/README.md`.
## 9. Rejected
- **A unique `jti` per slot, with one shared long `exp`.** A `jti` is an
identifier, not a replay defense: it does nothing unless the server keeps a
seen-set, and Endorser's behavior here was never confirmed. Day windows make
the tokens distinct for the same cost while also bounding each one.
- **One long-lived token instead of a pool.** Fails if Endorser rejects
duplicate JWT strings across days. That policy question is open (§10), so the
design does not depend on the answer.
- **Sizing the pool as `expiryDays + buffer`.** The rationale was headroom for
duplicate-token rules. With one token per day, the pool size is the grant
length in days and needs no separate buffer term.
- **Per-request signing in native code (DPoP-style).** The only true anti-replay
option, rejected to keep one signing implementation in TypeScript rather than
forking crypto into Java and Swift.
- **Routing all New Activity through the notification service and deleting this
path.** Rejected: it would force every user onto server-side delegation, and
the service is single-replica, so the direct device-to-Endorser path has no
equivalent.
## 10. Open questions
- **Endorser duplicate-JWT policy.** Whether Endorser rejects a Bearer JWT
string it has already seen is unconfirmed. The pool is correct either way; the
answer would determine whether a pool is required at all.
- **Maximum `exp` Endorser accepts.** Day-scoped windows are well inside any
plausible limit, so this gates only the single-token path.
- **Plugin behavior on an empty pool.** `clearNativeFetcherPool` passes empty
credentials to `configureNativeFetcher`. A plugin build that rejects them
leaves the previous pool in place; the failure is logged rather than reported
as a successful clear.
@@ -0,0 +1,80 @@
# Consuming app handoff: iOS native fetcher + chained dual (mirror)
**Canonical source:** `daily-notification-plugin` repo, `doc/CONSUMING_APP_HANDOFF_IOS_NATIVE_FETCHER_AND_CHAINED_DUAL.md` (same content as below for offline use).
---
## Implemented in this app
- **`ios/App/App/TimeSafariNativeFetcher.swift`** — Swift `NativeNotificationContentFetcher` mirroring `TimeSafariNativeFetcher.java` (`POST …/plansLastUpdatedBetween`, starred IDs from `daily_notification_timesafari.starredPlanIds`, JWT pool selection, pagination key `daily_notification_timesafari.last_acked_jwt_id`, aggregated copy).
- **`AppDelegate.swift`** — `DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)` at launch **before** any JS `configureNativeFetcher`; foreground handler reads `scheduled_time` as `Int64`, `NSNumber`, or `Int` for `DailyNotificationDelivered`.
## Dependency
- **`@timesafari/daily-notification-plugin`** must be **≥ 3.0.0** (register native fetcher, chained dual, iOS `updateStarredPlans`). Declare it in `package.json` from the official remote (`git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git`, branch or tag as needed), then `npm install` so `package-lock.json` resolves the published tree.
## Bump / sync (after plugin version is resolved)
1. `npm install`
2. `npx cap sync ios && npx cap sync android`
3. `cd ios/App && pod install`
4. Clean build in Xcode / Android Studio
## QA focus
- iOS: Fetcher registered before `configureNativeFetcher`; `updateStarredPlans` not `UNIMPLEMENTED`.
- Both: New Activity fires **after** prefetch for that cycle where the plugin implements chaining.
- Android: Existing `MainActivity.setNativeFetcher` unchanged; regression-test `cancelDualSchedule` vs Daily Reminder.
---
## Original handoff text (from plugin)
This document is for the **host app** repository (e.g. crowd-funder-for-time-pwa) after bumping `@timesafari/daily-notification-plugin` to a version that includes:
- **iOS** `NativeNotificationContentFetcher`–style registration (`DailyNotificationPlugin.registerNativeFetcher`)
- **iOS** `updateStarredPlans` / `getStarredPlans` (parity with Android `daily_notification_timesafari` / `starredPlanIds` semantics)
- **iOS** chained dual flow: user notification is **armed only after** prefetch completes (delay if fetch is late; max slip 15 minutes before fallback copy)
- **Android** chained dual flow: exact **notify** alarm is scheduled **after** dual prefetch completes (no longer scheduled at initial `scheduleDualNotification` before fetch)
Material from `doc/new-activity-notifications-ios-android-parity.md` still applies; the plugin doc adds **app-side** steps not spelled out there.
### 1. iOS — register native fetcher before `configureNativeFetcher`
The plugin **rejects** `configureNativeFetcher` if no fetcher is registered (aligned with Android).
**In `AppDelegate` (or earliest app startup before Capacitor calls into the plugin):**
```swift
import TimesafariDailyNotificationPlugin
DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)
```
Implement **`TimeSafariNativeFetcher`** as a Swift type that:
- Conforms to `NativeNotificationContentFetcher`
- Implements `fetchContent(context: FetchContext) async throws -> [NotificationContent]` with the same **Endorser** behavior as `TimeSafariNativeFetcher.java`
- Implements `configure(apiBaseUrl:activeDid:jwtToken:jwtTokenPool:)` if the fetcher needs credentials pushed from TypeScript
**Starred plan IDs for the fetcher:** Read JSON array string from UserDefaults key **`daily_notification_timesafari.starredPlanIds`** (written by `updateStarredPlans` from JS).
### 2. iOS — `UNUserNotificationCenterDelegate` / rollover
Chained dual notifications set:
- `notification_id` = `org.timesafari.dailynotification.dual`
- `scheduled_time` = `NSNumber` (fire time in ms)
Ensure **`DailyNotificationDelivered`** forwards **`notification_id`** and **`scheduled_time`** from **notification content `userInfo`**.
### 3. Android — no API change for `setNativeFetcher`
Host apps that already call `DailyNotificationPlugin.setNativeFetcher(TimeSafariNativeFetcher(...))` keep that flow.
**Behavior change:** the dual **notify** alarm is scheduled when **dual prefetch work finishes**, not at the initial `scheduleDualNotification` only.
### 4. Assumptions
- Swift host implements `TimeSafariNativeFetcher`; the plugin does **not** embed `plansLastUpdatedBetween` on iOS when a host fetcher is registered (mirrors Android).
- Module import: `TimesafariDailyNotificationPlugin` (Pod `TimesafariDailyNotificationPlugin`).
+1 -2
View File
@@ -6,8 +6,7 @@
2. **Notifications show when the app is in the foreground** (not only background/closed).
3. **Plugin loads at app launch** so recovery runs after reboot without the user opening notification UI.
**Reference:** Test app at
`/Users/aardimus/Sites/trentlarson/daily-notification-plugin_test/daily-notification-plugin/test-apps/daily-notification-test`
**Reference:** In the **daily-notification-plugin** repository, the test app lives at `test-apps/daily-notification-test` (same repo as `https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin`).
---
@@ -0,0 +1,152 @@
# Options: expired JWT during background “New Activity” prefetch (mobile)
**Date:** 2026-03-26 17:29 PST
**Audience:** TimeSafari / crowd-funder team; **Endorser server** maintainers (auth + API policy)
**Context:** Android Capacitor app, `POST /api/v2/report/plansLastUpdatedBetween`, native `TimeSafariNativeFetcher` invoked from WorkManager at **T−5 minutes** before the daily notification.
---
## Problem (short)
New Activity notifications prefetch Endorser data in **background** (no JavaScript, no WebView). The HTTP client uses a **Bearer JWT** supplied earlier via `configureNativeFetcher` / `getHeaders(activeDid)`.
If the **access token’s `exp`** is **before** prefetch time, the API returns **400** with a body like:
```json
{
"error": {
"message": "JWT failed verification: ... JWT has expired: exp: … < now: …",
"code": "JWT_VERIFY_FAILED"
}
}
```
We **cannot** rely on the user opening the app immediately before prefetch (T−5), so **client-only** mitigations (e.g. refresh JWT on app resume) **reduce** failures but **do not guarantee** a valid token for headless background work.
---
## Why this is different from normal in-app API calls
| In-app | Background prefetch |
|--------|----------------------|
| `getHeaders()` runs in JS when needed; user often recently active | WorkManager runs **without** Capacitor / passkey / session refresh |
| Short TTL tokens are refreshed as the user uses the app | Same token may sit in native memory until **T−5** (or longer) |
So **server-side** and **architecture** choices matter for this feature.
---
## Options (for decision)
### 1. Increase access token TTL (Endorser / IdP)
**Idea:** Issue access JWTs with a longer `exp` so that **configure time → prefetch time** (often **5+ minutes**, sometimes **24h+** if the user rarely opens the app) usually still falls inside validity.
| Pros | Cons |
|------|------|
| Simple to explain; one policy change | Longer-lived bearer tokens increase risk if exfiltrated; mitigate with scope, rotation, monitoring |
| No client protocol change | May not fit strict security posture without a dedicated scope |
**Endorser owner:** token lifetime, scopes, and whether a **dedicated** lifetime or scope for “mobile background read” is acceptable.
---
### 2. Scoped long-lived token for report reads only (Endorser)
**Idea:** Mint a **separate** access token (or sub-scope) valid only for **read-only report** endpoints (`plansLastUpdatedBetween`, etc.), with a **longer TTL** than the interactive session token.
| Pros | Cons |
|------|------|
| Limits blast radius vs “longer JWT for everything” | Requires auth model + issuance path; client must store/use this token only for prefetch |
**Endorser owner:** feasibility of **narrow scope** + **longer TTL** for this use case.
---
### 3. Refresh token or device grant (Endorser + mobile native)
**Idea:** Client stores a **refresh token** (or OAuth **device** grant) in **Android Keystore / iOS Keychain**. Before `plansLastUpdatedBetween`, **native** code (no JS) exchanges it for a **new access token**.
| Pros | Cons |
|------|------|
| Standard pattern; short TTL for access tokens remains | Endorser must support refresh (or equivalent); secure storage + rotation; **both** client and server work |
| Works when app is backgrounded for days | Implementation cost on mobile |
**Endorser owner:** refresh endpoint, token rotation, revocation.
**Mobile owner:** native fetch path, secure storage, failure handling.
---
### 4. Backend proxy / BFF (TimeSafari backend + Endorser)
**Idea:** Phone calls **your** backend with a **device session** (or FCM registration id); **server** uses **server-to-server** credentials or a **service account** to call Endorser. The device **never** sends an Endorser JWT for this path.
| Pros | Cons |
|------|------|
| No Endorser JWT lifetime problem on device | New service, auth, rate limits, privacy review |
| Central place for logging, abuse control | Operational cost |
**Endorser owner:** partner / S2S auth model for the BFF.
**Product team:** hosting and trust boundaries.
---
### 5. “Cron” or periodic jobs on the device to refresh JWT (JS)
**Idea:** Use something like a **cron** schedule to refresh tokens.
**Reality:** Scheduled **native** jobs can run, but **Capacitor / `getHeaders()` / passkey** do **not** run reliably in that context without waking the **WebView**. So **“cron”** only helps if refresh is **fully native** (see option 3) or you accept **unreliable** wake + JS.
**Not recommended** as the primary fix unless paired with **native refresh** or **server** changes.
---
### 6. Product / UX constraints (no server change)
**Idea:** Accept that **headless** API calls may fail if the session is stale; show **fallback** copy; or require “open app once per day” for best results.
| Pros | Cons |
|------|------|
| No Endorser change | Does not meet “API-driven notification” expectation for inactive users |
---
## Client-side mitigations already in play (not sufficient alone)
- **`configureNativeFetcherIfReady()`** after startup and when **Account** / identity is ready.
- **`appStateChange` → `isActive`:** refresh native fetcher when the app returns to foreground (reduces staleness when the user **does** open the app).
- **Error logging** of 400 bodies for diagnosis.
These **do not** guarantee a fresh JWT at **T−5** if the user never opens the app before prefetch.
---
## Suggested decision order
1. **Align on security posture:** Is a **longer TTL** or **scoped long-lived read token** acceptable for Endorser?
2. If not, is **refresh token in native** (option 3) or **BFF** (option 4) on the roadmap?
3. **Parallel:** UX fallback when API is unavailable (option 6) so the app never silently looks “broken.”
---
## References (this repo)
| Topic | Location |
|--------|----------|
| Native fetcher + JWT from `getHeaders` | `src/services/notifications/nativeFetcherConfig.ts` |
| Android POST + errors | `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` |
| Web `plansLastUpdatedBetween` + `afterId` | `src/libs/endorserServer.ts` (`getStarredProjectsWithChanges`) |
| New Activity / dual schedule | `doc/notification-from-api-call.md`, `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` |
---
## Open questions for Endorser (server developer)
1. What is the **current access token TTL** and can it be **increased** for mobile clients, or **per-scope**?
2. Is **refresh token** (or similar) available for **non-interactive** renewal?
3. Would a **read-only** scope for `plansLastUpdatedBetween` with a **longer** lifetime be acceptable?
4. Is there an existing **server-to-server** or **partner** path that a **BFF** could use instead of user JWT on device?
---
*This document is for internal planning and decision; update it when the team chooses an approach.*
+401
View File
@@ -0,0 +1,401 @@
# Android Local Notification Testing — Planning Analysis
**Created:** 2026-06-02
**Source document:** [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md)
**Status:** Planning snapshot from 2026-06-02. Several iOS-guide assumptions (app **Refresh Notifications**, Simulate WAKEUP, `applyNotificationRefreshPayload`, WAKEUP_PING → `/notifications/refresh` → `api_*`) are **retired**. For current Android procedure see [local-android-testing-ngrok.md](./local-android-testing-ngrok.md). Do not treat the reuse tables below as the live app path.
**Purpose:** Plan a future **Android** counterpart guide by mapping what can be reused from the iOS ngrok workflow and what must be written for Android-specific push, permissions, and OS behavior.
---
## Executive summary
The iOS guide’s **backend + ngrok + in-app debug panel** path is platform-agnostic. Most of sections **1–3**, **6**, **9** (with log tooling swapped), **10** (with `platform: "android"`), **12**, and parts of **11** can be copied or lightly edited.
Everything involving **APNs, Xcode, Apple Developer, iOS capabilities, and iOS background/silent-push caveats** must be replaced. Android adds **direct FCM delivery** (no APNs hop), **`google-services.json`**, **runtime notification permissions (API 33+)**, **Doze / battery optimization / OEM restrictions**, and different **force-stop / background** semantics.
Existing related docs to cross-link (not duplicate):
- [android-physical-device-guide.md](./android-physical-device-guide.md) — USB, `adb`, build/run commands
- [notification-system-overview.md](./notification-system-overview.md)
- [notification-from-api-call.md](./notification-from-api-call.md)
- [notification-permissions-and-rollovers.md](./notification-permissions-and-rollovers.md)
---
## iOS guide structure (reference map)
| § | iOS doc heading | Reuse for Android |
|---|-----------------|-------------------|
| Intro | Architecture overview | **Adapt** — swap APNs leg for FCM→device |
| — | Prerequisites | **Partial** — drop Xcode/APNs; add Android SDK/device |
| 1 | Install and configure ngrok | **Reuse unchanged** |
| 2 | Start the backend locally | **Reuse unchanged** |
| 3 | Obtain and use ngrok HTTPS URL | **Reuse** — wording: “device” not “iPhone” |
| 4 | Generate and open iOS workspace | **Rewrite** — Android Studio / Capacitor sync |
| 5 | Firebase + APNs setup | **Rewrite** — Firebase Android only; no APNs |
| 6 | Notification Debug Panel override | **Reuse unchanged** |
| 7 | Firebase and Xcode checklist | **Rewrite** — Android manifest / Gradle checklist |
| 8 | iOS-specific testing notes | **Rewrite** — Android delivery caveats |
| 9 | Recommended debug workflow | **Reuse** — replace Xcode console with logcat |
| 10 | Sample curl commands | **Reuse** — change `platform` to `android` |
| 11 | Troubleshooting | **Partial** — keep ngrok/API rows; replace push rows |
| 12 | Key source files | **Reuse unchanged** |
| 13 | Related docs | **Extend** — link Android build/device guides |
---
## Sections reusable unchanged (or near-unchanged)
These blocks can be carried into `doc/local-android-testing-ngrok.md` (proposed name) with at most global find-replace (“iPhone” → “Android device”, “Mac” tunnel audience unchanged).
### notification-wakeup-service startup (iOS §1 Terminal A, §2)
- Clone **notification-wakeup-service**, `npm install`, `.env` from `.env.example`
- `export PORT=3000` (or port from that repo’s README)
- `npm run dev`
- Local verify: `curl -sS http://localhost:3000/health`
- Firebase **Admin** service account for the backend (`GOOGLE_APPLICATION_CREDENTIALS`) — same project can serve iOS and Android apps
### ngrok setup (iOS §1)
- `brew install ngrok/ngrok/ngrok` (or download)
- `ngrok http 3000` in a second terminal
- Use **HTTPS** forwarding URL; free tier URL rotation note
- ngrok inspect UI at `http://127.0.0.1:4040`
### ngrok account creation (iOS §1 “Account and auth token”)
- Sign up at dashboard.ngrok.com
- `ngrok config add-authtoken YOUR_AUTHTOKEN_HERE`
### Obtaining HTTPS URL (iOS §3)
- Copy `https://….ngrok-free.app` from Forwarding line
- No trailing slash in debug panel
- Mac-side tunnel test: `export NGROK_URL=…` and `curl "$NGROK_URL/health"`
### Backend override configuration (iOS §6)
- Non-production build required for Notification Debug Panel
- Account → **Show All General Advanced Functions** → `/dev/notifications`
- **Notification Backend URL**, **Save Backend URL**
- `localStorage`: `notificationDebug.backendBaseUrl`, `notificationDebug.testMode`, `notificationDebug.bypassAuth`
- Optional programmatic override via `@/services/notifications` (`setBackendBaseUrl`, `setTestMode`, `setBypassAuth`, `getNotificationApiBaseUrl`)
### Debug panel usage (iOS §6 table, §8 “Two Simulate WAKEUP_PING buttons”)
| Control | Android relevance |
|---------|-------------------|
| Notification Backend URL | Same |
| Test Mode | Same (`testMode` in JSON body) |
| Skip JWT Authentication | Same — explicit opt-in for unauthenticated local backends (default off) |
| Register Token Now | Same (`POST /notifications/register`) |
| Refresh Notifications | Same |
| Simulate WAKEUP_PING (backend) | Same — isolates ngrok + refresh without FCM |
| Wakeup Ping Simulator | Same — exercises `handleCapacitorPushNotificationReceived` path |
| Event Log `[Notifications]` | Same |
| Pending Notification Inspector | Same concept; confirm Android plugin inspector behavior in **daily-notification-plugin** |
### testMode usage (iOS §6, §10)
- Default-on when unset in storage (`NotificationDebugConfig.ts`)
- Sent on register and refresh payloads
- Backend/debug endpoints accept `testMode: true` for dev traffic
### Refresh endpoint testing (iOS §9 steps 5, §11 “Refresh endpoint unreachable”)
- Panel **Refresh Notifications** → expect Event Log + ngrok `POST /notifications/refresh`
- **Simulate WAKEUP_PING** (backend button) for API-only path
- Troubleshooting table for network error, 404, wrong port, stale URL
### curl examples (iOS §10)
Reuse structure; **only payload deltas** for Android doc:
```bash
export BASE="https://abc123.ngrok-free.app"
```
- `$BASE/health` — unchanged
- `$BASE/notifications/register` — set `"platform": "android"`
- `$BASE/notifications/refresh` — set `"platform": "android"`
- `$BASE/debug/send-wakeup` — unchanged shape; confirm deviceId/token contract in **notification-wakeup-service** README
App still uses `Capacitor.getPlatform()` for `platform` in `NotificationService.ts` (`ios` | `android`).
### Shared architecture concepts (intro + silent wake sequence)
Reusable narrative (edit diagram only):
1. FCM **data** message with `data.type = "WAKEUP_PING"`
2. Capacitor `pushNotificationReceived` → `handleCapacitorPushNotificationReceived()`
3. `POST {backend}/notifications/refresh` with `testMode`
4. `nextNotifications` → `applyNotificationRefreshPayload()` → **daily-notification-plugin** clear + schedule
Repos table (notification-wakeup-service, crowd-funder-for-time-pwa, daily-notification-plugin) — unchanged.
### Key source files (iOS §12)
Same files apply on Android Capacitor builds:
- `NotificationDebugConfig.ts`, `NotificationDebugEvents.ts`, `notificationLog.ts`
- `NotificationService.ts`, `NativeNotificationService.ts`
- `firebaseMessagingClient.ts`, `NotificationDebugPanel.vue`, `main.capacitor.ts`
### Recommended debug workflow (iOS §9) — reuse with tooling swap
Steps 1–5, 8–9 unchanged. Replace step 7:
- **iOS:** Xcode console → `[Notifications] pushNotificationReceived type=WAKEUP_PING`
- **Android:** `adb logcat` filtered on app tag / `[Notifications]` (document exact filter in Android guide)
---
## iOS-specific sections — must rewrite for Android
### Architecture diagram (intro)
**iOS today:** Mac → ngrok → app; FCM → **APNs** → iPhone.
**Android doc:** FCM → **device directly** (no APNs). Update ASCII diagram and caption (“silent push” on Android is still FCM data; delivery rules differ).
### Prerequisites (intro list)
| iOS prerequisite | Android replacement |
|------------------|---------------------|
| Mac with **Xcode** | **Android Studio**, JDK 17+, `ANDROID_HOME`, `adb` — see [android-physical-device-guide.md](./android-physical-device-guide.md) |
| Physical **iPhone** | Physical **Android** device (emulator possible for some steps but **not** representative for Doze/OEM/battery) |
| Firebase with **APNs** for bundle ID | Firebase with **Android app** (`app.timesafari` package name) |
| Non-production build | Same — e.g. `build:android:dev` / `build:android:test` |
Remove: “simulator is not sufficient for reliable silent push / **APNs**”.
Add: emulator vs physical device guidance for FCM and background limits.
### §4 — Generate and open the iOS workspace
**Replace entirely** with Android equivalent:
- `npm install`
- `npm run build:android:dev` or `build:android:test` (non-production for debug panel)
- `npx cap sync android` if needed
- Open `android/` in Android Studio
- Run on physical device (USB debugging)
- `VITE_FIREBASE_*` in Capacitor web build
- `initializeNativePushAndFirebaseMessaging()` in `main.capacitor.ts` — same entry point
Do **not** reference `.xcworkspace`, signing in Xcode, or `build:ios:*` except as cross-link to iOS doc.
### §5 — Firebase + APNs setup (first-time setup)
**Keep (Android-relevant portions only):**
- Firebase account / Spark plan sufficient for FCM
- Create Firebase project
- **Register Android app** in Firebase (package name `app.timesafari` from `capacitor.config.ts`)
- Download **`google-services.json`** → `android/app/` (project may gitignore this file — document secure handling)
- Firebase Admin service account for **notification-wakeup-service** — same as iOS §5 tail
**Remove entirely:**
- Register **iOS** app in Firebase (or move to “shared project” sidebar: one Firebase project, two apps)
- **GoogleService-Info.plist** / Xcode drag-and-drop
- **Create APNs Authentication Key** (.p8)
- **Upload APNs key to Firebase**
- **Enable iOS capabilities** (Push Notifications, Background Modes → Remote notifications)
**Add in Android guide (see next major section):**
- Gradle plugin / `google-services` classpath if not already in repo
- `POST_NOTIFICATIONS` permission (API 33+)
- Default notification channel / Capacitor Push Notifications Android setup
- SHA-1/SHA-256 only if using Firebase features that require it (note whether wakeup testing needs Play App Signing keys)
### §5 verify checklist — iOS-only bullets
Replace:
- “Xcode without Firebase/plist errors” → Android Studio build; `google-services.json` present
- “iOS push permission prompt” → Android 13+ notification permission + older grant model
- “content-available style payload” → Android **high-priority data message** / FCM options as implemented by **notification-wakeup-service** (document actual payload; no APNs `content-available`)
### §7 — Firebase and Xcode checklist (iOS)
**Replace** with Android checklist, e.g.:
| Item | Action |
|------|--------|
| **Application ID** | `app.timesafari` in `capacitor.config.ts`, `android/app/build.gradle`, Firebase Android app |
| **google-services.json** | In `android/app/`; not committed if gitignored — local copy per developer |
| **Gradle** | Google services plugin applied (verify repo’s current `build.gradle`) |
| **Permissions** | `POST_NOTIFICATIONS` (API 33+); manifest entries for FCM |
| **FCM token** | Debug panel **Register Token Now** + ngrok `POST /notifications/register` |
| **No APNs** | N/A on Android |
### §8 — iOS-specific testing notes
**Replace** with Android-specific sections (draft topics below). Do not port:
- APNs silent delivery / Simulator unreliability (iOS framing)
- **Force-quit** via app switcher (iOS-specific policy)
- **Low Power Mode** (iOS) — Android has different battery saver APIs
- **Focus / Do Not Disturb** (iOS naming)
Port with Android wording:
- Two **Simulate WAKEUP_PING** buttons table — unchanged behavior
### §11 — Troubleshooting (partial)
**Reuse as-is:**
- Refresh endpoint unreachable (ngrok, URL, 404, CORS note)
- Stale ngrok URL
- Plugin / JWT errors after refresh
**Rewrite:**
| iOS troubleshooting | Android replacement |
|----------------------|---------------------|
| Push permission + `VITE_FIREBASE_*` + **Xcode** log | Permission (runtime POST_NOTIFICATIONS), logcat, Firebase Android config |
| Silent push not waking — **backgrounded not force-quit**, **APNs key**, wait 30–120s | FCM high-priority data, **force-stop** (`STOP` from settings), **Doze**, battery optimization, OEM autostart, token mismatch |
| Physical device + provisioning profile | USB debugging, correct build variant, Play vs debug signing if relevant |
### §13 — Related docs
Keep iOS-centric links as “see also”; add:
- [android-physical-device-guide.md](./android-physical-device-guide.md)
- `BUILDING.md` — Android build commands (`build:android:*`)
- **daily-notification-plugin** Android docs (exact alarm, pending inspector on Android)
---
## Android-Specific Topics Required
These sections do not exist in the iOS guide (or exist only by analogy) and must be written for the Android notification testing doc.
### Firebase project setup
- Use the **same** Firebase project as iOS when testing the same backend, or document a dedicated `timesafari-dev` project.
- Add an **Android** app with package name **`app.timesafari`**.
- Enable **Cloud Messaging** (default on new projects).
- Download **`google-services.json`** and install under `android/app/`.
- Note: `android/.gitignore` may exclude `google-services.json` — developers copy locally; never commit secrets.
### google-services.json
- Placement: `android/app/google-services.json`
- Sync after add: `npx cap sync android`, rebuild in Android Studio
- Verify build merges Firebase config (no “missing google-services” Gradle errors)
- Relationship to `VITE_FIREBASE_*` for the web layer / Capacitor JS Firebase initialization
### Android notification permissions
- **Android 13+ (API 33):** `POST_NOTIFICATIONS` runtime permission — required for notification **display**; document interaction with **data-only** FCM wake (may still deliver to app code when permission denied — verify against current app behavior and document accurately).
- **Android 12 and below:** install-time grant model; fewer runtime prompts.
- App Settings → Notifications — manual enable path for testers.
- Link [notification-permissions-and-rollovers.md](./notification-permissions-and-rollovers.md) for product-level permission UX.
### FCM token handling
- Token obtained via Capacitor Push Notifications + `firebaseMessagingClient.ts` (same JS path as iOS).
- **Register Token Now** in debug panel → `POST /notifications/register` with `platform: "android"`.
- Token rotation: when to re-register; duplicate skip behavior in panel.
- Ensure **notification-wakeup-service** stores/sends to the token shown in the panel for `/debug/send-wakeup`.
- Optional: `adb` cannot easily read FCM token — panel is source of truth (same as iOS).
### Android background delivery behavior
- FCM **data** messages handled in foreground/background per Capacitor plugin and `NativeNotificationService.ts`.
- No APNs intermediary — document expected latency vs iOS.
- **High-priority** FCM for wakeup testing (align with backend message options).
- App in **background** vs **foreground** vs **killed** — different from iOS “swipe away” story:
- **Force stop** (Settings → Force stop): delivery often blocked until user launches app again (stricter than iOS “backgrounded”).
- **Recent apps swipe**: behavior varies by OEM/Android version — document “test with Home button background, not force stop.”
- `pushNotificationReceived` / listener registration at startup (`main.capacitor.ts`).
### Doze Mode
- Device idle → deferred network and job execution.
- Testing: use `adb shell dumpsys deviceidle` (document safe dev-only commands) or unplugged idle wait.
- Explain why `/debug/send-wakeup` may succeed on server but device wakes late.
- Whitelisting app for tests (developer settings) — use cautiously; note production users won’t do this.
### Battery optimization
- Settings → Apps → TimeSafari → Battery → **Unrestricted** vs **Optimized**.
- Manufacturer “battery saver” modes that restrict background network.
- Recommend **Unrestricted** (or equivalent) for local wakeup validation; warn that production users may remain optimized.
### OEM restrictions (Samsung, Xiaomi, Oppo, etc.)
- **Autostart** / **Background activity** / **Battery** menus on Samsung, Xiaomi (MIUI), Oppo/ColorOS, Huawei, OnePlus, etc.
- Symptom: FCM works on Pixel but not on OEM device until autostart enabled.
- Provide a short “if wake fails on OEM, check…” checklist without exhaustive per-OEM screenshots (link community docs if needed).
- Physical device testing should include at least one **stock-ish** device (Pixel) and one **OEM** device when possible.
---
## Proposed outline for `doc/local-android-testing-ngrok.md`
Suggested section order mirroring iOS doc for easy maintenance:
1. Title, audience, goal (Android physical device + ngrok + wakeup service)
2. Architecture overview (FCM direct to Android)
3. Prerequisites (Android Studio, device, Firebase Android app, non-prod build)
4. ngrok install, account, tunnel (**reuse iOS §1**)
5. Start notification-wakeup-service (**reuse iOS §2**)
6. ngrok HTTPS URL (**reuse iOS §3**)
7. Build and open Android project (**new**, replaces iOS §4)
8. Firebase setup for Android (**new**, replaces iOS §5 — no APNs)
9. Notification Debug Panel (**reuse iOS §6**)
10. Android configuration checklist (**new**, replaces iOS §7)
11. Android-specific testing notes (**new**, replaces iOS §8)
12. Recommended debug workflow (**reuse iOS §9** + logcat)
13. Sample curl commands (**reuse iOS §10** + `platform: "android"`)
14. Troubleshooting (**merge reusable + Android push rows**)
15. Key source files (**reuse iOS §12**)
16. Related docs (**iOS doc + Android device guide + BUILDING**)
---
## Wording and terminology substitutions
When adapting reused sections:
| iOS doc term | Android doc term |
|--------------|------------------|
| iPhone | Android phone / device |
| Xcode console | logcat / Android Studio Logcat |
| `build:ios:dev` / `test` | `build:android:dev` / `test` |
| `GoogleService-Info.plist` | `google-services.json` |
| APNs / silent push | FCM data message / high-priority data |
| Bundle ID | Application ID / package name (`app.timesafari`) |
| Physical iPhone required for APNs | Physical device strongly recommended for Doze/OEM/FCM realism |
| `platform: "ios"` in curl | `platform: "android"` |
---
## Gaps to resolve while writing the Android guide
Research during authoring (code + **notification-wakeup-service** + **daily-notification-plugin**):
1. Exact FCM Android message priority and payload fields for `WAKEUP_PING` (parity with iOS data message).
2. Whether `POST_NOTIFICATIONS` denial blocks data message delivery to JS listeners on API 33+.
3. Gradle/Firebase plugin versions already in `android/` — document exact files to touch.
4. Android **Pending Notification Inspector** parity with iOS panel section.
5. Whether emulator with Google Play image is acceptable for minimal FCM smoke tests vs mandatory physical device for wakeup SLA testing.
---
## Document maintenance
| Document | Role |
|----------|------|
| [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md) | Canonical iOS + ngrok workflow (unchanged by this analysis) |
| **This file** | Reuse vs rewrite matrix and Android topic backlog |
| *Future* `local-android-testing-ngrok.md` | Operator guide for Android testers |
When backend or debug panel behavior changes, update **both** platform guides’ shared sections in lockstep (or extract shared “ngrok + debug panel” snippet later — out of scope unless requested).
+970
View File
@@ -0,0 +1,970 @@
# Local Android Testing with ngrok (notification-wakeup-service)
**Last updated:** 2026-09-24 (retired WAKEUP_PING → refresh → `api_*` consumption)
**Audience:** Developers on **crowd-funder-for-time-pwa**, **daily-notification-plugin**, and **notification-wakeup-service**
**Goal:** Exercise FCM token registration and FCM wakeup **delivery** (`WAKEUP_PING` via `/debug/send-wakeup`) against a Mac-hosted backend reachable from a physical Android device.
> **Retired (do not expect this in the app):** `WAKEUP_PING` → `POST /notifications/refresh` → `applyNotificationRefreshPayload()` → `api_*` local schedules. The app logs ignored push types and does not refresh or schedule from wakeup. `/debug/send-wakeup` remains an FCM diagnostic. Mac `curl` of `/notifications/refresh` only tests the backend. Local schedules come from Static Daily Reminder, New Activity / dual, and the native fetcher.
**See also:** [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md) for the iOS workflow (APNs, Xcode). [android-physical-device-guide.md](./android-physical-device-guide.md) for USB debugging and build/run commands.
---
## Architecture overview
End-to-end flow when testing FCM registration and wakeup **delivery** on a physical Android phone:
```text
┌─────────────────────┐ HTTPS ┌──────────────────────┐
│ Mac (localhost) │ ◄───────────── │ ngrok edge │
│ notification- │ tunnel │ (public HTTPS URL) │
│ wakeup-service │ └──────────┬───────────┘
└──────────┬──────────┘ │
│ │ fetch
│ │ POST /notifications/register
│ ▼
│ ┌──────────────────────┐
│ │ crowd-funder-for- │
│ │ time-pwa (Capacitor │
│ │ Android on device) │
│ └──────────┬───────────┘
│ │
│ FCM data message (WAKEUP_PING) │ daily-notification-plugin
▼ ▼ (Daily Reminder / dual / fetcher)
┌─────────────────────┐ ┌──────────────────────┐
│ Firebase Cloud │ ──FCM────────► │ Android device │
│ Messaging │ direct │ app.timesafari.app │
└─────────────────────┘ └──────────────────────┘
```
Unlike iOS, Android does **not** use APNs. FCM delivers directly to the app via Google Play services on the device.
### Repos and responsibilities
| Repo | Role |
|------|------|
| **notification-wakeup-service** | HTTP API: device registration, health, debug wakeup send; may still expose `/notifications/refresh` for the backend |
| **crowd-funder-for-time-pwa** | Capacitor app: FCM token, `POST /notifications/register`; logs `WAKEUP_PING` without refresh/`api_*` scheduling |
| **daily-notification-plugin** | Native Android: Daily Reminder, New Activity / dual, native fetcher; Phase 4 `clearApiNotifications()` |
### Android wakeup flow (current)
1. **notification-wakeup-service** `/debug/send-wakeup` sends an FCM **data** message with `data.type = "WAKEUP_PING"`.
2. FCM delivers to the device (best-effort; see [Android Platform Notes](#8-android-platform-notes) and [Battery Optimization Caveats](#9-battery-optimization-caveats)).
3. Capacitor `pushNotificationReceived` fires → `handleCapacitorPushNotificationReceived()` in `NativeNotificationService.ts`.
4. Handler logs `[Notifications] push handler ignored type=WAKEUP_PING`. It does **not** POST `/notifications/refresh` or schedule `api_*` notifications.
Console and debug panel lines are prefixed with **`[Notifications]`** (see `NotificationDebugEvents.ts`).
---
## Prerequisites
- Mac (or Linux) with Node.js 18+, **notification-wakeup-service** cloned and runnable
- **Android Studio**, JDK 17+, `ANDROID_HOME`, and `adb` — see [android-physical-device-guide.md](./android-physical-device-guide.md)
- Physical Android device with USB debugging (recommended for realistic FCM, Doze, and OEM behavior)
- ngrok account (free tier is enough for dev)
- Firebase project with an **Android** app registered for the Gradle **application ID**
- Non-production app build (Notification Debug Panel is dev-only)
- `google-services.json` in `android/app/` (not committed; see [`.gitignore`](../android/.gitignore))
---
## 1. Install and configure ngrok (macOS)
### Install
```bash
# Homebrew
brew install ngrok/ngrok/ngrok
```
Or download from [https://ngrok.com/download](https://ngrok.com/download).
### Create ngrok account and configure auth token
1. Sign up at [https://dashboard.ngrok.com/signup](https://dashboard.ngrok.com/signup).
2. Copy your authtoken from **Your Authtoken** in the dashboard.
3. Configure the CLI:
```bash
ngrok config add-authtoken YOUR_AUTHTOKEN_HERE
```
### Start a tunnel to the wakeup service
Assume the service listens on port **3000** (confirm in **notification-wakeup-service** `README` or `.env`).
```bash
# Terminal A — backend
cd /path/to/notification-wakeup-service
npm install
# one-time setup if needed
cp .env.example .env
# configure Firebase service account etc. as required
export PORT=3000
npm run dev
```
```bash
# Terminal B — ngrok
ngrok http 3000
```
ngrok prints a forwarding URL, for example:
```text
Forwarding https://abc123.ngrok-free.app -> http://localhost:3000
```
Use the **HTTPS** URL (not `http://127.0.0.1:3000`). The phone cannot reach your Mac’s localhost without the tunnel.
> **Note:** Free ngrok URLs change every time you restart ngrok unless you use a reserved domain (paid). Update the app debug override whenever the URL changes.
---
## 2. Start the backend locally
On first setup, copy `.env.example` to `.env` and set Firebase service account, `PORT`, and other variables per **notification-wakeup-service** docs.
If the backend is not already running from section 1:
```bash
cd /path/to/notification-wakeup-service
npm run dev
```
Verify locally before ngrok:
```bash
curl -sS http://localhost:3000/health
```
Expected: HTTP 200 and a JSON body indicating the service is up (exact shape depends on that repo).
### Configure Firebase Admin for the backend
**notification-wakeup-service** uses the Firebase Admin SDK to send FCM messages from your Mac.
1. Firebase Console → **Project settings** → **Service accounts**.
2. Click **Generate new private key** and download the JSON file.
3. Store the JSON outside the repo (do not commit it).
4. Point the backend at it:
```bash
export GOOGLE_APPLICATION_CREDENTIALS="/absolute/path/to/service-account.json"
```
Set the same variable (or the equivalent documented in **notification-wakeup-service**) in the shell where you run `npm run dev`, or add it to that repo’s `.env`.
---
## 3. Obtain and use the ngrok HTTPS URL
1. Run `ngrok http <PORT>`.
2. Copy the `https://….ngrok-free.app` host from the **Forwarding** line.
3. Do **not** add a trailing slash when saving in the app (the debug config trims it).
4. Optional: open `http://127.0.0.1:4040` (ngrok web UI) to inspect requests and responses while testing.
Test through the tunnel from your Mac:
```bash
export NGROK_URL="https://abc123.ngrok-free.app"
curl -sS "$NGROK_URL/health"
```
---
## 4. Build and deploy to a physical Android device
From **crowd-funder-for-time-pwa**, build a non-production Capacitor bundle and sync Android. Complete [section 5](#5-firebase-setup-for-android-first-time) before expecting FCM to work.
```bash
npm install
npm run build:android:dev # or build:android:test — non-production for debug panel
```
Or use the combined run targets from [android-physical-device-guide.md](./android-physical-device-guide.md):
```bash
npm run build:android:debug:run
# or
npm run build:android:test:run
```
Open `android/` in Android Studio if you need to inspect native logs or signing. Ensure `VITE_FIREBASE_*` variables are set for the build you use (see `.env` / [BUILDING.md](../BUILDING.md)).
Native push registration runs at startup via `initializeNativePushAndFirebaseMessaging()` in `main.capacitor.ts` once Firebase and `google-services.json` are in place.
---
## 5. Firebase setup for Android (first-time setup)
Complete this section once before your first physical-device push test. If Firebase is already configured for this Android app, skip to [section 6](#6-configure-the-notification-debug-panel-backend-override).
### Create or access a Firebase account
1. Sign in at [https://console.firebase.google.com/](https://console.firebase.google.com/).
2. No paid Firebase plan is required. The free **Spark** plan supports **Firebase Cloud Messaging (FCM)** and local ngrok development.
### Create a Firebase project
1. In the Firebase Console, click **Add project** (or **Create a project**).
2. Enter a project name (for example, `timesafari-dev`) and continue through the wizard.
3. **Google Analytics** is optional for this workflow.
4. When the project is created, open it. **Cloud Messaging** is available on all projects — you do not need a separate “enable FCM” step beyond registering the Android app.
### Add the Android app in Firebase
1. In the project overview, click the **Android** icon (**Add app** → Android).
2. Enter the **Android package name**. It must **exactly** match the Gradle **applicationId**:
**`app.timesafari.app`**
(see `applicationId` in `android/app/build.gradle`. This differs from Capacitor `appId` in `capacitor.config.ts`, which is `app.timesafari`.)
3. App nickname and SHA-1/SHA-256 are optional for basic FCM wakeup testing; you may add debug keystore fingerprints later if Firebase Console prompts for them.
4. Download **`google-services.json`** when prompted.
### Place google-services.json
1. Copy the file to:
```text
crowd-funder-for-time-pwa/android/app/google-services.json
```
2. The repo gitignores this file — each developer keeps a local copy; never commit it.
3. Rebuild so Gradle applies the Google Services plugin (`android/app/build.gradle` applies `com.google.gms.google-services` when the file exists). If the file is missing, the build logs: *google-services.json not found, google-services plugin not applied. Push Notifications won't work*.
4. Sync Capacitor if you changed native config:
```bash
npx cap sync android
```
### Enable Firebase Cloud Messaging
FCM is enabled by default for Firebase projects. Confirm in **Project settings** → **Cloud Messaging**:
- **Cloud Messaging API** is available (legacy or HTTP v1 per your backend setup).
- The Android app (`app.timesafari.app`) appears under your apps.
The **notification-wakeup-service** sends wakeup messages through Firebase Admin using the same project’s service account ([section 2](#2-start-the-backend-locally)).
### Web / Capacitor JS Firebase config
In addition to `google-services.json`, the Capacitor web build needs `VITE_FIREBASE_*` env vars (API key, project ID, messaging sender ID, app ID, and optionally `VITE_FIREBASE_VAPID_KEY`). These must refer to the **same Firebase project** as `google-services.json`.
### Verify Firebase configuration
Before ngrok end-to-end testing, confirm:
- [ ] App builds and installs without Gradle errors about `google-services.json`.
- [ ] Push permission is **granted** (see [section 7](#7-android-notification-permissions)).
- [ ] **Notification Debug Panel** shows an FCM token (after permission and registration).
- [ ] **Register Token Now** succeeds and ngrok shows `POST /notifications/register`.
- [ ] Backend health and `GOOGLE_APPLICATION_CREDENTIALS` are set so `/debug/send-wakeup` can run.
---
## 6. Configure the Notification Debug Panel backend override
The app normally calls `DEFAULT_NOTIFY_API_SERVER` (from `VITE_DEFAULT_NOTIFY_API_SERVER`, falling back to `AppString.PROD_NOTIFY_API_SERVER`). That is independent of `APP_SERVER`. For local wakeup testing, override the notification API base URL in the Debug Panel without rebuilding.
For a full panel reference (configuration, URL resolution order, authentication, and troubleshooting), see [notification-debug-panel.md](./notification-debug-panel.md).
### Open the panel
1. Use a **non-production** build (e.g. `build:android:dev` or `build:android:test`).
2. **Account** → enable **Show All General Advanced Functions**.
3. Open **Notification Debug Panel** (route `/dev/notifications`).
### Backend Testing section
| Control | Purpose |
|---------|---------|
| **Notification Backend URL** | Paste ngrok HTTPS URL → **Save Backend URL** (changes target server only) |
| **Test Mode** | Sends `testMode: true/false` in register / send-wakeup JSON bodies (default on when unset in storage) |
| **Skip JWT Authentication (Local Development Only)** | When on, omits `Authorization` headers for local servers that accept unauthenticated requests (default **off**) |
| **Register Token Now** | `POST /notifications/register` with current FCM token and `platform: "android"` |
| **Upload AlertSearch Authorization** | Uploads AlertSearch delegated JWTs (`/notifications/alert-authorization`) |
| **Send Real WAKEUP_PING** | `POST /debug/send-wakeup`; FCM delivery diagnostic only (no app-side refresh/`api_*` scheduling) |
| **Event Log** | Shared `[Notifications]` panel log (100 entries) |
Persistence: `localStorage` keys `notificationDebug.backendBaseUrl`, `notificationDebug.testMode`, and `notificationDebug.bypassAuth` (`NotificationDebugConfig.ts`).
### Authentication vs backend URL
These settings are **independent**:
- **Backend URL** — which server receives `/notifications/*` and `/debug/*` calls.
- **Test Mode** — `testMode` field in JSON request bodies only.
- **Skip JWT Authentication** — whether `Authorization: Bearer …` is sent (via `getNotificationApiHeaders()`).
For a **hosted shared test server** (for example `https://test-notify-api.timesafari.app`): set the backend URL, keep **Test Mode** on if the server requires it, and leave **Skip JWT Authentication** **off**. Ensure an active DID and endorser session exist in the app.
For **local ngrok / localhost**: set the backend URL to your tunnel or `http://127.0.0.1:PORT`. Enable **Skip JWT Authentication** only if your local **notification-wakeup-service** intentionally accepts unauthenticated requests.
### testMode
When **Test Mode** is on (default if never saved), register and send-wakeup requests include `"testMode": true`. The backend can route dev traffic separately from production. Turn it off in the panel only if you intentionally want production-mode API behavior against your tunnel.
### WAKEUP_PING debug controls
**Send Real WAKEUP_PING** is the remaining panel control for wakeup. Mock refresh, Simulate WAKEUP_PING, Wakeup Ping Simulator, and Flood Test were removed with the retired refresh pipeline.
Use **Send Real WAKEUP_PING** to confirm backend → FCM → Capacitor listener delivery. Do not expect `/notifications/refresh` or `api_*` rescheduling.
### Send Real WAKEUP_PING
**Send Real WAKEUP_PING** is the in-app equivalent of calling **`POST /debug/send-wakeup`** from the Mac (see [Verification Checklist step 7](#7-manual-wakeup-endpoint-sends-fcm-successfully)). It is intended for **local testing and diagnostics** on non-production builds only.
**What it does:**
1. Reads the **Current FCM Token** shown in the panel (same token used by **Register Token Now**). If no token is available, the action fails with a panel status message.
2. `POST`s to `{backend override}/debug/send-wakeup` with `deviceId`, `fcmToken`, `platform: "android"`, and `testMode` from the panel config (`NotificationDebugService.sendRealWakeupPing()`).
3. On HTTP success, the **notification-wakeup-service** enqueues a real FCM **data** message with `data.type = "WAKEUP_PING"` to that device.
4. When FCM delivers the message to the app, Capacitor fires `pushNotificationReceived` → `handleCapacitorPushNotificationReceived()`, which logs `push handler ignored type=WAKEUP_PING`. There is no `refreshNotificationsWithDiagnostics` and no `applyNotificationRefreshPayload`.
That exercises **backend → FCM → Capacitor push listener** on Android without manual `curl` on the Mac. It does **not** reschedule local notifications.
**Prerequisites:** ngrok backend override saved, **Test Mode** as needed, notification permission granted, **Register Token Now** succeeded, app **backgrounded** (Home — not force-stop) before expecting FCM delivery ([§8](#8-android-platform-notes)).
#### Expected Logcat output
Filter logcat (prefix is always `[Notifications]`):
```bash
adb logcat | grep -E '\[Notifications\].*(Real WAKEUP_PING|push handler ignored)'
```
On a **successful FCM delivery** run (HTTP success from the panel, then FCM delivery within ~30–120s), expect these key lines in order:
```
[Notifications] Real WAKEUP_PING requested
[Notifications] Real WAKEUP_PING success
[Notifications] push handler ignored type=WAKEUP_PING
```
Auth bypass messages when **Skip JWT Authentication** is on are normal. ngrok should **not** show a new `POST /notifications/refresh` from the app after the push.
#### Send Real WAKEUP_PING vs delivery success
The panel status **“Real WAKEUP_PING sent via backend.”** and the Event Log line **`Real WAKEUP_PING success`** only confirm that the backend **accepted the request and attempted FCM delivery**. They do **not** prove the device received the push.
**Successful delivery** is confirmed when **`push handler ignored type=WAKEUP_PING`** appears in logcat (or Event Log) within the delivery window. If you see `Real WAKEUP_PING success` but not that line, treat it as an FCM delivery problem ([FCM message not received](#fcm-message-not-received)), not a backend enqueue failure.
### Programmatic override (optional)
From Chrome DevTools attached to the WebView (`chrome://inspect` → your app):
```javascript
import {
setBackendBaseUrl,
setTestMode,
setBypassAuth,
getNotificationApiBaseUrl,
} from "@/services/notifications";
setBackendBaseUrl("https://abc123.ngrok-free.app");
setTestMode(true);
setBypassAuth(true); // local dev only — omit for hosted servers that require JWT
getNotificationApiBaseUrl(); // → ngrok URL
```
---
## 7. Android notification permissions
### Android 13+ (API 33+)
`AndroidManifest.xml` declares:
```xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
```
On **Android 13 and above**, this is a **runtime** permission. The user must grant it before the system allows notification **display**. The OS shows a system dialog the first time the app requests it.
### How this app requests permission
At startup, `initializeNativePushAndFirebaseMessaging()` in `firebaseMessagingClient.ts` calls:
```typescript
const perm = await PushNotifications.requestPermissions();
```
If `perm.receive !== "granted"`, native push registration does not proceed and you will not get a reliable FCM token in the debug panel.
Daily notification flows can also request permission via **daily-notification-plugin** (`NativeNotificationService.requestPermissions()` → plugin `POST_NOTIFICATIONS`). See [notification-permissions-and-rollovers.md](./notification-permissions-and-rollovers.md).
### Android 12 and below
`POST_NOTIFICATIONS` does not exist as a runtime prompt on older APIs. Notifications are generally allowed at install time; fewer permission dialogs appear during testing.
### Manual check for testers
**Settings** → **Apps** → **TimeSafari** → **Notifications** → ensure notifications are allowed.
### Permission vs FCM data wake
**WAKEUP_PING** uses FCM **data** messages handled in `pushNotificationReceived`. For local testing:
- Grant notification permission so **Register Token Now** and token display in the debug panel work.
- If permission is denied, fix permission before debugging FCM wakeup; do not assume data delivery will run the full refresh pipeline.
---
## 8. Android Platform Notes
### FCM vs iOS silent push
Android generally delivers **background FCM data messages** more reliably than iOS **silent APNs** (`content-available`), especially when the app is backgrounded (not force-stopped) and Google Play services is healthy. There is no separate APNs hop; FCM talks to the device directly.
Delivery is still **not guaranteed**. Treat wakeup as best-effort in tests and in production expectations.
### Force-stop vs backgrounding
| State | Typical FCM behavior |
|-------|----------------------|
| **Foreground** | Data messages handled promptly; `pushNotificationReceived` fires. |
| **Background** (Home) | Data messages usually delivered; handler may run with delay under load. |
| **Force stop** (Settings → Force stop) | Delivery often **blocked** until the user launches the app again. Stricter than iOS “swipe away” in many cases. |
| **Recents swipe** | Varies by OEM/Android version; less predictable than Home. Prefer **Home** for tests. |
Always validate wakeup with the app **backgrounded**, not force-stopped.
### Notification permissions (Android 13+)
On **API 33+**, `POST_NOTIFICATIONS` is a runtime permission ([section 7](#7-android-notification-permissions)). This app requests push permission via `PushNotifications.requestPermissions()` before `register()`. Denied permission blocks token registration in the debug panel and undermines end-to-end testing—fix permission before debugging FCM.
### Network connectivity
FCM needs network to Google’s endpoints. Registration needs the ngrok HTTPS URL for `POST /notifications/register`. Airplane mode, captive portals, VPNs, or flaky Wi‑Fi cause “server sent wakeup but app never logged ignored type” symptoms even when FCM eventually arrives.
### Physical device vs emulator
Doze, App Standby, and OEM battery menus are weak or absent on many emulators. Use a **physical device** for wakeup SLA testing; emulators are fine for panel-only register smoke tests.
### Logcat
```bash
adb logcat | grep -E '\[Notifications\]|\[FirebaseMessaging\]|\[NativeNotificationService\]'
```
Expect `push handler ignored type=WAKEUP_PING` after a successful wake. For a panel-driven test, use **Send Real WAKEUP_PING** ([§6](#send-real-wakeup_ping)) instead of manual `curl`.
---
## 9. Battery Optimization Caveats
Android power management can **delay or batch** FCM delivery and background work even when the server returns success from `/debug/send-wakeup`.
### Doze Mode
When the device is **unplugged**, screen off, and idle, Android enters **Doze**. Network access and jobs are deferred to **maintenance windows**. Wakeup messages may arrive minutes late.
**Testing tip:** Keep the device on charger, or wake the screen briefly, or wait longer (2–5+ minutes) before failing a Doze test.
### App Standby
Apps used infrequently move to **standby** buckets with reduced background network. Frequent dev installs reset some of this; long-idle test devices do not.
**Testing tip:** Open the app before sending wakeup; register token again if the device was idle for days.
### Adaptive Battery
**Adaptive Battery** / per-app battery savers learn usage patterns and restrict background activity for “unused” apps.
**Testing tip:** **Settings** → **Apps** → **TimeSafari** → **Battery** → **Unrestricted** (or **Don’t optimize**) during local validation.
### Manufacturer-specific restrictions
OEMs add layers on top of AOSP. Aggressive battery management can delay **WAKEUP_PING** delivery.
| Vendor | Where to look (names vary by OS version) |
|--------|------------------------------------------|
| **Samsung** | Device care → Battery → Background usage limits; app → Battery → Unrestricted |
| **Xiaomi** | Security app → Autostart; Battery saver → No restrictions |
| **Oppo** / **Realme** | Battery → App battery management → Allow background activity |
| **Vivo** | iManager / Battery → High background power consumption |
| **Huawei** | App launch → Manage manually → enable Auto-launch, Secondary launch, Run in background |
If wakeup works on a **Pixel** but fails on an OEM phone, assume battery policy first—not a broken FCM payload.
### How this affects wakeup testing
1. Server accepts `/debug/send-wakeup` → FCM enqueue succeeds.
2. Device may **hold** the message until Doze maintenance or OEM policy allows delivery.
3. `pushNotificationReceived` runs → `push handler ignored type=WAKEUP_PING`.
4. Any step can lag under battery savers; use **Send Real WAKEUP_PING** for the FCM path ([§6](#send-real-wakeup_ping)).
---
## 10. Recommended local testing workflow
1. Start **notification-wakeup-service** on the Mac (`npm run dev`, `GOOGLE_APPLICATION_CREDENTIALS` set).
2. Start **ngrok** and copy the HTTPS URL.
3. Install a **non-production** Android build with `google-services.json` in place.
4. Grant notification permission when prompted (or enable in Settings).
5. Open **Notification Debug Panel** → paste ngrok URL → **Save Backend URL**; confirm **Test Mode** is on; enable **Skip JWT Authentication** only if your local backend accepts unauthenticated requests.
6. Tap **Register Token Now** → confirm ngrok `POST /notifications/register` and `[Notifications] Token registration success` in Event Log / logcat.
7. Background the app (Home), then tap **Send Real WAKEUP_PING** (or from the Mac, call **`/debug/send-wakeup`** — see [curl examples](#13-sample-curl-commands)) with the registered `deviceId` / token as required by **notification-wakeup-service**.
8. Watch logcat for `push handler ignored type=WAKEUP_PING` ([expected output](#expected-logcat-output)).
9. Open **ngrok inspect UI** (`http://127.0.0.1:4040`) to correlate HTTP traffic (register and send-wakeup; not app-initiated refresh).
10. Use **Pending Notification Inspector** for Daily Reminder / New Activity / dual schedules — not for retired `api_*` refresh.
For a formal pass/fail sequence, use the [Verification Checklist](#11-verification-checklist) below.
---
## 11. Verification Checklist
Use this checklist during development or QA sign-off. Each step lists **actions**, then **expected outcome**. Prerequisites: non-production Android build, `google-services.json` installed, physical device (recommended), backend + ngrok running.
| # | Check | Pass criteria |
|---|--------|----------------|
| 1 | Backend via ngrok | §1 below |
| 2 | Device → backend override | §2 |
| 3 | FCM token registered | §3 |
| 4 | Device record in wakeup service | §4 |
| 5 | Optional backend `/notifications/refresh` curl | §5 (backend only; app does not call this) |
| 6 | Locals scheduled | §6 (Daily Reminder / dual / fetcher — not refresh) |
| 7 | Manual wakeup sends FCM | §7 |
| 8 | WAKEUP_PING delivered | §8 |
| 9 | _(retired)_ Replace after refresh | skipped |
| 10 | _(retired)_ Test mode frequent refreshes | skipped |
### 1. Backend reachable through ngrok
**Actions:**
```bash
export BASE="https://YOUR-NGROK-HOST.ngrok-free.app"
curl -sS -w "\nHTTP %{http_code}\n" "$BASE/health"
```
**Expected outcome:** HTTP **200**; JSON body indicates the service is healthy (exact fields per **notification-wakeup-service**). Mac `curl http://localhost:3000/health` must also pass before blaming ngrok.
---
### 2. Device can reach backend override URL
**Actions:**
1. Open **Notification Debug Panel** (`/dev/notifications`).
2. Paste ngrok HTTPS URL (no trailing slash) → **Save Backend URL**.
3. Confirm **Backend Status → URL** matches the saved ngrok host.
4. Enable **Test Mode** if using dev backend behavior.
**Expected outcome:** **Active** URL in the panel equals your ngrok `https://…` host. Subsequent app requests use that base (not the default `DEFAULT_NOTIFY_API_SERVER`) for `/notifications/register` and `/debug/send-wakeup`.
---
### 3. FCM token successfully registered
**Actions:**
1. Grant notification permission when prompted (Android 13+).
2. Tap **Register Token Now**.
3. Watch Event Log and logcat (`[Notifications]`, `[FirebaseMessaging]`).
**Expected outcome:**
- **Current FCM Token** shows a non-empty token (Copy works).
- Event Log: `[Notifications] Token registration success` (not failure / auth unavailable).
- ngrok inspect: `POST /notifications/register` with **200**; body includes `platform: "android"`, `testMode: true` (if Test Mode on), `deviceId`, and `fcmToken`.
---
### 4. Device record appears in notification-wakeup-service
**Actions:**
1. In ngrok inspect (`http://127.0.0.1:4040`), open the **register** request → copy `deviceId` and `fcmToken` from the JSON body.
2. In **notification-wakeup-service**, confirm persistence per that repo (server logs, database, admin/list endpoint, or debug CLI).
**Expected outcome:** The `deviceId` and `fcmToken` from step 3 are stored and retrievable by the service. `/debug/send-wakeup` can target that `deviceId` (or token, per service contract). If register returned 200 but no record exists, fix the wakeup service store/config before FCM tests.
> **Note:** `deviceId` is created in-app (`Preferences` key `stable_device_id` in `deviceId.ts`). It is not shown in the debug panel; use ngrok request body or logcat `[DeviceId]` lines.
---
### 5. Refresh endpoint (backend only; app does not call this)
**Actions:**
Mac-side curl against **notification-wakeup-service** if you need to confirm the backend still answers. The app has no **Refresh Notifications** button and does not schedule from this payload.
```bash
curl -sS -X POST "$BASE/notifications/refresh" \
-H "Content-Type: application/json" \
-d '{"platform":"android","testMode":true}'
```
**Expected outcome:** HTTP **200** from the **service** if that route is still deployed. Do **not** expect Event Log `Refresh completed` or `api_*` schedules in the app.
---
### 6. Local notifications are scheduled (not from refresh)
**Actions:**
1. Configure Static Daily Reminder and/or New Activity (dual) in the app, or rely on the native fetcher.
2. Open **Pending Notification Inspector** → **Refresh** (list button).
**Expected outcome:** Inspector lists pending Daily Reminder / dual / fetcher items. Do not expect `api_*` identifiers after Phase 4 startup cleanup. There is no `Schedule replacement applied` from WAKEUP_PING.
---
### 7. Manual wakeup endpoint sends FCM successfully
**Actions:**
1. Use `deviceId` from step 4.
2. Either:
- **On device:** background the app (Home), open **Notification Debug Panel**, tap **Send Real WAKEUP_PING**; or
- **From the Mac:**
```bash
curl -sS -X POST "$BASE/debug/send-wakeup" \
-H "Content-Type: application/json" \
-d '{"deviceId":"YOUR_DEVICE_ID","testMode":true}'
```
3. Check **notification-wakeup-service** logs for FCM send success (no Admin SDK / token errors).
**Expected outcome:** HTTP **200** (or documented success code) from `/debug/send-wakeup`; Event Log / logcat: `Real WAKEUP_PING success` when using the panel button; server logs indicate FCM message enqueued/sent with `data.type = "WAKEUP_PING"`. This step alone does not prove device delivery (see step 8 and [Send Real WAKEUP_PING vs delivery success](#send-real-wakeup_ping-vs-delivery-success)).
---
### 8. WAKEUP_PING is delivered (no refresh)
**Actions:**
1. **Background** the app (Home — not force-stop).
2. Run step 7 again (panel **Send Real WAKEUP_PING** or Mac `curl`), or wait for a server-driven wakeup.
3. Filter logcat:
```bash
adb logcat | grep -E 'WAKEUP_PING|push handler ignored'
```
**Expected outcome (within ~30–120s, longer under Doze/OEM):**
1. `Real WAKEUP_PING success` (panel path)
2. `push handler ignored type=WAKEUP_PING`
3. ngrok: **no** app-initiated `POST /notifications/refresh`
Full expected logcat for **Send Real WAKEUP_PING**: [§6](#expected-logcat-output).
---
### 9. Existing notifications are replaced after refresh
**Retired.** The app no longer replaces local schedules from `/notifications/refresh`. Pending list changes come from Daily Reminder / dual / native fetcher, or from Phase 4 `clearApiNotifications()`.
---
### 10. Test mode produces frequent notification refreshes
**Retired.** `testMode` still goes on register and send-wakeup bodies. It does not drive app-side `api_*` refresh cadences.
---
## 12. End-to-End Test
Single scripted run from cold start to scheduled local notification. Time: ~15–30 minutes (plus optional wait for a near `testMode` fire).
### Phase A — Mac backend and tunnel
1. Terminal A:
```bash
cd /path/to/notification-wakeup-service
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
export PORT=3000
npm run dev
```
2. Verify: `curl -sS http://localhost:3000/health` → **200**.
3. Terminal B: `ngrok http 3000` → copy `https://….ngrok-free.app` → `export BASE=…`.
4. Verify: `curl -sS "$BASE/health"` → **200**.
### Phase B — Android app
5. Build and install dev/test APK (`npm run build:android:dev` or `build:android:debug:run`); `google-services.json` in `android/app/`.
6. Launch app; accept **notification permission**.
7. **Account** → **Show All General Advanced Functions** → **Notification Debug Panel**.
8. Paste `BASE` → **Save Backend URL**; enable **Test Mode**.
### Phase C — Register
9. **Register Token Now** → Event Log success; ngrok `POST /notifications/register` **200**; copy `deviceId` from ngrok request body.
10. Confirm device in **notification-wakeup-service** (logs/DB per that repo).
### Phase D — FCM wakeup delivery
11. Background app (Home).
12. Tap **Send Real WAKEUP_PING** in the panel (or Mac: `curl -X POST "$BASE/debug/send-wakeup" -H "Content-Type: application/json" -d '{"deviceId":"…","testMode":true}'`) → panel `Real WAKEUP_PING success` and server FCM enqueue success.
13. Within 30–120s (longer if unplugged/Doze): logcat shows `push handler ignored type=WAKEUP_PING`; ngrok does **not** show an app `POST /notifications/refresh`.
### Phase E — Optional local notification proof
14. Enable Daily Reminder or New Activity; wait for wall-clock fire with app backgrounded; confirm the OS notification is **not** the retired generic `api_*` “Reminder” copy.
### End-to-end pass criteria
| Phase | Pass |
|-------|------|
| A | Health OK local + ngrok |
| B | Override URL + testMode active |
| C | Register succeeded |
| D | Wakeup curl/panel OK → logcat ignored-type line |
| E | Optional visible Daily Reminder / New Activity notification |
---
## 13. Sample curl commands
Set your tunnel base URL:
```bash
export BASE="https://abc123.ngrok-free.app"
```
### Health
```bash
curl -sS -w "\nHTTP %{http_code}\n" "$BASE/health"
```
### Register device (mirror app payload)
```bash
curl -sS -X POST "$BASE/notifications/register" \
-H "Content-Type: application/json" \
-d '{
"deviceId": "00000000-0000-4000-8000-000000000001",
"fcmToken": "YOUR_FCM_TOKEN_FROM_DEBUG_PANEL",
"platform": "android",
"testMode": true
}'
```
### Refresh (backend only; app does not consume)
```bash
curl -sS -X POST "$BASE/notifications/refresh" \
-H "Content-Type: application/json" \
-d '{
"platform": "android",
"testMode": true
}'
```
This exercises **notification-wakeup-service** only. The app does **not** call `applyNotificationRefreshPayload` or schedule `api_*` from the response.
### Send wakeup push (debug)
Exact path and body depend on **notification-wakeup-service**; typical pattern:
```bash
curl -sS -X POST "$BASE/debug/send-wakeup" \
-H "Content-Type: application/json" \
-d '{
"deviceId": "00000000-0000-4000-8000-000000000001",
"testMode": true
}'
```
Confirm parameters (token vs `deviceId`, auth headers) in that repo’s README or OpenAPI spec. The server may still send FCM data including `type: "WAKEUP_PING"`; the app logs it as ignored and does not refresh.
---
## 14. Troubleshooting
Structured checks for local ngrok + FCM testing. Each item lists **symptoms**, **likely causes**, **verification**, and **fixes**.
### Token registration failures
**Symptoms:** Event Log shows token registration failure; no FCM token in debug panel; ngrok has no `POST /notifications/register`; curl register fails.
**Likely causes:** Notification permission denied; missing `google-services.json`; Firebase package mismatch (`app.timesafari.app`); `VITE_FIREBASE_*` not in build; JWT auth failure or **Skip JWT Authentication** mismatch with server expectations; duplicate-token skip.
**Verification:**
1. Settings → app → Notifications → allowed.
2. Logcat: `[FirebaseMessaging] Push permission not granted` or registration errors.
3. Panel shows a token string before **Register Token Now**.
4. ngrok inspect UI (`http://127.0.0.1:4040`) for register request status body.
**Fixes:** Grant permission and cold-start app; add `android/app/google-services.json` and rebuild; align Firebase Android app ID with Gradle `applicationId`; rebuild with correct `.env`; tap **Register Token Now** (forces re-register); for JWT-required servers, ensure active DID/endorser session and **Skip JWT Authentication** off; for local unauthenticated backends, enable **Skip JWT Authentication** (see [notification-debug-panel.md](./notification-debug-panel.md)).
---
### Backend unreachable
**Symptoms:** Backend Status unhealthy in panel; register/refresh network errors; Mac `curl localhost:3000/health` fails.
**Likely causes:** `notification-wakeup-service` not running; wrong `PORT`; firewall; typo in saved backend URL (not ngrok).
**Verification:**
```bash
curl -sS http://localhost:3000/health
```
Compare with panel **Backend Status** and Event Log error text.
**Fixes:** Start backend with `npm run dev` and `GOOGLE_APPLICATION_CREDENTIALS`; match `PORT` to ngrok target; paste full ngrok **HTTPS** URL into panel (no trailing slash).
---
### Stale ngrok URL
**Symptoms:** Worked yesterday; today all API calls fail or hit wrong host; ngrok shows no requests.
**Likely causes:** Free ngrok URL changed after tunnel restart; old URL still in `notificationDebug.backendBaseUrl`.
**Verification:** Compare panel URL to current `ngrok http` **Forwarding** line; `curl -sS "$NEW_URL/health"`.
**Fixes:** Copy new HTTPS URL → **Save Backend URL** in panel; or clear override only if intentionally returning to `DEFAULT_NOTIFY_API_SERVER`.
---
### Refresh endpoint failures
**Symptoms:** Mac `curl` of `/notifications/refresh` fails; ngrok missing that path. This is a **backend** issue. The app does not POST refresh.
**Verification:** `curl` health and refresh from the Mac; confirm the service still ships that route.
**Fixes:** Fix backend URL and health. App scheduling uses Daily Reminder / dual / native fetcher, not this payload.
---
### FCM message not received
**Symptoms:** `/debug/send-wakeup` or panel **Send Real WAKEUP_PING** shows success (`Real WAKEUP_PING success` in Event Log); no `push handler ignored type=WAKEUP_PING` in logcat within 2 minutes.
**Likely causes:** Force-stopped app; wrong FCM token on server; Doze/OEM delay; no Google Play services; payload missing `data.type = "WAKEUP_PING"`; device offline.
**Note:** `Real WAKEUP_PING success` only means the backend accepted and sent the FCM request. Missing the ignored-type log indicates a **delivery** failure, not a failed wakeup API call ([§6](#send-real-wakeup_ping-vs-delivery-success)).
**Verification:**
1. App **backgrounded** (Home), not force-stopped.
2. Panel FCM token matches token used by server/register.
3. Wait 30–120s (longer on Doze/OEM).
4. Battery **Unrestricted** and OEM autostart enabled for test device.
**Fixes:** Re-register token; relaunch app; relax battery settings ([section 9](#9-battery-optimization-caveats)); confirm **notification-wakeup-service** message format; test on Pixel vs suspect OEM policy.
---
### Notification permission denied
**Symptoms:** No permission dialog or user denied; logcat `Push permission not granted`; empty FCM token; register skipped.
**Likely causes:** User denied prompt; permission revoked in Settings; testing on API 33+ without `POST_NOTIFICATIONS` grant.
**Verification:** Settings → Apps → TimeSafari → Notifications; logcat after cold start for `requestPermissions` result.
**Fixes:** Enable notifications in Settings; reinstall to re-prompt if needed; cold-start app so `initializeNativePushAndFirebaseMessaging()` runs again.
---
### Notifications not appearing
**Symptoms:** Daily Reminder or New Activity configured but no visible notification at fire time; Pending Inspector empty or stale.
**Likely causes:** Permission denied (display blocked); exact alarm permission on Android 12+; timestamps in past; plugin schedule error; DND/channel settings.
**Verification:**
1. Permission granted ([section 7](#7-android-notification-permissions)).
2. Pending Notification Inspector for Daily Reminder / dual identifiers (not `api_*` after Phase 4 cleanup).
**Fixes:** Grant `POST_NOTIFICATIONS`; check `SCHEDULE_EXACT_ALARM` / alarm permission per plugin docs. Do not expect wakeup refresh payloads to populate the inspector.
---
### Duplicate notifications
**Symptoms:** Multiple identical local notifications.
**Likely causes:** Separate Daily Reminder vs New Activity schedules; duplicate dual config; leftover `api_*` before Phase 4 cleanup.
**Verification:** Pending Inspector identifiers; see [notification-new-activity-lay-of-the-land.md](./notification-new-activity-lay-of-the-land.md) for product-level double-schedule issues.
**Fixes:** Confirm Daily Reminder vs dual settings. WAKEUP_PING no longer stacks `api_*` refreshes.
---
### Device enters battery-saving mode
**Symptoms:** Intermittent wakeup; long delays; works on charger but not unplugged; OEM “battery saver” icon on.
**Likely causes:** Doze; Adaptive Battery; manufacturer saver (Samsung, Xiaomi, Oppo, Vivo, Huawei).
**Verification:** Settings → Battery; OEM battery app; reproduce unplugged screen-off vs charging.
**Fixes:** For dev testing set app battery to **Unrestricted**; enable **Autostart** / background activity on OEM; wait for maintenance window or wake device before concluding FCM failure.
---
### Gradle: Push Notifications won't work
**Symptoms:** Build log: `google-services.json not found, google-services plugin not applied`.
**Likely causes:** Missing `android/app/google-services.json`.
**Verification:** File exists on disk; rebuild shows Google Services plugin applied.
**Fixes:** Download from Firebase Console (package `app.timesafari.app`); place in `android/app/`; `npx cap sync android` and rebuild.
---
## 15. Key source files (crowd-funder-for-time-pwa)
| File | Purpose |
|------|---------|
| `src/services/notifications/NotificationDebugConfig.ts` | Backend URL, testMode, and bypassAuth overrides |
| `src/services/notifications/NotificationDebugEvents.ts` | Panel event log + `logNotification()` |
| `src/services/notifications/notificationLog.ts` | Structured log helpers |
| `src/services/notifications/NotificationService.ts` | `POST /notifications/register` |
| `src/services/notifications/NativeNotificationService.ts` | Push delivery hook (logs ignored types; no refresh) |
| `src/services/notifications/firebaseMessagingClient.ts` | Capacitor push listeners, permission, token registration |
| `src/components/dev/NotificationDebugPanel.vue` | Dev UI |
| `src/main.capacitor.ts` | Native push init at startup |
| `android/app/build.gradle` | `applicationId`, conditional `google-services` plugin |
| `android/app/src/main/AndroidManifest.xml` | `POST_NOTIFICATIONS` and plugin permissions |
---
## 16. Related docs
- [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md) — iOS + APNs equivalent
- [local-android-testing-analysis.md](./local-android-testing-analysis.md) — reuse matrix used to author this guide
- [android-physical-device-guide.md](./android-physical-device-guide.md) — USB, `adb`, build commands
- [notification-system-overview.md](./notification-system-overview.md)
- [notification-from-api-call.md](./notification-from-api-call.md)
- [notification-permissions-and-rollovers.md](./notification-permissions-and-rollovers.md)
- [BUILDING.md](../BUILDING.md) — Android build commands
- [notification-debug-panel.md](./notification-debug-panel.md) — panel controls, authentication, troubleshooting
- [Notification Debug Panel (README)](../README.md#notification-debug-panel-dev-builds)
For plugin-native behavior (exact alarms, Android pending inspector), see **daily-notification-plugin** documentation. For FCM payload format and `/debug/send-wakeup` contract, see **notification-wakeup-service**.
+525
View File
@@ -0,0 +1,525 @@
# Local iOS Testing with ngrok (notification-wakeup-service)
**Last updated:** 2026-09-24 (retired WAKEUP_PING → refresh → `api_*` consumption)
**Audience:** Developers on **crowd-funder-for-time-pwa**, **daily-notification-plugin**, and **notification-wakeup-service**
**Goal:** Exercise FCM token registration and silent-push **delivery** (`WAKEUP_PING` via `/debug/send-wakeup`) against a Mac-hosted backend reachable from a physical iPhone.
> **Retired (do not expect this in the app):** `WAKEUP_PING` → `POST /notifications/refresh` → `applyNotificationRefreshPayload()` → `api_*` local schedules. The app logs ignored push types and does not refresh or schedule from wakeup. `/debug/send-wakeup` remains an FCM/APNs diagnostic. Mac `curl` of `/notifications/refresh` only tests the backend.
---
## Architecture overview
End-to-end flow when testing FCM registration and wakeup **delivery** on a physical iPhone:
```text
┌─────────────────────┐ HTTPS ┌──────────────────────┐
│ Mac (localhost) │ ◄───────────── │ ngrok edge │
│ notification- │ tunnel │ (public HTTPS URL) │
│ wakeup-service │ └──────────┬───────────┘
└──────────┬──────────┘ │
│ │ fetch
│ │ POST /notifications/register
│ ▼
│ ┌──────────────────────┐
│ │ crowd-funder-for- │
│ │ time-pwa (Capacitor │
│ │ iOS on iPhone) │
│ └──────────┬───────────┘
│ │
│ FCM data message (WAKEUP_PING) │ daily-notification-plugin
▼ ▼ (Daily Reminder / dual / fetcher)
┌─────────────────────┐ ┌──────────────────────┐
│ Firebase Cloud │ ──APNs──────► │ iPhone (physical) │
│ Messaging │ silent push │ app.timesafari │
└─────────────────────┘ └──────────────────────┘
```
### Repos and responsibilities
| Repo | Role |
|------|------|
| **notification-wakeup-service** | HTTP API: device registration, health, debug wakeup send; may still expose `/notifications/refresh` |
| **crowd-funder-for-time-pwa** | Capacitor app: FCM token, `POST /notifications/register`; logs `WAKEUP_PING` without refresh/`api_*` scheduling |
| **daily-notification-plugin** | Native iOS/Android: Daily Reminder, New Activity / dual, native fetcher; Phase 4 `clearApiNotifications()` |
### Silent wake sequence (current)
1. Backend `/debug/send-wakeup` sends an FCM **data** message with `data.type = "WAKEUP_PING"`.
2. APNs delivers to the device (best-effort; see iOS caveats below).
3. Capacitor `pushNotificationReceived` fires → `handleCapacitorPushNotificationReceived()`.
4. Handler logs `[Notifications] push handler ignored type=WAKEUP_PING`. It does **not** POST `/notifications/refresh` or schedule `api_*` notifications.
Console and debug panel lines are prefixed with **`[Notifications]`** (see `NotificationDebugEvents.ts`).
---
## Prerequisites
- Mac with Xcode, Node.js 18+, and the **notification-wakeup-service** repo cloned and runnable
- Physical iPhone (USB or wireless debugging) — **simulator is not sufficient** for reliable silent push / APNs behavior
- ngrok account (free tier is enough for dev)
- Firebase project with APNs configured for the iOS app bundle ID
- Non-production app build (Notification Debug Panel is dev-only)
---
## 1. Install and configure ngrok (macOS)
### Install
```bash
# Homebrew
brew install ngrok/ngrok/ngrok
```
Or download from [https://ngrok.com/download](https://ngrok.com/download).
### Account and auth token
1. Sign up at [https://dashboard.ngrok.com/signup](https://dashboard.ngrok.com/signup).
2. Copy your authtoken from **Your Authtoken** in the dashboard.
3. Configure the CLI:
```bash
ngrok config add-authtoken YOUR_AUTHTOKEN_HERE
```
### Start a tunnel to the wakeup service
Assume the service listens on port **3000** (confirm in **notification-wakeup-service** `README` or `.env`).
If the service already defaults to port 3000 internally, you may not need to export PORT manually.
```bash
# Terminal A — backend
cd /path/to/notification-wakeup-service
npm install
# one-time setup if needed
cp .env.example .env
# configure Firebase/service account/etc as required
export PORT=3000
npm run dev
```
```bash
# Terminal B — ngrok
ngrok http 3000
```
The backend only needs to be started once. The dedicated backend section below exists for verification and troubleshooting details, not as a second startup step.
ngrok prints a forwarding URL, for example:
```text
Forwarding https://abc123.ngrok-free.app -> http://localhost:3000
```
Use the **HTTPS** URL (not `http://127.0.0.1:3000`). The iPhone cannot reach your Mac’s localhost without the tunnel.
> **Note:** Free ngrok URLs change every time you restart ngrok unless you use a reserved domain (paid). Update the app debug override whenever the URL changes.
---
## 2. Start the backend locally
Example (adjust to match **notification-wakeup-service**). On first setup, copy `.env.example` to `.env` and set Firebase service account, `PORT`, and other variables per that repo's docs.
If the backend is not already running from section 1:
```bash
# If not already running from the previous step:
cd /path/to/notification-wakeup-service
npm run dev
```
Verify locally before ngrok:
```bash
curl -sS http://localhost:3000/health
```
Expected: HTTP 200 and a JSON body indicating the service is up (exact shape depends on that repo).
---
## 3. Obtain and use the ngrok HTTPS URL
1. Run `ngrok http <PORT>`.
2. Copy the `https://….ngrok-free.app` host from the **Forwarding** line.
3. Do **not** add a trailing slash when saving in the app (the debug config trims it).
4. Optional: open `http://127.0.0.1:4040` (ngrok web UI) to inspect requests and responses while testing.
Test through the tunnel from your Mac:
```bash
export NGROK_URL="https://abc123.ngrok-free.app"
curl -sS "$NGROK_URL/health"
```
---
## 4. Generate and open the iOS workspace
From **crowd-funder-for-time-pwa**, generate the Capacitor iOS project and open it in Xcode. **[Section 5](#5-firebase--apns-setup-first-time-setup) (Firebase + APNs)** needs this workspace—for example to add `GoogleService-Info.plist` and enable Push Notifications in the app target. The app does not need Firebase or push fully configured yet; the goal here is a buildable Xcode project on your Mac.
```bash
npm install
npm run build:ios:dev # or build:ios:test — non-production for debug panel
```
Open the generated Xcode workspace (for example `ios/App/App.xcworkspace`), select your **physical iPhone**, enable signing, and Run when you are ready to verify the app launches.
Ensure `VITE_FIREBASE_*` variables are set for the Capacitor build you use (see `.env` / build docs). Native push registration runs at startup via `initializeNativePushAndFirebaseMessaging()` in `main.capacitor.ts` once Firebase is configured in the next section.
---
## 5. Firebase + APNs setup (first-time setup)
Complete this section once before your first physical-device push test. If Firebase and APNs are already configured for this app, skip to [section 6](#6-configure-the-notification-debug-panel-backend-override).
### Create or access a Firebase account
1. Sign in with a Google account at [https://console.firebase.google.com/](https://console.firebase.google.com/).
2. If this is your first time using Firebase:
- Accept the Firebase terms.
- Create a new Firebase account/workspace when prompted.
3. No paid Firebase plan is required for local iOS notification testing. The free **Spark** plan is sufficient for:
- Firebase Cloud Messaging (FCM)
- APNs silent push testing
- local ngrok-based development
### Create a Firebase project
1. In the [Firebase Console](https://console.firebase.google.com/), click **Add project** (or **Create a project**).
2. Enter a project name (for example, `timesafari-dev`) and continue through the wizard.
3. **Google Analytics** is optional for this workflow; you can disable it for a simpler dev project.
4. When the project is created, open it. **Cloud Messaging** is available on all projects — you do not need a separate enable step for FCM.
### Register the iOS app in Firebase
1. In the project overview, click the **iOS** icon (**Add app** → iOS).
2. Enter the **Apple bundle ID**. It must **exactly** match the Capacitor / Xcode app ID:
- **`app.timesafari`** (see `appId` in `capacitor.config.ts` and the Xcode target **Bundle Identifier**).
3. App nickname and App Store ID are optional for local testing; continue.
4. Download **`GoogleService-Info.plist`** when prompted and keep it handy for the next step.
### Add GoogleService-Info.plist to Xcode
1. Open the iOS workspace you generated in [section 4](#4-generate-and-open-the-ios-workspace) (for example `ios/App/App.xcworkspace`).
2. In the Project Navigator, drag **`GoogleService-Info.plist`** into the **App** folder (the same one that contains AppDelegate.swift and Info.plist).
3. In the dialog that appears:
- Check **Copy items if needed** (so the file is copied into the project tree).
- Under **Add to targets**, ensure the main app target (not only the share extension) is checked.
4. Confirm the file appears under the app target in Xcode and is listed in **Build Phases** → **Copy Bundle Resources** if your project uses that phase for plists.
### Create an APNs Authentication Key
Apple uses APNs to deliver pushes to devices; Firebase needs an APNs key to talk to Apple on your behalf.
1. Sign in to [Apple Developer](https://developer.apple.com/account/) → **Certificates, Identifiers & Profiles**.
2. Open **Keys** → **+** (create a new key).
3. Name the key (for example, `Timesafari APNs Dev`).
4. Enable **Apple Push Notifications service (APNs)** and continue.
5. Register the key, then **Download** the `.p8` file. **You can download it only once** — store it securely.
6. Note:
- **Key ID** (shown on the key detail page)
- **Team ID** (top right of the developer portal, or **Membership** details)
### Upload APNs key to Firebase
1. Firebase Console → your project → **Project settings** (gear icon).
2. Open the **Cloud Messaging** tab.
3. Under **Apple app configuration**, select your iOS app (`app.timesafari`) if prompted.
4. Under **APNs Authentication Key**, click **Upload**.
5. Select the `.p8` file and enter:
- **Key ID**
- **Team ID**
6. Save. Firebase can now send FCM messages through APNs to your iOS app.
### Enable iOS capabilities in Xcode
1. Select the **App** target → **Signing & Capabilities**.
2. Click **+ Capability** and add **Push Notifications**.
3. Click **+ Capability** again and add **Background Modes**.
4. Under Background Modes, enable **Remote notifications**.
These match what silent / data wake flows expect for background delivery.
### Configure Firebase Admin for the backend
**notification-wakeup-service** uses the Firebase Admin SDK to send FCM (and thus APNs) messages from your Mac.
1. Firebase Console → **Project settings** → **Service accounts**.
2. Click **Generate new private key** and confirm download of the JSON file.
3. Store the JSON outside the repo (do not commit it).
4. Point the backend at it, for example:
```bash
export GOOGLE_APPLICATION_CREDENTIALS="/absolute/path/to/service-account.json"
```
The backend uses this credential to authenticate with Firebase when calling endpoints such as `/debug/send-wakeup`. Set the same variable (or the equivalent env var documented in **notification-wakeup-service**) in the shell where you run `npm run dev`, or add it to that repo’s `.env` per its README.
### Verify Firebase configuration
Before ngrok end-to-end testing, confirm:
- [ ] App builds and launches on a **physical** iPhone without Firebase/plist errors in Xcode.
- [ ] iOS shows the push **permission** prompt (or Settings → app → Notifications is enabled).
- [ ] **Notification Debug Panel** shows an FCM token (after permission).
- [ ] **Register Token Now** succeeds and ngrok (or local backend) shows `POST /notifications/register`.
- [ ] Backend health and Firebase Admin env are set so `/debug/send-wakeup` can run when you reach that step in the workflow below.
---
## 6. Configure the Notification Debug Panel backend override
The app normally calls `DEFAULT_NOTIFY_API_SERVER` (from `VITE_DEFAULT_NOTIFY_API_SERVER`, falling back to `AppString.PROD_NOTIFY_API_SERVER`). That is independent of `APP_SERVER`. For local wakeup testing, override the notification API base URL in the Debug Panel without rebuilding.
For a full panel reference (configuration, URL resolution order, authentication, and troubleshooting), see [notification-debug-panel.md](./notification-debug-panel.md).
### Open the panel
1. Use a **non-production** bundle (e.g. dev/test build).
2. **Account** → enable **Show All General Advanced Functions**.
3. Open **Notification Debug Panel** (route `/dev/notifications`).
### Backend Testing section
| Control | Purpose |
|---------|---------|
| **Notification Backend URL** | Paste ngrok HTTPS URL → **Save Backend URL** (changes target server only) |
| **Test Mode** | Sends `testMode: true/false` in register / send-wakeup JSON bodies (default on when unset in storage) |
| **Skip JWT Authentication (Local Development Only)** | When on, omits `Authorization` headers for local servers that accept unauthenticated requests (default **off**) |
| **Register Token Now** | `POST /notifications/register` with current FCM token |
| **Upload AlertSearch Authorization** | Uploads AlertSearch delegated JWTs |
| **Send Real WAKEUP_PING** | `POST /debug/send-wakeup`; FCM/APNs delivery diagnostic only |
| **Event Log** | Shared `[Notifications]` panel log (100 entries) |
Persistence: `localStorage` keys `notificationDebug.backendBaseUrl`, `notificationDebug.testMode`, and `notificationDebug.bypassAuth` (`NotificationDebugConfig.ts`).
### Authentication vs backend URL
These settings are **independent**:
- **Backend URL** — which server receives notification API calls.
- **Test Mode** — `testMode` field in JSON request bodies only.
- **Skip JWT Authentication** — whether JWT `Authorization` headers are sent.
For a **hosted shared test server**: set the backend URL, keep **Test Mode** on if required, leave **Skip JWT Authentication** **off**, and ensure an active DID exists.
For **local ngrok**: set the backend URL; enable **Skip JWT Authentication** only if your local backend accepts unauthenticated requests.
### Programmatic override (optional)
From Safari Web Inspector or a dev console attached to the WebView:
```javascript
import {
setBackendBaseUrl,
setTestMode,
setBypassAuth,
getNotificationApiBaseUrl,
} from "@/services/notifications";
setBackendBaseUrl("https://abc123.ngrok-free.app");
setTestMode(true);
setBypassAuth(true); // local dev only — omit for hosted servers that require JWT
getNotificationApiBaseUrl(); // → ngrok URL
```
---
## 7. Firebase and Xcode checklist (iOS)
This section is a quick verification checklist for the detailed Firebase/APNs setup steps above.
| Item | Action |
|------|--------|
| **Bundle ID** | Match Capacitor `appId` (`app.timesafari` in `capacitor.config.ts`) to Firebase iOS app and Xcode target |
| **APNs auth key** | Firebase Console → Project Settings → Cloud Messaging → upload **APNs Authentication Key** (.p8) or certificates |
| **Push Notifications** | Xcode target → **Signing & Capabilities** → **+ Capability** → **Push Notifications** |
| **Background Modes** | Enable **Remote notifications** (and any others required by your plugin docs) |
| **GoogleService-Info.plist** | Present in the iOS target if using Firebase iOS SDK paths in your build |
| **FCM token** | Confirm **Register Token Now** succeeds in the debug panel and ngrok shows `POST /notifications/register` |
Silent/data pushes used for wake typically use a **content-available** style payload; confirm **notification-wakeup-service** and Firebase message format. The app logs `WAKEUP_PING` as ignored and does not refresh.
---
## 8. iOS-specific testing notes
### Physical device required
- APNs silent delivery and background wake behavior are **not** representative on the iOS Simulator.
- Always validate on a plugged-in or trusted wireless device with a development provisioning profile.
### Silent push is best-effort
- iOS may **delay or coalesce** background pushes, especially on battery saver or under load.
- A successful `/debug/send-wakeup` from the server does not guarantee immediate app wake.
### Force-quit limitations
- If the user **swipes the app away** from the app switcher, iOS often **will not** deliver background notifications until the user launches the app again.
- Test with the app **backgrounded** (home button / gesture), not force-quit, when validating wake.
### Low Power Mode and Focus
- **Low Power Mode** can reduce background execution.
- **Focus / Do Not Disturb** may affect notification presentation (separate from silent data wake, but confusing during tests).
### Send Real WAKEUP_PING (FCM/APNs diagnostic)
**Send Real WAKEUP_PING** posts `/debug/send-wakeup`. Delivery is confirmed by `push handler ignored type=WAKEUP_PING`. Mock refresh, Simulate WAKEUP_PING, and Wakeup Ping Simulator were removed.
---
## 9. Recommended debug workflow
1. Start **notification-wakeup-service** on the Mac.
2. Start **ngrok** and copy the HTTPS URL.
3. Set URL + **Test Mode** in the Notification Debug Panel; confirm **Backend Status**.
4. Tap **Register Token Now** → confirm ngrok request and `[Notifications] Token registration success`.
5. From the backend, call **`/debug/send-wakeup`** (see curl below) with the registered `deviceId` / FCM token as required by that service, or tap **Send Real WAKEUP_PING**.
6. Watch **Xcode console** for `[Notifications] push handler ignored type=WAKEUP_PING`.
7. Open **ngrok inspect UI** (`http://127.0.0.1:4040`) to correlate requests (register and send-wakeup; not app-initiated refresh).
8. Use **Pending Notification Inspector** for Daily Reminder / dual / fetcher schedules.
---
## 10. Sample curl commands
Set your tunnel base URL:
```bash
export BASE="https://abc123.ngrok-free.app"
```
### Health
```bash
curl -sS -w "\nHTTP %{http_code}\n" "$BASE/health"
```
### Register device (mirror app payload)
```bash
curl -sS -X POST "$BASE/notifications/register" \
-H "Content-Type: application/json" \
-d '{
"deviceId": "00000000-0000-4000-8000-000000000001",
"fcmToken": "YOUR_FCM_TOKEN_FROM_DEBUG_PANEL",
"platform": "ios",
"testMode": true
}'
```
### Refresh (backend only; app does not consume)
```bash
curl -sS -X POST "$BASE/notifications/refresh" \
-H "Content-Type: application/json" \
-d '{
"platform": "ios",
"testMode": true
}'
```
This exercises **notification-wakeup-service** only. The app does **not** call `applyNotificationRefreshPayload` or schedule `api_*` from the response.
### Send wakeup push (debug)
Exact path and body depend on **notification-wakeup-service**; typical pattern:
```bash
curl -sS -X POST "$BASE/debug/send-wakeup" \
-H "Content-Type: application/json" \
-d '{
"deviceId": "00000000-0000-4000-8000-000000000001",
"testMode": true
}'
```
Confirm parameters (token vs deviceId, auth headers) in that repo’s README or OpenAPI spec.
---
## 11. Troubleshooting
### Refresh endpoint unreachable
| Symptom | Checks |
|---------|--------|
| Mac `curl` of `/notifications/refresh` fails | ngrok running? URL saved without typo/trailing slash? |
| HTTP 404 | Tunnel port matches backend `PORT`; path is `/notifications/refresh` (backend route; the app does not call it) |
| CORS (web only) | Native Capacitor fetch usually avoids browser CORS; if testing in Safari PWA, configure CORS on the service |
| ngrok browser warning | Free tier may show an interstitial for browser clients; native `fetch` from the app is usually unaffected |
### Token registration failures
- Push permission granted on the device?
- Firebase `VITE_FIREBASE_*` env vars baked into the build?
- `[Notifications] Token registration failure` in Xcode — read HTTP status in ngrok inspect
- Duplicate token skip: panel may show “skipped (duplicate)”; use **Register Token Now** to force re-register
### Silent push not waking the app
- App **backgrounded**, not force-quit
- Physical device, correct provisioning profile
- APNs key uploaded to Firebase; bundle ID matches
- FCM message includes `data.type = "WAKEUP_PING"` (logged as ignored in `NativeNotificationService.ts`)
- Server actually sent to the **same** FCM token shown in the debug panel
- Wait 30–120s — delivery is not instant
- Confirm Xcode shows `push handler ignored type=WAKEUP_PING` (there is no Simulate WAKEUP_PING / refresh API in the app)
### Notifications duplicating
- Daily Reminder vs New Activity both scheduling — see `doc/notification-new-activity-lay-of-the-land.md`
- Leftover `api_*` before Phase 4 cleanup (startup `clearApiNotifications()`)
### Stale ngrok URL
- After restarting ngrok, update **Notification Backend URL** in the panel and tap **Save**
- Or clear override (empty field + Save) only if you intend to hit `DEFAULT_NOTIFY_API_SERVER` again
### Plugin / JWT errors after refresh
- Refresh calls `configureNativeFetcherIfReady()` before scheduling — ensure an **active DID** and endorser API settings exist in the app DB
- See `doc/notification-from-api-call.md` and `nativeFetcherConfig.ts`
---
## 12. Key source files (crowd-funder-for-time-pwa)
| File | Purpose |
|------|---------|
| `src/services/notifications/NotificationDebugConfig.ts` | Backend URL, testMode, and bypassAuth overrides |
| `src/services/notifications/NotificationDebugEvents.ts` | Panel event log + `logNotification()` |
| `src/services/notifications/notificationLog.ts` | Structured log helpers |
| `src/services/notifications/NotificationService.ts` | `POST /notifications/register` |
| `src/services/notifications/NativeNotificationService.ts` | Push delivery hook (logs ignored types; no refresh) |
| `src/services/notifications/firebaseMessagingClient.ts` | Capacitor push listeners |
| `src/components/dev/NotificationDebugPanel.vue` | Dev UI |
| `src/main.capacitor.ts` | Native push init at startup |
---
## 13. Related docs
- [notification-debug-panel.md](./notification-debug-panel.md) — panel controls, authentication, troubleshooting
- [Notification Debug Panel (README)](../README.md#notification-debug-panel-dev-builds)
- [notification-system-overview.md](./notification-system-overview.md)
- [notification-from-api-call.md](./notification-from-api-call.md)
- [notification-new-activity-lay-of-the-land.md](./notification-new-activity-lay-of-the-land.md)
- [BUILDING.md](../BUILDING.md) — iOS build commands
For plugin-native behavior (exact alarm, iOS pending inspector), see **daily-notification-plugin** documentation. For FCM payload format and `/debug/send-wakeup` contract, see **notification-wakeup-service**.
@@ -0,0 +1,158 @@
# New Activity Notifications: iOS Parity with Android
**Purpose:** Describe what is required for **iOS** to match **Android** for the daily-notification-plugin **API-driven “New Activity”** flow (`scheduleDualNotification` / `cancelDualSchedule`, with prefetch and Endorser-backed content). The canonical product behavior is documented in `doc/notification-from-api-call.md` and `doc/notification-new-activity-lay-of-the-land.md`.
**Plugin source of truth:** The Capacitor package is `@timesafari/daily-notification-plugin`, pulled from the official remote in `package.json` (`git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git`). Plugin development happens in that repository; this app bumps the dependency and runs `npm install` / `npx cap sync` after releases.
---
## 1. What “parity” means here
| Concern | Intended behavior |
|--------|---------------------|
| **Scheduling** | Dual schedule: prefetch job **before** notify time (app uses cron T−5 minutes), then user-visible notification at the chosen time. |
| **API content** | Prefetch calls the **same Endorser semantics** as the Android host: **`plansLastUpdatedBetween`** (POST) with **starred plan IDs**, JWT auth, aggregated titles/bodies consistent with `TimeSafariNativeFetcher`. |
| **Starred plans** | `updateStarredPlans({ planIds })` from the app must affect what the native prefetch queries. |
| **Configure** | `configureNativeFetcher({ apiBaseUrl, activeDid, jwtToken, … })` supplies credentials the native layer uses for prefetch. |
| **Lifecycle** | `cancelDualSchedule()` removes the dual prefetch + notify schedule without breaking the separate Daily Reminder. |
Platform differences (iOS **BGTaskScheduler** is opportunistic; Android **alarms/WorkManager** can be more exact) mean **timing** may never be identical, but **API behavior and user-visible copy** should align.
---
## 2. Current state: Android (this app)
- **Host native fetcher:** `android/.../TimeSafariNativeFetcher.java` implements the plugin’s `NativeNotificationContentFetcher` and calls **`POST …/api/v2/report/plansLastUpdatedBetween`** using starred plan IDs (via plugin storage from `updateStarredPlans`).
- **Registration:** `MainActivity` calls `DailyNotificationPlugin.setNativeFetcher(new TimeSafariNativeFetcher(this))`.
- **Plugin (Android) — older notes:** Prior dual-schedule issues (native fetcher / fetch cron) are addressed in **plugin ≥ 3.0.0** (chained dual: notify after prefetch). Historical analysis: `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md`.
---
## 3. Current state: iOS (this app + bundled plugin)
### 3.1 This repository
- **iOS native fetcher:** `ios/App/App/TimeSafariNativeFetcher.swift` implements `NativeNotificationContentFetcher` (Endorser `plansLastUpdatedBetween`, same prefs keys as Java). **`AppDelegate`** calls `DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)` at launch **before** any `configureNativeFetcher` from JS (see plugin `doc/CONSUMING_APP_HANDOFF_IOS_NATIVE_FETCHER_AND_CHAINED_DUAL.md` and **`doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md`**).
- **JS/TS is already shared:** `nativeFetcherConfig.ts`, `dualScheduleConfig.ts`, `syncStarredPlansToNativePlugin.ts`, and `AccountViewView.vue` call the same APIs on both platforms.
- **Info.plist** already lists `UIBackgroundModes` (fetch, processing) and `BGTaskSchedulerPermittedIdentifiers` for the plugin’s task IDs. Xcode **Signing & Capabilities** should still enable **Background fetch** and **Background processing** (see `doc/daily-notification-plugin-integration.md`).
- **AppDelegate** posts `DailyNotificationDelivered` for foreground presentation—aligned with plugin rollover behavior.
### 3.2 Bundled plugin (`node_modules/@timesafari/daily-notification-plugin`, iOS)
Requires **plugin ≥ 3.0.0** (register native fetcher, chained dual, iOS `updateStarredPlans`). Version pinned in `ios/App/Podfile.lock` after `pod install`.
- **`scheduleDualNotification` / `cancelDualSchedule`** — see plugin release notes; clean sync + `pod install` if you see `UNIMPLEMENTED` (`doc/plugin-feedback-ios-scheduleDualNotification.md`).
- **`configureNativeFetcher`** — **requires** `DailyNotificationPlugin.registerNativeFetcher` first; the host Swift fetcher performs **`plansLastUpdatedBetween`** (plugin does not use in-plugin `offers` GET when a fetcher is registered—mirrors Android).
- **`updateStarredPlans`** — implemented on iOS in current plugin; persists **`daily_notification_timesafari.starredPlanIds`** for the host fetcher.
- **Chained dual** — user notification is armed **after** prefetch for that cycle (plugin); iOS remains subject to BG scheduling limits; see **§3.3**.
### 3.3 Prefetch before notify (ordering, not cron)
iOS has no system cron; the app/plugin may still **parse** cron to compute “next run” times. The hard part is **ordering**: if **prefetch** is driven by **`BGTaskScheduler`** (opportunistic) and **notify** by **`UNUserNotificationCenter`** at a fixed time **T**, those are **independent**. The OS can deliver the local notification at **T** while prefetch runs **after** **T** or not at all—so the awkward case (notify first, prefetch later, stale or fallback content) **can** happen. Two peer timers do **not** imply “fetch always completes before **T**.”
To **enforce** prefetch-before-notify as a rule, use **chaining**, not two unrelated schedules:
- After prefetch for that cycle **finishes** (success or explicit timeout policy), **then** schedule or **replace** the pending `UNNotificationRequest` for time **T** with the resolved title/body (or fallback). Until then, do not arm a user-visible notification that claims fresh API content.
- **Tradeoffs:** If prefetch is late, the notification may be **late**; if prefetch never runs before a deadline, use **fallback** copy at **T** or skip—product choice.
- **Parsing cron** remains useful to compute **T** and to decide when to **submit** BG work; **ordering** is a **pipeline** decision (fetch → cache → arm notify), not “BG at T−5 and UN at **T** both scheduled up front.”
Plugin work item **§4A.3** should reflect this: document the chosen strategy (chained arm vs best-effort dual timer) and how it interacts with `relationship.contentTimeout` / fallback.
---
## 4. Work breakdown
### 4A. Plugin (`daily-notification-plugin`) — status (v3.x)
Items below were the original gap list; **plugin ≥ 3.0.0** ships **iOS** `updateStarredPlans`, **`registerNativeFetcher`**, **chained dual** on iOS and Android, and Android dual-path fixes. Remaining work is **release coordination** (bump, sync, QA), not greenfield plugin implementation.
1. **`updateStarredPlans` on iOS** — shipped in current plugin.
2. **iOS `plansLastUpdatedBetween` / host fetcher** — shipped: host registers **`TimeSafariNativeFetcher`** (Swift); plugin does not duplicate Endorser logic when a fetcher is registered.
3. **Dual schedule / chaining** — shipped (notify after prefetch; see plugin release notes and **§3.3**).
4. **Android dual path** — chained dual + native fetcher alignment in current plugin (see `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` for historical context).
5. **JWT pool / expiry (Phase B)**
- **App:** Phase B is already implemented: `configureNativeFetcherIfReady()` passes `jwtTokens` from `mintBackgroundJwtTokenPool` on **both** iOS and Android (`src/services/notifications/nativeFetcherConfig.ts`).
- **Android:** `TimeSafariNativeFetcher` selects a bearer from the pool for background requests (`doc/plugin-feedback-daily-notification-configureNativeFetcher-jwt-pool.md`).
- **iOS:** The bundled plugin’s `configureNativeFetcher` **already accepts and persists** `jwtTokens` / `jwtTokenPoolJson`, and the in-plugin fetch path uses a bearer from the primary token or pool. What is **not** yet at parity with Android is **which API** that token is used for (`offers` GET vs `plansLastUpdatedBetween` + starred plans)—that falls under **§4A.2**, not “waiting for Phase B on iOS.”
- **Expiry:** Re-calling `configureNativeFetcherIfReady` on foreground / Account (see `notification-from-api-call.md`) remains relevant on both platforms.
### 4B. This app (crowd-funder-for-time-pwa) — after or alongside plugin changes
1. **Bump `@timesafari/daily-notification-plugin`** to **≥ 3.0.0** via the git dependency in `package.json`, run `npm install`, `npx cap sync ios`, `cd ios/App && pod install`, clean build (`doc/plugin-feedback-ios-scheduleDualNotification.md`, **`doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md`**).
2. **iOS native fetcher** — **Done:** `TimeSafariNativeFetcher.swift` + `registerNativeFetcher` in `AppDelegate` (see handoff doc).
3. **Re-test** `syncStarredPlansToNativePlugin` on iOS; the helper may still catch `UNIMPLEMENTED` for older plugin binaries.
4. **Xcode:** Confirm Background Modes capabilities match `Info.plist`.
5. **QA:** Full matrix in `doc/notification-from-api-call.md` (enable/disable, empty starred list, JWT expiry, foreground/background); chained dual timing (notify after prefetch).
### 4C. Related product bug (both platforms)
- **`PushNotificationPermission.vue` vs New Activity:** Enabling New Activity can still schedule the **single** daily reminder by mistake; turning New Activity off may not cancel that reminder. See `doc/notification-new-activity-lay-of-the-land.md`. Fixing this is orthogonal to iOS/Android API parity but affects perceived “notifications behavior.”
---
## 5. Reference map (this repo)
| Topic | Document |
|-------|-----------|
| Plugin post-bump handoff (iOS fetcher + chained dual) | `doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md` |
| Feature plan & file list | `doc/notification-from-api-call.md` |
| Dual vs Daily Reminder confusion | `doc/notification-new-activity-lay-of-the-land.md` |
| iOS `UNIMPLEMENTED` / PluginHeaders | `doc/plugin-feedback-ios-scheduleDualNotification.md` |
| Android dual schedule + native fetcher | `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` |
| Integration & Xcode | `doc/daily-notification-plugin-integration.md` |
| Android host fetcher | `android/.../TimeSafariNativeFetcher.java`, `MainActivity.java` |
---
## 6. Handoff to plugin repo (Cursor / isolated workspace)
Use this section when **daily-notification-plugin** is open **without** the TimeSafari app tree, so implementers do not depend on paths that only exist in crowd-funder-for-time-pwa.
### 6.1 Bring reference material into scope
| Source (this app repo) | Why |
|------------------------|-----|
| `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` | **Canonical Endorser behavior** for New Activity: POST body, pagination, aggregation copy, prefs keys for starred IDs and `last_acked_jwt_id`. Copy or open alongside the plugin when implementing iOS fetch or `setNativeFetcher`. |
| `src/services/notifications/dualScheduleConfig.ts` | Shape the app sends to `scheduleDualNotification` (`buildDualScheduleConfig`). |
| `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` | Android plugin: dual path must call native fetcher at fetch cron. |
| `doc/plugin-feedback-ios-scheduleDualNotification.md` | iOS `UNIMPLEMENTED` / PluginHeaders troubleshooting. |
In the plugin repo itself, align with **`src/definitions.ts`** (`DualScheduleConfiguration`, `configureNativeFetcher`, `updateStarredPlans`) and **INTEGRATION_GUIDE** if present.
### 6.2 HTTP / storage contract (match `TimeSafariNativeFetcher`)
Implementations on **iOS** (in-plugin Swift or host `NativeNotificationContentFetcher`) should match this **unless** product explicitly changes:
- **Method & path:** `POST` `{apiBaseUrl}/api/v2/report/plansLastUpdatedBetween` (no trailing slash mismatch on `apiBaseUrl`).
- **Headers:** `Content-Type: application/json`, `Authorization: Bearer {token}` (token from `jwtToken` or **JWT pool** selection—see Java `selectBearerTokenForRequest`: UTC day mod pool size).
- **JSON body:** `planIds` (array of strings, possibly empty), `afterId` (string; use `"0"` if none stored).
- **Starred plans:** Android: SharedPreferences **`daily_notification_timesafari`** + key **`starredPlanIds`**. iOS (plugin + host): `UserDefaults.standard` key **`daily_notification_timesafari.starredPlanIds`** (JSON array string).
- **Pagination:** After a successful response with non-empty `data`, update **`last_acked_jwt_id`** from the last row’s `jwtId` (item or nested `plan.jwtId`)—see Java `updateLastAckedJwtIdFromResponse`. iOS host (`TimeSafariNativeFetcher.swift`) persists **`daily_notification_timesafari.last_acked_jwt_id`** in `UserDefaults.standard`.
- **Empty `data`:** Return **no** notification items (empty list); do not synthesize a “no updates” push from an empty result—Java returns empty `contents` when `data` is absent or empty.
- **Non-empty `data`:** One aggregated `NotificationContent`: titles **Starred Project Update** / **Starred Project Updates**, bodies use typographic quotes around first project name and **has been updated.** / **+ N more have been updated.** (see Java `parseApiResponse`).
### 6.3 Likely plugin touchpoints (maintenance / debugging)
- **iOS:** `ios/Plugin/DailyNotificationPlugin.swift`, `DailyNotificationScheduleHelper.swift`, native fetcher registry, BG / UN paths.
- **Android:** `DailyNotificationPlugin.kt`, fetch workers / `ScheduleHelper`—see dual-schedule feedback doc for history.
### 6.4 Suggested order (plugin shipped ≥ 3.0.0)
1. Tag / publish **`@timesafari/daily-notification-plugin`**.
2. **Consuming app:** bump, `npm install`, `npx cap sync`, `pod install`, QA (`doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md`).
---
## 7. Acceptance checklist (iOS vs Android product intent)
- [ ] Prefetch uses **plansLastUpdatedBetween** (or host fetcher with identical behavior), not only `offers` GET.
- [ ] **Starred plan IDs** from settings change what is queried (`updateStarredPlans` works on iOS).
- [ ] Notification title/body match the **same rules** as Android for “starred project updates” (including empty updates).
- [ ] `configureNativeFetcher` + JWT refresh story documented; re-config on foreground if needed (`notification-from-api-call.md`).
- [ ] `cancelDualSchedule` clears dual prefetch/notify without leaving orphan schedules.
- [ ] Understand and document **iOS timing** limitations vs Android for support/Help copy.
- [ ] **Prefetch vs notify ordering** on iOS: chosen strategy (chained arm vs independent BG + UN) documented; avoids claiming fresh API content when prefetch has not run yet (**§3.3**).
+229
View File
@@ -0,0 +1,229 @@
# Notification Debug Panel
**Created:** 2026-07-07
**Updated:** 2026-09-24
**Audience:** Developers testing notification registration, AlertSearch authorization upload, and FCM delivery diagnostics on native (iOS/Android) dev builds.
The **Notification Debug Panel** is a dev-only UI for FCM token registration, AlertSearch authorization upload, FCM wakeup delivery diagnostics (`/debug/send-wakeup`), and local schedule inspection. It does not schedule notifications from `WAKEUP_PING`. The production `WAKEUP_PING` → `/notifications/refresh` → `api_*` path was retired; leftover `api_*` schedules are cleared once at startup (Phase 4).
---
## Notification API base URL
Notification HTTP calls (`/notifications/register`, `/notifications/alert-authorization`, `/debug/send-wakeup`, etc.) do **not** use `APP_SERVER`. They use a dedicated Notification API host, resolved at runtime by `getNotificationApiBaseUrl()` in `NotificationDebugConfig.ts`. The app does not call `/notifications/refresh`.
### Configuration constants
| Symbol | Location | Purpose |
|--------|----------|---------|
| `VITE_DEFAULT_NOTIFY_API_SERVER` | `.env.development` / `.env.test` / `.env.production` | Build-time default Notification API URL for that Vite mode (same pattern as other `VITE_DEFAULT_*` backends) |
| `DEFAULT_NOTIFY_API_SERVER` | `src/constants/app.ts` | Runtime constant: `import.meta.env.VITE_DEFAULT_NOTIFY_API_SERVER \|\| AppString.PROD_NOTIFY_API_SERVER` |
| `AppString.PROD_NOTIFY_API_SERVER` | `src/constants/app.ts` | Hardcoded production fallback: `https://notify-api.timesafari.app` |
| `AppString.TEST_NOTIFY_API_SERVER` | `src/constants/app.ts` | Hardcoded test host: `https://test-notify-api.timesafari.app` (for explicit UI/debug use; not the automatic fallback) |
Production, test, and development builds get different Notification API URLs from their respective `.env.*` files. Runtime request code always goes through `DEFAULT_NOTIFY_API_SERVER` (via `getNotificationApiBaseUrl()`), not by reading the env var directly at each call site.
Typical values today:
| Build / env file | `VITE_DEFAULT_NOTIFY_API_SERVER` |
|------------------|----------------------------------|
| `.env.production` | `https://notify-api.timesafari.app` |
| `.env.test` | `https://test-notify-api.timesafari.app` |
| `.env.development` | `https://test-notify-api.timesafari.app` |
### URL resolution order
`getNotificationApiBaseUrl()` selects the base URL in this order:
1. **Debug Panel backend override** — `localStorage` key `notificationDebug.backendBaseUrl` (set via **Save Backend URL** or `setBackendBaseUrl()`)
2. **`VITE_DEFAULT_NOTIFY_API_SERVER`** — baked into the build as part of `DEFAULT_NOTIFY_API_SERVER`
3. **`AppString.PROD_NOTIFY_API_SERVER`** — hardcoded fallback when the env var is unset (`https://notify-api.timesafari.app`)
Clearing the Debug Panel override (empty field + Save) returns the app to step 2 / 3 (`DEFAULT_NOTIFY_API_SERVER`). The override never changes auth behavior by itself.
`APP_SERVER` / `VITE_APP_SERVER` remain for deep links and the main app web host only — not for notification API traffic.
---
## Access
1. Use a **non-production** build (for example `build:android:dev`, `build:ios:dev`, or `vite dev` with a non-`production` mode).
2. Open **Account** → enable **Show All General Advanced Functions**.
3. Open **Notification Debug Panel** (route `/dev/notifications`).
On native platforms, grant notification permission when prompted so FCM token registration and the debug actions work.
---
## Configuration (Backend Testing)
Settings persist in `localStorage` via `NotificationDebugConfig.ts`:
| Key | Default | Purpose |
|-----|---------|---------|
| `notificationDebug.backendBaseUrl` | *(unset — use `DEFAULT_NOTIFY_API_SERVER`)* | Override which notification server receives API calls |
| `notificationDebug.testMode` | `true` | Sent in JSON request bodies (`testMode: true/false`) |
| `notificationDebug.bypassAuth` | `false` | When `true`, omit JWT `Authorization` headers on notification API calls |
All notification API requests (`/notifications/register`, `/notifications/alert-authorization`, `/debug/send-wakeup`, etc.) obtain headers through `getNotificationApiHeaders()` in `notificationApiAuth.ts`.
### Notification Backend URL
Paste a base URL (no trailing slash) and tap **Save Backend URL**. This changes **only** which server the app calls (`getNotificationApiBaseUrl()`). It does **not** disable JWT authentication.
Leave empty to use the configured build default (`DEFAULT_NOTIFY_API_SERVER`, from `VITE_DEFAULT_NOTIFY_API_SERVER` or `AppString.PROD_NOTIFY_API_SERVER`). The Debug Panel override still wins whenever a non-empty URL is saved.
### Test Mode
When enabled (default if never saved), register and send-wakeup requests include `"testMode": true` in the JSON body. The backend can use this to route test traffic separately from production.
Test Mode is **independent of authentication**. It does not control whether `Authorization` headers are sent.
### Skip JWT Authentication (Local Development Only)
When **off** (default), the app resolves the active DID and sends `Authorization: Bearer …` on notification API calls.
When **on**, requests include only `Content-Type: application/json` — for local servers (localhost or ngrok) that intentionally accept unauthenticated notification requests during development.
Enable this **only** for local development backends that do not require JWT. Hosted shared test servers that require normal app authentication should leave this **off**.
The panel **Backend Status** section shows the active URL, `testMode`, and `bypassAuth` values.
---
## Recommended settings
### Hosted test server
Example: `https://test-notify-api.timesafari.app`
On development and test builds, this host is already the default via `VITE_DEFAULT_NOTIFY_API_SERVER`. You can leave **Notification Backend URL** empty, or paste the same URL explicitly.
| Setting | Value |
|---------|-------|
| **Notification Backend URL** | Empty (use default) or `https://test-notify-api.timesafari.app` |
| **Test Mode** | **ON** (if the server expects `testMode: true`) |
| **Skip JWT Authentication** | **OFF** |
Ensure the app has an **active identity (DID)** with a valid endorser session so JWT headers can be built.
### Local localhost / ngrok development
Example: `https://abc123.ngrok-free.app` or `http://127.0.0.1:3000`
| Setting | Value |
|---------|-------|
| **Notification Backend URL** | Your local or ngrok URL |
| **Test Mode** | **ON** or **OFF** — match what your local **notification-wakeup-service** expects |
| **Skip JWT Authentication** | **ON** only if the local server accepts unauthenticated requests; **OFF** if it validates JWT like production |
---
## Backend Testing actions
| Action | What it does |
|--------|----------------|
| **Register Token Now** | `POST {backend}/notifications/register` with current FCM token, `deviceId`, `platform`, and `testMode`. Forces re-registration (bypasses duplicate-token skip). |
| **Upload AlertSearch Authorization** | Mints and uploads delegated AlertSearch JWTs (`POST /notifications/alert-authorization`). Requires an active `did:ethr` identity; Test Mode is not used. |
| **Send Real WAKEUP_PING** | `POST {backend}/debug/send-wakeup`; server sends a real FCM data message with `data.type = "WAKEUP_PING"`. FCM delivery diagnostic only — the app logs `push handler ignored type=…` and does **not** call `/notifications/refresh` or schedule `api_*` notifications. Background the app before expecting delivery. |
**Current FCM Token** displays the last token from Capacitor/Firebase registration. **Event Log** shows the last 100 `[Notifications]` messages (also visible in logcat / Xcode console on native).
---
## Other panel sections
| Section | Purpose |
|---------|---------|
| **Pending Notification Inspector** | Lists locally scheduled notifications (Daily Reminder, New Activity / dual, and any leftover `api_*` until Phase 4 cleanup). |
| **Clear Notifications** | Clears/cancels plugin-scheduled notifications on native. Does not replace the one-time `api_*` startup cleanup. |
---
## Programmatic override (optional)
From a WebView dev console (`chrome://inspect` on Android, Safari Web Inspector on iOS):
```javascript
import {
setBackendBaseUrl,
setTestMode,
setBypassAuth,
getNotificationApiBaseUrl,
} from "@/services/notifications";
setBackendBaseUrl("https://abc123.ngrok-free.app");
setTestMode(true);
setBypassAuth(true); // local dev only
getNotificationApiBaseUrl();
```
---
## Troubleshooting
### 401 Unauthorized (`registerToken failed: unauthorized`)
**Likely causes:** JWT required but **Skip JWT Authentication** is off and the session is missing or expired; or JWT sent but the server rejected it.
**Checks:**
1. Panel **Backend Status** → `bypassAuth: false` for hosted servers.
2. App has an active DID and endorser login.
3. Event Log: look for `Using authenticated notification request` vs `Using debug unauthenticated notification request`.
4. For hosted test server: keep **Skip JWT Authentication** **OFF**.
**Fixes:** Sign in / restore identity; refresh endorser session; for local ngrok without JWT support, enable **Skip JWT Authentication**.
### `registerToken auth unavailable` / `Waiting for auth before registration`
The app deferred registration because JWT could not be built (no active DID or empty token) and **Skip JWT Authentication** is **off**.
**Fixes:** Complete identity setup in the app, or enable **Skip JWT Authentication** only for an intentionally unauthenticated local backend.
### Failed to fetch / network error
**Likely causes:** Backend down, wrong URL, stale ngrok tunnel, device offline, or TLS/certificate issues.
**Checks:** Panel **Backend Status** URL; `curl -sS "$URL/health"` from your machine; ngrok inspect UI for incoming requests.
**Fixes:** Restart backend and ngrok; **Save Backend URL** with the current HTTPS forwarding URL (no trailing slash).
### Backend unreachable / no requests in ngrok
Same as above. Confirm the **Active** URL in the panel matches your running tunnel or local server port.
### Register succeeds but Send Real WAKEUP_PING does not show delivery
**Real WAKEUP_PING success** only means the backend accepted the wakeup request and attempted FCM delivery. It does **not** schedule local `api_*` notifications. Delivery is confirmed when logcat / Event Log shows `push handler ignored type=WAKEUP_PING` (the retired refresh chain is gone).
**Checks:** App backgrounded (not force-stopped); FCM token matches registration; Firebase / Play services available.
See platform-specific guides for extended ngrok and FCM workflows:
- [local-android-testing-ngrok.md](./local-android-testing-ngrok.md)
- [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md)
---
## Key source files
| File | Purpose |
|------|---------|
| `src/constants/app.ts` | `DEFAULT_NOTIFY_API_SERVER`, `PROD_NOTIFY_API_SERVER`, `TEST_NOTIFY_API_SERVER` |
| `src/components/dev/NotificationDebugPanel.vue` | Dev UI |
| `src/services/notifications/NotificationDebugConfig.ts` | Base URL resolution, testMode, bypassAuth persistence |
| `src/services/notifications/notificationApiAuth.ts` | JWT vs unauthenticated headers |
| `src/services/notifications/notificationApiDebugMode.ts` | Auth bypass gate |
| `src/services/notifications/NotificationDebugService.ts` | Panel action handlers |
| `src/services/notifications/NotificationService.ts` | `POST /notifications/register` |
| `src/services/notifications/NativeNotificationService.ts` | Push delivery hook (logs ignored types; no refresh) |
---
## Related docs
- [notification-system-overview.md](./notification-system-overview.md)
- [notification-from-api-call.md](./notification-from-api-call.md)
- [local-android-testing-ngrok.md](./local-android-testing-ngrok.md)
- [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md)
+108
View File
@@ -0,0 +1,108 @@
# New Activity Notification (API-Driven Daily Message)
**Purpose:** Integrate the daily-notification-plugin’s second feature—the **daily, API-driven message**—into the crowd-funder (TimeSafari) app. The first feature (daily static reminder) is already integrated; this document covers the plan, completed work, and remaining tasks for the API-driven flow.
**References:**
- Plugin: `daily-notification-plugin` (INTEGRATION_GUIDE.md, definitions.ts)
- Alignment outline: `doc/daily-notification-alignment-outline.md`
- Help copy: `HelpNotificationTypesView.vue` (“New Activity Notifications”)
---
## Plan Summary
The API-driven flow:
1. **Prefetch** – Shortly before the user’s chosen time, the plugin runs a background job that calls the Endorser.ch API (e.g. `plansLastUpdatedBetween`, and optionally offers endpoints) using credentials supplied by the app.
2. **Cache** – Fetched content is stored in the plugin’s cache.
3. **Notify** – At the chosen time, the user sees a notification whose title/body come from that content (or a fallback).
The app must:
- **Configure the native fetcher** with `apiBaseUrl`, `activeDid`, and a JWT so the plugin’s background workers can call the API.
- **Implement the native fetcher** (or register an implementation) so the plugin can perform the actual HTTP requests and parse responses into notification content.
- **Sync starred plan IDs** to the plugin via `updateStarredPlans` so the fetcher knows which plans to query.
- **Expose UI** to enable/disable the “New Activity” notification and choose a time, and call `scheduleDualNotification` / `cancelDualSchedule` accordingly.
---
## Tasks Finished
- **Configure native fetcher on startup and identity**
- Added `configureNativeFetcherIfReady()` in `src/services/notifications/nativeFetcherConfig.ts` (reads `activeDid` and `apiServer` from DB, gets JWT via `getHeaders(did)`, calls `DailyNotification.configureNativeFetcher()`).
- Called from `main.capacitor.ts` after the 2s delay (with deep link registration).
- Called from `AccountViewView.initializeState()` when on native and `activeDid` is set; when New Activity is enabled, also calls `updateStarredPlans(settings.starredPlanHandleIds)`.
- **Implement real API calls in Android native fetcher**
- `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` implements `NativeNotificationContentFetcher`: POST to `/api/v2/report/plansLastUpdatedBetween` with `planIds` (from SharedPreferences `daily_notification_timesafari` / `starredPlanIds`) and `afterId`; when `data` is non-empty, builds **one** aggregated `NotificationContent` (title **Starred Project Update** or **Starred Project Updates**, body from `plan.name` with typographic quotes, then `has been updated.` or `+ N more have been updated.`); when `data` is empty, returns an empty list (no “no updates” notification); updates `last_acked_jwt_id` for pagination when content is returned.
- Registered in `MainActivity.onCreate()` via `DailyNotificationPlugin.setNativeFetcher(new TimeSafariNativeFetcher(this))`.
- **Sync starred plan IDs**
- Shared helper `syncStarredPlansToNativePlugin(planIds)` in `src/services/notifications/syncStarredPlansToNativePlugin.ts` (exported from `src/services/notifications/index.ts`) calls `DailyNotification.updateStarredPlans` on native only; ignores `UNIMPLEMENTED`.
- When user enables New Activity, `scheduleNewActivityDualNotification()` uses the helper with `settings.starredPlanHandleIds ?? []`.
- When Account view loads and New Activity is on, `initializeState()` uses the helper with the same list.
- When the user stars or unstars on a project (`ProjectViewView.toggleStar`), after a successful settings save, the helper runs if `notifyingNewActivityTime` is set so prefetch sees the current list without reopening Account.
- **Dual schedule config and scheduling**
- Added `src/services/notifications/dualScheduleConfig.ts`: `timeToCron()`, `timeToCronFiveMinutesBefore()`, `buildDualScheduleConfig({ notifyTime, title?, body? })` (contentFetch 5 min before, userNotification at chosen time).
- When user enables New Activity and picks a time, app calls `DailyNotification.scheduleDualNotification({ config })` with this config.
- When user disables New Activity, app calls `DailyNotification.cancelDualSchedule()`.
- **UI for New Activity notification**
- Unhid the “New Activity Notification” block in `AccountViewView.vue` (toggle + accessibility).
- Enable flow: time dialog → save settings → on native, `scheduleNewActivityDualNotification(timeText)` (configure fetcher, updateStarredPlans, scheduleDualNotification).
- Disable flow: on native, `cancelDualSchedule()` then save and clear settings.
- Added `starredPlanHandleIds` to `AccountSettings` in `interfaces/accountView.ts`.
- **Exports**
- `src/services/notifications/index.ts` exports `configureNativeFetcherIfReady`, `syncStarredPlansToNativePlugin`, `buildDualScheduleConfig`, `timeToCron`, `timeToCronFiveMinutesBefore`, and `DualScheduleConfigInput`.
---
## Checklist of Remaining Tasks
### iOS
**Parity outline (API, starred plans, plugin vs app work):** See **`doc/new-activity-notifications-ios-android-parity.md`**.
- **Confirm iOS native fetcher / dual schedule**
Plugin exposes `configureNativeFetcher` on iOS. Confirm whether the plugin expects an iOS-specific native fetcher registration (similar to Android’s `setNativeFetcher`) and, if so, register a TimeSafari fetcher implementation for iOS so API-driven notifications work on iPhone.
- **Verify dual schedule on iOS**
Test `scheduleDualNotification` and `cancelDualSchedule` on iOS; ensure content fetch and user notification fire at the expected times and that foreground/background behavior matches expectations.
### Testing and hardening
- **Test full flow on Android**
Enable New Activity, set time, wait for prefetch and notification (or use a short rollover for testing). Confirm notification shows with API-derived or fallback content.
- **Test full flow on iOS**
Same as Android: enable, set time, verify prefetch and notification delivery and content.
- **Test with no starred plans**
Enable New Activity with empty `starredPlanHandleIds`; confirm no crash; the native fetcher returns no Endorser-derived items when there is nothing to query or no new rows (see `TimeSafariNativeFetcher`).
- **Test JWT expiry**
Ensure behavior when the token passed to `configureNativeFetcher` has expired (e.g. app in background for a long time); document or implement refresh (e.g. re-call `configureNativeFetcherIfReady` on foreground or when opening Account).
### Optional enhancements
- **Offers endpoints**
Extend `TimeSafariNativeFetcher` (and any iOS fetcher) to call offers endpoints (e.g. `offers`, `offersToPlansOwnedByMe`) and merge with project-update content for richer notifications.
- **Documentation**
Add a short “New Activity notifications” section to BUILDING.md or a user-facing help page describing how the feature works and how to troubleshoot (e.g. no notification, wrong content, JWT/API errors).
---
## File Reference
| Area | Files |
| ---------------------- | ----------------------------------------------------------------------- |
| Fetcher config | `src/services/notifications/nativeFetcherConfig.ts` |
| Starred list → plugin | `src/services/notifications/syncStarredPlansToNativePlugin.ts` |
| Dual schedule config | `src/services/notifications/dualScheduleConfig.ts` |
| Notification exports | `src/services/notifications/index.ts` |
| Startup | `src/main.capacitor.ts` |
| Account UI and flow | `src/views/AccountViewView.vue` |
| Project star / unstar | `src/views/ProjectViewView.vue` (`toggleStar`) |
| Settings type | `src/interfaces/accountView.ts` |
| Android native fetcher | `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` |
| Android registration | `android/app/src/main/java/app/timesafari/MainActivity.java` |
| iOS native fetcher | `ios/App/App/TimeSafariNativeFetcher.swift` |
| iOS registration | `ios/App/App/AppDelegate.swift` (`DailyNotificationPlugin.registerNativeFetcher`) |
| Plugin 3.x handoff | `doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md` |
@@ -0,0 +1,250 @@
# Lay of the Land: API-Driven Daily Message (New Activity) and Web-Push Confusion
**Purpose:** Shareable analysis of the New Activity (API-driven daily message) implementation and the root cause of “always fires / can’t be turned off.” For discussion with teammates.
**Related:** `doc/notification-from-api-call.md` (plan and progress), teammate note about web-push confusion and possibly removing that logic.
---
## 1. Two Separate Notification Features
There are **two** distinct native notification flows that both go through the same UI component:
| Feature | Plugin API | Purpose |
|--------|------------|--------|
| **Daily Reminder** | `scheduleDailyNotification` / `cancelDailyReminder` | Single daily alarm, static title/body (user’s message). |
| **New Activity** (API-driven) | `scheduleDualNotification` / `cancelDualSchedule` | Prefetch from API 5 min before, then notify at chosen time with API or fallback content. |
- **Daily Reminder** is driven from AccountViewView’s “Daily Reminder” toggle; on native it uses `NotificationService.getInstance().scheduleDailyNotification()` / `cancelDailyNotification()` (backed by `NativeNotificationService` and a single `reminderId`: `"daily_timesafari_reminder"`).
- **New Activity** is intended to be driven only by `scheduleNewActivityDualNotification()` / `cancelDualSchedule()` in AccountViewView (dual schedule only).
So: one feature = single schedule (reminder), the other = dual schedule (prefetch + notify). They are different plugin APIs and different lifecycle (enable/disable) handling.
---
## 2. Where the Bug Comes From: One Dialog, Two Behaviors
**New Activity** reuses the same dialog as Daily Reminder: **`PushNotificationPermission.vue`**.
- When the user turns **New Activity** on from AccountViewView:
- AccountViewView opens this dialog with `DAILY_CHECK_TITLE` and a callback that, on success, calls `scheduleNewActivityDualNotification(timeText)` on native.
- The dialog does **not** receive `skipSchedule: true` for this flow (only the “edit reminder” flow does).
So when the user clicks “Turn on Daily Reminder” in the dialog for **New Activity**:
1. **PushNotificationPermission** (native path) runs `turnOnNativeNotifications()` and always calls:
- `service.scheduleDailyNotification({ time, title: "Daily Check-In", body: "Time to check your TimeSafari activity", ... })`
- i.e. it schedules the **single** daily reminder (plugin’s `scheduleDailyNotification`), using the same `reminderId` as Daily Reminder (`"daily_timesafari_reminder"`).
2. Then the callback runs and AccountViewView calls **`scheduleNewActivityDualNotification(timeText)`**, which calls the plugin’s **`scheduleDualNotification`**.
Result:
- **Two schedules** are created when enabling New Activity:
- One **single** reminder (wrong for New Activity): static “Daily Check-In” message, same ID as Daily Reminder.
- One **dual** schedule (correct): prefetch + notify with API/fallback content.
- When the user turns **New Activity** off, AccountViewView only calls **`cancelDualSchedule()`**. It never calls `cancelDailyNotification()` (or equivalent) for the single reminder.
- So the **single** reminder stays scheduled and keeps firing at the chosen time. That’s the notification that “always fires” and “can’t be turned off.”
So the “huge problem with confusion with the web-push” is really: **the same dialog and the same “Turn on” path are used for both Daily Reminder and New Activity, but the dialog always schedules the single daily reminder on native**, while New Activity is supposed to use only the dual schedule. That mixing is what makes the wrong schedule stick and not be cancellable from the New Activity toggle.
---
## 3. Key Files and Flows
- **`src/components/PushNotificationPermission.vue`**
- Shared dialog for both “Daily Reminder” and “New Activity” (via `pushType` = `DIRECT_PUSH_TITLE` vs `DAILY_CHECK_TITLE`).
- On native it always uses `NotificationService.getInstance().scheduleDailyNotification(...)` (single reminder) and does not branch on “New Activity” to skip scheduling or to call the dual API.
- Saves `notifyingNewActivityTime` when `pushType === DAILY_CHECK_TITLE` (lines 834–836). So the dialog both schedules the wrong thing and persists settings for New Activity.
- **`src/views/AccountViewView.vue`**
- **Daily Reminder:** toggle opens same dialog with `DIRECT_PUSH_TITLE`; on native, disable path calls `service.cancelDailyNotification()`.
- **New Activity:** toggle opens same dialog with `DAILY_CHECK_TITLE`; on success callback calls `scheduleNewActivityDualNotification(timeText)`; on disable only calls `DailyNotification.cancelDualSchedule()`.
- `initializeState()`: on native with `activeDid`, calls `configureNativeFetcherIfReady(activeDid)` and, if New Activity is on, `updateStarredPlans(...)`. It does **not** re-call `scheduleNewActivityDualNotification` on load (so no double dual-schedule from here).
- **`src/services/notifications/NativeNotificationService.ts`**
- Single reminder only: `scheduleDailyNotification` → plugin `scheduleDailyNotification` with `id: this.reminderId` (`"daily_timesafari_reminder"`); `cancelDailyNotification` → `cancelDailyReminder({ reminderId })`. No dual API here.
- **`src/services/notifications/nativeFetcherConfig.ts`**
- Only configures the plugin for API calls (JWT, apiBaseUrl, activeDid). No scheduling.
- **`src/services/notifications/dualScheduleConfig.ts`**
- Builds config for `scheduleDualNotification` (contentFetch 5 min before, userNotification at notify time). Used only from AccountViewView’s `scheduleNewActivityDualNotification`.
- **`src/main.capacitor.ts`**
- Imports the daily-notification plugin; after a 2s delay calls `configureNativeFetcherIfReady()`. No scheduling; only fetcher config.
So: the “always fires / can’t turn off” behavior is from the **single** reminder created in `PushNotificationPermission` for New Activity and never cancelled when New Activity is turned off. The “confusion with web-push” is the reuse of the same dialog and the same native “schedule single reminder” path for both features.
---
## 4. Plugin Usage Summary
- **Single daily reminder (Daily Reminder):**
- Scheduled/cancelled via `NativeNotificationService.scheduleDailyNotification` / `cancelDailyNotification` → plugin `scheduleDailyNotification` / `cancelDailyReminder` with one `reminderId`.
- **Dual schedule (New Activity):**
- Scheduled/cancelled only in AccountViewView via `DailyNotification.scheduleDualNotification` / `cancelDualSchedule` (and `configureNativeFetcherIfReady` + `updateStarredPlans` as per doc).
- **Fetcher config (New Activity):**
- `configureNativeFetcherIfReady()` from main.capacitor and from AccountViewView `initializeState` / `scheduleNewActivityDualNotification`; no scheduling by itself.
---
## 5. Root Cause (Concise)
- **Single code path in PushNotificationPermission** for native: it always schedules the **single** daily reminder, regardless of `pushType` (Daily Reminder vs New Activity).
- For **New Activity**, that creates an extra, wrong schedule (single reminder) in addition to the correct dual schedule.
- **Disable path for New Activity** only calls `cancelDualSchedule()` and never cancels the single reminder, so that reminder keeps firing and appears as “always fires” and “can’t be turned off.”
---
## 6. Proper Fix: Options and Detail
A fix should ensure that (1) enabling New Activity creates only the dual schedule, and (2) disabling New Activity removes every schedule that was created for it. Below are concrete options and implementation notes.
### 6.1 Option A: Don’t schedule the single reminder when the dialog is for New Activity (recommended)
**Idea:** On native, when the dialog is opened for **New Activity** (`pushType === DAILY_CHECK_TITLE`), the dialog should **not** call `scheduleDailyNotification`. Only the callback in AccountViewView should run, and it already calls `scheduleNewActivityDualNotification(timeText)`, which uses the dual API only.
**Where:** `PushNotificationPermission.vue`, inside `turnOnNativeNotifications()`.
**Implementation sketch:**
- After requesting permissions and before calling `service.scheduleDailyNotification(...)`, branch on `pushType` and platform:
- If native **and** `pushType === this.DAILY_CHECK_TITLE`: skip the `scheduleDailyNotification` call entirely. Still run the rest of the flow (e.g. build `timeText`, save settings if desired, call `callback(true, timeText, ...)`). AccountViewView’s callback will then call `scheduleNewActivityDualNotification(timeText)` and that is the only schedule created for New Activity.
- Otherwise (web, or Daily Reminder on native): keep current behavior and call `scheduleDailyNotification` as today.
**Pros:** Single source of truth for “what is scheduled for New Activity” (dual only). No leftover single reminder to cancel later. Clear separation: dialog collects time + permission; AccountViewView owns native scheduling for New Activity.
**Cons:** Dialog’s native path now has two behaviors (schedule vs no schedule) depending on `pushType`; needs a quick comment so future changes don’t regress.
**Note:** The “edit reminder” flow already uses `skipSchedule: true` so the dialog doesn’t schedule; only the parent does. For New Activity enable, we’re doing the same idea: dialog doesn’t schedule on native, parent does.
### 6.2 Option B: When turning New Activity off, also cancel the single reminder
**Idea:** Assume the wrong single reminder might already exist (e.g. from before the fix, or from a different code path). When the user turns **New Activity** off, in addition to `cancelDualSchedule()`, call the service’s `cancelDailyNotification()` so the single reminder (same `reminderId` as Daily Reminder) is cancelled too.
**Where:** `AccountViewView.vue`, inside the disable branch of `showNewActivityNotificationChoice()` (where we currently only call `DailyNotification.cancelDualSchedule()`).
**Implementation sketch:**
- On native, when user confirms “turn off New Activity”:
1. Call `DailyNotification.cancelDualSchedule()` (existing).
2. Call `NotificationService.getInstance().cancelDailyNotification()` (new) so any single reminder that was mistakenly scheduled for this flow is removed.
**Pros:** Defensive: cleans up the bad schedule even if it was created in the past or by another path. Complements Option A (e.g. A prevents new wrong schedules; B cleans up existing ones).
**Cons:** That single `reminderId` is shared with **Daily Reminder**. If the user has **Daily Reminder** on and **New Activity** on, then turns only **New Activity** off, we must not cancel the reminder they still want for Daily Reminder. So either:
- Only call `cancelDailyNotification()` when we’re sure the single reminder was created for New Activity (e.g. we don’t have a separate “New Activity reminder ID”), which is hard without more state, or
- Don’t use Option B alone as the primary fix: use Option A so we never create the single reminder for New Activity, and only add B if we decide we need a one-time cleanup or a safety net (with care not to cancel Daily Reminder’s schedule).
**Recommendation:** Use Option A as the main fix. Add Option B only if the team agrees we need to cancel the single reminder on “New Activity off” and can do so without affecting Daily Reminder (e.g. by introducing a distinct reminder ID for a “New Activity legacy” reminder and only cancelling that, or by documenting that B is a one-time migration and not long-term behavior).
### 6.3 Optional cleanup: Separate reminder IDs or dialog responsibilities
- **Separate reminder IDs:** Today both Daily Reminder and the mistaken New Activity single reminder use `"daily_timesafari_reminder"`. If we ever want to support “both features on” and cancel only one, we’d need a second ID (e.g. one for Daily Reminder, one for New Activity). With Option A in place, New Activity no longer creates a single reminder, so we might not need a second ID unless we add a dedicated “New Activity fallback” single alarm later.
- **Dialog responsibilities:** We could narrow the dialog’s role when used for New Activity on native to “collect time + request permission and report success,” and leave all scheduling to AccountViewView. That’s what Option A does without necessarily refactoring the rest of the dialog (e.g. web push, Daily Reminder) in the same change.
- **Removing web-push logic for New Activity:** If the team decides to “totally remove” web-push logic that was added for New Activity, that would be a separate change (e.g. ensure New Activity on web either uses a different mechanism or is explicitly unsupported). The lay-of-the-land and this fix section focus on native; web can be scoped in a follow-up.
---
## 7. Testing New Activity on a Real Device (iOS or Android)
Use this section to verify the New Activity flow end-to-end on a physical device after implementing the fix (or to reproduce the current bug).
### Prerequisites
- **Build:** Native app built and installed (e.g. `npx cap sync` then build/run from Xcode or Android Studio), or a dev build on device.
- **Identity:** User is signed in (active DID set) so `configureNativeFetcherIfReady` and the native fetcher can use a valid JWT.
- **Endorser API URL:** New Activity prefetch uses **Account → API Server URL** (the Endorser base URL passed to `configureNativeFetcher`), not the Partner API URL. You can run these tests against **production, test, or local Endorser** (e.g. the test preset `https://test-api.endorser.ch`); use an identity, JWT, and starred plans that exist on **that** server. Changing only **Partner API** URL does not change where `plansLastUpdatedBetween` is called.
- **Optional:** One or more starred plans so the API can return activity; with zero starred plans the notification should still show with a sensible fallback (e.g. “No updates in your starred projects”).
### Enable flow
1. Open **Account** (Profile).
2. In the **Notifications** section, turn **New Activity Notification** on.
3. In the dialog, choose a time. For quick testing, set the device clock or pick a time **2–5 minutes from now** (e.g. if it’s 14:00, choose 14:03).
4. Tap **Turn on Daily Reminder** (or equivalent), grant notification permission when the OS prompts, and confirm the dialog closes and the toggle shows on with the chosen time.
5. **Background the app** (home or switch to another app). The prefetch runs ~5 minutes before the chosen time; the user notification fires at the chosen time.
### What to verify (after fix)
- **One notification** at the chosen time, with content from the API or the fallback text (e.g. “Check your starred projects and offers for updates.”). You should **not** see a second, static “Daily Check-In” / “Time to check your TimeSafari activity” notification from the old single-reminder path.
- **Before the fix:** You may see two notifications (one static from the mistaken single schedule, one from the dual schedule), and turning New Activity off will only stop the dual one; the static one will keep firing.
### Disable flow
1. On **Account**, turn **New Activity Notification** off and confirm in the “turn off” dialog.
2. Wait until the next occurrence of the previously chosen time (or use the same “time a few minutes ahead” trick and wait). **No notification** should appear. If one still appears, the single reminder was not cancelled (current bug or Option B not applied correctly).
### Device-specific notes
- **Android:** This app has **exact alarm disabled** (no `SCHEDULE_EXACT_ALARM`). Notification permission must be granted; delivery may be inexact or batched by the system. If the app is killed by the OS, behavior may depend on plugin boot/recovery behavior.
- **iOS:** Notification permission and background capabilities (e.g. background fetch) may affect prefetch. Test with app in background, not force-quit.
- **Time zone:** The chosen time is in the device’s local time. Ensure the device date/time and time zone are correct when testing.
### Optional test cases
- **No starred plans:** Enable New Activity with no starred projects; confirm no crash and a sensible fallback message in the notification.
- **JWT / API errors:** After leaving the app in background for a long time, the JWT may expire. Re-opening Account (or app) may re-run `configureNativeFetcherIfReady`; document or test whether a new notification still gets valid content or shows fallback.
- **Daily Reminder and New Activity both on:** With the fix, turning off only New Activity should not affect the Daily Reminder notification (they use different plugin APIs; Option B must not cancel the single reminder if the user still has Daily Reminder on).
### Testing: starred project with new activity (Android native fetcher)
Use this to verify that when a **starred** plan has **new** activity reported by `plansLastUpdatedBetween`, the notification shows API-derived copy (not only the dual-schedule default from `dualScheduleConfig.ts`).
The steps and expected notification copy below are **Android-specific**: this repo registers `TimeSafariNativeFetcher` only on Android today. Do not assume the same strings or behavior on iOS until native fetcher parity exists; see **`doc/notification-from-api-call.md`** (iOS checklist and remaining tasks).
**How it works (short):** On Android, `TimeSafariNativeFetcher` POSTs to `/api/v2/report/plansLastUpdatedBetween` with `planIds` from the plugin (`updateStarredPlans`) and `afterId` from stored `last_acked_jwt_id` (or `"0"` initially). When the response `data` array is **non-empty**, the fetcher builds **one** `NotificationContent`: title **Starred Project Update** (one row) or **Starred Project Updates** (two or more rows); body uses each row’s `plan.name` when present (else **Unnamed Project**). For a single update: `[name] has been updated.` For multiple: typographic quotes around the first row’s name, then ` + N more have been updated.` (with `N` = number of additional rows). When `data` is **empty**, the fetcher returns **no** notification items (no “nothing to report” notification). (See `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java`.)
**Procedure (repeatable on device)**
1. Sign in on the Endorser environment you mean to test (e.g. test API URL in Account—see **Prerequisites**, Endorser API URL) so `configureNativeFetcherIfReady` can set JWT and `activeDid`.
2. Star at least one project you can change (e.g. your own test plan on staging).
3. Turn **New Activity Notification** on and pick a time **2–5 minutes ahead** (same quick-test pattern as above).
4. Open **Account** once (or finish the enable flow) so `updateStarredPlans({ planIds })` runs with current `starredPlanHandleIds`.
5. **Background the app** (home out; do not force-quit). Prefetch runs on the cron **~5 minutes before** the chosen time; the user notification fires at the chosen time.
6. **Produce new activity the API will return:** before that prefetch window (i.e. early enough that the scheduled content fetch still sees it), make a real change to the starred plan so `plansLastUpdatedBetween` returns **new** rows after the current `afterId` (e.g. an edit or other update your backend exposes through that report). If you change the plan **after** prefetch already ran with no new rows, you may not get an API-derived notification until the next prefetch cycle (typically the next day at the same T−5 schedule, unless you reschedule).
**What to verify**
- **One notification** at the chosen time (no extra static “Daily Check-In” after the fix—see “What to verify (after fix)” above).
- **Success path (API returns updates):** Title/body match **Starred Project Update(s)** and the `[name] has been updated.` / `[first name] + N more have been updated.` patterns (names from `plan.name`), not the generic `buildDualScheduleConfig` defaults (**New Activity** / **Check your starred projects and offers for updates.**), which apply when the plugin falls back—e.g. fetch failure—not when the Android fetcher successfully returns Endorser-parsed content.
- **Contrast (cursor caught up, no new rows):** After a successful fetch that returned data, `last_acked_jwt_id` advances. Without further plan changes, a later prefetch may return an empty `data` array; the fetcher then supplies **no** Endorser-derived notification (useful to compare against the “has activity” case; the plugin may still show dual-schedule fallback text depending on configuration).
**Repeatability:** Each successful fetch that returns data moves the `afterId` cursor forward. To see **Starred Project Update** copy again on subsequent tests, make **another** qualifying plan change (or accept heavier setup such as clearing app/plugin storage to reset cursor—usually unnecessary).
**Debugging:** On Android, filter **logcat** for `TimeSafariNativeFetcher` (e.g. HTTP 200, `Fetched N notification(s)`) to confirm prefetch ran and how many `NotificationContent` items were built.
**Note:** The in-app **New Activity** screen loads starred changes via the JS stack; the **push** path uses the native fetcher and plugin cache. Validate the notification using **background + prefetch timing**, not only by opening that screen.
---
## 8. Plugin Repo Alignment and Attention Items
Comparison with the **daily-notification-plugin** repo on gitea (`trent_larson/daily-notification-plugin`, `master` or the tag this app pins) to confirm our documentation and usage line up, and to flag anything that needs attention for the New Activity feature.
### 8.1 What lines up
- **API surface:** Plugin `definitions.ts` exposes `configureNativeFetcher({ apiBaseUrl, activeDid, jwtToken })`, `scheduleDualNotification(config)`, `cancelDualSchedule()`, `updateStarredPlans({ planIds })`, `scheduleDailyNotification(options)`, and `cancelDailyReminder(reminderId)`. Our app uses these as described in this doc; `buildDualScheduleConfig` produces a `DualScheduleConfiguration` that matches the plugin’s `ContentFetchConfig` / `UserNotificationConfig` / `relationship` shape (cron schedules, title/body, `callbacks: {}`, `fallbackBehavior: "show_default"`, etc.).
- **Native fetcher:** Plugin is designed for a host-supplied JWT via `configureNativeFetcher` and a native fetcher implementation (e.g. Android `TimeSafariNativeFetcher`). Our `nativeFetcherConfig.ts` and Android `TimeSafariNativeFetcher.java` follow that model; prefetch runs in the plugin’s background workers and uses the configured credentials.
- **Dual vs single:** The plugin clearly separates:
- **Single daily path:** `scheduleDailyNotification(options)` (with `id` on Android) and `cancelDailyReminder(reminderId)` (iOS uses `reminder_<reminderId>` for the static-reminder path).
- **Dual path:** `scheduleDualNotification(config)` and `cancelDualSchedule()`.
So our analysis that “two schedules” are created when the dialog schedules the single reminder and AccountViewView schedules the dual is consistent with the plugin.
- **Exact alarm:** The plugin’s Android implementation does **not** require exact alarm: it proceeds with scheduling using inexact/windowed alarms when exact is not granted. The plugin’s `INTEGRATION_GUIDE.md` still shows `SCHEDULE_EXACT_ALARM` in the manifest example; this app has chosen to disable exact alarm, and the plugin supports that. No doc change needed beyond what we already state in section 7.
### 8.2 Attention items
- **`cancelDailyReminder` signature:** In the plugin’s `definitions.ts`, `cancelDailyReminder(reminderId: string)`. The app calls it with an object: `cancelDailyReminder({ reminderId })`. On iOS the plugin uses `call.getString("reminderId")`, so the object form works. If the plugin’s TypeScript definition is ever used for strict typing, prefer updating the plugin to accept `{ reminderId: string }` or document that the bridge accepts an object with a `reminderId` key.
- **Plugin INTEGRATION_GUIDE vs this app:** The guide describes generic polling, dual scheduling, and optional `SCHEDULE_EXACT_ALARM`. This app uses the dual-schedule + native-fetcher path only (no generic polling), and does not use exact alarm. When onboarding or debugging, treat the guide as the full plugin feature set; our flow is the “legacy dual scheduling” + native fetcher part plus `updateStarredPlans` and `configureNativeFetcher`.
- **iOS `scheduleDailyNotification` and stable `id`:** On **Android**, the plugin uses `options.getString("id")` as the stable `scheduleId` for “one per day” semantics and cleanup. On **iOS**, the implementation in the repo was observed to build notification content with an internally generated id (e.g. `daily_<timestamp>`) and not obviously use the app-provided `id` from the call. If the app ever relies on a stable id on iOS for the single reminder (e.g. to cancel or replace only that reminder), it’s worth confirming in the plugin’s iOS code whether the call’s `id` is read and used; if not, consider requesting or contributing a change so iOS also uses the app-provided id for consistency with Android.
- **Dual schedule and content fetch:** The plugin’s dual schedule runs the content-fetch job on its cron and then the user notification at the configured time; our config uses a 5-minute gap and `relationship.contentTimeout` / `fallbackBehavior: "show_default"`. The native fetcher is invoked by the plugin’s background layer when the content-fetch schedule fires; we don’t rely on JS `callbacks` in the config (we pass `callbacks: {}`). That matches the “native fetcher does the work” design.
### 8.3 iOS `UNIMPLEMENTED` on `scheduleDualNotification` (other methods work)
If iOS logs `scheduleNewActivityDualNotification failed: {"code":"UNIMPLEMENTED"}` while `configureNativeFetcher` succeeds, Capacitor is often rejecting the call in **JavaScript** because `scheduleDualNotification` is missing from `window.Capacitor.PluginHeaders` for `DailyNotification` (stale **Pods / Xcode binary** after upgrading the plugin). **Not** usually a missing Swift handler if `node_modules` already lists the method in `pluginMethods`.
**Recovery:** `npx cap sync ios`, `cd ios/App && pod install`, Xcode **Clean Build Folder**, rebuild. See **`doc/plugin-feedback-ios-scheduleDualNotification.md`** (troubleshooting section).
### 8.4 Summary
The plugin repo aligns with how we use it for New Activity (dual schedule + native fetcher, no generic polling, exact alarm optional). The main follow-ups are: (1) clarify or align `cancelDailyReminder` argument shape in the plugin if needed for typing/tooling, and (2) confirm on iOS whether `scheduleDailyNotification` uses the app-provided `id` for stable single-reminder semantics.
@@ -0,0 +1,126 @@
# Plugin feedback: Android dual schedule — native fetcher not used; fetch timing wrong
**Date:** 2026-03-24 21:56 PST
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
**Platform:** Android (Kotlin / Java)
**Related:** New Activity notifications (`scheduleDualNotification` / `cancelDualSchedule`)
---
## Summary
On Android, the **dual (New Activity) schedule** path is **not** implementing the intended contract:
1. **Prefetch does not call `NativeNotificationContentFetcher`.**
`ScheduleHelper.scheduleDualNotification` delegates fetch to `FetchWorker` (HTTP GET to optional `url`, or **mock JSON** when `url` is absent). The host app’s `TimeSafariNativeFetcher` is **never** invoked. Logcat shows `DNP-FETCH: Starting content fetch from: null, notificationTime=0` and **no** `TimeSafariNativeFetcher` `fetchContent` lines.
2. **Fetch is not scheduled at `contentFetch.schedule` (e.g. T−5 minutes).**
`FetchWorker.enqueueFetch` enqueues **immediate** `OneTimeWorkRequest` work (no `setInitialDelay` aligned to the fetch cron). The **notify** alarm is scheduled correctly for `dual_notify_*`, but there is **no** corresponding alarm/work at the **fetch** cron time. A `dual_fetch_*` row may exist in the DB with `nextRunAt`, but the **actual** fetch runs at **enable/setup time**, not at T−5.
3. **Cache vs `DualScheduleHelper` / `contentTimeout`.**
`DualScheduleHelper.resolveDualContentBlocking` only uses `contentCache` when the latest fetch is within `relationship.contentTimeout` (e.g. 5 minutes). If fetch runs **once at setup** and notify fires **~9+ minutes later**, cache is **stale** → `useCache=false` → default title/body from `userNotification`, even when mock payload was stored.
**Recommended direction (plugin):**
- For dual schedule when **no HTTP `url`** is configured (or when a flag indicates native mode), run **`NativeNotificationContentFetcher.fetchContent(FetchContext)`** (same path as `DailyNotificationFetchWorker` uses), persist results into the same `contentCache` / pipeline `DualScheduleHelper` expects.
- **Schedule** that work (or an alarm that enqueues it) **at** `calculateNextRunTime(contentFetch.schedule)` — i.e. **before** the notify alarm, typically **5 minutes** earlier per app cron (see consuming app `timeToCronFiveMinutesBefore`).
- Optionally align **one** scheduling mechanism: either exact alarm for fetch + notify, or WorkManager with **initial delay** to the next fetch instant (and reschedule after run).
---
## Symptoms (consuming app + logcat)
- Notification shows **default** copy from `userNotification` (`title` / `body` from `buildDualScheduleConfig`), not API-derived or native “No updates” copy.
- Logcat: `DNP-DUAL: Resolved dual content: useCache=false` at notify time.
- Logcat: `DNP-FETCH: Starting content fetch from: null, notificationTime=0` followed by `Content fetch completed successfully` **at schedule/setup time**, not at T−5.
- **No** `TimeSafariNativeFetcher` `fetchContent START` / `POST …/plansLastUpdatedBetween` during prefetch window (host registers `NativeNotificationContentFetcher` and logs on configure + fetch).
- **No** activity at the **prefetch cron** time (e.g. 19:05 for notify at 19:10); only **notify** fires at T.
---
## What the consuming app sends (contract)
**File:** `src/services/notifications/dualScheduleConfig.ts`
- `contentFetch.enabled: true`
- `contentFetch.schedule`: cron **5 minutes before** `userNotification.schedule` (e.g. `"25 19 * * *"` for notify `"30 19 * * *"`).
- **No** `contentFetch.url` — intended to use **native** Endorser API via `configureNativeFetcher` + `NativeNotificationContentFetcher`.
- `relationship.autoLink: true`, `relationship.contentTimeout: 5 * 60 * 1000`, `fallbackBehavior: "show_default"`.
**Host app:** `android/.../TimeSafariNativeFetcher.java` implements `NativeNotificationContentFetcher` and calls `POST /api/v2/report/plansLastUpdatedBetween` with starred plan IDs from `updateStarredPlans`.
---
## Root cause (plugin code — paths to review)
These paths are from a local clone of **daily-notification-plugin**; line numbers may drift.
### 1. `FetchWorker` is URL/mock-only; does not call native fetcher
`android/src/main/java/org/timesafari/dailynotification/FetchWorker.kt`
- `enqueueFetch` passes `config.url` into `InputData`; `doWork` logs `Starting content fetch from: $url`.
- `fetchContent(url, …)` when `url` is null/blank returns **`generateMockContent()`** — never calls `DailyNotificationPlugin.getNativeFetcherStatic().fetchContent(...)`.
### 2. `scheduleDualNotification` runs fetch work immediately, not at fetch cron
`android/src/main/java/org/timesafari/dailynotification/DailyNotificationPlugin.kt` — `object ScheduleHelper`, `suspend fun scheduleDualNotification(...)`
- Calls `scheduleFetch(context, contentFetchConfig)` which resolves to `FetchWorker.scheduleFetchForDual` → `enqueueFetch` **without** delay tied to `contentFetchConfig.schedule`.
- Schedules **notify** via `NotifyReceiver.scheduleExactNotification` for `dual_notify_*` at `calculateNextRunTime(userNotificationConfig.schedule)`.
- Persists `dual_fetch_*` with `nextRunAt = calculateNextRunTime(contentFetchConfig.schedule)` but **no** matching alarm/work is scheduled for that instant in the current flow (as observed).
### 3. Native fetcher exists elsewhere
`android/src/main/java/org/timesafari/dailynotification/DailyNotificationFetchWorker.java`
- Contains logic to call `NativeNotificationContentFetcher.fetchContent(FetchContext)` (with timeout). Dual schedule **does not** enqueue this worker for the TimeSafari `contentFetch` payload.
### 4. `DualScheduleHelper` behavior is consistent with “wrong fetch time”
`android/src/main/java/org/timesafari/dailynotification/DualScheduleHelper.kt`
- Uses latest `contentCache` only if `(now - fetchedAt) <= contentTimeoutMs`. If fetch ran at setup and notify is **later** than `contentTimeout`, **cache is ignored** → `useCache=false` in logs.
---
## Acceptance criteria (plugin)
After a fix, on a device with:
- `configureNativeFetcher` + `updateStarredPlans` called (host app),
- `scheduleDualNotification` with `contentFetch.enabled: true`, no `url`, cron 5 min before notify,
then:
1. **At or before** the notify fire time, **within** `contentTimeout`, the cache used by `DualScheduleHelper` reflects **native** fetch results when the API returns data (or empty), not only mock JSON.
2. Logcat **includes** host tag `TimeSafariNativeFetcher` with `fetchContent START` (or equivalent) **when** prefetch runs, **or** plugin logs an explicit `NativeNotificationContentFetcher` invocation.
3. Prefetch **does not** run only at **INITIAL_SETUP**; it runs at the **next** occurrence of `contentFetch.schedule` (and reschedules for the following day after success, same as notify rollover).
4. **Optional:** If `url` is set, preserve HTTP GET behavior; if `url` is absent and native fetcher is registered, use native path.
---
## References in consuming app
| Topic | Location |
|--------|----------|
| Dual config builder | `src/services/notifications/dualScheduleConfig.ts` |
| `scheduleDualNotification` call | `src/views/AccountViewView.vue` (`scheduleNewActivityDualNotification`, `editNewActivityNotification`) |
| Native fetcher | `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` |
| Registration | `MainActivity` / plugin init (host registers `DailyNotificationPlugin.setNativeFetcher`) |
---
## Notes for Cursor / implementers
- **Do not** assume `contentFetch.url` is present; TimeSafari intentionally omits it for native API.
- **Reuse** the same `FetchContext` / timeout semantics as `DailyNotificationFetchWorker` where possible to avoid two divergent native fetch implementations.
- After changing timing, **verify** `WorkManager` unique work name `fetch_dual` / `cancelDualSchedule` still cancel only dual fetch and do not break daily reminder.
---
## Related docs in this repo
- `doc/notification-from-api-call.md` — integration plan for API-driven New Activity.
- `doc/plugin-feedback-android-scheduleDualNotification-contentFetch-json.md` — optional `timeout` / `retry*` JSON parsing (already addressed on the plugin side).
@@ -2,7 +2,7 @@
**Date:** 2026-02-18
**Generated:** 2026-02-18 17:47:06 PST
**Target repo:** daily-notification-plugin (local copy at `daily-notification-plugin_test`)
**Target repo:** `@timesafari/daily-notification-plugin` (https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin)
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
**Platform:** Android
@@ -0,0 +1,99 @@
# Plugin feedback: Android `parseUserNotificationConfig` — optional fields vs `getBoolean` / `getString`
**Date:** 2026-03-20 21:11 PST
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
**Platform:** Android (Kotlin)
**Related:** Same class of issue as [plugin-feedback-android-scheduleDualNotification-contentFetch-json.md](./plugin-feedback-android-scheduleDualNotification-contentFetch-json.md) (`contentFetch` / `parseContentFetchConfig`).
---
## Summary
`DailyNotificationPlugin.parseUserNotificationConfig()` uses **`JSObject` / `JSONObject` strict getters** for fields that the published TypeScript **`UserNotificationConfig`** marks as **optional** (`sound?`, `vibration?`, `priority?`, `title?`, `body?`). If a key is omitted, Android throws **`JSONException`** (e.g. *No value for vibration*), and `scheduleDualNotification` fails before scheduling.
**Recommended direction (plugin):** Align Kotlin parsing with `dist/esm/definitions.d.ts` by using **optional reads + defaults**, consistent with the fix already applied for `parseContentFetchConfig` (e.g. `optIntOrNull`, or Capacitor/JSON equivalents for booleans and strings).
**Recommended direction (app / already done in TimeSafari):** Send explicit `sound`, `vibration`, and `priority` (and title/body) in `buildDualScheduleConfig()` so **older plugin builds** that still use strict getters continue to work.
**Does it make sense to change both sides?** **Yes** — same reasoning as for `contentFetch`: the plugin should match its public contract; the app can stay explicit for compatibility and clarity.
---
## Symptoms (consuming app)
- In-app toast: *“Could not schedule New Activity notification. Please try again.”* (generic catch after `scheduleDualNotification` rejects.)
- Logcat:
```text
E DNP-PLUGIN: Schedule dual notification error
E DNP-PLUGIN: org.json.JSONException: No value for vibration
E DNP-PLUGIN: at org.json.JSONObject.getBoolean(JSONObject.java:419)
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.parseUserNotificationConfig(DailyNotificationPlugin.kt:2428)
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.scheduleDualNotification(DailyNotificationPlugin.kt:1392)
```
(First failure observed after `contentFetch` timeouts were fixed was **`vibration`**; the same pattern can affect **`sound`** or **`priority`** if those keys are omitted.)
---
## Root cause
### Published TypeScript contract (`UserNotificationConfig`)
From `definitions.d.ts` (representative):
- `title?`, `body?`, `sound?`, `vibration?`, `priority?` — all optional.
### Current Android implementation (strict)
In `DailyNotificationPlugin.kt`, `parseUserNotificationConfig` (line numbers approximate; search for `parseUserNotificationConfig`):
```kotlin
private fun parseUserNotificationConfig(configJson: JSObject): UserNotificationConfig {
return UserNotificationConfig(
enabled = configJson.getBoolean("enabled") ?: true,
schedule = configJson.getString("schedule") ?: "0 9 * * *",
title = configJson.getString("title"),
body = configJson.getString("body"),
sound = configJson.getBoolean("sound"),
vibration = configJson.getBoolean("vibration"),
priority = configJson.getString("priority")
)
}
```
- **`getBoolean("vibration")`** (and **`getBoolean("sound")`**) throw if the key is **missing** — optional in TS, required at runtime on Android.
- **`getString("title")`**, **`getString("body")`**, **`getString("priority")`** likewise throw if missing (depending on `JSObject` / `JSONObject` behavior for absent keys).
So minimal or TS-faithful payloads omit `vibration` → immediate `JSONException`.
---
## Plugin-side recommendations
1. **Treat `UserNotificationConfig` optional fields as optional on Android**, mirroring `definitions.d.ts`:
- **`vibration`:** e.g. `optBoolean` / nullable + default **`true`** (or `false` if that matches product default — document the default).
- **`sound`:** same pattern; default **`true`** is typical for notifications.
- **`priority`:** optional string with default **`"normal"`** (or map from TS union).
- **`title` / `body`:** if TS allows omission, use optional reads + defaults consistent with dual-schedule UX (or reject with a clear `call.reject` message instead of a raw `JSONException`).
2. **Reuse the same helper style** as `parseContentFetchConfig` after the timeout fix (`optIntOrNull`, etc.) so one codebase convention applies to all dual-schedule JSON parsing.
3. **Tests:** Unit or integration test that calls `scheduleDualNotification` with a **minimal** `userNotification` object (only what TS strictly requires, if anything) and asserts scheduling succeeds on Android.
4. **iOS parity:** If iOS already accepts omitted `vibration` / `sound`, Android should match; if not, align both platforms to the same `UserNotificationConfig` rules.
---
## App-side note (TimeSafari)
`src/services/notifications/dualScheduleConfig.ts` — `buildDualScheduleConfig()` now includes **`vibration: true`** (with `sound: true`) so current native code paths succeed. Keeping this explicit is still recommended even after the plugin is fixed.
---
## References
- Plugin: `android/.../DailyNotificationPlugin.kt` — `parseUserNotificationConfig`
- TS: `dist/esm/definitions.d.ts` — `UserNotificationConfig`, `DualScheduleConfiguration`
- App: `src/services/notifications/dualScheduleConfig.ts` — `buildDualScheduleConfig`
@@ -0,0 +1,117 @@
# Plugin feedback: Android `scheduleDualNotification` — `JSONException: No value for timeout`
**Date:** 2026-03-20 18:21 PST
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
**Platform:** Android (Kotlin)
**Plugin version observed:** 2.1.2 (from app `node_modules`)
---
## Summary
Scheduling the **New Activity** dual notification on Android fails with a native `JSONException` because `DailyNotificationPlugin.parseContentFetchConfig()` uses **`JSONObject.getInt()`** for `timeout`, `retryAttempts`, and `retryDelay`. Those keys are **absent** from the app’s `contentFetch` object built by `buildDualScheduleConfig()`. The plugin’s own TypeScript `ContentFetchConfig` marks those fields as **optional**, so the Android parser is stricter than the published contract.
**Recommended direction:**
1. **Plugin (primary):** Parse optional numeric fields with defaults (e.g. `optInt` / nullable + defaults) so payloads that omit them do not crash and match `definitions.d.ts`.
2. **App (secondary / compatibility):** Include explicit `timeout`, `retryAttempts`, and `retryDelay` on `contentFetch` so older plugin versions that still use `getInt` continue to work.
**Does it make sense to change both sides?** **Yes.** Fixing the plugin aligns behavior with the documented API and protects any consumer that omits those fields. Fixing the app is still valuable for **older shipped plugin builds** and makes network behavior explicit. Together you get backward compatibility, clearer intent, and no silent reliance on undocumented defaults.
---
## Symptoms (consuming app)
- In-app toast: *“Could not schedule New Activity notification. Please try again.”* (generic error path after `scheduleDualNotification` rejects.)
- Logcat (filtered on DNP / plugin tags):
```text
E DNP-PLUGIN: Schedule dual notification error
E DNP-PLUGIN: org.json.JSONException: No value for timeout
E DNP-PLUGIN: at org.json.JSONObject.getInt(JSONObject.java:487)
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.parseContentFetchConfig(DailyNotificationPlugin.kt:2403)
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.scheduleDualNotification(DailyNotificationPlugin.kt:1391)
```
---
## Root cause
### Call path
`scheduleDualNotification` reads `config.contentFetch` and passes it to `parseContentFetchConfig`:
- File: `android/.../DailyNotificationPlugin.kt`
- `scheduleDualNotification` ~1391: `parseContentFetchConfig(contentFetchObj)`
- `parseContentFetchConfig` ~2397–2411: uses `getInt` for three keys.
### Strict Android parsing
Illustrative (exact line numbers may shift between releases):
```kotlin
// parseContentFetchConfig — timeout / retry fields are required via getInt()
timeout = configJson.getInt("timeout"),
retryAttempts = configJson.getInt("retryAttempts"),
retryDelay = configJson.getInt("retryDelay"),
```
`getInt` throws if the key is missing → first missing key in practice is `timeout` → `JSONException: No value for timeout`.
### App payload today (consuming app)
File: `src/services/notifications/dualScheduleConfig.ts` — `buildDualScheduleConfig()` sets `contentFetch` to:
- `enabled`, `schedule`, `callbacks` only (no `timeout`, `retryAttempts`, `retryDelay`, no `url`).
That matches the **TypeScript** contract in the plugin’s `dist/esm/definitions.d.ts`, where `timeout`, `retryAttempts`, and `retryDelay` are **optional** on `ContentFetchConfig`.
### Contract mismatch
| Layer | `timeout` / `retryAttempts` / `retryDelay` |
|--------|--------------------------------------------|
| TS `ContentFetchConfig` | Optional (`?`) |
| Android `parseContentFetchConfig` | Required (`getInt` — throws if absent) |
The consuming app followed the TS API; Android rejected it at runtime.
---
## Plugin-side recommendations
1. **Use optional reads with defaults** for `timeout`, `retryAttempts`, and `retryDelay` (and any similar fields), e.g. Kotlin/Capacitor equivalents of `optInt` or `getInteger` with fallbacks documented in `ContentFetchConfig`.
2. **Document defaults** in the plugin README or API docs if they are applied on native when omitted.
3. **Consider tests** that call `scheduleDualNotification` with a minimal `contentFetch` (only `enabled`, `schedule`, `callbacks`) and assert scheduling succeeds on Android.
4. **Optional:** If `url` is also read in a way that assumes presence, align with TS (`url?`) the same way.
---
## App-side recommendations (later; crowd-funder-for-time-pwa)
When you implement the app fix:
- Extend `contentFetch` in `buildDualScheduleConfig()` (`src/services/notifications/dualScheduleConfig.ts`) to include explicit integers, for example aligned with existing app/network conventions (the app’s `capacitor.config.ts` already uses a `timeout` value in one place — reuse or document chosen values).
- Ensure **both** code paths that build dual config stay in sync (e.g. `AccountViewView.vue` uses `buildDualScheduleConfig` for New Activity scheduling and for `updateDualScheduleConfig` fallback).
This unblocks users on **current** plugin versions that still require those keys.
---
## References (paths in consuming app workspace)
- App config builder: `src/services/notifications/dualScheduleConfig.ts`
- Native scheduling entry: `node_modules/@timesafari/daily-notification-plugin/android/.../DailyNotificationPlugin.kt` (`scheduleDualNotification`, `parseContentFetchConfig`)
---
## Answer: change both plugin and app?
**Yes, it makes sense to change both**, for different reasons:
| Side | Why |
|------|-----|
| **Plugin** | Fixes the real bug: native behavior must match the published optional TS fields; avoids breaking any client that sends a minimal `contentFetch`. |
| **App** | Defense in depth and support for **already-shipped** plugin binaries that will not get the Kotlin fix until users update the app. Explicit values also document intended fetch/retry behavior in one place. |
If you only fix the plugin, new app releases still need users to update the **native** binary. If you only fix the app, any other consumer of the plugin or future minimal payloads can hit the same crash until the plugin is fixed.
@@ -0,0 +1,95 @@
# Plugin feedback: `configureNativeFetcher` — optional JWT pool for background API calls
**Date:** 2026-03-27 PST
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
**Related app plan:** `doc/background-jwt-pool.md`
---
## Summary
The host app’s **`NativeNotificationContentFetcher`** (`TimeSafariNativeFetcher` on Android) calls Endorser with a Bearer JWT set via **`configureNativeFetcher`**. For **background** prefetch, the token must stay valid until WorkManager runs (often **minutes later**); Endorser may also reject **duplicate** JWT strings across days.
The **app** will mint a **pool** of distinct JWTs (see app plan) and needs the plugin to **accept and persist** that pool so native code can select a token **without JavaScript** at prefetch time.
**Requested change (plugin):** extend **`configureNativeFetcher`** to accept an optional **JWT pool** alongside the existing **`jwtToken`**, persist it in the same storage the host already relies on (e.g. SharedPreferences / app group), and document how **`NativeNotificationContentFetcher`** implementations should read it.
---
## Motivation
| Issue | Why plugin support helps |
|-------|---------------------------|
| Single short-lived `jwtToken` | Expires before background fetch |
| Server duplicate-JWT rules | Need many distinct bearer strings over time |
| No JS in WorkManager | Pool must be readable **only** from native |
---
## Proposed API (TypeScript / Capacitor)
**Extend** existing `configureNativeFetcher` options (names indicative — align with plugin naming conventions):
```ts
configureNativeFetcher(options: {
apiBaseUrl: string;
activeDid: string;
/** Primary token; keep for backward compatibility and Phase A (single long-lived JWT). */
jwtToken: string;
/**
* Optional. Distinct JWT strings for background use (e.g. one per day slot).
* If omitted, behavior matches today (single jwtToken only).
*/
jwtTokens?: string[];
});
```
**Alternatives** (if size limits matter for bridge payload):
- `jwtTokenPoolJson: string` — JSON array string of JWT strings (single string across the bridge).
**Validation (plugin):**
- If `jwtTokens` present: length **≤** a sane cap (host will use ~100; plugin may enforce max e.g. 128).
- Empty array: treat as “no pool” (same as omitting).
---
## Android
1. **Parse** new fields in `DailyNotificationPlugin.configureNativeFetcher` (or equivalent).
2. **Persist** pool under the same prefs namespace used for other TimeSafari / dual-schedule data, or a **documented** key prefix (e.g. `jwt_token_pool` as JSON array string).
3. **Document** for host implementers: `NativeNotificationContentFetcher` should:
- Prefer **pool entry** for `fetchContent` when pool is non-empty (selection policy is **host** responsibility — e.g. day index % length), **or**
- Expose a small helper the host fetcher calls to resolve “current” bearer.
4. **Clear** pool when `configureNativeFetcher` is called with a new identity / empty pool / logout path (coordinate with host).
5. **Backward compatibility:** if only `jwtToken` is sent, behavior **unchanged** from current release.
---
## iOS
When `configureNativeFetcher` exists on iOS, mirror Android: accept optional pool, persist, document read path for native fetcher.
---
## Versioning & release
- Bump **plugin semver** (minor: new optional fields).
- Publish package; consuming app bumps **`@timesafari/daily-notification-plugin`** and updates `nativeFetcherConfig.ts` to pass `jwtTokens` when Phase B ships.
---
## References (host app)
| Topic | Location |
|--------|----------|
| Pool design, slot ordering, lifecycle | `doc/background-jwt-pool.md` |
| Android fetcher | `android/.../TimeSafariNativeFetcher.java` |
| Current configure call | `src/services/notifications/nativeFetcherConfig.ts` |
| JWT options (expired token context) | `doc/endorser-jwt-background-prefetch-options.md` |
---
*This document is intended to be copied or linked from PRs in **daily-notification-plugin**; keep app-specific details in the app plan.*
@@ -0,0 +1,140 @@
# Plugin Feedback: Implement scheduleDualNotification on iOS
**Target repo:** daily-notification-plugin (iOS native layer)
**Purpose:** Document for implementing or fixing `scheduleDualNotification` on iOS so the consuming app (TimeSafari / crowd-funder) can enable “New Activity” notifications.
**Consuming app doc:** `doc/notification-new-activity-lay-of-the-land.md`
---
## Troubleshooting: `UNIMPLEMENTED` on iOS (Capacitor 6)
If **`configureNativeFetcher`** (or other DailyNotification methods) work but **`scheduleDualNotification`** still fails with **`{"code":"UNIMPLEMENTED"}`** and you **do not** see a native log line like `To Native -> DailyNotification scheduleDualNotification`, the failure is often **not** missing Swift code—it is **Capacitor’s JavaScript layer** rejecting the call because the method is **not listed** in `window.Capacitor.PluginHeaders` for `DailyNotification`. Those headers are built at runtime from the **compiled** plugin’s `pluginMethods` list (`CAPBridgedPlugin`).
**Fix in the consuming app (usual cause: stale Pods / binary):**
1. Ensure `node_modules/@timesafari/daily-notification-plugin` includes `scheduleDualNotification` in `DailyNotificationPlugin.swift`’s `pluginMethods` (v2.1.0+).
2. From the project root: `npx cap sync ios`
3. `cd ios/App && pod install` (or delete `Pods` + `Podfile.lock` and `pod install` if upgrading the plugin).
4. Xcode: **Product → Clean Build Folder**, then rebuild and run on device/simulator.
**Verify:** Safari → Develop → attach to the app WebView → Console: inspect `window.Capacitor.PluginHeaders` and confirm the `DailyNotification` entry’s `methods` array includes `{ name: "scheduleDualNotification", ... }`.
If a full clean rebuild still doesn't fix it, clear Xcode's **system** DerivedData (quit Xcode, run `rm -rf ~/Library/Developer/Xcode/DerivedData/*TimeSafari*`, reopen and rebuild). On launch the app logs `[Capacitor] DNP PluginHeaders methods: [...]`; if that list omits `scheduleDualNotification`, the native binary is still stale.
If the method **is** present in headers but scheduling still fails, debug the Swift implementation (reject message, BG tasks, etc.).
### Misleading `UNIMPLEMENTED` before `scheduleDualNotification`
Capacitor’s `registerPlugin` proxy returns a **callable stub for every property name**. So `if (DailyNotification?.updateStarredPlans)` is **always truthy** even when iOS does not expose `updateStarredPlans` in `pluginMethods`. Calling that stub throws **`UNIMPLEMENTED`** in JS **before** any `To Native -> DailyNotification scheduleDualNotification` line appears—so logs look like “dual schedule is unimplemented” when the real failure was **`updateStarredPlans`**.
**Consuming-app fix:** treat `updateStarredPlans` as optional: catch `UNIMPLEMENTED` and continue, or only call after verifying the method name exists on `PluginHeaders` for `DailyNotification`. If the plugin adds `updateStarredPlans` natively later, starred-plan filtering will start working without app changes.
---
## Current behavior
- The **consuming app** calls `DailyNotification.scheduleDualNotification({ config })` from TypeScript when the user turns on “New Activity Notification” and picks a time (native iOS).
- On **iOS**, the plugin rejects with **`code: "UNIMPLEMENTED"`** (observed in Xcode: `[AccountViewView] scheduleNewActivityDualNotification failed: {"code":"UNIMPLEMENTED"}`).
- On **Android**, the same call is expected to work (dual schedule: content fetch + user notification).
The app has already:
- Called `configureNativeFetcher({ apiBaseUrl, activeDid, jwtToken })` so the plugin can use the native fetcher for API-driven content.
- Called `updateStarredPlans({ planIds })` so the fetcher knows which plans to query.
- Built a `config` object that matches the plugin’s `DualScheduleConfiguration` (see below).
So the missing piece on iOS is a **working implementation** of `scheduleDualNotification` that accepts this config and schedules the dual flow (content fetch at one time, user notification at a later time).
---
## Call from the consuming app
```ts
await DailyNotification.scheduleDualNotification({ config });
```
`config` is built by the app’s `buildDualScheduleConfig({ notifyTime })` and has the following shape.
---
## Config shape the app sends
The app sends a single `config` object that matches the plugin’s `DualScheduleConfiguration` (see `definitions.ts`). Example for `notifyTime: "18:30"` (6:30 PM):
```json
{
"contentFetch": {
"enabled": true,
"schedule": "25 18 * * *",
"callbacks": {}
},
"userNotification": {
"enabled": true,
"schedule": "30 18 * * *",
"title": "New Activity",
"body": "Check your starred projects and offers for updates.",
"sound": true,
"priority": "normal"
},
"relationship": {
"autoLink": true,
"contentTimeout": 300000,
"fallbackBehavior": "show_default"
}
}
```
- **Cron format:** `"minute hour * * *"` (daily at that local time).
- **contentFetch.schedule:** 5 minutes **before** the user’s chosen time (e.g. 18:25 for notify at 18:30).
- **userNotification.schedule:** The user’s chosen time (e.g. 18:30).
- **contentFetch.callbacks:** The app sends `{}`; the actual fetch is done by the **native fetcher** (already configured via `configureNativeFetcher`). The plugin should run the content-fetch job at the contentFetch cron and use the native fetcher to get content; at userNotification time it should show a notification using that content or the fallback title/body.
- **relationship.contentTimeout:** Milliseconds to wait for content before showing the notification (app uses 5 minutes = 300000).
- **relationship.fallbackBehavior:** `"show_default"` means if content isn’t ready in time, show the notification with the default title/body from `userNotification`.
The app does **not** send `contentFetch.url` or `contentFetch.timesafariConfig`; it relies on the native fetcher and `configureNativeFetcher` / `updateStarredPlans` for API behavior.
---
## Expected plugin behavior (iOS)
1. **Accept** the `config` argument (object with `contentFetch`, `userNotification`, and optional `relationship`).
2. **Parse** the cron expressions for `contentFetch.schedule` and `userNotification.schedule` (e.g. using a shared cron parser or the same approach as Android).
3. **Schedule** two things:
- **Content fetch:** At the time given by `contentFetch.schedule`, run the **native notification content fetcher** (the one configured via `configureNativeFetcher`). Store the result in the plugin’s cache (or equivalent) for use when the user notification fires.
- **User notification:** At the time given by `userNotification.schedule`, show a local notification. Use cached content from the fetch if available and within `relationship.contentTimeout`; otherwise use `userNotification.title` and `userNotification.body` (per `relationship.fallbackBehavior: "show_default"`).
4. **Do not** reject with `UNIMPLEMENTED`; resolve the promise once scheduling has succeeded (or reject with a descriptive error if scheduling fails).
5. **cancelDualSchedule()** should cancel both the content-fetch schedule and the user-notification schedule so the user can turn off New Activity from the app.
Alignment with **Android** (if implemented there) is desirable: same config shape, same semantics (prefetch then notify, fallback to default title/body). The plugin’s **definitions.ts** already defines `DualScheduleConfiguration`, `ContentFetchConfig`, `UserNotificationConfig`, and the `scheduleDualNotification` / `cancelDualSchedule` API.
---
## Where to look in the plugin (iOS)
- **Plugin entry:** `ios/Plugin/DailyNotificationPlugin.swift` (or equivalent)—find the handler for `scheduleDualNotification` (e.g. method that receives `call.getObject("config")`).
- **Android reference:** `android/` implementation of `scheduleDualNotification` and how it schedules WorkManager/alarms for content fetch and for the user notification.
- **Definitions:** `src/definitions.ts` — `DualScheduleConfiguration`, `scheduleDualNotification`, `cancelDualSchedule`.
- **Native fetcher:** The app configures the native fetcher before calling `scheduleDualNotification`; the iOS plugin should invoke that same fetcher when the content-fetch job runs (BGAppRefreshTask or equivalent), not a URL from the config.
---
## Acceptance criteria
- [ ] On iOS, calling `DailyNotification.scheduleDualNotification({ config })` with the config shape above **does not** reject with `code: "UNIMPLEMENTED"`.
- [ ] The content-fetch job is scheduled at `contentFetch.schedule` and uses the configured native fetcher to fetch content.
- [ ] The user notification is scheduled at `userNotification.schedule` and shows with API-derived content when available, or with `userNotification.title` / `userNotification.body` as fallback.
- [ ] Calling `DailyNotification.cancelDualSchedule()` cancels both schedules on iOS.
- [ ] Behavior is consistent with Android where applicable (same config, same lifecycle).
---
## Relationship to consuming app
The consuming app will continue to call:
1. `configureNativeFetcher(...)` on startup and when enabling New Activity.
2. `updateStarredPlans({ planIds })` when enabling or when Account view loads with New Activity on.
3. `scheduleDualNotification({ config })` when the user turns on New Activity and picks a time.
4. `cancelDualSchedule()` when the user turns off New Activity.
No change to the app’s config shape or call order is planned; the fix is entirely on the plugin iOS side to implement or correct `scheduleDualNotification` (and ensure `cancelDualSchedule` clears the dual schedule).
@@ -0,0 +1,96 @@
# Plugin fix: Android compile error — duplicate `scheduleId` in `handleDisplayNotification`
**Date:** 2026-03-20
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
**Platform:** Android (Java)
---
## Summary
The Android module fails to compile with **two** `javac` errors: `variable scheduleId is already defined in method handleDisplayNotification(String)`. The method already declares `String scheduleId` at the start of the `try` block; two nested blocks incorrectly **redeclare** `String scheduleId`, which Java forbids in the same method scope. Remove the redundant declarations and reuse the existing variable (or assign without `String` if you ever need to refresh it).
---
## Problem
- **File:** `android/src/main/java/org/timesafari/dailynotification/DailyNotificationWorker.java`
- **Method:** `private Result handleDisplayNotification(String notificationId)`
**Compiler output (representative):**
```text
DailyNotificationWorker.java:162: error: variable scheduleId is already defined in method handleDisplayNotification(String)
String scheduleId = inputData.getString("schedule_id");
^
DailyNotificationWorker.java:193: error: variable scheduleId is already defined in method handleDisplayNotification(String)
String scheduleId = inputData.getString("schedule_id");
^
```
**Root cause:** At the top of the `try` block, the code already has:
```java
Data inputData = getInputData();
String scheduleId = inputData.getString("schedule_id");
```
Later, inside:
1. The `if (isStaticReminder) { ... }` branch — a line like `String scheduleId = inputData.getString("schedule_id");` (around line 162).
2. The `else { ... }` branch — the same pattern (around line 193).
In Java, a local variable name cannot be declared again in nested blocks that share the enclosing method’s scope for that name. These inner `String scheduleId` lines are **illegal** and break `:timesafari-daily-notification-plugin:compileDebugJavaWithJavac`.
**Functional note:** Both inner reads use the same key (`"schedule_id"`) as the outer declaration, so they add **no** new information; the fix is to **delete** those inner declarations and keep using `scheduleId` from the first assignment.
---
## Required change
**Option A (recommended):** Delete the two redundant lines entirely:
- Remove the inner `String scheduleId = inputData.getString("schedule_id");` in the **static reminder** branch (post-reboot/rollover comment block).
- Remove the inner `String scheduleId = inputData.getString("schedule_id");` in the **regular notification** branch (rollover/notify_* comment block).
All subsequent uses of `scheduleId` in those branches should continue to refer to the variable declared immediately after `getInputData()`.
**Option B (only if you must re-read input later):** Replace redeclaration with assignment:
```java
scheduleId = inputData.getString("schedule_id");
```
Do **not** prefix with `String` again inside the same method.
---
## Verification
1. **Compile:** From the plugin repo, run the Android Java compile for the library (or assemble debug). Expect **zero** errors for `DailyNotificationWorker.java`.
2. **Consuming app:** Bump/publish the plugin version, update `package.json` in TimeSafari, `npm install`, `npx cap sync android`, then run the usual Android debug build (e.g. `./scripts/build-android.sh --test` or `assembleDebug`). The task `:timesafari-daily-notification-plugin:compileDebugJavaWithJavac` must succeed.
3. **Behavior:** No intended behavior change: `schedule_id` is still read once per worker run from `getInputData()` and used for dual-prefix checks, static reminder DB fallback, and canonical content by `schedule_id` in the non-static path.
---
## Context (how this was found)
- Observed when running `npm run build:android:test:run` on crowd-funder-for-time-pwa; Vite/TypeScript succeeded; Gradle failed on the plugin’s Java sources under `node_modules/.../DailyNotificationWorker.java`.
- Line numbers in published packages may drift slightly; search for `handleDisplayNotification` and duplicate `String scheduleId` inside that method.
---
## Cursor prompt (paste into plugin repo)
You can paste the block below into Cursor in the **daily-notification-plugin** workspace:
```text
Fix Android compile errors in DailyNotificationWorker.java: in handleDisplayNotification(String notificationId), scheduleId is declared once after getInputData(). Remove the two illegal inner redeclarations "String scheduleId = inputData.getString(\"schedule_id\");" (static reminder branch and else branch). Reuse the outer scheduleId variable. Do not shadow or redeclare String scheduleId in the same method. Verify compileDebugJavaWithJavac passes.
```
---
## After the fix
Release a new plugin version and update the consuming app’s dependency so `node_modules` is not hand-edited (edits there are lost on `npm install`).
+30
View File
@@ -0,0 +1,30 @@
# SMS Registration
All text providers now require 10DLC registration, which is a horrendous process. (I can refer you to others who have also found the process to be a nightmare. I just tried to look up docs on the official pages and found broken links... cool.)
The functionality here mirrors the server-push FCM functionality. We're taking this approach as well because A) iOS client-side notifications are unreliable, and B) some users prefer to get text messages.
## Details on iOS client-side problems
iOS in particular makes it impossible to guarantee that the user will get notifications,
even if we separate the data-fetch from the user-notify as designed in the daily-notification-plugin
You can see more details here: https://chatgpt.com/share/69e601ea-6434-8398-8d28-f1a3118f86ad
... which explains:
```
That implies one of these patterns:
- Polling (setInterval / timers / background fetch)
- Service worker / PWA background sync
- App wake-up logic (foreground or semi-background)
All three are fragile or outright blocked on iOS.
Unlike Android, iOS has these restrictions:
- No persistent timers when app is backgrounded
- No reliable background fetch at exact times
- No service worker push for non-installed PWAs (and even then, limited)
- No “wake up at X time and run JS”
```
+3
View File
@@ -133,6 +133,7 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://dev-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://dev-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://dev-partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://dev.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
# .env.test
@@ -141,6 +142,7 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://staging-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://staging-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://staging-partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://staging.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
# .env.production
@@ -149,6 +151,7 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
```
+38 -20
View File
@@ -15,9 +15,13 @@
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 90DCAFB4D8948F7A50C13800 /* Pods_App.framework */; };
B7E1C4F82A9D3E506F1B2C8D /* TimeSafariNativeFetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3F8E2D91B4C5E60718293A4 /* TimeSafariNativeFetcher.swift */; };
C86585DF2ED456DE00824752 /* TimeSafariShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = C86585D52ED456DE00824752 /* TimeSafariShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
C8C56E142EE0474B00737D0E /* SharedImageUtility.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8C56E132EE0474B00737D0E /* SharedImageUtility.swift */; };
C8C56E162EE064CB00737D0E /* SharedImagePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8C56E152EE064CA00737D0E /* SharedImagePlugin.swift */; };
C8E73DD12FC6E5DC0057F59A /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = C8E73DD02FC6E5DC0057F59A /* GoogleService-Info.plist */; };
C8E73DD22FC6E5DC0057F59A /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = C8E73DD02FC6E5DC0057F59A /* GoogleService-Info.plist */; };
E9F1A0022EE05A8B00737D01 /* NotificationInspectorPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F1A0012EE05A8B00737D01 /* NotificationInspectorPlugin.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -55,16 +59,20 @@
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
90DCAFB4D8948F7A50C13800 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
A3F8E2D91B4C5E60718293A4 /* TimeSafariNativeFetcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimeSafariNativeFetcher.swift; sourceTree = "<group>"; };
C86585D52ED456DE00824752 /* TimeSafariShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = TimeSafariShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
C86585E52ED4577F00824752 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = "<group>"; };
C8C56E132EE0474B00737D0E /* SharedImageUtility.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedImageUtility.swift; sourceTree = "<group>"; };
C8C56E152EE064CA00737D0E /* SharedImagePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedImagePlugin.swift; sourceTree = "<group>"; };
C8E73DD02FC6E5DC0057F59A /* GoogleService-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = "<group>"; };
C8E73DD32FC6ECC30057F59A /* AppDebug.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = AppDebug.entitlements; sourceTree = "<group>"; };
E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
E9F1A0012EE05A8B00737D01 /* NotificationInspectorPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationInspectorPlugin.swift; sourceTree = "<group>"; };
EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
C86585E32ED456DE00824752 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
C86585E32ED456DE00824752 /* Exceptions for "TimeSafariShareExtension" folder in "TimeSafariShareExtension" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -77,7 +85,7 @@
C86585D62ED456DE00824752 /* TimeSafariShareExtension */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
C86585E32ED456DE00824752 /* PBXFileSystemSynchronizedBuildFileExceptionSet */,
C86585E32ED456DE00824752 /* Exceptions for "TimeSafariShareExtension" folder in "TimeSafariShareExtension" target */,
);
explicitFileTypes = {
};
@@ -138,8 +146,11 @@
504EC3061FED79650016851F /* App */ = {
isa = PBXGroup;
children = (
C8E73DD32FC6ECC30057F59A /* AppDebug.entitlements */,
C8C56E152EE064CA00737D0E /* SharedImagePlugin.swift */,
E9F1A0012EE05A8B00737D01 /* NotificationInspectorPlugin.swift */,
C8C56E132EE0474B00737D0E /* SharedImageUtility.swift */,
A3F8E2D91B4C5E60718293A4 /* TimeSafariNativeFetcher.swift */,
C86585E52ED4577F00824752 /* App.entitlements */,
50379B222058CBB4000EE86E /* capacitor.config.json */,
504EC3071FED79650016851F /* AppDelegate.swift */,
@@ -149,6 +160,7 @@
504EC3131FED79650016851F /* Info.plist */,
2FAD9762203C412B000D30F8 /* config.xml */,
50B271D01FEDC1A000F3C39B /* public */,
C8E73DD02FC6E5DC0057F59A /* GoogleService-Info.plist */,
);
path = App;
sourceTree = "<group>";
@@ -174,9 +186,9 @@
504EC3011FED79650016851F /* Frameworks */,
504EC3021FED79650016851F /* Resources */,
012076E8FFE4BF260A79B034 /* Fix Privacy Manifest */,
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */,
96A7EF592DF3366D00084D51 /* Fix Privacy Manifest */,
C86585E02ED456DE00824752 /* Embed Foundation Extensions */,
2B3F98670AF3508A35AC3248 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
@@ -204,8 +216,6 @@
C86585D62ED456DE00824752 /* TimeSafariShareExtension */,
);
name = TimeSafariShareExtension;
packageProductDependencies = (
);
productName = TimeSafariShareExtension;
productReference = C86585D52ED456DE00824752 /* TimeSafariShareExtension.appex */;
productType = "com.apple.product-type.app-extension";
@@ -218,7 +228,7 @@
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 2610;
LastUpgradeCheck = 1630;
LastUpgradeCheck = 2660;
TargetAttributes = {
504EC3031FED79650016851F = {
CreatedOnToolsVersion = 9.2;
@@ -260,6 +270,7 @@
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,
504EC30D1FED79650016851F /* Main.storyboard in Resources */,
2FAD9763203C412B000D30F8 /* config.xml in Resources */,
C8E73DD12FC6E5DC0057F59A /* GoogleService-Info.plist in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -267,6 +278,7 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C8E73DD22FC6E5DC0057F59A /* GoogleService-Info.plist in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -293,7 +305,7 @@
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" \n";
showEnvVarsInLog = 0;
};
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */ = {
2B3F98670AF3508A35AC3248 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
@@ -357,8 +369,10 @@
buildActionMask = 2147483647;
files = (
C8C56E162EE064CB00737D0E /* SharedImagePlugin.swift in Sources */,
E9F1A0022EE05A8B00737D01 /* NotificationInspectorPlugin.swift in Sources */,
504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
C8C56E142EE0474B00737D0E /* SharedImageUtility.swift in Sources */,
B7E1C4F82A9D3E506F1B2C8D /* TimeSafariNativeFetcher.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -452,10 +466,11 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
@@ -508,9 +523,10 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
@@ -522,9 +538,10 @@
baseConfigurationReference = EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = App/AppDebug.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 70;
CURRENT_PROJECT_VERSION = 72;
DEVELOPMENT_TEAM = GM3FS5JQPH;
ENABLE_APP_SANDBOX = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
@@ -535,7 +552,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.4.4;
MARKETING_VERSION = 1.4.6;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -551,9 +568,10 @@
baseConfigurationReference = E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 70;
CURRENT_PROJECT_VERSION = 72;
DEVELOPMENT_TEAM = GM3FS5JQPH;
ENABLE_APP_SANDBOX = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
@@ -564,7 +582,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.4.4;
MARKETING_VERSION = 1.4.6;
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
@@ -582,21 +600,21 @@
CLANG_ENABLE_OBJC_WEAK = YES;
CODE_SIGN_ENTITLEMENTS = TimeSafariShareExtension/TimeSafariShareExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 70;
CURRENT_PROJECT_VERSION = 72;
DEVELOPMENT_TEAM = GM3FS5JQPH;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = TimeSafariShareExtension/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Giftopia;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.4.4;
MARKETING_VERSION = 1.4.6;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari.TimeSafariShareExtension;
@@ -620,21 +638,21 @@
CLANG_ENABLE_OBJC_WEAK = YES;
CODE_SIGN_ENTITLEMENTS = TimeSafariShareExtension/TimeSafariShareExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 70;
CURRENT_PROJECT_VERSION = 72;
DEVELOPMENT_TEAM = GM3FS5JQPH;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = TimeSafariShareExtension/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Giftopia;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.4.4;
MARKETING_VERSION = 1.4.6;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari.TimeSafariShareExtension;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1630"
LastUpgradeVersion = "2660"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.security.application-groups</key>
<array>
<string>group.app.timesafari.share</string>
</array>
</dict>
</plist>
+34 -8
View File
@@ -1,6 +1,7 @@
import UIKit
import Capacitor
import CapacitorCommunitySqlite
import TimesafariDailyNotificationPlugin
import UserNotifications
@UIApplicationMain
@@ -9,6 +10,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// New Activity / dual schedule: plugin requires a registered native fetcher before configureNativeFetcher (parity with Android setNativeFetcher).
DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)
// Set notification center delegate so notifications show in foreground and rollover is triggered
UNUserNotificationCenter.current().delegate = self
@@ -25,6 +29,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
attempts += 1
if registerSharedImagePlugin() {
print("[AppDelegate] ✅ Plugin registration successful on attempt \(attempts)")
_ = registerNotificationInspectorPlugin()
} else if attempts < maxAttempts {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(attempts) * 0.5) {
tryRegister()
@@ -60,6 +65,20 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
return true
}
@discardableResult
private func registerNotificationInspectorPlugin() -> Bool {
guard let window = self.window,
let bridgeVC = window.rootViewController as? CAPBridgeViewController,
let bridge = bridgeVC.bridge else {
return false
}
let pluginInstance = NotificationInspectorPlugin()
bridge.registerPluginInstance(pluginInstance)
print("[AppDelegate] ✅ Registered NotificationInspectorPlugin (exposed as 'NotificationInspector')")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
@@ -89,13 +108,20 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
/// Show notifications when app is in foreground and post DailyNotificationDelivered for rollover.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let notificationId = userInfo["notification_id"] as? String,
let scheduledTime = userInfo["scheduled_time"] as? Int64 {
NotificationCenter.default.post(
name: NSNotification.Name("DailyNotificationDelivered"),
object: nil,
userInfo: ["notification_id": notificationId, "scheduled_time": scheduledTime]
)
if let notificationId = userInfo["notification_id"] as? String {
let scheduledTime: Int64? = {
if let v = userInfo["scheduled_time"] as? Int64 { return v }
if let n = userInfo["scheduled_time"] as? NSNumber { return n.int64Value }
if let i = userInfo["scheduled_time"] as? Int { return Int64(i) }
return nil
}()
if let scheduledTime = scheduledTime {
NotificationCenter.default.post(
name: NSNotification.Name("DailyNotificationDelivered"),
object: nil,
userInfo: ["notification_id": notificationId, "scheduled_time": scheduledTime]
)
}
}
if #available(iOS 14.0, *) {
completionHandler([.banner, .sound, .badge])
@@ -133,7 +159,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Called when the app was launched with a url. Feel free to add additional processing here,
// but if you want the App API to support tracking app url opens, make sure to keep this call
// Note: Share Extension opens app with timesafari:// (empty path), which is handled by JavaScript
// Note: Share Extension opens app with timesafari://shared-photo, which is handled by JavaScript
// via the appUrlOpen listener in main.capacitor.ts
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>API_KEY</key>
<string>AIzaSyDhiy46kW7TH4VvUxzl2pOTLEK7mT14mIo</string>
<key>GCM_SENDER_ID</key>
<string>1094643115061</string>
<key>PLIST_VERSION</key>
<string>1</string>
<key>BUNDLE_ID</key>
<string>app.timesafari</string>
<key>PROJECT_ID</key>
<string>pc-api-7249509642322112640-286</string>
<key>STORAGE_BUCKET</key>
<string>pc-api-7249509642322112640-286.firebasestorage.app</string>
<key>IS_ADS_ENABLED</key>
<false></false>
<key>IS_ANALYTICS_ENABLED</key>
<false></false>
<key>IS_APPINVITE_ENABLED</key>
<true></true>
<key>IS_GCM_ENABLED</key>
<true></true>
<key>IS_SIGNIN_ENABLED</key>
<true></true>
<key>GOOGLE_APP_ID</key>
<string>1:1094643115061:ios:587b9422d019375e887d7c</string>
</dict>
</plist>
+26 -25
View File
@@ -2,6 +2,13 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>org.timesafari.dailynotification.fetch</string>
<string>org.timesafari.dailynotification.notify</string>
<string>org.timesafari.dailynotification.content-fetch</string>
<string>org.timesafari.dailynotification.notification-delivery</string>
</array>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
@@ -18,6 +25,17 @@
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>app.timesafari</string>
<key>CFBundleURLSchemes</key>
<array>
<string>timesafari</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
@@ -26,6 +44,14 @@
<string>Time Safari allows you to take photos, and also scan QR codes from contacts.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Time Safari allows you to upload photos.</string>
<key>NSUserNotificationAlertStyle</key>
<string>alert</string>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
<string>remote-notification</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
@@ -47,30 +73,5 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>app.timesafari</string>
<key>CFBundleURLSchemes</key>
<array>
<string>timesafari</string>
</array>
</dict>
</array>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>org.timesafari.dailynotification.fetch</string>
<string>org.timesafari.dailynotification.notify</string>
<string>org.timesafari.dailynotification.content-fetch</string>
<string>org.timesafari.dailynotification.notification-delivery</string>
</array>
<key>NSUserNotificationAlertStyle</key>
<string>alert</string>
</dict>
</plist>
@@ -0,0 +1,88 @@
import Foundation
import Capacitor
import UserNotifications
// DEV-only diagnostic plugin.
// Kept separate from DailyNotificationPlugin intentionally
// to avoid altering production notification scheduling behavior.
@objc(NotificationInspector)
public class NotificationInspectorPlugin: CAPPlugin, CAPBridgedPlugin {
public var identifier: String { "NotificationInspector" }
public var jsName: String { "NotificationInspector" }
public var pluginMethods: [CAPPluginMethod] {
[
CAPPluginMethod(#selector(getPendingNotifications(_:)), returnType: .promise)
]
}
/// Stable wall-clock target: plugin `userInfo["scheduled_time"]`, or epoch ms in API notification identifiers.
/// (Apple documents `UNTimeIntervalNotificationTrigger.nextTriggerDate()` as resampling ~now+interval when queried.)
/// API notification identifiers use the `api_` prefix.
private static let apiNotificationIdentifierPrefix = "api_"
private func wallClockMillis(from request: UNNotificationRequest) -> (ms: Int64, source: String)? {
let info = request.content.userInfo
if let v = info["scheduled_time"] as? Int64 {
return (v, "userInfo.scheduled_time")
}
if let n = info["scheduled_time"] as? NSNumber {
return (n.int64Value, "userInfo.scheduled_time")
}
if let i = info["scheduled_time"] as? Int {
return (Int64(i), "userInfo.scheduled_time")
}
let prefix = Self.apiNotificationIdentifierPrefix
if request.identifier.hasPrefix(prefix) {
let suffix = String(request.identifier.dropFirst(prefix.count))
if let ms = Int64(suffix) {
return (ms, "identifier (API notification)")
}
}
return nil
}
@objc public func getPendingNotifications(_ call: CAPPluginCall) {
UNUserNotificationCenter.current().getPendingNotificationRequests { requests in
let pending: [[String: Any]] = requests.map { req in
var nextTriggerMs: NSNumber? = nil
var triggerType: String? = nil
if let trigger = req.trigger as? UNCalendarNotificationTrigger {
triggerType = "calendar"
if let next = trigger.nextTriggerDate() {
nextTriggerMs = NSNumber(value: Int64(next.timeIntervalSince1970 * 1000))
}
} else if let trigger = req.trigger as? UNTimeIntervalNotificationTrigger {
triggerType = "timeInterval"
if let next = trigger.nextTriggerDate() {
nextTriggerMs = NSNumber(value: Int64(next.timeIntervalSince1970 * 1000))
}
} else if req.trigger != nil {
triggerType = "other"
} else {
triggerType = nil
}
var obj: [String: Any] = [
"identifier": req.identifier
]
obj["nextTriggerDate"] = nextTriggerMs ?? NSNull()
obj["triggerType"] = triggerType ?? NSNull()
if let wall = self.wallClockMillis(from: req) {
obj["wallClockMillis"] = NSNumber(value: wall.ms)
obj["wallClockSource"] = wall.source
} else {
obj["wallClockMillis"] = NSNull()
obj["wallClockSource"] = NSNull()
}
return obj
}
call.resolve([
"pending": pending
])
}
}
}
+223
View File
@@ -0,0 +1,223 @@
import Foundation
import TimesafariDailyNotificationPlugin
/// Native content fetcher for API-driven New Activity notifications on iOS.
/// Mirrors `TimeSafariNativeFetcher.java` (POST `plansLastUpdatedBetween`, starred plans, JWT pool, pagination).
final class TimeSafariNativeFetcher: NativeNotificationContentFetcher {
static let shared = TimeSafariNativeFetcher()
private let endpoint = "/api/v2/report/plansLastUpdatedBetween"
private let readTimeoutSec: TimeInterval = 15
private let maxRetries = 3
private let retryDelayMs = 1_000
/// Matches plugin `updateStarredPlans` storage (`DailyNotificationPlugin.swift`).
private let prefsStarredKey = "daily_notification_timesafari.starredPlanIds"
/// Matches Java `TimeSafariNativeFetcher` prefs namespace `daily_notification_timesafari` + `last_acked_jwt_id`.
private let prefsLastAckedKey = "daily_notification_timesafari.last_acked_jwt_id"
private var apiBaseUrl: String?
private var activeDid: String?
private var jwtToken: String?
private var jwtTokenPool: [String]?
private init() {}
func configure(apiBaseUrl: String, activeDid: String, jwtToken: String, jwtTokenPool: [String]?) {
self.apiBaseUrl = apiBaseUrl.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(
of: "/$",
with: "",
options: .regularExpression
)
self.activeDid = activeDid
self.jwtToken = jwtToken
self.jwtTokenPool = (jwtTokenPool?.isEmpty == false) ? jwtTokenPool : nil
}
func fetchContent(context: FetchContext) async throws -> [NotificationContent] {
try await fetchContentWithRetry(context: context, retryCount: 0)
}
/// Picks the pool entry whose validity window covers today, falling back to the
/// primary `jwtToken` when no pool is configured. Same arithmetic as Java.
///
/// Each pooled JWT carries nbf/exp spanning exactly one UTC day, and the minter
/// (`mintBackgroundJwtTokenPool`) files the token for a given day at index
/// `epochDay % size`. That is why the index below is the raw epoch day rather than
/// a count from when the pool arrived: this side keeps no mint date, and the same
/// arithmetic on both ends is what lines the slot up with the day it covers.
/// A token read from the wrong slot is outside its window and Endorser rejects it.
private func selectBearerTokenForRequest() -> String? {
guard let pool = jwtTokenPool, !pool.isEmpty else { return jwtToken }
let epochDay = Int64(Date().timeIntervalSince1970 * 1000) / (24 * 60 * 60 * 1000)
let idx = Int(epochDay) % pool.count
let t = pool[idx]
if t.isEmpty { return jwtToken }
return t
}
private func fetchContentWithRetry(context: FetchContext, retryCount: Int) async throws -> [NotificationContent] {
guard let base = apiBaseUrl, !base.isEmpty,
activeDid != nil,
let bearer = selectBearerTokenForRequest(), !bearer.isEmpty
else {
NSLog("[TimeSafariNativeFetcher] Not configured; call configureNativeFetcher from JS first.")
return []
}
guard let url = URL(string: base + endpoint) else {
return []
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization")
request.timeoutInterval = readTimeoutSec
let planIds = getStarredPlanIds()
var afterId = getLastAcknowledgedJwtId() ?? "0"
if afterId.isEmpty { afterId = "0" }
let body: [String: Any] = [
"planIds": planIds,
"afterId": afterId,
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
NSLog(
"[TimeSafariNativeFetcher] POST \(endpoint) planCount=\(planIds.count) afterId=\(afterId.prefix(12))…"
)
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = readTimeoutSec
config.timeoutIntervalForResource = readTimeoutSec
let session = URLSession(configuration: config)
do {
let (data, response) = try await session.data(for: request)
guard let http = response as? HTTPURLResponse else {
return []
}
if http.statusCode == 200 {
let bodyStr = String(data: data, encoding: .utf8) ?? ""
let contents = parseApiResponse(responseBody: bodyStr, context: context)
if !contents.isEmpty {
updateLastAckedJwtIdFromResponse(responseBody: bodyStr)
}
return contents
}
if retryCount < maxRetries && (http.statusCode >= 500 || http.statusCode == 429) {
let delayMs = retryDelayMs * (1 << retryCount)
try await Task.sleep(nanoseconds: UInt64(delayMs) * 1_000_000)
return try await fetchContentWithRetry(context: context, retryCount: retryCount + 1)
}
NSLog("[TimeSafariNativeFetcher] API error \(http.statusCode)")
return []
} catch {
NSLog("[TimeSafariNativeFetcher] Fetch failed: \(error.localizedDescription)")
if retryCount < maxRetries {
let delayMs = retryDelayMs * (1 << retryCount)
try await Task.sleep(nanoseconds: UInt64(delayMs) * 1_000_000)
return try await fetchContentWithRetry(context: context, retryCount: retryCount + 1)
}
return []
}
}
private func getStarredPlanIds() -> [String] {
guard let jsonStr = UserDefaults.standard.string(forKey: prefsStarredKey),
!jsonStr.isEmpty, jsonStr != "[]",
let data = jsonStr.data(using: .utf8),
let arr = try? JSONSerialization.jsonObject(with: data) as? [Any]
else {
return []
}
return arr.compactMap { $0 as? String }
}
private func getLastAcknowledgedJwtId() -> String? {
let s = UserDefaults.standard.string(forKey: prefsLastAckedKey)
return (s?.isEmpty == false) ? s : nil
}
private func updateLastAckedJwtIdFromResponse(responseBody: String) {
guard let data = responseBody.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let dataArray = root["data"] as? [[String: Any]], !dataArray.isEmpty
else { return }
let lastItem = dataArray[dataArray.count - 1]
var jwtId: String?
if let j = lastItem["jwtId"] as? String {
jwtId = j
} else if let plan = lastItem["plan"] as? [String: Any], let j = plan["jwtId"] as? String {
jwtId = j
}
if let jwtId = jwtId, !jwtId.isEmpty {
UserDefaults.standard.set(jwtId, forKey: prefsLastAckedKey)
}
}
private func extractProjectDisplayTitle(_ item: [String: Any]) -> String {
if let plan = item["plan"] as? [String: Any],
let name = plan["name"] as? String,
!name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return name.trimmingCharacters(in: .whitespacesAndNewlines)
}
return "Unnamed Project"
}
private func extractJwtIdFromItem(_ item: [String: Any]) -> String? {
if let plan = item["plan"] as? [String: Any], let j = plan["jwtId"] as? String, !j.isEmpty {
return j
}
if let j = item["jwtId"] as? String, !j.isEmpty { return j }
return nil
}
private func parseApiResponse(responseBody: String, context: FetchContext) -> [NotificationContent] {
guard let data = responseBody.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let dataArray = root["data"] as? [[String: Any]], !dataArray.isEmpty
else {
return []
}
let firstItem = dataArray[0]
let firstTitle = extractProjectDisplayTitle(firstItem)
let jwtId = extractJwtIdFromItem(firstItem)
let nowMs = Int64(Date().timeIntervalSince1970 * 1000)
let scheduledMs: Int64 = context.scheduledTimeMillis ?? (nowMs + 3_600_000)
let n = dataArray.count
let quotedFirst = "\u{201C}\(firstTitle)\u{201D}"
let title: String
let body: String
if n == 1 {
title = "Starred Project Update"
body = "\(quotedFirst) has been updated."
} else {
title = "Starred Project Updates"
let more = n - 1
body = "\(quotedFirst) + \(more) more have been updated."
}
let id = "endorser_\(jwtId ?? "batch_\(nowMs)")"
return [
NotificationContent(
id: id,
title: title,
body: body,
scheduledTime: scheduledMs,
fetchedAt: nowMs,
url: apiBaseUrl,
payload: nil,
etag: nil
),
]
}
}
+91
View File
@@ -17,6 +17,8 @@ def capacitor_pods
pod 'CapacitorCamera', :path => '../../node_modules/@capacitor/camera'
pod 'CapacitorClipboard', :path => '../../node_modules/@capacitor/clipboard'
pod 'CapacitorFilesystem', :path => '../../node_modules/@capacitor/filesystem'
pod 'CapacitorPreferences', :path => '../../node_modules/@capacitor/preferences'
pod 'CapacitorPushNotifications', :path => '../../node_modules/@capacitor/push-notifications'
pod 'CapacitorShare', :path => '../../node_modules/@capacitor/share'
pod 'CapacitorStatusBar', :path => '../../node_modules/@capacitor/status-bar'
pod 'CapawesomeCapacitorFilePicker', :path => '../../node_modules/@capawesome/capacitor-file-picker'
@@ -28,6 +30,95 @@ target 'App' do
# Add your Pods here
end
def merge_sqlite_omit_load_extension_definition(config)
defs = config.build_settings['GCC_PREPROCESSOR_DEFINITIONS']
if defs.nil?
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = ['$(inherited)', 'SQLITE_OMIT_LOAD_EXTENSION']
elsif defs.is_a?(Array)
unless defs.any? { |d| d.to_s.include?('SQLITE_OMIT_LOAD_EXTENSION') }
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = defs + ['SQLITE_OMIT_LOAD_EXTENSION']
end
else
s = defs.to_s
unless s.include?('SQLITE_OMIT_LOAD_EXTENSION')
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "#{s} SQLITE_OMIT_LOAD_EXTENSION".squeeze(' ').strip
end
end
end
def strip_system_sqlite_from_pod_config(config)
bad_header = lambda do |path|
p = path.to_s
p.include?('/usr/include') || p.include?('/usr/local/include')
end
%w[HEADER_SEARCH_PATHS USER_HEADER_SEARCH_PATHS].each do |key|
paths = config.build_settings[key]
next unless paths
if paths.is_a?(Array)
config.build_settings[key] = paths.reject(&bad_header)
else
kept = paths.to_s.split(/\s+/).reject(&bad_header)
config.build_settings[key] = kept.join(' ')
end
end
%w[OTHER_LDFLAGS OTHER_LIBTOOLFLAGS].each do |key|
val = config.build_settings[key]
next unless val
if val.is_a?(Array)
config.build_settings[key] = val.reject do |x|
s = x.to_s
s.match?(/libsqlite3\.tbd/) || s == '-l"sqlite3"' || s.match?(/-l\s*sqlite3\b/)
end
else
s = val.to_s.gsub(/\s*-l"sqlite3"\s+/, ' ')
.gsub(/\s*-l\s*sqlite3\b/, ' ')
.gsub(/[^\s]*libsqlite3\.tbd[^\s]*/, ' ')
config.build_settings[key] = s.squeeze(' ').strip
end
end
end
post_install do |installer|
assertDeploymentTarget(installer)
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
deployment_target = config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'].to_f
if deployment_target > 0.0 && deployment_target < 15.5
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.5'
end
config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
merge_sqlite_omit_load_extension_definition(config)
strip_system_sqlite_from_pod_config(config)
end
end
end
# Aggregate Pods-App xcconfigs merge -l"sqlite3" from dependencies; that pulls in Apple's
# libsqlite3 alongside SQLCipher. Strip it after CocoaPods writes the files (post_install is too early).
# Also strip SQLCipher header-guard macros leaked into GCC_PREPROCESSOR_DEFINITIONS: Swift explicit
# modules build the SDK SQLite3.modulemap PCM with the same -D flags; _SQLITE3_H_=1 empties sqlite3.h
# and breaks sqlite3ext.h (unknown sqlite3_* types).
def strip_aggregate_pods_app_xcconfig(contents)
# Unlink system libsqlite3 (SQLCipher is the only SQLite).
patched = contents.gsub(/\s+-l"sqlite3"\s+/, ' ')
.gsub(/\s+-lsqlite3\b/, ' ')
# SQLCipher leaks sqlite3*.h guard macros into GCC_PREPROCESSOR_DEFINITIONS; Swift explicit
# modules must not inherit them when building the SDK SQLite3 module.
%w[_SQLITE3_H_=1 _FTS5_H=1 _SQLITE3RTREE_H_=1].each do |macro|
escaped = Regexp.escape(macro)
patched.gsub!(/(?:^|\s)-D#{escaped}(?=\s|$)/, ' ')
patched.gsub!(/(?:^|\s)#{escaped}(?=\s|$)/, ' ')
end
patched.gsub(/[ \t]+/, ' ')
end
post_integrate do |installer|
support = File.join(installer.sandbox.root, 'Target Support Files', 'Pods-App')
%w[Pods-App.debug.xcconfig Pods-App.release.xcconfig].each do |name|
path = File.join(support, name)
next unless File.exist?(path)
contents = File.read(path)
patched = strip_aggregate_pods_app_xcconfig(contents)
File.write(path, patched) if patched != contents
end
end
+13 -1
View File
@@ -18,6 +18,10 @@ PODS:
- CapacitorMlkitBarcodeScanning (7.5.0):
- Capacitor
- GoogleMLKit/BarcodeScanning (= 7.0.0)
- CapacitorPreferences (7.0.4):
- Capacitor
- CapacitorPushNotifications (7.0.7):
- Capacitor
- CapacitorShare (7.0.4):
- Capacitor
- CapacitorStatusBar (7.0.6):
@@ -89,6 +93,8 @@ DEPENDENCIES:
- "CapacitorCordova (from `../../node_modules/@capacitor/ios`)"
- "CapacitorFilesystem (from `../../node_modules/@capacitor/filesystem`)"
- "CapacitorMlkitBarcodeScanning (from `../../node_modules/@capacitor-mlkit/barcode-scanning`)"
- "CapacitorPreferences (from `../../node_modules/@capacitor/preferences`)"
- "CapacitorPushNotifications (from `../../node_modules/@capacitor/push-notifications`)"
- "CapacitorShare (from `../../node_modules/@capacitor/share`)"
- "CapacitorStatusBar (from `../../node_modules/@capacitor/status-bar`)"
- "CapawesomeCapacitorFilePicker (from `../../node_modules/@capawesome/capacitor-file-picker`)"
@@ -128,6 +134,10 @@ EXTERNAL SOURCES:
:path: "../../node_modules/@capacitor/filesystem"
CapacitorMlkitBarcodeScanning:
:path: "../../node_modules/@capacitor-mlkit/barcode-scanning"
CapacitorPreferences:
:path: "../../node_modules/@capacitor/preferences"
CapacitorPushNotifications:
:path: "../../node_modules/@capacitor/push-notifications"
CapacitorShare:
:path: "../../node_modules/@capacitor/share"
CapacitorStatusBar:
@@ -146,6 +156,8 @@ SPEC CHECKSUMS:
CapacitorCordova: e343e95a672ff73e21a77a80257b52fb609b47d5
CapacitorFilesystem: c63fc54df41e5a6761785a7f3c49dc696c22e296
CapacitorMlkitBarcodeScanning: afd6fc431b550026a2c052e11ab2b71c7ae30011
CapacitorPreferences: 69d9991307507aeab8ef8019c10b9babfda0e9ca
CapacitorPushNotifications: 0527809a9619ed775439d5ab2c2d996122b48319
CapacitorShare: 25f7fc5dd0e4edbde5d6801c6de5d14a8b450a41
CapacitorStatusBar: 416e9e53fd6397e668d4a181cd2131617d949bd6
CapawesomeCapacitorFilePicker: 0f4a913a00e39dd77213449f0d917e92f35a5ca9
@@ -165,6 +177,6 @@ SPEC CHECKSUMS:
TimesafariDailyNotificationPlugin: 69277c884380a9a620f671b68e0327eaa4b3d27d
ZIPFoundation: dfd3d681c4053ff7e2f7350bc4e53b5dba3f5351
PODFILE CHECKSUM: 87c07d03f36ef38ab0c873802aee1ce9b5d34448
PODFILE CHECKSUM: 5736811d271d5309d3e2de8f3eefdbb6632086a3
COCOAPODS: 1.16.2
@@ -46,7 +46,7 @@ class ShareViewController: UIViewController {
if success {
// Set flag that shared photo is ready
self.setSharedPhotoReadyFlag()
// Open the main app (using minimal URL - app will detect shared data on activation)
// Open the main app at its shared-photo deep link.
self.openMainApp()
}
@@ -186,8 +186,7 @@ class ShareViewController: UIViewController {
}
private func openMainApp() {
// Open the main app with minimal URL - app will detect shared data on activation
guard let url = URL(string: "timesafari://") else {
guard let url = URL(string: "timesafari://shared-photo") else {
return
}
+3
View File
@@ -1,6 +1,9 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
// Unit tests live under src/. test-playwright/ holds Playwright specs,
// which use a different runner and fail if Jest collects them.
roots: ['<rootDir>/src'],
moduleFileExtensions: ['ts', 'js', 'json', 'vue'],
transform: {
'^.+\\.ts$': 'ts-jest'
+2929 -2314
View File
File diff suppressed because it is too large Load Diff
+124 -118
View File
@@ -1,138 +1,140 @@
{
"name": "giftopia",
"version": "1.4.4",
"version": "1.4.7",
"description": "Giftopia App",
"author": {
"name": "Gift Economies Team"
},
"scripts": {
"lint": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src",
"lint-fix": "eslint --ext .js,.ts,.vue --ignore-path .gitignore --fix src",
"type-safety-check": "./scripts/type-safety-check.sh",
"type-check": "tsc --noEmit",
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js",
"test:prerequisites": "node scripts/check-prerequisites.js",
"check:dependencies": "./scripts/check-dependencies.sh",
"deps:update-daily-notification-plugin": "npm install @timesafari/daily-notification-plugin@git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git#master",
"test:all": "npm run lint && tsc && npm run test:web && npm run test:mobile && ./scripts/test-safety-check.sh && echo '\n\n\nGotta add the performance tests'",
"test:web": "npx playwright test -c playwright.config-local.ts --trace on",
"test:mobile": "./scripts/test-mobile.sh",
"test:android": "node scripts/test-android.js",
"test:ios": "node scripts/test-ios.js",
"check:android-device": "adb devices | grep -w 'device' || (echo 'No Android device connected' && exit 1)",
"check:ios-device": "xcrun xctrace list devices 2>&1 | grep -w 'Booted' || (echo 'No iOS simulator running' && exit 1)",
"auto-run": "./scripts/auto-run.sh",
"auto-run:test": "./scripts/auto-run.sh --test",
"auto-run:prod": "./scripts/auto-run.sh --prod",
"auto-run:ios": "./scripts/auto-run.sh --platform=ios",
"auto-run:android": "./scripts/auto-run.sh --platform=android",
"auto-run:electron": "./scripts/auto-run.sh --platform=electron",
"build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts",
"build:capacitor:sync": "npm run build:capacitor && npx cap sync && node scripts/restore-local-plugins.js",
"build:native": "vite build && npx cap sync && node scripts/restore-local-plugins.js && bash -c 'source scripts/common.sh && ensure_ios_capacitor_asset_directories' && npx capacitor-assets generate",
"assets:clean": "rimraf android/app/src/main/res/mipmap-* ios/App/App/Assets.xcassets/**/AppIcon*.png ios/App/App/Assets.xcassets/**/Splash*.png || true",
"assets:config": "npx tsx scripts/assets-config.ts",
"assets:validate": "npx tsx scripts/assets-validator.ts",
"assets:validate:android": "./scripts/build-android.sh --assets-only",
"assets:clean": "rimraf android/app/src/main/res/mipmap-* ios/App/App/Assets.xcassets/**/AppIcon*.png ios/App/App/Assets.xcassets/**/Splash*.png || true",
"build:ios": "./scripts/build-ios.sh",
"build:ios:dev": "./scripts/build-ios.sh --dev",
"build:ios:test": "./scripts/build-ios.sh --test",
"build:ios:test:run": "./scripts/build-ios.sh --test --auto-run",
"build:ios:prod": "./scripts/build-ios.sh --prod",
"build:ios:prod:run": "./scripts/build-ios.sh --prod --auto-run",
"build:ios:debug": "./scripts/build-ios.sh --debug",
"build:ios:debug:run": "./scripts/build-ios.sh --debug --auto-run",
"build:ios:release": "./scripts/build-ios.sh --release",
"build:ios:release:run": "./scripts/build-ios.sh --release --auto-run",
"build:ios:studio": "./scripts/build-ios.sh --studio",
"build:ios:ipa": "./scripts/build-ios.sh --ipa",
"build:ios:clean": "./scripts/build-ios.sh --clean",
"build:ios:sync": "./scripts/build-ios.sh --sync",
"build:ios:assets": "./scripts/build-ios.sh --assets",
"build:ios:deploy": "./scripts/build-ios.sh --deploy",
"build:ios:dev:custom": "./scripts/build-ios.sh --dev --api-ip",
"build:ios:test:custom": "./scripts/build-ios.sh --test --api-ip",
"build:ios:dev:run:custom": "./scripts/build-ios.sh --dev --api-ip --auto-run",
"build:ios:test:run:custom": "./scripts/build-ios.sh --test --api-ip --auto-run",
"build:web": "./scripts/build-web.sh",
"build:web:dev": "./scripts/build-web.sh --dev",
"build:web:test": "./scripts/build-web.sh --test",
"build:web:prod": "./scripts/build-web.sh --prod",
"build:web:docker": "./scripts/build-web.sh --docker",
"build:web:docker:test": "./scripts/build-web.sh --docker:test",
"build:web:docker:prod": "./scripts/build-web.sh --docker:prod",
"build:web:serve": "./scripts/build-web.sh --serve",
"build:web:serve:test": "./scripts/build-web.sh --serve --test",
"build:web:serve:prod": "./scripts/build-web.sh --serve --prod",
"docker:up": "docker-compose up",
"docker:up:test": "npm run build:web:build -- --mode test && docker-compose up test",
"docker:up:prod": "npm run build:web:build -- --mode production && docker-compose up production",
"docker:down": "docker-compose down",
"docker:logs": "docker-compose logs -f",
"build:electron": "./scripts/build-electron.sh",
"build:electron:dev": "./scripts/build-electron.sh --dev",
"build:electron:dev:run": "./scripts/build-electron.sh --dev --auto-run",
"build:electron:test": "./scripts/build-electron.sh --test",
"build:electron:test:run": "./scripts/build-electron.sh --test --auto-run",
"build:electron:prod": "./scripts/build-electron.sh --prod",
"build:electron:prod:run": "./scripts/build-electron.sh --prod --auto-run",
"build:electron:windows": "./scripts/build-electron.sh --prod --windows",
"build:electron:windows:dev": "./scripts/build-electron.sh --dev --windows",
"build:electron:windows:test": "./scripts/build-electron.sh --test --windows",
"build:electron:windows:prod": "./scripts/build-electron.sh --prod --windows",
"build:electron:mac": "./scripts/build-electron.sh --prod --mac",
"build:electron:mac:dev": "./scripts/build-electron.sh --dev --mac",
"build:electron:mac:test": "./scripts/build-electron.sh --test --mac",
"build:electron:mac:prod": "./scripts/build-electron.sh --prod --mac",
"build:electron:linux": "./scripts/build-electron.sh --prod --linux",
"build:electron:linux:dev": "./scripts/build-electron.sh --dev --linux",
"build:electron:linux:test": "./scripts/build-electron.sh --test --linux",
"build:electron:linux:prod": "./scripts/build-electron.sh --prod --linux",
"build:electron:appimage": "./scripts/build-electron.sh --prod --appimage",
"build:electron:appimage:dev": "./scripts/build-electron.sh --dev --appimage",
"build:electron:appimage:test": "./scripts/build-electron.sh --test --appimage",
"build:electron:appimage:prod": "./scripts/build-electron.sh --prod --appimage",
"build:electron:deb": "./scripts/build-electron.sh --prod --deb",
"build:electron:deb:dev": "./scripts/build-electron.sh --dev --deb",
"build:electron:deb:test": "./scripts/build-electron.sh --test --deb",
"build:electron:deb:prod": "./scripts/build-electron.sh --prod --deb",
"build:electron:dmg": "./scripts/build-electron.sh --prod --dmg",
"build:electron:dmg:dev": "./scripts/build-electron.sh --dev --dmg",
"build:electron:dmg:test": "./scripts/build-electron.sh --test --dmg",
"build:electron:dmg:prod": "./scripts/build-electron.sh --prod --dmg",
"markdown:fix": "markdownlint-cli2 --fix",
"markdown:check": "markdownlint-cli2",
"markdown:setup": "./scripts/setup-markdown-hooks.sh",
"prepare": "husky",
"guard": "bash ./scripts/build-arch-guard.sh",
"guard:test": "bash ./scripts/build-arch-guard.sh --staged",
"guard:setup": "npm run prepare && echo '✅ Build Architecture Guard is now active!'",
"clean:android": "./scripts/uninstall-android.sh",
"clean:ios": "rm -rf ios/App/build ios/App/Pods ios/App/output ios/App/App/public ios/DerivedData ios/capacitor-cordova-ios-plugins ios/App/App/capacitor.config.json ios/App/App/config.xml || true",
"clean:electron": "./scripts/build-electron.sh --clean",
"clean:all": "npm run clean:ios && npm run clean:android && npm run clean:electron",
"auto-run": "./scripts/auto-run.sh",
"auto-run:android": "./scripts/auto-run.sh --platform=android",
"auto-run:electron": "./scripts/auto-run.sh --platform=electron",
"auto-run:ios": "./scripts/auto-run.sh --platform=ios",
"auto-run:prod": "./scripts/auto-run.sh --prod",
"auto-run:test": "./scripts/auto-run.sh --test",
"build:android": "./scripts/build-android.sh",
"build:android:dev": "./scripts/build-android.sh --dev",
"build:android:test": "./scripts/build-android.sh --test",
"build:android:test:run": "./scripts/build-android.sh --test --auto-run",
"build:android:prod": "./scripts/build-android.sh --prod",
"build:android:prod:run": "./scripts/build-android.sh --prod --auto-run",
"build:android:aab": "./scripts/build-android.sh --aab",
"build:android:apk": "./scripts/build-android.sh --apk",
"build:android:assets": "./scripts/build-android.sh --assets",
"build:android:clean": "./scripts/build-android.sh --clean",
"build:android:debug": "./scripts/build-android.sh --debug",
"build:android:debug:run": "./scripts/build-android.sh --debug --auto-run",
"build:android:deploy": "./scripts/build-android.sh --deploy",
"build:android:dev": "./scripts/build-android.sh --dev",
"build:android:dev:custom": "./scripts/build-android.sh --dev --api-ip",
"build:android:dev:run:custom": "./scripts/build-android.sh --dev --api-ip --auto-run",
"build:android:prod": "./scripts/build-android.sh --prod",
"build:android:prod:run": "./scripts/build-android.sh --prod --auto-run",
"build:android:release": "./scripts/build-android.sh --release",
"build:android:release:run": "./scripts/build-android.sh --release --auto-run",
"build:android:studio": "./scripts/build-android.sh --studio",
"build:android:apk": "./scripts/build-android.sh --apk",
"build:android:aab": "./scripts/build-android.sh --aab",
"build:android:clean": "./scripts/build-android.sh --clean",
"build:android:sync": "./scripts/build-android.sh --sync",
"build:android:assets": "./scripts/build-android.sh --assets",
"build:android:deploy": "./scripts/build-android.sh --deploy",
"build:android:dev:custom": "./scripts/build-android.sh --dev --api-ip",
"build:android:test": "./scripts/build-android.sh --test",
"build:android:test:custom": "./scripts/build-android.sh --test --api-ip",
"build:android:dev:run:custom": "./scripts/build-android.sh --dev --api-ip --auto-run",
"build:android:test:run:custom": "./scripts/build-android.sh --test --api-ip --auto-run"
"build:android:test:run": "./scripts/build-android.sh --test --auto-run",
"build:android:test:run:custom": "./scripts/build-android.sh --test --api-ip --auto-run",
"build:capacitor": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --mode capacitor --config vite.config.capacitor.mts",
"build:capacitor:sync": "npm run build:capacitor && npx cap sync && node scripts/restore-local-plugins.js",
"build:electron": "./scripts/build-electron.sh",
"build:electron:appimage": "./scripts/build-electron.sh --prod --appimage",
"build:electron:appimage:dev": "./scripts/build-electron.sh --dev --appimage",
"build:electron:appimage:prod": "./scripts/build-electron.sh --prod --appimage",
"build:electron:appimage:test": "./scripts/build-electron.sh --test --appimage",
"build:electron:deb": "./scripts/build-electron.sh --prod --deb",
"build:electron:deb:dev": "./scripts/build-electron.sh --dev --deb",
"build:electron:deb:prod": "./scripts/build-electron.sh --prod --deb",
"build:electron:deb:test": "./scripts/build-electron.sh --test --deb",
"build:electron:dev": "./scripts/build-electron.sh --dev",
"build:electron:dev:run": "./scripts/build-electron.sh --dev --auto-run",
"build:electron:dmg": "./scripts/build-electron.sh --prod --dmg",
"build:electron:dmg:dev": "./scripts/build-electron.sh --dev --dmg",
"build:electron:dmg:prod": "./scripts/build-electron.sh --prod --dmg",
"build:electron:dmg:test": "./scripts/build-electron.sh --test --dmg",
"build:electron:linux": "./scripts/build-electron.sh --prod --linux",
"build:electron:linux:dev": "./scripts/build-electron.sh --dev --linux",
"build:electron:linux:prod": "./scripts/build-electron.sh --prod --linux",
"build:electron:linux:test": "./scripts/build-electron.sh --test --linux",
"build:electron:mac": "./scripts/build-electron.sh --prod --mac",
"build:electron:mac:dev": "./scripts/build-electron.sh --dev --mac",
"build:electron:mac:prod": "./scripts/build-electron.sh --prod --mac",
"build:electron:mac:test": "./scripts/build-electron.sh --test --mac",
"build:electron:prod": "./scripts/build-electron.sh --prod",
"build:electron:prod:run": "./scripts/build-electron.sh --prod --auto-run",
"build:electron:test": "./scripts/build-electron.sh --test",
"build:electron:test:run": "./scripts/build-electron.sh --test --auto-run",
"build:electron:windows": "./scripts/build-electron.sh --prod --windows",
"build:electron:windows:dev": "./scripts/build-electron.sh --dev --windows",
"build:electron:windows:prod": "./scripts/build-electron.sh --prod --windows",
"build:electron:windows:test": "./scripts/build-electron.sh --test --windows",
"build:ios": "./scripts/build-ios.sh",
"build:ios:assets": "./scripts/build-ios.sh --assets",
"build:ios:clean": "./scripts/build-ios.sh --clean",
"build:ios:debug": "./scripts/build-ios.sh --debug",
"build:ios:debug:run": "./scripts/build-ios.sh --debug --auto-run",
"build:ios:deploy": "./scripts/build-ios.sh --deploy",
"build:ios:dev": "./scripts/build-ios.sh --dev",
"build:ios:dev:custom": "./scripts/build-ios.sh --dev --api-ip",
"build:ios:dev:run:custom": "./scripts/build-ios.sh --dev --api-ip --auto-run",
"build:ios:ipa": "./scripts/build-ios.sh --ipa",
"build:ios:prod": "./scripts/build-ios.sh --prod",
"build:ios:prod:run": "./scripts/build-ios.sh --prod --auto-run",
"build:ios:release": "./scripts/build-ios.sh --release",
"build:ios:release:run": "./scripts/build-ios.sh --release --auto-run",
"build:ios:studio": "./scripts/build-ios.sh --studio",
"build:ios:sync": "./scripts/build-ios.sh --sync",
"build:ios:test": "./scripts/build-ios.sh --test",
"build:ios:test:custom": "./scripts/build-ios.sh --test --api-ip",
"build:ios:test:run": "./scripts/build-ios.sh --test --auto-run",
"build:ios:test:run:custom": "./scripts/build-ios.sh --test --api-ip --auto-run",
"build:native": "vite build && npx cap sync && node scripts/restore-local-plugins.js && bash -c 'source scripts/common.sh && ensure_ios_capacitor_asset_directories' && npx capacitor-assets generate --assetPath resources",
"build:web": "./scripts/build-web.sh",
"build:web:dev": "./scripts/build-web.sh --dev",
"build:web:docker": "./scripts/build-web.sh --docker",
"build:web:docker:prod": "./scripts/build-web.sh --docker:prod",
"build:web:docker:test": "./scripts/build-web.sh --docker:test",
"build:web:prod": "./scripts/build-web.sh --prod",
"build:web:serve": "./scripts/build-web.sh --serve",
"build:web:serve:prod": "./scripts/build-web.sh --serve --prod",
"build:web:serve:test": "./scripts/build-web.sh --serve --test",
"build:web:test": "./scripts/build-web.sh --test",
"check:android-device": "adb devices | grep -w 'device' || (echo 'No Android device connected' && exit 1)",
"check:dependencies": "./scripts/check-dependencies.sh",
"check:ios-device": "xcrun xctrace list devices 2>&1 | grep -w 'Booted' || (echo 'No iOS simulator running' && exit 1)",
"check:prod-bundle": "./scripts/check-prod-bundle.sh",
"clean:all": "npm run clean:ios && npm run clean:android && npm run clean:electron",
"clean:android": "./scripts/uninstall-android.sh",
"clean:electron": "./scripts/build-electron.sh --clean",
"clean:ios": "rm -rf ios/App/build ios/App/Pods ios/App/output ios/App/App/public ios/DerivedData ios/capacitor-cordova-ios-plugins ios/App/App/capacitor.config.json ios/App/App/config.xml || true",
"deps:update-daily-notification-plugin": "npm install @timesafari/daily-notification-plugin@git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git#master",
"dev": "npm run build:web:dev",
"docker:down": "docker-compose down",
"docker:logs": "docker-compose logs -f",
"docker:up": "docker-compose up",
"docker:up:prod": "npm run build:web:build -- --mode production && docker-compose up production",
"docker:up:test": "npm run build:web:build -- --mode test && docker-compose up test",
"guard": "bash ./scripts/build-arch-guard.sh",
"guard:setup": "npm run prepare && echo 'Build Architecture Guard is now active!'",
"guard:test": "bash ./scripts/build-arch-guard.sh --staged",
"lint": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src",
"lint-fix": "eslint --ext .js,.ts,.vue --ignore-path .gitignore --fix src",
"markdown:check": "markdownlint-cli2",
"markdown:fix": "markdownlint-cli2 --fix",
"markdown:setup": "./scripts/setup-markdown-hooks.sh",
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js",
"prepare": "husky",
"test:all": "npm run lint && npm run type-check && npm run type-check:vue && npm run test:unit && npm run test:web && npm run test:mobile && echo '\n\n\nGotta add the performance tests'",
"test:android": "node scripts/test-android.js",
"test:ios": "node scripts/test-ios.js",
"test:mobile": "./scripts/test-mobile.sh",
"test:prerequisites": "node scripts/check-prerequisites.js",
"test:unit": "jest",
"test:web": "npx playwright test -c playwright.config-local.ts --trace on",
"type-check": "tsc --noEmit",
"type-check:vue": "vue-tsc --noEmit"
},
"lint-staged": {
"*.{js,ts,vue,css,json,yml,yaml}": "eslint --fix || true",
@@ -150,6 +152,8 @@
"@capacitor/core": "^7.6.4",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/ios": "^7.6.4",
"@capacitor/preferences": "^7.0.4",
"@capacitor/push-notifications": "^7.0.7",
"@capacitor/share": "^7.0.4",
"@capacitor/status-bar": "^7.0.6",
"@capawesome/capacitor-file-picker": "^7.2.0",
@@ -196,6 +200,7 @@
"electron-builder": "^26.0.12",
"ethereum-cryptography": "^2.1.3",
"ethereumjs-util": "^7.1.5",
"firebase": "^12.12.1",
"jdenticon": "^3.2.0",
"js-generate-password": "^0.1.9",
"js-yaml": "^4.1.0",
@@ -281,6 +286,7 @@
"ts-jest": "^29.4.0",
"tsx": "^4.20.4",
"typescript": "~5.2.2",
"vite": "^5.2.0"
"vite": "^5.2.0",
"vue-tsc": "^2.1.10"
}
}
+7 -8
View File
@@ -46,20 +46,19 @@ Assets are automatically generated during the build process using `capacitor-ass
```bash
# Generate assets for all platforms
npx capacitor-assets generate
npx capacitor-assets generate --assetPath resources
# Generate assets for specific platform
npx capacitor-assets generate --ios
npx capacitor-assets generate --android
npx capacitor-assets generate --web
npx capacitor-assets generate --ios --assetPath resources
npx capacitor-assets generate --android --assetPath resources
npx capacitor-assets generate --web --assetPath resources
```
## Configuration
`resources/` is this project's canonical asset source. `@capacitor/assets`
prioritizes a top-level `assets/` directory over `resources/`, so a legacy
`assets/` directory can prevent these assets from being discovered. Remove that
directory when it is empty or obsolete.
`resources/` is this project's canonical asset source. Pass it explicitly with
`--assetPath resources`; `@capacitor/assets` otherwise prioritizes a top-level
`assets/` directory when one exists, even when that directory is empty.
## Version Control
+1 -1
View File
@@ -204,7 +204,7 @@ run_android() {
safe_execute "Launching app" "adb -s $device_id shell am start -n app.timesafari.app/app.timesafari.MainActivity"
else
log_info "Launching emulator and installing app"
safe_execute "Launching app" "npx cap run android"
safe_execute "Launching app" "npx cap run android --no-sync"
fi
}
+51 -29
View File
@@ -492,21 +492,6 @@ log_info "Build type: $BUILD_TYPE"
# Setup environment for Capacitor build
setup_build_env "capacitor" "$BUILD_MODE"
# Override API servers for Android development
if [ "$BUILD_MODE" = "development" ]; then
if [ -n "$CUSTOM_API_IP" ]; then
# Use custom IP for physical device development
export VITE_DEFAULT_ENDORSER_API_SERVER="http://${CUSTOM_API_IP}:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://${CUSTOM_API_IP}:3000"
log_info "Android development mode: Using custom IP ${CUSTOM_API_IP} for physical device"
else
# Use Android emulator IP (10.0.2.2) for Android development
export VITE_DEFAULT_ENDORSER_API_SERVER="http://10.0.2.2:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://10.0.2.2:3000"
log_debug "Android development mode: Using 10.0.2.2 for emulator"
fi
fi
# Setup application directories
setup_app_directories
@@ -523,6 +508,21 @@ if [ -f ".env" ]; then
load_env_file ".env"
fi
# Override API servers for Android development
if [ "$BUILD_MODE" = "development" ]; then
if [ -n "$CUSTOM_API_IP" ]; then
# Use custom IP for physical device development
export VITE_DEFAULT_ENDORSER_API_SERVER="http://${CUSTOM_API_IP}:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://${CUSTOM_API_IP}:3000"
log_info "Android development mode: Using custom IP ${CUSTOM_API_IP} for physical device"
else
# Use Android emulator IP (10.0.2.2) for Android development
export VITE_DEFAULT_ENDORSER_API_SERVER="http://10.0.2.2:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://10.0.2.2:3000"
log_debug "Android development mode: Using 10.0.2.2 for emulator"
fi
fi
# Handle clean-only mode
if [ "$CLEAN_ONLY" = true ]; then
log_info "Clean-only mode: cleaning build artifacts"
@@ -545,7 +545,7 @@ fi
# Handle assets-only mode
if [ "$ASSETS_ONLY" = true ]; then
log_info "Assets-only mode: generating assets"
safe_execute "Generating assets" "npx capacitor-assets generate --android" || exit 7
safe_execute "Generating assets" "npx capacitor-assets generate --android --assetPath resources" || exit 7
log_success "Assets generation completed successfully!"
exit 0
fi
@@ -612,25 +612,31 @@ elif [ "$BUILD_MODE" = "production" ]; then
safe_execute "Building Capacitor version (production)" "npm run build:capacitor -- --mode production" || exit 3
fi
# Step 6: Clean Gradle build
# Step 6: Sync with Capacitor (before any Gradle assemble, which packages
# whatever web bundle and resources are in android/app/src/main at that moment)
safe_execute "Syncing with Capacitor" "npx cap sync android" || exit 6
# Step 6.5: Restore local plugins (capacitor.plugins.json gets overwritten by cap sync)
safe_execute "Restoring local plugins" "node scripts/restore-local-plugins.js" || exit 7
# Step 6.6: Verify the synced web bundle has production server defaults
if [ "$BUILD_MODE" = "production" ]; then
safe_execute "Checking production bundle" "./scripts/check-prod-bundle.sh android/app/src/main/assets/public" || exit 10
fi
# Step 7: Generate assets
safe_execute "Generating assets" "npx capacitor-assets generate --android --assetPath resources" || exit 7
# Step 8: Clean Gradle build
safe_execute "Cleaning Gradle build" "cd android && ./gradlew clean && cd .." || exit 4
# Step 7: Build based on type
# Step 9: Build based on type
if [ "$BUILD_TYPE" = "debug" ]; then
safe_execute "Assembling debug build" "cd android && ./gradlew assembleDebug && cd .." || exit 5
elif [ "$BUILD_TYPE" = "release" ]; then
safe_execute "Assembling release build" "cd android && ./gradlew assembleRelease && cd .." || exit 5
fi
# Step 8: Sync with Capacitor
safe_execute "Syncing with Capacitor" "npx cap sync android" || exit 6
# Step 8.5: Restore local plugins (capacitor.plugins.json gets overwritten by cap sync)
safe_execute "Restoring local plugins" "node scripts/restore-local-plugins.js" || exit 7
# Step 9: Generate assets
safe_execute "Generating assets" "npx capacitor-assets generate --android" || exit 7
# Step 10: Build APK/AAB if requested
if [ "$BUILD_APK" = true ]; then
if [ "$BUILD_TYPE" = "debug" ]; then
@@ -642,14 +648,30 @@ fi
if [ "$BUILD_AAB" = true ]; then
safe_execute "Building AAB" "cd android && ./gradlew bundleRelease && cd .." || exit 5
if [ "$BUILD_MODE" = "production" ]; then
safe_execute "Checking production AAB" "./scripts/check-prod-bundle.sh android/app/build/outputs/bundle/release/app-release.aab" || exit 10
fi
fi
# Step 11: Auto-run app if requested
# cap run runs sync by default, which would overwrite capacitor.plugins.json again;
# we already synced and ran restore-local-plugins.js above, so skip sync here.
if [ "$AUTO_RUN" = true ]; then
log_step "Auto-running Android app..."
safe_execute "Launching app" "npx cap run android" || {
# With exactly one connected device, target it directly. Otherwise cap run
# shows an interactive picker, which without a terminal exits 0 having
# launched nothing, so fail instead of reporting a false success.
run_devices=$(adb devices | awk 'NR > 1 && $2 == "device" { print $1 }')
run_target=""
if [ "$(printf '%s\n' "$run_devices" | grep -c .)" = "1" ]; then
run_target="--target $run_devices"
elif [ ! -t 0 ]; then
log_error "Auto-run needs exactly one connected device when not run from a terminal (found: ${run_devices:-none})"
exit 9
fi
safe_execute "Launching app" "npx cap run android --no-sync $run_target" || {
log_error "Failed to launch Android app"
log_info "You can manually run with: npx cap run android"
log_info "You can manually run with: npx cap run android --no-sync"
exit 9
}
log_success "Android app launched successfully!"
+16 -15
View File
@@ -295,12 +295,7 @@ apply_ios_app_icon_appearances() {
# Generate iOS assets (capacitor-assets), then apply optional appearance variants.
generate_ios_assets() {
ensure_ios_capacitor_asset_directories
if [ -d "assets" ]; then
log_warn "@capacitor/assets prioritizes the top-level assets/ directory over resources/."
log_warn "This project intentionally uses resources/ as the canonical asset source."
log_warn "Remove the legacy assets/ directory if it is empty or obsolete."
fi
npx capacitor-assets generate --ios
npx capacitor-assets generate --ios --assetPath resources
apply_ios_app_icon_appearances
}
@@ -351,6 +346,7 @@ build_ios_app() {
unset DYLD_LIBRARY_PATH
unset DYLD_FALLBACK_LIBRARY_PATH
# Build the app:
# -quiet: skip the huge export VAR dump (compiler warnings still show unless suppressed below).
# SWIFT_SUPPRESS_WARNINGS / GCC_WARN_INHIBIT_ALL_WARNINGS: quiet CLI output from Pods + plugins;
@@ -443,14 +439,6 @@ log_info "Build type: $BUILD_TYPE"
# Setup environment for Capacitor build
setup_build_env "capacitor" "$BUILD_MODE"
# Override API servers for iOS development when custom IP is specified
if [ "$BUILD_MODE" = "development" ] && [ -n "$CUSTOM_API_IP" ]; then
# Use custom IP for physical device development
export VITE_DEFAULT_ENDORSER_API_SERVER="http://${CUSTOM_API_IP}:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://${CUSTOM_API_IP}:3000"
log_info "iOS development mode: Using custom IP ${CUSTOM_API_IP} for physical device"
fi
# Setup application directories
setup_app_directories
@@ -467,6 +455,14 @@ if [ -f ".env" ]; then
load_env_file ".env"
fi
# Override API servers for iOS development when custom IP is specified
if [ "$BUILD_MODE" = "development" ] && [ -n "$CUSTOM_API_IP" ]; then
# Use custom IP for physical device development
export VITE_DEFAULT_ENDORSER_API_SERVER="http://${CUSTOM_API_IP}:3000"
export VITE_DEFAULT_PARTNER_API_SERVER="http://${CUSTOM_API_IP}:3000"
log_info "iOS development mode: Using custom IP ${CUSTOM_API_IP} for physical device"
fi
# Validate iOS environment
validate_ios_environment
@@ -684,6 +680,11 @@ safe_execute "Installing CocoaPods dependencies" "run_pod_install_with_workaroun
# Step 6.6: Sync with Capacitor (uses run_cap_sync_with_workaround defined above for Xcode 26)
safe_execute "Syncing with Capacitor" "run_cap_sync_with_workaround" || exit 6
# Step 6.7: Verify the synced web bundle has production server defaults
if [ "$BUILD_MODE" = "production" ]; then
safe_execute "Checking production bundle" "./scripts/check-prod-bundle.sh ios/App/App/public" || exit 10
fi
# Step 7: Generate assets
safe_execute "Generating assets" "generate_ios_assets" || exit 7
@@ -750,4 +751,4 @@ fi
print_footer "iOS Build"
# Exit with success
exit 0
exit 0
+100
View File
@@ -0,0 +1,100 @@
#!/bin/bash
# check-prod-bundle.sh
# Fails if a built web bundle has test/dev server URLs baked in as defaults.
#
# Native packaging (gradlew bundleRelease, Xcode archive) ships whatever web
# bundle was last synced into the native project, whether it came from a
# --test, --dev, or --prod build. Run this on the bundle before uploading.
#
# Usage:
# ./scripts/check-prod-bundle.sh [PATH...]
#
# Each PATH is a directory (e.g. android/app/src/main/assets/public,
# ios/App/App/public, an .xcarchive) or an .aab, .apk, or .ipa file.
# With no PATH, checks the synced Android and iOS web assets plus the
# release AAB if it exists.
#
# Detection: the canary URLs below appear in src/ only as AppString.TEST_*
# enum values, which minify to `x.TEST_..._SERVER="<url>"`. Any other quoted
# occurrence is a VITE_* default compiled in from .env.test or
# .env.development (.env.development also uses the test image server).
#
# Exit codes: 0 = clean, 1 = test defaults found, 2 = bad input
source "$(dirname "$0")/common.sh"
CANARY_REGEX='"https://test(-image-api|-notify-api)?\.timesafari\.app"'
ENUM_REGEX='TEST[0-9]*_[A-Z_]+="https'
# Prints offending snippets from the JS files under a directory; returns 1 if any.
check_js_dir() {
local dir="$1"
local js_count
js_count=$(find "$dir" -name "*.js" -path "*assets*" | wc -l | tr -d ' ')
if [ "$js_count" = "0" ]; then
log_error "No JS assets found under $dir"
return 2
fi
local hits
hits=$(find "$dir" -name "*.js" -path "*assets*" -print0 \
| xargs -0 grep -ohE ".{0,40}${CANARY_REGEX}" \
| grep -vE "$ENUM_REGEX")
if [ -n "$hits" ]; then
log_error "Test/dev server defaults found in bundle:"
echo "$hits" | sed 's/^/ /' >&2
return 1
fi
return 0
}
check_path() {
local path="$1"
local result
if [ -d "$path" ]; then
check_js_dir "$path"
result=$?
elif [ -f "$path" ]; then
case "$path" in
*.aab|*.apk|*.ipa) ;;
*)
log_error "Unsupported file type: $path"
return 2
;;
esac
local tmp
tmp=$(mktemp -d)
unzip -q "$path" '*public/assets/*.js' -d "$tmp" 2>/dev/null
check_js_dir "$tmp"
result=$?
rm -rf "$tmp"
else
log_error "Not found: $path"
return 2
fi
if [ "$result" = "0" ]; then
log_success "Production defaults OK: $path"
else
log_error "Not a production bundle: $path"
fi
return $result
}
paths=("$@")
if [ ${#paths[@]} -eq 0 ]; then
for p in android/app/src/main/assets/public \
ios/App/App/public \
android/app/build/outputs/bundle/release/app-release.aab; do
[ -e "$p" ] && paths+=("$p")
done
fi
status=0
for p in "${paths[@]}"; do
check_path "$p"
rc=$?
[ $rc -gt $status ] && status=$rc
done
exit $status
+10
View File
@@ -183,6 +183,16 @@ setup_build_env() {
export VITE_GIT_HASH="$git_hash"
log_debug "Set VITE_GIT_HASH=$git_hash"
# Vite derives import.meta.env.DEV/PROD from NODE_ENV, not from --mode.
# Without this, every native build reports DEV=false and loads the
# production .env file in vite.config.common.mts.
case "$build_mode" in
"production") export NODE_ENV=production ;;
"test") export NODE_ENV=test ;;
*) export NODE_ENV=development ;;
esac
log_debug "Set NODE_ENV=$NODE_ENV"
case $build_type in
"capacitor")
export VITE_PLATFORM=capacitor
+5 -1
View File
@@ -2,7 +2,7 @@
/**
* Restore Local Capacitor Plugins
*
* This script ensures that local custom plugins (SafeArea and SharedImage)
* This script ensures that local custom plugins (SafeArea, SharedImage, NotificationInspector)
* are present in capacitor.plugins.json after `npx cap sync` runs.
*
* The capacitor.plugins.json file is auto-generated by Capacitor and gets
@@ -28,6 +28,10 @@ const LOCAL_PLUGINS = [
{
pkg: 'SharedImage',
classpath: 'app.timesafari.sharedimage.SharedImagePlugin'
},
{
pkg: 'NotificationInspector',
classpath: 'app.timesafari.notifications.NotificationInspectorPlugin'
}
];
-103
View File
@@ -1,103 +0,0 @@
#!/bin/bash
# Type Safety Pre-commit Check Script
# This script ensures type safety before commits by running linting and type checking
set -e
echo "🔍 Running Type Safety Pre-commit Checks..."
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Function to print colored output
print_status() {
echo -e "${GREEN}✅ $1${NC}"
}
print_warning() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
print_error() {
echo -e "${RED}❌ $1${NC}"
}
# Check if we're in the right directory
if [ ! -f "package.json" ]; then
print_error "Must run from project root directory"
exit 1
fi
# Step 1: Run ESLint with TypeScript rules
print_status "Running ESLint TypeScript checks..."
if npm run lint > /dev/null 2>&1; then
print_status "ESLint passed - no type safety issues found"
else
print_error "ESLint failed - type safety issues detected"
echo ""
echo "Running lint with details..."
npm run lint
echo ""
print_error "Please fix the above type safety issues before committing"
exit 1
fi
# Step 2: Run TypeScript type checking
print_status "Running TypeScript type checking..."
if npm run type-check > /dev/null 2>&1; then
print_status "TypeScript compilation passed"
else
print_error "TypeScript compilation failed"
echo ""
echo "Running type check with details..."
npm run type-check
echo ""
print_error "Please fix the above TypeScript errors before committing"
exit 1
fi
# Step 3: Check for any remaining 'any' types
print_status "Scanning for any remaining 'any' types..."
ANY_COUNT=$(grep -r "any" src/ --include="*.ts" --include="*.vue" | grep -v "// eslint-disable" | grep -v "eslint-disable-next-line" | wc -l)
if [ "$ANY_COUNT" -eq 0 ]; then
print_status "No 'any' types found in source code"
else
print_warning "Found $ANY_COUNT instances of 'any' type usage"
echo ""
echo "Instances found:"
grep -r "any" src/ --include="*.ts" --include="*.vue" | grep -v "// eslint-disable" | grep -v "eslint-disable-next-line" || true
echo ""
print_error "Please replace 'any' types with proper TypeScript types before committing"
exit 1
fi
# Step 4: Verify database migration status
print_status "Checking database migration status..."
if grep -r "databaseUtil" src/ --include="*.ts" --include="*.vue" > /dev/null 2>&1; then
print_warning "Found databaseUtil imports - ensure migration is complete"
echo ""
echo "Files with databaseUtil imports:"
grep -r "databaseUtil" src/ --include="*.ts" --include="*.vue" | head -5 || true
echo ""
print_warning "Consider completing database migration to PlatformServiceMixin"
else
print_status "No databaseUtil imports found - migration appears complete"
fi
# All checks passed
echo ""
print_status "All type safety checks passed! 🎉"
print_status "Your code is ready for commit"
echo ""
echo "📚 Remember to follow the Type Safety Guidelines:"
echo " - doc/typescript-type-safety-guidelines.md"
echo " - Use proper error handling patterns"
echo " - Leverage existing type definitions"
echo " - Run 'npm run lint-fix' for automatic fixes"
exit 0
+40 -6
View File
@@ -360,6 +360,7 @@
<script lang="ts">
import { Vue, Component } from "vue-facing-decorator";
import { Capacitor } from "@capacitor/core";
import { NotificationIface } from "./constants/app";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
@@ -382,6 +383,33 @@ export default class App extends Vue {
async turnOffNotifications(
notification: NotificationIface,
): Promise<boolean> {
// On native (iOS/Android) we don't use web push; the callback handles cancel + state in the view.
// The callback is the one passed for this specific modal (New Activity or Daily Reminder), so we only turn off that one.
if (Capacitor.isNativePlatform()) {
// A false callback means the view refused the off (AlertSearch revoke
// failed). Leave the existing "Notifications are off." toast for every
// other callback, which returns void.
let turnedOff = true;
if (notification.callback) {
const callbackResult = await notification.callback(true);
if (callbackResult === false) {
turnedOff = false;
}
}
if (turnedOff) {
this.$notify(
{
group: "alert",
type: "info",
title: "Finished",
text: "Notifications are off.",
},
5000,
);
}
return turnedOff;
}
let subscription: PushSubscriptionJSON | null = null;
let allGoingOff = false;
@@ -464,7 +492,17 @@ export default class App extends Vue {
return false;
});
const message = pushServerSuccess
// Ask the view before announcing success. A callback that returns false
// (failed AlertSearch revoke) keeps the existing failure sentence.
// Callbacks that return void, including Daily Reminder, keep today's copy.
let callbackRefused = false;
if (notification.callback) {
const callbackResult = await notification.callback(pushServerSuccess);
callbackRefused = callbackResult === false;
}
const turnedOff = pushServerSuccess && !callbackRefused;
const message = turnedOff
? "Notification is off."
: "Notification is still on. Try to turn it off again.";
@@ -478,11 +516,7 @@ export default class App extends Vue {
5000,
);
if (notification.callback) {
notification.callback(pushServerSuccess);
}
return pushServerSuccess;
return turnedOff;
} catch (error) {
this.$logAndConsole(
"Error turning off notifications: " + JSON.stringify(error),
+2 -7
View File
@@ -130,6 +130,7 @@
<script lang="ts">
import { Vue, Component, Prop } from "vue-facing-decorator";
import { NotificationIface } from "@/constants/app";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { SOMEONE_UNNAMED } from "@/constants/entities";
@@ -149,10 +150,7 @@ export default class BulkMembersDialog extends Vue {
@Prop({ required: true }) isOrganizer!: boolean;
// Vue notification system
$notify!: (
notification: { group: string; type: string; title: string; text: string },
timeout?: number,
) => void;
$notify!: (notification: NotificationIface, timeout?: number) => void;
// Notification system
notify!: ReturnType<typeof createNotifyHelpers>;
@@ -381,9 +379,6 @@ export default class BulkMembersDialog extends Vue {
contact,
);
if (result.success) {
if (result.embeddedRecordError) {
throw new Error(result.embeddedRecordError);
}
await this.$updateContact(member.did, { registered: true });
} else {
throw result;
+3
View File
@@ -25,6 +25,7 @@
<p :class="textClasses">{{ text }}</p>
<button
v-if="option1Text"
:class="option1ButtonClasses"
@click="handleOption1(close)"
>
@@ -32,6 +33,7 @@
</button>
<button
v-if="option2Text"
:class="option2ButtonClasses"
@click="handleOption2(close)"
>
@@ -39,6 +41,7 @@
</button>
<button
v-if="option3Text"
:class="option3ButtonClasses"
@click="handleOption3(close)"
>
+1
View File
@@ -106,6 +106,7 @@ import { Router } from "vue-router";
import * as R from "ramda";
import { NotificationIface } from "../constants/app";
import { Contact } from "../db/tables/contacts";
import { logger } from "../utils/logger";
import { createNotifyHelpers, TIMEOUTS } from "@/utils/notify";
+1 -1
View File
@@ -135,7 +135,7 @@ export default class EntitySummaryButton extends Vue {
}
// If the entity does not have a set name, but is not the special "Unnamed", use their DID
return this.entity?.did;
return this.entity?.did ?? "";
}
/**
+20 -1
View File
@@ -450,7 +450,26 @@ export default class GiftedDialog extends Vue {
TIMEOUTS.MODAL,
);
} else {
this.safeNotify.success("That gift was recorded.", TIMEOUTS.VERY_LONG);
if (result.embeddedRecordError) {
// The claim was stored but the server could not record part of it,
// eg. the link to the project this gift came from. Reporting a plain
// success here is how such a gift comes to sit on a project page
// that never shows it.
logger.warn(
"Give recorded but part of it was not:",
result.embeddedRecordError,
);
this.safeNotify.warning(
"That gift was recorded, but some of it was not: " +
result.embeddedRecordError,
TIMEOUTS.MODAL,
);
} else {
this.safeNotify.success(
"That gift was recorded.",
TIMEOUTS.VERY_LONG,
);
}
// Show seed phrase backup reminder if needed
try {
+6 -6
View File
@@ -854,19 +854,19 @@ export default class ImageMethodDialog extends Vue {
formData.append("image", this.blob, this.fileName || "photo.jpg");
formData.append("claimType", this.claimType);
try {
const imageServer =
(await this.$accountSettings()).imageServer || DEFAULT_IMAGE_API_SERVER;
if (
window.location.hostname === "localhost" &&
!DEFAULT_IMAGE_API_SERVER.includes("localhost")
!imageServer.includes("localhost")
) {
logger.log(
"Using shared image API server, so only users on that server can play with images.",
);
}
const response = await axios.post(
DEFAULT_IMAGE_API_SERVER + "/image",
formData,
{ headers },
);
const response = await axios.post(imageServer + "/image", formData, {
headers,
});
this.uploading = false;
this.close();
-3
View File
@@ -43,9 +43,6 @@ export default class InfiniteScroll extends Vue {
/** Intersection Observer instance for detecting scroll position */
private observer!: IntersectionObserver;
/** Flag to track initial render state */
private isInitialRender = true;
/** Flag to prevent multiple simultaneous loading states */
private isLoading = false;
+7 -7
View File
@@ -251,7 +251,7 @@ export default class PhotoDialog extends Vue {
* Provides cached access to platform capabilities
*/
get platformCapabilities() {
return this.$platformService.getCapabilities();
return this.platformService.getCapabilities();
}
// =================================================
@@ -556,19 +556,19 @@ export default class PhotoDialog extends Vue {
formData.append("image", this.blob, this.fileName || "photo.jpg");
formData.append("claimType", this.claimType);
try {
const imageServer =
(await this.$accountSettings()).imageServer || DEFAULT_IMAGE_API_SERVER;
if (
window.location.hostname === "localhost" &&
!DEFAULT_IMAGE_API_SERVER.includes("localhost")
!imageServer.includes("localhost")
) {
logger.log(
"Using shared image API server, so only users on that server can play with images.",
);
}
const response = await axios.post(
DEFAULT_IMAGE_API_SERVER + "/image",
formData,
{ headers },
);
const response = await axios.post(imageServer + "/image", formData, {
headers,
});
this.uploading = false;
this.close();
+61 -16
View File
@@ -67,7 +67,7 @@
class="block w-full text-center text-md font-bold uppercase bg-blue-600 text-white mt-2 px-2 py-2 rounded-md"
@click="handleTurnOnNotifications"
>
Turn on Daily Reminder
{{ isDailyCheck ? "Turn on New Activity Notifications" : "Turn on Daily Reminder" }}
</button>
</div>
@@ -95,6 +95,7 @@ import {
NOTIFY_PUSH_PERMISSION_ERROR,
NOTIFY_PUSH_SETUP_UNDERWAY,
NOTIFY_PUSH_SUCCESS,
NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY,
NOTIFY_PUSH_SETUP_ERROR,
NOTIFY_PUSH_SUBSCRIPTION_ERROR,
PUSH_NOTIFICATION_TIMEOUT_SHORT,
@@ -158,6 +159,13 @@ export default class PushNotificationPermission extends Vue {
pushType = "";
/** When true, dialog only returns time/message to parent; parent does cancel+schedule (avoids double schedule on edit). */
skipScheduleForOpen = false;
/**
* When true, the dialog is a time picker and nothing else: no permission
* request, no web-push subscription, no settings write. Used by delivery
* channels that carry their own schedule -- SMS sends its hour to the
* notify-api rather than arming anything on this device.
*/
timeOnlyForOpen = false;
/** When set (e.g. 10), passed to plugin for dev/test fast rollover. */
rolloverIntervalMinutesForSchedule: number | undefined = undefined;
serviceWorkerReady = false;
@@ -173,14 +181,27 @@ export default class PushNotificationPermission extends Vue {
async open(
pushType: string,
callback?: (success: boolean, time: string, message?: string) => void,
options?: { skipSchedule?: boolean; rolloverIntervalMinutes?: number },
options?: {
skipSchedule?: boolean;
rolloverIntervalMinutes?: number;
timeOnly?: boolean;
},
) {
this.callback = callback || this.callback;
this.isVisible = true;
this.pushType = pushType;
this.skipScheduleForOpen = options?.skipSchedule ?? false;
this.timeOnlyForOpen = options?.timeOnly ?? false;
this.rolloverIntervalMinutesForSchedule = options?.rolloverIntervalMinutes;
// Time-only callers never subscribe to anything, so the web-push
// handshake would only be a way to fail before showing a clock.
if (this.timeOnlyForOpen) {
this.serviceWorkerReady = true;
this.messageInput = "";
return;
}
// Native platforms: Skip web push initialization
if (this.isNativePlatform) {
logger.debug(
@@ -588,8 +609,8 @@ export default class PushNotificationPermission extends Vue {
* For native platforms, always returns true (no VAPID needed)
*/
get isSystemReady(): boolean {
if (this.isNativePlatform) {
return true; // Native doesn't need VAPID/service worker
if (this.isNativePlatform || this.timeOnlyForOpen) {
return true; // Neither needs VAPID/service worker
}
return this.serviceWorkerReady && !!this.vapidKey;
}
@@ -600,8 +621,8 @@ export default class PushNotificationPermission extends Vue {
* For native platforms, always returns true (no VAPID needed)
*/
get canShowNotificationForm(): boolean {
if (this.isNativePlatform) {
return true; // Native doesn't need VAPID/service worker
if (this.isNativePlatform || this.timeOnlyForOpen) {
return true; // Neither needs VAPID/service worker
}
return this.serviceWorkerReady && !!this.vapidKey;
}
@@ -671,6 +692,12 @@ export default class PushNotificationPermission extends Vue {
* Close only after async flow completes so success/error $notify runs while component is mounted (fixes Android).
*/
async handleTurnOnNotifications() {
if (this.timeOnlyForOpen) {
// Nothing to arm on this device; the caller owns whatever the time means.
this.callback(true, this.notificationTimeText, this.messageInput);
this.close();
return;
}
if (this.isNativePlatform) {
await this.turnOnNativeNotifications();
} else {
@@ -758,17 +785,35 @@ export default class PushNotificationPermission extends Vue {
time24h,
);
// Determine title and body based on pushType
const title =
this.pushType === this.DAILY_CHECK_TITLE
? "Daily Check-In"
: "Daily Reminder";
const body =
this.pushType === this.DIRECT_PUSH_TITLE
? this.messageInput || this.notificationMessagePlaceholder
: "Time to check your TimeSafari activity";
// Option A: For New Activity we do not schedule the single daily reminder here.
// AccountViewView's callback will call scheduleNewActivityDualNotification(timeText),
// which uses the dual schedule (prefetch + notify) only. This keeps the two notification
// types separate and avoids a second, uncancellable reminder.
if (this.pushType === this.DAILY_CHECK_TITLE) {
logger.info(
"[PushNotificationPermission] New Activity: skipping single reminder schedule; parent will schedule dual notification",
);
const timeText = this.notificationTimeText;
await this.$saveSettings({ notifyingNewActivityTime: timeText });
logger.debug(
"[PushNotificationPermission] Settings saved: notifyingNewActivityTime",
);
this.$notify(
{
group: "alert",
type: "success",
title: NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY.title,
text: NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY.message,
},
PUSH_NOTIFICATION_TIMEOUT_LONG,
);
this.callback(true, timeText, this.messageInput);
return;
}
// Schedule notification
// Daily Reminder: schedule the single daily notification (native only).
const title = "Daily Reminder";
const body = this.messageInput || this.notificationMessagePlaceholder;
logger.info(
"[PushNotificationPermission] Scheduling native notification:",
{
+305
View File
@@ -0,0 +1,305 @@
<template>
<div v-if="visible" class="dialog-overlay">
<div class="dialog">
<!-- Step 1: enter phone number -->
<div v-if="step === 'phone'">
<h1 class="text-xl font-bold text-center mb-2">Verify Your Phone</h1>
<p class="text-sm text-slate-500 mb-4">
Enter the mobile number where you want to receive New Activity text
messages. We'll send a one-time code to confirm it's yours. Standard
message and data rates may apply.
</p>
<label for="sms-phone" class="text-slate-500 text-sm font-bold">
Mobile number
</label>
<input
id="sms-phone"
v-model="phoneNumber"
type="tel"
inputmode="tel"
autocomplete="tel"
placeholder="+1 555 123 4567"
class="block w-full rounded border border-slate-400 mt-1 mb-1 px-3 py-2"
:disabled="sending"
@keyup.enter="sendCode()"
/>
<p v-if="errorMessage" class="text-sm text-red-600 mb-2">
{{ errorMessage }}
</p>
<div class="mt-6">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
<button
type="button"
:class="primaryButtonClasses"
:disabled="sending"
@click="sendCode()"
>
<font-awesome v-if="sending" icon="spinner" spin class="mr-1" />
{{ sending ? "Sending…" : "Send Code" }}
</button>
<button
type="button"
:class="cancelButtonClasses"
:disabled="sending"
@click="onClickCancel()"
>
Cancel
</button>
</div>
</div>
</div>
<!-- Step 2: enter the code -->
<div v-else-if="step === 'code'">
<h1 class="text-xl font-bold text-center mb-2">Enter the Code</h1>
<p class="text-sm text-slate-500 mb-4">
We sent a 6-digit code to
<b>{{ sentTo }}</b
>. Enter it below to finish verifying your number.
</p>
<label for="sms-code" class="text-slate-500 text-sm font-bold">
Verification code
</label>
<input
id="sms-code"
v-model="code"
type="text"
inputmode="numeric"
autocomplete="one-time-code"
maxlength="6"
placeholder="123456"
class="block w-full tracking-[0.4em] text-center text-lg rounded border border-slate-400 mt-1 mb-1 px-3 py-2"
:disabled="verifying"
@keyup.enter="verifyCode()"
/>
<p v-if="errorMessage" class="text-sm text-red-600 mb-2">
{{ errorMessage }}
</p>
<div class="text-center mb-2">
<button
type="button"
class="text-sm text-blue-500"
:disabled="sending || verifying"
@click="resendCode()"
>
{{ sending ? "Resending…" : "Resend code" }}
</button>
</div>
<div class="mt-4">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
<button
type="button"
:class="primaryButtonClasses"
:disabled="verifying"
@click="verifyCode()"
>
<font-awesome v-if="verifying" icon="spinner" spin class="mr-1" />
{{ verifying ? "Verifying…" : "Verify" }}
</button>
<button
type="button"
:class="cancelButtonClasses"
:disabled="verifying"
@click="onClickCancel()"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { Vue, Component } from "vue-facing-decorator";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { logger } from "@/utils/logger";
import {
normalizePhoneNumber,
registerSmsPhone,
SmsApiError,
smsErrorMessage,
verifySmsPhone,
} from "@/services/notifications/smsNotificationApi";
/**
* SmsVerificationDialog Component
*
* A two-step modal that walks the user through verifying a mobile number so
* they can opt in to SMS "New Activity" notifications:
* 1. Enter phone number -> `POST /notify-sms/phone` texts a one-time code
* 2. Enter the code -> `PUT /notify-sms/phone` confirms possession
*
* On successful verification the callback fires with (true, phoneNumber), the
* number in the E.164 form the service stores, so the caller can then let the
* user turn the SMS notification on. Cancelling fires the callback with
* (false).
*
* A number this identity has already verified comes back from the POST with
* `verified: true` and no text sent, which finishes the dialog in one step.
*/
@Component({
mixins: [PlatformServiceMixin],
})
export default class SmsVerificationDialog extends Vue {
visible = false;
step: "phone" | "code" = "phone";
phoneNumber = "";
sentTo = "";
code = "";
sending = false;
verifying = false;
errorMessage = "";
/** Identity the registration is scoped to; every route is per-DID. */
activeDid = "";
callback: (success: boolean, phoneNumber?: string) => void = () => {};
/**
* Opens the dialog at the phone-entry step.
* @param activeDid - identity the number is registered under
* @param aCallback - fired with (true, phoneNumber) on success, (false) on cancel
* @param prefillPhone - optional number to pre-populate (e.g. re-verifying)
*/
open(
activeDid: string,
aCallback?: (success: boolean, phoneNumber?: string) => void,
prefillPhone = "",
) {
this.activeDid = activeDid;
this.callback = aCallback || this.callback;
this.step = "phone";
this.phoneNumber = prefillPhone;
this.sentTo = "";
this.code = "";
this.sending = false;
this.verifying = false;
this.errorMessage = "";
this.visible = true;
}
/**
* Validate the phone number and ask the service to text a code.
*
* The masked number the service echoes back is what the user sees; the
* normalized one is what later calls send, since the mask is not a number.
*/
async sendCode(): Promise<void> {
this.errorMessage = "";
const normalized = normalizePhoneNumber(this.phoneNumber);
if (!normalized || normalized.replace(/\D/g, "").length < 7) {
this.errorMessage = "Please enter a valid mobile number.";
return;
}
this.sending = true;
try {
const result = await registerSmsPhone(this.activeDid, normalized);
this.phoneNumber = normalized;
if (result.verified) {
// Already verified under this identity: nothing was texted and there
// is no code to enter.
this.visible = false;
this.callback(true, normalized);
return;
}
this.sentTo = result.phoneNumber || normalized;
// Only a dev server with SMS_DEV_ECHO_CODE returns this; it saves a
// developer with no carrier coverage from a dead-end flow.
this.code = result.devCode || "";
this.step = "code";
} catch (error) {
logger.error("[SmsVerificationDialog] sendCode failed:", error);
this.errorMessage = smsErrorMessage(
error,
"Could not send the code. Please try again.",
);
} finally {
this.sending = false;
}
}
/**
* Ask the service to send a fresh code to the same number. Sends are
* throttled to three per number per hour, so this can be refused.
*/
async resendCode(): Promise<void> {
this.errorMessage = "";
this.sending = true;
try {
const result = await registerSmsPhone(this.activeDid, this.phoneNumber);
this.sentTo = result.phoneNumber || this.sentTo;
// A number already verified comes back with no code, dev or otherwise.
this.code = result.verified ? "" : result.devCode || "";
} catch (error) {
logger.error("[SmsVerificationDialog] resendCode failed:", error);
this.errorMessage = smsErrorMessage(
error,
"Could not resend the code. Please try again.",
);
} finally {
this.sending = false;
}
}
/**
* Confirm the entered code with the service.
*
* A wrong code says how many tries are left; running out clears the code
* server-side, so the only way forward is a fresh send from step one.
*/
async verifyCode(): Promise<void> {
this.errorMessage = "";
if (!/^\d{6}$/.test(this.code.trim())) {
this.errorMessage = "Enter the 6-digit code we texted you.";
return;
}
this.verifying = true;
try {
await verifySmsPhone(this.activeDid, this.phoneNumber, this.code);
this.visible = false;
this.callback(true, this.phoneNumber);
} catch (error) {
logger.error("[SmsVerificationDialog] verifyCode failed:", error);
this.errorMessage = smsErrorMessage(
error,
"Could not verify the code. Please try again.",
);
if (
error instanceof SmsApiError &&
error.code === "SMS_CODE_ATTEMPTS_EXHAUSTED"
) {
// The stored code is gone; recovery is another send, not another guess.
this.step = "phone";
this.code = "";
}
} finally {
this.verifying = false;
}
}
onClickCancel(): void {
this.visible = false;
this.callback(false);
}
get primaryButtonClasses(): string {
return "block w-full text-center text-lg font-bold uppercase bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-2 py-3 rounded-md disabled:opacity-50";
}
get cancelButtonClasses(): string {
return "block w-full text-center text-md uppercase bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-2 py-3 rounded-md disabled:opacity-50";
}
}
</script>
+19
View File
@@ -0,0 +1,19 @@
import type { Camera, Scene } from "three";
/**
* Type declarations for World.js, which is plain JavaScript.
*
* Only the members used outside the module are declared; its internals stay
* untyped.
*/
export declare class World {
camera: Camera;
scene: Scene;
constructor(container: Element | null, vue: unknown);
update(time: number): void;
render(): void;
start(): void;
stop(): void;
setExposedWorldProperties(key: string, value: unknown): void;
}
@@ -0,0 +1,450 @@
<template>
<section class="bg-slate-100 rounded-md overflow-hidden px-4 py-4">
<!-- Backend testing -->
<div class="mb-6">
<h2 class="mb-2 font-bold">Backend Testing</h2>
<label class="block text-sm font-medium text-slate-700 mb-1">
Notification Backend URL
</label>
<input
v-model="backendUrlDraft"
type="url"
class="w-full text-sm px-3 py-2 rounded border border-slate-300 bg-white mb-1"
placeholder="Leave empty for default (DEFAULT_NOTIFY_API_SERVER)"
:disabled="busy"
@keydown.enter="onSaveBackendUrl"
/>
<p class="text-xs text-slate-500 mb-2">
Active:
<code class="text-[11px] break-all">{{ activeBackendUrl }}</code>
</p>
<button
class="w-full text-sm mb-4 px-3 py-2 rounded border border-slate-300 bg-white"
:disabled="busy"
:class="{ 'opacity-50 cursor-not-allowed': busy }"
@click="onSaveBackendUrl"
>
Save Backend URL
</button>
<label class="flex items-center gap-2 text-sm mb-4 cursor-pointer">
<input
v-model="testModeEnabled"
type="checkbox"
class="rounded border-slate-300"
:disabled="busy"
@change="onTestModeChange"
/>
<span>Test Mode</span>
</label>
<label class="flex items-center gap-2 text-sm mb-1 cursor-pointer">
<input
v-model="bypassAuthEnabled"
type="checkbox"
class="rounded border-slate-300"
:disabled="busy"
@change="onBypassAuthChange"
/>
<span>Skip JWT Authentication (Local Development Only)</span>
</label>
<p class="text-xs text-slate-500 mb-4">
Enable only when using a local development server (for example localhost
or ngrok) that intentionally accepts unauthenticated notification
requests.
</p>
<div class="flex flex-col gap-2 mb-4">
<button
class="w-full text-md bg-gradient-to-b from-emerald-400 to-emerald-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md"
:disabled="busy"
:class="{ 'opacity-50 cursor-not-allowed': busy }"
@click="onRegisterToken"
>
Register Token Now
</button>
<button
class="w-full text-md bg-gradient-to-b from-cyan-500 to-cyan-800 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md"
:disabled="busy"
:class="{ 'opacity-50 cursor-not-allowed': busy }"
@click="onUploadAlertAuthorization"
>
Upload AlertSearch Authorization
</button>
<p
v-if="alertAuthorizationStatus"
class="text-xs rounded px-3 py-2 border"
:class="
alertAuthorizationStatus.ok
? 'text-emerald-900 bg-emerald-50 border-emerald-200'
: 'text-rose-900 bg-rose-50 border-rose-200'
"
role="status"
>
{{ alertAuthorizationStatus.message }}
</p>
<p v-else class="text-xs text-slate-500">
Manually mints and uploads 100 delegated day JWTs. Requires an active
did:ethr identity and JWT authentication; Test Mode is not used.
</p>
<button
class="w-full text-md bg-gradient-to-b from-amber-400 to-amber-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md"
:disabled="busy"
:class="{ 'opacity-50 cursor-not-allowed': busy }"
@click="onSendRealWakeupPing"
>
Send Real WAKEUP_PING
</button>
<p
v-if="realWakeupStatus"
class="text-xs rounded px-3 py-2 border"
:class="
realWakeupStatus.ok
? 'text-emerald-900 bg-emerald-50 border-emerald-200'
: 'text-rose-900 bg-rose-50 border-rose-200'
"
role="status"
>
{{ realWakeupStatus.message }}
</p>
<p v-else class="text-xs text-slate-500">
FCM delivery diagnostic only — backend `/debug/send-wakeup`. The app
no longer schedules api_* notifications from WAKEUP_PING.
</p>
</div>
<div class="mb-4">
<h3 class="text-sm font-bold mb-1">Current FCM Token</h3>
<div
v-if="fcmToken"
class="bg-white rounded border border-slate-200 px-3 py-2 text-xs font-mono break-all flex gap-2 items-start"
>
<span class="min-w-0 flex-1">{{ truncatedFcmToken }}</span>
<button
type="button"
class="shrink-0 text-sm px-2 py-1 rounded border border-slate-300 bg-slate-50"
@click="onCopyFcmToken"
>
Copy
</button>
</div>
<p
v-else
class="text-sm text-slate-500 bg-white rounded px-3 py-2 border border-slate-200"
>
(not available — try Register Token Now on native)
</p>
</div>
<div class="mb-2">
<h3 class="text-sm font-bold mb-1">Backend Status</h3>
<dl
class="bg-white rounded border border-slate-200 px-3 py-2 text-xs space-y-1"
>
<div class="flex gap-2">
<dt class="text-slate-500 shrink-0">URL</dt>
<dd class="break-all font-mono">{{ activeBackendUrl }}</dd>
</div>
<div class="flex gap-2">
<dt class="text-slate-500 shrink-0">testMode</dt>
<dd>{{ testModeEnabled ? "true" : "false" }}</dd>
</div>
<div class="flex gap-2">
<dt class="text-slate-500 shrink-0">bypassAuth</dt>
<dd>{{ bypassAuthEnabled ? "true" : "false" }}</dd>
</div>
</dl>
</div>
</div>
<!-- SECTION D: Pending Notification Inspector -->
<div class="mb-6">
<div class="flex items-center gap-3 mb-2">
<h2 class="font-bold">Pending Notification Inspector</h2>
<button
class="ms-auto text-sm px-3 py-2 rounded border border-slate-300 bg-white"
:disabled="busy"
:class="{ 'opacity-50 cursor-not-allowed': busy }"
@click="refreshPending"
>
Refresh
</button>
</div>
<div
v-if="pendingInspectorMessage"
class="text-sm text-amber-900 bg-amber-50 rounded px-3 py-2 border border-amber-200"
role="status"
>
{{ pendingInspectorMessage }}
</div>
<div
v-else-if="pending.length === 0"
class="text-sm text-slate-500 bg-white rounded px-3 py-2 border border-slate-200"
>
(none)
</div>
<ul v-else class="bg-white rounded border border-slate-200 divide-y">
<li
v-for="p in pending"
:key="p.identifier"
class="px-3 py-2 text-sm flex gap-3 items-start"
>
<code class="truncate min-w-0">{{ p.identifier }}</code>
<span
class="ms-auto text-xs text-right text-slate-600 max-w-[58%] shrink-0"
>
<template v-if="p.wallClockMillis != null">
<span class="block font-medium">{{
formatIsoMs(p.wallClockMillis)
}}</span>
<span class="block text-[10px] text-slate-400"
>Scheduled target ({{ p.wallClockSource }})</span
>
<span
v-if="
p.nextTriggerDate != null &&
Math.abs(p.nextTriggerDate - p.wallClockMillis) > 5000
"
class="block text-[10px] text-amber-800 mt-0.5"
>iOS nextTriggerDate (resamples on each fetch for interval
triggers): {{ formatIsoMs(p.nextTriggerDate) }}</span
>
</template>
<template v-else>
<span class="block">{{
formatIsoMs(p.nextTriggerDate ?? null)
}}</span>
<span class="block text-[10px] text-slate-400"
>iOS nextTriggerDate</span
>
</template>
</span>
</li>
</ul>
</div>
<!-- SECTION E: Clear Notifications -->
<div class="mb-6">
<h2 class="mb-2 font-bold">Clear Notifications</h2>
<button
class="w-full text-md bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md"
:disabled="busy"
:class="{ 'opacity-50 cursor-not-allowed': busy }"
@click="onClearNotifications"
>
Clear Notifications
</button>
</div>
<!-- SECTION G: Event Log -->
<div>
<div class="flex items-center gap-3 mb-2">
<h2 class="font-bold">Event Log</h2>
<button
class="ms-auto text-sm px-3 py-2 rounded border border-slate-300 bg-white"
@click="NotificationDebugService.clearDebugLogs()"
>
Clear Log
</button>
</div>
<div
class="bg-white rounded border border-slate-200 px-3 py-2 text-xs font-mono whitespace-pre-wrap min-h-[8rem]"
>
<div v-if="eventLog.length === 0" class="text-slate-400">(empty)</div>
<div v-for="(line, idx) in eventLog" v-else :key="idx">
{{ line }}
</div>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { copyToClipboard } from "@/services/ClipboardService";
import { subscribe } from "@/services/notifications/NotificationDebugEvents";
import { NotificationDebugService } from "@/services/notifications/NotificationDebugService";
type PendingInfo = {
identifier: string;
nextTriggerDate?: number | null;
triggerType?: string | null;
wallClockMillis?: number | null;
wallClockSource?: string | null;
};
const busy = ref(false);
const pending = ref<PendingInfo[]>([]);
const pendingInspectorMessage = ref<string | null>(null);
const backendUrlDraft = ref("");
const testModeEnabled = ref(NotificationDebugService.isTestModeEnabled());
const bypassAuthEnabled = ref(NotificationDebugService.isBypassAuthEnabled());
const fcmToken = ref<string | null>(NotificationDebugService.getFcmToken());
const activeBackendUrl = ref(NotificationDebugService.getActiveBackendUrl());
const realWakeupStatus = ref<{ ok: boolean; message: string } | null>(null);
const alertAuthorizationStatus = ref<{
ok: boolean;
message: string;
} | null>(null);
const truncatedFcmToken = computed(() => {
const t = fcmToken.value?.trim() ?? "";
if (!t) {
return "";
}
if (t.length <= 24) {
return t;
}
return `${t.slice(0, 12)}…${t.slice(-8)}`;
});
const eventLog = ref<string[]>([]);
let unsubscribeEventLog: (() => void) | undefined;
function formatIsoMs(ms: number | null | undefined): string {
if (ms == null || !Number.isFinite(ms)) {
return "";
}
return new Date(ms).toISOString();
}
async function withBusy(fn: () => Promise<void>): Promise<void> {
if (busy.value) return;
busy.value = true;
try {
await fn();
} finally {
busy.value = false;
}
}
async function refreshPending(): Promise<void> {
const result = await NotificationDebugService.getPendingNotifications();
pending.value = result.pending;
pendingInspectorMessage.value = result.inspectorUnavailableMessage ?? null;
}
async function onClearNotifications(): Promise<void> {
await withBusy(async () => {
await NotificationDebugService.clearNotifications();
await refreshPending();
});
}
function syncBackendState(): void {
backendUrlDraft.value =
NotificationDebugService.getBackendUrlOverride() ?? "";
testModeEnabled.value = NotificationDebugService.isTestModeEnabled();
bypassAuthEnabled.value = NotificationDebugService.isBypassAuthEnabled();
fcmToken.value = NotificationDebugService.getFcmToken();
activeBackendUrl.value = NotificationDebugService.getActiveBackendUrl();
}
function onSaveBackendUrl(): void {
NotificationDebugService.saveBackendBaseUrl(backendUrlDraft.value);
syncBackendState();
}
function onTestModeChange(): void {
NotificationDebugService.setTestModeEnabled(testModeEnabled.value);
}
function onBypassAuthChange(): void {
NotificationDebugService.setBypassAuthEnabled(bypassAuthEnabled.value);
}
async function onRegisterToken(): Promise<void> {
await withBusy(async () => {
try {
await NotificationDebugService.registerTokenNow();
} catch {
// logged in panel
} finally {
fcmToken.value = NotificationDebugService.getFcmToken();
}
});
}
async function onUploadAlertAuthorization(): Promise<void> {
alertAuthorizationStatus.value = null;
await withBusy(async () => {
const result =
await NotificationDebugService.uploadAlertSearchAuthorization();
alertAuthorizationStatus.value = result.ok
? {
ok: true,
message: [
`Uploaded ${result.jwtCount} JWTs (HTTP ${result.status}).`,
`Batch ${result.batchId}.`,
`${result.timezone}: ${result.firstDay} through ${result.lastDay}.`,
]
.filter(Boolean)
.join(" "),
}
: {
ok: false,
message: [
`AlertSearch authorization upload failed: ${result.errorMessage}`,
result.status != null ? `(HTTP ${result.status})` : undefined,
result.errorCode ? `Code: ${result.errorCode}.` : undefined,
]
.filter(Boolean)
.join(" "),
};
});
}
function formatRealWakeupStatusMessage(
result: Awaited<
ReturnType<typeof NotificationDebugService.sendRealWakeupPing>
>,
): string {
if (result.ok) {
const parts = ["Real WAKEUP_PING sent via backend."];
const suffix = result.responseBody?.fcmTokenSuffix?.trim();
if (suffix) {
parts.push(`token …${suffix}`);
}
return parts.join(" ");
}
const parts = [`Real WAKEUP_PING failed: ${result.errorMessage}`];
if (result.status != null) {
parts.push(`(HTTP ${result.status})`);
}
return parts.join(" ");
}
async function onSendRealWakeupPing(): Promise<void> {
realWakeupStatus.value = null;
await withBusy(async () => {
const result = await NotificationDebugService.sendRealWakeupPing();
realWakeupStatus.value = {
ok: result.ok,
message: formatRealWakeupStatusMessage(result),
};
});
}
async function onCopyFcmToken(): Promise<void> {
const token = fcmToken.value?.trim();
if (!token) {
return;
}
await copyToClipboard(token);
}
onMounted(() => {
unsubscribeEventLog = subscribe((entries) => {
eventLog.value = [...entries];
});
syncBackendState();
void refreshPending();
});
onBeforeUnmount(() => {
unsubscribeEventLog?.();
});
</script>
-97
View File
@@ -1,97 +0,0 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { inject } from "vue";
import { NotificationIface } from "../constants/app";
/**
* Vue 3 composable for notifications
* Provides a concise API for common notification patterns
*/
export const NOTIFICATION_TIMEOUTS = {
BRIEF: 1000, // Very brief toasts ("Sent..." messages)
SHORT: 2000, // Short notifications (clipboard copies, quick confirmations)
STANDARD: 3000, // Standard notifications (success messages, general info)
LONG: 5000, // Longer notifications (errors, warnings, important info)
VERY_LONG: 7000, // Very long notifications (complex operations)
MODAL: -1, // Modal confirmations (no auto-dismiss)
} as const;
export function useNotifications() {
// Inject the notify function from the app
const notify =
inject<(notification: NotificationIface, timeout?: number) => void>(
"notify",
);
if (!notify) {
throw new Error(
"useNotifications must be used within a component that has $notify available",
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function success(_notification: NotificationIface, _timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function error(_notification: NotificationIface, _timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function warning(_notification: NotificationIface, _timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function info(_notification: NotificationIface, _timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function toast(_title: string, _text?: string, _timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function copied(_item: string, _timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function sent(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function confirm(
_text: string,
_onYes: () => Promise<void>,
_timeout?: number,
) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function confirmationSubmitted(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function genericError(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function genericSuccess(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function alreadyConfirmed(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function cannotConfirmIssuer(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function cannotConfirmHidden(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function notRegistered(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function notAGive(_timeout?: number) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function notificationOff(
_title: string,
_callback: (success: boolean) => Promise<void>,
_timeout?: number,
) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function downloadStarted(_format: string = "Dexie", _timeout?: number) {}
return {
success,
error,
warning,
info,
toast,
copied,
sent,
confirm,
confirmationSubmitted,
genericError,
genericSuccess,
alreadyConfirmed,
cannotConfirmIssuer,
cannotConfirmHidden,
notRegistered,
notAGive,
notificationOff,
downloadStarted,
};
}
+14 -3
View File
@@ -40,6 +40,8 @@ export const ACCOUNT_VIEW_CONSTANTS = {
NO_PROFILE_LOCATION: "No profile location is saved.",
RELOAD_VAPID:
"Now reload the app to get a new VAPID to use with this push server.",
NOTIFY_SERVER_INFO:
"The notify server URL can be modified on the Notification Debug screen.",
},
// Warning messages
@@ -57,11 +59,20 @@ export const ACCOUNT_VIEW_CONSTANTS = {
// Notification messages
NOTIFICATIONS: {
NEW_ACTIVITY_INFO: `
This will only notify you when there is new relevant activity for you personally.
Note that it runs on your device and many factors may affect delivery,
so if you want a reliable but simple daily notification then choose a 'Reminder'.
This will notify you with an app message when there is new relevant activity for you personally.
Do you want more details?
`,
NEW_ACTIVITY_SMS_INFO: `
This is opt-in: by turning it on you agree to receive text messages when there is new relevant activity for you personally.
Standard message and data rates may apply, and you can turn it off at any time.
Do you want more details?
`,
SMS_OPT_IN_CHOICE: `
This is opt-in: by entering your phone number you agree to receive text messages when there is new relevant activity for you personally.
Standard message and data rates may apply, and you can turn it off at any time.
`,
SMS_FORGET_PHONE_CONFIRM:
"This will remove your phone number and turn off all text messages. You will have to verify a number again to re-enable them. Are you sure?",
REMINDER_INFO: `
This will notify you at a specific time each day.
Note that it does not give you personalized notifications,
+10 -1
View File
@@ -26,6 +26,10 @@ export enum AppString {
TEST1_PUSH_SERVER = "https://test.timesafari.app",
TEST2_PUSH_SERVER = "https://timesafari-pwa.anomalistlabs.com",
PROD_NOTIFY_API_SERVER = "https://notify-api.timesafari.app",
TEST_NOTIFY_API_SERVER = "https://test-notify-api.timesafari.app",
LOCAL_NOTIFY_API_SERVER = "http://127.0.0.1:3003",
NO_CONTACT_NAME = "(no name)",
}
@@ -47,6 +51,11 @@ export const DEFAULT_PARTNER_API_SERVER =
export const DEFAULT_PUSH_SERVER =
import.meta.env.VITE_DEFAULT_PUSH_SERVER || AppString.PROD_PUSH_SERVER;
/** Base URL of the notify-api (FCM wakeup registration and SMS notifications). */
export const DEFAULT_NOTIFY_API_SERVER =
import.meta.env.VITE_DEFAULT_NOTIFY_API_SERVER ||
AppString.PROD_NOTIFY_API_SERVER;
export const IMAGE_TYPE_PROFILE = "profile";
/**
@@ -70,7 +79,7 @@ export interface NotificationIface {
type: string; // "toast" | "info" | "success" | "warning" | "danger"
title?: string;
text?: string;
callback?: (success: boolean) => Promise<void>; // if this triggered an action
callback?: (success: boolean) => Promise<void | boolean>; // if this triggered an action
noText?: string;
onCancel?: (stopAsking?: boolean) => Promise<void>;
onNo?: (stopAsking?: boolean) => Promise<void>;
+27
View File
@@ -0,0 +1,27 @@
/**
* JWT lifetime for the single-token native background prefetch path
* (`accessTokenForBackgroundNotifications`). Confirm the maximum `exp` Endorser
* accepts before raising this.
*/
export const BACKGROUND_JWT_EXPIRY_DAYS = 90;
export const BACKGROUND_JWT_EXPIRY_SECONDS =
BACKGROUND_JWT_EXPIRY_DAYS * 24 * 60 * 60;
/** Seconds in a UTC day; the frame every pool slot is cut from. */
export const BACKGROUND_JWT_SECONDS_PER_DAY = 24 * 60 * 60;
/**
* Consecutive UTC days the native background prefetch pool covers, one JWT per
* day. This is the whole forward grant the user authorizes in a single mint:
* past the last day the pool carries no credential and prefetch stops until the
* app opens again. See `doc/background-jwt-pool.md`.
*/
export const BACKGROUND_JWT_POOL_SIZE = 100;
/**
* Padding on each end of a day's validity window, for clock skew between the
* device and Endorser. Widening a window is safe; narrowing it can leave a
* prefetch inside the day with no usable token.
*/
export const BACKGROUND_JWT_WINDOW_SLACK_SECONDS = 5 * 60;
+23 -1
View File
@@ -1401,6 +1401,22 @@ export const NOTIFY_PROJECT_DELETE_IMAGE_GENERAL_ERROR = {
message: "There was an error deleting the image.",
};
// Used in: AccountViewView.vue, GiftedDetailsView.vue, NewEditProjectView.vue
// (deleteImage - the image server returned 404). The server looks an image up
// by URL and uploader, so this also happens when the image was uploaded to a
// different image server than the one in settings.
export const NOTIFY_IMAGE_DELETE_NOT_FOUND = {
title: "Image Not Deleted",
message:
"The image server in your settings has no record of that image, so it was not removed from storage. It may already be gone, or it may have been uploaded through a different image server.",
};
// Used in: GiftedDetailsView.vue (deleteImage method - image deletion error)
export const NOTIFY_IMAGE_DELETE_ERROR = {
title: "Image Deletion Error",
message: "There was an error deleting the image from the image server.",
};
// Used in: NewEditProjectView.vue (validateLocation method - invalid location error)
export const NOTIFY_PROJECT_INVALID_LOCATION = {
title: "Invalid Location",
@@ -1635,12 +1651,18 @@ export const NOTIFY_PUSH_SETUP_UNDERWAY = {
"Setting up notifications for interesting activity, which takes about 10 seconds. If you don't see a final confirmation, check the 'Troubleshoot' page.",
};
// Used in: PushNotificationPermission.vue (turnOnNotifications method - success)
// Used in: PushNotificationPermission.vue (turnOnNotifications method - success, Daily Reminder)
export const NOTIFY_PUSH_SUCCESS = {
title: "Notifications On",
message: "Daily Reminder notifications are now enabled.",
};
// Used in: PushNotificationPermission.vue (turnOnNotifications method - success, New Activity only)
export const NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY = {
title: "Notifications On",
message: "New Activity notifications are now enabled.",
};
// Used in: PushNotificationPermission.vue (turnOnNotifications method - general error)
export const NOTIFY_PUSH_SETUP_ERROR = {
title: "Error Setting Notification Permissions",
+19 -1
View File
@@ -225,7 +225,7 @@ const MIGRATIONS = [
},
{
name: "008_remove_iViewContent_from_contacts",
// Recreate contacts without iViewContent: backup, drop, recreate, restore
// Recreate contacts without iViewContent (since we use hideTheirContent instead): backup, drop, recreate, restore
sql: `
PRAGMA foreign_keys = OFF;
@@ -276,6 +276,24 @@ const MIGRATIONS = [
ALTER TABLE settings ADD COLUMN reminderFastRolloverForTesting BOOLEAN DEFAULT FALSE;
`,
},
{
name: "010_add_sms_notification_settings",
sql: `
-- Verified mobile number this identity registered with the notify-api
ALTER TABLE settings ADD COLUMN notifyingNewActivitySmsPhone TEXT;
-- Local time of day the notify-api was told to text, blank when off
ALTER TABLE settings ADD COLUMN notifyingNewActivitySmsTime TEXT;
-- Master switch for the SMS channel; a paused channel keeps its number
ALTER TABLE settings ADD COLUMN smsNotificationsEnabled BOOLEAN DEFAULT FALSE;
`,
},
{
name: "011_add_imageServer_to_settings",
sql: `
-- Image API server URL; blank means DEFAULT_IMAGE_API_SERVER
ALTER TABLE settings ADD COLUMN imageServer TEXT;
`,
},
];
/**
+4 -3
View File
@@ -258,13 +258,14 @@ export async function logToDb(
try {
const platform = PlatformServiceFactory.getInstance();
const timestamp = new Date().toISOString();
const todayKey = new Date().toDateString();
try {
memoryLogs.push(`${new Date().toISOString()} ${message}`);
memoryLogs.push(`${timestamp} ${message}`);
// Insert using actual schema: date, message (no level column)
await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
todayKey, // Use date string to match schema
timestamp,
`[${level.toUpperCase()}] ${message}`, // Include level in message
]);
@@ -273,7 +274,7 @@ export async function logToDb(
if (!lastCleanupDate || lastCleanupDate !== todayKey) {
const sevenDaysAgo = new Date(
new Date().getTime() - 7 * 24 * 60 * 60 * 1000,
).toDateString(); // Use date string to match schema
).toISOString();
memoryLogs = memoryLogs.filter(
(log) => log.split(" ")[0] > sevenDaysAgo,
);
+5 -1
View File
@@ -38,7 +38,7 @@ export type Settings = {
hasBackedUpSeed?: boolean; // tracks whether the user has backed up their seed phrase
hideRegisterPromptOnNewContact?: boolean;
isRegistered?: boolean;
// imageServer?: string; // if we want to allow modification then we should make image functionality optional -- or at least customizable
imageServer?: string; // image API server URL
lastName?: string; // deprecated - put all names in firstName
lastAckedOfferToUserJwtId?: string; // the last JWT ID for offer-to-user that they've acknowledged seeing
@@ -50,11 +50,15 @@ export type Settings = {
lastViewedClaimId?: string;
notifyingNewActivityTime?: string; // set to their chosen time if they have turned on daily check for new activity via the push server
notifyingNewActivitySmsPhone?: string; // verified mobile number registered with the notify-api for text alerts
notifyingNewActivitySmsTime?: string; // set to their chosen time if they have turned on new-activity texts
notifyingReminderMessage?: string; // set to their chosen message for a daily reminder
notifyingReminderTime?: string; // set to their chosen time for a daily reminder
/** Dev/test only: use 10-minute rollover interval for daily reminder (plugin rolloverIntervalMinutes) */
reminderFastRolloverForTesting?: boolean;
smsNotificationsEnabled?: boolean; // master switch for the text-message channel
partnerApiServer?: string; // partner server API URL
passkeyExpirationMinutes?: number; // passkey access token time-to-live in minutes
+13
View File
@@ -31,8 +31,13 @@ export interface AccountSettings {
bbox: BoundingBox;
}>;
notifyingNewActivityTime?: string;
notifyingNewActivitySmsPhone?: string;
notifyingNewActivitySmsTime?: string;
smsNotificationsEnabled?: boolean;
notifyingReminderMessage?: string;
notifyingReminderTime?: string;
starredPlanHandleIds?: string[];
imageServer?: string;
reminderFastRolloverForTesting?: boolean;
partnerApiServer?: string;
profileImageUrl?: string;
@@ -79,6 +84,12 @@ export interface ProfileState {
export interface NotificationState {
notifyingNewActivity: boolean;
notifyingNewActivityTime: string;
/** Master switch for the text-message channel. */
smsEnabled: boolean;
/** Verified number, kept while the channel is paused so re-enabling is free. */
notifyingNewActivitySmsPhone: string;
notifyingNewActivitySms: boolean;
notifyingNewActivitySmsTime: string;
notifyingReminder: boolean;
notifyingReminderMessage: string;
notifyingReminderTime: string;
@@ -92,6 +103,8 @@ export interface SettingsState {
activeDid: string;
apiServer: string;
apiServerInput: string;
imageServer: string;
imageServerInput: string;
partnerApiServer: string;
partnerApiServerInput: string;
webPushServer: string;
+125
View File
@@ -0,0 +1,125 @@
/**
* alertSearch response item and envelope types.
*
* These buckets are new to this app. Item shapes are taken from the endorser-ch
* SELECT lists for alertSearch, not from similarly named existing report types.
*
* Existing types that were considered and not reused:
* - GenericCredWrapper — claims lack a `claim` body; extra jwt columns differ.
* - GiveSummaryRecord / OfferSummaryRecord — those use `jwtId` and give/offer
* summary fields; alertSearch jwt rows use `id` and jwt table columns.
* - PlanSummaryAndPreviousClaim — `/plansLastUpdatedBetween` wraps `{ plan,
* wrappedClaimBefore }`; alertSearch `trackedPlanUpdates` are plan_claim rows.
* - PlanSummaryRecord — overlapping plan fields, but the app type is a subset
* (missing fulfillsLinkConfirmed, result*, etc.) and required fields differ.
* - UserProfile — partner nearby rows include `updatedAt` / `rowId` and omit
* embedding flags that UserProfile models.
*/
/**
* Server-issued ULID on a stored JWT/plan record, used as alertSearch afterId /
* beforeId. Not an authentication JWT and not a delegated notification JWT.
*/
export type AlertSearchCursorUlid = string;
/**
* JWT row from endorser `jwtsWithDidAfterId` (no claim body).
* Cursor field: `id`.
*/
export interface AlertSearchClaimRecord {
id: AlertSearchCursorUlid;
issuedAt: string;
issuer: string;
subject?: string;
claimType?: string;
handleId?: string;
fromEntity?: string;
toEntity?: string;
}
/**
* JWT row from `jwtsForUserPlanContributions` and
* `jwtsGiveActionOfferForPlanHandleIds`. `claim` is the jwt table TEXT
* (canonical JSON string); alertSearch does not JSON.parse it.
* Cursor field: `id`.
*/
export interface AlertSearchJwtWithClaimRecord extends AlertSearchClaimRecord {
claim?: string;
}
/**
* plan_claim row from `plansLastUpdatedBetween` and `plansByLocationAfterId`.
* Cursor field: `jwtId` (not `id`).
*/
export interface AlertSearchPlanRecord {
handleId: string;
jwtId: AlertSearchCursorUlid;
issuerDid?: string;
agentDid?: string;
fulfillsLinkConfirmed?: boolean | number;
fulfillsPlanClaimId?: string;
fulfillsPlanHandleId?: string;
name?: string;
description?: string;
image?: string;
endTime?: string;
startTime?: string;
locLat?: number;
locLon?: number;
resultDescription?: string;
resultIdentifier?: string;
url?: string;
}
/**
* user_profile row from partner `profilesByLocationAfterDate`.
* Profiles have no JWT `id`; partner paging uses dates decoded from cursor ULIDs.
*/
export interface AlertSearchProfileRecord {
rowId?: number;
issuerDid: string;
updatedAt?: string;
description: string;
locLat?: number;
locLon?: number;
locLat2?: number;
locLon2?: number;
}
export interface EndorserAlertSearchData {
claims: AlertSearchClaimRecord[];
personalPlanContributions: AlertSearchJwtWithClaimRecord[];
trackedPlanUpdates: AlertSearchPlanRecord[];
trackedPlanClaims: AlertSearchJwtWithClaimRecord[];
plansNearby: AlertSearchPlanRecord[];
}
export interface PartnerAlertSearchData {
profilesNearby: AlertSearchProfileRecord[];
}
/**
* Endorser GET/POST /api/v2/report/alertSearch body.
* Per-bucket SQL hitLimit is not currently copied onto this envelope.
* Timeouts may set `userMessage` instead.
*/
export interface EndorserAlertSearchResponse {
data: EndorserAlertSearchData;
userMessage?: string;
}
/**
* Partner GET/POST /api/partner/alertSearch body.
*/
export interface PartnerAlertSearchResponse {
data: PartnerAlertSearchData;
userMessage?: string;
}
/**
* Union of the six alertSearch buckets for a future combined daily run.
* Not returned by a single server endpoint today.
*/
export interface CombinedAlertSearchData
extends EndorserAlertSearchData,
PartnerAlertSearchData {}
+17
View File
@@ -15,6 +15,23 @@ export interface GenericCredWrapper<T extends GenericVerifiableCredential> {
publicUrls?: Record<string, string>;
}
/**
* The fields the certificate canvases read off a claim.
*
* GenericVerifiableCredential carries an index signature of `unknown`, which is
* correct for a claim of any type but leaves each field unusable without a
* cast. This names the handful the drawing code actually touches. An `agent` is
* either a bare DID string or an object carrying one, depending on claim type.
*/
export interface CertifiableClaim extends GenericVerifiableCredential {
agent?: string | { identifier?: string };
description?: string;
includesObject?: { amountOfThisGood?: number; unitCode?: string };
itemOffered?: { description?: string };
name?: string;
object?: { amountOfThisGood?: number; unitCode?: string };
}
export interface ErrorResponse {
error?: {
message?: string;
+32
View File
@@ -29,6 +29,9 @@ import { z } from "zod";
// Parameter validation schemas for each route type
export const deepLinkPathSchemas = {
// A bare "timesafari://" with no path: open the app at the default view.
"": z.object({}),
account: z.object({}),
claim: z.object({
id: z.string(),
}),
@@ -48,6 +51,11 @@ export const deepLinkPathSchemas = {
"contact-import": z.object({
jwt: z.string(),
}),
// Both paths reach the same destination: the page that shows your QR code,
// scans someone else's, and prompts for your name if you have not set one.
// See ROUTE_NAME_RESOLVERS in src/services/deepLinks.ts for which view that is.
"contact-qr": z.object({}),
"contact-qr-scan-full": z.object({}),
contacts: z.object({
contactJwt: z.string().optional(),
inviteJwt: z.string().optional(),
@@ -55,22 +63,46 @@ export const deepLinkPathSchemas = {
did: z.object({
did: z.string().optional(),
}),
discover: z.object({}),
help: z.object({}),
"help-notification-types": z.object({}),
"help-notifications": z.object({}),
"help-onboarding": z.object({}),
"help-terms": z.object({}),
"invite-one": z.object({}),
"invite-one-accept": z.object({
// optional because A) it could be a query param, and B) the page displays an input if things go wrong
jwt: z.string().optional(),
}),
"new-activity": z.object({}),
"onboard-meeting-list": z.object({}),
"onboard-meeting-members": z.object({
groupId: z.string(),
}),
project: z.object({
id: z.string(),
}),
projects: z.object({}),
"recent-offers-to-user": z.object({}),
"recent-offers-to-user-projects": z.object({}),
"search-area": z.object({}),
"share-my-contact-info": z.object({}),
// Internal handoff used by the native image-share targets.
"shared-photo": z.object({}),
statistics: z.object({}),
"user-profile": z.object({
id: z.string(),
}),
};
export const deepLinkQuerySchemas = {
// All optional: the view defaults searchText to "" and the two flags to
// false, so a bare "timesafari://discover" is valid.
discover: z.object({
searchText: z.string().optional(),
searchPeople: z.string().optional(),
hideOnboarding: z.string().optional(),
}),
"onboard-meeting-members": z.object({
password: z.string(),
}),
+2
View File
@@ -1,7 +1,9 @@
export * from "./alertSearch";
export * from "./claims";
export * from "./claims-result";
export * from "./common";
export * from "./deepLinks";
export * from "./limits";
export * from "./notifyApi";
export * from "./records";
export * from "./user";
+427
View File
@@ -0,0 +1,427 @@
/**
* Wire payloads for the notify-api (notification-wakeup-service): request
* bodies, query parameters, the JWT payloads the app signs for it, and the
* bodies it answers with.
*
* Each type names the route it belongs to and holds the fields that route reads
* or writes; a field the app sends and the service ignores is marked "Not read
* by the service." The service's code is the source of truth, in
* notification-wakeup-service: `src/routes/notifications.ts`,
* `src/routes/notifySms.ts`, `src/routes/debug.ts`, `src/middleware/`, and
* `src/services/alertAuthorization.ts`.
*
* Two kinds of JWT travel to the service:
* - The Bearer token on each request authenticates the caller, and the service
* takes the DID from it; no body carries the DID. On `/notify-sms` that token
* also carries an {@link SmsNotificationActionClaim}.
* - The delegated JWTs inside an {@link AlertAuthorizationRequestBody} are
* stored credentials the service later presents to Endorser and Partner.
* They authenticate nothing about the upload that carries them.
*
* Refusals come in these shapes, by where they are raised:
* - {@link NotifyApiUncodedFailure}: a message and no code, from the auth
* stages in front of every authenticated route, and from a push
* alert-authorization route that fails to store or delete.
* - {@link NotificationDeviceRouteFailure}: a sentence under `error`, from
* register and refresh.
* - {@link DebugSendWakeupResponse} with `success: false`.
* - {@link AlertAuthorizationBatchFailure} and {@link NotifySmsFailure}: coded.
*
* A proxy in front of the service can answer with none of these, or with no
* JSON at all.
*/
// ---------------------------------------------------------------------------
// Shared
// ---------------------------------------------------------------------------
/**
* Refusal with a message and no code. The auth stages send it with 401 for a
* missing, invalid, or Endorser-rejected Bearer token and 503 when Endorser
* cannot be reached; their messages end with a timestamp for finding the server
* log. The push alert-authorization routes send it with 500 when storing or
* deleting fails.
*/
export interface NotifyApiUncodedFailure {
success: false;
message: string;
}
// ---------------------------------------------------------------------------
// Device routes: /notifications/register, /notifications/refresh, /debug
// ---------------------------------------------------------------------------
/**
* Local-test switch on the device routes. `true` with no `Authorization`
* header makes the service skip JWT and Endorser checks and file the request
* under a synthetic test user. A request carrying a Bearer token is
* authenticated normally whatever this says, and no other route reads it.
*/
export interface NotifyApiTestModeFlag {
testMode?: boolean;
}
/**
* Body of `POST /notifications/register`: store this device's FCM token under
* the caller's DID, keyed by `deviceId`. Success is a bare 200 with a
* plain-text body; a failure to store is a bare 500.
*/
export interface NotificationRegisterRequest extends NotifyApiTestModeFlag {
/** Stable per-install id; trimmed by the service and required non-empty. */
deviceId: string;
/** Required non-empty. */
fcmToken: string;
/** `Capacitor.getPlatform()`: `"ios"`, `"android"`, or `"web"`. Required non-empty. */
platform: string;
/** The DID comes from the Bearer token; a body with a `userId` key is rejected. */
userId?: never;
}
/**
* Body of `POST /notifications/refresh`. The Capacitor app no longer calls this
* route (WAKEUP_PING → refresh → `api_*` scheduling was retired). These types
* remain because notification-wakeup-service still exposes the endpoint.
* The service finds the caller's device
* by `deviceId`, or by `fcmToken` when no `deviceId` is sent, and answers 400
* when neither is present and non-empty. When both are sent they must name the
* same device, or the answer is 404.
*/
export type NotificationRefreshRequest = NotifyApiTestModeFlag & {
/** Not read by the service. */
platform?: string;
} & (
| { deviceId: string; fcmToken?: string }
| { deviceId?: string; fcmToken: string }
);
/** Success body of `POST /notifications/refresh`. */
export interface NotificationRefreshResponse {
shouldNotify: boolean;
/** Instants for the device to schedule, as Unix milliseconds. */
nextNotifications: Array<{ timestamp: number }>;
}
/**
* Refusal from `POST /notifications/register` (400) or
* `POST /notifications/refresh` (400, or 404 when no device of the caller's
* matches). `error` is a sentence such as `"Device not found"`, not a code.
*/
export interface NotificationDeviceRouteFailure {
error: string;
}
/**
* Body of `POST /debug/send-wakeup`, which pushes a WAKEUP_PING to one of the
* caller's devices. The `/debug` routes exist only on a service started with
* `DEBUG_ENDPOINT` on.
*/
export interface DebugSendWakeupRequest extends NotifyApiTestModeFlag {
/** A token registered under the caller's DID; required non-empty. */
fcmToken: string;
/** Not read by the service. */
deviceId?: string;
/** Not read by the service. */
platform?: string;
}
/**
* Every answer `POST /debug/send-wakeup` writes itself. A 200 still carries
* `success: false` when the push was skipped or failed, so `success`, not the
* status, says whether a WAKEUP_PING went out.
*/
export interface DebugSendWakeupResponse {
success: boolean;
/**
* Why no push went out: `"fcmToken is required"` (400), `"Device not found"`
* (404), or with a 200, `"Device was notified within the eligibility
* threshold"` or `"FCM send failed"`.
*/
failureReason?: string;
/** Last six characters of the token; absent on the 400. */
fcmTokenSuffix?: string;
}
// ---------------------------------------------------------------------------
// Alert authorization: /notifications/alert-authorization and
// /notify-sms/alert-authorization
// ---------------------------------------------------------------------------
/**
* Payload the app signs for one {@link DelegatedAlertJwt}; the signer adds
* `iss` (the DID) and `iat`. The service requires the signed `nbf` and `exp` to
* equal the values listed beside the JWT.
*/
export interface DelegatedAlertJwtPayload {
/** Unix seconds, at or before the midnight UTC that opens the entry's `day`. */
nbf: number;
/** Unix seconds, at or after the midnight UTC that closes the entry's `day`. */
exp: number;
}
/** One day's delegated credential inside an {@link AlertAuthorizationRequestBody}. */
export interface DelegatedAlertJwt {
/** Integer; the batch's values are consecutive, starting anywhere. */
sequence: number;
/** UTC calendar day, `YYYY-MM-DD`, distinct across the batch. */
day: string;
/** Unix seconds; equal to the signed `nbf`. */
nbf: number;
/** Unix seconds; equal to the signed `exp`. */
exp: number;
/** Signed by the caller's DID, which must be a `did:ethr`. */
jwt: string;
}
/**
* Body of `POST /notifications/alert-authorization` (push) and
* `POST /notify-sms/alert-authorization` (SMS), which validate it with one
* rule. A stored batch replaces the unused inventory the DID holds in that
* channel; JWTs already spent stay behind.
*/
export interface AlertAuthorizationRequestBody {
/** Required non-empty; echoed in the response. */
batchId: string;
/** UTC hour, integer 0-23. */
notifyHourUtc: number;
/** UTC minute, integer 0-59. */
notifyMinuteUtc: number;
/**
* IANA zone name such as `"America/Denver"`. Validated and stored; no
* scheduling decision reads it.
*/
timezone?: string;
/** Exactly 100 entries. */
jwts: DelegatedAlertJwt[];
}
/** Success body of storing a batch, on either alert-authorization route. */
export interface AlertAuthorizationResponse {
success: true;
batchId: string;
/** The stored UTC hour; null only for a batch stored without one. */
notifyHourUtc: number | null;
/** The stored UTC minute; null only for a batch stored without one. */
notifyMinuteUtc: number | null;
timezone: string | null;
/** JWTs stored from this batch. */
storedCount: number;
/** Unused JWTs the DID holds in this channel once the batch is stored. */
unusedCount: number;
}
/** Success body of `DELETE` on either alert-authorization route. */
export interface AlertAuthorizationRevokeResponse {
success: true;
/** Batches removed, spent ones included. */
deletedBatches: number;
/** JWTs removed, spent ones included. */
deletedJwts: number;
}
/**
* Coded refusal of a batch (400) on either alert-authorization route: it failed
* validation, or the caller's identity cannot hold one. Nothing was stored.
*/
export interface AlertAuthorizationBatchFailure {
success: false;
error:
| "ALERT_AUTHORIZATION_INVALID_BATCH"
| "DELEGATED_JWT_UNSUPPORTED_IDENTITY";
message: string;
/** Specific problems, at most 20 plus a count of the rest. */
details: string[];
}
/** Refusal from `POST` or `DELETE /notifications/alert-authorization`. */
export type AlertAuthorizationFailure =
| AlertAuthorizationBatchFailure
| NotifyApiUncodedFailure;
// ---------------------------------------------------------------------------
// SMS channel: /notify-sms
// ---------------------------------------------------------------------------
/**
* What a `/notify-sms` action claim authorizes. The service checks `action`
* against the route and, for handset actions, checks that `phoneNumber`
* normalizes to the same E.164 number the request names.
*/
export type SmsActionTarget =
// Bound to one handset; the number must match the request's.
| {
action: "register-phone" | "verify-phone" | "delete-phone";
phoneNumber: string;
}
// Bound to a number only when the request sends `?phoneNumber=`.
| { action: "list-phones"; phoneNumber?: string }
// Acts on the DID's whole alert authorization; the service reads no number.
| {
action: "authorize-alert-search" | "revoke-alert-search";
phoneNumber?: undefined;
};
/** Actions the service's `requireSmsActionJwt` stage recognizes, one per route. */
export type SmsAction = SmsActionTarget["action"];
/** The `claim` in the Bearer JWT on every `/notify-sms` request. */
export type SmsNotificationActionClaim = {
/** Claim namespace; distinct from `https://giftopia.me`, the link in the texts. */
"@context": "https://giftopia.tech";
"@type": "SmsNotificationAction";
} & SmsActionTarget;
/**
* Payload the app signs as the Bearer JWT on every `/notify-sms` request; the
* signer adds `iss`, `iat`, and `exp`. The service refuses a token whose `iat`
* is further than `SMS_ACTION_JWT_MAX_AGE_SEC` from its clock or whose `exp`
* has passed, and accepts each token once.
*/
export interface SmsActionJwtPayload {
claim: SmsNotificationActionClaim;
}
/**
* Query of `GET /notify-sms/phone`. With `phoneNumber`, the response adds the
* DIDs verified on that number, which the service reveals only to a DID that
* has verified it too.
*/
export interface SmsPhoneListQuery {
phoneNumber?: string;
}
/** One of the caller's registrations, as `GET /notify-sms/phone` lists it. */
export interface SmsPhoneRegistration {
/** The full E.164 number; these are the caller's own. */
phoneNumber: string;
verified: boolean;
/** ISO 8601; null until verified. */
verifiedAt: string | null;
/** ISO 8601. */
createdAt: string;
}
/**
* Success body of `GET /notify-sms/phone`, oldest registration first. An
* identity with no registrations gets an empty list.
*/
export interface SmsPhoneListResponse {
success: true;
phones: SmsPhoneRegistration[];
/** The queried number, normalized; present exactly when `?phoneNumber=` was sent. */
phoneNumber?: string;
/**
* Every DID verified on the queried number, the caller's included; present
* exactly when `?phoneNumber=` was sent.
*/
dids?: string[];
}
/** Body of `POST /notify-sms/phone`: record the number, unverified, and text it a code. */
export interface SmsPhoneRegisterRequest {
/** E.164; the service normalizes, taking ten bare digits as a US number. */
phoneNumber: string;
}
/**
* Success body of `POST /notify-sms/phone`. `phoneNumber` is masked, such as
* `+1555*****23`, so it cannot stand in for the number that was sent.
*/
export type SmsPhoneRegisterResponse =
// The caller had already verified this number; no text was sent.
| { success: true; phoneNumber: string; verified: true }
| {
success: true;
phoneNumber: string;
verified: false;
/** ISO 8601; when the texted code stops working. */
expiresAt: string;
/**
* The plaintext code, only from a service run with both
* `NODE_ENV=test-local` and `SMS_DEV_ECHO_CODE`.
*/
devCode?: string;
};
/** Body of `PUT /notify-sms/phone`: match the texted code. */
export interface SmsPhoneVerifyRequest {
phoneNumber: string;
/** The six digits as texted. */
code: string;
}
/**
* Success body of `PUT /notify-sms/phone`, also for a number the caller had
* already verified. `phoneNumber` is masked.
*/
export interface SmsPhoneVerifyResponse {
success: true;
phoneNumber: string;
verified: true;
}
/**
* Body, and also query, of `DELETE /notify-sms/phone`. The service reads the
* body first and falls back to the query, because proxies may drop DELETE
* bodies.
*/
export interface SmsPhoneDeleteRequest {
phoneNumber: string;
}
/** Success body of `DELETE /notify-sms/phone`; `deleted` is false when the number was not registered. */
export interface SmsPhoneDeleteResponse {
success: true;
deleted: boolean;
}
/** Codes of `/notify-sms` refusals that carry nothing beyond the message. */
export type NotifySmsPlainErrorCode =
| "SMS_DISABLED" // 503
| "SMS_NOT_CONFIGURED" // 500
| "SMS_PHONE_INVALID" // 400
| "SMS_PHONE_BLOCKED" // 403
| "SMS_PHONE_NOT_VERIFIED_BY_CALLER" // 403
| "SMS_RECIPIENT_NOT_ALLOWED" // 403
| "SMS_CODE_RATE_LIMITED" // 429
| "SMS_CODE_SEND_FAILED" // 502
| "SMS_CODE_EXPIRED" // 400
| "SMS_CODE_ATTEMPTS_EXHAUSTED" // 429
| "SMS_NO_VERIFIED_PHONE" // 409
| "SMS_ALERT_AUTHORIZATION_FAILED" // 500
| "SMS_ALERT_AUTHORIZATION_DELETE_FAILED" // 500
| "SMS_ACTION_JWT_NOT_AUTHENTICATED" // 500
| "SMS_ACTION_JWT_MISSING_CLAIM" // 403
| "SMS_ACTION_JWT_WRONG_ACTION" // 403
| "SMS_ACTION_JWT_PHONE_MISMATCH" // 403
| "SMS_ACTION_JWT_STALE" // 401
| "SMS_ACTION_JWT_EXPIRED" // 401
| "SMS_ACTION_JWT_REPLAYED"; // 401
/**
* A coded refusal from any `/notify-sms` route. The auth stages in front of
* these routes refuse with a {@link NotifyApiUncodedFailure} instead.
*/
export type NotifySmsFailure =
| { success: false; error: NotifySmsPlainErrorCode; message: string }
| {
success: false;
error: "SMS_CODE_MISMATCH"; // 400
message: string;
/** Wrong codes left before this code is cleared. */
attemptsRemaining: number;
}
| {
success: false;
error: "SMS_PHONE_DID_LIMIT"; // 409
message: string;
/** Most identities one number may carry. */
limit: number;
/** Identities other than the caller already verified on the number. */
verifiedCount: number;
/**
* Every DID verified on the number. Sent only by `PUT`, whose caller has
* just proved possession of the handset.
*/
dids?: string[];
}
| AlertAuthorizationBatchFailure;
+69
View File
@@ -0,0 +1,69 @@
/**
* Typed alertSearch API contract only. No HTTP client yet.
*
* Hosts: use DEFAULT_ENDORSER_API_SERVER and DEFAULT_PARTNER_API_SERVER from
* `@/constants/app`. Do not duplicate those constants here.
*
* JWT kinds (do not mix these):
* - Authentication JWT: short-lived access token (`iss`/`iat`/`exp`) sent as
* `Authorization: Bearer` for interactive API calls (`accessToken` /
* `getHeaders`). Identifies the requester DID.
* - Delegated notification JWT: a batch of 100 tokens, each valid for one whole
* UTC day, from `mintAlertAuthorizationBatch`
* (`@/services/notifications/alertAuthorizationBatch`), uploaded to the
* notify-api's push or SMS `alert-authorization` route.
* - Native background pool: `mintBackgroundJwtTokenPool` for daily-notification
* plugin prefetch. Unrelated to alertSearch and to the delegated batch.
* - alertSearch cursor ULID: server-issued record/JWT primary id (26-char
* ULID). `afterId` means ids strictly greater than that ULID; `beforeId`
* means strictly less. First daily run omits afterId. `beforeId` is for
* pagination within a run. These are not auth JWTs and not signed tokens.
*
* Truncation: each endorser bucket query uses a server hit-limit (typically
* 50). That flag is not currently returned on the alertSearch JSON envelope.
* Timeouts may add `userMessage`. A later caller must still paginate with
* beforeId when a bucket may be incomplete.
*/
import type {
AlertSearchCursorUlid,
CombinedAlertSearchData,
EndorserAlertSearchResponse,
PartnerAlertSearchResponse,
} from "@/interfaces/alertSearch";
export const ENDORSER_ALERT_SEARCH_PATH = "/api/v2/report/alertSearch";
export const PARTNER_ALERT_SEARCH_PATH = "/api/partner/alertSearch";
export interface AlertSearchLocationBBox {
minLocLat: number;
maxLocLat: number;
minLocLon: number;
maxLocLon: number;
}
/**
* Query/body params accepted by endorser and partner alertSearch (GET or POST).
* GET is the planned daily method; the server also accepts POST.
*/
export interface AlertSearchRequestParams {
afterId?: AlertSearchCursorUlid;
beforeId?: AlertSearchCursorUlid;
afterDate?: string;
beforeDate?: string;
location?: AlertSearchLocationBBox;
minLocLat?: number;
maxLocLat?: number;
minLocLon?: number;
maxLocLon?: number;
planHandleIds?: string[];
planIds?: string[];
handleIds?: string[];
}
export type {
AlertSearchCursorUlid,
CombinedAlertSearchData,
EndorserAlertSearchResponse,
PartnerAlertSearchResponse,
};
+93
View File
@@ -0,0 +1,93 @@
/**
* Day-scoped JWT pool for native New Activity background prefetch.
*
* Kept apart from `@/libs/crypto` so minting depends only on the signer and the
* pool constants: the prefetch path is the one place in the app where a
* credential is handed to native code and used without any JavaScript running,
* and its dependencies should stay small enough to read in one sitting.
*/
import {
BACKGROUND_JWT_POOL_SIZE,
BACKGROUND_JWT_SECONDS_PER_DAY,
BACKGROUND_JWT_WINDOW_SLACK_SECONDS,
} from "@/constants/backgroundJwt";
import type { KeyMetaWithPrivate } from "@/interfaces/common";
import { createEndorserJwtForKey } from "./vc";
/** Thrown for identities whose keys cannot sign a day-scoped background pool. */
export class BackgroundJwtUnsupportedIdentityError extends Error {
constructor(message: string) {
super(message);
this.name = "BackgroundJwtUnsupportedIdentityError";
}
}
/**
* Mint one JWT per UTC day for native background prefetch
* (`configureNativeFetcher` `jwtTokens`), covering the
* {@link BACKGROUND_JWT_POOL_SIZE} consecutive days starting with the day of
* the call.
*
* Each token is valid only for the single day it covers: `nbf` at that day's
* opening midnight and `exp` at its closing one, each widened by
* {@link BACKGROUND_JWT_WINDOW_SLACK_SECONDS} for clock skew. A token that
* escapes through a log line or a captured header therefore buys one day of
* Endorser access rather than the whole grant. The day windows are also what
* make the tokens distinct: the ES256K signer is deterministic, so JWTs built
* from identical payloads are byte-identical, and a pool of identical strings
* defeats any duplicate-token rule the server may apply.
*
* Slot order is a contract with the native selector, which reads
* `pool[epochDay % pool.size()]` and has no record of when the pool was minted:
* the token covering a UTC day sits at index `epochDay % POOL_SIZE`. Any
* POOL_SIZE consecutive days hit every index exactly once, so the array is
* dense whatever day minting starts on.
*
* The caller supplies the decrypted account rather than a DID: signing
* {@link BACKGROUND_JWT_POOL_SIZE} tokens from a DID would decrypt the identity
* once per token, which costs seconds on a phone and runs on every app
* foreground.
*
* Passkey (`did:peer`) identities cannot mint this pool -- each signature is a
* WebAuthn assertion, and `createJwtNavigator` overrides the day window with its
* own one-minute `exp` -- so they raise
* {@link BackgroundJwtUnsupportedIdentityError} instead of prompting
* {@link BACKGROUND_JWT_POOL_SIZE} times for tokens that expire before the
* prefetch they were minted for.
*
* @param account decrypted identity the pool is issued by and for
* @throws BackgroundJwtUnsupportedIdentityError for passkey identities
*/
export async function mintBackgroundJwtTokenPool(
account: KeyMetaWithPrivate,
): Promise<string[]> {
if (!account?.identity) {
throw new BackgroundJwtUnsupportedIdentityError(
`No day-scoped signing key for ${account?.did}; background prefetch ` +
"requires a seed-phrase identity.",
);
}
const did = account.did;
const nowEpoch = Math.floor(Date.now() / 1000);
const firstEpochDay = Math.floor(nowEpoch / BACKGROUND_JWT_SECONDS_PER_DAY);
const tokens: string[] = new Array(BACKGROUND_JWT_POOL_SIZE);
for (let offset = 0; offset < BACKGROUND_JWT_POOL_SIZE; offset++) {
const epochDay = firstEpochDay + offset;
const dayStartEpoch = epochDay * BACKGROUND_JWT_SECONDS_PER_DAY;
const tokenPayload = {
nbf: dayStartEpoch - BACKGROUND_JWT_WINDOW_SLACK_SECONDS,
exp:
dayStartEpoch +
BACKGROUND_JWT_SECONDS_PER_DAY +
BACKGROUND_JWT_WINDOW_SLACK_SECONDS,
iat: nowEpoch,
iss: did,
};
tokens[epochDay % BACKGROUND_JWT_POOL_SIZE] = await createEndorserJwtForKey(
account,
tokenPayload,
);
}
return tokens;
}
+60
View File
@@ -0,0 +1,60 @@
/**
* @fileoverview Handle ID string handling for the Endorser server
*
* A handle ID is the permanent ID of a claim's entity on Endorser, eg.
* "https://endorser.ch/entity/01D25AVGQG1N8E9JNGK7C7DZRD". Deep links carry it
* with the prefix stripped off, so the two forms both circulate in the app and
* have to be converted deliberately at the boundary between them.
*
* This module holds no dependencies on purpose. Everything here is string
* handling that claims and report queries depend on, so it stays loadable
* without a database, a network client, or a build-time environment.
*
* @module endorserHandleIds
*/
/**
* The prefix for handle IDs, the permanent ID for claims on Endorser
* @constant {string}
*/
export const ENDORSER_CH_HANDLE_PREFIX = "https://endorser.ch/entity/";
/**
* from https://tools.ietf.org/html/rfc3986#section-3
*
* An ID carrying a scheme belongs to whoever issued it; one without a scheme
* names an entity on the Endorser server. (libs/util.ts exports the same
* predicate as isGlobalUri for view code.)
*/
const hasUriScheme = (id: string) => /^[A-Za-z][A-Za-z0-9+.-]+:/.test(id);
/**
* Shorten a full handle ID to the part a deep link carries.
*/
export function stripEndorserPrefix(claimId: string) {
if (claimId && claimId.startsWith(ENDORSER_CH_HANDLE_PREFIX)) {
return claimId.substring(ENDORSER_CH_HANDLE_PREFIX.length);
} else {
return claimId;
}
}
/**
* The inverse of stripEndorserPrefix: expand an ID that names an entity on the
* Endorser server into the full handle ID.
*
* An ID taken from a route parameter goes through here before it reaches a
* claim or a report query. A claim is a credential that outlives this app and
* travels beyond this server, where "01D25AVGQG1N8E9JNGK7C7DZRD" identifies
* nothing; the report endpoints match on the full handle.
*
* An ID that already carries a URI scheme -- a full handle, or a handle from
* another system -- is returned unchanged.
*/
export function addEndorserPrefix(claimId: string) {
if (claimId && !hasUriScheme(claimId)) {
return ENDORSER_CH_HANDLE_PREFIX + claimId;
} else {
return claimId;
}
}
+41 -24
View File
@@ -23,7 +23,7 @@ import { LRUCache } from "lru-cache";
import * as R from "ramda";
import { DEFAULT_IMAGE_API_SERVER, NotificationIface } from "../constants/app";
import { NOTIFICATION_TIMEOUTS } from "../composables/useNotifications";
import { NOTIFICATION_TIMEOUTS } from "../utils/notificationUtils";
import { createNotifyHelpers } from "../utils/notify";
import { NOTIFY_PERSONAL_DATA_ERROR } from "../constants/notifications";
import { Contact } from "../db/tables/contacts";
@@ -104,11 +104,14 @@ export const CONTACT_URL_PATH_ENDORSER_CH_OLD = "/contact?jwt=";
*/
export const CONTACT_CONFIRM_URL_PATH_TIME_SAFARI = "/contact/confirm/";
/**
* The prefix for handle IDs, the permanent ID for claims on Endorser
* @constant {string}
*/
export const ENDORSER_CH_HANDLE_PREFIX = "https://endorser.ch/entity/";
// Handle ID string handling lives in its own module so that it can be loaded
// and tested without everything this one needs. Re-exported here because that
// is where callers have always found it.
export {
ENDORSER_CH_HANDLE_PREFIX,
addEndorserPrefix,
stripEndorserPrefix,
} from "./endorserHandleIds";
export const BLANK_GENERIC_SERVER_RECORD: GenericCredWrapper<GenericVerifiableCredential> =
{
@@ -222,14 +225,6 @@ export const containsNonHiddenDid = (obj: any) => {
return testRecursivelyOnStrings(obj, (s: any) => isDid(s) && !isHiddenDid(s));
};
export function stripEndorserPrefix(claimId: string) {
if (claimId && claimId.startsWith(ENDORSER_CH_HANDLE_PREFIX)) {
return claimId.substring(ENDORSER_CH_HANDLE_PREFIX.length);
} else {
return claimId;
}
}
// similar logic is found in endorser-mobile
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function removeSchemaContext(obj: any) {
@@ -381,6 +376,19 @@ export function didInfoOrNobody(
/**
* return text description without any references to "you" as user
*/
/**
* A claim's agent is either a bare DID string or an object carrying one,
* depending on the claim type.
*
* @param agent - the `agent` field of a claim, in either shape
* @returns the DID, or undefined when the agent carries none
*/
export function didOfAgent(
agent: string | { identifier?: string } | undefined,
): string | undefined {
return typeof agent === "string" ? agent : agent?.identifier;
}
export function didInfoForCertificate(
did: string | undefined,
contacts: Contact[],
@@ -676,15 +684,18 @@ export async function setPlanInCache(
/**
* Extracts user-friendly message from server error
* @param {AxiosErrorResponse} error - Error thrown from Endorser server call
*
* Takes `unknown` because callers pass it straight from a `catch`, and every
* access below is optional-chained, so a value of any shape is safe.
*
* @param error - Error thrown from an Endorser server call
* @returns {string|undefined} User-friendly message or undefined if none found
*/
export function serverMessageForUser(
error: AxiosErrorResponse,
): string | undefined {
export function serverMessageForUser(error: unknown): string | undefined {
const err = error as AxiosErrorResponse;
return (
error?.response?.data?.error?.userMessage ||
error?.response?.data?.error?.message
err?.response?.data?.error?.userMessage ||
err?.response?.data?.error?.message
);
}
@@ -1210,19 +1221,25 @@ export async function createAndSubmitClaim(
},
});
// The server wraps its result: { success: { claimId, handleId, ... } }.
// Reading the top level instead leaves every field undefined, which hides
// embeddedRecordError -- the server's way of saying it stored the claim but
// could not record part of it, eg. a link to a project.
const result = response.data?.success;
logger.debug("[Claim Submission] ✅ Claim submitted successfully:", {
requestId,
status: response.status,
handleId: response.data?.handleId,
handleId: result?.handleId,
responseSize: JSON.stringify(response.data).length,
timestamp: new Date().toISOString(),
});
return {
success: true,
claimId: response.data?.claimId,
handleId: response.data?.handleId,
embeddedRecordError: response.data?.embeddedRecordError,
claimId: result?.claimId,
handleId: result?.handleId,
embeddedRecordError: result?.embeddedRecordError,
};
} catch (error: unknown) {
// Enhanced error logging with comprehensive context
+108 -184
View File
@@ -39,14 +39,47 @@ import { logger, safeStringify } from "./utils/logger";
import { PlatformServiceFactory } from "./services/PlatformServiceFactory";
import { SHARED_PHOTO_BASE64_KEY } from "./libs/util";
import { SharedImage } from "./plugins/SharedImagePlugin";
import { createSharedImageHandoff } from "./services/sharedImageHandoff";
import "./utils/safeAreaInset";
// Load Daily Notification plugin at startup so native performRecovery() runs at launch (rollover recovery)
import "@timesafari/daily-notification-plugin";
import {
configureNativeFetcherIfReady,
initializeNativePushAndFirebaseMessaging,
onNotificationAuthMayBeReady,
runLegacyApiNotificationsCleanupOnce,
} from "@/services/notifications";
logger.log("[Capacitor] 🚀 Starting initialization");
logger.log("[Capacitor] Platform:", process.env.VITE_PLATFORM);
// Diagnostic: log DailyNotification methods from native PluginHeaders (helps debug UNIMPLEMENTED)
type CapacitorWindow = {
Capacitor?: {
PluginHeaders?: Array<{ name: string; methods?: Array<{ name: string }> }>;
};
};
const cap =
typeof window !== "undefined"
? (window as unknown as CapacitorWindow).Capacitor
: undefined;
if (cap?.PluginHeaders) {
const dn = cap.PluginHeaders.find((h) => h.name === "DailyNotification");
const methodNames = dn?.methods?.map((m) => m.name) ?? null;
logger.log(
"[Capacitor] DNP PluginHeaders methods:",
methodNames ?? "DailyNotification NOT IN HEADERS",
);
if (methodNames && !methodNames.includes("scheduleDualNotification")) {
logger.warn(
"[Capacitor] scheduleDualNotification missing from PluginHeaders – native plugin may be stale; try clearing Xcode DerivedData and rebuilding",
);
}
} else {
logger.warn("[Capacitor] Capacitor.PluginHeaders not present");
}
const app = initializeApp();
// Initialize API error handling for unhandled promise rejections
@@ -58,9 +91,6 @@ window.addEventListener("unhandledrejection", (event) => {
const deepLinkHandler = new DeepLinkHandler(router);
// Lock to prevent duplicate processing of shared images
let isProcessingSharedImage = false;
/**
* Stores shared image data in temp database
* Handles clearing old data, converting base64 to data URL, and storing
@@ -107,87 +137,80 @@ async function storeSharedImageInTempDB(
logger.info(`[Main] Stored shared image: ${fileName || "unknown"}`);
}
/**
* Handles deep link routing for the application
* Processes URLs in the format timesafari://<route>/<param>
* Maps incoming deep links to corresponding router paths with parameters
*
* @param {Object} data - Deep link data object
* @param {string} data.url - The full deep link URL to process
* @returns {Promise<void>}
*
* @example
* // Handles URLs like:
* // timesafari://claim/01JMAAFZRNSRTQ0EBSD70A8E1H
* // timesafari://project/abc123
*
* @throws {Error} If URL format is invalid
*/
/**
* Check for native shared image using SharedImage plugin
* Reads from native layer (App Group UserDefaults on iOS, SharedPreferences on Android)
* and stores in temp database before routing to shared-photo view
*/
async function checkAndStoreNativeSharedImage(): Promise<{
success: boolean;
fileName?: string;
}> {
// Prevent duplicate processing
if (isProcessingSharedImage) {
logger.debug(
"[Main] ⏸️ Shared image processing already in progress, skipping",
);
return { success: false };
async function navigateToSharedPhoto(fileName: string): Promise<void> {
await router.isReady();
if (router.currentRoute.value.path === "/shared-photo") {
await router.replace({
path: "/shared-photo",
query: { fileName, _refresh: Date.now().toString() },
});
} else {
await router.push({
path: "/shared-photo",
query: { fileName },
});
}
isProcessingSharedImage = true;
logger.info(`[Main] ✅ Navigated to /shared-photo?fileName=${fileName}`);
}
try {
if (
!Capacitor.isNativePlatform() ||
(Capacitor.getPlatform() !== "ios" &&
Capacitor.getPlatform() !== "android")
) {
isProcessingSharedImage = false;
return { success: false };
}
// Use SharedImage plugin to get shared image data directly from native layer
// No file I/O or polling needed - direct native-to-JS communication
let result;
const sharedImageHandoff = createSharedImageHandoff({
getSharedImage: async () => {
try {
result = await SharedImage.getSharedImage();
return await SharedImage.getSharedImage();
} catch (error) {
logger.error("[Main] Error calling SharedImage.getSharedImage():", {
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
isProcessingSharedImage = false;
return { success: false };
return null;
}
},
storeSharedImage: async (base64, fileName) => {
logger.info("[Main] Native shared image found, storing in temp DB");
await storeSharedImageInTempDB(base64, fileName);
},
navigateToSharedPhoto,
});
// Check if we have valid image data (base64 must be non-null and non-empty)
if (result && result.base64 && result.base64.trim().length > 0) {
const fileName = result.fileName || "shared-image.jpg";
/**
* Consume a pending native shared image and route to the share screen. The
* in-flight handoff is shared by URL, launch, and activation callbacks because
* the native plugin removes an image after it is read.
*/
async function checkForSharedImageAndNavigate(): Promise<boolean> {
if (
!Capacitor.isNativePlatform() ||
(Capacitor.getPlatform() !== "ios" && Capacitor.getPlatform() !== "android")
) {
return false;
}
// Store in temp database using extracted method
logger.info(
"[Main] Native shared image found (via plugin), storing in temp DB",
);
await storeSharedImageInTempDB(result.base64, fileName);
isProcessingSharedImage = false;
return { success: true, fileName };
try {
const navigated = await sharedImageHandoff.process();
if (!navigated) {
logger.debug("[Main] ℹ️ No native shared image found");
}
// No shared image found
logger.debug("[Main] No shared image found via plugin");
isProcessingSharedImage = false;
return { success: false };
return navigated;
} catch (error) {
logger.error("[Main] Error checking for native shared image:", error);
isProcessingSharedImage = false;
return { success: false };
logger.error("[Main] ❌ Error processing native shared image:", error);
return false;
}
}
function isSharedPhotoDeepLink(url: string): boolean {
try {
const parsed = new URL(url);
return (
parsed.protocol === "timesafari:" &&
parsed.hostname === "shared-photo" &&
(parsed.pathname === "" || parsed.pathname === "/") &&
!parsed.search &&
!parsed.hash
);
} catch {
return false;
}
}
@@ -196,67 +219,10 @@ const handleDeepLink = async (data: { url: string }) => {
logger.debug(`[Main] 🌐 Deeplink received from Capacitor: ${url}`);
try {
// Handle empty path URLs from share extension (timesafari://)
// These are used to open the app, and we should check for shared images
const isEmptyPathUrl = url === "timesafari://" || url === "timesafari:///";
if (
isEmptyPathUrl &&
Capacitor.isNativePlatform() &&
Capacitor.getPlatform() === "ios"
) {
logger.debug(
"[Main] 📸 Empty path URL from share extension, checking for native shared image",
);
// Try to get shared image from App Group and store in temp database
// AppDelegate writes the file when the deep link is received, so we may need to retry
// The checkAndStoreNativeSharedImage function now uses polling internally, so we just call it once
try {
const imageResult = await checkAndStoreNativeSharedImage();
if (imageResult.success) {
logger.info(
"[Main] ✅ Native shared image found, navigating to shared-photo",
);
// Wait for router to be ready
await router.isReady();
// Navigate directly to shared-photo route
// Use replace if already on shared-photo to force refresh, otherwise push
const fileName = imageResult.fileName || "shared-image.jpg";
const isAlreadyOnSharedPhoto =
router.currentRoute.value.path === "/shared-photo";
if (isAlreadyOnSharedPhoto) {
// Force refresh by replacing the route
await router.replace({
path: "/shared-photo",
query: { fileName, _refresh: Date.now().toString() }, // Add timestamp to force update
});
} else {
await router.push({
path: "/shared-photo",
query: { fileName },
});
}
logger.info(
`[Main] ✅ Navigated to /shared-photo?fileName=${fileName}`,
);
return; // Exit early, don't process as deep link
} else {
logger.debug(
"[Main] ℹ️ No native shared image found, ignoring empty path URL",
);
return; // Exit early, don't process empty path as deep link
}
} catch (error) {
logger.error("[Main] Error processing native shared image:", error);
// If check fails, don't process as deep link (empty path would fail validation anyway)
return;
}
if (isSharedPhotoDeepLink(url) && Capacitor.isNativePlatform()) {
logger.debug("[Main] 📸 Shared-photo handoff received");
await checkForSharedImageAndNavigate();
return;
}
// Wait for router to be ready
@@ -346,58 +312,6 @@ const registerDeepLinkListener = async () => {
}
};
/**
* Check for shared image and navigate to shared-photo route if found
* This is called when app becomes active (from share extension or app launch)
*/
async function checkForSharedImageAndNavigate() {
if (
!Capacitor.isNativePlatform() ||
(Capacitor.getPlatform() !== "ios" && Capacitor.getPlatform() !== "android")
) {
return;
}
try {
logger.debug("[Main] 🔍 Checking for shared image on app activation");
const imageResult = await checkAndStoreNativeSharedImage();
if (imageResult.success) {
logger.info(
"[Main] ✅ Shared image found, navigating to shared-photo route",
);
// Wait for router to be ready
await router.isReady();
// Navigate to shared-photo route with fileName if available
// Use replace if already on shared-photo to force refresh, otherwise push
const fileName = imageResult.fileName || "shared-image.jpg";
const isAlreadyOnSharedPhoto =
router.currentRoute.value.path === "/shared-photo";
if (isAlreadyOnSharedPhoto) {
// Force refresh by replacing the route
await router.replace({
path: "/shared-photo",
query: { fileName, _refresh: Date.now().toString() }, // Add timestamp to force update
});
} else {
const route = imageResult.fileName
? `/shared-photo?fileName=${encodeURIComponent(imageResult.fileName)}`
: "/shared-photo";
await router.push(route);
}
logger.info(`[Main] ✅ Navigated to /shared-photo?fileName=${fileName}`);
} else {
logger.debug("[Main] ℹ️ No shared image found");
}
} catch (error) {
logger.error("[Main] ❌ Error checking for shared image:", error);
}
}
logger.log("[Capacitor] 🚀 Mounting app");
app.mount("#app");
logger.info(`[Main] ✅ App mounted successfully`);
@@ -432,11 +346,15 @@ if (
if (isActive) {
logger.debug("[Main] 📱 App became active, checking for shared image");
await checkForSharedImageAndNavigate();
// Refresh JWT for background New Activity prefetch (WorkManager cannot run JS;
// short-lived tokens would expire between configure and T−5 fetch without this).
await configureNativeFetcherIfReady();
onNotificationAuthMayBeReady();
}
});
}
// Register deeplink listener after app is mounted
// Register deeplink listener and configure native notification fetcher after app is mounted
setTimeout(async () => {
try {
logger.info(
@@ -444,6 +362,12 @@ setTimeout(async () => {
);
await registerDeepLinkListener();
logger.info(`[Main] 🎉 Deep link system fully initialized!`);
// One-time: remove persisted legacy api_* schedules from pre-retirement installs
await runLegacyApiNotificationsCleanupOnce();
// Firebase Messaging (JS) + Capacitor PushNotifications (FCM/APNs token, delivery listeners)
await initializeNativePushAndFirebaseMessaging();
// Configure native fetcher for API-driven daily notifications (activeDid + JWT)
await configureNativeFetcherIfReady();
} catch (error) {
logger.error(`[Main] ❌ Deep link system initialization failed:`, error);
}

Some files were not shown because too many files have changed in this diff Show More