@technomoron/mail-magic 1.0.42 → 1.0.43

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.
package/CHANGES CHANGED
@@ -1,12 +1,26 @@
1
1
  CHANGES
2
2
  =======
3
3
 
4
- Unreleased (2026-02-27)
5
-
6
- - chore(release): prepare release metadata for server package.
4
+ Version 1.0.43 (2026-03-04)
5
+
6
+ - fix(security): add allowlist for custom email headers on `/v1/tx/message` to prevent header injection via arbitrary keys (e.g. `Bcc`, `From`, `Sender`).
7
+ - fix(security): sanitize Swagger error response to avoid leaking internal filesystem paths.
8
+ - fix(security): reject `..` and `.` path segments explicitly in `normalizeSubdir`.
9
+ - fix(forms): return 500 error instead of silent success when all `form_key` generation attempts are exhausted.
10
+ - fix(mailer): guard `transport` with null check instead of non-null assertion; return 503 when transport is unavailable.
11
+ - fix(mailer): stop leaking internal error details (SMTP errors, file paths) in `/v1/tx/message` error responses.
12
+ - fix(autoreload): debounce `fs.watch` callback (300ms) to prevent reload storms from rapid file change events.
13
+ - refactor(form-replyto): replace duplicated `getFirstStringField` with shared `getBodyValue` from utils.
14
+ - docs(readme): fix `rcpt` example from JSON array to comma-separated string to match actual API contract.
15
+ - feat(locale): implement 3-step locale fallback for template lookup: request locale → domain default locale → empty locale.
16
+ - fix(auth): resolve default locale from domain record instead of hardcoding `'en'` when request omits `locale`.
17
+ - refactor(locale): remove `user.locale` from all locale resolution chains; domain locale is the sole default.
18
+ - docs(tutorial): replace non-existent `now().iso8601()` Nunjucks call with `default('unknown')`.
19
+ - test(autoreload): update store-autoreload tests to use fake timers for debounced reload.
7
20
  - perf(forms): batch recipient resolution for `_mm_recipients` into scoped + fallback `IN` queries while preserving precedence and requested order.
8
21
  - test(forms): add coverage for multi-recipient resolution order with scoped-over-domain recipient precedence.
9
22
  - (Changes generated/assisted by Codex (profile: openai-gpt-5-codex/medium).)
23
+ - (Changes generated/assisted by Claude Code (profile: anthropic-claude-opus-4-6/high).)
10
24
 
11
25
  Version 1.0.42 (2026-02-27)
12
26
 
package/README.md CHANGED
@@ -209,7 +209,7 @@ curl -X POST http://localhost:3776/api/v1/tx/message \
209
209
  "domain": "example.test",
210
210
  "name": "welcome",
211
211
  "locale": "en",
212
- "rcpt": ["person@example.test"],
212
+ "rcpt": "person@example.test",
213
213
  "vars": { "first_name": "Ada" }
214
214
  }'
215
215
  ```
@@ -47,9 +47,17 @@ export class AssetAPI extends ApiModule {
47
47
  }
48
48
  const templateType = templateTypeRaw.toLowerCase();
49
49
  const domainId = apireq.domain.domain_id;
50
+ const deflocale = apireq.domain.locale || '';
50
51
  if (templateType === 'tx') {
51
- const template = (await api_txmail.findOne({ where: { name: templateName, domain_id: domainId, locale } })) ||
52
- (await api_txmail.findOne({ where: { name: templateName, domain_id: domainId, locale: '' } }));
52
+ let template = await api_txmail.findOne({ where: { name: templateName, domain_id: domainId, locale } });
53
+ if (!template && deflocale && deflocale !== locale) {
54
+ template = await api_txmail.findOne({
55
+ where: { name: templateName, domain_id: domainId, locale: deflocale }
56
+ });
57
+ }
58
+ if (!template && locale !== '') {
59
+ template = await api_txmail.findOne({ where: { name: templateName, domain_id: domainId, locale: '' } });
60
+ }
53
61
  if (!template) {
54
62
  throw new ApiError({
55
63
  code: 404,
@@ -65,8 +73,15 @@ export class AssetAPI extends ApiModule {
65
73
  return path.dirname(candidate);
66
74
  }
67
75
  if (templateType === 'form') {
68
- const form = (await api_form.findOne({ where: { idname: templateName, domain_id: domainId, locale } })) ||
69
- (await api_form.findOne({ where: { idname: templateName, domain_id: domainId, locale: '' } }));
76
+ let form = await api_form.findOne({ where: { idname: templateName, domain_id: domainId, locale } });
77
+ if (!form && deflocale && deflocale !== locale) {
78
+ form = await api_form.findOne({
79
+ where: { idname: templateName, domain_id: domainId, locale: deflocale }
80
+ });
81
+ }
82
+ if (!form && locale !== '') {
83
+ form = await api_form.findOne({ where: { idname: templateName, domain_id: domainId, locale: '' } });
84
+ }
70
85
  if (!form) {
71
86
  throw new ApiError({
72
87
  code: 404,
@@ -36,5 +36,5 @@ export async function assert_domain_and_user(apireq) {
36
36
  }
37
37
  apireq.domain = dbdomain;
38
38
  apireq.user = user;
39
- apireq.locale = locale || 'en';
39
+ apireq.locale = locale || dbdomain.locale || '';
40
40
  }
@@ -89,6 +89,7 @@ export class FormAPI extends ApiModule {
89
89
  payload
90
90
  });
91
91
  let created = false;
92
+ let upserted = false;
92
93
  for (let attempt = 0; attempt < 10; attempt++) {
93
94
  try {
94
95
  const [form, wasCreated] = await api_form.upsert(record, {
@@ -96,6 +97,7 @@ export class FormAPI extends ApiModule {
96
97
  conflictFields: ['user_id', 'domain_id', 'locale', 'idname']
97
98
  });
98
99
  created = wasCreated ?? false;
100
+ upserted = true;
99
101
  form_key = form.form_key || form_key;
100
102
  this.server.storage.print_debug(`Form template upserted: ${form.idname} (created=${wasCreated})`);
101
103
  break;
@@ -115,6 +117,9 @@ export class FormAPI extends ApiModule {
115
117
  });
116
118
  }
117
119
  }
120
+ if (!upserted) {
121
+ throw new ApiError({ code: 500, message: 'Unable to generate a unique form_key after multiple attempts' });
122
+ }
118
123
  return [200, { Status: 'OK', created, form_key }];
119
124
  }
120
125
  async postSendForm(apireq) {
@@ -185,6 +190,9 @@ export class FormAPI extends ApiModule {
185
190
  ...(replyToValue ? { replyTo: replyToValue } : {})
186
191
  };
187
192
  try {
193
+ if (!this.server.storage.transport) {
194
+ throw new ApiError({ code: 503, message: 'Mail transport is not available' });
195
+ }
188
196
  const info = await this.server.storage.transport.sendMail(mailOptions);
189
197
  this.server.storage.print_debug('Email sent: ' + info.response);
190
198
  }
@@ -96,10 +96,18 @@ export class MailerAPI extends ApiModule {
96
96
  }
97
97
  let template = null;
98
98
  const domain_id = apireq.domain.domain_id;
99
+ const deflocale = apireq.domain.locale || '';
99
100
  try {
100
- template =
101
- (await api_txmail.findOne({ where: { name, domain_id, locale } })) ||
102
- (await api_txmail.findOne({ where: { name, domain_id, locale: '' } }));
101
+ // 1. Exact locale match
102
+ template = await api_txmail.findOne({ where: { name, domain_id, locale } });
103
+ // 2. Domain/user default locale (if different from request locale)
104
+ if (!template && deflocale && deflocale !== locale) {
105
+ template = await api_txmail.findOne({ where: { name, domain_id, locale: deflocale } });
106
+ }
107
+ // 3. Empty-locale fallback (if not already tried above)
108
+ if (!template && locale !== '') {
109
+ template = await api_txmail.findOne({ where: { name, domain_id, locale: '' } });
110
+ }
103
111
  }
104
112
  catch (error) {
105
113
  throw new ApiError({
@@ -145,6 +153,19 @@ export class MailerAPI extends ApiModule {
145
153
  throw new ApiError({ code: 400, message: 'Invalid reply-to email address' });
146
154
  }
147
155
  }
156
+ const ALLOWED_CUSTOM_HEADERS = new Set([
157
+ 'x-mailer',
158
+ 'x-priority',
159
+ 'x-entity-ref-id',
160
+ 'list-unsubscribe',
161
+ 'list-unsubscribe-post',
162
+ 'list-id',
163
+ 'precedence',
164
+ 'references',
165
+ 'in-reply-to',
166
+ 'message-id',
167
+ 'importance'
168
+ ]);
148
169
  let normalizedHeaders;
149
170
  if (headers !== undefined) {
150
171
  if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
@@ -155,6 +176,9 @@ export class MailerAPI extends ApiModule {
155
176
  if (typeof value !== 'string') {
156
177
  throw new ApiError({ code: 400, message: `headers.${key} must be a string` });
157
178
  }
179
+ if (!ALLOWED_CUSTOM_HEADERS.has(key.toLowerCase())) {
180
+ throw new ApiError({ code: 400, message: `Header "${key}" is not allowed` });
181
+ }
158
182
  normalizedHeaders[key] = value;
159
183
  }
160
184
  }
@@ -181,14 +205,20 @@ export class MailerAPI extends ApiModule {
181
205
  ...(normalizedReplyTo ? { replyTo: normalizedReplyTo } : {}),
182
206
  ...(normalizedHeaders ? { headers: normalizedHeaders } : {})
183
207
  };
208
+ if (!this.server.storage.transport) {
209
+ throw new ApiError({ code: 503, message: 'Mail transport is not available' });
210
+ }
184
211
  await this.server.storage.transport.sendMail(sendargs);
185
212
  }
186
213
  return [200, { Status: 'OK', Message: 'Emails sent successfully' }];
187
214
  }
188
215
  catch (error) {
216
+ if (error instanceof ApiError) {
217
+ throw error;
218
+ }
189
219
  throw new ApiError({
190
220
  code: 500,
191
- message: error instanceof Error ? error.message : String(error)
221
+ message: 'Failed to render or send email'
192
222
  });
193
223
  }
194
224
  }
@@ -231,12 +231,11 @@ export async function init_api_form(api_db) {
231
231
  return api_form;
232
232
  }
233
233
  export async function upsert_form(record) {
234
- const { user, domain } = await user_and_domain(record.domain_id);
234
+ const { domain } = await user_and_domain(record.domain_id);
235
235
  const dname = normalizeSlug(domain.name);
236
236
  const { slug, filename: generatedFilename } = buildFormSlugAndFilename({
237
237
  domainName: domain.name,
238
238
  domainLocale: domain.locale,
239
- userLocale: user.locale,
240
239
  idname: record.idname,
241
240
  locale: record.locale
242
241
  });
@@ -67,12 +67,12 @@ async function _load_template(store, filename, pathname, user, domain, locale, t
67
67
  }
68
68
  export async function loadFormTemplate(store, form) {
69
69
  const { user, domain } = await user_and_domain(form.domain_id);
70
- const locale = form.locale || domain.locale || user.locale || null;
70
+ const locale = form.locale || domain.locale || null;
71
71
  return _load_template(store, form.filename, '', user, domain, locale, 'form-template');
72
72
  }
73
73
  export async function loadTxTemplate(store, template) {
74
74
  const { user, domain } = await user_and_domain(template.domain_id);
75
- const locale = template.locale || domain.locale || user.locale || null;
75
+ const locale = template.locale || domain.locale || null;
76
76
  return _load_template(store, template.filename, '', user, domain, locale, 'tx-template');
77
77
  }
78
78
  export async function importData(store) {
@@ -29,10 +29,10 @@ export const api_txmail_schema = z
29
29
  export class api_txmail extends Model {
30
30
  }
31
31
  export async function upsert_txmail(record) {
32
- const { user, domain } = await user_and_domain(record.domain_id);
32
+ const { domain } = await user_and_domain(record.domain_id);
33
33
  const dname = normalizeSlug(domain.name);
34
34
  const name = normalizeSlug(record.name);
35
- const locale = normalizeSlug(record.locale || domain.locale || user.locale || '');
35
+ const locale = normalizeSlug(record.locale || domain.locale || '');
36
36
  if (!record.slug) {
37
37
  record.slug = `${dname}${locale ? '-' + locale : ''}-${name}`;
38
38
  }
@@ -157,10 +157,10 @@ export async function init_api_txmail(api_db) {
157
157
  ]
158
158
  });
159
159
  api_txmail.addHook('beforeValidate', async (template) => {
160
- const { user, domain } = await user_and_domain(template.domain_id);
160
+ const { domain } = await user_and_domain(template.domain_id);
161
161
  const dname = normalizeSlug(domain.name);
162
162
  const name = normalizeSlug(template.name);
163
- const locale = normalizeSlug(template.locale || domain.locale || user.locale || '');
163
+ const locale = normalizeSlug(template.locale || domain.locale || '');
164
164
  template.slug ||= `${dname}${locale ? '-' + locale : ''}-${name}`;
165
165
  if (!template.filename) {
166
166
  const parts = [dname, 'tx-template'];
@@ -10,7 +10,7 @@ export const api_user_schema = z
10
10
  name: z.string().min(1).describe('Display name for the user.'),
11
11
  email: z.string().email().describe('User email address.'),
12
12
  domain: z.number().int().nonnegative().nullable().optional().describe('Default domain ID for the user.'),
13
- locale: z.string().default('').describe('Default locale for the user.')
13
+ locale: z.string().default('').describe('Reserved. Locale resolution uses the domain locale.')
14
14
  })
15
15
  .describe('User account record and API credentials.');
16
16
  export class api_user extends Model {
@@ -30,14 +30,21 @@ export function enableInitDataAutoReload(ctx, reload) {
30
30
  }
31
31
  const initDataPath = ctx.config_filename('init-data.json');
32
32
  ctx.print_debug('Enabling auto reload of init-data.json');
33
+ let debounceTimer = null;
33
34
  const onChange = () => {
34
- ctx.print_debug('Config file changed, reloading...');
35
- try {
36
- reload();
37
- }
38
- catch (err) {
39
- ctx.print_debug(`Failed to reload config: ${err}`);
35
+ if (debounceTimer) {
36
+ clearTimeout(debounceTimer);
40
37
  }
38
+ debounceTimer = setTimeout(() => {
39
+ debounceTimer = null;
40
+ ctx.print_debug('Config file changed, reloading...');
41
+ try {
42
+ reload();
43
+ }
44
+ catch (err) {
45
+ ctx.print_debug(`Failed to reload config: ${err}`);
46
+ }
47
+ }, 300);
41
48
  };
42
49
  try {
43
50
  const watcher = fs.watch(initDataPath, { persistent: false }, onChange);
@@ -54,8 +54,8 @@ function loadPackagedOpenApiSpec() {
54
54
  cachedSpec = JSON.parse(raw);
55
55
  return cachedSpec;
56
56
  }
57
- catch (err) {
58
- cachedSpecError = err instanceof Error ? err.message : String(err);
57
+ catch {
58
+ cachedSpecError = 'Failed to load OpenAPI spec';
59
59
  return null;
60
60
  }
61
61
  }
@@ -1,14 +1,5 @@
1
1
  import emailAddresses from 'email-addresses';
2
- function getFirstStringField(body, key) {
3
- const value = body[key];
4
- if (Array.isArray(value) && value.length > 0) {
5
- return String(value[0] ?? '');
6
- }
7
- if (value !== undefined && value !== null) {
8
- return String(value);
9
- }
10
- return '';
11
- }
2
+ import { getBodyValue } from './utils.js';
12
3
  function sanitizeHeaderValue(value, maxLen) {
13
4
  const trimmed = String(value ?? '').trim();
14
5
  if (!trimmed) {
@@ -21,7 +12,7 @@ function sanitizeHeaderValue(value, maxLen) {
21
12
  return trimmed.slice(0, maxLen);
22
13
  }
23
14
  export function extractReplyToFromSubmission(body) {
24
- const emailRaw = sanitizeHeaderValue(getFirstStringField(body, 'email'), 320);
15
+ const emailRaw = sanitizeHeaderValue(getBodyValue(body, 'email'), 320);
25
16
  if (!emailRaw) {
26
17
  return undefined;
27
18
  }
@@ -34,10 +25,10 @@ export function extractReplyToFromSubmission(body) {
34
25
  return undefined;
35
26
  }
36
27
  // Prefer a single "name" field, otherwise compose from first_name/last_name.
37
- let name = sanitizeHeaderValue(getFirstStringField(body, 'name'), 200);
28
+ let name = sanitizeHeaderValue(getBodyValue(body, 'name'), 200);
38
29
  if (!name) {
39
- const first = sanitizeHeaderValue(getFirstStringField(body, 'first_name'), 100);
40
- const last = sanitizeHeaderValue(getFirstStringField(body, 'last_name'), 100);
30
+ const first = sanitizeHeaderValue(getBodyValue(body, 'first_name'), 100);
31
+ const last = sanitizeHeaderValue(getBodyValue(body, 'last_name'), 100);
41
32
  name = sanitizeHeaderValue(`${first}${first && last ? ' ' : ''}${last}`, 200);
42
33
  }
43
34
  return name ? { name, address } : address;
@@ -301,7 +301,6 @@ export function buildFormTemplatePaths(params) {
301
301
  return buildFormSlugAndFilename({
302
302
  domainName: params.domain.name,
303
303
  domainLocale: params.domain.locale,
304
- userLocale: params.user.locale,
305
304
  idname: params.idname,
306
305
  locale: params.locale
307
306
  });
@@ -4,7 +4,6 @@ export declare function assertSafeRelativePath(filename: string, label: string):
4
4
  export declare function buildFormSlugAndFilename(params: {
5
5
  domainName: string;
6
6
  domainLocale: string;
7
- userLocale: string;
8
7
  idname: string;
9
8
  locale: string;
10
9
  }): {
@@ -12,6 +12,9 @@ export function normalizeSubdir(value) {
12
12
  }
13
13
  const segments = cleaned.split('/').filter(Boolean);
14
14
  for (const segment of segments) {
15
+ if (segment === '..' || segment === '.') {
16
+ throw new ApiError({ code: 400, message: `Invalid path segment "${segment}"` });
17
+ }
15
18
  if (!SEGMENT_PATTERN.test(segment)) {
16
19
  throw new ApiError({ code: 400, message: `Invalid path segment "${segment}"` });
17
20
  }
@@ -31,7 +34,7 @@ export function assertSafeRelativePath(filename, label) {
31
34
  export function buildFormSlugAndFilename(params) {
32
35
  const domainSlug = normalizeSlug(params.domainName);
33
36
  const formSlug = normalizeSlug(params.idname);
34
- const localeSlug = normalizeSlug(params.locale || params.domainLocale || params.userLocale || '');
37
+ const localeSlug = normalizeSlug(params.locale || params.domainLocale || '');
35
38
  const slug = `${domainSlug}${localeSlug ? '-' + localeSlug : ''}-${formSlug}`;
36
39
  const filenameParts = [domainSlug, 'form-template'];
37
40
  if (localeSlug) {
package/docs/tutorial.md CHANGED
@@ -264,7 +264,7 @@ Create `${CONFIG_ROOT}/init-data.json` so the service can bootstrap the MyOrg us
264
264
  <tr>
265
265
  <td style="padding:16px 24px;background:#f9fafb;color:#4b5563;font-size:12px;">
266
266
  <strong>Sender IP:</strong> {{ _meta_.client_ip | default('unknown') }} ·
267
- <strong>Received at:</strong> {{ _meta_.received_at | default(now().iso8601()) }}
267
+ <strong>Received at:</strong> {{ _meta_.received_at | default('unknown') }}
268
268
  </td>
269
269
  </tr>
270
270
  {% endif %}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@technomoron/mail-magic",
3
- "version": "1.0.42",
3
+ "version": "1.0.43",
4
4
  "main": "dist/cjs/index.js",
5
5
  "module": "dist/esm/index.js",
6
6
  "type": "module",