create-nextblock 0.15.5 → 0.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/package.json +50 -26
  2. package/templates/nextblock-template/app/ToasterProvider.tsx +26 -17
  3. package/templates/nextblock-template/app/actions/contactSellerActions.test.ts +280 -0
  4. package/templates/nextblock-template/app/actions/contactSellerActions.ts +222 -0
  5. package/templates/nextblock-template/app/actions/email-retry.test.ts +62 -0
  6. package/templates/nextblock-template/app/actions/email.ts +241 -110
  7. package/templates/nextblock-template/app/actions/formActions.ts +245 -116
  8. package/templates/nextblock-template/app/actions/interactions.ts +489 -396
  9. package/templates/nextblock-template/app/actions/threadActions.ts +166 -0
  10. package/templates/nextblock-template/app/api/checkout/route.ts +162 -146
  11. package/templates/nextblock-template/app/api/cron/reset-sandbox/route.ts +14 -0
  12. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +664 -1
  13. package/templates/nextblock-template/app/checkout/page.tsx +57 -52
  14. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +552 -529
  15. package/templates/nextblock-template/app/cms/blocks/editors/FormBlockEditor.tsx +304 -181
  16. package/templates/nextblock-template/app/cms/components/ContactReminderBanner.tsx +75 -0
  17. package/templates/nextblock-template/app/cms/components/PaymentsReminderBanner.tsx +58 -0
  18. package/templates/nextblock-template/app/cms/components/VisibilityControl.tsx +542 -528
  19. package/templates/nextblock-template/app/cms/inquiries/actions.ts +66 -0
  20. package/templates/nextblock-template/app/cms/inquiries/page.tsx +12 -0
  21. package/templates/nextblock-template/app/cms/interactions/page.tsx +12 -51
  22. package/templates/nextblock-template/app/cms/layout.tsx +101 -73
  23. package/templates/nextblock-template/app/cms/messages/MessagesClient.tsx +661 -0
  24. package/templates/nextblock-template/app/cms/messages/actions.ts +404 -0
  25. package/templates/nextblock-template/app/cms/messages/loadInbox.ts +333 -0
  26. package/templates/nextblock-template/app/cms/messages/page.tsx +87 -0
  27. package/templates/nextblock-template/app/cms/messages/require-admin.ts +37 -0
  28. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +370 -362
  29. package/templates/nextblock-template/app/cms/revisions/service.ts +20 -0
  30. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +227 -185
  31. package/templates/nextblock-template/app/layout.tsx +671 -667
  32. package/templates/nextblock-template/app/lib/seo.ts +319 -311
  33. package/templates/nextblock-template/app/product/[slug]/page.tsx +502 -482
  34. package/templates/nextblock-template/app/providers.tsx +96 -96
  35. package/templates/nextblock-template/app/thread/ThreadView.tsx +164 -0
  36. package/templates/nextblock-template/app/thread/[token]/route.ts +57 -0
  37. package/templates/nextblock-template/app/thread/layout.tsx +15 -0
  38. package/templates/nextblock-template/app/thread/page.tsx +98 -0
  39. package/templates/nextblock-template/components/BlockRenderer.tsx +312 -296
  40. package/templates/nextblock-template/components/ContactSellerSection.tsx +188 -0
  41. package/templates/nextblock-template/components/PostCommentsSection.tsx +378 -369
  42. package/templates/nextblock-template/components/ProductReviewsSection.tsx +426 -419
  43. package/templates/nextblock-template/components/StaffReplies.tsx +102 -0
  44. package/templates/nextblock-template/components/blocks/renderers/CartBlockRenderer.tsx +18 -17
  45. package/templates/nextblock-template/components/blocks/renderers/CheckoutBlockRenderer.tsx +20 -19
  46. package/templates/nextblock-template/components/blocks/renderers/FeaturedProductBlockRenderer.tsx +25 -22
  47. package/templates/nextblock-template/components/blocks/renderers/FormBlockRenderer.tsx +385 -381
  48. package/templates/nextblock-template/components/blocks/renderers/ProductDetailsBlockRenderer.tsx +157 -92
  49. package/templates/nextblock-template/components/blocks/renderers/ProductGridBlockRenderer.tsx +34 -31
  50. package/templates/nextblock-template/components/blocks/renderers/SectionBlockRenderer.tsx +612 -600
  51. package/templates/nextblock-template/components/commerce/PaymentReadinessBoundary.tsx +32 -0
  52. package/templates/nextblock-template/docs/05-DEVELOPER-GUIDE.md +25 -19
  53. package/templates/nextblock-template/docs/06-CLI-AND-SCAFFOLDING.md +1 -1
  54. package/templates/nextblock-template/docs/08-NEXTBLOCK-CORTEX-AI-ARCHITECTURE.md +2 -2
  55. package/templates/nextblock-template/docs/12-VERCEL-DEPLOYMENT.md +32 -9
  56. package/templates/nextblock-template/docs/14-MESSAGES-INBOX.md +309 -0
  57. package/templates/nextblock-template/docs/README.md +42 -41
  58. package/templates/nextblock-template/docs/TECHNICAL_SPECIFICATION.md +540 -542
  59. package/templates/nextblock-template/docs/assets/lighthouse-scores.png +0 -0
  60. package/templates/nextblock-template/lib/blocks/blockColors.test.ts +22 -2
  61. package/templates/nextblock-template/lib/blocks/blockColors.ts +44 -1
  62. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +761 -753
  63. package/templates/nextblock-template/lib/cms/contact-reminder.ts +64 -0
  64. package/templates/nextblock-template/lib/cms/payments-reminder.ts +98 -0
  65. package/templates/nextblock-template/lib/cms/unread-messages.ts +42 -0
  66. package/templates/nextblock-template/lib/commerce/seller-contact.ts +162 -0
  67. package/templates/nextblock-template/lib/config/email-settings.ts +323 -254
  68. package/templates/nextblock-template/lib/config/email-tls.test.ts +57 -0
  69. package/templates/nextblock-template/lib/email/placeholder-address.test.ts +59 -0
  70. package/templates/nextblock-template/lib/email/placeholder-address.ts +39 -0
  71. package/templates/nextblock-template/lib/messages/thread-reference.test.ts +70 -0
  72. package/templates/nextblock-template/lib/messages/thread-token.test.ts +93 -0
  73. package/templates/nextblock-template/lib/messages/thread-token.ts +157 -0
  74. package/templates/nextblock-template/lib/messages/threads.ts +579 -0
  75. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +20 -0
  76. package/templates/nextblock-template/lib/site-url.test.ts +89 -0
  77. package/templates/nextblock-template/lib/site-url.ts +102 -48
  78. package/templates/nextblock-template/package.json +14 -1
  79. package/templates/nextblock-template/public/assets/nextblock-banner.jpg +0 -0
@@ -1,254 +1,323 @@
1
- import 'server-only';
2
- // DB-backed SMTP configuration. Non-secret fields (host, port, from, secure) live in the
3
- // public `email_public` row; the SMTP username and password live encrypted in the
4
- // ADMIN-only `email_secret` row. Resolution is DB-first with an env fallback
5
- // (SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS / SMTP_FROM_EMAIL / SMTP_FROM_NAME) so
6
- // existing deployments keep working until the values are moved into the CMS.
7
- import {
8
- createClient,
9
- getServiceRoleSupabaseClient,
10
- encryptWithEnvKey,
11
- getSecretEnvelopeStatus,
12
- isSandboxEnvironment,
13
- resolveConfigValue,
14
- tryDecryptWithEnvKey,
15
- } from '@nextblock-cms/db/server';
16
-
17
- const EMAIL_PUBLIC_KEY = 'email_public';
18
- const EMAIL_SECRET_KEY = 'email_secret';
19
-
20
- export type EmailPublicSettings = {
21
- host: string;
22
- port: string;
23
- fromEmail: string;
24
- fromName: string;
25
- secure: boolean;
26
- };
27
-
28
- export const DEFAULT_EMAIL_PUBLIC_SETTINGS: EmailPublicSettings = {
29
- host: '',
30
- port: '',
31
- fromEmail: '',
32
- fromName: '',
33
- secure: true,
34
- };
35
-
36
- /** What the CMS form needs: public fields + whether each secret is already stored. */
37
- export type EmailSettingsView = EmailPublicSettings & {
38
- hasUser: boolean;
39
- hasPass: boolean;
40
- userLast4: string | null;
41
- envFallbackActive: boolean;
42
- };
43
-
44
- /** Fully-resolved transport config consumed by nodemailer. */
45
- export type ResolvedEmailConfig = {
46
- host: string;
47
- port: number;
48
- secure: boolean;
49
- auth: { user: string; pass: string };
50
- from: string;
51
- };
52
-
53
- function asString(value: unknown, fallback = ''): string {
54
- return typeof value === 'string' ? value : fallback;
55
- }
56
-
57
- function asBool(value: unknown, fallback: boolean): boolean {
58
- if (typeof value === 'boolean') return value;
59
- if (typeof value === 'string') return value === 'true' || value === 'on';
60
- return fallback;
61
- }
62
-
63
- function normalizePublic(value: unknown): EmailPublicSettings {
64
- const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
65
- return {
66
- host: asString(raw['host']),
67
- port: asString(raw['port']),
68
- fromEmail: asString(raw['fromEmail']),
69
- fromName: asString(raw['fromName']),
70
- secure: asBool(raw['secure'], true),
71
- };
72
- }
73
-
74
- export async function getEmailPublicSettings(): Promise<EmailPublicSettings> {
75
- const supabase = createClient();
76
- const { data } = await supabase
77
- .from('site_settings')
78
- .select('value')
79
- .eq('key', EMAIL_PUBLIC_KEY)
80
- .maybeSingle();
81
- return normalizePublic(data?.value);
82
- }
83
-
84
- /**
85
- * Read the public settings plus stored-secret status for the CMS form. Uses the
86
- * request-scoped client; RLS restricts the secret row to ADMIN, which is who reaches
87
- * this page.
88
- */
89
- export async function getEmailSettingsView(): Promise<EmailSettingsView> {
90
- const supabase = createClient();
91
- const [{ data: publicData }, { data: secretData }] = await Promise.all([
92
- supabase.from('site_settings').select('value').eq('key', EMAIL_PUBLIC_KEY).maybeSingle(),
93
- supabase.from('site_settings').select('value').eq('key', EMAIL_SECRET_KEY).maybeSingle(),
94
- ]);
95
-
96
- const pub = normalizePublic(publicData?.value);
97
- const secret = (secretData?.value ?? {}) as Record<string, unknown>;
98
- const userStatus = getSecretEnvelopeStatus(secret['user']);
99
- const passStatus = getSecretEnvelopeStatus(secret['pass']);
100
-
101
- return {
102
- ...pub,
103
- hasUser: userStatus.hasStoredValue,
104
- hasPass: passStatus.hasStoredValue,
105
- userLast4: userStatus.last4,
106
- // Show a hint in the UI when SMTP still comes from env vars rather than the CMS.
107
- envFallbackActive: !pub.host && Boolean(process.env['SMTP_HOST']),
108
- };
109
- }
110
-
111
- export type SaveEmailSettingsInput = {
112
- host: string;
113
- port: string;
114
- fromEmail: string;
115
- fromName: string;
116
- secure: boolean;
117
- /** Only persisted when non-empty — a blank field keeps the existing stored secret. */
118
- user?: string;
119
- pass?: string;
120
- };
121
-
122
- /**
123
- * Persist email settings. Public fields always overwrite; secret fields are encrypted
124
- * and only written when a new value is supplied. Refuses to store real secrets in the
125
- * sandbox (its DB resets daily). Caller must enforce ADMIN; RLS double-enforces.
126
- */
127
- export async function saveEmailSettings(input: SaveEmailSettingsInput): Promise<void> {
128
- const supabase = createClient();
129
-
130
- const publicValue: EmailPublicSettings = {
131
- host: input.host.trim(),
132
- port: input.port.trim(),
133
- fromEmail: input.fromEmail.trim(),
134
- fromName: input.fromName.trim(),
135
- secure: input.secure,
136
- };
137
-
138
- const { error: publicError } = await supabase
139
- .from('site_settings')
140
- .upsert({ key: EMAIL_PUBLIC_KEY, value: publicValue });
141
- if (publicError) {
142
- console.error('Error saving email_public settings:', publicError.message);
143
- throw new Error('Failed to save email settings.');
144
- }
145
-
146
- const newUser = input.user?.trim();
147
- const newPass = input.pass?.trim();
148
- if (newUser || newPass) {
149
- if (isSandboxEnvironment()) {
150
- throw new Error('The sandbox cannot store live SMTP credentials.');
151
- }
152
-
153
- // Read-merge so updating only one of user/pass keeps the other.
154
- const { data: existing } = await supabase
155
- .from('site_settings')
156
- .select('value')
157
- .eq('key', EMAIL_SECRET_KEY)
158
- .maybeSingle();
159
- const current = (existing?.value ?? {}) as Record<string, unknown>;
160
-
161
- const nextValue: Record<string, unknown> = { ...current };
162
- if (newUser) nextValue['user'] = encryptWithEnvKey(newUser);
163
- if (newPass) nextValue['pass'] = encryptWithEnvKey(newPass);
164
-
165
- const { error: secretError } = await supabase
166
- .from('site_settings')
167
- .upsert({ key: EMAIL_SECRET_KEY, value: nextValue });
168
- if (secretError) {
169
- console.error('Error saving email_secret settings:', secretError.message);
170
- throw new Error('Failed to save email credentials.');
171
- }
172
- }
173
-
174
- // The mailer memoizes the resolved transport config; make the new values live now.
175
- invalidateEmailConfigCache();
176
- }
177
-
178
- // Resolving SMTP costs two service-role reads plus an AES decrypt of each secret, and
179
- // transactional email (2FA codes especially) is latency-sensitive. The values only change
180
- // when an admin saves the form, so memoize briefly and bust the cache on save.
181
- const CONFIG_CACHE_TTL_MS = 60_000;
182
- let configCache: { value: ResolvedEmailConfig | null; expiresAt: number } | null = null;
183
-
184
- /** Drop the memoized SMTP config so the next resolve re-reads the DB. */
185
- export function invalidateEmailConfigCache(): void {
186
- configCache = null;
187
- }
188
-
189
- /**
190
- * Cheap "can this instance actually send mail right now?" check for UI gating. Never
191
- * logs — an unconfigured instance is an expected state here, not an error condition.
192
- */
193
- export async function isEmailConfigured(): Promise<boolean> {
194
- return (await resolveEmailServerConfig({ silent: true })) !== null;
195
- }
196
-
197
- /**
198
- * Resolve the full SMTP transport config, DB-first with an env fallback. Uses the
199
- * service-role client so it works from any context (the secret row is ADMIN-only under
200
- * RLS). Returns null when host/user/pass/from cannot be resolved from either source.
201
- *
202
- * Memoized for CONFIG_CACHE_TTL_MS; pass `silent` when "not configured" is an expected
203
- * answer (UI gating) rather than a misconfiguration worth warning about.
204
- */
205
- export async function resolveEmailServerConfig(
206
- options: { silent?: boolean } = {},
207
- ): Promise<ResolvedEmailConfig | null> {
208
- const cached = configCache;
209
- if (cached && cached.expiresAt > Date.now()) {
210
- return cached.value;
211
- }
212
-
213
- let pub: EmailPublicSettings = DEFAULT_EMAIL_PUBLIC_SETTINGS;
214
- let secret: Record<string, unknown> = {};
215
-
216
- try {
217
- const supabase = getServiceRoleSupabaseClient();
218
- const [{ data: publicData }, { data: secretData }] = await Promise.all([
219
- supabase.from('site_settings').select('value').eq('key', EMAIL_PUBLIC_KEY).maybeSingle(),
220
- supabase.from('site_settings').select('value').eq('key', EMAIL_SECRET_KEY).maybeSingle(),
221
- ]);
222
- pub = normalizePublic(publicData?.value);
223
- secret = (secretData?.value ?? {}) as Record<string, unknown>;
224
- } catch {
225
- // No service-role key (unconfigured instance) — fall through to env-only resolution.
226
- }
227
-
228
- const host = resolveConfigValue(pub.host, 'SMTP_HOST');
229
- const port = resolveConfigValue(pub.port, 'SMTP_PORT');
230
- const fromEmail = resolveConfigValue(pub.fromEmail, 'SMTP_FROM_EMAIL');
231
- const fromName = resolveConfigValue(pub.fromName, 'SMTP_FROM_NAME');
232
- const user = resolveConfigValue(tryDecryptWithEnvKey(secret['user']), 'SMTP_USER');
233
- const pass = resolveConfigValue(tryDecryptWithEnvKey(secret['pass']), 'SMTP_PASS');
234
-
235
- if (!host || !port || !user || !pass || !fromEmail) {
236
- if (!options.silent) {
237
- console.warn('Email is not configured (CMS or SMTP_* env). Outbound email will not be sent.');
238
- }
239
- configCache = { value: null, expiresAt: Date.now() + CONFIG_CACHE_TTL_MS };
240
- return null;
241
- }
242
-
243
- const portNumber = Number(port);
244
- const resolved: ResolvedEmailConfig = {
245
- host,
246
- port: portNumber,
247
- // Honor the CMS toggle; fall back to the SMTPS convention (465 ⇒ implicit TLS).
248
- secure: pub.host ? pub.secure : portNumber === 465,
249
- auth: { user, pass },
250
- from: fromName ? `"${fromName}" <${fromEmail}>` : fromEmail,
251
- };
252
- configCache = { value: resolved, expiresAt: Date.now() + CONFIG_CACHE_TTL_MS };
253
- return resolved;
254
- }
1
+ import 'server-only';
2
+ // DB-backed SMTP configuration. Non-secret fields (host, port, from, secure) live in the
3
+ // public `email_public` row; the SMTP username and password live encrypted in the
4
+ // ADMIN-only `email_secret` row. Resolution is DB-first with an env fallback
5
+ // (SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS / SMTP_FROM_EMAIL / SMTP_FROM_NAME) so
6
+ // existing deployments keep working until the values are moved into the CMS.
7
+ import {
8
+ createClient,
9
+ getServiceRoleSupabaseClient,
10
+ encryptWithEnvKey,
11
+ getSecretEnvelopeStatus,
12
+ isSandboxEnvironment,
13
+ resolveConfigValue,
14
+ tryDecryptWithEnvKey,
15
+ } from '@nextblock-cms/db/server';
16
+
17
+ const EMAIL_PUBLIC_KEY = 'email_public';
18
+ const EMAIL_SECRET_KEY = 'email_secret';
19
+
20
+ export type EmailPublicSettings = {
21
+ host: string;
22
+ port: string;
23
+ fromEmail: string;
24
+ fromName: string;
25
+ secure: boolean;
26
+ };
27
+
28
+ export const DEFAULT_EMAIL_PUBLIC_SETTINGS: EmailPublicSettings = {
29
+ host: '',
30
+ port: '',
31
+ fromEmail: '',
32
+ fromName: '',
33
+ secure: true,
34
+ };
35
+
36
+ /** What the CMS form needs: public fields + whether each secret is already stored. */
37
+ export type EmailSettingsView = EmailPublicSettings & {
38
+ hasUser: boolean;
39
+ hasPass: boolean;
40
+ userLast4: string | null;
41
+ envFallbackActive: boolean;
42
+ };
43
+
44
+ /** Fully-resolved transport config consumed by nodemailer. */
45
+ export type ResolvedEmailConfig = {
46
+ /** Refuse to send unless the connection is upgraded to TLS (STARTTLS ports). */
47
+ requireTLS?: boolean;
48
+ host: string;
49
+ port: number;
50
+ secure: boolean;
51
+ auth: { user: string; pass: string };
52
+ from: string;
53
+ };
54
+
55
+ function asString(value: unknown, fallback = ''): string {
56
+ return typeof value === 'string' ? value : fallback;
57
+ }
58
+
59
+ function asBool(value: unknown, fallback: boolean): boolean {
60
+ if (typeof value === 'boolean') return value;
61
+ if (typeof value === 'string') return value === 'true' || value === 'on';
62
+ return fallback;
63
+ }
64
+
65
+ function normalizePublic(value: unknown): EmailPublicSettings {
66
+ const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
67
+ return {
68
+ host: asString(raw['host']),
69
+ port: asString(raw['port']),
70
+ fromEmail: asString(raw['fromEmail']),
71
+ fromName: asString(raw['fromName']),
72
+ secure: asBool(raw['secure'], true),
73
+ };
74
+ }
75
+
76
+ export async function getEmailPublicSettings(): Promise<EmailPublicSettings> {
77
+ const supabase = createClient();
78
+ const { data } = await supabase
79
+ .from('site_settings')
80
+ .select('value')
81
+ .eq('key', EMAIL_PUBLIC_KEY)
82
+ .maybeSingle();
83
+ return normalizePublic(data?.value);
84
+ }
85
+
86
+ /**
87
+ * Read the public settings plus stored-secret status for the CMS form. Uses the
88
+ * request-scoped client; RLS restricts the secret row to ADMIN, which is who reaches
89
+ * this page.
90
+ */
91
+ export async function getEmailSettingsView(): Promise<EmailSettingsView> {
92
+ const supabase = createClient();
93
+ const [{ data: publicData }, { data: secretData }] = await Promise.all([
94
+ supabase.from('site_settings').select('value').eq('key', EMAIL_PUBLIC_KEY).maybeSingle(),
95
+ supabase.from('site_settings').select('value').eq('key', EMAIL_SECRET_KEY).maybeSingle(),
96
+ ]);
97
+
98
+ const pub = normalizePublic(publicData?.value);
99
+ const secret = (secretData?.value ?? {}) as Record<string, unknown>;
100
+ const userStatus = getSecretEnvelopeStatus(secret['user']);
101
+ const passStatus = getSecretEnvelopeStatus(secret['pass']);
102
+
103
+ return {
104
+ ...pub,
105
+ hasUser: userStatus.hasStoredValue,
106
+ hasPass: passStatus.hasStoredValue,
107
+ userLast4: userStatus.last4,
108
+ // Show a hint in the UI when SMTP still comes from env vars rather than the CMS.
109
+ envFallbackActive: !pub.host && Boolean(process.env['SMTP_HOST']),
110
+ };
111
+ }
112
+
113
+ export type SaveEmailSettingsInput = {
114
+ host: string;
115
+ port: string;
116
+ fromEmail: string;
117
+ fromName: string;
118
+ secure: boolean;
119
+ /** Only persisted when non-empty — a blank field keeps the existing stored secret. */
120
+ user?: string;
121
+ pass?: string;
122
+ };
123
+
124
+ /**
125
+ * Persist email settings. Public fields always overwrite; secret fields are encrypted
126
+ * and only written when a new value is supplied. Refuses to store real secrets in the
127
+ * sandbox (its DB resets daily). Caller must enforce ADMIN; RLS double-enforces.
128
+ */
129
+ export async function saveEmailSettings(input: SaveEmailSettingsInput): Promise<void> {
130
+ const supabase = createClient();
131
+
132
+ const publicValue: EmailPublicSettings = {
133
+ host: input.host.trim(),
134
+ port: input.port.trim(),
135
+ fromEmail: input.fromEmail.trim(),
136
+ fromName: input.fromName.trim(),
137
+ secure: input.secure,
138
+ };
139
+
140
+ const { error: publicError } = await supabase
141
+ .from('site_settings')
142
+ .upsert({ key: EMAIL_PUBLIC_KEY, value: publicValue });
143
+ if (publicError) {
144
+ console.error('Error saving email_public settings:', publicError.message);
145
+ throw new Error('Failed to save email settings.');
146
+ }
147
+
148
+ const newUser = input.user?.trim();
149
+ const newPass = input.pass?.trim();
150
+ if (newUser || newPass) {
151
+ if (isSandboxEnvironment()) {
152
+ throw new Error('The sandbox cannot store live SMTP credentials.');
153
+ }
154
+
155
+ // Read-merge so updating only one of user/pass keeps the other.
156
+ const { data: existing } = await supabase
157
+ .from('site_settings')
158
+ .select('value')
159
+ .eq('key', EMAIL_SECRET_KEY)
160
+ .maybeSingle();
161
+ const current = (existing?.value ?? {}) as Record<string, unknown>;
162
+
163
+ const nextValue: Record<string, unknown> = { ...current };
164
+ if (newUser) nextValue['user'] = encryptWithEnvKey(newUser);
165
+ if (newPass) nextValue['pass'] = encryptWithEnvKey(newPass);
166
+
167
+ const { error: secretError } = await supabase
168
+ .from('site_settings')
169
+ .upsert({ key: EMAIL_SECRET_KEY, value: nextValue });
170
+ if (secretError) {
171
+ console.error('Error saving email_secret settings:', secretError.message);
172
+ throw new Error('Failed to save email credentials.');
173
+ }
174
+ }
175
+
176
+ // The mailer memoizes the resolved transport config; make the new values live now.
177
+ invalidateEmailConfigCache();
178
+ }
179
+
180
+ // Resolving SMTP costs two service-role reads plus an AES decrypt of each secret, and
181
+ // transactional email (2FA codes especially) is latency-sensitive. The values only change
182
+ // when an admin saves the form, so memoize briefly and bust the cache on save.
183
+ const CONFIG_CACHE_TTL_MS = 60_000;
184
+ let configCache: { value: ResolvedEmailConfig | null; expiresAt: number } | null = null;
185
+
186
+ /** Drop the memoized SMTP config so the next resolve re-reads the DB. */
187
+ export function invalidateEmailConfigCache(): void {
188
+ configCache = null;
189
+ }
190
+
191
+ /**
192
+ * Cheap "can this instance actually send mail right now?" check for UI gating. Never
193
+ * logs an unconfigured instance is an expected state here, not an error condition.
194
+ */
195
+ export async function isEmailConfigured(): Promise<boolean> {
196
+ return (await resolveEmailServerConfig({ silent: true })) !== null;
197
+ }
198
+
199
+ /**
200
+ * Ports whose TLS mode is not a preference but a protocol fact.
201
+ *
202
+ * 465 is SMTPS: the server expects a TLS handshake as the very first bytes. 25, 587 and
203
+ * 2525 are plaintext-then-STARTTLS: the server opens with a plaintext `220` greeting.
204
+ *
205
+ * Getting this backwards produces an error nobody can act on. Implicit TLS against a
206
+ * STARTTLS port makes OpenSSL read that plaintext greeting as a TLS record and fail with
207
+ * "ssl3_get_record:wrong version number" which says nothing about ports or SMTP. The
208
+ * combination is never valid, so rather than honour a setting that cannot work, reconcile
209
+ * it and say so.
210
+ */
211
+ const IMPLICIT_TLS_PORTS = new Set([465]);
212
+ const STARTTLS_PORTS = new Set([25, 587, 2525]);
213
+
214
+ /** Local relays (Mailpit, MailHog, Papercut) legitimately speak plaintext with no TLS. */
215
+ function isLocalRelay(host: string): boolean {
216
+ const normalized = host.trim().toLowerCase();
217
+ return normalized === 'localhost' || normalized === '127.0.0.1' || normalized === '::1';
218
+ }
219
+
220
+ export interface ReconciledTls {
221
+ secure: boolean;
222
+ /** True when we refuse to send unless the connection is upgraded to TLS. */
223
+ requireTLS: boolean;
224
+ /** Set when the stored setting disagreed with the port and was overridden. */
225
+ correctedFrom?: boolean;
226
+ }
227
+
228
+ export function reconcileTlsForPort(
229
+ port: number,
230
+ configuredSecure: boolean,
231
+ host: string
232
+ ): ReconciledTls {
233
+ if (IMPLICIT_TLS_PORTS.has(port)) {
234
+ return {
235
+ secure: true,
236
+ requireTLS: false,
237
+ ...(configuredSecure ? {} : { correctedFrom: configuredSecure }),
238
+ };
239
+ }
240
+
241
+ if (STARTTLS_PORTS.has(port)) {
242
+ return {
243
+ secure: false,
244
+ // Opportunistic STARTTLS would silently send credentials in the clear against a
245
+ // relay that stopped advertising it. Demand the upgrade — every hosted provider
246
+ // on these ports supports it; only a local test relay might not.
247
+ requireTLS: !isLocalRelay(host),
248
+ ...(configuredSecure ? { correctedFrom: configuredSecure } : {}),
249
+ };
250
+ }
251
+
252
+ // A non-standard port carries no convention, so the operator's choice stands.
253
+ return { secure: configuredSecure, requireTLS: false };
254
+ }
255
+
256
+ /**
257
+ * Resolve the full SMTP transport config, DB-first with an env fallback. Uses the
258
+ * service-role client so it works from any context (the secret row is ADMIN-only under
259
+ * RLS). Returns null when host/user/pass/from cannot be resolved from either source.
260
+ *
261
+ * Memoized for CONFIG_CACHE_TTL_MS; pass `silent` when "not configured" is an expected
262
+ * answer (UI gating) rather than a misconfiguration worth warning about.
263
+ */
264
+ export async function resolveEmailServerConfig(
265
+ options: { silent?: boolean } = {},
266
+ ): Promise<ResolvedEmailConfig | null> {
267
+ const cached = configCache;
268
+ if (cached && cached.expiresAt > Date.now()) {
269
+ return cached.value;
270
+ }
271
+
272
+ let pub: EmailPublicSettings = DEFAULT_EMAIL_PUBLIC_SETTINGS;
273
+ let secret: Record<string, unknown> = {};
274
+
275
+ try {
276
+ const supabase = getServiceRoleSupabaseClient();
277
+ const [{ data: publicData }, { data: secretData }] = await Promise.all([
278
+ supabase.from('site_settings').select('value').eq('key', EMAIL_PUBLIC_KEY).maybeSingle(),
279
+ supabase.from('site_settings').select('value').eq('key', EMAIL_SECRET_KEY).maybeSingle(),
280
+ ]);
281
+ pub = normalizePublic(publicData?.value);
282
+ secret = (secretData?.value ?? {}) as Record<string, unknown>;
283
+ } catch {
284
+ // No service-role key (unconfigured instance) — fall through to env-only resolution.
285
+ }
286
+
287
+ const host = resolveConfigValue(pub.host, 'SMTP_HOST');
288
+ const port = resolveConfigValue(pub.port, 'SMTP_PORT');
289
+ const fromEmail = resolveConfigValue(pub.fromEmail, 'SMTP_FROM_EMAIL');
290
+ const fromName = resolveConfigValue(pub.fromName, 'SMTP_FROM_NAME');
291
+ const user = resolveConfigValue(tryDecryptWithEnvKey(secret['user']), 'SMTP_USER');
292
+ const pass = resolveConfigValue(tryDecryptWithEnvKey(secret['pass']), 'SMTP_PASS');
293
+
294
+ if (!host || !port || !user || !pass || !fromEmail) {
295
+ if (!options.silent) {
296
+ console.warn('Email is not configured (CMS or SMTP_* env). Outbound email will not be sent.');
297
+ }
298
+ configCache = { value: null, expiresAt: Date.now() + CONFIG_CACHE_TTL_MS };
299
+ return null;
300
+ }
301
+
302
+ const portNumber = Number(port);
303
+ // The CMS toggle defaults to ON, so a host entered with port 587 or 2525 lands in a
304
+ // combination that can never connect. Reconcile against the port before building the
305
+ // transport rather than letting it fail at handshake time.
306
+ const tls = reconcileTlsForPort(portNumber, pub.host ? pub.secure : portNumber === 465, host);
307
+ if (tls.correctedFrom !== undefined) {
308
+ console.warn(
309
+ `[email] Port ${portNumber} requires TLS mode "${tls.secure ? 'implicit' : 'STARTTLS'}"; ` +
310
+ `the saved setting said the opposite and was overridden. Update it in CMS Settings → Email.`
311
+ );
312
+ }
313
+ const resolved: ResolvedEmailConfig = {
314
+ host,
315
+ port: portNumber,
316
+ secure: tls.secure,
317
+ requireTLS: tls.requireTLS,
318
+ auth: { user, pass },
319
+ from: fromName ? `"${fromName}" <${fromEmail}>` : fromEmail,
320
+ };
321
+ configCache = { value: resolved, expiresAt: Date.now() + CONFIG_CACHE_TTL_MS };
322
+ return resolved;
323
+ }
@@ -0,0 +1,57 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { reconcileTlsForPort } from './email-settings';
4
+
5
+ /**
6
+ * The TLS mode is a property of the SMTP port, not a preference — and getting it wrong
7
+ * produces "ssl3_get_record:wrong version number", which mentions neither TLS nor ports.
8
+ * A real install hit exactly that: SMTP2GO on 2525 with the toggle left at its default
9
+ * of ON. These tests pin the reconciliation that makes the combination unreachable.
10
+ */
11
+
12
+ describe('reconcileTlsForPort', () => {
13
+ it('forces implicit TLS on 465 even when the setting says otherwise', () => {
14
+ const result = reconcileTlsForPort(465, false, 'smtp.example.com');
15
+ expect(result.secure).toBe(true);
16
+ expect(result.requireTLS).toBe(false);
17
+ expect(result.correctedFrom).toBe(false);
18
+ });
19
+
20
+ it('leaves a correct 465 configuration untouched', () => {
21
+ const result = reconcileTlsForPort(465, true, 'smtp.example.com');
22
+ expect(result.secure).toBe(true);
23
+ expect(result.correctedFrom).toBeUndefined();
24
+ });
25
+
26
+ it.each([25, 587, 2525])('forces STARTTLS on port %i', (port) => {
27
+ const result = reconcileTlsForPort(port, true, 'mail.smtp2go.com');
28
+ expect(result.secure).toBe(false);
29
+ // Downgrading to plaintext would be worse than the bug being fixed.
30
+ expect(result.requireTLS).toBe(true);
31
+ expect(result.correctedFrom).toBe(true);
32
+ });
33
+
34
+ it('reproduces the reported failure: SMTP2GO on 2525 with the toggle left on', () => {
35
+ const result = reconcileTlsForPort(2525, true, 'mail.smtp2go.com');
36
+ expect(result.secure).toBe(false);
37
+ expect(result.correctedFrom).toBe(true);
38
+ });
39
+
40
+ it('does not demand STARTTLS from a local test relay', () => {
41
+ for (const host of ['localhost', '127.0.0.1', '::1', 'LocalHost']) {
42
+ expect(reconcileTlsForPort(587, false, host).requireTLS).toBe(false);
43
+ }
44
+ });
45
+
46
+ it('honours the operator on a non-standard port, either way', () => {
47
+ expect(reconcileTlsForPort(1025, false, 'localhost')).toMatchObject({
48
+ secure: false,
49
+ requireTLS: false,
50
+ });
51
+ expect(reconcileTlsForPort(2526, true, 'smtp.example.com')).toMatchObject({
52
+ secure: true,
53
+ requireTLS: false,
54
+ });
55
+ expect(reconcileTlsForPort(2526, true, 'smtp.example.com').correctedFrom).toBeUndefined();
56
+ });
57
+ });