Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

Validate timezones and list all IANA zones in workspace settings

Jonas Kaninda93559c0541b9
diff --git a/cmd/posta/main.go b/cmd/posta/main.go
index 4ff15b4..1f41767 100644
--- a/cmd/posta/main.go
+++ b/cmd/posta/main.go
@@ -4,6 +4,10 @@
package main
import (
+ // Embed the tz database so timezone validation and scheduling behave the
+ // same on hosts without /usr/share/zoneinfo.
+ _ "time/tzdata"
+
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
"github.com/jkaninda/okapi/okapicli"
diff --git a/docs/docs/subscribers/bulk-import.md b/docs/docs/subscribers/bulk-import.md
index 18876b7..b46ac04 100644
--- a/docs/docs/subscribers/bulk-import.md
+++ b/docs/docs/subscribers/bulk-import.md
@@ -51,13 +51,16 @@ Response:
"data": {
"created": 2,
"skipped": 0,
- "total": 2
+ "total": 2,
+ "invalid_timezones": 0
}
}
```
Duplicate emails (already existing) are skipped, not updated.
+`timezone` must be an IANA name such as `Europe/London` or `America/New_York`. A subscriber with an unrecognised timezone is still imported, without a timezone, and counted in `invalid_timezones`. Creating or updating a single subscriber with an invalid timezone returns `400 Bad Request`.
+
## CSV Import
```
@@ -89,7 +92,7 @@ Map CSV columns to subscriber fields using a JSON object where keys are column i
}
```
-Custom fields use dot notation: `custom_fields.field_name`.
+Supported fields are `email`, `name`, `status`, `language`, `timezone` (IANA name, see [JSON Import](#json-import)) and custom fields, which use dot notation: `custom_fields.field_name`.
### Example
diff --git a/internal/handlers/data_export.go b/internal/handlers/data_export.go
index b314c47..bfbb024 100644
--- a/internal/handlers/data_export.go
+++ b/internal/handlers/data_export.go
@@ -531,10 +531,13 @@ func importSubscribers(data []ExportSubscriber, userID uint, workspaceID *uint,
if status == "" {
status = models.SubscriberStatusSubscribed
}
+ // Backups predate timezone validation; drop a bad value rather than
+ // carry it into the restored workspace.
+ tz, _ := subscriberTimezone(sub.Timezone)
if err := db.Create(&models.Subscriber{
UserID: userID, WorkspaceID: workspaceID,
Email: sub.Email, Name: sub.Name, Status: status,
- CustomFields: sub.CustomFields, Timezone: sub.Timezone, Language: sub.Language,
+ CustomFields: sub.CustomFields, Timezone: tz, Language: sub.Language,
}).Error; err != nil {
continue
}
diff --git a/internal/handlers/setting_timezone_test.go b/internal/handlers/setting_timezone_test.go
new file mode 100644
index 0000000..3037e22
--- /dev/null
+++ b/internal/handlers/setting_timezone_test.go
@@ -0,0 +1,96 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/jkaninda/okapi"
+)
+
+// Both settings endpoints accept only IANA names; an omitted timezone leaves
+// the stored one alone.
+func TestSettingsTimezoneValidation(t *testing.T) {
+ app := okapi.New()
+ ok := func(c *okapi.Context) error { return c.String(http.StatusOK, "ok") }
+ app.Put("/workspace", okapi.H(func(c *okapi.Context, _ *UpdateWorkspaceSettingsRequest) error { return ok(c) }))
+ app.Put("/user", okapi.H(func(c *okapi.Context, _ *UpdateUserSettingsRequest) error { return ok(c) }))
+
+ cases := []struct {
+ body string
+ want int
+ }{
+ {`{}`, http.StatusOK},
+ {`{"timezone":"UTC"}`, http.StatusOK},
+ {`{"timezone":"Africa/Kinshasa"}`, http.StatusOK},
+ {`{"timezone":"America/Argentina/Buenos_Aires"}`, http.StatusOK},
+ {`{"timezone":""}`, http.StatusBadRequest},
+ {`{"timezone":"Local"}`, http.StatusBadRequest},
+ {`{"timezone":"Mars/Olympus"}`, http.StatusBadRequest},
+ {`{"timezone":"+02:00"}`, http.StatusBadRequest},
+ }
+ for _, path := range []string{"/workspace", "/user"} {
+ for _, tc := range cases {
+ req := httptest.NewRequest(http.MethodPut, path, strings.NewReader(tc.body))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, req)
+ if rec.Code != tc.want {
+ t.Errorf("%s %s: status %d, want %d (%s)", path, tc.body, rec.Code, tc.want, rec.Body.String())
+ }
+ }
+ }
+}
+
+// A subscriber may have no timezone, but a given one must be an IANA name.
+func TestSubscriberTimezoneValidation(t *testing.T) {
+ app := okapi.New()
+ ok := func(c *okapi.Context) error { return c.String(http.StatusOK, "ok") }
+ app.Post("/subscribers", okapi.H(func(c *okapi.Context, _ *CreateSubscriberRequest) error { return ok(c) }))
+ app.Put("/subscribers/{id}", okapi.H(func(c *okapi.Context, _ *UpdateSubscriberRequest) error { return ok(c) }))
+
+ for _, tc := range []struct {
+ tz string
+ want int
+ }{
+ {`""`, http.StatusOK},
+ {`"Africa/Kinshasa"`, http.StatusOK},
+ {`"Mars/Olympus"`, http.StatusBadRequest},
+ {`"Local"`, http.StatusBadRequest},
+ } {
+ for _, r := range []struct{ method, path string }{{http.MethodPost, "/subscribers"}, {http.MethodPut, "/subscribers/1"}} {
+ body := `{"email":"[email protected]","timezone":` + tc.tz + `}`
+ req := httptest.NewRequest(r.method, r.path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, req)
+ if rec.Code != tc.want {
+ t.Errorf("%s %s timezone=%s: status %d, want %d (%s)", r.method, r.path, tc.tz, rec.Code, tc.want, rec.Body.String())
+ }
+ }
+ }
+}
+
+// Imports and restores keep the subscriber and drop only a bad timezone.
+func TestSubscriberTimezoneNormalisation(t *testing.T) {
+ for _, tc := range []struct {
+ in, want string
+ valid bool
+ }{
+ {"", "", true},
+ {" Europe/Paris ", "Europe/Paris", true},
+ {"UTC", "UTC", true},
+ {"Local", "", false},
+ {"GMT+2", "", false},
+ {"Mars/Olympus", "", false},
+ } {
+ got, valid := subscriberTimezone(tc.in)
+ if got != tc.want || valid != tc.valid {
+ t.Errorf("subscriberTimezone(%q) = %q, %v; want %q, %v", tc.in, got, valid, tc.want, tc.valid)
+ }
+ }
+}
diff --git a/internal/handlers/subscriber_handler.go b/internal/handlers/subscriber_handler.go
index 553203a..1b4bdf2 100644
--- a/internal/handlers/subscriber_handler.go
+++ b/internal/handlers/subscriber_handler.go
@@ -30,7 +30,7 @@ type CreateSubscriberRequest struct {
Name string `json:"name"`
Status string `json:"status"`
CustomFields map[string]interface{} `json:"custom_fields"`
- Timezone string `json:"timezone"`
+ Timezone string `json:"timezone" format:"timezone" maxLength:"50" doc:"IANA timezone name; empty for none"`
Language string `json:"language"`
} `json:"body"`
}
@@ -41,7 +41,7 @@ type UpdateSubscriberRequest struct {
Name string `json:"name"`
Status string `json:"status"`
CustomFields map[string]interface{} `json:"custom_fields"`
- Timezone string `json:"timezone"`
+ Timezone string `json:"timezone" format:"timezone" maxLength:"50" doc:"IANA timezone name; empty for none"`
Language string `json:"language"`
} `json:"body"`
}
@@ -79,6 +79,26 @@ type BulkImportResult struct {
Created int `json:"created"`
Skipped int `json:"skipped"`
Total int `json:"total"`
+ // InvalidTimezones counts imported subscribers whose timezone was not an
+ // IANA name. They are still imported, with no timezone.
+ InvalidTimezones int `json:"invalid_timezones"`
+}
+
+// subscriberTimezone returns tz when it is an IANA name (the check okapi's
+// format:"timezone" applies), and "" otherwise. Imports and restores use it
+// so one bad value drops the field instead of failing the whole batch.
+func subscriberTimezone(tz string) (string, bool) {
+ tz = strings.TrimSpace(tz)
+ if tz == "" {
+ return "", true
+ }
+ if tz == "Local" || len(tz) > 50 {
+ return "", false
+ }
+ if _, err := time.LoadLocation(tz); err != nil {
+ return "", false
+ }
+ return tz, true
}
func (h *SubscriberHandler) Create(c *okapi.Context, req *CreateSubscriberRequest) error {
@@ -193,17 +213,22 @@ func (h *SubscriberHandler) BulkImportJSON(c *okapi.Context, req *BulkImportSubs
now := time.Now()
var subscribers []models.Subscriber
+ invalidTZ := 0
for _, entry := range req.Body.Subscribers {
email := strings.ToLower(strings.TrimSpace(entry.Email))
if email == "" {
continue
}
+ tz, valid := subscriberTimezone(entry.Timezone)
+ if !valid {
+ invalidTZ++
+ }
subscribers = append(subscribers, models.Subscriber{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
Email: email,
Name: strings.TrimSpace(entry.Name),
- Timezone: strings.TrimSpace(entry.Timezone),
+ Timezone: tz,
Language: strings.TrimSpace(entry.Language),
Status: models.SubscriberStatusSubscribed,
CustomFields: entry.CustomFields,
@@ -217,9 +242,10 @@ func (h *SubscriberHandler) BulkImportJSON(c *okapi.Context, req *BulkImportSubs
}
return ok(c, BulkImportResult{
- Created: created,
- Skipped: skipped,
- Total: len(subscribers),
+ Created: created,
+ Skipped: skipped,
+ Total: len(subscribers),
+ InvalidTimezones: invalidTZ,
})
}
@@ -262,6 +288,7 @@ func (h *SubscriberHandler) BulkImportCSV(c *okapi.Context) error {
now := time.Now()
var subscribers []models.Subscriber
+ invalidTZ := 0
for {
record, err := reader.Read()
if err == io.EOF {
@@ -293,6 +320,12 @@ func (h *SubscriberHandler) BulkImportCSV(c *okapi.Context) error {
s.Status = models.SubscriberStatus(val)
case "language":
s.Language = val
+ case "timezone":
+ tz, valid := subscriberTimezone(val)
+ if !valid {
+ invalidTZ++
+ }
+ s.Timezone = tz
default:
if strings.HasPrefix(field, "custom_fields.") {
key := strings.TrimPrefix(field, "custom_fields.")
@@ -313,8 +346,9 @@ func (h *SubscriberHandler) BulkImportCSV(c *okapi.Context) error {
}
return ok(c, BulkImportResult{
- Created: createdCount,
- Skipped: skipped,
- Total: len(subscribers),
+ Created: createdCount,
+ Skipped: skipped,
+ Total: len(subscribers),
+ InvalidTimezones: invalidTZ,
})
}
diff --git a/internal/handlers/user_setting_handler.go b/internal/handlers/user_setting_handler.go
index 631df19..5ce4e60 100644
--- a/internal/handlers/user_setting_handler.go
+++ b/internal/handlers/user_setting_handler.go
@@ -19,7 +19,7 @@ func NewUserSettingHandler(repo *repositories.UserSettingRepository) *UserSettin
type UpdateUserSettingsRequest struct {
Body struct {
- Timezone *string `json:"timezone"`
+ Timezone *string `json:"timezone" format:"timezone" minLength:"1" example:"Africa/Kinshasa" doc:"IANA timezone name"`
DefaultSenderName *string `json:"default_sender_name"`
DefaultSenderEmail *string `json:"default_sender_email"`
EmailNotifications *bool `json:"email_notifications"`
diff --git a/internal/handlers/workspace_setting_handler.go b/internal/handlers/workspace_setting_handler.go
index 749bb1e..16983b8 100644
--- a/internal/handlers/workspace_setting_handler.go
+++ b/internal/handlers/workspace_setting_handler.go
@@ -18,7 +18,7 @@ func NewWorkspaceSettingHandler(repo *repositories.WorkspaceSettingRepository) *
type UpdateWorkspaceSettingsRequest struct {
Body struct {
- Timezone *string `json:"timezone"`
+ Timezone *string `json:"timezone" format:"timezone" minLength:"1" example:"Africa/Kinshasa" doc:"IANA timezone name"`
DefaultSenderName *string `json:"default_sender_name"`
DefaultSenderEmail *string `json:"default_sender_email"`
WebhookRetryCount *int `json:"webhook_retry_count"`
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 5e08854..b592bb3 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -1079,6 +1079,8 @@ export interface BulkImportResult {
created: number
skipped: number
total: number
+ // Imported anyway, with no timezone.
+ invalid_timezones?: number
}
// Campaigns
diff --git a/web/src/composables/timezones.ts b/web/src/composables/timezones.ts
new file mode 100644
index 0000000..3a3f686
--- /dev/null
+++ b/web/src/composables/timezones.ts
@@ -0,0 +1,62 @@
+// IANA timezone names for timezone pickers, with their current UTC offset.
+// The list comes from the browser (Intl.supportedValuesOf) so it tracks the
+// tz database instead of a hand-maintained subset; the backend validates the
+// chosen name against Go's tz database (okapi `format:"timezone"`).
+
+export interface TimezoneOption {
+ value: string
+ label: string
+}
+
+// Used only when the browser cannot enumerate zones (pre-2022 engines).
+const FALLBACK_ZONES = [
+ 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles',
+ 'America/Sao_Paulo', 'Europe/London', 'Europe/Paris', 'Europe/Berlin', 'Europe/Moscow',
+ 'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Kolkata', 'Asia/Dubai', 'Asia/Singapore',
+ 'Australia/Sydney', 'Pacific/Auckland', 'Africa/Kinshasa', 'Africa/Lubumbashi',
+ 'Africa/Nairobi', 'Africa/Lagos', 'Africa/Johannesburg', 'Africa/Cairo',
+]
+
+function zoneNames(): string[] {
+ try {
+ const names = Intl.supportedValuesOf('timeZone')
+ if (names.length > 0) return names
+ } catch {
+ /* fall through */
+ }
+ return FALLBACK_ZONES
+}
+
+function utcOffset(zone: string, at: Date): string {
+ try {
+ const part = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' })
+ .formatToParts(at)
+ .find((p) => p.type === 'timeZoneName')?.value
+ // "GMT" alone means +00:00; otherwise it is "GMT+05:30".
+ return !part || part === 'GMT' ? 'UTC+00:00' : part.replace('GMT', 'UTC')
+ } catch {
+ return ''
+ }
+}
+
+let cached: TimezoneOption[] | null = null
+
+// timezoneOptions returns UTC first, then every zone sorted by name. A saved
+// value missing from the browser's list (an alias such as Asia/Calcutta, or a
+// zone this engine does not know) is kept so opening the form never changes it.
+export function timezoneOptions(current?: string): TimezoneOption[] {
+ if (!cached) {
+ const now = new Date()
+ const names = zoneNames().filter((z) => z !== 'UTC').sort()
+ cached = [{ value: 'UTC', label: 'UTC' }].concat(
+ names.map((z) => {
+ const offset = utcOffset(z, now)
+ return { value: z, label: offset ? `${z} (${offset})` : z }
+ }),
+ )
+ }
+ if (current && !cached.some((o) => o.value === current)) {
+ return [{ value: current, label: current }, ...cached]
+ }
+ return cached
+}
diff --git a/web/src/views/subscribers/Subscribers.vue b/web/src/views/subscribers/Subscribers.vue
index e0e07e9..0fefc5a 100644
--- a/web/src/views/subscribers/Subscribers.vue
+++ b/web/src/views/subscribers/Subscribers.vue
@@ -2,7 +2,7 @@
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { subscribersApi } from '../../api/subscribers'
-import type { Subscriber, SubscriberStatus } from '../../api/types'
+import type { BulkImportResult, Subscriber, SubscriberStatus } from '../../api/types'
import Pagination from '../../components/Pagination.vue'
import { usePagination } from '../../composables/usePagination'
import { useNotificationStore } from '../../stores/notification'
@@ -95,6 +95,14 @@ function openImportJson() {
showImportJsonModal.value = true
}
+function importSummary(prefix: string, result: BulkImportResult): string {
+ let msg = `${prefix}: ${result.created} created, ${result.skipped} skipped out of ${result.total}`
+ if (result.invalid_timezones) {
+ msg += ` (${result.invalid_timezones} with an unrecognised timezone, imported without one)`
+ }
+ return msg
+}
+
async function importJson() {
if (!importJsonText.value.trim()) return
importing.value = true
@@ -103,7 +111,7 @@ async function importJson() {
const subscribers = Array.isArray(data) ? data : [data]
const res = await subscribersApi.bulkImportJSON(subscribers)
const result = res.data.data
- notify.success(`Import complete: ${result.created} created, ${result.skipped} skipped out of ${result.total}`)
+ notify.success(importSummary('Import complete', result))
showImportJsonModal.value = false
await goToPage(pageable.value.current_page)
} catch (e: any) {
@@ -129,7 +137,7 @@ async function onCsvFileSelected(event: Event) {
try {
const res = await subscribersApi.bulkImportCSV(file)
const result = res.data.data
- notify.success(`CSV import complete: ${result.created} created, ${result.skipped} skipped out of ${result.total}`)
+ notify.success(importSummary('CSV import complete', result))
await goToPage(pageable.value.current_page)
} catch (e: any) {
notify.error(e?.response?.data?.error?.message || 'Failed to import CSV')
diff --git a/web/src/views/workspaces/WorkspaceSettings.vue b/web/src/views/workspaces/WorkspaceSettings.vue
index 960cbd4..5f49a67 100644
--- a/web/src/views/workspaces/WorkspaceSettings.vue
+++ b/web/src/views/workspaces/WorkspaceSettings.vue
@@ -8,6 +8,7 @@ import type { Workspace, Plan, OAuthProviderInfo, WorkspaceSSOConfig, WorkspaceS
import { useNotificationStore } from '../../stores/notification'
import { useWorkspaceStore } from '../../stores/workspace'
import { useConfirm } from '../../composables/useConfirm'
+import { timezoneOptions } from '../../composables/timezones'
const route = useRoute()
const router = useRouter()
@@ -64,12 +65,6 @@ const saving = ref(false)
// Operational workspace settings (timezone, sender defaults, webhook retries,
// API-key expiry, bounce auto-suppress) — backed by /workspaces/current/settings.
-const timezones = [
- 'UTC', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles',
- 'Europe/London', 'Europe/Paris', 'Europe/Berlin', 'Europe/Moscow',
- 'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Kolkata', 'Asia/Dubai',
- 'Australia/Sydney', 'Pacific/Auckland', 'Africa/Kinshasa', 'Africa/Nairobi', 'Africa/Lagos', 'Africa/Lubumbashi',
-]
const wsSettings = ref<Partial<WorkspaceSettings>>({
timezone: 'UTC',
default_sender_name: '',
@@ -79,6 +74,7 @@ const wsSettings = ref<Partial<WorkspaceSettings>>({
bounce_auto_suppress: true,
require_verified_domain: false,
})
+const timezones = computed(() => timezoneOptions(wsSettings.value.timezone))
const wsSettingsLoading = ref(false)
const wsSettingsSaving = ref(false)
@@ -545,7 +541,7 @@ watch(activeTab, (value) => {
<div class="form-group">
<label class="form-label">Timezone</label>
<select v-model="wsSettings.timezone" class="form-select">
- <option v-for="tz in timezones" :key="tz" :value="tz">{{ tz }}</option>
+ <option v-for="tz in timezones" :key="tz.value" :value="tz.value">{{ tz.label }}</option>
</select>
</div>
<div class="form-group">