feat(mail-ingest): the transport settings in the admin form, each overridable from the environment

The IMAP box, the webhook secret and the address template join the admin
settings form (masked, encrypted, held by the operator on a managed install),
and MAIL_INGEST_* variables override them through the mailIngestConfig token.
The audit row masks every masked key, and key rotation covers the new secrets.
This commit is contained in:
Maurice
2026-11-13 16:22:31 +01:00
parent f319b3610a
commit 7d3ed21a03
20 changed files with 406 additions and 20 deletions
+4 -2
View File
@@ -105,8 +105,10 @@ Every variable has exactly one owner, and the owner decides how it is read:
`app.get(httpConfig.KEY)` for the pre-init Express layer). Today:
`httpConfig` (TRUST_PROXY, HSTS_INCLUDE_SUBDOMAINS, HTTP_KEEP_ALIVE_TIMEOUT_MS),
`storageConfig` (TREK_PLACE_PHOTO_DIR), `transitConfig` (TRANSIT_API_URL,
for TransitService) and `kitineraryConfig` (KITINERARY_EXTRACTOR_PATH and
PATH, for KitineraryExtractorService's binary probe). A module whose provider
for TransitService), `kitineraryConfig` (KITINERARY_EXTRACTOR_PATH and
PATH, for KitineraryExtractorService's binary probe), `servicesConfig`
(TREK_SERVICES and its hosts) and `mailIngestConfig` (MAIL_INGEST_*, for
MailIngestSettingsService, each over its stored setting). A module whose provider
injects one imports `AppConfigModule`, so it also builds on its own in a test.
- **`readEnv()` / `RuntimeEnvService`** (`derive.ts`): everything else, both
the runtime-toggled values and the boot-stable ones that code outside a Nest
+22
View File
@@ -90,6 +90,27 @@ export function deriveServices(raw: RawEnv) {
};
}
/**
* How the booking mail import takes mail in, set in the environment rather
* than in the admin dialog: each value wins over its stored setting when it is
* non-empty (MailIngestSettingsService applies them). Unset leaves the dialog
* in charge, so an install that sets none of them behaves as before.
*/
export function deriveMailIngest(raw: RawEnv) {
const read = (value: string | undefined) => value?.trim() || null;
return {
transport: read(raw.MAIL_INGEST_TRANSPORT)?.toLowerCase() ?? null,
imapHost: read(raw.MAIL_INGEST_IMAP_HOST),
imapPort: read(raw.MAIL_INGEST_IMAP_PORT),
imapTls: read(raw.MAIL_INGEST_IMAP_TLS)?.toLowerCase() ?? null,
imapUser: read(raw.MAIL_INGEST_IMAP_USER),
imapPass: read(raw.MAIL_INGEST_IMAP_PASS),
imapMailbox: read(raw.MAIL_INGEST_IMAP_MAILBOX),
addressTemplate: read(raw.MAIL_INGEST_ADDRESS_TEMPLATE),
webhookSecret: read(raw.MAIL_INGEST_WEBHOOK_SECRET),
};
}
/** One entry per token: the namespace it registers under and the function it derives with. */
export const BOOT_DERIVERS = {
http: deriveHttpBoot,
@@ -97,6 +118,7 @@ export const BOOT_DERIVERS = {
transit: deriveTransit,
kitinerary: deriveKitinerary,
services: deriveServices,
mailIngest: deriveMailIngest,
} as const;
export type BootNamespace = keyof typeof BOOT_DERIVERS;
+14
View File
@@ -110,6 +110,20 @@ export const envSchema = z.object({
SMTP_FROM: anyString,
SMTP_SKIP_TLS_VERIFY: boolStr,
// Booking mail import: each wins over its field in the admin dialog
MAIL_INGEST_TRANSPORT: oneOf(['off', 'imap', 'webhook', 'cloud']),
MAIL_INGEST_IMAP_HOST: anyString,
MAIL_INGEST_IMAP_PORT: integer(1, 65535, 'must be a port number (1-65535)'),
MAIL_INGEST_IMAP_TLS: oneOf(['tls', 'starttls']),
MAIL_INGEST_IMAP_USER: anyString,
MAIL_INGEST_IMAP_PASS: anyString,
MAIL_INGEST_IMAP_MAILBOX: anyString,
MAIL_INGEST_ADDRESS_TEMPLATE: optionalWith(
(v) => v.includes('{token}') && v.includes('@'),
'must hold {token} and an @, like trek+{token}@example.com',
),
MAIL_INGEST_WEBHOOK_SECRET: optionalWith((v) => v.length >= 32, 'must be at least 32 characters'),
// WebAuthn
WEBAUTHN_RP_ID: anyString,
WEBAUTHN_ORIGINS: anyString,
+11 -1
View File
@@ -38,4 +38,14 @@ export const kitineraryConfig = registerAs('kitinerary', () => BOOT_DERIVERS.kit
*/
export const servicesConfig = registerAs('services', () => BOOT_DERIVERS.services(process.env));
export const BOOT_STABLE_TOKENS = [httpConfig, storageConfig, transitConfig, kitineraryConfig, servicesConfig];
/** How the booking mail import takes mail in (MAIL_INGEST_*), each value over its stored setting. */
export const mailIngestConfig = registerAs('mailIngest', () => BOOT_DERIVERS.mailIngest(process.env));
export const BOOT_STABLE_TOKENS = [
httpConfig,
storageConfig,
transitConfig,
kitineraryConfig,
servicesConfig,
mailIngestConfig,
];
+4 -2
View File
@@ -778,7 +778,8 @@ export class AuthService {
}
});
const changedKeys = ADMIN_FORM_SETTING_KEYS.filter(k => !blocked.includes(k) && body[k] !== undefined && !(k === 'smtp_pass' && String(body[k]) === '••••••••'));
// A masked key sent back as its mask was not changed, and a secret's value never reaches the audit row.
const changedKeys = ADMIN_FORM_SETTING_KEYS.filter(k => !blocked.includes(k) && body[k] !== undefined && !(MASKED_ADMIN_SETTING_KEYS.has(k) && String(body[k]) === '••••••••'));
const summary: Record<string, unknown> = {};
const smtpChanged = changedKeys.some(k => k.startsWith('smtp_'));
@@ -789,10 +790,11 @@ export class AuthService {
if (changedKeys.includes('allow_registration')) summary.allow_registration = body.allow_registration;
if (changedKeys.includes('allowed_file_types')) summary.allowed_file_types_updated = true;
if (changedKeys.includes('require_mfa')) summary.require_mfa = body.require_mfa;
if (changedKeys.some(k => k.startsWith('mail_ingest_'))) summary.mail_ingest_settings_updated = true;
const debugDetails: Record<string, unknown> = {};
for (const k of changedKeys) {
debugDetails[k] = k === 'smtp_pass' ? '***' : body[k];
debugDetails[k] = MASKED_ADMIN_SETTING_KEYS.has(k) ? '***' : body[k];
}
// The reminder crons read their enable gates and channels per tick, so a
@@ -1,6 +1,6 @@
import { readEnv } from '../../app-config';
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
import { aiPolicySchema, mailIngestTransportSettingSchema } from '@trek/shared';
import { aiPolicySchema, mailIngestImapTlsSchema, mailIngestTransportSettingSchema } from '@trek/shared';
import { z } from 'zod';
@@ -161,15 +161,46 @@ export const APP_SETTINGS = {
synology_capture_repair_3019: { schema: text, default: null },
/** How many starts have tried that so far, while some photo could not be confirmed. */
synology_capture_repair_3019_tries: { schema: intText, default: null },
// The booking mail import (mail-ingest). Off until switched on: on a self-hosted install by its
// admin, on a managed one by the operator, for the plans that include it and never for Start.
mail_ingest_enabled: { schema: flag, default: 'false' },
// The booking mail import (mail-ingest), set in its own admin dialog. Off until switched on: on a
// self-hosted install by its admin, on a managed one by the operator, for the plans that include
// it and never for Start, so every key is the operator's there. The MAIL_INGEST_* environment
// variables win over the stored transport keys; they belong to the mailIngestConfig token, so
// MailIngestSettingsService applies them rather than the `env` of an entry here.
mail_ingest_enabled: { schema: flag, default: 'false', adminForm: true, managedLocked: true },
/** How mail reaches the install: not at all (uploads only), IMAP, a signed webhook, or the TREK Cloud relay. */
mail_ingest_transport: { schema: mailIngestTransportSettingSchema, default: 'off' },
mail_ingest_transport: {
schema: mailIngestTransportSettingSchema,
default: 'off',
adminForm: true,
managedLocked: true,
},
mail_ingest_imap_host: { schema: text, default: null, adminForm: true, managedLocked: true },
mail_ingest_imap_port: { schema: intText, default: '993', adminForm: true, managedLocked: true },
mail_ingest_imap_tls: { schema: mailIngestImapTlsSchema, default: 'tls', adminForm: true, managedLocked: true },
mail_ingest_imap_user: { schema: text, default: null, adminForm: true, managedLocked: true },
mail_ingest_imap_pass: {
schema: text,
default: null,
adminForm: true,
masked: true,
encrypted: 'always',
managedLocked: true,
},
/** The folder the forwarded mails arrive in; read mails move on to TREK/processed. */
mail_ingest_imap_mailbox: { schema: text, default: 'INBOX', adminForm: true, managedLocked: true },
/** The forwarding address, `{token}` standing where a person's token goes: `trek+{token}@example.com`. */
mail_ingest_address_template: { schema: text, default: null },
mail_ingest_address_template: { schema: text, default: null, adminForm: true, managedLocked: true },
/** The key the webhook's sender signs every mail with (HMAC-SHA256). */
mail_ingest_webhook_secret: {
schema: text,
default: null,
adminForm: true,
masked: true,
encrypted: 'always',
managedLocked: true,
},
/** How many forwarded mails a day an AI reads for one person. */
mail_ingest_ai_per_user_daily: { schema: intText, default: '10' },
mail_ingest_ai_per_user_daily: { schema: intText, default: '10', adminForm: true, managedLocked: true },
} as const satisfies Record<string, AppSettingDef>;
export type AppSettingKey = keyof typeof APP_SETTINGS;
+13
View File
@@ -88,6 +88,19 @@ export const MANAGED_LOCKED_SETTING_KEYS = [
'llm_model',
'llm_multimodal',
'llm_provider',
// The booking mail import: whether a plan includes it is the operator's call (never on Start),
// and so is how mail reaches the install (the TREK Cloud relay) and the address it is sent to.
'mail_ingest_address_template',
'mail_ingest_ai_per_user_daily',
'mail_ingest_enabled',
'mail_ingest_imap_host',
'mail_ingest_imap_mailbox',
'mail_ingest_imap_pass',
'mail_ingest_imap_port',
'mail_ingest_imap_tls',
'mail_ingest_imap_user',
'mail_ingest_transport',
'mail_ingest_webhook_secret',
'mapbox_access_token',
'maps_api_key',
// Whether the login page waits or goes straight to the provider is part of the
@@ -1,13 +1,19 @@
import { MailIngestPrefs } from '../../db/entities/MailIngestPrefs.entity';
import type { MailIngestPrefsPatch, MailIngestPrefsRepository } from '../../db/repositories/MailIngestPrefs.repository';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { mailIngestConfig } from '../app-config/tokens';
import type { AppSettingKey } from '../common/app-settings.registry';
import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { DEFAULT_ALLOWED_EXTENSIONS } from '../files/files.constants';
import { SettingsService } from '../settings/settings.service';
import { MAIL_INGEST_LIMITS } from './mail-ingest.constants';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import {
mailIngestImapTlsSchema,
mailIngestTransportSettingSchema,
type MailIngestImapTls,
type MailIngestPrefs as MailIngestPrefsView,
type MailIngestPrefsUpdateRequest,
type MailIngestTransportSetting,
@@ -15,6 +21,17 @@ import {
/** The daily AI cap when the setting is missing or unreadable. */
const DEFAULT_AI_PER_USER_DAILY = 10;
const DEFAULT_IMAP_MAILBOX = 'INBOX';
/** The IMAP box the import reads, complete: a box without a host, a user or a password is no box. */
export interface MailIngestImapConfig {
host: string;
port: number;
tls: MailIngestImapTls;
user: string;
pass: string;
mailbox: string;
}
/**
* Whether the mail import runs on this install, how mail reaches it, and the
@@ -24,12 +41,16 @@ const DEFAULT_AI_PER_USER_DAILY = 10;
* install that setting is the operator's: it is written for the plans that
* include the import and never for Start, so on Start every surface reports
* the import as unavailable and nothing is read.
*
* The transport's values come from the admin dialog, each overridden by its
* MAIL_INGEST_* variable where that is set (the mailIngestConfig token).
*/
@Injectable()
export class MailIngestSettingsService {
constructor(
private readonly settings: SettingsService,
private readonly env: RuntimeEnvService,
@Inject(mailIngestConfig.KEY) private readonly config: ConfigType<typeof mailIngestConfig>,
@InjectRepository(MailIngestPrefs) private readonly prefs: MailIngestPrefsRepository,
) {}
@@ -40,17 +61,43 @@ export class MailIngestSettingsService {
/** How mail reaches the install; a managed one takes it from the TREK Cloud relay alone. */
async transport(): Promise<MailIngestTransportSetting> {
if (this.env.isManaged()) return 'cloud';
const stored = await this.settings.getAppSetting('mail_ingest_transport');
const parsed = mailIngestTransportSettingSchema.safeParse(stored);
const parsed = mailIngestTransportSettingSchema.safeParse(
await this.pick(this.config.transport, 'mail_ingest_transport'),
);
return parsed.success ? parsed.data : 'off';
}
/** The forwarding address with `{token}` where a person's token goes; null until an admin set one. */
async addressTemplate(): Promise<string | null> {
const template = (await this.settings.getAppSetting('mail_ingest_address_template'))?.trim();
const template = await this.pick(this.config.addressTemplate, 'mail_ingest_address_template');
return template && template.includes('{token}') ? template : null;
}
/** The IMAP box to read; null while its host, user or password is missing. */
async imapConfig(): Promise<MailIngestImapConfig | null> {
const host = await this.pick(this.config.imapHost, 'mail_ingest_imap_host');
const user = await this.pick(this.config.imapUser, 'mail_ingest_imap_user');
const pass = this.config.imapPass ?? decrypt_api_key(await this.settings.getAppSetting('mail_ingest_imap_pass'));
if (!host || !user || !pass) return null;
const tls = mailIngestImapTlsSchema.catch('tls').parse(await this.pick(this.config.imapTls, 'mail_ingest_imap_tls'));
const port = Number(await this.pick(this.config.imapPort, 'mail_ingest_imap_port'));
const mailbox = await this.pick(this.config.imapMailbox, 'mail_ingest_imap_mailbox');
return {
host,
port: Number.isInteger(port) && port > 0 && port <= 65535 ? port : defaultImapPort(tls),
tls,
user,
pass,
mailbox: mailbox ?? DEFAULT_IMAP_MAILBOX,
};
}
/** The key a webhook sender signs its mails with; while none is set, the webhook takes no mail. */
async webhookSecret(): Promise<string | null> {
const stored = await this.settings.getAppSetting('mail_ingest_webhook_secret');
return this.config.webhookSecret ?? (decrypt_api_key(stored) || null);
}
async aiDailyCap(): Promise<number> {
const value = Number(await this.settings.getAppSetting('mail_ingest_ai_per_user_daily'));
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_AI_PER_USER_DAILY;
@@ -84,4 +131,13 @@ export class MailIngestSettingsService {
await this.prefs.upsertForUser(userId, patch);
return this.prefsOf(userId);
}
/** The environment's value where it is set, else the stored one; blank reads as unset. */
private async pick(override: string | null, key: AppSettingKey): Promise<string | null> {
return (override ?? (await this.settings.getAppSetting(key)))?.trim() || null;
}
}
function defaultImapPort(tls: MailIngestImapTls): number {
return tls === 'tls' ? 993 : 143;
}