feat(messaging): add explicit versioned consent and eligibility
This commit is contained in:
parent
0f4e73f06e
commit
779496cc15
|
|
@ -80,3 +80,5 @@ Seasonal campaigns and scheduled collection discovery: see [Phase 4C API guide](
|
|||
Campaign-linked collection discounts: see [Phase 4D API guide](docs/campaign-discounts-api.md).
|
||||
|
||||
Private idle cart recovery: see [Phase 4E API guide](docs/cart-recovery-api.md).
|
||||
|
||||
Explicit messaging consent and eligibility: see [Phase 4F API guide](docs/messaging-consent-api.md).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
# Consent-aware messaging (Phase 4F)
|
||||
|
||||
Customers explicitly choose optional promotions and cart recovery reminders for email and WhatsApp independently. All four preferences default to off. Preferences are self-service; staff can check eligibility but cannot grant consent on a customer's behalf. The existing order outbox and account-recovery mail retain their separate transactional contracts.
|
||||
|
||||
| Method | Route | Access and result |
|
||||
| ------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
|
||||
| GET | `/api/v1/messaging/preferences` | Own active session; current notice texts and four current channel/purpose preferences. |
|
||||
| POST | `/api/v1/messaging/preferences` | Own active session; append a versioned grant or withdrawal and return its receipt plus the current preference. |
|
||||
| GET | `/api/v1/messaging/preferences/history` | Own active session; immutable receipts, newest first, with existing `limit`/`offset` pagination. |
|
||||
| GET | `/api/v1/messaging/eligibility/:userId?channel=EMAIL&purpose=PROMOTIONS` | `messaging.read`; scoped recipient's current preference and eligibility. |
|
||||
|
||||
To grant, send `{ "channel": "EMAIL", "purpose": "PROMOTIONS", "granted": true, "version": 0, "noticeVersion": "2026-10-07", "idempotencyKey": "<uuid>" }`. Supported channels are `EMAIL` and `WHATSAPP`; supported purposes are `PROMOTIONS` and `CART_RECOVERY`. The UI must show the returned notice for the selected purpose and channel before submitting a customer's affirmative choice. Never preselect opt-in or infer consent from an order, login, wishlist, cart activity, review, or business verification.
|
||||
|
||||
To withdraw, send the same channel/purpose with `granted: false`, the current `version`, and a fresh `idempotencyKey`, omitting `noticeVersion`. Withdrawal requires no notice agreement. Bodies are strict: no target user, contact data, arbitrary purpose, or client timestamp is accepted. All successful decisions, including repeated choices with new keys, append the next revision and a `messaging.consent.recorded` audit event atomically. Timestamps come from the server/database; notice versions and decision receipts are retained as evidence.
|
||||
|
||||
Each channel/purpose has its own version starting at zero. Stale writes return `CONSENT_CHANGED` (409). Reusing a key with changed input returns `IDEMPOTENCY_CONFLICT` (409). Exact retries return the original immutable `decision` and the **live** `current` preference, so replaying an old grant after withdrawal cannot revive consent or imply current eligibility. Receipt/history responses omit user profile, contact details, internal organization/user scope, hashes, and idempotency keys.
|
||||
|
||||
Staff eligibility returns `channel`, `purpose`, `granted`, `version`, and `eligible`. Eligibility requires a current grant and an active recipient in the staff member's organization. Missing/foreign recipients return `MESSAGING_RECIPIENT_NOT_FOUND` (404), unauthorized staff return 403, and inactive customer sessions cannot change preferences. The additive migration grants `messaging.read` to existing system Owners; custom roles remain explicit.
|
||||
|
||||
The shared `messagingEligibility` function reads the latest decision and live recipient status. A staff preview is not a delivery authorization: future adapters must recheck this gate inside the existing serialized dispatch transaction, including retries, and also validate recipient contact ownership, provider/channel policy, suppression and content eligibility. Consent withdrawal must suppress unsent optional messages. Recovery messages additionally need a currently recoverable cart; promotions need current campaign eligibility. Consent alone does not prove a verified email or WhatsApp destination.
|
||||
|
||||
This milestone stores preferences and exposes the reusable eligibility gate. It sends no messages and adds no provider credentials, contact directory, campaign audience export, guest unsubscribe tokens, templates, scheduler, or promotional outbox. Those belong with enabled provider delivery; existing transactional notifications are not converted into promotional messages.
|
||||
|
||||
Deploy the new table and permission migration before the application. Existing accounts remain opted out with no inferred decisions. Composite user/organization foreign keys enforce scope; native checks validate terms, a serialized insert guard enforces consecutive revisions, and update/delete triggers protect immutable evidence. No historical migration is changed. Older application code ignores the table; preserve decisions and audit evidence on rollback, and keep optional delivery disabled until it uses the consent gate.
|
||||
|
||||
Verification covers default-off and purpose/channel isolation, explicit notice requirements, strict schemas, withdrawal without agreement, stale/conflicting retries, old-grant replay, scoped permission checks, inactive recipients, competing revisions, privacy-preserving history, immutable database records, and migration drift. Multi-connection PostgreSQL verification remains dependent on the project's existing native CI setup.
|
||||
|
|
@ -59,6 +59,7 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov
|
|||
- 4C (implemented): organization-scoped seasonal campaign drafts, versioned editing/publication, immutable published terms, reasoned cancellation, and time-windowed public collection discovery. Campaign discounts, media assets, outbound messaging, and channel integrations remain separate milestones.
|
||||
- 4D (implemented): draft-bound campaign coupons, version-aware offer publication, public offer terms, and collection-only fixed/percentage checkout discounts with exact eligible-subtotal snapshots. Generic coupons retain their behavior; payment enablement, media assets and messaging remain separate milestones.
|
||||
- 4E (implemented): private discovery and versioned resumption of carts idle for 24 hours, current catalog previews, unavailable-item redaction/removal, and audited activity tracking. Outbound recovery reminders remain dependent on consent-aware messaging and provider enablement.
|
||||
- 4F (consent and eligibility implemented; live delivery deferred): explicit, independent email/WhatsApp opt-in and withdrawal for promotions/cart reminders, immutable versioned evidence, private history, and scoped live eligibility checks. Provider delivery, verified channel destinations, suppression-aware dispatch and unsubscribe links remain separate milestones.
|
||||
|
||||
## Phase 5: Community and optimization
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
model MessagingConsentDecision {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
channel String @db.VarChar(20)
|
||||
purpose String @db.VarChar(20)
|
||||
granted Boolean
|
||||
version Int
|
||||
noticeVersion String? @map("notice_version") @db.VarChar(40)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([userId, organizationId, channel, purpose, version])
|
||||
@@unique([userId, organizationId, idempotencyKey])
|
||||
@@index([userId, organizationId, createdAt, id])
|
||||
@@map("messaging_consent_decisions")
|
||||
}
|
||||
|
|
@ -47,5 +47,6 @@
|
|||
"20261005160000_verified_product_reviews": "1f71f6d49622c48a37c88f2eb7740174cbc9aea7d0027f6fc27d81301d87c757",
|
||||
"20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40",
|
||||
"20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017",
|
||||
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31"
|
||||
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31",
|
||||
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
CREATE TABLE "messaging_consent_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"channel" VARCHAR(20) NOT NULL,
|
||||
"purpose" VARCHAR(20) NOT NULL,
|
||||
"granted" BOOLEAN NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"notice_version" VARCHAR(40),
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "messaging_consent_decisions_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "messaging_consent_decisions_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "messaging_consent_terms" CHECK (
|
||||
channel IN ('EMAIL', 'WHATSAPP') AND purpose IN ('PROMOTIONS', 'CART_RECOVERY') AND version > 0
|
||||
AND ((granted AND notice_version = '2026-10-07' AND notice_version IS NOT NULL) OR (NOT granted AND notice_version IS NULL))
|
||||
AND request_hash ~ '^[a-f0-9]{64}$'
|
||||
)
|
||||
);
|
||||
CREATE UNIQUE INDEX "messaging_consent_decisions_user_id_organization_id_channel_key" ON "messaging_consent_decisions"("user_id", "organization_id", "channel", "purpose", "version");
|
||||
CREATE UNIQUE INDEX "messaging_consent_decisions_user_id_organization_id_idempot_key" ON "messaging_consent_decisions"("user_id", "organization_id", "idempotency_key");
|
||||
CREATE INDEX "messaging_consent_decisions_user_id_organization_id_created_idx" ON "messaging_consent_decisions"("user_id", "organization_id", "created_at", "id");
|
||||
|
||||
CREATE FUNCTION guard_messaging_consent() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE previous_version integer;
|
||||
BEGIN
|
||||
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Messaging consent decisions are immutable'; END IF;
|
||||
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
||||
SELECT COALESCE(MAX(version), 0) INTO previous_version FROM messaging_consent_decisions
|
||||
WHERE organization_id = NEW.organization_id AND user_id = NEW.user_id AND channel = NEW.channel AND purpose = NEW.purpose;
|
||||
IF NEW.version::bigint <> previous_version::bigint + 1 THEN RAISE EXCEPTION 'Consent requires next version'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER messaging_consent_guard BEFORE INSERT OR UPDATE OR DELETE ON messaging_consent_decisions
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_messaging_consent();
|
||||
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['messaging.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -90,6 +90,7 @@ model User {
|
|||
recoveryTokens RecoveryToken[]
|
||||
addresses Address[]
|
||||
wishlistItems WishlistItem[]
|
||||
messagingConsents MessagingConsentDecision[]
|
||||
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
|
||||
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
||||
reviewRevocations ReviewPurchaseRevocation[]
|
||||
|
|
|
|||
|
|
@ -14,9 +14,11 @@ import { B2bModule } from './b2b/b2b.module';
|
|||
import { WishlistModule } from './wishlist/wishlist.module';
|
||||
import { ReviewsModule } from './reviews/reviews.module';
|
||||
import { CampaignsModule } from './campaigns/campaigns.module';
|
||||
import { MessagingModule } from './messaging/messaging.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MessagingModule,
|
||||
CampaignsModule,
|
||||
ReviewsModule,
|
||||
WishlistModule,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { B2B_CUSTOM_CANDLE_ERRORS } from './b2b-custom-candle-errors';
|
|||
import { WISHLIST_ERRORS } from './wishlist-errors';
|
||||
import { REVIEW_ERRORS } from './review-errors';
|
||||
import { CAMPAIGN_ERRORS } from './campaign-errors';
|
||||
import { MESSAGING_ERRORS } from './messaging-errors';
|
||||
import { CHECKOUT_ERRORS } from './checkout-errors';
|
||||
import { OPERATIONS_ERRORS } from './operations-errors';
|
||||
import { PLATFORM_ERRORS } from './platform-errors';
|
||||
|
|
@ -15,6 +16,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
|
|||
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
|
||||
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
|
||||
export const ERRORS = {
|
||||
...MESSAGING_ERRORS,
|
||||
...CAMPAIGN_ERRORS,
|
||||
...REVIEW_ERRORS,
|
||||
...WISHLIST_ERRORS,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
export const MESSAGING_ERRORS = {
|
||||
CONSENT_CHANGED: [
|
||||
409,
|
||||
'Consent version has changed',
|
||||
'Stale messaging preference rejected',
|
||||
],
|
||||
MESSAGING_RECIPIENT_NOT_FOUND: [
|
||||
404,
|
||||
'Recipient not found',
|
||||
'Scoped messaging recipient lookup failed',
|
||||
],
|
||||
} as const;
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
export const PERMISSIONS = [
|
||||
'messaging.read',
|
||||
'campaigns.read',
|
||||
'campaigns.manage',
|
||||
'reviews.verify',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
import { z } from 'zod';
|
||||
export const CHANNELS = ['EMAIL', 'WHATSAPP'] as const;
|
||||
export const PURPOSES = ['PROMOTIONS', 'CART_RECOVERY'] as const;
|
||||
export const NOTICE_VERSION = '2026-10-07';
|
||||
export const consentQuerySchema = z
|
||||
.object({ channel: z.enum(CHANNELS), purpose: z.enum(PURPOSES) })
|
||||
.strict();
|
||||
export const consentSchema = consentQuerySchema
|
||||
.extend({
|
||||
granted: z.boolean(),
|
||||
version: z.number().int().min(0).max(2147483646),
|
||||
noticeVersion: z.literal(NOTICE_VERSION).optional(),
|
||||
idempotencyKey: z.uuid(),
|
||||
})
|
||||
.refine(
|
||||
(input) =>
|
||||
input.granted
|
||||
? input.noticeVersion === NOTICE_VERSION
|
||||
: input.noticeVersion === undefined,
|
||||
{
|
||||
message:
|
||||
'Grants require the current notice; withdrawal requires no notice',
|
||||
path: ['noticeVersion'],
|
||||
},
|
||||
);
|
||||
export type ConsentQuery = z.infer<typeof consentQuerySchema>;
|
||||
export type ConsentInput = z.infer<typeof consentSchema>;
|
||||
export const CONSENT_NOTICES = PURPOSES.map((purpose) => ({
|
||||
purpose,
|
||||
version: NOTICE_VERSION,
|
||||
text:
|
||||
purpose === 'PROMOTIONS'
|
||||
? 'I agree to receive optional Mani Candles promotions on the channel I select. I can withdraw this preference at any time.'
|
||||
: 'I agree to receive optional Mani Candles reminders about my unfinished cart on the channel I select. I can withdraw this preference at any time.',
|
||||
}));
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import type { PageInput } from '../identity/identity.schemas';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { assertReplay, commandHash } from '../common/idempotency';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import {
|
||||
CHANNELS,
|
||||
PURPOSES,
|
||||
CONSENT_NOTICES,
|
||||
type ConsentInput,
|
||||
type ConsentQuery,
|
||||
} from './consent.schemas';
|
||||
|
||||
const receiptSelect = {
|
||||
id: true,
|
||||
channel: true,
|
||||
purpose: true,
|
||||
granted: true,
|
||||
version: true,
|
||||
noticeVersion: true,
|
||||
createdAt: true,
|
||||
};
|
||||
async function currentConsent(
|
||||
tx: Prisma.TransactionClient,
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
query: ConsentQuery,
|
||||
) {
|
||||
const decision = await tx.messagingConsentDecision.findFirst({
|
||||
where: { organizationId, userId, ...query },
|
||||
orderBy: { version: 'desc' },
|
||||
select: { granted: true, version: true },
|
||||
});
|
||||
return {
|
||||
...query,
|
||||
granted: decision?.granted ?? false,
|
||||
version: decision?.version ?? 0,
|
||||
};
|
||||
}
|
||||
// Providers must call this inside their serialized dispatch transaction, not cache a staff preview.
|
||||
export async function messagingEligibility(
|
||||
tx: Prisma.TransactionClient,
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
query: ConsentQuery,
|
||||
) {
|
||||
const user = await tx.user.findFirst({
|
||||
where: { id: userId, organizationId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!user) throw new AppError('MESSAGING_RECIPIENT_NOT_FOUND');
|
||||
const current = await currentConsent(tx, organizationId, userId, query);
|
||||
return { ...current, eligible: current.granted && user.status === 'ACTIVE' };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ConsentStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
get(actor: Principal) {
|
||||
return this.access.mutate(actor, null, async (tx) => {
|
||||
const preferences = [];
|
||||
for (const channel of CHANNELS)
|
||||
for (const purpose of PURPOSES)
|
||||
preferences.push(
|
||||
await currentConsent(tx, actor.organizationId, actor.userId, {
|
||||
channel,
|
||||
purpose,
|
||||
}),
|
||||
);
|
||||
return { notices: CONSENT_NOTICES, preferences };
|
||||
});
|
||||
}
|
||||
history(actor: Principal, page: PageInput) {
|
||||
return this.access.mutate(actor, null, (tx) =>
|
||||
tx.messagingConsentDecision.findMany({
|
||||
where: { userId: actor.userId, organizationId: actor.organizationId },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: page.offset,
|
||||
take: page.limit,
|
||||
select: receiptSelect,
|
||||
}),
|
||||
);
|
||||
}
|
||||
record(actor: Principal, input: ConsentInput) {
|
||||
const query = { channel: input.channel, purpose: input.purpose };
|
||||
const requestHash = commandHash(
|
||||
input.channel,
|
||||
input.purpose,
|
||||
Number(input.granted),
|
||||
input.version,
|
||||
input.noticeVersion ?? '',
|
||||
);
|
||||
return this.access.mutate(actor, null, async (tx) => {
|
||||
const scope = {
|
||||
userId: actor.userId,
|
||||
organizationId: actor.organizationId,
|
||||
};
|
||||
const previous = await tx.messagingConsentDecision.findUnique({
|
||||
where: {
|
||||
userId_organizationId_idempotencyKey: {
|
||||
...scope,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
select: { ...receiptSelect, requestHash: true },
|
||||
});
|
||||
const current = await currentConsent(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
query,
|
||||
);
|
||||
if (previous) {
|
||||
const { requestHash: previousHash, ...decision } = previous;
|
||||
assertReplay(previousHash, requestHash);
|
||||
return { decision, current };
|
||||
}
|
||||
if (current.version !== input.version)
|
||||
throw new AppError('CONSENT_CHANGED');
|
||||
const decision = await tx.messagingConsentDecision.create({
|
||||
data: {
|
||||
...scope,
|
||||
...query,
|
||||
granted: input.granted,
|
||||
version: input.version + 1,
|
||||
noticeVersion: input.noticeVersion ?? null,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
requestHash,
|
||||
},
|
||||
select: receiptSelect,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'messaging.consent.recorded',
|
||||
decision.id,
|
||||
);
|
||||
return {
|
||||
decision,
|
||||
current: {
|
||||
...query,
|
||||
granted: decision.granted,
|
||||
version: decision.version,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
eligibility(actor: Principal, userId: string, query: ConsentQuery) {
|
||||
return this.access.mutate(actor, 'messaging.read', (tx) =>
|
||||
messagingEligibility(tx, actor.organizationId, userId, query),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import { ConsentStore } from './consent.store';
|
||||
import {
|
||||
consentQuerySchema,
|
||||
consentSchema,
|
||||
type ConsentQuery,
|
||||
type ConsentInput,
|
||||
} from './consent.schemas';
|
||||
|
||||
@Controller('messaging')
|
||||
export class MessagingController {
|
||||
constructor(private readonly consents: ConsentStore) {}
|
||||
@Get('preferences')
|
||||
get(@CurrentPrincipal() actor: Principal) {
|
||||
return this.consents.get(actor);
|
||||
}
|
||||
@Get('preferences/history')
|
||||
history(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||
) {
|
||||
return this.consents.history(actor, page);
|
||||
}
|
||||
@Post('preferences')
|
||||
record(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Body(new SchemaPipe(consentSchema)) input: ConsentInput,
|
||||
) {
|
||||
return this.consents.record(actor, input);
|
||||
}
|
||||
@Get('eligibility/:userId')
|
||||
@RequirePermission('messaging.read')
|
||||
eligibility(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('userId', ParseUUIDPipe) userId: string,
|
||||
@Query(new SchemaPipe(consentQuerySchema)) query: ConsentQuery,
|
||||
) {
|
||||
return this.consents.eligibility(actor, userId, query);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { IdentityModule } from '../identity/identity.module';
|
||||
import { MessagingController } from './messaging.controller';
|
||||
import { ConsentStore } from './consent.store';
|
||||
@Module({
|
||||
imports: [IdentityModule],
|
||||
controllers: [MessagingController],
|
||||
providers: [ConsentStore],
|
||||
})
|
||||
export class MessagingModule {}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { consentSchema } from '../src/messaging/consent.schemas';
|
||||
|
||||
it('requires explicit supported terms and permits withdrawal without agreeing to a notice', () => {
|
||||
const grant = {
|
||||
channel: 'EMAIL',
|
||||
purpose: 'PROMOTIONS',
|
||||
granted: true,
|
||||
version: 0,
|
||||
noticeVersion: '2026-10-07',
|
||||
idempotencyKey: randomUUID(),
|
||||
};
|
||||
expect(consentSchema.safeParse(grant).success).toBe(true);
|
||||
expect(
|
||||
consentSchema.safeParse({
|
||||
...grant,
|
||||
granted: false,
|
||||
noticeVersion: undefined,
|
||||
}).success,
|
||||
).toBe(true);
|
||||
for (const override of [
|
||||
{ granted: 'true' },
|
||||
{ noticeVersion: undefined },
|
||||
{ granted: false },
|
||||
{ channel: 'SMS' },
|
||||
{ purpose: 'ALL' },
|
||||
{ version: -1 },
|
||||
{ version: 2147483647 },
|
||||
{ userId: randomUUID() },
|
||||
]) {
|
||||
expect(consentSchema.safeParse({ ...grant, ...override }).success).toBe(
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue