create-nextblock 0.17.0 → 0.17.2

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.
@@ -1,323 +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
- /** 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
- }
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 every 15 minutes). 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
+ }
@@ -13,8 +13,9 @@
13
13
  *
14
14
  * WHY THE ROW TYPE IS HAND-WRITTEN. `libs/db`'s generated `Database` type is
15
15
  * produced by `npm run db:types` against a live Supabase project. The migration
16
- * that creates `cms_redirects` (00000000000030_seo_redirects_and_robots.sql) is
17
- * committed but has not been applied yet, so the generated type does not contain
16
+ * that created `cms_redirects` (originally 00000000000030_seo_redirects_and_robots.sql,
17
+ * now part of 02001_baseline_schema.sql) was
18
+ * committed before it was applied, so the generated type did not contain
18
19
  * the table and `Database['public']['Tables']['cms_redirects']` would not compile.
19
20
  * Writing the row shape by hand from the migration's DDL keeps this file building
20
21
  * today; once the migration is applied and the types are regenerated, this