@basicbenframework/cms 0.9.0 → 0.10.0

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 (50) hide show
  1. package/lib/client/components/Nav/DesktopNav.js +3 -1
  2. package/lib/client/components/Nav/MobileNav.js +3 -1
  3. package/lib/client/components/admin/ConfigField.d.ts +34 -0
  4. package/lib/client/components/admin/ConfigField.js +26 -0
  5. package/lib/client/hooks/useRegistrationOpen.d.ts +1 -0
  6. package/lib/client/hooks/useRegistrationOpen.js +31 -0
  7. package/lib/client/host/index.d.ts +5 -0
  8. package/lib/client/i18n/locales/es/site.js +40 -0
  9. package/lib/client/pages/Auth.js +3 -1
  10. package/lib/client/pages/admin/Health.js +5 -1
  11. package/lib/client/pages/admin/Settings.js +41 -4
  12. package/lib/client/styles.css +9 -0
  13. package/lib/controllers/AuthController.js +2 -1
  14. package/lib/controllers/EmailVerificationController.js +2 -1
  15. package/lib/controllers/HealthController.js +15 -5
  16. package/lib/controllers/MediaController.js +5 -5
  17. package/lib/controllers/PasskeyController.js +2 -1
  18. package/lib/controllers/PasswordResetController.js +2 -1
  19. package/lib/controllers/SettingsController.d.ts +0 -8
  20. package/lib/controllers/SettingsController.js +72 -20
  21. package/lib/controllers/TwoFactorController.js +2 -1
  22. package/lib/controllers/UserController.js +1 -1
  23. package/lib/features/analytics/controller.js +2 -1
  24. package/lib/features/mysendbox/MySendboxSettingsCard.d.ts +1 -1
  25. package/lib/features/mysendbox/MySendboxSettingsCard.js +15 -5
  26. package/lib/features/mysendbox/config.d.ts +10 -7
  27. package/lib/features/mysendbox/config.js +17 -10
  28. package/lib/features/mysendbox/i18n/es.js +6 -1
  29. package/lib/helpers/config.d.ts +77 -0
  30. package/lib/helpers/config.js +158 -0
  31. package/lib/helpers/export-data.js +1 -1
  32. package/lib/helpers/health.js +4 -4
  33. package/lib/helpers/images.js +2 -1
  34. package/lib/helpers/secrets.d.ts +18 -0
  35. package/lib/helpers/secrets.js +52 -0
  36. package/lib/helpers/site-settings.d.ts +6 -0
  37. package/lib/helpers/site-settings.js +34 -1
  38. package/lib/helpers/site.d.ts +2 -2
  39. package/lib/helpers/site.js +4 -3
  40. package/lib/helpers/storage.d.ts +16 -0
  41. package/lib/helpers/storage.js +58 -0
  42. package/lib/hooks.js +11 -0
  43. package/lib/host/cron.js +5 -0
  44. package/lib/models/Page.js +1 -1
  45. package/lib/models/Post.js +1 -1
  46. package/lib/models/PublicContent.js +2 -1
  47. package/lib/models/Settings.d.ts +1 -1
  48. package/lib/models/Settings.js +4 -2
  49. package/lib/models/User.js +1 -1
  50. package/package.json +1 -1
@@ -27,6 +27,7 @@ import { TwoFactor } from "../models/TwoFactor.js";
27
27
  import { Credential } from "../models/Credential.js";
28
28
  import { emailSendLimiter } from "../middleware/rate-limits.js";
29
29
  import { issueSessionToken, revokeSessions } from "../helpers/session.js";
30
+ import { siteName } from "../helpers/config.js";
30
31
  const appUrl = () => process.env.APP_URL || 'http://localhost:3000';
31
32
  const RESET_TTL = 60 * 60 * 1000; // 1 hour
32
33
  /** The one answer the request endpoint gives, whoever asks. */
@@ -51,7 +52,7 @@ async function sendResetEmail(user) {
51
52
  subject: 'Reset your password',
52
53
  ...renderMail('password-reset', {
53
54
  name: user.name,
54
- siteName: process.env.SITE_NAME || 'BasicBen',
55
+ siteName: siteName(),
55
56
  resetUrl
56
57
  })
57
58
  });
@@ -1,12 +1,4 @@
1
1
  import type { Request, Response } from '../types/index.ts';
2
- /**
3
- * Site settings.
4
- *
5
- * Every write goes through `validateSettings`, which knows each key the site
6
- * uses and what it accepts (see helpers/site-settings.ts). The routes require
7
- * `settings.manage`, which only the admin role holds — that matters most for
8
- * code injection, which is raw HTML the front end renders unsanitised.
9
- */
10
2
  export declare const SettingsController: {
11
3
  index(req: Request, res: Response): Promise<void>;
12
4
  byGroup(req: Request, res: Response): Promise<void>;
@@ -1,6 +1,9 @@
1
1
  import { Settings } from "../models/Settings.js";
2
- import { validateSettings, isKnownSetting } from "../helpers/site-settings.js";
2
+ import { validateSettings, isKnownSetting, isSecretDefinition } from "../helpers/site-settings.js";
3
3
  import { siteUrl } from "../helpers/site.js";
4
+ import { describeConfig, lockedBy, refreshConfig, registrationOpen } from "../helpers/config.js";
5
+ import { encryptSecret } from "../helpers/secrets.js";
6
+ import { isSecretSetting } from "../helpers/export-data.js";
4
7
  /**
5
8
  * Site settings.
6
9
  *
@@ -8,25 +11,70 @@ import { siteUrl } from "../helpers/site.js";
8
11
  * uses and what it accepts (see helpers/site-settings.ts). The routes require
9
12
  * `settings.manage`, which only the admin role holds — that matters most for
10
13
  * code injection, which is raw HTML the front end renders unsanitised.
14
+ *
15
+ * Some settings are configuration the environment can also set (storage, the
16
+ * site URL, mail keys: see helpers/config.ts). Where the variable is set it
17
+ * wins, and a save leaves that setting alone. Secret settings are encrypted
18
+ * before they are stored and are never sent back: reads report them as '' and
19
+ * list which are set under `secrets`. A blank secret on save keeps the stored
20
+ * one; DELETE /api/settings/:key clears it.
21
+ */
22
+ const isSecret = (key) => isSecretDefinition(key) || isSecretSetting(key);
23
+ /** Settings with every secret blanked, and which secrets are set. */
24
+ function redact(settings) {
25
+ const secrets = {};
26
+ const visible = {};
27
+ for (const [key, value] of Object.entries(settings)) {
28
+ if (isSecret(key)) {
29
+ secrets[key] = value !== '';
30
+ visible[key] = '';
31
+ }
32
+ else {
33
+ visible[key] = value;
34
+ }
35
+ }
36
+ return { settings: visible, secrets };
37
+ }
38
+ /**
39
+ * Write validated settings. Locked ones (the environment sets them) are
40
+ * skipped and reported; a blank secret keeps the stored value.
11
41
  */
42
+ async function writeSettings(values) {
43
+ const skipped = {};
44
+ for (const [key, { value, group }] of Object.entries(values)) {
45
+ const env = lockedBy(key);
46
+ if (env) {
47
+ skipped[key] = env;
48
+ continue;
49
+ }
50
+ // Secrets are never sent to the admin, so a form saves them back blank:
51
+ // blank means unchanged. Only declared secrets are encrypted; a feature's
52
+ // key that merely looks secret is stored as the feature reads it.
53
+ if (isSecret(key) && value.trim() === '')
54
+ continue;
55
+ await Settings.set(key, isSecretDefinition(key) ? encryptSecret(value.trim()) : value, group);
56
+ }
57
+ await refreshConfig({ force: true });
58
+ return skipped;
59
+ }
12
60
  export const SettingsController = {
13
61
  async index(req, res) {
14
- const settings = await Settings.asObject();
15
- // The site URL is configuration (SITE_URL), not a setting: it is shown so
16
- // the admin can see what feeds and the sitemap link to, and it is never
17
- // writable from here — a URL that can be changed from a form is one stolen
18
- // admin session away from pointing every feed reader somewhere else.
19
- res.json({ settings, site_url: siteUrl(req) });
62
+ const { settings, secrets } = redact(await Settings.asObject());
63
+ // `config` says, for each value the environment can also set, where the
64
+ // one in use comes from — so the admin can show which fields are locked.
65
+ res.json({ settings, secrets, site_url: siteUrl(req), config: describeConfig() });
20
66
  },
21
67
  async byGroup(req, res) {
22
- const settings = await Settings.asObject(req.params.group);
23
- res.json({ settings });
68
+ const { settings, secrets } = redact(await Settings.asObject(req.params.group));
69
+ res.json({ settings, secrets });
24
70
  },
25
71
  async get(req, res) {
26
72
  const value = await Settings.get(req.params.key);
27
73
  if (value === null) {
28
74
  return res.json({ error: 'Setting not found' }, 404);
29
75
  }
76
+ if (isSecret(req.params.key))
77
+ return res.json({ key: req.params.key, value: '', set: true });
30
78
  res.json({ key: req.params.key, value });
31
79
  },
32
80
  async update(req, res) {
@@ -34,11 +82,9 @@ export const SettingsController = {
34
82
  const result = validateSettings(settings);
35
83
  if ('errors' in result)
36
84
  return res.json({ errors: result.errors }, 422);
37
- for (const [key, { value, group }] of Object.entries(result.values)) {
38
- await Settings.set(key, value, group);
39
- }
40
- const updated = await Settings.asObject();
41
- res.json({ settings: updated });
85
+ const skipped = await writeSettings(result.values);
86
+ const updated = redact(await Settings.asObject());
87
+ res.json({ ...updated, skipped, config: describeConfig() });
42
88
  },
43
89
  async set(req, res) {
44
90
  const { value } = req.body;
@@ -51,9 +97,14 @@ export const SettingsController = {
51
97
  const result = validateSettings({ [req.params.key]: value });
52
98
  if ('errors' in result)
53
99
  return res.json({ errors: result.errors }, 422);
100
+ // One setting, named on purpose: a locked one is an error, not a skip.
101
+ const env = lockedBy(req.params.key);
102
+ if (env) {
103
+ return res.json({ errors: { [req.params.key]: [`Set by ${env} in the environment`] } }, 422);
104
+ }
54
105
  const stored = result.values[req.params.key];
55
- await Settings.set(req.params.key, stored.value, stored.group);
56
- res.json({ key: req.params.key, value: stored.value });
106
+ await writeSettings({ [req.params.key]: stored });
107
+ res.json({ key: req.params.key, value: isSecretDefinition(req.params.key) ? '' : stored.value });
57
108
  },
58
109
  async delete(req, res) {
59
110
  // Deleting an unknown key is harmless, but refusing it keeps the API
@@ -63,6 +114,7 @@ export const SettingsController = {
63
114
  return res.json({ errors: { [req.params.key]: ['Unknown setting'] } }, 422);
64
115
  }
65
116
  await Settings.delete(req.params.key);
117
+ await refreshConfig({ force: true });
66
118
  res.json({ message: 'Setting deleted' });
67
119
  },
68
120
  /**
@@ -82,7 +134,9 @@ export const SettingsController = {
82
134
  const siteDescription = await Settings.getSiteDescription();
83
135
  res.json({
84
136
  site_name: siteName,
85
- site_description: siteDescription
137
+ site_description: siteDescription,
138
+ // For the sign-up links: DISABLE_REGISTRATION or the setting.
139
+ registration_open: registrationOpen()
86
140
  });
87
141
  },
88
142
  async updateSiteInfo(req, res) {
@@ -94,9 +148,7 @@ export const SettingsController = {
94
148
  });
95
149
  if ('errors' in result)
96
150
  return res.json({ errors: result.errors }, 422);
97
- for (const [key, { value, group }] of Object.entries(result.values)) {
98
- await Settings.set(key, value, group);
99
- }
151
+ await writeSettings(result.values);
100
152
  res.json({
101
153
  site_name: await Settings.getSiteName(),
102
154
  site_description: await Settings.getSiteDescription()
@@ -7,10 +7,11 @@ import { generateRecoveryCodes, hashRecoveryCodes, findRecoveryCode, lockoutStat
7
7
  import { User } from "../models/User.js";
8
8
  import { verifyPasskeyAssertion } from "./PasskeyController.js";
9
9
  import { TwoFactor } from "../models/TwoFactor.js";
10
+ import { siteName } from "../helpers/config.js";
10
11
  // A challenge is the only thing standing between a correct password and a
11
12
  // session, so it is short-lived and single use.
12
13
  const CHALLENGE_TTL = 5 * 60 * 1000;
13
- const issuer = () => process.env.SITE_NAME || 'BasicBen';
14
+ const issuer = () => siteName();
14
15
  /**
15
16
  * Start the second step of a login.
16
17
  *
@@ -27,8 +27,8 @@ import { getDb } from '@basicbenframework/core/db';
27
27
  import { User } from "../models/User.js";
28
28
  import { paginationFrom, meta } from "../models/pagination.js";
29
29
  import { issueSessionToken, revokeSessions } from "../helpers/session.js";
30
+ import { siteName } from "../helpers/config.js";
30
31
  const appUrl = () => process.env.APP_URL || 'http://localhost:3000';
31
- const siteName = () => process.env.SITE_NAME || 'BasicBen';
32
32
  /**
33
33
  * The auth_tokens kind for an invitation.
34
34
  *
@@ -1,6 +1,7 @@
1
1
  import { clientIp } from "../../middleware/rate-limits.js";
2
2
  import { normalizeAnalyticsPath, referrerDomain, hostOf, isBot, optedOut, parseHitBody } from "./helpers.js";
3
3
  import { recordHit, summary, analyticsSettings, purgeOpportunistically } from "./model.js";
4
+ import { configValue } from "../../helpers/config.js";
4
5
  /** The ranges the admin offers. Anything else is refused, not clamped. */
5
6
  const RANGES = [7, 30, 90];
6
7
  /** 204 with nothing to cache: a hit is never a resource. */
@@ -37,7 +38,7 @@ export const AnalyticsController = {
37
38
  if (!settings.enabled)
38
39
  return accepted(res);
39
40
  const ownHosts = [
40
- hostOf(process.env.SITE_URL),
41
+ hostOf(configValue('SITE_URL')),
41
42
  hostOf(process.env.APP_URL),
42
43
  hostOf(req.headers.origin),
43
44
  hostOf(body.path)
@@ -4,4 +4,4 @@ import type { SettingsSectionProps } from '../../client/host/index.ts';
4
4
  * copies the members who aren't yet. Saved with the rest of Settings, except
5
5
  * the copy, which runs at once.
6
6
  */
7
- export default function MySendboxSettingsCard({ values, onChange }: SettingsSectionProps): import("react").JSX.Element | null;
7
+ export default function MySendboxSettingsCard({ values, onChange, config, secrets }: SettingsSectionProps): import("react").JSX.Element | null;
@@ -1,23 +1,33 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useState } from 'react';
3
3
  import { api } from "../../helpers/api.js";
4
4
  import { useT } from "../../client/i18n/index.js";
5
+ import { ConfigField } from "../../client/components/admin/ConfigField.js";
5
6
  const hint = { color: 'var(--fg-muted)', fontSize: '0.875rem', marginTop: '0.25rem' };
6
7
  /**
7
8
  * MySendbox: where newsletters go, who is copied there, and the button that
8
9
  * copies the members who aren't yet. Saved with the rest of Settings, except
9
10
  * the copy, which runs at once.
10
11
  */
11
- export default function MySendboxSettingsCard({ values, onChange }) {
12
+ export default function MySendboxSettingsCard({ values, onChange, config = [], secrets = {} }) {
12
13
  const { t } = useT();
13
14
  const [status, setStatus] = useState(null);
14
15
  const [copying, setCopying] = useState(false);
15
16
  const [message, setMessage] = useState('');
16
17
  const load = () => api.get('/api/mysendbox/status').then(setStatus).catch(() => setStatus(null));
17
18
  useEffect(() => { load(); }, []);
18
- // Not set up, or not someone who manages members: say nothing.
19
- if (!status?.configured)
19
+ // The key and URL, which can also come from MYSENDBOX_API_KEY and
20
+ // MYSENDBOX_API_URL. Shown before the feature is configured, since this is
21
+ // where it gets configured.
22
+ const statusOf = (setting) => config.find((entry) => entry.setting === setting);
23
+ const connection = (_jsxs(_Fragment, { children: [_jsx(ConfigField, { name: "mysendbox_api_key", label: t('MySendbox API key'), value: values.mysendbox_api_key ?? '', onChange: (value) => onChange({ mysendbox_api_key: value }), status: statusOf('mysendbox_api_key'), saved: secrets.mysendbox_api_key, help: t('A key with the contacts and broadcasts scopes. Stored encrypted with APP_KEY and never shown again.') }), _jsx(ConfigField, { name: "mysendbox_api_url", label: t('MySendbox API URL'), value: values.mysendbox_api_url ?? '', onChange: (value) => onChange({ mysendbox_api_url: value }), status: statusOf('mysendbox_api_url'), help: t('Blank for MySendbox itself.') })] }));
24
+ // Not set up yet: just the connection. Not someone who manages members
25
+ // (no status at all): nothing.
26
+ if (!status)
20
27
  return null;
28
+ if (!status.configured) {
29
+ return (_jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Newsletters through MySendbox') }), _jsx("p", { style: hint, children: t('Add an API key to send newsletters to members through MySendbox. Save, then reload this page.') }), connection] }));
30
+ }
21
31
  const copy = async () => {
22
32
  setCopying(true);
23
33
  setMessage('');
@@ -44,5 +54,5 @@ export default function MySendboxSettingsCard({ values, onChange }) {
44
54
  const field = (key, label, help, type = 'text') => (_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: key, children: label }), type === 'textarea' ? (_jsx("textarea", { id: key, rows: 3, value: values[key] ?? '', onChange: e => onChange({ [key]: e.target.value }), className: "admin-input" })) : (_jsx("input", { id: key, type: type, value: values[key] ?? '', onChange: e => onChange({ [key]: e.target.value }), className: "admin-input" })), _jsx("p", { style: hint, children: help })] }));
45
55
  return (_jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Newsletters through MySendbox') }), _jsxs("p", { style: hint, children: [t('{synced} member(s) in MySendbox, {waiting} waiting for consent, {refused} refused.', {
46
56
  synced: c.synced ?? 0, waiting: c.needs_consent ?? 0, refused: c.refused ?? 0
47
- }), ' ', status.sendable !== null && t('A broadcast would reach {count} now.', { count: status.sendable }), !status.webhook && _jsxs(_Fragment, { children: [" ", t('No webhook secret: unsubscribes made in MySendbox arrive through the daily check.')] })] }), status.error && _jsx("p", { style: { ...hint, color: 'var(--danger, #b00)' }, children: status.error }), field('mysendbox_from_address', t('From address'), t("Blank uses your MySendbox workspace's default sender."), 'email'), field('mysendbox_from_name', t('From name'), t('Blank uses the newsletter sender name.')), field('mysendbox_consent_attestation', t('Consent for members you added or imported'), t('How they agreed to receive posts by email, in your words. MySendbox records it with each contact. Leave blank and they are not copied, unless a signup form is set.'), 'textarea'), field('mysendbox_form_id', t('Signup form (frm_…)'), t('Optional. Members without recorded consent are sent this form’s confirmation email instead.')), field('mysendbox_audience_id', t('Audience (aud_…)'), t('Made for you on first use. Change it only to use another MySendbox list.')), _jsxs("div", { className: "admin-form-group", children: [_jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", disabled: copying, onClick: copy, children: copying ? t('Copying…') : t('Copy members to MySendbox') }), _jsx("p", { style: hint, children: message || t('Copies every subscribed member not yet in MySendbox. Safe to run again. Save settings first if you changed consent.') })] }), status.problems.length > 0 && (_jsxs("details", { children: [_jsx("summary", { children: t('Members not copied ({count})', { count: status.problems.length }) }), _jsx("ul", { style: hint, children: status.problems.map(p => _jsxs("li", { children: ["#", p.member_id, " \u2014 ", p.last_error || p.state] }, p.member_id)) })] }))] }));
57
+ }), ' ', status.sendable !== null && t('A broadcast would reach {count} now.', { count: status.sendable }), !status.webhook && _jsxs(_Fragment, { children: [" ", t('No webhook secret: unsubscribes made in MySendbox arrive through the daily check.')] })] }), status.error && _jsx("p", { style: { ...hint, color: 'var(--danger, #b00)' }, children: status.error }), connection, field('mysendbox_from_address', t('From address'), t("Blank uses your MySendbox workspace's default sender."), 'email'), field('mysendbox_from_name', t('From name'), t('Blank uses the newsletter sender name.')), field('mysendbox_consent_attestation', t('Consent for members you added or imported'), t('How they agreed to receive posts by email, in your words. MySendbox records it with each contact. Leave blank and they are not copied, unless a signup form is set.'), 'textarea'), field('mysendbox_form_id', t('Signup form (frm_…)'), t('Optional. Members without recorded consent are sent this form’s confirmation email instead.')), field('mysendbox_audience_id', t('Audience (aud_…)'), t('Made for you on first use. Change it only to use another MySendbox list.')), _jsxs("div", { className: "admin-form-group", children: [_jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", disabled: copying, onClick: copy, children: copying ? t('Copying…') : t('Copy members to MySendbox') }), _jsx("p", { style: hint, children: message || t('Copies every subscribed member not yet in MySendbox. Safe to run again. Save settings first if you changed consent.') })] }), status.problems.length > 0 && (_jsxs("details", { children: [_jsx("summary", { children: t('Members not copied ({count})', { count: status.problems.length }) }), _jsx("ul", { style: hint, children: status.problems.map(p => _jsxs("li", { children: ["#", p.member_id, " \u2014 ", p.last_error || p.state] }, p.member_id)) })] }))] }));
48
58
  }
@@ -1,12 +1,15 @@
1
1
  /**
2
- * How the feature finds MySendbox: environment for secrets, site settings for
3
- * everything an admin may choose.
2
+ * How the feature finds MySendbox: site settings for everything an admin may
3
+ * choose, with the environment winning where it is set (helpers/config.ts).
4
4
  *
5
- * - `MYSENDBOX_API_KEY`: a key with contacts and broadcasts scopes and no
6
- * domain or mailbox limits. Without it the feature does nothing at all.
7
- * - `MYSENDBOX_WEBHOOK_SECRET`: the `whsec_…` secret of the webhook pointed
8
- * at `/api/webhooks/mysendbox`. Without it that endpoint answers 404.
9
- * - `MYSENDBOX_API_URL`: only to point at another MySendbox, such as in tests.
5
+ * - `MYSENDBOX_API_KEY`, or the API key setting (stored encrypted): a key with
6
+ * contacts and broadcasts scopes and no domain or mailbox limits. Without it
7
+ * the feature does nothing at all.
8
+ * - `MYSENDBOX_API_URL`, or its setting: only to point at another MySendbox,
9
+ * such as in tests.
10
+ * - `MYSENDBOX_WEBHOOK_SECRET`: environment only, because it authenticates
11
+ * requests to this server. The `whsec_…` secret of the webhook pointed at
12
+ * `/api/webhooks/mysendbox`. Without it that endpoint answers 404.
10
13
  */
11
14
  import { type SettingDefinition } from '../../helpers/site-settings.ts';
12
15
  import { type ClientOptions, type MySendboxClient } from './client.ts';
@@ -1,15 +1,19 @@
1
1
  /**
2
- * How the feature finds MySendbox: environment for secrets, site settings for
3
- * everything an admin may choose.
2
+ * How the feature finds MySendbox: site settings for everything an admin may
3
+ * choose, with the environment winning where it is set (helpers/config.ts).
4
4
  *
5
- * - `MYSENDBOX_API_KEY`: a key with contacts and broadcasts scopes and no
6
- * domain or mailbox limits. Without it the feature does nothing at all.
7
- * - `MYSENDBOX_WEBHOOK_SECRET`: the `whsec_…` secret of the webhook pointed
8
- * at `/api/webhooks/mysendbox`. Without it that endpoint answers 404.
9
- * - `MYSENDBOX_API_URL`: only to point at another MySendbox, such as in tests.
5
+ * - `MYSENDBOX_API_KEY`, or the API key setting (stored encrypted): a key with
6
+ * contacts and broadcasts scopes and no domain or mailbox limits. Without it
7
+ * the feature does nothing at all.
8
+ * - `MYSENDBOX_API_URL`, or its setting: only to point at another MySendbox,
9
+ * such as in tests.
10
+ * - `MYSENDBOX_WEBHOOK_SECRET`: environment only, because it authenticates
11
+ * requests to this server. The `whsec_…` secret of the webhook pointed at
12
+ * `/api/webhooks/mysendbox`. Without it that endpoint answers 404.
10
13
  */
11
14
  import { Settings } from "../../models/Settings.js";
12
15
  import { checks } from "../../helpers/site-settings.js";
16
+ import { configValue } from "../../helpers/config.js";
13
17
  import { createClient } from "./client.js";
14
18
  export const SETTINGS = {
15
19
  // The audience (MySendbox list) this site's members are in. Made on first
@@ -23,10 +27,13 @@ export const SETTINGS = {
23
27
  mysendbox_consent_attestation: { group: 'mysendbox', check: checks.text(1000) },
24
28
  // A MySendbox signup form (`frm_…`). With one, an added or imported member
25
29
  // without an attestation gets its double opt-in mail instead.
26
- mysendbox_form_id: { group: 'mysendbox', check: checks.text(64) }
30
+ mysendbox_form_id: { group: 'mysendbox', check: checks.text(64) },
31
+ // MYSENDBOX_API_KEY and MYSENDBOX_API_URL win over these when set.
32
+ mysendbox_api_key: { group: 'mysendbox', check: checks.text(256), secret: true },
33
+ mysendbox_api_url: { group: 'mysendbox', check: checks.httpUrlOrBlank }
27
34
  };
28
35
  export function apiKey() {
29
- return process.env.MYSENDBOX_API_KEY?.trim() || '';
36
+ return configValue('MYSENDBOX_API_KEY');
30
37
  }
31
38
  export function webhookSecret() {
32
39
  return process.env.MYSENDBOX_WEBHOOK_SECRET?.trim() || '';
@@ -42,7 +49,7 @@ export function setClientOptions(next) {
42
49
  export function client() {
43
50
  return createClient({
44
51
  apiKey: apiKey(),
45
- ...(process.env.MYSENDBOX_API_URL ? { baseUrl: process.env.MYSENDBOX_API_URL } : {}),
52
+ ...(configValue('MYSENDBOX_API_URL') ? { baseUrl: configValue('MYSENDBOX_API_URL') } : {}),
46
53
  ...overrides
47
54
  });
48
55
  }
@@ -23,6 +23,11 @@ const strings = {
23
23
  "draft": "borrador",
24
24
  "scheduled": "programado",
25
25
  "paused": "en pausa",
26
- "canceled": "cancelado"
26
+ "canceled": "cancelado",
27
+ "MySendbox API key": "Clave de API de MySendbox",
28
+ "MySendbox API URL": "URL de la API de MySendbox",
29
+ "A key with the contacts and broadcasts scopes. Stored encrypted with APP_KEY and never shown again.": "Una clave con los permisos de contactos y envíos. Se guarda cifrada con APP_KEY y no se vuelve a mostrar.",
30
+ "Blank for MySendbox itself.": "En blanco para el propio MySendbox.",
31
+ "Add an API key to send newsletters to members through MySendbox. Save, then reload this page.": "Añade una clave de API para enviar boletines a los miembros a través de MySendbox. Guarda y vuelve a cargar esta página."
27
32
  };
28
33
  export default strings;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Configuration an admin may set from the Settings screen, with the
3
+ * environment taking priority.
4
+ *
5
+ * Each entry pairs an environment variable with a site setting. When the
6
+ * variable is set it wins and the setting is locked in the admin, so a
7
+ * deployment configured through its environment (every one before this)
8
+ * behaves exactly as it did. When it is not set, the setting is used.
9
+ *
10
+ * What stays environment-only, and why: the database connection (settings live
11
+ * in the database), APP_KEY (it signs sessions and encrypts the secrets here),
12
+ * CRON_SECRET and the webhook secrets (they authenticate requests to this
13
+ * server), and TRUST_PROXY, PORT and NODE_ENV (how the server runs). None of
14
+ * those should be one stolen admin session away from changing.
15
+ *
16
+ * Reads are synchronous, from a snapshot of the settings. `refreshConfig()`
17
+ * reloads it at most every 30 seconds per instance (on each request, through
18
+ * the `request.before` hook in src/hooks.ts) and at once after an admin saves.
19
+ * On a serverless platform another instance can therefore act on the old
20
+ * value for up to 30 seconds after a change.
21
+ *
22
+ * Secret settings are stored encrypted (helpers/secrets.ts), decrypted only
23
+ * into this snapshot, never sent to the browser, and left out of exports and
24
+ * backups by the secret-setting rule in helpers/export-data.ts.
25
+ */
26
+ export type ConfigGroup = 'site' | 'media' | 'storage' | 'mail';
27
+ export interface ConfigEntry {
28
+ /** The environment variable. It wins when set. */
29
+ env: string;
30
+ /** The site setting used when the variable is not set. */
31
+ setting: string;
32
+ label: string;
33
+ group: ConfigGroup;
34
+ /** Stored encrypted, never sent back to the admin. */
35
+ secret?: boolean;
36
+ /**
37
+ * Variables that, when any is set, put this entry under the environment
38
+ * even if its own variable is not. Storage is configured as a whole: a
39
+ * bucket from the environment with keys from settings would be two halves
40
+ * of two configurations.
41
+ */
42
+ lockedBy?: string[];
43
+ }
44
+ export declare const CONFIG: ConfigEntry[];
45
+ /** The environment variable that controls a setting right now, or null. */
46
+ export declare function lockedBy(setting: string, env?: NodeJS.ProcessEnv): string | null;
47
+ export declare function isSecretConfig(setting: string): boolean;
48
+ /** The value for an environment variable's name: the variable, else its setting, else ''. */
49
+ export declare function configValue(env: string): string;
50
+ export type ConfigSource = 'env' | 'settings' | 'unset' | 'unreadable';
51
+ export interface ConfigStatus {
52
+ env: string;
53
+ setting: string;
54
+ label: string;
55
+ group: ConfigGroup;
56
+ secret: boolean;
57
+ source: ConfigSource;
58
+ /** The variable that locks this setting, when one does. */
59
+ locked_by: string | null;
60
+ /** The value in use, for entries that are not secret. */
61
+ value: string | null;
62
+ }
63
+ /** Where each value comes from, for the admin. Never a secret's value. */
64
+ export declare function describeConfig(): ConfigStatus[];
65
+ /**
66
+ * Reload the snapshot when it is older than 30 seconds, or now with `force`.
67
+ * A failed read (no settings table yet, database down) keeps the old one.
68
+ */
69
+ export declare function refreshConfig({ force }?: {
70
+ force?: boolean | undefined;
71
+ }): Promise<void>;
72
+ /** For tests: replace the snapshot. */
73
+ export declare function setConfigSnapshot(values: Record<string, string>): void;
74
+ /** The site's name: SITE_NAME, else the Site Name setting, else `fallback`. */
75
+ export declare function siteName(fallback?: string): string;
76
+ /** False when DISABLE_REGISTRATION (or the setting) is 'true'. The first account can always register. */
77
+ export declare function registrationOpen(): boolean;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Configuration an admin may set from the Settings screen, with the
3
+ * environment taking priority.
4
+ *
5
+ * Each entry pairs an environment variable with a site setting. When the
6
+ * variable is set it wins and the setting is locked in the admin, so a
7
+ * deployment configured through its environment (every one before this)
8
+ * behaves exactly as it did. When it is not set, the setting is used.
9
+ *
10
+ * What stays environment-only, and why: the database connection (settings live
11
+ * in the database), APP_KEY (it signs sessions and encrypts the secrets here),
12
+ * CRON_SECRET and the webhook secrets (they authenticate requests to this
13
+ * server), and TRUST_PROXY, PORT and NODE_ENV (how the server runs). None of
14
+ * those should be one stolen admin session away from changing.
15
+ *
16
+ * Reads are synchronous, from a snapshot of the settings. `refreshConfig()`
17
+ * reloads it at most every 30 seconds per instance (on each request, through
18
+ * the `request.before` hook in src/hooks.ts) and at once after an admin saves.
19
+ * On a serverless platform another instance can therefore act on the old
20
+ * value for up to 30 seconds after a change.
21
+ *
22
+ * Secret settings are stored encrypted (helpers/secrets.ts), decrypted only
23
+ * into this snapshot, never sent to the browser, and left out of exports and
24
+ * backups by the secret-setting rule in helpers/export-data.ts.
25
+ */
26
+ import { getDb } from '@basicbenframework/core/db';
27
+ import { decryptSecret } from "./secrets.js";
28
+ const STORAGE_ENV = ['S3_BUCKET'];
29
+ export const CONFIG = [
30
+ { env: 'SITE_NAME', setting: 'site_name', label: 'Site name', group: 'site' },
31
+ { env: 'SITE_URL', setting: 'site_url', label: 'Site URL', group: 'site' },
32
+ { env: 'DISABLE_REGISTRATION', setting: 'disable_registration', label: 'Registration closed', group: 'site' },
33
+ { env: 'PUBLIC_THEME', setting: 'public_theme', label: 'Public theme', group: 'site' },
34
+ { env: 'IMAGE_TRANSFORM_URL', setting: 'image_transform_url', label: 'Image transform URL', group: 'media' },
35
+ { env: 'S3_BUCKET', setting: 'storage_bucket', label: 'Bucket', group: 'storage', lockedBy: STORAGE_ENV },
36
+ { env: 'S3_ENDPOINT', setting: 'storage_endpoint', label: 'Endpoint', group: 'storage', lockedBy: STORAGE_ENV },
37
+ { env: 'S3_REGION', setting: 'storage_region', label: 'Region', group: 'storage', lockedBy: STORAGE_ENV },
38
+ { env: 'S3_PUBLIC_URL', setting: 'storage_public_url', label: 'Public URL', group: 'storage', lockedBy: STORAGE_ENV },
39
+ { env: 'S3_ACCESS_KEY_ID', setting: 'storage_access_key_id', label: 'Access key ID', group: 'storage', secret: true, lockedBy: STORAGE_ENV },
40
+ { env: 'S3_SECRET_ACCESS_KEY', setting: 'storage_secret_access_key', label: 'Secret access key', group: 'storage', secret: true, lockedBy: STORAGE_ENV },
41
+ { env: 'MYSENDBOX_API_KEY', setting: 'mysendbox_api_key', label: 'MySendbox API key', group: 'mail', secret: true },
42
+ { env: 'MYSENDBOX_API_URL', setting: 'mysendbox_api_url', label: 'MySendbox API URL', group: 'mail' }
43
+ ];
44
+ const byEnv = new Map(CONFIG.map((entry) => [entry.env, entry]));
45
+ const bySetting = new Map(CONFIG.map((entry) => [entry.setting, entry]));
46
+ const TTL_MS = 30_000;
47
+ /** Setting values (secrets decrypted), and secrets that would not decrypt. */
48
+ let snapshot = {};
49
+ let unreadable = new Set();
50
+ let loadedAt = 0;
51
+ let loading = null;
52
+ const envValue = (name, env = process.env) => env[name]?.trim() || '';
53
+ /** The environment variable that controls a setting right now, or null. */
54
+ export function lockedBy(setting, env = process.env) {
55
+ const entry = bySetting.get(setting);
56
+ if (!entry)
57
+ return null;
58
+ if (envValue(entry.env, env))
59
+ return entry.env;
60
+ return entry.lockedBy?.find((name) => envValue(name, env)) ?? null;
61
+ }
62
+ export function isSecretConfig(setting) {
63
+ return Boolean(bySetting.get(setting)?.secret);
64
+ }
65
+ /** The value for an environment variable's name: the variable, else its setting, else ''. */
66
+ export function configValue(env) {
67
+ const entry = byEnv.get(env);
68
+ if (!entry)
69
+ return envValue(env);
70
+ const fromEnv = envValue(entry.env);
71
+ if (fromEnv)
72
+ return fromEnv;
73
+ if (lockedBy(entry.setting))
74
+ return '';
75
+ return snapshot[entry.setting]?.trim() || '';
76
+ }
77
+ /** Where each value comes from, for the admin. Never a secret's value. */
78
+ export function describeConfig() {
79
+ return CONFIG.map((entry) => {
80
+ const locked = lockedBy(entry.setting);
81
+ const value = configValue(entry.env);
82
+ let source = 'unset';
83
+ if (envValue(entry.env))
84
+ source = 'env';
85
+ else if (!locked && value)
86
+ source = 'settings';
87
+ else if (!locked && unreadable.has(entry.setting))
88
+ source = 'unreadable';
89
+ return {
90
+ env: entry.env,
91
+ setting: entry.setting,
92
+ label: entry.label,
93
+ group: entry.group,
94
+ secret: Boolean(entry.secret),
95
+ source,
96
+ locked_by: locked,
97
+ value: entry.secret ? null : value || null
98
+ };
99
+ });
100
+ }
101
+ /**
102
+ * Reload the snapshot when it is older than 30 seconds, or now with `force`.
103
+ * A failed read (no settings table yet, database down) keeps the old one.
104
+ */
105
+ export async function refreshConfig({ force = false } = {}) {
106
+ if (!force && loadedAt && Date.now() - loadedAt < TTL_MS)
107
+ return;
108
+ if (loading && !force)
109
+ return loading;
110
+ loading = (async () => {
111
+ try {
112
+ const keys = CONFIG.map((entry) => entry.setting);
113
+ const db = await getDb();
114
+ const rows = (await db.all(`SELECT key, value FROM settings WHERE key IN (${keys.map(() => '?').join(', ')})`, keys));
115
+ const next = {};
116
+ const failed = new Set();
117
+ for (const { key, value } of rows) {
118
+ if (!value)
119
+ continue;
120
+ if (isSecretConfig(key)) {
121
+ const plain = decryptSecret(value);
122
+ if (plain === null)
123
+ failed.add(key);
124
+ else
125
+ next[key] = plain;
126
+ }
127
+ else {
128
+ next[key] = value;
129
+ }
130
+ }
131
+ snapshot = next;
132
+ unreadable = failed;
133
+ loadedAt = Date.now();
134
+ }
135
+ catch {
136
+ // Keep what we had. Try again on the next request rather than after the TTL.
137
+ loadedAt = 0;
138
+ }
139
+ finally {
140
+ loading = null;
141
+ }
142
+ })();
143
+ return loading;
144
+ }
145
+ /** For tests: replace the snapshot. */
146
+ export function setConfigSnapshot(values) {
147
+ snapshot = { ...values };
148
+ unreadable = new Set();
149
+ loadedAt = Date.now();
150
+ }
151
+ /** The site's name: SITE_NAME, else the Site Name setting, else `fallback`. */
152
+ export function siteName(fallback = 'BasicBen') {
153
+ return configValue('SITE_NAME') || fallback;
154
+ }
155
+ /** False when DISABLE_REGISTRATION (or the setting) is 'true'. The first account can always register. */
156
+ export function registrationOpen() {
157
+ return configValue('DISABLE_REGISTRATION') !== 'true';
158
+ }
@@ -96,7 +96,7 @@ export const NEVER_EXPORTED = [
96
96
  * under `omitted.settings` — a false positive costs a setting re-entered by
97
97
  * hand, a false negative would put a key in a file.
98
98
  */
99
- const SECRET_SETTING = /(secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|smtp_pass)/i;
99
+ const SECRET_SETTING = /(secret|password|passwd|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|smtp_pass)/i;
100
100
  export function isSecretSetting(key) {
101
101
  return SECRET_SETTING.test(String(key ?? ''));
102
102
  }