Files
twenty/packages/twenty-server/test/integration/graphql/suites/dpa/dpa.integration-spec.ts
T
Félix Malfait 538b180824 feat(dpa): self-serve Data Processing Agreement generator (#22243)
## What

A single, region-aware DPA that serves all customers, generated
automatically from the customer's deployment. Two layers:

1. **Click-through DPA** — recorded at signup (acceptance = execution),
resolving merge fields from the deployment region. Cloud only.
2. **In-app signed-PDF generator** — Settings → Legal → Generate DPA:
preview the agreement, enter legal entity + authorized signatory,
download a PDF pre-signed by Twenty, and store the executed copy against
the workspace with its template version + timestamp. Deep-linkable at
`/dpa` (login-gated) for `twenty.com/dpa`.

## How it resolves

A typed variable matrix (`dpa-region-config.constant.ts`) maps the
deployment region to the contracting Processor entity and terms:

- **EU (default)** → Twenty.com SAS, hosting EU/Frankfurt, governing law
France, SCC section dormant.
- **US (custom)** → Twenty, Inc., hosting US, SCC section active.

Region is a deployment-wide setting (`DPA_DEPLOYMENT_REGION`, default
EU) behind a `DpaRegionService` seam so it can later become
per-workspace without touching callers. The legal text is verbatim from
the template (generated into `dpa-template.constant.ts` directly from
the source `.docx`); only the 6 merge fields are filled and the SCC
sections (7.2–7.5) stay in the document for every region per the spec —
only field values branch. Sub-processors are deferred to
trust.twenty.com (not enumerated). Billing stays decoupled (Twenty, Inc.
remains merchant of record regardless of Processor).

## UI

Standard list + create-page pattern (mirrors API keys / webhooks): a
list of executed copies (with re-download) — or the agreement preview
when none exists — and a top-right blue **Generate DPA** CTA opening a
standard create page. The "Legal" item is intentionally **not** in the
settings menu; the page is reached via the `/dpa` deep link.

## Notable implementation details

- **PDF** is rendered server-side with `@react-pdf/renderer`. The
built-in standard-14 fonts only encode ASCII and crash on the template's
curly quotes / em–en dashes / accented Latin, so Liberation Sans (OFL)
is **subset to a Latin glyph set and embedded as base64 data: URLs** —
no font files to ship or resolve at runtime (works in dev, prod-Docker
and CI).
- New `core.dpaAgreement` table via a fast instance command (FK hash
reproduced to match TypeORM).
- Self-hosted deployments (billing disabled) skip click-through
recording and stamp a prominent "not a valid agreement" banner on the
preview and PDF.

## Tests

- Unit: resolver (per-region entity/law/SCC state, EU default, no
unresolved `{{ }}`, SCC sections present in both regions, self-hosted
notice) and HTML renderer.
- Integration (`test/integration/graphql/suites/dpa`): preview has no
unresolved fields; `generateSignedDpa` renders + persists + returns a
downloadable PDF (asserted with accented input to guard the font
regression); list re-download.

## ⚠ Needs legal input before go-live (marked `TODO_CONFIRM` in
`dpa-region-config.constant.ts`)

- Registered-office addresses for Twenty.com SAS and Twenty, Inc.
- US deployment governing law (the template only specifies France).
- DPO name and the Twenty pre-signed authorized signatory name/title.

## Out of scope (flagged per spec)

Intra-group legal agreement and any Stripe/billing-entity changes. A
future e-sign provider would plug in at `DpaService.generateSignedDpa` +
the signatory input.

> Draft until the integration test passes in CI and the legal
`TODO_CONFIRM` values are supplied.

https://claude.ai/code/session_01Ahjydxx6J1souz1s1NeA9a

---
_Generated by [Claude
Code](https://claude.ai/code/session_01Ahjydxx6J1souz1s1NeA9a)_

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/22243?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
2026-06-27 17:46:38 +02:00

178 lines
5.5 KiB
TypeScript

import gql from 'graphql-tag';
import request from 'supertest';
import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
// End-to-end coverage for the self-serve DPA generator. The generate mutation
// renders the PDF with @react-pdf/renderer on the server, so this also guards
// against the embedded-font regression ("unsupported number" on non-ASCII
// glyphs) — the input below intentionally contains accents and an em dash.
describe('DPA resolver (integration)', () => {
const createdAgreementIds: string[] = [];
afterAll(async () => {
for (const id of createdAgreementIds) {
await global.testDataSource
.query('DELETE FROM core."dpaAgreement" WHERE id = $1', [id])
.catch(() => {});
}
});
describe('dpaPreview query', () => {
it('resolves the deployment document with no unresolved merge fields', async () => {
const response = await makeGraphqlAPIRequest({
query: gql`
query DpaPreview {
dpaPreview {
title
region
processorEntity
templateVersion
sccSectionActive
blocks {
kind
text
}
}
}
`,
});
expect(response.status).toBe(200);
expect(response.body.errors).toBeUndefined();
const preview = response.body.data.dpaPreview;
expect(preview).toBeDefined();
expect(['EU', 'US']).toContain(preview.region);
expect(preview.processorEntity).toBeTruthy();
expect(preview.templateVersion).toBeTruthy();
expect(preview.blocks.length).toBeGreaterThan(0);
const joined = preview.blocks
.map((block: { text: string }) => block.text)
.join('\n');
expect(joined).not.toMatch(/\{\{[^}]+\}\}/);
});
});
describe('generateSignedDpa mutation', () => {
it('generates a signed PDF, returns a download URL and persists the record', async () => {
const input = {
customerLegalEntityName: 'Société Générale — Genève',
signatoryName: 'José Peña',
signatoryTitle: 'Directeur Général',
};
const response = await makeGraphqlAPIRequest({
query: gql`
mutation GenerateSignedDpa($input: GenerateSignedDpaInput!) {
generateSignedDpa(input: $input) {
downloadUrl
agreement {
id
type
region
processorEntity
templateVersion
customerLegalEntityName
signatoryName
signatoryTitle
}
}
}
`,
variables: { input },
});
expect(response.status).toBe(200);
// No errors here means renderToBuffer succeeded with the embedded font.
expect(response.body.errors).toBeUndefined();
const result = response.body.data.generateSignedDpa;
expect(result).toBeDefined();
expect(typeof result.downloadUrl).toBe('string');
expect(result.downloadUrl).toContain('/file/');
expect(result.agreement.id).toBeDefined();
expect(result.agreement.type).toBe('SIGNED');
expect(result.agreement.customerLegalEntityName).toBe(
input.customerLegalEntityName,
);
expect(result.agreement.templateVersion).toBeTruthy();
createdAgreementIds.push(result.agreement.id);
// The stored copy is downloadable and is a real PDF.
const downloadUrl = new URL(result.downloadUrl);
const downloadResponse = await request(
`http://localhost:${APP_PORT}`,
).get(`${downloadUrl.pathname}${downloadUrl.search}`);
expect(downloadResponse.status).toBe(200);
const body = downloadResponse.body;
const header = Buffer.isBuffer(body)
? body.subarray(0, 5).toString()
: '';
// Local storage streams the bytes; S3 would 30x-redirect. Only assert the
// PDF magic bytes when we actually received the file body.
if (header !== '') {
expect(header).toBe('%PDF-');
}
});
it('rejects blank execution fields via server-side validation', async () => {
const response = await makeGraphqlAPIRequest({
query: gql`
mutation GenerateSignedDpa($input: GenerateSignedDpaInput!) {
generateSignedDpa(input: $input) {
downloadUrl
}
}
`,
variables: {
input: {
customerLegalEntityName: 'Acme GmbH',
signatoryName: '',
signatoryTitle: 'Head of Legal',
},
},
});
expect(response.body.errors).toBeDefined();
});
});
describe('dpaAgreements query', () => {
it('lists executed copies with a re-download URL', async () => {
const response = await makeGraphqlAPIRequest({
query: gql`
query DpaAgreements {
dpaAgreements {
id
type
templateVersion
downloadUrl
}
}
`,
});
expect(response.status).toBe(200);
expect(response.body.errors).toBeUndefined();
expect(Array.isArray(response.body.data.dpaAgreements)).toBe(true);
const signed = response.body.data.dpaAgreements.find(
(agreement: { id: string }) =>
createdAgreementIds.includes(agreement.id),
);
expect(signed).toBeDefined();
expect(signed.type).toBe('SIGNED');
expect(typeof signed.downloadUrl).toBe('string');
});
});
});