Files
redefined-designs/backend/tests/integration/emailTemplates.integration.test.ts
T
synAdminandClaude Opus 5 90e372d6bd
Linting / lint (pull_request) Successful in 3m37s
SonarQube Analysis / sonarqube (pull_request) Failing after 35m39s
feat(admin): move a customer's account to an address they can reach (#337)
The third step of the only recovery route a customer who has lost their mailbox has. The first two are contacting the shop and being verified against order history. The third had no implementation, so the answer was a hand-written database edit that left no record of who did it or why.

The thing to say plainly, because everything here follows from it: this operation and an account takeover are the same operation. They differ only in whether the verification was sound, and nothing in the software can check that. What the software can do is make the change recorded, announced, and complete in its effects.

Recorded. The endpoint refuses without a written reason, and the reason is stored against the account. That row is the only thing that tells a genuine recovery from a takeover afterwards, which is why a hand edit was never acceptable and why the field is required by the server rather than merely collected by the form. It is never shown to the customer: it is a note about how somebody was verified and can name things the customer should not be handed back.

There is no column for who did it. Admin access is one shared gate secret in front of a single operator, so such a column could only ever hold a constant, and a constant dressed up as an identity is worse than an honest absence.

Announced, to the address being replaced. If the recovery was sound that reaches nobody and costs nothing. If it was not, it reaches the real owner, who is the only person in the world who can say so, and that is the only reason this endpoint is safe to have at all. Its own template rather than the self-service one, because that copy says to contact us if you did not make this change, and here somebody already did — the sentence would be addressed to the customer who just did the thing it asks for, while the person who needs to act on it did nothing.

The new address is marked unverified and sent a confirmation link. Somebody reading an address out over the phone has not demonstrated they can receive mail at it, and that is the commonest way this goes wrong harmlessly.

Complete in its effects. The move signs the customer out everywhere, removes every passkey, and cancels reset links already sent. That is the conclusion #42 reached for password reset, and it applies here with more force: somebody the system cannot identify asked for this change, so a session or a credential surviving it is one the new owner cannot see and cannot revoke, and a reset link sitting in the mailbox being taken away would let whoever still reads it take the account straight back.

The password is left alone. What the customer lost was the mailbox, so demanding a new one adds a step for no gain.

The verification-email helper moved out of the customers route into its own module, for the reason session creation moved out for passkeys: two implementations that agree today are two that can be changed one at a time, and the one that gets forgotten is whichever the manual testing does not exercise. This path runs perhaps once a year, so it is exactly the one that would rot.

The admin drawer gains the action next to the address rather than among the account controls, because it is a thing done to that field by someone already looking at it. It leads with the warning instead of burying it. The history of moves sits on the same drawer and renders nothing at all for the overwhelming majority of customers, who have never been moved.

Verified: backend tsc clean for src and tests, 526 unit tests pass, lint clean apart from warnings that predate this branch; frontend tsc, lint and build clean. The integration suite needs a database this machine has no Docker for. It also cannot be proven by CI right now — run 917 has been hung since it started and 24 runs are queued behind it, which is the same hang #154 identifies as the source of the leftover Postgres containers.

Closes #337

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 16:36:34 -05:00

182 lines
6.6 KiB
TypeScript

import request from 'supertest';
import app from '../../src/app';
import { pool } from '../../src/db';
import { resetDb, closeDb } from './setup/testDb';
import { renderTemplate } from '../../src/emailTemplates';
import { loadStoredTemplate } from '../../src/routes/adminEmailTemplates';
beforeEach(async () => {
// resetDb clears stored email templates as well, so a template saved by one
// test cannot change the mail another asserts on.
await resetDb();
});
afterAll(async () => {
await pool.end();
await closeDb();
});
const VALID_RESET_BODY = 'New copy. [Choose a new password]({{resetUrl}}) within the hour.';
describe('GET /api/admin/email-templates', () => {
it('lists every template with its defaults and placeholder rules', async () => {
const res = await request(app).get('/api/admin/email-templates');
expect(res.status).toBe(200);
expect(res.body.map((t: { key: string }) => t.key).sort()).toEqual([
'cartReminder',
'emailChanged',
'emailChangedByAdmin',
'favoriteSold',
'favoriteWithdrawn',
'intakeDraft',
'passwordReset',
'uploadLink',
'verification'
]);
const reset = res.body.find((t: { key: string }) => t.key === 'passwordReset');
expect(reset.required).toEqual(['resetUrl']);
expect(reset.defaultBody).toContain('{{resetUrl}}');
});
// Null rather than the default text, so the screen can tell "never edited"
// from "edited to something identical to the default".
it('reports an uncustomised template as null rather than as its default', async () => {
const res = await request(app).get('/api/admin/email-templates');
const reset = res.body.find((t: { key: string }) => t.key === 'passwordReset');
expect(reset.subject).toBeNull();
expect(reset.body).toBeNull();
});
});
describe('PUT /api/admin/email-templates/:key', () => {
it('stores a replacement subject and body', async () => {
const res = await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: 'Your reset link', body: VALID_RESET_BODY });
expect(res.status).toBe(200);
const listed = await request(app).get('/api/admin/email-templates');
const reset = listed.body.find((t: { key: string }) => t.key === 'passwordReset');
expect(reset.subject).toBe('Your reset link');
expect(reset.body).toBe(VALID_RESET_BODY);
});
// The rule that keeps this from being a way to break password resets from a
// settings screen.
it('refuses a body that has dropped the required placeholder', async () => {
const res = await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: 'Your reset link', body: 'Just click the thing.' });
expect(res.status).toBe(400);
expect(res.body.error).toContain('{{resetUrl}}');
});
it('names every missing placeholder, not just the first', async () => {
const res = await request(app)
.put('/api/admin/email-templates/cartReminder')
.send({ subject: 'Your cart', body: 'You left things behind.' });
expect(res.status).toBe(400);
expect(res.body.error).toContain('{{itemList}}');
expect(res.body.error).toContain('{{cartUrl}}');
});
it('refuses an empty subject or body', async () => {
const noSubject = await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: ' ', body: VALID_RESET_BODY });
expect(noSubject.status).toBe(400);
const noBody = await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: 'Something', body: ' ' });
expect(noBody.status).toBe(400);
});
it('refuses a template key it does not recognise', async () => {
const res = await request(app)
.put('/api/admin/email-templates/invoiceOverdue')
.send({ subject: 'x', body: 'y' });
expect(res.status).toBe(404);
});
// Nothing is stored when a save is refused, or a half-applied edit would sit
// there looking accepted.
it('stores nothing when it refuses', async () => {
await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: 'Your reset link', body: 'No link here.' });
const { rows } = await pool.query(`SELECT key FROM admin_settings WHERE key LIKE 'email%'`);
expect(rows).toHaveLength(0);
});
});
describe('DELETE /api/admin/email-templates/:key', () => {
it('restores the built-in copy by forgetting the stored rows', async () => {
await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: 'Custom', body: VALID_RESET_BODY });
const res = await request(app).delete('/api/admin/email-templates/passwordReset');
expect(res.status).toBe(200);
const listed = await request(app).get('/api/admin/email-templates');
const reset = listed.body.find((t: { key: string }) => t.key === 'passwordReset');
expect(reset.subject).toBeNull();
expect(reset.body).toBeNull();
});
});
// The point of the whole feature: what is stored is what customers receive.
describe('what a stored template does to the email that gets sent', () => {
it('is used in place of the default once saved', async () => {
await request(app)
.put('/api/admin/email-templates/passwordReset')
.send({ subject: 'Reset requested', body: VALID_RESET_BODY });
const { subject, html } = renderTemplate(
'passwordReset',
await loadStoredTemplate('passwordReset'),
{ greeting: 'Hi Thom,', resetUrl: 'https://shop.test/r?token=abc' }
);
expect(subject).toBe('Reset requested');
expect(html).toContain('New copy.');
expect(html).toContain('https://shop.test/r?token=abc');
});
it('falls back to the built-in copy when nothing is stored', async () => {
const { subject, html } = renderTemplate(
'passwordReset',
await loadStoredTemplate('passwordReset'),
{ greeting: 'Hi,', resetUrl: 'https://shop.test/r?token=abc' }
);
expect(subject).toBe('Reset your Redefined Designs password');
expect(html).toContain('Choose a new password');
});
// Editing the copy must not be able to remove the sentence that explains why
// the email is lawful to send.
it('keeps the consent footer on a favorite alert whose body was replaced', async () => {
await request(app)
.put('/api/admin/email-templates/favoriteSold')
.send({ subject: 'Gone', body: 'Sorry, {{itemName}} sold.' });
const { html } = renderTemplate('favoriteSold', await loadStoredTemplate('favoriteSold'), {
itemName: 'Oak table',
siteUrl: 'https://shop.test'
});
expect(html).toContain('Sorry, Oak table sold.');
expect(html).toContain('account page');
});
});