manicanldes-backend/test/messaging-consent.spec.ts

178 lines
6.0 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
describe('explicit messaging consent', () => {
let ctx: IdentityApp;
beforeAll(async () => {
ctx = await identityApp();
});
afterAll(async () => {
await ctx.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
const decision = (version = 0, granted = true) => ({
channel: 'EMAIL',
purpose: 'PROMOTIONS',
version,
granted,
...(granted ? { noticeVersion: '2026-10-07' } : {}),
idempotencyKey: randomUUID(),
});
const submit = (token: string, input: object) =>
ctx
.api()
.post('/api/v1/messaging/preferences')
.auth(token, { type: 'bearer' })
.send(input);
const eligibility = (userId: string, token = ctx.token) =>
ctx
.api()
.get('/api/v1/messaging/eligibility/' + userId)
.query({ channel: 'EMAIL', purpose: 'PROMOTIONS' })
.auth(token, { type: 'bearer' });
it('defaults to no consent, isolates preferences and requires the published notice', async () => {
const actor = await secondActor(ctx);
const initial = await ctx
.api()
.get('/api/v1/messaging/preferences')
.auth(actor.token, { type: 'bearer' })
.expect(200);
expect(initial.body.preferences).toHaveLength(4);
expect(
initial.body.preferences.every((p: any) => !p.granted && p.version === 0),
).toBe(true);
const input = decision();
await submit(actor.token, { ...input, noticeVersion: undefined }).expect(
400,
);
await submit(actor.token, { ...input, noticeVersion: 'old' }).expect(400);
await submit(actor.token, { ...input, userId: ctx.owner.userId }).expect(
400,
);
expect((await eligibility(actor.userId).expect(200)).body.eligible).toBe(
false,
);
await submit(actor.token, input).expect(201);
const preferences = await ctx
.api()
.get('/api/v1/messaging/preferences')
.auth(actor.token, { type: 'bearer' })
.expect(200);
expect(preferences.body.preferences.filter((p: any) => p.granted)).toEqual([
{ channel: 'EMAIL', purpose: 'PROMOTIONS', granted: true, version: 1 },
]);
const other = await secondActor(ctx);
expect(
(
await ctx
.api()
.get('/api/v1/messaging/preferences')
.auth(other.token, { type: 'bearer' })
.expect(200)
).body.preferences.every((p: any) => !p.granted),
).toBe(true);
await ctx.api().get('/api/v1/messaging/preferences').expect(401);
});
it('withdraws immediately and an old grant replay cannot revive consent', async () => {
const actor = await secondActor(ctx);
const grant = decision();
const first = await submit(actor.token, grant).expect(201);
expect((await eligibility(actor.userId).expect(200)).body.eligible).toBe(
true,
);
await submit(actor.token, decision(1, false)).expect(201);
const replay = await submit(actor.token, grant).expect(201);
expect(replay.body.decision).toEqual(first.body.decision);
expect(replay.body.current).toEqual({
channel: 'EMAIL',
purpose: 'PROMOTIONS',
granted: false,
version: 2,
});
expect((await eligibility(actor.userId).expect(200)).body.eligible).toBe(
false,
);
expect((await submit(actor.token, decision(1)).expect(409)).body.code).toBe(
'CONSENT_CHANGED',
);
expect(
(
await submit(actor.token, {
...grant,
granted: false,
noticeVersion: undefined,
}).expect(409)
).body.code,
).toBe('IDEMPOTENCY_CONFLICT');
const history = await ctx
.api()
.get('/api/v1/messaging/preferences/history')
.auth(actor.token, { type: 'bearer' })
.query({ limit: 1 })
.expect(200);
expect(history.body).toHaveLength(1);
expect(history.body[0]).toMatchObject({
granted: false,
version: 2,
noticeVersion: null,
});
expect(JSON.stringify(history.body)).not.toMatch(
/requestHash|idempotencyKey|organizationId|email|passwordHash/,
);
expect(
await ctx.db.auditEvent.count({
where: { actorId: actor.userId, action: 'messaging.consent.recorded' },
}),
).toBe(2);
});
it('gates staff checks by permission, organization and live recipient status', async () => {
const actor = await secondActor(ctx);
const staff = await secondActor(ctx, true, ['messaging.read']);
await submit(actor.token, decision()).expect(201);
await eligibility(actor.userId, actor.token).expect(403);
expect(
(await eligibility(actor.userId, staff.token).expect(200)).body,
).toEqual({
channel: 'EMAIL',
purpose: 'PROMOTIONS',
granted: true,
version: 1,
eligible: true,
});
const foreign = await secondActor(ctx, false);
await eligibility(foreign.userId).expect(404);
await ctx.db.user.update({
where: { id: actor.userId },
data: { status: 'SUSPENDED' },
});
expect((await eligibility(actor.userId).expect(200)).body.eligible).toBe(
false,
);
await submit(actor.token, decision(1, false)).expect(401);
});
it('serializes competing revisions and protects evidence from database mutation', async () => {
const actor = await secondActor(ctx);
const results = await Promise.all([
submit(actor.token, decision()),
submit(actor.token, decision()),
]);
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
await expect(
ctx.executeSql(
`UPDATE messaging_consent_decisions SET granted = false WHERE user_id = '${actor.userId}'`,
),
).rejects.toThrow(/immutable/);
await expect(
ctx.executeSql(
`DELETE FROM messaging_consent_decisions WHERE user_id = '${actor.userId}'`,
),
).rejects.toThrow(/immutable/);
expect((await eligibility(actor.userId).expect(200)).body.granted).toBe(
true,
);
});
});