From 3963778da1c1de50e3d6acbdc0667cdbd7d06e16 Mon Sep 17 00:00:00 2001 From: Tero Huttunen Date: Tue, 3 Nov 2026 07:49:07 +0200 Subject: [PATCH] Implemented the Android notification-privacy part of Phase 1: --- ANDROID_SECURITY_PLAN.md | 6 +-- README.md | 2 +- TODO.md | 1 + .../daybreak/mail/AndroidAccountVault.kt | 10 ++++ .../java/studio/daybreak/mail/EpMailPlugin.kt | 23 +++++++++- .../studio/daybreak/mail/MailIdleService.kt | 46 +++++++++++++------ .../mail/NotificationPrivacyPolicy.kt | 15 ++++++ .../mail/NotificationPrivacyPolicyTest.kt | 31 +++++++++++++ platform-bridge.js | 2 + productivity.js | 18 +++++--- scripts/android-bridge.js | 2 + www/platform-bridge.js | 2 + www/productivity.js | 18 +++++--- 13 files changed, 142 insertions(+), 34 deletions(-) create mode 100644 android/app/src/main/java/studio/daybreak/mail/NotificationPrivacyPolicy.kt create mode 100644 android/app/src/test/java/studio/daybreak/mail/NotificationPrivacyPolicyTest.kt diff --git a/ANDROID_SECURITY_PLAN.md b/ANDROID_SECURITY_PLAN.md index f49fc45..e5bd1f2 100644 --- a/ANDROID_SECURITY_PLAN.md +++ b/ANDROID_SECURITY_PLAN.md @@ -6,9 +6,9 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU ## Implementation progress (2026-11-03) -- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification previews and native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials. -- Tested: DAV URL policy and attachment-name policy have Android unit tests. The debug Android build and unit tests pass, as does the Node test suite. -- Still open: invalid-certificate integration tests, device-level review of the merged release APK, private notification preference UI, app lock/biometric unlock, full vault lifecycle testing, and Android OpenPGP. OpenPGP work remains gated on an independent cryptography/security review. +- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification details are opt-in, stored in the encrypted vault, and redacted on the lock screen; native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials. +- Tested: DAV URL, attachment-name, and notification privacy policies have Android unit tests. The debug Android build and unit tests pass, as does the Node test suite. +- Still open: invalid-certificate integration tests, device-level review of the merged release APK, app lock/biometric unlock, full vault lifecycle testing, and Android OpenPGP. OpenPGP work remains gated on an independent cryptography/security review. ## Goals and limits diff --git a/README.md b/README.md index 3a0e44e..1ac5368 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ npm install npm run android:apk ``` -The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail -debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail .apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification previews contain generic text rather than mailbox addresses or message subjects. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management. +The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail -debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail .apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management. ## Run on Windows or Linux diff --git a/TODO.md b/TODO.md index 817ad99..4309c3c 100644 --- a/TODO.md +++ b/TODO.md @@ -40,6 +40,7 @@ - [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android. - [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation. - [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks. + - [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews. ## Appearance and settings diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt index ea6b7b1..283a7f0 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt @@ -56,6 +56,16 @@ internal object AndroidAccountVault { } fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray() + + fun notificationDetailsEnabled(): Boolean = + read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS) + + @Synchronized + fun setNotificationDetailsEnabled(enabled: Boolean): Boolean { + val store = read().put("showNotificationDetails", enabled) + write(store) + return enabled + } fun account(id: String? = null): JSONObject? { val store = read() diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index d3d5612..799c249 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -54,7 +54,28 @@ class EpMailPlugin : Plugin() { @PluginMethod fun getAppVersion(call: PluginCall) { call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME)) - } + } + + @PluginMethod + fun getNotificationPrivacy(call: PluginCall) { + try { + call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled())) + } catch (error: Exception) { + call.reject(error.message ?: "Could not read notification privacy settings.") + } + } + + @PluginMethod + fun setNotificationDetails(call: PluginCall) { + try { + val enabled = call.getBoolean("enabled") + ?: throw IllegalArgumentException("Choose whether notifications may show details.") + AndroidAccountVault.setNotificationDetailsEnabled(enabled) + call.resolve(JSObject().put("showDetails", enabled)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save notification privacy settings.") + } + } @PluginMethod fun getAccount(call: PluginCall) { diff --git a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt index 5999ed0..d581339 100644 --- a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt @@ -136,6 +136,7 @@ class MailIdleService : Service() { .setContentIntent(appPendingIntent()) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_LOW) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .build() private fun appPendingIntent(): PendingIntent { @@ -219,14 +220,21 @@ class MailIdleService : Service() { appContext, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) - val title = if (count == 1) "New mail" else "$count new messages" - val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) - .setSmallIcon(android.R.drawable.ic_dialog_email) - .setContentTitle(title) - .setContentText("Open ep-mail to check your inbox") - .setAutoCancel(true) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setContentIntent(pendingIntent) + val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false) + val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setContentTitle("New mail") + .setContentText(NotificationPrivacyPolicy.newMailText(showDetails, email, count)) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setContentTitle("ep-mail") + .setContentText("New mail") + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .build()) + .setContentIntent(pendingIntent) .build() try { NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification) @@ -256,13 +264,21 @@ class MailIdleService : Service() { NotificationManager.IMPORTANCE_DEFAULT )) } - val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) - .setSmallIcon(android.R.drawable.ic_dialog_email) - .setContentTitle("Mail reminder") - .setContentText("A snoozed message is due") - .setAutoCancel(true) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setContentIntent(appPendingIntentFor(appContext)) + val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false) + val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setContentTitle("Mail reminder") + .setContentText(NotificationPrivacyPolicy.reminderText(showDetails, reminder.optString("subject"))) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setContentTitle("ep-mail") + .setContentText("A mail reminder is due") + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .build()) + .setContentIntent(appPendingIntentFor(appContext)) .build() try { NotificationManagerCompat.from(appContext).notify( diff --git a/android/app/src/main/java/studio/daybreak/mail/NotificationPrivacyPolicy.kt b/android/app/src/main/java/studio/daybreak/mail/NotificationPrivacyPolicy.kt new file mode 100644 index 0000000..66e1d6a --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/NotificationPrivacyPolicy.kt @@ -0,0 +1,15 @@ +package studio.daybreak.mail + +internal object NotificationPrivacyPolicy { + const val DEFAULT_SHOW_DETAILS = false + + fun newMailText(showDetails: Boolean, email: String, count: Int): String = + if (showDetails) { + if (count == 1) email else "$count new messages · $email" + } else { + "Open ep-mail to check your inbox" + } + + fun reminderText(showDetails: Boolean, subject: String): String = + if (showDetails && subject.isNotBlank()) subject else "A snoozed message is due" +} diff --git a/android/app/src/test/java/studio/daybreak/mail/NotificationPrivacyPolicyTest.kt b/android/app/src/test/java/studio/daybreak/mail/NotificationPrivacyPolicyTest.kt new file mode 100644 index 0000000..8e3eacb --- /dev/null +++ b/android/app/src/test/java/studio/daybreak/mail/NotificationPrivacyPolicyTest.kt @@ -0,0 +1,31 @@ +package studio.daybreak.mail + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test + +class NotificationPrivacyPolicyTest { + @Test + fun notificationDetailsAreDisabledByDefault() { + assertFalse(NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS) + assertEquals( + "Open ep-mail to check your inbox", + NotificationPrivacyPolicy.newMailText(NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS, "person@example.test", 1) + ) + assertEquals( + "A snoozed message is due", + NotificationPrivacyPolicy.reminderText(NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS, "Private subject") + ) + } + + @Test + fun detailsAppearOnlyAfterExplicitOptIn() { + assertEquals("person@example.test", NotificationPrivacyPolicy.newMailText(true, "person@example.test", 1)) + assertEquals( + "3 new messages · person@example.test", + NotificationPrivacyPolicy.newMailText(true, "person@example.test", 3) + ) + assertEquals("Private subject", NotificationPrivacyPolicy.reminderText(true, "Private subject")) + assertEquals("A snoozed message is due", NotificationPrivacyPolicy.reminderText(true, " ")) + } +} diff --git a/platform-bridge.js b/platform-bridge.js index 46541bd..6163851 100644 --- a/platform-bridge.js +++ b/platform-bridge.js @@ -513,6 +513,8 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") { window.daybreakMail = { getAppVersion: () => EpMail.getAppVersion().then((result) => result.version), + getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), + setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }), getAccount: () => EpMail.getAccount(), listAccounts: () => EpMail.listAccounts(), selectAccount: (id) => EpMail.selectAccount({ id }), diff --git a/productivity.js b/productivity.js index 45dbd12..7d5ef65 100644 --- a/productivity.js +++ b/productivity.js @@ -27,16 +27,20 @@ function openAccountSettings() { selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')}; selectProductivityUi('#profile-name').focus(); } -function openPreferences() { - const root=selectProductivityUi('#modal-root'); - const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; - const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; - const options=themes.map(([value,label])=>``).join(''); - root.innerHTML=``; +async function openPreferences() { + const root=selectProductivityUi('#modal-root'); + const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; + const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; + const options=themes.map(([value,label])=>``).join(''); + const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null; + let notificationPrivacy={showDetails:false}; + if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}} + const notificationSetting=notificationBridge?``:''; + root.innerHTML=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; - selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')}; + selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}}; selectProductivityUi('#theme-select').focus(); } function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); } diff --git a/scripts/android-bridge.js b/scripts/android-bridge.js index 2f67d3d..dfdd3fc 100644 --- a/scripts/android-bridge.js +++ b/scripts/android-bridge.js @@ -5,6 +5,8 @@ const EpMail = registerPlugin('EpMail'); if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { window.daybreakMail = { getAppVersion: () => EpMail.getAppVersion().then(result => result.version), + getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), + setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }), getAccount: () => EpMail.getAccount(), listAccounts: () => EpMail.listAccounts(), selectAccount: id => EpMail.selectAccount({ id }), diff --git a/www/platform-bridge.js b/www/platform-bridge.js index 46541bd..6163851 100644 --- a/www/platform-bridge.js +++ b/www/platform-bridge.js @@ -513,6 +513,8 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") { window.daybreakMail = { getAppVersion: () => EpMail.getAppVersion().then((result) => result.version), + getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), + setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }), getAccount: () => EpMail.getAccount(), listAccounts: () => EpMail.listAccounts(), selectAccount: (id) => EpMail.selectAccount({ id }), diff --git a/www/productivity.js b/www/productivity.js index 45dbd12..7d5ef65 100644 --- a/www/productivity.js +++ b/www/productivity.js @@ -27,16 +27,20 @@ function openAccountSettings() { selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')}; selectProductivityUi('#profile-name').focus(); } -function openPreferences() { - const root=selectProductivityUi('#modal-root'); - const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; - const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; - const options=themes.map(([value,label])=>``).join(''); - root.innerHTML=``; +async function openPreferences() { + const root=selectProductivityUi('#modal-root'); + const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; + const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; + const options=themes.map(([value,label])=>``).join(''); + const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null; + let notificationPrivacy={showDetails:false}; + if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}} + const notificationSetting=notificationBridge?``:''; + root.innerHTML=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; - selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')}; + selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}}; selectProductivityUi('#theme-select').focus(); } function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }