283 lines
10 KiB
JavaScript
283 lines
10 KiB
JavaScript
import { beforeEach, afterEach, after, test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { createDatabase } from '@merchantflow/database';
|
|
import { merchantDetailSchema, dashboardSchema } from '@merchantflow/contracts';
|
|
import { createApp } from '../dist/app.js';
|
|
|
|
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
|
|
throw new Error('Only the isolated test database is allowed');
|
|
const db = createDatabase(process.env.DATABASE_URL);
|
|
const keys = new Set();
|
|
let app, base;
|
|
const origin = process.env.APP_ORIGIN;
|
|
const input = () => ({
|
|
name: 'Public lead integration',
|
|
contactName: 'Test Contact',
|
|
contactEmail: `lead-${randomUUID()}@example.test`,
|
|
website: 'example.test',
|
|
country: 'GB',
|
|
industry: 'OTHER',
|
|
estimatedMonthlyVolumeUsd: '1234,50',
|
|
companyFax: '',
|
|
});
|
|
function key() {
|
|
const value = randomUUID();
|
|
keys.add(value);
|
|
return value;
|
|
}
|
|
async function start() {
|
|
app = await createApp();
|
|
await app.listen(0, '127.0.0.1');
|
|
base = `${await app.getUrl()}/api`;
|
|
}
|
|
async function request(path, body, headers = {}, method = 'POST', url = base) {
|
|
const response = await fetch(`${url}${path}`, {
|
|
method,
|
|
headers: {
|
|
origin,
|
|
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
...headers,
|
|
},
|
|
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
});
|
|
return { status: response.status, body: await response.json(), headers: response.headers };
|
|
}
|
|
const submit = (data, id, headers = {}, url = base) =>
|
|
request('/public/leads', data, { 'Idempotency-Key': id, ...headers }, 'POST', url);
|
|
async function cookie(account) {
|
|
const result = await request('/auth/login', {
|
|
email: `${account}@merchantflow.test`,
|
|
password: 'MerchantFlow123!',
|
|
});
|
|
assert.equal(result.status, 201);
|
|
return result.headers.get('set-cookie').split(';')[0];
|
|
}
|
|
beforeEach(start);
|
|
afterEach(async () => {
|
|
await app?.close();
|
|
await db.merchant.deleteMany({ where: { publicSubmissionKey: { in: [...keys] } } });
|
|
keys.clear();
|
|
});
|
|
after(() => db.$disconnect());
|
|
|
|
test('public submission persists complete onboarding context and respects CRM permissions', async () => {
|
|
const id = key(),
|
|
data = input();
|
|
const result = await submit(data, id);
|
|
assert.equal(result.status, 202);
|
|
assert.deepEqual(result.body, { ok: true });
|
|
const merchant = await db.merchant.findUnique({
|
|
where: { publicSubmissionKey: id },
|
|
include: { activities: true, events: true, checklist: { include: { changes: true } } },
|
|
});
|
|
assert.equal(merchant.status, 'NEW_LEAD');
|
|
assert.equal(merchant.ownerId, null);
|
|
assert.equal(merchant.source, 'LANDING_PAGE');
|
|
assert.equal(merchant.version, 0);
|
|
assert.equal(merchant.name, data.name);
|
|
assert.equal(merchant.contactName, data.contactName);
|
|
assert.equal(merchant.contactEmail, data.contactEmail);
|
|
assert.equal(merchant.country, 'GB');
|
|
assert.equal(merchant.industry, 'OTHER');
|
|
assert.equal(merchant.website, 'https://example.test/');
|
|
assert.equal(merchant.estimatedMonthlyVolumeUsd.toFixed(2), '1234.50');
|
|
assert.equal(merchant.checklist.length, 3);
|
|
assert.ok(
|
|
merchant.checklist.every((item) => item.state === 'MISSING' && item.changes.length === 0),
|
|
);
|
|
assert.equal(merchant.activities.length, 1);
|
|
assert.equal(merchant.activities[0].actorId, null);
|
|
assert.equal(merchant.activities[0].kind, 'AUDIT');
|
|
assert.equal(merchant.events.length, 1);
|
|
assert.equal(merchant.events[0].actorId, null);
|
|
assert.equal(merchant.events[0].fromStatus, null);
|
|
assert.equal(merchant.events[0].toStatus, 'NEW_LEAD');
|
|
const head = await cookie('head'),
|
|
compliance = await cookie('compliance'),
|
|
alex = await cookie('alex'),
|
|
sam = await cookie('sam');
|
|
for (const staff of [head, compliance]) {
|
|
const detail = await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET');
|
|
assert.equal(detail.status, 200);
|
|
assert.equal(merchantDetailSchema.safeParse(detail.body).success, true);
|
|
assert.equal(detail.body.activities[0].actor, null);
|
|
assert.ok(!JSON.stringify(detail.body).includes('publicSubmission'));
|
|
const dashboard = await request('/dashboard', undefined, { cookie: staff }, 'GET');
|
|
assert.equal(dashboardSchema.safeParse(dashboard.body).success, true);
|
|
}
|
|
for (const staff of [alex, sam]) {
|
|
assert.equal(
|
|
(await request(`/merchants/${merchant.id}`, undefined, { cookie: staff }, 'GET')).status,
|
|
404,
|
|
);
|
|
const list = await request(
|
|
`/merchants?search=${encodeURIComponent(data.contactEmail)}`,
|
|
undefined,
|
|
{ cookie: staff },
|
|
'GET',
|
|
);
|
|
assert.equal(list.body.total, 0);
|
|
}
|
|
assert.equal(
|
|
(
|
|
await request(
|
|
`/merchants/${merchant.id}/transitions`,
|
|
{ version: 0, toStatus: 'CONTACTED' },
|
|
{ cookie: head },
|
|
)
|
|
).status,
|
|
409,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request(
|
|
`/merchants/${merchant.id}/assignment`,
|
|
{ version: 0, ownerId: 'user-manager1' },
|
|
{ cookie: head },
|
|
'PATCH',
|
|
)
|
|
).status,
|
|
200,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request(
|
|
`/merchants/${merchant.id}/activities`,
|
|
{ version: 1, kind: 'EMAIL', text: 'Responded to the public enquiry' },
|
|
{ cookie: alex },
|
|
)
|
|
).status,
|
|
201,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request(
|
|
`/merchants/${merchant.id}/transitions`,
|
|
{ version: 2, toStatus: 'CONTACTED' },
|
|
{ cookie: alex },
|
|
)
|
|
).status,
|
|
201,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request(
|
|
`/merchants/${merchant.id}/activities/${merchant.activities[0].id}`,
|
|
{ version: 3, kind: 'NOTE', text: 'attempt to edit audit' },
|
|
{ cookie: head },
|
|
'PATCH',
|
|
)
|
|
).status,
|
|
403,
|
|
);
|
|
});
|
|
|
|
test('sequential, concurrent and post-restart retries create exactly one lead', async () => {
|
|
const id = key(),
|
|
data = input();
|
|
const other = await createApp();
|
|
await other.listen(0, '127.0.0.1');
|
|
try {
|
|
const results = await Promise.all([
|
|
submit(data, id),
|
|
submit(data, id),
|
|
submit(data, id, {}, `${await other.getUrl()}/api`),
|
|
]);
|
|
assert.ok(results.every((result) => result.status === 202));
|
|
assert.equal((await submit({ ...data, estimatedMonthlyVolumeUsd: '1234.50' }, id)).status, 202);
|
|
} finally {
|
|
await other.close();
|
|
}
|
|
await app.close();
|
|
await start();
|
|
assert.equal((await submit(data, id)).status, 202);
|
|
assert.equal((await submit({ ...data, name: 'Changed payload' }, id)).status, 409);
|
|
const matches = await db.merchant.findMany({
|
|
where: { publicSubmissionKey: id },
|
|
include: { activities: true, events: true },
|
|
});
|
|
assert.equal(matches.length, 1);
|
|
assert.equal(matches[0].activities.length, 1);
|
|
assert.equal(matches[0].events.length, 1);
|
|
});
|
|
|
|
test('honeypots always accept valid envelopes without creating any related records', async () => {
|
|
const before = [
|
|
await db.merchant.count(),
|
|
await db.activity.count(),
|
|
await db.statusEvent.count(),
|
|
await db.kybChecklistItem.count(),
|
|
];
|
|
for (let i = 0; i < 12; i++) {
|
|
const result = await submit(
|
|
i % 2 ? { ...input(), companyFax: 'spam' } : { companyFax: ' ', contactEmail: 'invalid' },
|
|
key(),
|
|
);
|
|
assert.equal(result.status, 202);
|
|
assert.deepEqual(result.body, { ok: true });
|
|
}
|
|
assert.deepEqual(
|
|
[
|
|
await db.merchant.count(),
|
|
await db.activity.count(),
|
|
await db.statusEvent.count(),
|
|
await db.kybChecklistItem.count(),
|
|
],
|
|
before,
|
|
);
|
|
});
|
|
|
|
test('origin, key and body checks reject invalid submissions without persisting', async () => {
|
|
const id = key();
|
|
for (const headers of [
|
|
{ origin: 'https://untrusted.example' },
|
|
{ origin: '' },
|
|
{ 'sec-fetch-site': 'cross-site' },
|
|
])
|
|
assert.equal((await submit(input(), id, headers)).status, 403);
|
|
assert.equal((await submit(input(), 'invalid')).status, 400);
|
|
assert.equal((await request('/public/leads', input())).status, 400);
|
|
for (const data of [
|
|
{ ...input(), country: 'ZZ' },
|
|
{ ...input(), ownerId: 'user-head' },
|
|
{ ...input(), estimatedMonthlyVolumeUsd: '-1' },
|
|
{ ...input(), companyFax: 42 },
|
|
])
|
|
assert.equal((await submit(data, id)).status, 400);
|
|
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0);
|
|
});
|
|
|
|
test('email quotas allow successful replays and IP quotas include invalid attempts', async () => {
|
|
const data = input(),
|
|
first = key();
|
|
assert.equal((await submit(data, first)).status, 202);
|
|
for (let i = 0; i < 2; i++) assert.equal((await submit(data, key())).status, 202);
|
|
assert.equal((await submit(data, first)).status, 202);
|
|
const result = await submit(data, key());
|
|
assert.equal(result.status, 429);
|
|
assert.ok(Number(result.headers.get('retry-after')) > 0);
|
|
await app.close();
|
|
await start();
|
|
for (let i = 0; i < 10; i++) assert.equal((await submit({}, key())).status, 400);
|
|
const limited = await submit(input(), key(), { 'x-forwarded-for': '1.2.3.4' });
|
|
assert.equal(limited.status, 429);
|
|
assert.ok(Number(limited.headers.get('retry-after')) > 0);
|
|
});
|
|
|
|
test('a failed creation activity rolls back the lead and its children; retry remains safe', async () => {
|
|
const id = key(),
|
|
data = { ...input(), name: 'Force rollback integration' };
|
|
await db.$executeRaw`CREATE FUNCTION fail_public_lead_activity() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM "Merchant" WHERE id = NEW."merchantId" AND name = 'Force rollback integration') THEN RAISE EXCEPTION 'Injected test failure'; END IF; RETURN NEW; END $$`;
|
|
await db.$executeRaw`CREATE TRIGGER fail_public_lead_activity BEFORE INSERT ON "Activity" FOR EACH ROW EXECUTE FUNCTION fail_public_lead_activity()`;
|
|
try {
|
|
assert.equal((await submit(data, id)).status, 500);
|
|
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 0);
|
|
} finally {
|
|
await db.$executeRaw`DROP TRIGGER fail_public_lead_activity ON "Activity"`;
|
|
await db.$executeRaw`DROP FUNCTION fail_public_lead_activity()`;
|
|
}
|
|
assert.equal((await submit(data, id)).status, 202);
|
|
assert.equal(await db.merchant.count({ where: { publicSubmissionKey: id } }), 1);
|
|
});
|