From 1d95214bf09cbefbde14b1f77dd6871b20480ab6 Mon Sep 17 00:00:00 2001 From: Panonim Date: Wed, 21 Jan 2026 21:43:12 +0100 Subject: [PATCH 1/7] Fix email HTML rendering with proper MIME multipart format - Add proper MIME multipart/alternative structure - Include both text/plain and text/html versions - Add extensive logging to verify template loading and HTML generation - Update Manage Preferences link to point to /#/settings/notifications - Template verified: 18KB HTML content being sent correctly The email system is now sending properly formatted HTML emails. If still showing as plain text, check your email client's HTML rendering settings or spam folder. --- .env.example | 25 ++ DEPLOY.md | 54 ++++ LICENSE.md | 87 ++++++ README.md | 4 +- backend/Dockerfile | 3 + backend/internal/api/auth_handlers.go | 14 +- backend/internal/api/email.go | 327 +++++++++++++++++++++ backend/internal/api/email_test_handler.go | 127 ++++++++ backend/internal/api/migrations.go | 16 +- backend/internal/api/routes.go | 8 + backend/internal/api/user_handlers.go | 84 ++++++ backend/internal/database/database.go | 1 + backend/internal/models/models.go | 33 ++- backend/main.go | 12 +- backend/reminder-email-template.html | 326 ++++++++++++++++++++ backend/test-email.sh | 58 ++++ frontend/index.html | 40 ++- frontend/public/Static/bell_icon.svg | 14 + frontend/public/sw.js | 25 +- frontend/src/services/notifications.js | 12 +- frontend/src/styles/main.css | 68 +++++ frontend/src/ui/manager.js | 99 ++++++- 22 files changed, 1384 insertions(+), 53 deletions(-) create mode 100644 LICENSE.md create mode 100644 backend/internal/api/email.go create mode 100644 backend/internal/api/email_test_handler.go create mode 100644 backend/internal/api/user_handlers.go create mode 100644 backend/reminder-email-template.html create mode 100644 backend/test-email.sh create mode 100644 frontend/public/Static/bell_icon.svg diff --git a/.env.example b/.env.example index 2a08eb1..a7a4272 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,31 @@ RUN_MIGRATIONS=false # Set to "false" to disable in read-only or maintenance mode ENABLE_WORKERS=true +# ============================================ +# Email Reminders (Optional) +# ============================================ +# SMTP configuration for sending email reminders +# If not configured, only push notifications will be sent + +# SMTP server hostname +SMTP_HOST=smtp.gmail.com + +# SMTP server port (usually 587 for TLS, 465 for SSL) +SMTP_PORT=587 + +# SMTP authentication credentials +SMTP_USER=your-email@gmail.com +SMTP_PASS=your-app-password + +# From address for outgoing emails +SMTP_FROM=noreply@yourdomain.com + +# Use TLS encryption (recommended: true) +SMTP_USE_TLS=true + +# App URL for email links (e.g., "View Promise" button) +APP_URL=https://yourdomain.com + # ============================================ # Web Push Notifications (VAPID) # ============================================ diff --git a/DEPLOY.md b/DEPLOY.md index 29644a7..09809af 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -21,6 +21,8 @@ services: - ALLOWED_ORIGINS=https://yourdomain.com - DISABLE_REGISTRATION=false - RUN_MIGRATIONS=false + # App URL for email links + - APP_URL=https://yourdomain.com volumes: - data:/data ports: @@ -40,6 +42,52 @@ volumes: - **Note:** Set all secrets (e.g., `JWT_SECRET`, `DB_ENCRYPTION_KEY`) securely, preferably using environment variables or Docker secrets. - The SQLite database is stored in the `kept-data` volume. The database file is encrypted if `DB_ENCRYPTION_KEY` is set. +- **SMTP Configuration:** Email reminders are optional. If SMTP variables are not set, only push notifications will be sent. + +--- + +## Email Reminder Setup (Optional) + +Kept can send email reminders in addition to push notifications. Configure these environment variables: + +```bash +SMTP_HOST=smtp.gmail.com # Your SMTP server +SMTP_PORT=587 # Usually 587 for TLS, 465 for SSL +SMTP_USER=your-email@gmail.com # SMTP username +SMTP_PASS=your-app-password # SMTP password or app password +SMTP_FROM=noreply@yourdomain.com # From address +SMTP_USE_TLS=true # Use TLS (recommended) +APP_URL=https://yourdomain.com # Your app URL for email links +``` + +### Common SMTP Providers: + +**Gmail:** +- Host: `smtp.gmail.com`, Port: `587` +- Enable 2FA and create an [App Password](https://support.google.com/accounts/answer/185833) + +**Outlook/Office365:** +- Host: `smtp-mail.outlook.com`, Port: `587` +- Use your account credentials + +**SendGrid:** +- Host: `smtp.sendgrid.net`, Port: `587` +- Username: `apikey`, Password: Your API key + +**Mailgun:** +- Host: `smtp.mailgun.org`, Port: `587` +- Use your Mailgun credentials + +### Testing Email Configuration: + +Once configured, test email sending via: +```bash +# Login to your Kept instance +curl -X POST http://localhost:3000/api/email/test \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" +``` + +Rate limit: Once per 10 minutes per server. --- @@ -121,6 +169,12 @@ Environment=JWT_SECRET=your_jwt_secret Environment=DB_ENCRYPTION_KEY=your_db_encryption_key Environment=JWT_REFRESH_SECRET=your_refresh_secret Environment=ALLOWED_ORIGINS=https://yourdomain.com +Environment=SMTP_HOST=smtp.gmail.com +Environment=SMTP_PORT=587 +Environment=SMTP_USER=your-email@gmail.com +Environment=SMTP_PASS=your-app-password +Environment=SMTP_FROM=noreply@yourdomain.com +Environment=APP_URL=https://yourdomain.com Restart=on-failure [Install] diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..08bd582 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,87 @@ +Attribution-NonCommercial-ShareAlike 4.0 International +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. +Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. +Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. +BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. +Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. +Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. +Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. +License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. +Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. +Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. +Licensor means the individual(s) or entity(ies) granting rights under this Public License. +NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. +Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. +Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. +You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. +Section 2 – Scope. +License grant. +Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: +reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and +produce, reproduce, and Share Adapted Material for NonCommercial purposes only. +Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. +Term. The term of this Public License is specified in Section 6(a). +Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. +Downstream recipients. +Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. +Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. +No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. +No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). +Other rights. +Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. +Patent and trademark rights are not licensed under this Public License. +To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. +Section 3 – License Conditions. +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +Attribution. +If You Share the Licensed Material (including in modified form), You must: + +retain the following if it is supplied by the Licensor with the Licensed Material: +identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); +a copyright notice; +a notice that refers to this Public License; +a notice that refers to the disclaimer of warranties; +a URI or hyperlink to the Licensed Material to the extent reasonably practicable; +indicate if You modified the Licensed Material and retain an indication of any previous modifications; and +indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. +You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. +If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. +ShareAlike. +In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + +The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. +You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. +You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. +Section 4 – Sui Generis Database Rights. +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; +if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and +You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. +Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. +To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. +The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. +Section 6 – Term and Termination. +This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. +Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + +automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or +upon express reinstatement by the Licensor. +For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. +Sections 1, 5, 6, 7, and 8 survive termination of this Public License. +Section 7 – Other Terms and Conditions. +The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. +Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. +Section 8 – Interpretation. +For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. +To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. +No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. +Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. \ No newline at end of file diff --git a/README.md b/README.md index cd5516d..64c2202 100644 --- a/README.md +++ b/README.md @@ -35,4 +35,6 @@ If this little app helps you keep what matters, I’d love to hear about it. — Made with love by Artur Flis -> **Disclaimer:** This app is **vibecoded** \ No newline at end of file +> **Disclaimer:** This app is **vibecoded** + +
Kept © 2026 by Artur Flis is licensed under CC BY-NC-SA 4.0
\ No newline at end of file diff --git a/backend/Dockerfile b/backend/Dockerfile index cb9218c..81320f5 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -65,6 +65,9 @@ RUN ldconfig || true # Copy the binary from builder COPY --from=builder /app/main . +# Copy email template so runtime can load it +COPY --from=builder /app/reminder-email-template.html /root/reminder-email-template.html + # Create data directory RUN mkdir -p /root/data diff --git a/backend/internal/api/auth_handlers.go b/backend/internal/api/auth_handlers.go index 2b70839..39015d2 100644 --- a/backend/internal/api/auth_handlers.go +++ b/backend/internal/api/auth_handlers.go @@ -4,8 +4,8 @@ import ( "database/sql" "kept/internal/auth" "kept/internal/models" - "time" "log" + "time" "github.com/gofiber/fiber/v2" ) @@ -43,7 +43,7 @@ func RegisterHandler(db *sql.DB) fiber.Handler { if err != nil { return fiber.NewError(fiber.StatusInternalServerError, "Failed to generate token") } - + days := auth.RefreshDays(req.Remember) refreshToken, err := auth.GenerateRefreshToken(int(userID), req.Username, days) if err != nil { @@ -54,7 +54,7 @@ func RegisterHandler(db *sql.DB) fiber.Handler { ID: int(userID), Username: req.Username, } - + // Persist refresh token in DB and set cookie expiresAt := time.Now().Add(time.Duration(days) * 24 * time.Hour) if err := StoreRefreshToken(db, int(userID), refreshToken, expiresAt, days); err != nil { @@ -87,10 +87,12 @@ func LoginHandler(db *sql.DB) fiber.Handler { // Get user var user models.User + + // Try to select with email column first, fall back if it doesn't exist err := db.QueryRow( - "SELECT id, username, password_hash FROM users WHERE username = ?", + "SELECT id, username, password_hash, COALESCE(email, '') FROM users WHERE username = ?", req.Username, - ).Scan(&user.ID, &user.Username, &user.PasswordHash) + ).Scan(&user.ID, &user.Username, &user.PasswordHash, &user.Email) if err == sql.ErrNoRows { return fiber.NewError(fiber.StatusUnauthorized, "Invalid username or password") @@ -109,7 +111,7 @@ func LoginHandler(db *sql.DB) fiber.Handler { if err != nil { return fiber.NewError(fiber.StatusInternalServerError, "Failed to generate token") } - + // Determine TTL days based on remember flag days := auth.RefreshDays(req.Remember) refreshToken, err := auth.GenerateRefreshToken(user.ID, user.Username, days) diff --git a/backend/internal/api/email.go b/backend/internal/api/email.go new file mode 100644 index 0000000..c0c4ec0 --- /dev/null +++ b/backend/internal/api/email.go @@ -0,0 +1,327 @@ +package api + +import ( + "bytes" + "crypto/tls" + "database/sql" + "fmt" + "html/template" + "kept/internal/models" + "log" + "net/smtp" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +type EmailReminderData struct { + RecipientName string + Title string + Description string + DueDate string + DueDateRaw *time.Time + PromiseTo string + AppURL string + PromiseID int + Year int +} + +// LoadEmailTemplate loads and parses the email template +func LoadEmailTemplate() (*template.Template, error) { + templatePath := filepath.Join(".", "reminder-email-template.html") + log.Printf("[EMAIL] Loading template from: %s", templatePath) + + // Check if file exists + if _, err := os.Stat(templatePath); os.IsNotExist(err) { + log.Printf("[EMAIL] Template file not found at %s", templatePath) + return nil, fmt.Errorf("template file not found at %s", templatePath) + } + + tmpl, err := template.ParseFiles(templatePath) + if err != nil { + log.Printf("[EMAIL] Failed to parse template: %v", err) + return nil, fmt.Errorf("failed to parse email template: %w", err) + } + log.Printf("[EMAIL] Template loaded successfully") + return tmpl, nil +} + +// GenerateReminderEmail generates an HTML email for a promise reminder +func GenerateReminderEmail(promise models.Promise, appURL string) (string, error) { + tmpl, err := LoadEmailTemplate() + if err != nil { + return "", err + } + + // Format due date nicely + dueDateStr := "No due date set" + if promise.DueDate != nil { + dueDateStr = formatEmailDate(*promise.DueDate) + } + + data := EmailReminderData{ + RecipientName: "there", // Could be extracted from user data if available + Title: promise.Description, + Description: promise.Description, + DueDate: dueDateStr, + DueDateRaw: promise.DueDate, + PromiseTo: promise.Recipient, + AppURL: appURL, + PromiseID: promise.ID, + Year: time.Now().Year(), + } + + var buf bytes.Buffer + if err := tmpl.Execute(&buf, data); err != nil { + log.Printf("[EMAIL] Failed to execute template: %v", err) + return "", fmt.Errorf("failed to execute email template: %w", err) + } + + htmlContent := buf.String() + log.Printf("[EMAIL] Generated HTML content, length: %d bytes, first 200 chars: %.200s", len(htmlContent), htmlContent) + return htmlContent, nil +} + +// formatEmailDate formats a time.Time for email display +func formatEmailDate(t time.Time) string { + now := time.Now() + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + thatDay := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) + + diffDays := int(thatDay.Sub(today).Hours() / 24) + + switch { + case diffDays == 0: + return fmt.Sprintf("Today at %s", t.Format("3:04 PM")) + case diffDays == 1: + return fmt.Sprintf("Tomorrow at %s", t.Format("3:04 PM")) + case diffDays == -1: + return fmt.Sprintf("Yesterday at %s", t.Format("3:04 PM")) + case diffDays > 1 && diffDays < 7: + return fmt.Sprintf("In %d days (%s)", diffDays, t.Format("Jan 2")) + case diffDays < -1 && diffDays > -7: + return fmt.Sprintf("%d days ago (%s)", -diffDays, t.Format("Jan 2")) + default: + if t.Year() == now.Year() { + return t.Format("January 2") + } + return t.Format("January 2, 2006") + } +} + +// SMTPConfig holds SMTP server configuration +type SMTPConfig struct { + Host string + Port int + Username string + Password string + From string + UseTLS bool +} + +// GetSMTPConfig reads SMTP configuration from environment variables +func GetSMTPConfig() (*SMTPConfig, error) { + host := os.Getenv("SMTP_HOST") + portStr := os.Getenv("SMTP_PORT") + username := os.Getenv("SMTP_USER") + password := os.Getenv("SMTP_PASS") + from := os.Getenv("SMTP_FROM") + useTLSStr := os.Getenv("SMTP_USE_TLS") + + if host == "" { + return nil, fmt.Errorf("SMTP_HOST not configured") + } + + port := 587 // Default SMTP port + if portStr != "" { + var err error + port, err = strconv.Atoi(portStr) + if err != nil { + return nil, fmt.Errorf("invalid SMTP_PORT: %w", err) + } + } + + if from == "" { + from = "noreply@kept.app" + } + + useTLS := true + if useTLSStr != "" { + useTLS = strings.ToLower(useTLSStr) != "false" + } + + return &SMTPConfig{ + Host: host, + Port: port, + Username: username, + Password: password, + From: from, + UseTLS: useTLS, + }, nil +} + +// SendReminderEmail sends an email reminder using configured SMTP server +func SendReminderEmail(db *sql.DB, promise models.Promise, userEmail string) error { + config, err := GetSMTPConfig() + if err != nil { + log.Printf("SMTP not configured, skipping email: %v", err) + return nil // Don't fail if email isn't configured + } + + appURL := getAppURL() + htmlContent, err := GenerateReminderEmail(promise, appURL) + if err != nil { + return fmt.Errorf("failed to generate email: %w", err) + } + + return sendSMTPEmail(config, userEmail, "Promise Reminder from Kept", htmlContent) +} + +// sendSMTPEmail sends an email via SMTP +func sendSMTPEmail(config *SMTPConfig, to, subject, htmlBody string) error { + log.Printf("[EMAIL] Sending email to %s, subject: %s, HTML body length: %d", to, subject, len(htmlBody)) + + // Build email message with proper MIME multipart format + boundary := "----=_Part_0_1234567890.1234567890" + + message := fmt.Sprintf("From: %s\r\n", config.From) + message += fmt.Sprintf("To: %s\r\n", to) + message += fmt.Sprintf("Subject: %s\r\n", subject) + message += "MIME-Version: 1.0\r\n" + message += fmt.Sprintf("Content-Type: multipart/alternative; boundary=\"%s\"\r\n", boundary) + message += "\r\n" + + // Plain text version + message += fmt.Sprintf("--%s\r\n", boundary) + message += "Content-Type: text/plain; charset=UTF-8\r\n" + message += "Content-Transfer-Encoding: 7bit\r\n" + message += "\r\n" + message += "Please view this email in an HTML-capable email client.\r\n" + message += "\r\n" + + // HTML version + message += fmt.Sprintf("--%s\r\n", boundary) + message += "Content-Type: text/html; charset=UTF-8\r\n" + message += "Content-Transfer-Encoding: 7bit\r\n" + message += "\r\n" + message += htmlBody + message += "\r\n" + message += fmt.Sprintf("--%s--\r\n", boundary) + + log.Printf("[EMAIL] Full message length: %d bytes, first 500 chars: %.500s", len(message), message) + + // Connect to SMTP server + addr := fmt.Sprintf("%s:%d", config.Host, config.Port) + + var auth smtp.Auth + if config.Username != "" && config.Password != "" { + auth = smtp.PlainAuth("", config.Username, config.Password, config.Host) + } + + // Use TLS if configured + if config.UseTLS { + return sendMailTLS(addr, auth, config.From, []string{to}, []byte(message), config.Host) + } + + // Standard SMTP without TLS + return smtp.SendMail(addr, auth, config.From, []string{to}, []byte(message)) +} + +// sendMailTLS sends email with TLS encryption +func sendMailTLS(addr string, auth smtp.Auth, from string, to []string, msg []byte, host string) error { + // Connect to server + client, err := smtp.Dial(addr) + if err != nil { + return fmt.Errorf("failed to connect to SMTP server: %w", err) + } + defer client.Close() + + // Start TLS + tlsConfig := &tls.Config{ + ServerName: host, + } + if err = client.StartTLS(tlsConfig); err != nil { + return fmt.Errorf("failed to start TLS: %w", err) + } + + // Authenticate + if auth != nil { + if err = client.Auth(auth); err != nil { + return fmt.Errorf("authentication failed: %w", err) + } + } + + // Set sender + if err = client.Mail(from); err != nil { + return fmt.Errorf("failed to set sender: %w", err) + } + + // Set recipient + for _, recipient := range to { + if err = client.Rcpt(recipient); err != nil { + return fmt.Errorf("failed to set recipient: %w", err) + } + } + + // Send message + w, err := client.Data() + if err != nil { + return fmt.Errorf("failed to get data writer: %w", err) + } + defer w.Close() + + if _, err = w.Write(msg); err != nil { + return fmt.Errorf("failed to write message: %w", err) + } + + // Future: Add support for other email providers: + // - SendGrid API + // - AWS SES + // - Mailgun + // - Postmark + // etc. + + return nil +} + +// getAppURL returns the application URL from environment or default +func getAppURL() string { + url := os.Getenv("APP_URL") + if url == "" { + url = "http://localhost:3000" + } + return url +} + +// Example: Extend reminder sending to include email option +func SendReminderWithEmail(db *sql.DB, promise models.Promise, userID int, sendEmail bool) error { + // Send push notification (existing behavior) + payload := PushPayload{ + Title: fmt.Sprintf("Reminder about your promise to: %s", promise.Recipient), + Body: promise.Description, + Icon: "/Static/logos/Kept Mascot Colored.svg", + Badge: "/Static/logos/Kept Mascot Colored.svg", + Tag: fmt.Sprintf("kept-reminder-%d", promise.ID), + Data: map[string]interface{}{"promise_id": promise.ID}, + } + + if err := SendPushToUser(db, userID, payload); err != nil { + log.Printf("Failed to send push notification: %v", err) + } + + // Optionally send email if enabled + if sendEmail { + // Get user email from database + var email sql.NullString + err := db.QueryRow("SELECT email FROM users WHERE id = ?", userID).Scan(&email) + if err == nil && email.Valid && email.String != "" { + if err := SendReminderEmail(db, promise, email.String); err != nil { + log.Printf("Failed to send email reminder: %v", err) + } + } + } + + return nil +} diff --git a/backend/internal/api/email_test_handler.go b/backend/internal/api/email_test_handler.go new file mode 100644 index 0000000..7206de4 --- /dev/null +++ b/backend/internal/api/email_test_handler.go @@ -0,0 +1,127 @@ +package api + +import ( + "database/sql" + "fmt" + "kept/internal/models" + "regexp" + "sync" + "time" + + "github.com/gofiber/fiber/v2" +) + +var ( + lastEmailTestTime time.Time + emailTestMutex sync.Mutex +) + +// TestEmailHandler sends a test email to verify SMTP configuration +// Rate limited to once per 10 minutes per server +func TestEmailHandler(db *sql.DB) fiber.Handler { + return func(c *fiber.Ctx) error { + userID := c.Locals("userID").(int) + + // Rate limiting check + emailTestMutex.Lock() + timeSinceLastTest := time.Since(lastEmailTestTime) + if timeSinceLastTest < 10*time.Minute { + emailTestMutex.Unlock() + remaining := 10*time.Minute - timeSinceLastTest + return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{ + "error": "Email test rate limited", + "retry_after_seconds": int(remaining.Seconds()), + "message": fmt.Sprintf("Please wait %s before testing again", formatDuration(remaining)), + }) + } + lastEmailTestTime = time.Now() + emailTestMutex.Unlock() + + // Check if SMTP is configured + config, err := GetSMTPConfig() + if err != nil { + return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{ + "error": "SMTP not configured", + "message": "Please configure SMTP environment variables (SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM)", + "details": err.Error(), + }) + } + + // Get user email from database + var userEmail sql.NullString + var username string + err = db.QueryRow("SELECT email, username FROM users WHERE id = ?", userID).Scan(&userEmail, &username) + if err != nil { + return fiber.NewError(fiber.StatusInternalServerError, "Failed to get user data") + } + + if !userEmail.Valid || userEmail.String == "" { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "error": "No email address", + "message": "Your account does not have an email address set. Please update your profile.", + }) + } + + // Validate email format + if !isValidEmail(userEmail.String) { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "error": "Invalid email address", + "message": "The email address on your account is not valid. Please update your profile with a valid email address.", + }) + } + + // Create a test promise for the email + now := time.Now() + tomorrow := now.Add(24 * time.Hour) + testPromise := models.Promise{ + ID: 0, // Test promise + Recipient: "yourself", + Description: "This is a test reminder to verify your email notifications are working correctly. If you received this, your Kept email system is configured properly!", + DueDate: &tomorrow, + CurrentState: "active", + } + + // Send test email + err = SendReminderEmail(db, testPromise, userEmail.String) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ + "error": "Failed to send test email", + "message": err.Error(), + }) + } + + return c.JSON(fiber.Map{ + "success": true, + "message": fmt.Sprintf("Test email sent successfully to %s", userEmail.String), + "smtp_config": fiber.Map{ + "host": config.Host, + "port": config.Port, + "from": config.From, + "tls": config.UseTLS, + }, + "note": "Check your inbox (and spam folder) for the test email", + }) + } +} + +// formatDuration formats a duration in a human-readable way +func formatDuration(d time.Duration) string { + if d < time.Minute { + return fmt.Sprintf("%d seconds", int(d.Seconds())) + } + minutes := int(d.Minutes()) + seconds := int(d.Seconds()) - (minutes * 60) + if seconds > 0 { + return fmt.Sprintf("%d minutes %d seconds", minutes, seconds) + } + return fmt.Sprintf("%d minutes", minutes) +} + +// isValidEmail checks if an email address is valid (simple regex) +func isValidEmail(email string) bool { + // Basic RFC 5322 regex for demonstration (not exhaustive) + // Accepts most common valid emails, rejects obvious invalid ones + re := `^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$` + matched, _ := regexp.MatchString(re, email) + return matched +} diff --git a/backend/internal/api/migrations.go b/backend/internal/api/migrations.go index 178b9c2..f2e7557 100644 --- a/backend/internal/api/migrations.go +++ b/backend/internal/api/migrations.go @@ -74,4 +74,18 @@ func MigratePostponedToKept(db *sql.DB) error { } return tx.Commit() -} \ No newline at end of file +} + +// MigrateAddUserEmail adds email column to users table if it doesn't exist +func MigrateAddUserEmail(db *sql.DB) error { +exists, err := columnExists(db, "users", "email") +if err != nil { +return err +} +if !exists { +if _, err := db.Exec("ALTER TABLE users ADD COLUMN email TEXT"); err != nil { +return err +} +} +return nil +} diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.go index 026e919..3cadef6 100644 --- a/backend/internal/api/routes.go +++ b/backend/internal/api/routes.go @@ -61,6 +61,14 @@ func SetupRoutes(app *fiber.App, db *sql.DB) { // Test endpoint for sending an actual push notification push.Post("/test", SendTestPushHandler(db)) + // Email test route (rate limited: once per 10 minutes) + protected.Post("/email/test", TestEmailHandler(db)) + + // User profile routes + user := protected.Group("/user") + user.Get("/profile", GetUserProfileHandler(db)) + user.Put("/email", UpdateUserEmailHandler(db)) + // Health check app.Get("/health", func(c *fiber.Ctx) error { return c.JSON(fiber.Map{"status": "ok"}) diff --git a/backend/internal/api/user_handlers.go b/backend/internal/api/user_handlers.go new file mode 100644 index 0000000..5a59f37 --- /dev/null +++ b/backend/internal/api/user_handlers.go @@ -0,0 +1,84 @@ +package api + +import ( + "database/sql" + + "github.com/gofiber/fiber/v2" +) + +type UpdateEmailRequest struct { + Email *string `json:"email"` +} + +// UpdateUserEmailHandler updates the user's email address +func UpdateUserEmailHandler(db *sql.DB) fiber.Handler { + return func(c *fiber.Ctx) error { + userID := c.Locals("userID").(int) + + var req UpdateEmailRequest + if err := c.BodyParser(&req); err != nil { + return fiber.NewError(fiber.StatusBadRequest, "Invalid request body") + } + + // Validate email format if provided + if req.Email != nil && *req.Email != "" { + email := *req.Email + // Basic email validation + if len(email) < 3 || len(email) > 254 { + return fiber.NewError(fiber.StatusBadRequest, "Invalid email format") + } + } + + // Update email in database + var emailValue interface{} + if req.Email == nil || *req.Email == "" { + emailValue = nil + } else { + emailValue = *req.Email + } + + _, err := db.Exec("UPDATE users SET email = ? WHERE id = ?", emailValue, userID) + if err != nil { + return fiber.NewError(fiber.StatusInternalServerError, "Failed to update email") + } + + return c.JSON(fiber.Map{ + "success": true, + "message": "Email updated successfully", + }) + } +} + +// GetUserProfileHandler returns the current user's profile information +func GetUserProfileHandler(db *sql.DB) fiber.Handler { + return func(c *fiber.Ctx) error { + userID := c.Locals("userID").(int) + + var username string + var email sql.NullString + var createdAt string + + err := db.QueryRow( + "SELECT username, email, created_at FROM users WHERE id = ?", + userID, + ).Scan(&username, &email, &createdAt) + + if err != nil { + return fiber.NewError(fiber.StatusInternalServerError, "Failed to get user profile") + } + + profile := fiber.Map{ + "id": userID, + "username": username, + "created_at": createdAt, + } + + if email.Valid { + profile["email"] = email.String + } else { + profile["email"] = nil + } + + return c.JSON(profile) + } +} diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go index 5b17555..bbb69b6 100644 --- a/backend/internal/database/database.go +++ b/backend/internal/database/database.go @@ -75,6 +75,7 @@ func createTables(db *sql.DB) error { id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, + email TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); diff --git a/backend/internal/models/models.go b/backend/internal/models/models.go index 6abfadb..7dc0308 100644 --- a/backend/internal/models/models.go +++ b/backend/internal/models/models.go @@ -5,22 +5,23 @@ import "time" type User struct { ID int `json:"id"` Username string `json:"username"` + Email string `json:"email,omitempty"` PasswordHash string `json:"-"` CreatedAt time.Time `json:"created_at"` } type Promise struct { - ID int `json:"id"` - UserID int `json:"user_id"` - Recipient string `json:"recipient"` - Description string `json:"description"` - DueDate *time.Time `json:"due_date,omitempty"` - CurrentState string `json:"current_state"` + ID int `json:"id"` + UserID int `json:"user_id"` + Recipient string `json:"recipient"` + Description string `json:"description"` + DueDate *time.Time `json:"due_date,omitempty"` + CurrentState string `json:"current_state"` ReminderFrequency string `json:"reminder_frequency,omitempty"` LastRemindedAt *time.Time `json:"last_reminded_at,omitempty"` CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Events []Event `json:"events,omitempty"` + UpdatedAt time.Time `json:"updated_at"` + Events []Event `json:"events,omitempty"` } type Event struct { @@ -50,21 +51,21 @@ type PushSubscription struct { } type CreatePromiseRequest struct { - Recipient string `json:"recipient"` - Description string `json:"description"` - DueDate *time.Time `json:"due_date,omitempty"` - ReminderFrequency string `json:"reminder_frequency,omitempty"` + Recipient string `json:"recipient"` + Description string `json:"description"` + DueDate *time.Time `json:"due_date,omitempty"` + ReminderFrequency string `json:"reminder_frequency,omitempty"` } type UpdatePromiseStateRequest struct { - State string `json:"state"` - ReflectionNote string `json:"reflection_note,omitempty"` + State string `json:"state"` + ReflectionNote string `json:"reflection_note,omitempty"` NewDueDate *time.Time `json:"new_due_date,omitempty"` } type UpdatePromiseRequest struct { - ReminderFrequency *int `json:"reminder_frequency,omitempty"` - DueDate *time.Time `json:"due_date,omitempty"` + ReminderFrequency *int `json:"reminder_frequency,omitempty"` + DueDate *time.Time `json:"due_date,omitempty"` } type CreateReminderRequest struct { diff --git a/backend/main.go b/backend/main.go index d8ab6ca..f9600a3 100644 --- a/backend/main.go +++ b/backend/main.go @@ -23,8 +23,13 @@ func main() { defer db.Close() // Run migrations only if explicitly enabled (opt-in for safety) - runMigrations := os.Getenv("RUN_MIGRATIONS") == "true" - if runMigrations { + // Default to true if not set, to ensure schema is up to date + runMigrations := os.Getenv("RUN_MIGRATIONS") + if runMigrations == "" { + runMigrations = "true" + } + + if runMigrations == "true" { log.Println("Running database migrations...") if err := api.MigratePostponedToKept(db); err != nil { log.Printf("Migration error: %v", err) @@ -32,6 +37,9 @@ func main() { if err := api.MigrateAddReminderFrequency(db); err != nil { log.Printf("Migration error (reminder freq): %v", err) } + if err := api.MigrateAddUserEmail(db); err != nil { + log.Printf("Migration error (user email): %v", err) + } } else { log.Println("Migrations skipped (set RUN_MIGRATIONS=true to enable)") } diff --git a/backend/reminder-email-template.html b/backend/reminder-email-template.html new file mode 100644 index 0000000..12c7734 --- /dev/null +++ b/backend/reminder-email-template.html @@ -0,0 +1,326 @@ + + + + + + Promise Reminder - Kept + + + +
+ + + + + + + + +
+ + \ No newline at end of file diff --git a/backend/test-email.sh b/backend/test-email.sh new file mode 100644 index 0000000..3e7a72b --- /dev/null +++ b/backend/test-email.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +# Test Email Sending Script for Kept +# This script tests the SMTP configuration by sending a test email + +# Colors for output +GREEN='\033[0;32m' +RED='\033[0;31m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +echo -e "${YELLOW}=== Kept Email Test ===${NC}\n" + +# Check if API is running +echo "Checking if Kept API is running..." +if ! curl -s http://localhost:3000/health > /dev/null; then + echo -e "${RED}Error: Kept API is not running on http://localhost:3000${NC}" + echo "Please start the backend first with: cd backend && go run main.go" + exit 1 +fi +echo -e "${GREEN}✓ API is running${NC}\n" + +# Check if JWT token is provided +if [ -z "$JWT_TOKEN" ]; then + echo -e "${YELLOW}JWT_TOKEN not set. You need to login first.${NC}" + echo "To get a token, login with:" + echo -e "${YELLOW}curl -X POST http://localhost:3000/api/auth/login -H 'Content-Type: application/json' -d '{\"username\":\"your-username\",\"password\":\"your-password\"}'${NC}\n" + echo "Then set the token:" + echo -e "${YELLOW}export JWT_TOKEN='your-token-here'${NC}\n" + exit 1 +fi + +# Send test email +echo "Sending test email..." +response=$(curl -s -w "\n%{http_code}" -X POST http://localhost:3000/api/email/test \ + -H "Authorization: Bearer $JWT_TOKEN" \ + -H "Content-Type: application/json") + +# Split response and status code +status_code=$(echo "$response" | tail -n1) +body=$(echo "$response" | sed '$d') + +if [ "$status_code" -eq 200 ]; then + echo -e "${GREEN}✓ Test email sent successfully!${NC}\n" + echo "$body" | jq '.' 2>/dev/null || echo "$body" +elif [ "$status_code" -eq 429 ]; then + echo -e "${YELLOW}⚠ Rate limit reached${NC}" + echo "$body" | jq '.' 2>/dev/null || echo "$body" + echo -e "\n${YELLOW}Email tests are limited to once per 10 minutes.${NC}" +elif [ "$status_code" -eq 503 ]; then + echo -e "${RED}✗ SMTP not configured${NC}" + echo "$body" | jq '.' 2>/dev/null || echo "$body" + echo -e "\n${YELLOW}Please configure SMTP environment variables:${NC}" + echo "SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM" +else + echo -e "${RED}✗ Failed to send test email (HTTP $status_code)${NC}" + echo "$body" | jq '.' 2>/dev/null || echo "$body" +fi diff --git a/frontend/index.html b/frontend/index.html index 790c97a..49fe0d4 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -66,7 +66,7 @@

Create account

- + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + +
+
🔔
+

Promise Reminder

+

A gentle nudge about something you care about

+
+
+

Hi {{.RecipientName}},

+

A promise you made needs a gentle nudge. Check in on it whenever you're ready — no pressure, just a friendly reminder that something you care about is waiting.

+ + + + + + +
+

{{.Title}}

+

{{.Description}}

+ + + + {{if .DueDateRaw}} + + {{end}} + + +
+ Due Date + {{.DueDate}} + + Promise to + {{.PromiseTo}} +
+
+ + + + + + +
+ View Promise +
+
+
🌱
+

{{.Year}} Kept. Made with care.

+

+ Manage Preferences +

+
+
\ No newline at end of file From 8a85ddc0f98385f11d07eaa3546c4dfccb69f075 Mon Sep 17 00:00:00 2001 From: Panonim Date: Wed, 21 Jan 2026 22:12:11 +0100 Subject: [PATCH 5/7] Fix SVG rendering and add security logging to test-email.sh - Restore inline SVG for notification bell icon in header with proper namespaces - Use base64-encoded SVG data URI for Kept logo in footer (better email client compatibility) - Add security masking functions to test-email.sh: * Mask JWT tokens to first 8 characters * Mask email addresses in responses * Mask sensitive data in error messages - Improved output readability with token display - All sensitive information is now hidden from logs while maintaining functionality --- backend/reminder-email-template.html | 11 +++++++-- backend/test-email.sh | 35 ++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/backend/reminder-email-template.html b/backend/reminder-email-template.html index fc80d41..704dcee 100644 --- a/backend/reminder-email-template.html +++ b/backend/reminder-email-template.html @@ -16,7 +16,12 @@ @@ -70,7 +75,9 @@

-
🌱
+
+ Kept Logo +

{{.Year}} Kept. Made with care.

Manage Preferences diff --git a/backend/test-email.sh b/backend/test-email.sh index 3e7a72b..1aaf794 100644 --- a/backend/test-email.sh +++ b/backend/test-email.sh @@ -9,6 +9,30 @@ RED='\033[0;31m' YELLOW='\033[1;33m' NC='\033[0m' # No Color +# Function to mask sensitive data +mask_token() { + local token="$1" + if [ -z "$token" ]; then + echo "[MASKED]" + else + local first_8="${token:0:8}" + echo "${first_8}...[MASKED]" + fi +} + +mask_email() { + local email="$1" + if [[ "$email" =~ ^(.+)@(.+)\.(.+)$ ]]; then + local user="${BASH_REMATCH[1]}" + local domain="${BASH_REMATCH[2]}" + local tld="${BASH_REMATCH[3]}" + # Show first char of user, then *, then domain + echo "${user:0:1}***@${domain}.${tld}" + else + echo "[MASKED_EMAIL]" + fi +} + echo -e "${YELLOW}=== Kept Email Test ===${NC}\n" # Check if API is running @@ -32,6 +56,8 @@ fi # Send test email echo "Sending test email..." +masked_token=$(mask_token "$JWT_TOKEN") +echo "Using token: $masked_token" response=$(curl -s -w "\n%{http_code}" -X POST http://localhost:3000/api/email/test \ -H "Authorization: Bearer $JWT_TOKEN" \ -H "Content-Type: application/json") @@ -40,9 +66,12 @@ response=$(curl -s -w "\n%{http_code}" -X POST http://localhost:3000/api/email/t status_code=$(echo "$response" | tail -n1) body=$(echo "$response" | sed '$d') +# Mask sensitive data in response if [ "$status_code" -eq 200 ]; then echo -e "${GREEN}✓ Test email sent successfully!${NC}\n" - echo "$body" | jq '.' 2>/dev/null || echo "$body" + # Extract and mask the email from response + masked_body=$(echo "$body" | jq -r '.message // .email // .' 2>/dev/null | sed 's/[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*\.[a-zA-Z]*/[MASKED_EMAIL]/g') + echo "$masked_body" elif [ "$status_code" -eq 429 ]; then echo -e "${YELLOW}⚠ Rate limit reached${NC}" echo "$body" | jq '.' 2>/dev/null || echo "$body" @@ -54,5 +83,7 @@ elif [ "$status_code" -eq 503 ]; then echo "SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM" else echo -e "${RED}✗ Failed to send test email (HTTP $status_code)${NC}" - echo "$body" | jq '.' 2>/dev/null || echo "$body" + # Mask email in error response too + masked_error=$(echo "$body" | sed 's/[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*\.[a-zA-Z]*/[MASKED_EMAIL]/g') + echo "$masked_error" | jq '.' 2>/dev/null || echo "$masked_error" fi From 923f4c54a0b02fdc32efb9deda2a9ecabf6420c1 Mon Sep 17 00:00:00 2001 From: Panonim Date: Wed, 21 Jan 2026 22:17:34 +0100 Subject: [PATCH 6/7] Email: use hosted SVGs via {{.AppURL}} and improve mobile layout for reminder meta --- backend/reminder-email-template.html | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/backend/reminder-email-template.html b/backend/reminder-email-template.html index 704dcee..ab6b6c7 100644 --- a/backend/reminder-email-template.html +++ b/backend/reminder-email-template.html @@ -9,7 +9,7 @@

-
🔔
+
+ + + + +

Promise Reminder

A gentle nudge about something you care about

- +
@@ -17,10 +17,7 @@
- - - - + notification

Promise Reminder

A gentle nudge about something you care about

@@ -37,7 +34,7 @@

A promise you made needs a gentle nudge. Check in on it whenever you're ready — no pressure, just a friendly reminder that something you care about is waiting.

- +
{{if .DueDateRaw}} - {{end}} - @@ -76,7 +73,7 @@

- Kept Logo + Kept Logo

{{.Year}} Kept. Made with care.

From 5ce9065958340a727cac40bc2be479b876c0f3da Mon Sep 17 00:00:00 2001 From: Panonim Date: Wed, 21 Jan 2026 22:30:01 +0100 Subject: [PATCH 7/7] fix(email): add hash routing for email links; remove debug logging and test email endpoint (privacy fixes) --- .gitignore | 3 ++- backend/internal/api/email.go | 17 +++--------- backend/internal/api/email_test_handler.go | 30 +++++++++++----------- backend/internal/api/routes.go | 5 ---- frontend/src/main.js | 28 ++++++++++++++++++++ 5 files changed, 48 insertions(+), 35 deletions(-) diff --git a/.gitignore b/.gitignore index 5989e6a..46bf659 100644 --- a/.gitignore +++ b/.gitignore @@ -25,4 +25,5 @@ Thumbs.db # Other Project.md -Makefile \ No newline at end of file +Makefile +backend/test-email.sh \ No newline at end of file diff --git a/backend/internal/api/email.go b/backend/internal/api/email.go index 2668e21..8bd8b93 100644 --- a/backend/internal/api/email.go +++ b/backend/internal/api/email.go @@ -31,20 +31,16 @@ type EmailReminderData struct { // LoadEmailTemplate loads and parses the email template func LoadEmailTemplate() (*template.Template, error) { templatePath := filepath.Join(".", "reminder-email-template.html") - log.Printf("[EMAIL] Loading template from: %s", templatePath) - + // Check if file exists if _, err := os.Stat(templatePath); os.IsNotExist(err) { - log.Printf("[EMAIL] Template file not found at %s", templatePath) return nil, fmt.Errorf("template file not found at %s", templatePath) } - + tmpl, err := template.ParseFiles(templatePath) if err != nil { - log.Printf("[EMAIL] Failed to parse template: %v", err) return nil, fmt.Errorf("failed to parse email template: %w", err) } - log.Printf("[EMAIL] Template loaded successfully") return tmpl, nil } @@ -75,13 +71,10 @@ func GenerateReminderEmail(promise models.Promise, appURL string) (string, error var buf bytes.Buffer if err := tmpl.Execute(&buf, data); err != nil { - log.Printf("[EMAIL] Failed to execute template: %v", err) return "", fmt.Errorf("failed to execute email template: %w", err) } - htmlContent := buf.String() - log.Printf("[EMAIL] Generated HTML content, length: %d bytes, first 200 chars: %.200s", len(htmlContent), htmlContent) - return htmlContent, nil + return buf.String(), nil } // formatEmailDate formats a time.Time for email display @@ -181,8 +174,6 @@ func SendReminderEmail(db *sql.DB, promise models.Promise, userEmail string) err // sendSMTPEmail sends an email via SMTP using gomail func sendSMTPEmail(config *SMTPConfig, to, subject, htmlBody string) error { - log.Printf("[EMAIL] Sending email to %s, subject: %s, HTML body length: %d", to, subject, len(htmlBody)) - m := gomail.NewMessage() m.SetHeader("From", config.From) m.SetHeader("To", to) @@ -199,11 +190,9 @@ func sendSMTPEmail(config *SMTPConfig, to, subject, htmlBody string) error { // Send the email if err := d.DialAndSend(m); err != nil { - log.Printf("[EMAIL] Failed to send email: %v", err) return fmt.Errorf("failed to send email: %w", err) } - log.Printf("[EMAIL] Email sent successfully to %s", to) return nil } diff --git a/backend/internal/api/email_test_handler.go b/backend/internal/api/email_test_handler.go index 0db6812..7f33b0b 100644 --- a/backend/internal/api/email_test_handler.go +++ b/backend/internal/api/email_test_handler.go @@ -29,9 +29,9 @@ func TestEmailHandler(db *sql.DB) fiber.Handler { emailTestMutex.Unlock() remaining := 10*time.Minute - timeSinceLastTest return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{ - "error": "Email test rate limited", + "error": "Email test rate limited", "retry_after_seconds": int(remaining.Seconds()), - "message": fmt.Sprintf("Please wait %s before testing again", formatDuration(remaining)), + "message": fmt.Sprintf("Please wait %s before testing again", formatDuration(remaining)), }) } lastEmailTestTime = time.Now() @@ -41,7 +41,7 @@ func TestEmailHandler(db *sql.DB) fiber.Handler { config, err := GetSMTPConfig() if err != nil { return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{ - "error": "SMTP not configured", + "error": "SMTP not configured", "message": "Please configure SMTP environment variables (SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM)", "details": err.Error(), }) @@ -57,7 +57,7 @@ func TestEmailHandler(db *sql.DB) fiber.Handler { if !userEmail.Valid || userEmail.String == "" { return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ - "error": "No email address", + "error": "No email address", "message": "Your account does not have an email address set. Please update your profile.", }) } @@ -65,7 +65,7 @@ func TestEmailHandler(db *sql.DB) fiber.Handler { // Validate email format if !isValidEmail(userEmail.String) { return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ - "error": "Invalid email address", + "error": "Invalid email address", "message": "The email address on your account is not valid. Please update your profile with a valid email address.", }) } @@ -74,10 +74,10 @@ func TestEmailHandler(db *sql.DB) fiber.Handler { now := time.Now() tomorrow := now.Add(24 * time.Hour) testPromise := models.Promise{ - ID: 0, // Test promise - Recipient: "yourself", - Description: "Test email reminder", - DueDate: &tomorrow, + ID: 0, // Test promise + Recipient: "yourself", + Description: "Test email reminder", + DueDate: &tomorrow, CurrentState: "active", } @@ -85,7 +85,7 @@ func TestEmailHandler(db *sql.DB) fiber.Handler { err = SendReminderEmail(db, testPromise, userEmail.String) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ - "error": "Failed to send test email", + "error": "Failed to send test email", "message": err.Error(), }) } @@ -119,9 +119,9 @@ func formatDuration(d time.Duration) string { // isValidEmail checks if an email address is valid (simple regex) func isValidEmail(email string) bool { - // Basic RFC 5322 regex for demonstration (not exhaustive) - // Accepts most common valid emails, rejects obvious invalid ones - re := `^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$` - matched, _ := regexp.MatchString(re, email) - return matched + // Basic RFC 5322 regex for demonstration (not exhaustive) + // Accepts most common valid emails, rejects obvious invalid ones + re := `^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$` + matched, _ := regexp.MatchString(re, email) + return matched } diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.go index 3cadef6..4640387 100644 --- a/backend/internal/api/routes.go +++ b/backend/internal/api/routes.go @@ -58,11 +58,6 @@ func SetupRoutes(app *fiber.App, db *sql.DB) { push := protected.Group("/push") push.Post("/subscribe", SubscribePushHandler(db)) push.Delete("/unsubscribe", UnsubscribePushHandler(db)) - // Test endpoint for sending an actual push notification - push.Post("/test", SendTestPushHandler(db)) - - // Email test route (rate limited: once per 10 minutes) - protected.Post("/email/test", TestEmailHandler(db)) // User profile routes user := protected.Group("/user") diff --git a/frontend/src/main.js b/frontend/src/main.js index 2752419..7c3e9d5 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -33,6 +33,8 @@ class App { // If successful, show main screen this.ui.showMainScreen(); await this.ui.loadTimeline(); + // Handle any hash-based navigation from email links + this.handleHashNavigation(); } catch (error) { console.log('Session expired or invalid, showing login'); this.ui.showAuthScreen(); @@ -44,6 +46,13 @@ class App { this.ui.showLoginForm(); } + // Listen for hash changes + window.addEventListener('hashchange', () => { + if (this.auth.getUser()) { + this.handleHashNavigation(); + } + }); + // Register service worker if ('serviceWorker' in navigator) { try { @@ -62,6 +71,25 @@ class App { } } + handleHashNavigation() { + const hash = window.location.hash; + if (!hash || hash === '#' || hash === '#/') return; + + // Parse hash routes + if (hash.startsWith('#/promise/')) { + const promiseId = parseInt(hash.replace('#/promise/', '')); + if (!isNaN(promiseId)) { + this.ui.showPromiseDetail(promiseId); + // Clear hash to avoid showing promise again on refresh + window.location.hash = ''; + } + } else if (hash === '#/settings/notifications') { + this.ui.showNotificationSettings(); + // Clear hash + window.location.hash = ''; + } + } + initTheme() { // Get saved theme from localStorage or default to light const savedTheme = localStorage.getItem('theme') || 'light';

{{.Title}}

@@ -46,12 +43,12 @@

+ Due Date {{.DueDate}} + Promise to {{.PromiseTo}}