mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
04d134755a
- GET /api/addons/atlas/flights folds the user's flight bookings into routes, airports and totals for the globe's arcs (#1369, #2642). - GET /api/addons/atlas/people answers the Atlas side of other travellers on the instance: counts, visited countries and earned badges, never trips, places or dates. A user hides themselves with the atlas_hidden setting; the admin switch atlas_compare_enabled turns it off for all. - shared/src/atlas/atlas-badges.ts holds the badge rules, computed from the data a user already has, so nothing is stored. - MCP: list_atlas_flight_routes, list_atlas_badges, list_atlas_travellers.
289 lines
17 KiB
TypeScript
289 lines
17 KiB
TypeScript
import { readEnv } from '../../app-config';
|
|
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
|
|
import { encrypt_api_key, maybe_encrypt_api_key } from './crypto/apiKeyCrypto';
|
|
import { DomainError } from './domain-error';
|
|
import { aiPolicySchema, mailIngestImapTlsSchema, mailIngestTransportSettingSchema } from '@trek/shared';
|
|
|
|
import { z } from 'zod';
|
|
|
|
/**
|
|
* The instance-wide settings (`app_settings`) the server reads by name, in one
|
|
* typed register.
|
|
*
|
|
* Every entry says what the stored text means (`schema`), what a reader takes
|
|
* when the row is missing (`default`), which environment variable wins over it
|
|
* (`env`), and how it is handled: part of the admin settings form (`adminForm`,
|
|
* in the form's order), answered masked to that form (`masked`), stored
|
|
* encrypted (`encrypted`), held by the operator on a managed install
|
|
* (`managedLocked`), read for the public app config (`publicConfig`).
|
|
*
|
|
* The key lists that used to be typed out by hand (the admin form's keys, its
|
|
* masked and encrypted ones, the public config's reads) are derived from here,
|
|
* and code outside this module names a setting through {@link readAppSetting} or
|
|
* {@link resolveAppSetting}, whose key is checked against the register: ESLint
|
|
* refuses a literal `appSettings.getValue('...')` anywhere else.
|
|
*
|
|
* Stored values are text, as they have always been. A reader that needs a
|
|
* boolean or a number still converts at its own site, the way it did before;
|
|
* the register only fixes the name and documents the meaning.
|
|
*/
|
|
|
|
/** `'true'`/`'false'`; most readers take anything but `'false'` as on. */
|
|
const flag = z.enum(['true', 'false']);
|
|
const text = z.string();
|
|
/** A whole number written as text. */
|
|
const intText = z.string().regex(/^\d+$/);
|
|
|
|
type Env = ReturnType<typeof readEnv>;
|
|
|
|
export interface AppSettingDef {
|
|
readonly schema: z.ZodType<string>;
|
|
/** What the readers take for a missing row (documentation; each reader applies it itself). */
|
|
readonly default: string | null;
|
|
/** The environment value that wins over the stored one when it is non-empty. */
|
|
readonly env?: (env: Env) => string | null | undefined;
|
|
readonly adminForm?: true;
|
|
readonly masked?: true;
|
|
/** `always`: encrypted on every write. `if-plain`: encrypted unless it already is. Read back with `decrypt_api_key`. */
|
|
readonly encrypted?: 'always' | 'if-plain';
|
|
readonly managedLocked?: true;
|
|
readonly publicConfig?: true;
|
|
/** The admin save refuses a value the schema does not take, with the schema's own message, instead of storing it. */
|
|
readonly validated?: true;
|
|
}
|
|
|
|
// The admin form's keys come first, in the order the form has always answered them.
|
|
export const APP_SETTINGS = {
|
|
allow_registration: { schema: flag, default: 'true', adminForm: true },
|
|
allowed_file_types: { schema: text, default: null, adminForm: true },
|
|
require_mfa: { schema: flag, default: 'false', adminForm: true, publicConfig: true },
|
|
smtp_host: {
|
|
schema: text,
|
|
default: null,
|
|
env: (e) => e.smtp.host,
|
|
adminForm: true,
|
|
managedLocked: true,
|
|
publicConfig: true,
|
|
},
|
|
smtp_port: { schema: intText, default: null, env: (e) => e.smtp.port, adminForm: true, managedLocked: true },
|
|
smtp_user: { schema: text, default: null, env: (e) => e.smtp.user, adminForm: true, managedLocked: true },
|
|
smtp_pass: {
|
|
schema: text,
|
|
default: null,
|
|
env: (e) => e.smtp.pass,
|
|
adminForm: true,
|
|
masked: true,
|
|
encrypted: 'always',
|
|
managedLocked: true,
|
|
},
|
|
smtp_from: { schema: text, default: null, env: (e) => e.smtp.from, adminForm: true, managedLocked: true },
|
|
smtp_skip_tls_verify: { schema: flag, default: 'false', adminForm: true, managedLocked: true },
|
|
notification_channels: { schema: text, default: null, adminForm: true, publicConfig: true },
|
|
admin_webhook_url: { schema: text, default: null, adminForm: true, masked: true, encrypted: 'if-plain' },
|
|
admin_ntfy_server: { schema: text, default: null, adminForm: true },
|
|
admin_ntfy_topic: { schema: text, default: null, adminForm: true },
|
|
admin_ntfy_token: { schema: text, default: null, adminForm: true, masked: true, encrypted: 'if-plain' },
|
|
notify_trip_reminder: { schema: flag, default: 'true', adminForm: true, publicConfig: true },
|
|
password_login: { schema: flag, default: 'true', adminForm: true },
|
|
password_registration: { schema: flag, default: 'true', adminForm: true },
|
|
oidc_login: { schema: flag, default: 'true', adminForm: true, managedLocked: true },
|
|
oidc_registration: { schema: flag, default: 'true', adminForm: true, managedLocked: true },
|
|
// Whether an instance without password login sends a visitor straight to the
|
|
// identity provider. Off shows the login page with its SSO button first (#2925).
|
|
oidc_auto_redirect: { schema: flag, default: 'true', adminForm: true, publicConfig: true, managedLocked: true },
|
|
passkey_login: { schema: flag, default: 'false', adminForm: true },
|
|
webauthn_rp_id: { schema: text, default: null, adminForm: true, managedLocked: true },
|
|
webauthn_origins: { schema: text, default: null, adminForm: true, managedLocked: true },
|
|
// 'auto' (what every install had before Amap existed), 'google', 'amap' or
|
|
// 'openstreetmap'; the maps domain validates it (isPlacesProviderChoice).
|
|
places_provider: { schema: text, default: 'auto', adminForm: true, publicConfig: true, managedLocked: true },
|
|
// Live flight status from the keyless ADS-B feeds (flight-live). On by default; FLIGHT_LIVE_ENABLED wins over it.
|
|
flight_live_enabled: { schema: flag, default: 'true', env: (e) => e.integrations.flightLiveEnabled, adminForm: true },
|
|
// Whether the Atlas compares travellers of this instance (ranking, overlays). On by default;
|
|
// off, GET /api/addons/atlas/people answers nobody and the client hides the ranking.
|
|
atlas_compare_enabled: { schema: flag, default: 'true', adminForm: true, publicConfig: true },
|
|
|
|
// Read by name elsewhere.
|
|
oidc_issuer: { schema: text, default: null, env: (e) => e.oidc.issuer, publicConfig: true },
|
|
oidc_client_id: { schema: text, default: null, env: (e) => e.oidc.clientId, publicConfig: true },
|
|
oidc_client_secret: { schema: text, default: null, env: (e) => e.oidc.clientSecret, encrypted: 'if-plain' },
|
|
oidc_display_name: { schema: text, default: 'SSO', env: (e) => e.oidc.displayName, publicConfig: true },
|
|
oidc_discovery_url: { schema: text, default: null, env: (e) => e.oidc.discoveryUrl },
|
|
/** The legacy single switch, read only while none of the four login toggles has a row. */
|
|
oidc_only: { schema: flag, default: 'false' },
|
|
notification_channel: { schema: text, default: 'none', publicConfig: true },
|
|
notify_todo_due: { schema: flag, default: 'true' },
|
|
places_photos_enabled: { schema: flag, default: 'true', publicConfig: true },
|
|
places_autocomplete_enabled: { schema: flag, default: 'true', publicConfig: true },
|
|
places_details_enabled: { schema: flag, default: 'true', publicConfig: true },
|
|
places_enrich_enabled: { schema: flag, default: 'true', publicConfig: true },
|
|
place_shadow_enabled: { schema: flag, default: 'false', publicConfig: true },
|
|
bag_tracking_enabled: { schema: flag, default: 'false' },
|
|
// Off until an admin allows it: every user's wanderer calls go out to an address of their choosing.
|
|
tours_wanderer_enabled: { schema: flag, default: 'false' },
|
|
// MAP-01: OpenHikingMap as a base map of the Tours planner. On, since its tiles are free for
|
|
// the installs TREK is made for; an admin whose install is commercial or larger switches it off
|
|
// until there is an agreement with the operator (openmaps.fr/tile-usage-policy.html).
|
|
tours_hiking_map_enabled: { schema: flag, default: 'true' },
|
|
// BIK-06: CyclOSM as a base map of a bike tour in the Tours planner, on the same terms: its
|
|
// tiles are OpenStreetMap France's, free for moderate use with a Referer; a heavy or commercial
|
|
// install switches it off (or reaches an agreement) under the operator's usage policy.
|
|
tours_cycle_map_enabled: { schema: flag, default: 'true' },
|
|
// The piste router for ski tours, on wherever TREK Places is: it only downloads the ski areas a
|
|
// planner plans in, and no clicked point leaves the server. The switch is the operator's way out.
|
|
ski_routing_enabled: { schema: flag, default: 'true' },
|
|
route_usage_enabled: { schema: flag, default: 'false' },
|
|
// PAD-11C: how TREK gets the water data of a place a paddler plans in (auto, ask, off) and the largest extract it loads by itself.
|
|
paddle_auto_load: { schema: z.enum(['auto', 'ask', 'off']), default: 'auto' },
|
|
paddle_auto_max_mb: { schema: intText, default: '500' },
|
|
airtrail_sync_enabled: { schema: flag, default: 'true' },
|
|
airtrail_poll_interval_minutes: { schema: intText, default: null },
|
|
dawarich_poll_interval_minutes: { schema: intText, default: null },
|
|
/** The release the admins were last notified about (the version-check job's memory). */
|
|
last_notified_version: { schema: text, default: null },
|
|
// The trip assistant: whose connection it runs on, how many turns a day a
|
|
// user may take on the instance's, and how long chats are kept (the JSON of
|
|
// aiRetentionSchema). The admin sets them through /api/admin/ai/settings.
|
|
ai_assistant_policy: { schema: aiPolicySchema, default: 'instance_or_user' },
|
|
ai_assistant_daily_turns: { schema: intText, default: '50' },
|
|
ai_assistant_retention: { schema: text, default: '{"mode":"days","days":90}' },
|
|
/** Whether the assistant may search the web through its provider's own search, where the provider has one. */
|
|
ai_assistant_web_search: { schema: flag, default: 'true' },
|
|
/** `urn:uuid:<uuid>`: this install as one host to Sign in with ChatGPT, created on the first sign-in. */
|
|
ai_siwc_host_id: { schema: text, default: null },
|
|
// Community enrichment of place details (place-contrib). The installation's decision as the
|
|
// JSON of placeContribConsentSchema, off until an admin agrees; per admin, when their
|
|
// "not now" ends; why sending waits although an admin agreed (a refused key, a pause
|
|
// the service asked for); and how far the catch-up of values typed before the agreement
|
|
// got. None is the operator's to set on a managed install.
|
|
places_contribute: { schema: text, default: null },
|
|
places_contribute_snooze: { schema: text, default: null },
|
|
places_contribute_pause: { schema: text, default: null },
|
|
places_contribute_backfill: { schema: text, default: null },
|
|
/** This installation's key towards the liketrek services, issued on first use (service-identity). */
|
|
service_key: { schema: text, default: null, encrypted: 'always', managedLocked: true },
|
|
/** The key's bookkeeping as JSON: when to renew, when to ask again after a refusal, a revocation. */
|
|
service_key_state: { schema: text, default: null },
|
|
/** When every Synology photo was asked again for its own capture data (#3019); set once. */
|
|
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), 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',
|
|
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, adminForm: true, managedLocked: true },
|
|
/** The key the webhook's sender signs every mail with (HMAC-SHA256). */
|
|
mail_ingest_webhook_secret: {
|
|
// As MAIL_INGEST_WEBHOOK_SECRET: a short secret's HMAC can be guessed. Empty switches the webhook off.
|
|
schema: z.union([z.literal(''), z.string().min(32, 'The webhook secret needs at least 32 characters')]),
|
|
default: null,
|
|
adminForm: true,
|
|
masked: true,
|
|
encrypted: 'always',
|
|
managedLocked: true,
|
|
validated: true,
|
|
},
|
|
/** How many forwarded mails a day an AI reads for one person. */
|
|
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;
|
|
|
|
const ENTRIES = Object.entries(APP_SETTINGS) as Array<[AppSettingKey, AppSettingDef]>;
|
|
const keysWhere = (pick: (def: AppSettingDef) => unknown): AppSettingKey[] =>
|
|
ENTRIES.filter(([, def]) => pick(def)).map(([key]) => key);
|
|
|
|
/** The admin settings form's keys, in the order its answer has always listed them. */
|
|
export const ADMIN_FORM_SETTING_KEYS: readonly AppSettingKey[] = keysWhere((d) => d.adminForm);
|
|
/** The form's keys answered as `••••••••` rather than their value. */
|
|
export const MASKED_ADMIN_SETTING_KEYS: ReadonlySet<AppSettingKey> = new Set(keysWhere((d) => d.masked));
|
|
|
|
/** What the admin form shows for a stored secret, and takes back as "unchanged". */
|
|
export const ADMIN_SETTING_MASK = '••••••••';
|
|
|
|
/** True when the admin form sent a masked key back as its mask: the stored value stays. */
|
|
export function isMaskEcho(key: AppSettingKey, value: unknown): boolean {
|
|
return MASKED_ADMIN_SETTING_KEYS.has(key) && String(value) === ADMIN_SETTING_MASK;
|
|
}
|
|
|
|
/**
|
|
* The value an admin form key is stored as: checked against its schema where
|
|
* the registry asks for it (`validated`, a 400 naming what is wrong), and
|
|
* encrypted where it says so.
|
|
*/
|
|
export function storedAdminValue(key: AppSettingKey, value: string): string {
|
|
const def = APP_SETTINGS[key] as AppSettingDef;
|
|
if (def.validated) {
|
|
const checked = def.schema.safeParse(value);
|
|
if (!checked.success) throw new DomainError(400, checked.error.issues[0]?.message ?? `${key} is not valid`);
|
|
}
|
|
if (def.encrypted === 'always') return encrypt_api_key(value);
|
|
if (def.encrypted === 'if-plain' && value) return maybe_encrypt_api_key(value) ?? value;
|
|
return value;
|
|
}
|
|
/** The keys stored encrypted. */
|
|
export const ENCRYPTED_APP_SETTING_KEYS: ReadonlySet<AppSettingKey> = new Set(keysWhere((d) => d.encrypted));
|
|
/** The registered keys a managed install withholds from its admin (the rest of that list is user settings and profile columns). */
|
|
export const MANAGED_LOCKED_APP_SETTING_KEYS: readonly AppSettingKey[] = keysWhere((d) => d.managedLocked);
|
|
/** The keys the public app config reads, in one query. */
|
|
export const PUBLIC_CONFIG_SETTING_KEYS: readonly AppSettingKey[] = keysWhere((d) => d.publicConfig);
|
|
|
|
type AppSettingsReader = Pick<AppSettingsRepository, 'getValue'>;
|
|
|
|
/** The stored text of a registered setting, or null when it has no row: exactly what `getValue` answers. */
|
|
export function readAppSetting(repo: AppSettingsReader, key: AppSettingKey): Promise<string | null> {
|
|
return repo.getValue(key);
|
|
}
|
|
|
|
/**
|
|
* The environment value when it is set and non-empty, else the stored text
|
|
* (`env || stored`, the rule every env-over-settings reader has followed).
|
|
* A setting without an environment variable reads as {@link readAppSetting}.
|
|
*/
|
|
export async function resolveAppSetting(repo: AppSettingsReader, key: AppSettingKey): Promise<string | null> {
|
|
const def: AppSettingDef = APP_SETTINGS[key];
|
|
return def.env?.(readEnv()) || (await repo.getValue(key));
|
|
}
|
|
|
|
/**
|
|
* Whether sign-in through OIDC is set up: an issuer and a client id, each from
|
|
* the environment or the setting, an empty value counting as unset. The client
|
|
* secret is not asked for here: the login toggles, the public config and the
|
|
* lockout guard never did. Building the provider config (OidcService) needs it
|
|
* and checks it there.
|
|
*/
|
|
export async function isOidcConfigured(repo: AppSettingsReader): Promise<boolean> {
|
|
return !!((await resolveAppSetting(repo, 'oidc_issuer')) && (await resolveAppSetting(repo, 'oidc_client_id')));
|
|
}
|
|
|
|
/** {@link isOidcConfigured} over values already read in one batch (`AppSettingsRepository.getValues`). */
|
|
export function isOidcConfiguredIn(values: ReadonlyMap<string, string>): boolean {
|
|
const env = readEnv();
|
|
return !!((env.oidc.issuer || values.get('oidc_issuer')) && (env.oidc.clientId || values.get('oidc_client_id')));
|
|
}
|