Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Fixed

- **Email can be set up in Settings with the stock docker-compose.yml, and unlocks when `SMTP_*` is removed.** The compose file passes every `SMTP_*` variable, empty when `.env` doesn't set them, and an empty one counted as set: Settings > Email (SMTP) was locked with no server, so email could only be set up in `.env`. Once locked, removing the variables never unlocked it, and mail kept going to the old server. The environment now manages email only when `SMTP_HOST` names a server; without one the settings are yours, and values an earlier `SMTP_HOST` wrote are cleared.
- **Newer USDA Foundation foods have their calories.** Many Foundation foods from USDA FoodData Central, such as "Yogurt, Greek, plain, whole milk", give their energy only as Atwater figures, which CookTrace didn't read, so pantry items added from them had 0 kcal. Search and Refresh from USDA now take USDA's calories from those figures. An item you already added stays as it is: tap **Edit** on it, then **Refresh from USDA**, then Save; a recipe's saved nutrition picks up the new values when it's calculated again. (found with [nutritrace#314](https://github.com/TraceApps/nutritrace/issues/314))
- **A backup from 1.4 brings back the whole cook diary, and the Android app drops what a restore took away.** On 1.5.0-dev01, restoring a backup made by CookTrace 1.4 lost the whole cook diary. After restoring a full backup, recipes, pantry items, cooks, shopping items, cookbooks, comments, recipe versions, categories, custom units and Trace chat messages made after the backup stayed in the Android app. It now drops them, along with a category or unit deleted just before the restore. A kitchen or invite made after the backup also stayed after the restore when the backup had none. API tokens and webhooks are now in the backup too, so a restore no longer removes them; one removed after the backup comes back with it, so remove it again. On a server with another `TOKEN_ENC_KEY` (or `JWT_SECRET`), a webhook's secret can't be read, so its deliveries fail until you make it again.
- **Locked Out? says what disabling user management deletes.** It said your food and diary data would be kept; it deletes every account and its recipes, pantry and plans. The words now say so.
Expand Down
88 changes: 88 additions & 0 deletions scripts/smtp-env-lock.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* SMTP_* in the environment and the lock on Settings > Email (SMTP)
* (server/email.js). The env manages SMTP only when SMTP_HOST names a server;
* the stock docker-compose.yml passes it empty.
*/
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createRequire } from 'node:module';
import test from 'node:test';

const req = createRequire(new URL('../server/package.json', import.meta.url));
let sqlite = true;
try { req('better-sqlite3'); } catch { sqlite = false; }

let db = null, dir = null, seedSmtpFromEnv, isSmtpEnvLocked;
if (sqlite) {
dir = mkdtempSync(join(tmpdir(), 'ct-smtp-env-'));
process.env.DB_PATH = join(dir, 'test.db');
db = (await import('../server/db.js')).default;
({ seedSmtpFromEnv, isSmtpEnvLocked } = await import('../server/email.js'));
}
test.after(() => { try { db?.close(); } catch {} if (dir) rmSync(dir, { recursive: true, force: true }); });

const KEYS = ['SMTP_HOST', 'SMTP_PORT', 'SMTP_SECURE', 'SMTP_USER', 'SMTP_PASS', 'SMTP_FROM'];
const withEnv = (env, fn) => {
const saved = Object.fromEntries(KEYS.map(k => [k, process.env[k]]));
for (const k of KEYS) delete process.env[k];
Object.assign(process.env, env);
try { fn(); } finally {
for (const k of KEYS) { if (saved[k] == null) delete process.env[k]; else process.env[k] = saved[k]; }
}
};
const smtpRows = () => Object.fromEntries(
db.prepare("SELECT key, value FROM app_config WHERE key LIKE 'smtp_%'").all().map(r => [r.key, r.value]));
const reset = () => db.prepare("DELETE FROM app_config WHERE key LIKE 'smtp_%'").run();
const save = (rows) => {
const put = db.prepare('INSERT INTO app_config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value');
for (const [k, v] of Object.entries(rows)) put.run(k, v);
};
// What the stock docker-compose.yml passes when .env sets none of them.
const STOCK_COMPOSE = { SMTP_HOST: '', SMTP_PORT: '587', SMTP_SECURE: 'false', SMTP_USER: '', SMTP_PASS: '', SMTP_FROM: '' };

test('the stock compose file leaves Settings > Email to the admin', { skip: !sqlite }, () => {
reset();
save({ smtp_host: 'mail.admin.example', smtp_port: '465', smtp_from: 'admin@example.com' });
withEnv(STOCK_COMPOSE, seedSmtpFromEnv);
assert.equal(isSmtpEnvLocked(), false);
assert.deepEqual(smtpRows(), { smtp_host: 'mail.admin.example', smtp_port: '465', smtp_from: 'admin@example.com' });
});

test('with SMTP_HOST set, the env wins and locks the form', { skip: !sqlite }, () => {
reset();
save({ smtp_host: 'mail.admin.example', smtp_user: 'admin' });
withEnv({ SMTP_HOST: 'mail.env.example', SMTP_PORT: '587', SMTP_FROM: 'env@example.com' }, seedSmtpFromEnv);
assert.equal(isSmtpEnvLocked(), true);
assert.deepEqual(smtpRows(), {
smtp_host: 'mail.env.example', smtp_port: '587', smtp_from: 'env@example.com',
smtp_user: 'admin', smtp_env_locked: 'true',
});
});

test('removing SMTP_* unlocks the form and drops what the env wrote', { skip: !sqlite }, () => {
reset();
withEnv({ SMTP_HOST: 'mail.env.example', SMTP_PORT: '587', SMTP_PASS: 'secret' }, seedSmtpFromEnv);
assert.equal(isSmtpEnvLocked(), true);
withEnv({}, seedSmtpFromEnv);
assert.equal(isSmtpEnvLocked(), false);
assert.deepEqual(smtpRows(), {});
});

test('emptying SMTP_HOST, as the stock compose does, unlocks it too', { skip: !sqlite }, () => {
reset();
withEnv({ SMTP_HOST: 'mail.env.example', SMTP_FROM: 'env@example.com' }, seedSmtpFromEnv);
withEnv(STOCK_COMPOSE, seedSmtpFromEnv);
assert.equal(isSmtpEnvLocked(), false);
assert.deepEqual(smtpRows(), {});
});

test('a server set up in Settings stays when the env never named one', { skip: !sqlite }, () => {
reset();
save({ smtp_host: 'mail.admin.example', smtp_pass: 'p' });
withEnv({}, seedSmtpFromEnv);
withEnv({}, seedSmtpFromEnv);
assert.equal(isSmtpEnvLocked(), false);
assert.deepEqual(smtpRows(), { smtp_host: 'mail.admin.example', smtp_pass: 'p' });
});
19 changes: 12 additions & 7 deletions server/email.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,20 @@ export function seedSmtpFromEnv() {
const upsert = db.prepare(
'INSERT INTO app_config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'
);
let locked = false;
for (const [envKey, dbKey] of Object.entries(map)) {
if (process.env[envKey] != null) {
upsert.run(dbKey, process.env[envKey]);
locked = true;
// The env takes over only when it names a server: the stock compose passes
// SMTP_HOST empty, and that must leave Settings > Email to the admin.
if (process.env.SMTP_HOST) {
for (const [envKey, dbKey] of Object.entries(map)) {
if (process.env[envKey] != null) upsert.run(dbKey, process.env[envKey]);
}
// Store lock flag so clients can disable the UI fields
upsert.run('smtp_env_locked', 'true');
} else if (isSmtpEnvLocked()) {
// The env stopped managing SMTP: unlock, and drop the values it wrote so
// mail doesn't keep going to a server nobody configures any more.
const keys = [...Object.values(map), 'smtp_env_locked'];
db.prepare(`DELETE FROM app_config WHERE key IN (${keys.map(() => '?').join(', ')})`).run(...keys);
}
// Store lock flag so clients can disable the UI fields
if (locked) upsert.run('smtp_env_locked', 'true');
}

export function isSmtpEnvLocked() {
Expand Down