Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: Confirmed customers' own data requests by email before acting on them (#14934)
Łukasz Adamczykdc2f1a786e4a
diff --git a/.changeset/sdk-data-request-confirmation.md b/.changeset/sdk-data-request-confirmation.mdnew file mode 100644index 0000000000..047751e500--- /dev/null+++ b/.changeset/sdk-data-request-confirmation.md@@ -0,0 +1,7 @@+---+"@spree/sdk": minor+"@spree/admin-sdk": patch+"@spree/dashboard": patch+---++A customer's own data request now waits for confirmation from the account's email address. `client.customer.dataRequests` lists, reads and opens requests, and `create` takes a `redirect_url` for the page the emailed link opens. `client.dataRequests.confirm(token)` confirms one from that page, and `client.dataRequests.get(token)` reads it, with the download link once the export is ready. `DataRequestStatus` gains `awaiting_confirmation` and `lapsed`. The dashboard's email editor lists the new confirmation email.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex eec4b41afd..155bf10406 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -6353,7 +6353,7 @@ paths:| `kind` | One of `access`, `erasure` | `eq` `not_eq` `in` `not_in` `null` `not_null` || `number` | Text | `eq` `not_eq` `in` `not_in` `cont` `i_cont` `not_cont` `start` `end` `null` `not_null` `present` `blank` || `requested_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |- | `status` | One of `pending`, `processing`, `completed`, `failed` | `eq` `not_eq` `in` `not_in` `null` `not_null` |+ | `status` | One of `awaiting_confirmation`, `pending`, `processing`, `completed`, `failed`, `lapsed` | `eq` `not_eq` `in` `not_in` `null` `not_null` || `updated_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |**Sort by:** `completed_at`, `created_at`, `email`, `id`, `kind`, `number`, `requested_at`, `status`, `updated_at`. Prefix a field with `-` to sort descending.@@ -37321,6 +37321,12 @@ paths:credential: falsedeprecated: falsereplaced_by:+ - name: data_request.confirmation_requested+ group: data_request+ credential_permission: write_customers+ credential: true+ deprecated: false+ replaced_by:- name: data_request.createdgroup: data_requestcredential_permission:@@ -38666,7 +38672,7 @@ paths:deprecated: falsereplaced_by:meta:- count: 251+ count: 252"/api/v3/admin/catalogs":get:summary: List catalogs@@ -61303,10 +61309,12 @@ components:anyOf:- type: stringenum:+ - awaiting_confirmation- pending- processing- completed- failed+ - lapsed- type: stringdescription: The values listed are the built-in ones; extensions may addmore.@@ -84558,10 +84566,12 @@ components:requested_at: datetimestatus:enum:+ - awaiting_confirmation- pending- processing- completed- failed+ - lapsedupdated_at: datetimeassociations: {}scopes:diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yamlindex ddf2ded4f9..b3beeb94a8 100644--- a/docs/api-reference/store.yaml+++ b/docs/api-reference/store.yaml@@ -8790,7 +8790,7 @@ paths:| `kind` | One of `access`, `erasure` | `eq` `not_eq` `in` `not_in` `null` `not_null` || `number` | Text | `eq` `not_eq` `in` `not_in` `cont` `i_cont` `not_cont` `start` `end` `null` `not_null` `present` `blank` || `requested_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |- | `status` | One of `pending`, `processing`, `completed`, `failed` | `eq` `not_eq` `in` `not_in` `null` `not_null` |+ | `status` | One of `awaiting_confirmation`, `pending`, `processing`, `completed`, `failed`, `lapsed` | `eq` `not_eq` `in` `not_in` `null` `not_null` || `updated_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |**Sort by:** `completed_at`, `created_at`, `email`, `id`, `kind`, `number`, `requested_at`, `status`, `updated_at`. Prefix a field with `-` to sort descending.@@ -8849,11 +8849,14 @@ paths:bearer_auth: []description: |Opens a GDPR request for a copy of the customer's personal data (`access`)- or its erasure (`erasure`). The work happens in the background and the- response is the pending request.+ or its erasure (`erasure`). Nothing happens until the request is confirmed+ from the link emailed to the account's address: the response is the request+ awaiting confirmation, and the link opens `redirect_url` with the+ confirmation token appended. The work then happens in the background.An erasure request requires the account password. A request of the same- kind that is still in flight is returned instead of starting a second one.+ kind that is still in flight is returned instead of starting a second one,+ and a request still awaiting confirmation sends the email again.parameters:- name: x-spree-api-keyin: header@@ -8874,7 +8877,7 @@ paths:id: dsr_UkLWZg9DAJnumber: DSR1001kind: access- status: pending+ status: awaiting_confirmationrequested_at: '2026-01-15T12:00:00Z'completed_at:expires_at:@@ -8904,8 +8907,9 @@ paths:security:- api_key: []bearer_auth: []- description: Returns one of the customer's own data requests, with a download- link once the export is ready+ description: 'Returns one of the customer''s own data requests. The download+ link is never shown here: it goes only to the holder of the emailed confirmation+ token'parameters:- name: x-spree-api-keyin: header@@ -8948,6 +8952,110 @@ paths:message: Data request not foundschema:"$ref": "#/components/schemas/ErrorResponse"+ "/api/v3/store/data_requests/{token}":+ get:+ summary: Get a data request by its confirmation token+ tags:+ - Customers+ security:+ - api_key: []+ description: |+ Returns the data request the emailed confirmation token belongs to, with a+ download link once the export is ready. Needs no signed-in session, because+ the link may be opened on a device that was never signed in.++ The token stays readable after the 24-hour confirmation window, and the+ response carries the request's saved `status`. A request that is+ `awaiting_confirmation` can be confirmed only within that window: a later+ confirmation attempt returns `422` and marks the request `lapsed`. `404`+ means the token is unknown, or was voided when the customer's data was+ erased.+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: token+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: data request found+ content:+ application/json:+ example:+ id: dsr_UkLWZg9DAJ+ number: DSR1001+ kind: access+ status: pending+ requested_at: '2026-01-15T12:00:00Z'+ completed_at:+ expires_at:+ download_url:+ schema:+ "$ref": "#/components/schemas/DataRequest"+ '404':+ description: token unknown or voided+ content:+ application/json:+ example:+ error:+ code: invalid_token+ message: This confirmation link has expired or is no longer valid+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ "/api/v3/store/data_requests/{token}/confirmation":+ post:+ summary: Confirm a data request+ tags:+ - Customers+ security:+ - api_key: []+ description: |+ Confirms a data request with the token from the confirmation email, and+ starts the work. Call it when the person presses a button on the page the+ link opens, never when the page loads: some mail scanners open links and+ run the page's scripts. Confirming again returns the request as it stands.+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: token+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: data request confirmed+ content:+ application/json:+ example:+ id: dsr_UkLWZg9DAJ+ number: DSR1001+ kind: access+ status: pending+ requested_at: '2026-01-15T12:00:00Z'+ completed_at:+ expires_at:+ download_url:+ schema:+ "$ref": "#/components/schemas/DataRequest"+ '422':+ description: token not recognised, or the request has lapsed+ content:+ application/json:+ example:+ error:+ code: invalid_token+ message: This confirmation link has expired or is no longer valid+ schema:+ "$ref": "#/components/schemas/ErrorResponse""/api/v3/store/customers/me/gift_cards":get:summary: List gift cards@@ -15541,6 +15649,56 @@ components:- newsletter_subscriber- customer_groupsx-typelizer: true+ DataRequestConfirmationRequestedEvent:+ type: object+ properties:+ id:+ type: string+ number:+ type: string+ kind:+ type: string+ enum:+ - access+ - erasure+ status:+ anyOf:+ - type: string+ enum:+ - awaiting_confirmation+ - pending+ - processing+ - completed+ - failed+ - lapsed+ - type: string+ description: The values listed are the built-in ones; extensions may add+ more.+ requested_at:+ type: string+ nullable: true+ completed_at:+ type: string+ nullable: true+ email:+ type: string+ confirmation_token:+ type: string+ store_id:+ type: string+ redirect_url:+ type: string+ required:+ - id+ - number+ - kind+ - status+ - requested_at+ - completed_at+ - confirmation_token+ - store_id+ x-typelizer: trueDataRequestEvent:type: objectproperties:@@ -15557,10 +15715,12 @@ components:anyOf:- type: stringenum:+ - awaiting_confirmation- pending- processing- completed- failed+ - lapsed- type: stringdescription: The values listed are the built-in ones; extensions may addmore.@@ -15594,10 +15754,12 @@ components:anyOf:- type: stringenum:+ - awaiting_confirmation- pending- processing- completed- failed+ - lapsed- type: stringdescription: The values listed are the built-in ones; extensions may addmore.@@ -23826,6 +23988,12 @@ components:current_password:type: stringdescription: Required for `erasure`.+ redirect_url:+ type: string+ format: uri+ description: The storefront page the confirmation link opens, with the token+ appended. Ignored unless it matches one of the store's allowed origins.+ example: https://myshop.com/account/data-requests/confirmCreateNewsletterSubscriberParams:type: objectproperties:@@ -24355,10 +24523,12 @@ components:requested_at: datetimestatus:enum:+ - awaiting_confirmation- pending- processing- completed- failed+ - lapsedupdated_at: datetimeassociations: {}scopes:diff --git a/docs/developer/core-concepts/data-privacy.mdx b/docs/developer/core-concepts/data-privacy.mdxindex 8606e771bb..534ac3495f 100644--- a/docs/developer/core-concepts/data-privacy.mdx+++ b/docs/developer/core-concepts/data-privacy.mdx@@ -19,23 +19,107 @@ A person has the right to a copy of their data and the right to have iterased. Both arrive as a `Spree::DataRequest`, which records that the requestwas made and how it was answered.-```http-POST /api/v3/store/customers/me/data_requests { "kind": "access" }-POST /api/v3/store/customers/me/data_requests { "kind": "erasure", "current_password": "..." }+A customer opens a request from their account:++<CodeGroup>++```typescript Store SDK+await client.customer.dataRequests.create(+ { kind: 'access', redirect_url: 'https://myshop.com/account/data-requests/confirm' },+ { token: customerJwt },+)++await client.customer.dataRequests.create(+ { kind: 'erasure', current_password: '...', redirect_url: 'https://myshop.com/account/data-requests/confirm' },+ { token: customerJwt },+)```-The response is `202 Accepted` with a pending request. Building the export-reads a person's whole history, so it happens in the background and the file-arrives by email as a signed link that expires. Asking again while a request-of the same kind is still in flight returns the one already running, rather-than starting a second.+```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/customers/me/data_requests' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Authorization: Bearer <customer JWT>' \+ -H 'Content-Type: application/json' \+ -d '{ "kind": "access", "redirect_url": "https://myshop.com/account/data-requests/confirm" }'+```++</CodeGroup>-An erasure request needs the account password, because erasure cannot be+The response is `202 Accepted` with the request `awaiting_confirmation`.+Nothing happens yet. A request also covers the guest orders placed at the+account's email address, so it waits until it is confirmed from that address.++An erasure request also needs the account password, because erasure cannot beundone and an unattended session should not be enough to trigger it.+### Confirming a request++Spree publishes `data_request.confirmation_requested`, carrying a confirmation+token. `spree_emails` sends the person a link to `redirect_url` with+`?token=` appended. A storefront that sends its own emails subscribes a webhook+endpoint to the event instead: it carries a live credential, so only an+endpoint that names it receives it (see [Webhooks](/developer/core-concepts/webhooks)).+`redirect_url` is used only when it matches one of the store's allowed origins.+Otherwise the link falls back to the store's storefront URL.++The page the link opens confirms the request when the person presses a button:++<CodeGroup>++```typescript Store SDK+await client.dataRequests.confirm(tokenFromTheLink)+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/data_requests/<token>/confirmation' \+ -H 'X-Spree-Api-Key: pk_xxx'+```++</CodeGroup>++<Warning>+Confirm on a button press, never when the page loads. Some mail scanners open+links and run the page's scripts, and an erasure cannot be undone.+</Warning>++A request left unconfirmed for 24 hours lapses. Asking again while a request of+the same kind is waiting for confirmation, or still being worked on, returns the+existing one. A waiting request also gets its email sent again.++### Receiving the export++Building the export reads a person's whole history, so it happens in the+background. When it is ready, `spree_emails` sends a download link to the same+address. The link expires after seven days.++The download link is shown only to whoever holds the confirmation token, never+to the signed-in account. A storefront that sends its own emails reads it with+the token:++<CodeGroup>++```typescript Store SDK+const dataRequest = await client.dataRequests.get(tokenFromTheLink)+// dataRequest.download_url is set once dataRequest.status is 'completed'+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/data_requests/<token>' \+ -H 'X-Spree-Api-Key: pk_xxx'+```++</CodeGroup>++<Note>+A store without `spree_emails`, and without a webhook handler for+`data_request.confirmation_requested`, cannot complete a request a customer+raises. Requests staff raise in the admin still work.+</Note>+Most requests never reach the storefront. They arrive as email to themerchant, often from someone who can no longer sign in, so the same two-actions exist in the admin:+actions exist in the admin. Staff confirm who they are dealing with+themselves, so these requests need no email confirmation:```httpGET /api/v3/admin/customers/:id/exportdiff --git a/docs/developer/core-concepts/webhooks.mdx b/docs/developer/core-concepts/webhooks.mdxindex aba60d7cce..0388c2a05d 100644--- a/docs/developer/core-concepts/webhooks.mdx+++ b/docs/developer/core-concepts/webhooks.mdx@@ -147,7 +147,7 @@ The `subscriptions` array accepts exact event names and wildcard patterns:| `['order.*', 'payment.*', 'fulfillment.fulfilled']` | Multiple patterns || `[]` or `['*']` | All events |-An event that carries a credential — `customer.password_reset_requested`, which includes a reset token — is never matched by a pattern. An endpoint receives it only when it names it, and naming it needs the permission to manage customers. Password reset requests for staff and sellers are never sent to webhooks: Spree emails those itself.+An event that carries a credential — `customer.password_reset_requested`, which includes a reset token, and `data_request.confirmation_requested`, which includes the token that confirms a customer's data request — is never matched by a pattern. An endpoint receives it only when it names it, and naming it needs the permission to manage customers. Password reset requests for staff and sellers are never sent to webhooks: Spree emails those itself.To see every event you can subscribe to, including those your installed extensions add, list them:diff --git a/docs/developer/customization/email-variables.mdx b/docs/developer/customization/email-variables.mdxindex 1eac84e5bf..a8b570b4d4 100644--- a/docs/developer/customization/email-variables.mdx+++ b/docs/developer/customization/email-variables.mdx@@ -19,6 +19,7 @@ These are the emails your customers receive. Every one of their templates receiv| `spree/digital_asset_mailer/files_ready_email` | `order`, `downloads`, `resend` || `spree/customer_mailer/password_reset_email` | `customer`, `reset_url` || `spree/customer_mailer/data_export_email` | `download_url`, `expires_at` |+| `spree/customer_mailer/data_request_confirmation_email` | `kind`, `confirmation_url`, `expires_at` || `spree/newsletter_mailer/email_confirmation` | `confirmation_url` || `spree/company_mailer/invitation_email` | `company`, `accept_url` |@@ -31,9 +32,10 @@ These are the emails your customers receive. Every one of their templates receiv| `payment_url` | Where the customer pays for the order. || `reset_url` | The password reset link, carrying its token. || `accept_url` | The link that accepts the invitation, carrying its token. |-| `confirmation_url` | The link that confirms the subscription, carrying its token. |+| `confirmation_url` | The link that confirms the subscription or data request, carrying its token. |+| `kind` | What a data request asks for: `access` (a copy of the data) or `erasure`. || `download_url` | The signed link to the customer's data export. |-| `expires_at` | When the data export link stops working. |+| `expires_at` | When the data export or confirmation link stops working. || `downloads` | Each file bought: `filename`, `url` (carrying its token) and `expires_at`. |## Objectsdiff --git a/docs/developer/deployment/emails.mdx b/docs/developer/deployment/emails.mdxindex f16fa44aaf..c00e2070f4 100644--- a/docs/developer/deployment/emails.mdx+++ b/docs/developer/deployment/emails.mdx@@ -30,7 +30,7 @@ Spree Backend → Webhook POST → Storefront → render email → send via Rese1. **Create a webhook endpoint** in Spree Admin → Settings → Developer → Webhooks:- **URL:** `https://your-storefront.com/api/webhooks/spree`- - **Events:** `order.placed`, `order.canceled`, `order.fulfilled`, `customer.password_reset_requested`+ - **Events:** `order.placed`, `order.canceled`, `order.fulfilled`, `customer.password_reset_requested`, `data_request.confirmation_requested`2. **Configure the storefront** with the webhook secret and email provider:@@ -53,6 +53,7 @@ Spree Backend → Webhook POST → Storefront → render email → send via Rese| `order.canceled` | Cancellation notice || `order.fulfilled` | Shipping notification with tracking link || `customer.password_reset_requested` | Password reset link |+| `data_request.confirmation_requested` | Link that confirms a customer's data request |<Note>Spree 6.0 also sends the pre-6.0 names `order.completed` and `order.shipped` as deprecated aliases until 6.1. Subscribe the endpoint to the new names only — subscribing to both makes Spree deliver both events.diff --git a/docs/developer/storefront/nextjs/emails.mdx b/docs/developer/storefront/nextjs/emails.mdxindex 5e6a720356..e67dd7bb58 100644--- a/docs/developer/storefront/nextjs/emails.mdx+++ b/docs/developer/storefront/nextjs/emails.mdx@@ -20,6 +20,7 @@ Email templates are React components in `src/lib/emails/`:| `order-canceled.tsx` | `order.canceled` | Cancellation notice with items || `shipment-shipped.tsx` | `order.fulfilled` | Tracking number and link || `password-reset.tsx` | `customer.password_reset_requested` | Reset button and fallback link |+| `data-request-confirmation.tsx` | `data_request.confirmation_requested` | Link that confirms a customer's data request |Customize a template by editing its file directly — they use `@react-email/components` for email-safe layout primitives.@@ -63,6 +64,7 @@ const handler = createWebhookHandler({'order.canceled': handleOrderCanceled,'order.fulfilled': handleOrderFulfilled,'customer.password_reset_requested': handlePasswordReset,+ 'data_request.confirmation_requested': handleDataRequestConfirmation,},})```@@ -76,7 +78,7 @@ To add a new email type:## Setup-1. **Create a webhook endpoint** in Spree Admin → Settings → Developer → Webhooks. Subscribe to `order.placed`, `order.canceled`, `order.fulfilled`, and `customer.password_reset_requested`, and copy the secret key into `SPREE_WEBHOOK_SECRET`.+1. **Create a webhook endpoint** in Spree Admin → Settings → Developer → Webhooks. Subscribe to `order.placed`, `order.canceled`, `order.fulfilled`, `customer.password_reset_requested` and `data_request.confirmation_requested`, and copy the secret key into `SPREE_WEBHOOK_SECRET`.2. **Receive webhooks locally.** Expose the storefront with a public URL so Spree can reach it — the simplest option is a [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/):diff --git a/docs/plans/5.4-6.0-eu-legal-compliance.md b/docs/plans/5.4-6.0-eu-legal-compliance.mdindex 48a8acb453..3d03a3de8a 100644--- a/docs/plans/5.4-6.0-eu-legal-compliance.md+++ b/docs/plans/5.4-6.0-eu-legal-compliance.md@@ -30,7 +30,7 @@ Cookie consent is left to storefront implementations (Next.js, etc.) — not par7. **Withdrawal period is tracked per-Market in 6.0.** In 5.4, it's a store-level preference. In 6.0, the Market model (from channels-catalogs-b2b plan) owns it, since different markets may have different legal requirements.-8. **Subject access requests are asynchronous and leave a record** (2026-09-02). `POST /store/customers/me/data_requests` enqueues a job, answers `202`, and emails a signed link to a privately-stored file; a second request while one is pending returns the pending one instead of starting a second build. A new `Spree::DataRequest` model carries it, not a `Spree::Export` subclass — that pipeline is admin-owned, CSV-only and store-scoped, and a customer's JSON subject export is none of those. The pending record is the cooldown, so no separate rate limit is needed. This resolves Open Question 1.+8. **Subject access requests are asynchronous and leave a record** (2026-09-02, amended 2026-10-19). `POST /store/customers/me/data_requests` answers `202` with the request `awaiting_confirmation`; it is confirmed from a link emailed to the account's address (`POST /store/data_requests/:token/confirmation`), which enqueues a job that emails a signed link to a privately-stored file. The request reaches guest orders placed at that address, so the address confirms it first. A second request while one is waiting or pending returns that one instead of starting a second build, and a waiting one sends its email again. A new `Spree::DataRequest` model carries it, not a `Spree::Export` subclass — that pipeline is admin-owned, CSV-only and store-scoped, and a customer's JSON subject export is none of those. The pending record is the cooldown for the build; the create endpoint is rate limited only because a waiting request resends its email. This resolves Open Question 1.9. **Both subject-request endpoints ship in open source, at both ends** (2026-09-02). `POST /admin/customers/:id/anonymize` and `GET /admin/customers/:id/export` are core, gated on `write_customers`. Erasure and access requests arrive as email to the merchant, from people who often cannot log in and from guests who never had an account — a self-service-only build serves the rare case and leaves the ordinary one to the Rails console. Enterprise keeps the request queue, the Art. 12(3) deadline clock, the audit trail, automated retention and per-market legal text. This resolves Open Question 2.@@ -684,6 +684,7 @@ bundle exec rake spree:price_history:seed # Snapshot existing prices- **The withdrawal deadline is read, never stored.** It derives from the order's market and its fulfillments' `delivered_at`; a persisted copy would go stale the moment a parcel is delivered. A partly-delivered order has **not** started its clock — the period runs from the last parcel, so anything reading a max over the delivered subset would expire the right while the buyer is still waiting.- **Never record consent that was not given.** A `ConsentRecord` is evidence; writing one because an account was created, rather than because a box was ticked, manufactures proof of an agreement the buyer never made. Terms consent is recorded only when the caller passes `terms_of_service`.- **The export download link is a credential.** It must not enter an event payload, a webhook body or the delivery log — `Spree::Api::V3::DataRequestEventSerializer` is what `data_request.*` publishes, and `download_url` is on the webhook redaction list as defence in depth.+- **A customer's own data request is not acted on until it is confirmed from its email address.** Staff-raised requests skip confirmation. The confirmation token travels only in `data_request.confirmation_requested`, a credential event (`credential: 'write_customers'`), and `confirmation_token` is on the webhook redaction list. The download link goes only to whoever holds the token, never to the account's own session.## Open Questionsdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 3f0e38f164..836415deff 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,13 @@+## 2026-10-19: A self-service data request is confirmed from its email address before Spree acts on it++**Context:** A customer's own access or erasure request covers the guest orders, carts, cards and consent recorded at the account's email address, so that someone who checked out as a guest and registered later receives their whole history. Spree never confirms that an account's email address belongs to the account holder, so a request should not reach rows at that address until the address itself confirms it.++**Decision:** A request a customer raises for themselves starts as `awaiting_confirmation` and does nothing until it is confirmed from the address it names. Spree publishes `data_request.confirmation_requested` with a confirmation token, gated with `credential: 'write_customers'` like `customer.password_reset_requested`, and its key joins `Spree::WebhookPayloadRedaction::SENSITIVE_PAYLOAD_KEYS`, so the webhook delivery log stores `[REDACTED]` in its place. `spree_emails` sends the link, and a headless storefront can send it from a webhook instead. As in the newsletter and password reset flows, the request takes a `redirect_url`, kept only when it matches one of the store's allowed origins, and the email links to `<redirect_url>?token=…`, falling back to the store's storefront URL. That page acts only when the person presses its button, which calls `POST /api/v3/store/data_requests/:token/confirmation`: some mail scanners open links and run the page's scripts, so a page that confirmed on load could erase data nobody approved. Only then is the request queued, and it matches guest rows by email as before. The download link is given only to whoever holds the token, by email or through the token-addressed read; the account's own session sees the status and never the link. After 24 hours an unconfirmed request can no longer be confirmed, and it is marked `lapsed` the next time the customer asks, follows the link or is erased. Erasure still asks for the account password. Staff-raised requests skip confirmation, since staff check identity themselves. A verified-email flag on the customer was rejected for now: it would add state that every email change must clear, and no other feature needs it yet. Limiting self-service requests to rows the account owns was also rejected, because a former guest would then never receive their full history.++**Consequences:** Every self-service request costs one extra email, and an access request sends a second one when the file is ready. A store with neither `spree_emails` nor a handler for the event cannot complete self-service requests; staff requests still work, and the docs say so. `download_url` stays in the Store API response but is `null` on the account's own reads, which matters only to 6.0 prerelease adopters, since no stable release had data requests. The storefront gains the confirmation page in the same change, since it has no page for the newsletter's links either and a link to the storefront's home page would confirm nothing; and `spree_emails` gains a customer email that merchants can edit. `awaiting_confirmation` and `lapsed` join `DataRequestStatus`.++**Plan amended:** `5.4-6.0-eu-legal-compliance.md` (Key Decision 8 and the Constraints on Current Work).+## 2026-10-17: Certificates point at their exemption reason**Context:** Certificates stored a copy of their reason's code, so a code had to be locked once any certificate used it. A new store's seeded reasons could then never be switched to Avalara's codes, and finding a reason's certificates meant joining through companies on a copied string.diff --git a/packages/admin-sdk/src/types/filters.generated.ts b/packages/admin-sdk/src/types/filters.generated.tsindex 7aa6465f50..25f0340656 100644--- a/packages/admin-sdk/src/types/filters.generated.ts+++ b/packages/admin-sdk/src/types/filters.generated.ts@@ -120,7 +120,7 @@ export type DataRequestFields = Filter.RangeFilters<'completed_at' | 'created_at& Filter.TextFilters<'email' | 'number'>& Filter.IdFilters<'id'>& Filter.EnumFilters<'kind', 'access' | 'erasure'>- & Filter.EnumFilters<'status', 'pending' | 'processing' | 'completed' | 'failed'>+ & Filter.EnumFilters<'status', 'awaiting_confirmation' | 'pending' | 'processing' | 'completed' | 'failed' | 'lapsed'>export type DeliveryFields = Filter.TextFilters<'carrier' | 'tracking_number'>& Filter.RangeFilters<'created_at' | 'updated_at'>diff --git a/packages/admin-sdk/src/types/generated/DataRequest.ts b/packages/admin-sdk/src/types/generated/DataRequest.tsindex 9ecf9b7b5a..2d3b3e9b53 100644--- a/packages/admin-sdk/src/types/generated/DataRequest.ts+++ b/packages/admin-sdk/src/types/generated/DataRequest.ts@@ -1,4 +1,4 @@-// Typelizer digest b8871e4d9ccee9bcb5855a65f27eb024+// Typelizer digest beb2d0c28b620fff4d37468e01447d09//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Customer, DataRequestStatus} from '@/types'diff --git a/packages/admin-sdk/src/types/generated/Enums.ts b/packages/admin-sdk/src/types/generated/Enums.tsindex 204eb4fa65..3580e46669 100644--- a/packages/admin-sdk/src/types/generated/Enums.ts+++ b/packages/admin-sdk/src/types/generated/Enums.ts@@ -1,11 +1,11 @@-// Typelizer digest 447e80c3166e5f6fecb839a9bbf3bf2e+// Typelizer digest 9aff97510b37a847b605a9f369433d6a//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type ActorKind = 'admin_user' | 'api_key' | (string & {});export type ClaimStatus = 'open' | 'approved' | 'resolved' | 'denied' | 'canceled' | (string & {});export type { CountryCode } from '@spree/sdk-core';export type { CurrencyCode } from '@spree/sdk-core';-export type DataRequestStatus = 'pending' | 'processing' | 'completed' | 'failed' | (string & {});+export type DataRequestStatus = 'awaiting_confirmation' | 'pending' | 'processing' | 'completed' | 'failed' | 'lapsed' | (string & {});export type { DimensionUnit } from '@spree/sdk-core';export type ExchangeStatus = 'requested' | 'approved' | 'received' | 'fulfilled' | 'canceled' | (string & {});export type FeeKind = 'surcharge' | 'handling' | 'gift_wrap' | 'cod' | 'payment' | 'duty' | 'exchange' | (string & {});diff --git a/packages/dashboard/src/lib/email-template-variables.ts b/packages/dashboard/src/lib/email-template-variables.tsindex 8ad9e9290d..ceb87a90f6 100644--- a/packages/dashboard/src/lib/email-template-variables.ts+++ b/packages/dashboard/src/lib/email-template-variables.ts@@ -154,6 +154,11 @@ export const EMAIL_TEMPLATE_VARIABLES: Record<string, EmailTemplateVariable[]> =variable('reset_url'),],'spree.customer_mailer.data_export_email': [variable('download_url'), variable('expires_at')],+ 'spree.customer_mailer.data_request_confirmation_email': [+ variable('kind'),+ variable('confirmation_url'),+ variable('expires_at'),+ ],'spree.newsletter_mailer.email_confirmation': [variable('confirmation_url')],'spree.company_mailer.invitation_email': [variable('company', ['name'] as const satisfies FieldsOf<Company>),diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 27c3c3a8ef..ddd75f3885 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -6517,6 +6517,7 @@"digital_asset_mailer_files_ready_email": "التنزيلات جاهزة","customer_mailer_password_reset_email": "إعادة تعيين كلمة المرور","customer_mailer_data_export_email": "تصدير البيانات الشخصية جاهز",+ "customer_mailer_data_request_confirmation_email": "تأكيد طلب البيانات","newsletter_mailer_email_confirmation": "تأكيد النشرة البريدية","company_mailer_invitation_email": "دعوة إلى شركة","spree_base_mailer": "تخطيط الرسائل",@@ -6620,7 +6621,8 @@"reset_url": "رابط اختيار كلمة مرور جديدة.","download_url": "رابط تنزيل ملف التصدير.","expires_at": "متى يتوقف الرابط عن العمل.",- "confirmation_url": "الرابط الذي يؤكد الاشتراك.",+ "confirmation_url": "الرابط الذي يؤكد الاشتراك أو طلب البيانات.",+ "kind": "ما إذا كان طلب البيانات يطلب نسخة (access) أو محوًا (erasure).","company": "الشركة التي دُعي إليها العميل.","accept_url": "الرابط الذي يقبل الدعوة.","store": "متجرك: الاسم والروابط والشعار والهوية البصرية.",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex a89bc91244..4613e8d5a0 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -6473,6 +6473,7 @@"digital_asset_mailer_files_ready_email": "Downloads bereit","customer_mailer_password_reset_email": "Passwort zurücksetzen","customer_mailer_data_export_email": "Export persönlicher Daten bereit",+ "customer_mailer_data_request_confirmation_email": "Bestätigung der Datenanfrage","newsletter_mailer_email_confirmation": "Newsletter-Bestätigung","company_mailer_invitation_email": "Firmeneinladung","spree_base_mailer": "E-Mail-Layout",@@ -6576,7 +6577,8 @@"reset_url": "Der Link zum Festlegen eines neuen Passworts.","download_url": "Der Link zum Herunterladen des Exports.","expires_at": "Wann der Link nicht mehr funktioniert.",- "confirmation_url": "Der Link, der das Abonnement bestätigt.",+ "confirmation_url": "Der Link, der das Abonnement oder die Datenanfrage bestätigt.",+ "kind": "Ob die Datenanfrage eine Kopie (access) oder die Löschung (erasure) verlangt.","company": "Die Firma, zu der der Kunde eingeladen ist.","accept_url": "Der Link, der die Einladung annimmt.","store": "Ihr Shop: Name, Links, Logo und Branding.",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex bd06d49273..15f66a8203 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -6473,6 +6473,7 @@"digital_asset_mailer_files_ready_email": "Downloads ready","customer_mailer_password_reset_email": "Password reset","customer_mailer_data_export_email": "Personal data export ready",+ "customer_mailer_data_request_confirmation_email": "Data request confirmation","newsletter_mailer_email_confirmation": "Newsletter confirmation","company_mailer_invitation_email": "Company invitation","spree_base_mailer": "Email layout",@@ -6576,7 +6577,8 @@"reset_url": "The link to choose a new password.","download_url": "The link to download the export.","expires_at": "When the link stops working.",- "confirmation_url": "The link that confirms the subscription.",+ "confirmation_url": "The link that confirms the subscription or data request.",+ "kind": "Whether the data request asks for a copy (access) or for erasure (erasure).","company": "The company the customer is invited to.","accept_url": "The link that accepts the invitation.","store": "Your store: name, links, logo and branding.",diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 5a77843433..0c2128e518 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -6474,6 +6474,7 @@"digital_asset_mailer_files_ready_email": "Descargas listas","customer_mailer_password_reset_email": "Restablecer contraseña","customer_mailer_data_export_email": "Exportación de datos personales lista",+ "customer_mailer_data_request_confirmation_email": "Confirmación de solicitud de datos","newsletter_mailer_email_confirmation": "Confirmación del boletín","company_mailer_invitation_email": "Invitación de empresa","spree_base_mailer": "Diseño del correo",@@ -6577,7 +6578,8 @@"reset_url": "El enlace para elegir una nueva contraseña.","download_url": "El enlace para descargar la exportación.","expires_at": "Cuándo deja de funcionar el enlace.",- "confirmation_url": "El enlace que confirma la suscripción.",+ "confirmation_url": "El enlace que confirma la suscripción o la solicitud de datos.",+ "kind": "Si la solicitud de datos pide una copia (access) o la eliminación (erasure).","company": "La empresa a la que se invita al cliente.","accept_url": "El enlace que acepta la invitación.","store": "Tu tienda: nombre, enlaces, logotipo y marca.",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex bd458a862f..609e406798 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -6474,6 +6474,7 @@"digital_asset_mailer_files_ready_email": "Téléchargements prêts","customer_mailer_password_reset_email": "Réinitialisation du mot de passe","customer_mailer_data_export_email": "Export des données personnelles prêt",+ "customer_mailer_data_request_confirmation_email": "Confirmation de demande de données","newsletter_mailer_email_confirmation": "Confirmation de la newsletter","company_mailer_invitation_email": "Invitation d'entreprise","spree_base_mailer": "Mise en page des e-mails",@@ -6577,7 +6578,8 @@"reset_url": "Le lien pour choisir un nouveau mot de passe.","download_url": "Le lien pour télécharger l'export.","expires_at": "Quand le lien cesse de fonctionner.",- "confirmation_url": "Le lien qui confirme l'abonnement.",+ "confirmation_url": "Le lien qui confirme l'abonnement ou la demande de données.",+ "kind": "Si la demande de données porte sur une copie (access) ou sur l'effacement (erasure).","company": "L'entreprise à laquelle le client est invité.","accept_url": "Le lien qui accepte l'invitation.","store": "Votre boutique : nom, liens, logo et image de marque.",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 54a460cb91..2a04dcf627 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -6543,6 +6543,7 @@"digital_asset_mailer_files_ready_email": "Pliki gotowe do pobrania","customer_mailer_password_reset_email": "Reset hasła","customer_mailer_data_export_email": "Eksport danych osobowych gotowy",+ "customer_mailer_data_request_confirmation_email": "Potwierdzenie wniosku o dane","newsletter_mailer_email_confirmation": "Potwierdzenie newslettera","company_mailer_invitation_email": "Zaproszenie do firmy","spree_base_mailer": "Układ e-maili",@@ -6646,7 +6647,8 @@"reset_url": "Link do ustawienia nowego hasła.","download_url": "Link do pobrania eksportu.","expires_at": "Kiedy link przestaje działać.",- "confirmation_url": "Link potwierdzający subskrypcję.",+ "confirmation_url": "Link potwierdzający subskrypcję lub wniosek o dane.",+ "kind": "Czy wniosek o dane dotyczy kopii (access), czy usunięcia (erasure).","company": "Firma, do której zaproszono klienta.","accept_url": "Link przyjmujący zaproszenie.","store": "Twój sklep: nazwa, linki, logo i wygląd marki.",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 53f3496f08..e407cbc825 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -6459,6 +6459,7 @@"digital_asset_mailer_files_ready_email": "下载已就绪","customer_mailer_password_reset_email": "重置密码","customer_mailer_data_export_email": "个人数据导出已就绪",+ "customer_mailer_data_request_confirmation_email": "数据请求确认","newsletter_mailer_email_confirmation": "订阅确认","company_mailer_invitation_email": "公司邀请","spree_base_mailer": "邮件布局",@@ -6562,7 +6563,8 @@"reset_url": "设置新密码的链接。","download_url": "下载导出文件的链接。","expires_at": "链接失效的时间。",- "confirmation_url": "确认订阅的链接。",+ "confirmation_url": "确认订阅或数据请求的链接。",+ "kind": "数据请求是索取副本(access)还是要求删除(erasure)。","company": "邀请客户加入的公司。","accept_url": "接受邀请的链接。","store": "您的店铺:名称、链接、标志和品牌样式。",diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.tsindex 6305ea54a9..f9f96569a9 100644--- a/packages/sdk/src/store-client.ts+++ b/packages/sdk/src/store-client.ts@@ -35,6 +35,7 @@ import type {Country,CreateCartParams,CreateClaimParams,+ CreateDataRequestParams,CreateNewsletterSubscriberParams,CreatePaymentParams,CreatePaymentSessionParams,@@ -45,6 +46,7 @@ import type {CreditCard,Currency,Customer,+ DataRequest,DeliveryMethod,DigitalLink,DigitalLinkFilters,@@ -1053,6 +1055,42 @@ export class StoreClient {this.request<void>('DELETE', `/customers/me/addresses/${id}`, options),},+ /**+ * Nested resource: GDPR data requests (a copy of the customer's data, or its erasure)+ */+ dataRequests: {+ /**+ * List the customer's data requests, most recent first+ */+ list: (+ params?: ListParams,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<DataRequest>> =>+ this.request<PaginatedResponse<DataRequest>>('GET', '/customers/me/data_requests', {+ ...options,+ params: transformListParams({ ...params }),+ }),++ /**+ * Get one of the customer's data requests. Never carries the download+ * link: that goes only to the holder of the emailed confirmation token.+ */+ get: (id: string, options?: RequestOptions): Promise<DataRequest> =>+ this.request<DataRequest>('GET', `/customers/me/data_requests/${id}`, options),++ /**+ * Open a data request. Nothing happens until it is confirmed from the+ * link emailed to the customer's address, which opens `redirect_url`+ * with the token appended (see `client.dataRequests.confirm`). Erasure+ * needs `current_password`.+ */+ create: (params?: CreateDataRequestParams, options?: RequestOptions): Promise<DataRequest> =>+ this.request<DataRequest>('POST', '/customers/me/data_requests', {+ ...options,+ body: params,+ }),+ },+/*** Nested resource: Credit Cards*/@@ -1233,6 +1271,31 @@ export class StoreClient {},}+ // ============================================+ // Data Requests (by confirmation token)+ // ============================================++ readonly dataRequests = {+ /**+ * Get the data request a confirmation token belongs to, with the download+ * link once the export is ready. Needs no signed-in customer.+ */+ get: (token: string, options?: RequestOptions): Promise<DataRequest> =>+ this.request<DataRequest>('GET', `/data_requests/${encodeURIComponent(token)}`, options),++ /**+ * Confirm a data request with the token from the confirmation email, and+ * start the work. Call it when the person presses a button, never on page+ * load: some mail scanners open links and run the page's scripts.+ */+ confirm: (token: string, options?: RequestOptions): Promise<DataRequest> =>+ this.request<DataRequest>(+ 'POST',+ `/data_requests/${encodeURIComponent(token)}/confirmation`,+ options,+ ),+ }+// ============================================// Password Resets// ============================================diff --git a/packages/sdk/src/types/filters.generated.ts b/packages/sdk/src/types/filters.generated.tsindex 425b935f6b..8451feb38f 100644--- a/packages/sdk/src/types/filters.generated.ts+++ b/packages/sdk/src/types/filters.generated.ts@@ -40,7 +40,7 @@ export type DataRequestFields = Filter.RangeFilters<'completed_at' | 'created_at& Filter.TextFilters<'email' | 'number'>& Filter.IdFilters<'id'>& Filter.EnumFilters<'kind', 'access' | 'erasure'>- & Filter.EnumFilters<'status', 'pending' | 'processing' | 'completed' | 'failed'>+ & Filter.EnumFilters<'status', 'awaiting_confirmation' | 'pending' | 'processing' | 'completed' | 'failed' | 'lapsed'>export type DeliveryMethodFields = Filter.BooleanFilters<'available_to_sellers' | 'storefront_visible'>& Filter.RangeFilters<'created_at' | 'updated_at'>diff --git a/packages/sdk/src/types/generated/DataRequest.ts b/packages/sdk/src/types/generated/DataRequest.tsindex e78858c897..dbfa47f9e2 100644--- a/packages/sdk/src/types/generated/DataRequest.ts+++ b/packages/sdk/src/types/generated/DataRequest.ts@@ -1,4 +1,4 @@-// Typelizer digest 17ec6823633f64d817251ffe2f578b89+// Typelizer digest bcf82011390ed00470315f02b5b367e4//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {DataRequestStatus} from '@/types'diff --git a/packages/sdk/src/types/generated/DataRequestConfirmationRequestedEvent.ts b/packages/sdk/src/types/generated/DataRequestConfirmationRequestedEvent.tsnew file mode 100644index 0000000000..641a367d93--- /dev/null+++ b/packages/sdk/src/types/generated/DataRequestConfirmationRequestedEvent.ts@@ -0,0 +1,19 @@+// Typelizer digest d31f214c2ea06eae46b8db85a2a87cec+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {DataRequestStatus} from '@/types'++interface DataRequestConfirmationRequestedEvent {+ id: string;+ number: string;+ kind: 'access' | 'erasure';+ status: DataRequestStatus;+ requested_at: string | null;+ completed_at: string | null;+ email: string;+ confirmation_token: string;+ store_id: string;+ redirect_url?: string;+}++export default DataRequestConfirmationRequestedEvent;diff --git a/packages/sdk/src/types/generated/DataRequestEvent.ts b/packages/sdk/src/types/generated/DataRequestEvent.tsindex ecec1047f4..9a211fb057 100644--- a/packages/sdk/src/types/generated/DataRequestEvent.ts+++ b/packages/sdk/src/types/generated/DataRequestEvent.ts@@ -1,4 +1,4 @@-// Typelizer digest 55fca4f27ef38d07ceee0a884f493e98+// Typelizer digest b78893ceac5cfb91c7e0630561ca731f//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {DataRequestStatus} from '@/types'diff --git a/packages/sdk/src/types/generated/Enums.ts b/packages/sdk/src/types/generated/Enums.tsindex 5b05bd1859..dcb2a9222f 100644--- a/packages/sdk/src/types/generated/Enums.ts+++ b/packages/sdk/src/types/generated/Enums.ts@@ -1,10 +1,10 @@-// Typelizer digest d6c31229658dad8df6d30a1b0cd15713+// Typelizer digest 9441893a974e59fb804b75fcf039b4f6//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type ClaimStatus = 'open' | 'approved' | 'resolved' | 'denied' | 'canceled' | (string & {});export type { CountryCode } from '@spree/sdk-core';export type { CurrencyCode } from '@spree/sdk-core';-export type DataRequestStatus = 'pending' | 'processing' | 'completed' | 'failed' | (string & {});+export type DataRequestStatus = 'awaiting_confirmation' | 'pending' | 'processing' | 'completed' | 'failed' | 'lapsed' | (string & {});export type { DimensionUnit } from '@spree/sdk-core';export type ExchangeStatus = 'requested' | 'approved' | 'received' | 'fulfilled' | 'canceled' | (string & {});export type FeeKind = 'surcharge' | 'handling' | 'gift_wrap' | 'cod' | 'payment' | 'duty' | 'exchange' | (string & {});diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.tsindex 0166711ce3..a568e5f645 100644--- a/packages/sdk/src/types/generated/index.ts+++ b/packages/sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest 38b1abb78a641134b2e2551384a19f9d+// Typelizer digest 6cf1c023876556016d0774360f3e76b3//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { ClaimStatus, CountryCode, CurrencyCode, DataRequestStatus, DimensionUnit, ExchangeStatus, FeeKind, FulfillmentStatus, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, LocaleCode, PaymentSessionStatus, PaymentSetupSessionStatus, PaymentStatus, ProductSubmissionStatus, ReturnStatus, ShippingLabelStatus, WeightUnit } from './Enums'@@ -21,6 +21,7 @@ export type { default as Currency } from './Currency'export type { default as CustomField } from './CustomField'export type { default as CustomerGroup } from './CustomerGroup'export type { default as Customer } from './Customer'+export type { default as DataRequestConfirmationRequestedEvent } from './DataRequestConfirmationRequestedEvent'export type { default as DataRequestEvent } from './DataRequestEvent'export type { default as DataRequest } from './DataRequest'export type { default as DeliveryMethod } from './DeliveryMethod'diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.tsindex 2aafca0e8f..b9e2b9d654 100644--- a/packages/sdk/src/types/index.ts+++ b/packages/sdk/src/types/index.ts@@ -45,6 +45,7 @@ export type {Customer,CustomerGroup,CustomField,+ DataRequest,Delivery,DeliveryMethod,DeliveryRate,diff --git a/packages/sdk/src/types/params/CreateDataRequestParams.ts b/packages/sdk/src/types/params/CreateDataRequestParams.tsindex 67f63bd8b2..e052b785de 100644--- a/packages/sdk/src/types/params/CreateDataRequestParams.ts+++ b/packages/sdk/src/types/params/CreateDataRequestParams.ts@@ -5,4 +5,9 @@ export type CreateDataRequestParams = {kind?: 'access' | 'erasure'/** Required for `erasure`. */current_password?: string+ /**+ * The storefront page the confirmation link opens, with the token appended. Ignored unless it+ * matches one of the store's allowed origins.+ */+ redirect_url?: string}diff --git a/packages/sdk/src/webhooks/generated/events.ts b/packages/sdk/src/webhooks/generated/events.tsindex 10889ee783..f041a02e86 100644--- a/packages/sdk/src/webhooks/generated/events.ts+++ b/packages/sdk/src/webhooks/generated/events.ts@@ -5,6 +5,7 @@ import type {Company,CompanyInvitation,Customer,+ DataRequestConfirmationRequestedEvent,DataRequestEvent,Delivery,DigitalAsset,@@ -91,6 +92,8 @@ export interface WebhookEventMap {/** Carries a live credential: delivered only to endpoints that name this event. */'customer.password_reset_requested': PasswordResetRequestedEvent'data_request.completed': DataRequestEvent+ /** Carries a live credential: delivered only to endpoints that name this event. */+ 'data_request.confirmation_requested': DataRequestConfirmationRequestedEvent'data_request.created': DataRequestEvent'data_request.deleted': DataRequestEvent'data_request.updated': DataRequestEventdiff --git a/packages/sdk/src/webhooks/generated/schemas.ts b/packages/sdk/src/webhooks/generated/schemas.tsindex a412b3479c..bb3c830c67 100644--- a/packages/sdk/src/webhooks/generated/schemas.ts+++ b/packages/sdk/src/webhooks/generated/schemas.ts@@ -6,6 +6,7 @@ import {CompanySchema,CompanyInvitationSchema,CustomerSchema,+ DataRequestConfirmationRequestedEventSchema,DataRequestEventSchema,DeliverySchema,DigitalAssetSchema,@@ -85,6 +86,7 @@ type WebhookEventName =| 'customer.password_reset'| 'customer.password_reset_requested'| 'data_request.completed'+ | 'data_request.confirmation_requested'| 'data_request.created'| 'data_request.deleted'| 'data_request.updated'@@ -339,6 +341,7 @@ export const webhookEventSchemas: Readonly<Record<WebhookEventName, z.ZodType>>'customer.password_reset': CustomerSchema,'customer.password_reset_requested': PasswordResetRequestedEventSchema,'data_request.completed': DataRequestEventSchema,+ 'data_request.confirmation_requested': DataRequestConfirmationRequestedEventSchema,'data_request.created': DataRequestEventSchema,'data_request.deleted': DataRequestEventSchema,'data_request.updated': DataRequestEventSchema,diff --git a/packages/sdk/src/zod/generated/DataRequestConfirmationRequestedEvent.ts b/packages/sdk/src/zod/generated/DataRequestConfirmationRequestedEvent.tsnew file mode 100644index 0000000000..e581db0d76--- /dev/null+++ b/packages/sdk/src/zod/generated/DataRequestConfirmationRequestedEvent.ts@@ -0,0 +1,17 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';++export const DataRequestConfirmationRequestedEventSchema = z.object({+ id: z.string(),+ number: z.string(),+ kind: z.string(),+ status: z.string(),+ requested_at: z.string().nullable(),+ completed_at: z.string().nullable(),+ email: z.string(),+ confirmation_token: z.string(),+ store_id: z.string(),+ redirect_url: z.string().optional(),+});++export type DataRequestConfirmationRequestedEvent = z.infer<typeof DataRequestConfirmationRequestedEventSchema>;diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.tsindex 2dd239652b..32197d1799 100644--- a/packages/sdk/src/zod/generated/index.ts+++ b/packages/sdk/src/zod/generated/index.ts@@ -19,6 +19,7 @@ export { CustomFieldSchema, type CustomField } from './CustomField';export { CustomerSchema, type Customer } from './Customer';export { CustomerGroupSchema, type CustomerGroup } from './CustomerGroup';export { DataRequestSchema, type DataRequest } from './DataRequest';+export { DataRequestConfirmationRequestedEventSchema, type DataRequestConfirmationRequestedEvent } from './DataRequestConfirmationRequestedEvent';export { DataRequestEventSchema, type DataRequestEvent } from './DataRequestEvent';export { DeliverySchema, type Delivery } from './Delivery';export { DeliveryMethodSchema, type DeliveryMethod } from './DeliveryMethod';diff --git a/packages/sdk/tests/data-requests.test.ts b/packages/sdk/tests/data-requests.test.tsnew file mode 100644index 0000000000..604f470809--- /dev/null+++ b/packages/sdk/tests/data-requests.test.ts@@ -0,0 +1,92 @@+import { HttpResponse, http } from 'msw'+import { describe, expect, it } from 'vitest'+import { createTestClient, TEST_BASE_URL } from './helpers'+import { server } from './mocks/server'++const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`++const dataRequest = {+ id: 'dsr_UkLWZg9DAJ',+ number: 'DSR1001',+ kind: 'access',+ status: 'awaiting_confirmation',+ requested_at: '2026-10-19T10:00:00Z',+ completed_at: null,+ expires_at: null,+ download_url: null,+}++describe('customer.dataRequests', () => {+ it('opens a request with the page the confirmation link opens', async () => {+ let capturedBody: Record<string, unknown> = {}+ server.use(+ http.post(`${API_PREFIX}/customers/me/data_requests`, async ({ request }) => {+ capturedBody = (await request.json()) as Record<string, unknown>+ return HttpResponse.json(dataRequest, { status: 202 })+ }),+ )++ const client = createTestClient()+ const result = await client.customer.dataRequests.create(+ { kind: 'access', redirect_url: 'https://myshop.com/account/data-requests/confirm' },+ { token: 'customer-jwt' },+ )++ expect(result.status).toBe('awaiting_confirmation')+ expect(capturedBody).toEqual({+ kind: 'access',+ redirect_url: 'https://myshop.com/account/data-requests/confirm',+ })+ })++ it('lists the customer requests', async () => {+ server.use(+ http.get(`${API_PREFIX}/customers/me/data_requests`, () =>+ HttpResponse.json({+ data: [dataRequest],+ meta: { page: 1, limit: 25, count: 1, pages: 1 },+ }),+ ),+ )++ const client = createTestClient()+ const result = await client.customer.dataRequests.list({}, { token: 'customer-jwt' })++ expect(result.data[0].id).toBe('dsr_UkLWZg9DAJ')+ })+})++describe('dataRequests', () => {+ it('confirms a request with the emailed token', async () => {+ let calledPath = ''+ server.use(+ http.post(`${API_PREFIX}/data_requests/:token/confirmation`, ({ params }) => {+ calledPath = String(params.token)+ return HttpResponse.json({ ...dataRequest, status: 'pending' })+ }),+ )++ const client = createTestClient()+ const result = await client.dataRequests.confirm('signed--token')++ expect(calledPath).toBe('signed--token')+ expect(result.status).toBe('pending')+ })++ it('reads the request, with its download link, by the emailed token', async () => {+ server.use(+ http.get(`${API_PREFIX}/data_requests/:token`, () =>+ HttpResponse.json({+ ...dataRequest,+ status: 'completed',+ download_url: 'https://api.myshop.com/api/v3/store/data_requests/abc/download',+ }),+ ),+ )++ const client = createTestClient()+ const result = await client.dataRequests.get('signed--token')++ expect(result.download_url).toContain('/download')+ })+})diff --git a/spree/api/app/controllers/concerns/spree/api/v3/allowed_redirect_url.rb b/spree/api/app/controllers/concerns/spree/api/v3/allowed_redirect_url.rbnew file mode 100644index 0000000000..04d1dbc5e5--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/allowed_redirect_url.rb@@ -0,0 +1,27 @@+module Spree+ module Api+ module V3+ # Reads the `redirect_url` a storefront passes for an emailed link.+ #+ # The link carries a live token, so a page outside the store's allowed+ # origins would hand that token to whoever named the page. An address+ # that does not match is dropped rather than refused, so callers cannot+ # probe the allow-list through error responses.+ module AllowedRedirectUrl+ extend ActiveSupport::Concern++ private++ # @return [String, nil] the redirect URL when it matches one of the+ # store's allowed origins+ def validated_redirect_url+ redirect_url = params[:redirect_url]+ return if redirect_url.blank?+ return unless current_store.allowed_origin?(redirect_url)++ redirect_url+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/customer/data_requests_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/data_requests_controller.rbindex e54a6d9afe..ffe23a2f08 100644--- a/spree/api/app/controllers/spree/api/v3/store/customer/data_requests_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customer/data_requests_controller.rb@@ -10,14 +10,30 @@ module Spree# irreversible, and an unattended session should not be enough to# trigger it — the same bar the account already applies to changing# an email address.+ #+ # Nothing happens until the request is confirmed from the link emailed+ # to the account's address (see DataRequestConfirmationsController),+ # and the export link is never shown to this session.class DataRequestsController < ResourceControllerinclude Spree::Api::V3::CurrentPasswordConfirmation+ include Spree::Api::V3::AllowedRedirectUrlprepend_before_action :require_authentication!+ # Each request while one waits sends the confirmation email again.+ rate_limit to: Spree::Api::Config[:rate_limit_password_reset],+ within: Spree::Api::Config[:rate_limit_window].seconds,+ store: Rails.cache,+ only: :create,+ with: RATE_LIMIT_RESPONSE+request_params 'CreateDataRequestParams', action: :create do |body|body.attribute :kind, :string, choices: Spree::DataRequest::KINDS, description: 'Defaults to `access`.'body.attribute :current_password, :string, description: 'Required for `erasure`.'+ body.attribute :redirect_url, :string,+ format: :uri,+ example: 'https://myshop.com/account/data-requests/confirm',+ description: "The storefront page the confirmation link opens, with the token appended. Ignored unless it matches one of the store's allowed origins."end# POST /api/v3/store/customers/me/data_requests@@ -27,7 +43,9 @@ module Spreeresult = Spree::DataRequests::Create.call(store: current_store,customer: current_user,- kind: requested_kind+ kind: requested_kind,+ confirm_by_email: true,+ redirect_url: validated_redirect_url)return render_result_error(result) unless result.success?diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rbindex ebc3d1bdab..f6d68b1894 100644--- a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb@@ -6,6 +6,8 @@ module Spreemodule Storemodule Customerclass PasswordResetsController < Store::BaseController+ include Spree::Api::V3::AllowedRedirectUrl+allow_guest_storefront_access!rate_limit to: Spree::Api::Config[:rate_limit_password_reset],within: Spree::Api::Config[:rate_limit_window].seconds,@@ -33,26 +35,13 @@ module Spree# POST /api/v3/store/password_resetsdef create- redirect_url = params[:redirect_url]-- # Validate redirect_url against allowed origins (secure by default).- # If no allowed origins are configured, redirect_url is silently ignored- # to prevent open redirect / token exfiltration attacks.- if redirect_url.present?- if current_store.allowed_origins.exists? && current_store.allowed_origin?(redirect_url)- # redirect_url is valid — keep it- else- redirect_url = nil- end- end-user = Spree.customer_class.find_by(email: params[:email])if userevent_name = 'customer.password_reset_requested'payload = user.event_payload_for(event_name,- reset_token: user.generate_token_for(:password_reset), store: current_store, redirect_url: redirect_url.presence+ reset_token: user.generate_token_for(:password_reset), store: current_store, redirect_url: validated_redirect_url)user.publish_event(event_name, payload)enddiff --git a/spree/api/app/controllers/spree/api/v3/store/data_request_confirmations_controller.rb b/spree/api/app/controllers/spree/api/v3/store/data_request_confirmations_controller.rbnew file mode 100644index 0000000000..cb89c27eb3--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/store/data_request_confirmations_controller.rb@@ -0,0 +1,23 @@+module Spree+ module Api+ module V3+ module Store+ # Confirms a request a customer raised, from the page the emailed link+ # opens. The page calls this when the person presses its button, never+ # on load: some mail scanners open links and run the page's scripts.+ class DataRequestConfirmationsController < DataRequestsController+ # POST /api/v3/store/data_requests/:token/confirmation+ def create+ return render_confirmation_invalid(status: :unprocessable_content) unless data_request++ result = Spree::DataRequests::Confirm.call(data_request: data_request)++ return render_confirmation_invalid(status: :unprocessable_content) unless result.success?++ render json: serialize_resource(result.value)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/data_requests_controller.rb b/spree/api/app/controllers/spree/api/v3/store/data_requests_controller.rbnew file mode 100644index 0000000000..509b43ee51--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/store/data_requests_controller.rb@@ -0,0 +1,56 @@+module Spree+ module Api+ module V3+ module Store+ # A data request as seen by whoever holds its confirmation token: the+ # person reading mail at the address the request names.+ #+ # Token-addressed rather than session-authenticated, because the link+ # arrives by email and may be opened on a device that was never signed+ # in. Besides the export email, it is the only place the export link is+ # shown, since the token is what reached the address the request names.+ class DataRequestsController < Store::BaseController+ allow_guest_storefront_access!++ # The response can carry a live link to a person's whole export, the+ # same credential the download itself keeps out of shared caches.+ before_action { response.headers['Cache-Control'] = 'no-store' }++ # GET /api/v3/store/data_requests/:token+ def show+ return render_confirmation_invalid(status: :not_found) unless data_request++ render json: serialize_resource(data_request)+ end++ protected++ def serializer_class+ Spree.api.data_request_serializer+ end++ def serializer_params+ super.merge(download_url_visible: true)+ end++ private++ def data_request+ return @data_request if defined?(@data_request)++ token = params[:token].presence+ @data_request = token && Spree::DataRequest.for_store(current_store).find_by_token_for(:confirmation, token)+ end++ def render_confirmation_invalid(status:)+ render_error(+ code: ERROR_CODES[:invalid_token],+ message: I18n.t('spree.data_request_errors.confirmation_invalid'),+ status: status+ )+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rbindex 54acbfbc72..29ed69a5b9 100644--- a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb@@ -3,6 +3,8 @@ module Spreemodule V3module Storeclass NewsletterSubscribersController < Store::BaseController+ include Spree::Api::V3::AllowedRedirectUrl+allow_guest_storefront_access!rate_limit to: Spree::Api::Config[:rate_limit_register],within: Spree::Api::Config[:rate_limit_window].seconds,@@ -139,17 +141,6 @@ module Spreesubscriber = Spree::NewsletterSubscriber.for_store(current_store).find_by_token_for(:unsubscribe, params[:token])subscriber if subscriber&.prefixed_id == params[:id]end-- # Drop redirect_url when it isn't in the store's allow-list — secure-by-default,- # mirrors password_resets. Returning nil omits it from the webhook payload rather- # than rejecting the request, so callers can't probe the allow-list via 4xx errors.- def validated_redirect_url- redirect_url = params[:redirect_url]- return nil if redirect_url.blank?- return nil unless current_store.allowed_origin?(redirect_url)-- redirect_url- endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/data_request_confirmation_requested_event_serializer.rb b/spree/api/app/serializers/spree/api/v3/data_request_confirmation_requested_event_serializer.rbnew file mode 100644index 0000000000..54d21cf521--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/data_request_confirmation_requested_event_serializer.rb@@ -0,0 +1,28 @@+module Spree+ module Api+ module V3+ # The event shape for `data_request.confirmation_requested`: what a+ # storefront that sends its own emails needs to ask the person to confirm+ # a request they raised. `confirmation_token` is a live credential, so+ # the event reaches only endpoints that name it.+ class DataRequestConfirmationRequestedEventSerializer < DataRequestEventSerializer+ typelize email: :string, confirmation_token: :string, store_id: :string,+ redirect_url: [:string, optional: true]++ attributes :email++ attribute :confirmation_token do+ params[:confirmation_token]+ end++ attribute :store_id do |data_request|+ data_request.store.prefixed_id+ end++ attribute :redirect_url, if: proc { params[:redirect_url].present? } do+ params[:redirect_url]+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/data_request_serializer.rb b/spree/api/app/serializers/spree/api/v3/data_request_serializer.rbindex 532a352d25..0d5470b673 100644--- a/spree/api/app/serializers/spree/api/v3/data_request_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/data_request_serializer.rb@@ -25,11 +25,15 @@ module Spreeend# Present only while the file is still there — a link the storefront- # can render without having to reason about expiry itself.- attribute :download_url do |data_request, params|+ # can render without having to reason about expiry itself — and only+ # to a caller holding the confirmation token, never to the signed-in+ # account, because the export covers guest orders placed at the address+ # the request names.+ attribute :download_url do |data_request|+ next nil unless params[:download_url_visible]next nil unless data_request.downloadable?- host = (params&.dig(:store) || data_request.store)&.formatted_url+ host = (params[:store] || data_request.store)&.formatted_urlnext nil if host.blank?Spree::Api::DataRequestUrls.download_url(data_request, host)diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 8c8b817c44..e7e78722d9 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -154,6 +154,10 @@ Spree::Core::Engine.add_routes do# Token-addressed so the emailed link works from a device that was# never signed in.get 'data_requests/:token/download', to: 'data_request_downloads#show', as: :data_request_download+ # Addressed by the confirmation token emailed to the address a+ # customer's own request names, for the same reason.+ get 'data_requests/:token', to: 'data_requests#show', as: :data_request+ post 'data_requests/:token/confirmation', to: 'data_request_confirmations#create', as: :data_request_confirmation# Legacy path — emailed and bookmarked URLs outlive the rename. Removed in 6.1.get 'digitals/:token', to: 'digital_links#show', as: :digital_downloaddiff --git a/spree/api/spec/controllers/spree/api/v3/store/customer/data_requests_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/customer/data_requests_controller_spec.rbindex 4db0e9b5a0..abfa0960a7 100644--- a/spree/api/spec/controllers/spree/api/v3/store/customer/data_requests_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/customer/data_requests_controller_spec.rb@@ -11,18 +11,50 @@ RSpec.describe Spree::Api::V3::Store::Customer::DataRequestsController, type: :cenddescribe 'POST #create' do- it 'accepts an access request without doing the work inline' do+ it 'accepts an access request and waits for it to be confirmed' dopost :create, as: :jsonexpect(response).to have_http_status(:accepted)expect(json_response['kind']).to eq('access')- expect(json_response['status']).to eq('pending')+ expect(json_response['status']).to eq('awaiting_confirmation')end- it 'queues the build' do+ # Nothing is built until someone reading mail at the account's address+ # confirms the request.+ it 'queues nothing until the request is confirmed' doexpect {post :create, as: :json- }.to have_enqueued_job(Spree::DataRequests::ProcessJob)+ }.not_to have_enqueued_job(Spree::DataRequests::ProcessJob)+ end++ describe 'the page the confirmation link opens' do+ let!(:allowed_origin) { create(:allowed_origin, store: store, origin: 'https://myshop.com') }++ def published_redirect_url+ redirect_url = :not_published+ allow_any_instance_of(Spree::DataRequest).to receive(:publish_event) do |_request, _name, payload|+ redirect_url = payload['redirect_url']+ end+ yield+ redirect_url+ end++ it 'is passed on when it matches one of the store\'s allowed origins' do+ redirect_url = published_redirect_url do+ post :create, params: { redirect_url: 'https://myshop.com/account/data-requests/confirm' }, as: :json+ end++ expect(redirect_url).to eq('https://myshop.com/account/data-requests/confirm')+ end++ it 'is dropped when it does not, so the token cannot be sent elsewhere' do+ redirect_url = published_redirect_url do+ post :create, params: { redirect_url: 'https://attacker.example/confirm' }, as: :json+ end++ expect(response).to have_http_status(:accepted)+ expect(redirect_url).to be_nil+ endendit 'returns the request already in flight rather than starting another' do@@ -79,6 +111,16 @@ RSpec.describe Spree::Api::V3::Store::Customer::DataRequestsController, type: :cdescribe 'GET #show' dolet!(:someone_elses) { create(:data_request, store: store, customer: create(:user)) }+ it 'never shows the export link to the signed-in account' do+ own_request = create(:data_request, store: store, customer: user)+ Spree::DataRequests::Fulfill.call(data_request: own_request)++ get :show, params: { id: own_request.prefixed_id }, as: :json++ expect(json_response['status']).to eq('completed')+ expect(json_response['download_url']).to be_nil+ end+it '404s on another person\'s request' doget :show, params: { id: someone_elses.prefixed_id }, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/store/data_request_confirmations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/data_request_confirmations_controller_spec.rbnew file mode 100644index 0000000000..a2f75e3afe--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/store/data_request_confirmations_controller_spec.rb@@ -0,0 +1,45 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Store::DataRequestConfirmationsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let(:data_request) { create(:data_request, :awaiting_confirmation, store: store, customer: user) }+ let(:token) { data_request.generate_token_for(:confirmation) }++ before { request.headers['X-Spree-Api-Key'] = api_key.token }++ describe 'POST #create' do+ it 'confirms the request and queues the work' do+ expect {+ post :create, params: { token: token }, as: :json+ }.to have_enqueued_job(Spree::DataRequests::ProcessJob)++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('pending')+ end++ it 'needs no signed-in session, because the link may be opened on another device' do+ post :create, params: { token: token }, as: :json++ expect(response).to have_http_status(:ok)+ end++ it 'refuses a token that does not match' do+ post :create, params: { token: 'not-a-token' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(data_request.reload).to be_awaiting_confirmation+ end++ it 'refuses a request left unconfirmed past the window' do+ data_request.update_columns(requested_at: (Spree::DataRequest::CONFIRMATION_WINDOW + 1.minute).ago)++ post :create, params: { token: token }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(data_request.reload).to be_lapsed+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/store/data_requests_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/data_requests_controller_spec.rbnew file mode 100644index 0000000000..ba5c724581--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/store/data_requests_controller_spec.rb@@ -0,0 +1,46 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Store::DataRequestsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let(:data_request) { create(:data_request, store: store, customer: user) }+ let(:token) { data_request.generate_token_for(:confirmation) }++ before { request.headers['X-Spree-Api-Key'] = api_key.token }++ describe 'GET #show' do+ it 'shows the request to whoever holds the emailed token' do+ get :show, params: { token: token }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(data_request.prefixed_id)+ end++ # The token is what reached the request's address, so this is the one+ # place the API shows the link to a finished export.+ it 'shows the export link once the file is ready' do+ Spree::DataRequests::Fulfill.call(data_request: data_request)++ get :show, params: { token: token }, as: :json++ expect(json_response['download_url']).to include(data_request.reload.download_token)+ expect(response.headers['Cache-Control']).to include('no-store')+ end++ it 'finds nothing for a token that does not match' do+ get :show, params: { token: 'not-a-token' }, as: :json++ expect(response).to have_http_status(:not_found)+ end++ it 'finds nothing for a request in another store' do+ other_request = create(:data_request, store: create(:store), customer: user)++ get :show, params: { token: other_request.generate_token_for(:confirmation) }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end+enddiff --git a/spree/api/spec/integration/spree/api/v3/store/data_requests_spec.rb b/spree/api/spec/integration/spree/api/v3/store/data_requests_spec.rbindex 907257da37..07685dc206 100644--- a/spree/api/spec/integration/spree/api/v3/store/data_requests_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/store/data_requests_spec.rb@@ -43,11 +43,14 @@ RSpec.describe 'Data Requests API', type: :request, swagger_doc: 'api-reference/security [api_key: [], bearer_auth: []]description <<~DESCOpens a GDPR request for a copy of the customer's personal data (`access`)- or its erasure (`erasure`). The work happens in the background and the- response is the pending request.+ or its erasure (`erasure`). Nothing happens until the request is confirmed+ from the link emailed to the account's address: the response is the request+ awaiting confirmation, and the link opens `redirect_url` with the+ confirmation token appended. The work then happens in the background.An erasure request requires the account password. A request of the same- kind that is still in flight is returned instead of starting a second one.+ kind that is still in flight is returned instead of starting a second one,+ and a request still awaiting confirmation sends the email again.DESCparameter name: 'x-spree-api-key', in: :header, type: :string, required: true@@ -64,7 +67,7 @@ RSpec.describe 'Data Requests API', type: :request, swagger_doc: 'api-reference/run_test! do |response|data = JSON.parse(response.body)expect(data['kind']).to eq('access')- expect(data['status']).to eq('pending')+ expect(data['status']).to eq('awaiting_confirmation')endend@@ -85,7 +88,7 @@ RSpec.describe 'Data Requests API', type: :request, swagger_doc: 'api-reference/tags 'Customers'produces 'application/json'security [api_key: [], bearer_auth: []]- description 'Returns one of the customer\'s own data requests, with a download link once the export is ready'+ description 'Returns one of the customer\'s own data requests. The download link is never shown here: it goes only to the holder of the emailed confirmation token'parameter name: 'x-spree-api-key', in: :header, type: :string, required: trueparameter name: 'Authorization', in: :header, type: :string, required: true@@ -113,4 +116,84 @@ RSpec.describe 'Data Requests API', type: :request, swagger_doc: 'api-reference/endendend++ path '/api/v3/store/data_requests/{token}' do+ get 'Get a data request by its confirmation token' do+ tags 'Customers'+ produces 'application/json'+ security [api_key: []]+ description <<~DESC+ Returns the data request the emailed confirmation token belongs to, with a+ download link once the export is ready. Needs no signed-in session, because+ the link may be opened on a device that was never signed in.++ The token stays readable after the 24-hour confirmation window, and the+ response carries the request's saved `status`. A request that is+ `awaiting_confirmation` can be confirmed only within that window: a later+ confirmation attempt returns `422` and marks the request `lapsed`. `404`+ means the token is unknown, or was voided when the customer's data was+ erased.+ DESC++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :token, in: :path, type: :string, required: true++ response '200', 'data request found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:data_request) { create(:data_request, store: store, customer: user) }+ let(:token) { data_request.generate_token_for(:confirmation) }++ schema '$ref' => '#/components/schemas/DataRequest'++ run_test!+ end++ response '404', 'token unknown or voided' do+ let(:'x-spree-api-key') { api_key.token }+ let(:token) { 'not-a-token' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/store/data_requests/{token}/confirmation' do+ post 'Confirm a data request' do+ tags 'Customers'+ produces 'application/json'+ security [api_key: []]+ description <<~DESC+ Confirms a data request with the token from the confirmation email, and+ starts the work. Call it when the person presses a button on the page the+ link opens, never when the page loads: some mail scanners open links and+ run the page's scripts. Confirming again returns the request as it stands.+ DESC++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :token, in: :path, type: :string, required: true++ response '200', 'data request confirmed' do+ let(:'x-spree-api-key') { api_key.token }+ let(:data_request) { create(:data_request, :awaiting_confirmation, store: store, customer: user) }+ let(:token) { data_request.generate_token_for(:confirmation) }++ schema '$ref' => '#/components/schemas/DataRequest'++ run_test! do |response|+ expect(JSON.parse(response.body)['status']).to eq('pending')+ end+ end++ response '422', 'token not recognised, or the request has lapsed' do+ let(:'x-spree-api-key') { api_key.token }+ let(:token) { 'not-a-token' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ endenddiff --git a/spree/api/spec/requests/spree/api/v3/store/data_requests_spec.rb b/spree/api/spec/requests/spree/api/v3/store/data_requests_spec.rbnew file mode 100644index 0000000000..142e715625--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/store/data_requests_spec.rb@@ -0,0 +1,89 @@+require 'spec_helper'++RSpec.describe 'Store data requests', type: :request do+ include_context 'API v3 Store'++ # A request reaches guest orders placed at the account's address only once+ # someone reading mail there confirms it.+ describe 'a request from an account whose address also has guest orders' do+ let(:guest_email) { '[email protected]' }+ let(:password) { 'Passw0rd!secret' }++ let!(:guest_order) do+ create(:completed_order_with_totals, store: store).tap do |order|+ order.update_columns(customer_id: nil, email: guest_email)+ end+ end++ let(:account_headers) do+ post '/api/v3/store/customers',+ params: { email: guest_email, password: password, password_confirmation: password },+ headers: api_key_headers, as: :json+ expect(response).to have_http_status(:created)++ api_key_headers.merge('Authorization' => "Bearer #{JSON.parse(response.body)['token']}")+ end++ def open_request(params)+ perform_enqueued_jobs do+ post '/api/v3/store/customers/me/data_requests', params: params, headers: account_headers, as: :json+ end+ expect(response).to have_http_status(:accepted)++ Spree::DataRequest.find_by_prefix_id!(JSON.parse(response.body)['id'])+ end++ it 'builds no export until the address confirms the request' do+ data_request = open_request(kind: 'access')++ expect(data_request.reload).to be_awaiting_confirmation+ expect(data_request.export_file).not_to be_attached+ end++ it 'leaves the guest order alone until the address confirms an erasure' do+ address1 = guest_order.ship_address.address1++ open_request(kind: 'erasure', current_password: password)++ guest_order.reload+ expect(guest_order.email).to eq(guest_email)+ expect(guest_order.ship_address.address1).to eq(address1)+ end++ it 'refuses the link once the account has moved to another address' do+ data_request = open_request(kind: 'access')+ token = data_request.generate_token_for(:confirmation)++ patch '/api/v3/store/customers/me',+ params: { email: '[email protected]', current_password: password },+ headers: account_headers, as: :json+ expect(response).to have_http_status(:ok)++ post "/api/v3/store/data_requests/#{token}/confirmation", headers: api_key_headers, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(data_request.reload).to be_lapsed+ end++ it 'hands the confirmed export to the token holder and never to the account' do+ data_request = open_request(kind: 'access')+ token = data_request.generate_token_for(:confirmation)++ perform_enqueued_jobs do+ post "/api/v3/store/data_requests/#{token}/confirmation", headers: api_key_headers, as: :json+ end+ expect(response).to have_http_status(:ok)++ get "/api/v3/store/customers/me/data_requests/#{data_request.prefixed_id}", headers: account_headers, as: :json+ expect(JSON.parse(response.body)['status']).to eq('completed')+ expect(JSON.parse(response.body)['download_url']).to be_nil++ get "/api/v3/store/data_requests/#{token}", headers: api_key_headers, as: :json+ download_url = JSON.parse(response.body)['download_url']++ get URI.parse(download_url).path+ expect(response).to have_http_status(:ok)+ expect(JSON.parse(response.body)['orders'].map { |order| order['number'] }).to include(guest_order.number)+ end+ end+enddiff --git a/spree/api/spec/serializers/spree/api/v3/data_request_event_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/data_request_event_serializer_spec.rbindex 8cbbaa4d2c..f9aa3a22a9 100644--- a/spree/api/spec/serializers/spree/api/v3/data_request_event_serializer_spec.rb+++ b/spree/api/spec/serializers/spree/api/v3/data_request_event_serializer_spec.rb@@ -40,4 +40,17 @@ RSpec.describe Spree::Api::V3::DataRequestEventSerializer doit 'is what the model publishes, not the store serializer' doexpect(data_request.event_serializer_class).to eq(described_class)end++ # What a storefront that sends its own emails needs to ask for confirmation,+ # and still nothing that opens the export.+ it 'gives the confirmation request the token and the page the link opens' do+ payload = data_request.event_payload_for(+ 'data_request.confirmation_requested',+ confirmation_token: 'live-token', redirect_url: 'https://shop.example.com/confirm'+ )++ expect(payload).to include('confirmation_token' => 'live-token', 'redirect_url' => 'https://shop.example.com/confirm',+ 'email' => data_request.email, 'store_id' => store.prefixed_id)+ expect(payload.to_s).not_to include(data_request.reload.download_token)+ endenddiff --git a/spree/core/app/models/concerns/spree/webhook_payload_redaction.rb b/spree/core/app/models/concerns/spree/webhook_payload_redaction.rbindex 8484a78e1f..7735204ecf 100644--- a/spree/core/app/models/concerns/spree/webhook_payload_redaction.rb+++ b/spree/core/app/models/concerns/spree/webhook_payload_redaction.rb@@ -32,6 +32,7 @@ module Spreereset_tokenunsubscribe_tokenverification_token+ confirmation_tokendownload_urlexternal_client_secretclient_secretdiff --git a/spree/core/app/models/spree/data_request.rb b/spree/core/app/models/spree/data_request.rbindex fd3b6f74f5..f96e0d6e9e 100644--- a/spree/core/app/models/spree/data_request.rb+++ b/spree/core/app/models/spree/data_request.rb@@ -20,9 +20,12 @@ module Spreepublishes_lifecycle_eventspublishes_event :completed+ publishes_event :confirmation_requested,+ serializer: 'Spree::Api::V3::DataRequestConfirmationRequestedEventSerializer',+ credential: 'write_customers'include Spree::HasStatus- has_status :pending, :processing, :completed, :failed, default: :pending+ has_status :awaiting_confirmation, :pending, :processing, :completed, :failed, :lapsed, default: :pendingACCESS = 'access'.freezeERASURE = 'erasure'.freeze@@ -33,11 +36,23 @@ module Spree# about them is not left lying around.DEFAULT_EXPIRY = 7.days+ # How long a request a customer raised waits for confirmation from its+ # email address before it lapses.+ CONFIRMATION_WINDOW = 24.hours+# Addresses the finished export. Plaintext like the digital-link token:# the URL is the credential, it is only ever sent to the address that# asked, and it stops working when the request expires.has_secure_token :download_token+ # Proves that whoever confirms reads mail at the address the request+ # names. Bound to+ # the download token, so an erasure, which clears it, voids every link+ # already sent.+ generates_token_for :confirmation do+ download_token+ end+belongs_to :customer, class_name: Spree.customer_class.to_s# Null when the subject asked for it themselves; set when staff acted on a# request that arrived by email.@@ -52,6 +67,8 @@ module Spreescope :access, -> { where(kind: ACCESS) }scope :erasure, -> { where(kind: ERASURE) }scope :in_progress, -> { with_status(:pending, :processing) }+ scope :confirmable, -> { awaiting_confirmation.where(requested_at: CONFIRMATION_WINDOW.ago..) }+ scope :past_confirmation_window, -> { awaiting_confirmation.where(requested_at: ...CONFIRMATION_WINDOW.ago) }scope :recent_first, -> { order(requested_at: :desc) }self.whitelisted_ransackable_attributes = %w[number kind status email requested_at completed_at]@@ -89,6 +106,22 @@ module Spreeexpires_at.present? && expires_at.past?end+ # Whether the request is still waiting for confirmation, within the window+ # to receive it, and still names the account's address.+ # @return [Boolean]+ def confirmable?+ awaiting_confirmation? && requested_at > CONFIRMATION_WINDOW.ago && addressed_to_customer?+ end++ # Whether the request names the address the account has now. The work+ # matches guest rows by the account's address when it runs, so a request+ # for an address the account has since left would reach rows it never+ # named.+ # @return [Boolean]+ def addressed_to_customer?+ customer.present? && email.to_s.casecmp?(customer.email.to_s)+ end+privatedef set_defaultsdiff --git a/spree/core/app/services/spree/data_requests/confirm.rb b/spree/core/app/services/spree/data_requests/confirm.rbnew file mode 100644index 0000000000..14fc639de9--- /dev/null+++ b/spree/core/app/services/spree/data_requests/confirm.rb@@ -0,0 +1,37 @@+module Spree+ module DataRequests+ # Confirms a request the customer raised, from the link emailed to the+ # address it names, and queues the work.+ #+ # Confirming again is answered with the request as it stands, so a second+ # click on the same link changes nothing.+ class Confirm+ prepend Spree::ServiceModule::Base++ # @param data_request [Spree::DataRequest]+ # @return [Spree::ServiceModule::Result] the confirmed request+ def call(data_request:)+ newly_confirmed = false++ data_request.with_lock do+ newly_confirmed = data_request.confirmable?++ if newly_confirmed+ data_request.update!(status: 'pending')+ elsif data_request.awaiting_confirmation?+ data_request.update!(status: 'lapsed')+ end+ end++ if data_request.lapsed?+ data_request.errors.add(:base, I18n.t('spree.data_request_errors.confirmation_invalid'))+ return failure(data_request)+ end++ Spree::DataRequests::ProcessJob.perform_later(data_request.prefixed_id) if newly_confirmed++ success(data_request)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/data_requests/create.rb b/spree/core/app/services/spree/data_requests/create.rbindex d10c379507..53f0489b02 100644--- a/spree/core/app/services/spree/data_requests/create.rb+++ b/spree/core/app/services/spree/data_requests/create.rb@@ -7,9 +7,15 @@ module Spree# whole history, and a customer holding the button down should not be able# to queue a hundred of them. It is also the honest answer — the request# they already made is still being worked on.+ #+ # A request the customer raised themselves waits for confirmation from its+ # email address instead of being queued, because it reaches guest orders+ # placed at that address. Asking again while it waits sends the email again.class Createprepend Spree::ServiceModule::Base+ CONFIRMATION_EVENT = 'data_request.confirmation_requested'.freeze+# @param store [Spree::Store]# @param customer [Spree::Customer]# @param kind [String] Spree::DataRequest::ACCESS or ERASURE@@ -19,8 +25,12 @@ module Spree# caller fulfils the request itself — the admin export renders the file# inline for a waiting staffer, and queueing would additionally email# the customer a copy of something they did not ask for+ # @param confirm_by_email [Boolean] hold the request until it is+ # confirmed from its email address; true for the customer's own requests+ # @param redirect_url [String, nil] the storefront page the confirmation+ # link opens, already checked against the store's allowed origins# @return [Spree::ServiceModule::Result]- def call(store:, customer:, kind:, requested_by: nil, process: true)+ def call(store:, customer:, kind:, requested_by: nil, process: true, confirm_by_email: false, redirect_url: nil)# Nothing useful is left to answer with: an export would return the# tombstone and email a link to an address that no longer receives,# and a second erasure has nothing to erase.@@ -38,7 +48,9 @@ module Spree# of the same person's whole history; taking the lock closes it without# a partial unique index, which MySQL does not support.customer.with_lock do- existing = in_flight_request(store: store, customer: customer, kind: kind)+ lapse_unconfirmed_requests(store: store, customer: customer, kind: kind, staff_request: !confirm_by_email)+ existing = in_flight_request(store: store, customer: customer, kind: kind,+ include_unconfirmed: confirm_by_email)unless existingdata_request = Spree::DataRequest.new(@@ -46,20 +58,27 @@ module Spreecustomer: customer,kind: kind.to_s,email: customer.email,- requested_by: requested_by+ requested_by: requested_by,+ status: confirm_by_email ? 'awaiting_confirmation' : 'pending')data_request.saveendend- return success(existing) if existing- return failure(data_request) unless data_request.persisted?+ return failure(data_request) if data_request && !data_request.persisted?- # Enqueued after the lock is released: the job may start immediately,- # and it should not contend for the row this flow still holds.- Spree::DataRequests::ProcessJob.perform_later(data_request.prefixed_id) if process+ request = existing || data_request- success(data_request)+ # Both happen after the lock is released: the job may start at once and+ # should not contend for the row this flow holds, and the email must+ # not go out before the row is committed.+ if request.awaiting_confirmation?+ request_confirmation(request, redirect_url: redirect_url)+ elsif data_request && process+ Spree::DataRequests::ProcessJob.perform_later(data_request.prefixed_id)+ end++ success(request)endprivate@@ -67,10 +86,39 @@ module Spree# Only the person's own requests. A staff member exporting from the admin# opens their own row and answers it inline, and handing that back here# would close the customer's request with a file they can never download.- def in_flight_request(store:, customer:, kind:)- Spree::DataRequest.where(store_id: store.id, customer_id: customer.id, kind: kind.to_s,- requested_by_id: nil).- in_progress.recent_first.first+ # A request still waiting for confirmation is returned only to the+ # customer: staff have checked who they are dealing with, so theirs+ # proceeds on its own row (see lapse_unconfirmed_requests).+ def in_flight_request(store:, customer:, kind:, include_unconfirmed:)+ requests = Spree::DataRequest.where(store_id: store.id, customer_id: customer.id, kind: kind.to_s,+ requested_by_id: nil)+ open_requests = include_unconfirmed ? requests.in_progress.or(requests.confirmable) : requests.in_progress++ open_requests.recent_first.first+ end++ # Lapses what can no longer be confirmed: requests past the window, and+ # requests naming an address the account has since moved away from, so+ # asking again emails the current address. A staff request of the same+ # kind replaces the customer's unconfirmed one, which would otherwise+ # run the same work a second time once confirmed.+ def lapse_unconfirmed_requests(store:, customer:, kind:, staff_request:)+ unconfirmed = Spree::DataRequest.where(store_id: store.id, customer_id: customer.id).awaiting_confirmation+ stale = unconfirmed.past_confirmation_window.or(unconfirmed.where.not(email: customer.email))+ stale = stale.or(unconfirmed.where(kind: kind.to_s)) if staff_request++ stale.find_each { |data_request| data_request.update!(status: 'lapsed') }+ end++ # The token travels in a credential event, which reaches only webhook+ # endpoints that name it and keeps the token out of the delivery log.+ def request_confirmation(data_request, redirect_url:)+ payload = data_request.event_payload_for(+ CONFIRMATION_EVENT,+ confirmation_token: data_request.generate_token_for(:confirmation),+ redirect_url: redirect_url.presence+ )+ data_request.publish_event(CONFIRMATION_EVENT, payload)endendenddiff --git a/spree/core/app/workflows/spree/customers/anonymize.rb b/spree/core/app/workflows/spree/customers/anonymize.rbindex 18d4466b54..752af6bd2f 100644--- a/spree/core/app/workflows/spree/customers/anonymize.rb+++ b/spree/core/app/workflows/spree/customers/anonymize.rb@@ -407,7 +407,9 @@ module Spreeend# The token goes too, so a link already emailed stops resolving rather- # than waiting out its expiry.+ # than waiting out its expiry. Confirmation links are bound to it, so+ # a request still waiting for one can never be confirmed.+ requests.awaiting_confirmation.update_all(status: 'lapsed', updated_at: Time.current)requests.update_all(email: customer.email,download_token: nil,diff --git a/spree/core/app/workflows/spree/data_requests/fulfill.rb b/spree/core/app/workflows/spree/data_requests/fulfill.rbindex 772170ebe4..328f354cba 100644--- a/spree/core/app/workflows/spree/data_requests/fulfill.rb+++ b/spree/core/app/workflows/spree/data_requests/fulfill.rb@@ -36,6 +36,7 @@ module Spreesuperstep :ensure_pending+ step :ensure_addressed_to_customerstep :mark_processingrun_hooks :before_fulfill@@ -56,6 +57,15 @@ module Spreefailure(data_request, I18n.t('spree.data_request_errors.not_pending'))end+ # An account already erased has a replaced address by design, and+ # erase_customer counts that as done.+ def ensure_addressed_to_customer+ customer = data_request.customer+ return if customer.nil? || customer.anonymized? || data_request.addressed_to_customer?++ failure(data_request, I18n.t('spree.data_request_errors.address_changed'))+ end+def mark_processingdata_request.update!(status: 'processing')end@@ -78,21 +88,25 @@ module Spree# anonymizer starts after the check and finishes its attachment scan# before this attaches, stranding a full personal-data file it will# never see.+ #+ # The address is checked again under the same lock, so it cannot change+ # between the check and the export reading it.return attach_export unless customer- refused = false+ refusal = nilcustomer.with_lock do- if customer.reload.anonymized?- refused = true+ customer.reload+ if customer.anonymized?+ refusal = 'spree.data_request_errors.already_anonymized'+ elsif !data_request.addressed_to_customer?+ refusal = 'spree.data_request_errors.address_changed'elseattach_exportendend- return unless refused-- failure(data_request, I18n.t('spree.data_request_errors.already_anonymized'))+ failure(data_request, I18n.t(refusal)) if refusalenddef attach_exportdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 95638f4ef0..d7ebfdbaf1 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -774,7 +774,9 @@ en:anonymize_failed: The erasure could not be completed and nothing was changedcustomers: Customersdata_request_errors:+ address_changed: The account's email address changed after this request was madealready_anonymized: This customer's personal data has already been erased+ confirmation_invalid: This confirmation link has expired or is no longer validdownload_unavailable: This download link has expired or is no longer validnot_pending: This request has already been processeddefault: Defaultdiff --git a/spree/core/lib/spree/testing_support/factories/data_request_factory.rb b/spree/core/lib/spree/testing_support/factories/data_request_factory.rbindex f1f4c70e2a..3e02424ca8 100644--- a/spree/core/lib/spree/testing_support/factories/data_request_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/data_request_factory.rb@@ -9,6 +9,10 @@ FactoryBot.define dokind { Spree::DataRequest::ERASURE }end+ trait :awaiting_confirmation do+ status { 'awaiting_confirmation' }+ end+trait :completed dostatus { 'completed' }completed_at { Time.current }diff --git a/spree/core/spec/lib/spree/events/catalog_spec.rb b/spree/core/spec/lib/spree/events/catalog_spec.rbindex 3094a4e163..92a172cd62 100644--- a/spree/core/spec/lib/spree/events/catalog_spec.rb+++ b/spree/core/spec/lib/spree/events/catalog_spec.rb@@ -88,8 +88,9 @@ RSpec.describe Spree::Events::Catalog doexpect(entries.map(&:name)).to include('order.created', 'order.placed', 'fulfillment.fulfilled', 'customer.anonymized')end- it 'marks the customer password reset request as a credential event' do- expect(Spree::Events.catalog.credential_events.map(&:name)).to eq(['customer.password_reset_requested'])+ it 'marks the events carrying a customer credential' do+ expect(Spree::Events.catalog.credential_events.map(&:name)).+ to contain_exactly('customer.password_reset_requested', 'data_request.confirmation_requested')endit 'never forwards staff or seller password reset requests to webhooks' dodiff --git a/spree/core/spec/models/concerns/spree/webhook_payload_redaction_spec.rb b/spree/core/spec/models/concerns/spree/webhook_payload_redaction_spec.rbindex 956d4bc6f5..561fed805b 100644--- a/spree/core/spec/models/concerns/spree/webhook_payload_redaction_spec.rb+++ b/spree/core/spec/models/concerns/spree/webhook_payload_redaction_spec.rb@@ -42,6 +42,18 @@ describe Spree::WebhookPayloadRedaction doexpect(described_class.merge(payload, secrets)).to eq(original)end+ it 'redacts the data request confirmation_token' do+ original = {+ 'name' => 'data_request.confirmation_requested',+ 'data' => { 'email' => '[email protected]', 'confirmation_token' => 'live-token' }+ }++ payload, secrets = described_class.split(original)++ expect(payload['data']['confirmation_token']).to eq(placeholder)+ expect(secrets).to eq('data.confirmation_token' => 'live-token')+ end+# Payment session events carry live gateway credentials: a client secret# confirms a payment and an ephemeral key lists a customer's saved cards.it 'redacts payment session credentials nested inside external_data' dodiff --git a/spree/core/spec/services/spree/data_requests/confirm_spec.rb b/spree/core/spec/services/spree/data_requests/confirm_spec.rbnew file mode 100644index 0000000000..726d7bd46d--- /dev/null+++ b/spree/core/spec/services/spree/data_requests/confirm_spec.rb@@ -0,0 +1,37 @@+require 'spec_helper'++RSpec.describe Spree::DataRequests::Confirm do+ let(:store) { @default_store }+ let(:data_request) { create(:data_request, :awaiting_confirmation, store: store) }++ subject(:result) { described_class.call(data_request: data_request) }++ it 'opens the request and queues the work' do+ expect { result }.to have_enqueued_job(Spree::DataRequests::ProcessJob).with(data_request.prefixed_id)+ expect(result).to be_success+ expect(data_request.reload).to be_pending+ end++ it 'changes nothing when the link is followed again' do+ described_class.call(data_request: data_request)++ expect { result }.not_to have_enqueued_job(Spree::DataRequests::ProcessJob)+ expect(result).to be_success+ end++ it 'refuses a request whose account has moved to another address' do+ data_request.customer.update_columns(email: '[email protected]')++ expect { result }.not_to have_enqueued_job(Spree::DataRequests::ProcessJob)+ expect(result).to be_failure+ expect(data_request.reload).to be_lapsed+ end++ it 'refuses a request left unconfirmed past the window' do+ data_request.update_columns(requested_at: (Spree::DataRequest::CONFIRMATION_WINDOW + 1.minute).ago)++ expect { result }.not_to have_enqueued_job(Spree::DataRequests::ProcessJob)+ expect(result).to be_failure+ expect(data_request.reload).to be_lapsed+ end+enddiff --git a/spree/core/spec/services/spree/data_requests/create_spec.rb b/spree/core/spec/services/spree/data_requests/create_spec.rbindex 59518274f0..91c8fa0733 100644--- a/spree/core/spec/services/spree/data_requests/create_spec.rb+++ b/spree/core/spec/services/spree/data_requests/create_spec.rb@@ -45,6 +45,75 @@ RSpec.describe Spree::DataRequests::Create doendend+ # The request reaches guest orders placed at the account's address, so+ # nothing happens until the address confirms it.+ describe 'a request the customer raised themselves' do+ subject(:result) do+ described_class.call(store: store, customer: customer, kind: Spree::DataRequest::ACCESS,+ confirm_by_email: true, redirect_url: 'https://shop.example.com/confirm')+ end++ it 'waits for confirmation instead of queueing the work' do+ expect { result }.not_to have_enqueued_job(Spree::DataRequests::ProcessJob)+ expect(result.value).to be_awaiting_confirmation+ end++ it 'asks the address to confirm it' do+ expect_any_instance_of(Spree::DataRequest).to receive(:publish_event).+ with('data_request.confirmation_requested', anything)++ result+ end++ it 'asks again rather than opening a second request while one waits' do+ first = result.value++ expect_any_instance_of(Spree::DataRequest).to receive(:publish_event).+ with('data_request.confirmation_requested', anything)++ again = described_class.call(store: store, customer: customer, kind: Spree::DataRequest::ACCESS,+ confirm_by_email: true)++ expect(again.value).to eq(first)+ end++ it 'lapses a request left unconfirmed past the window and opens a new one' do+ first = result.value+ first.update_columns(requested_at: (Spree::DataRequest::CONFIRMATION_WINDOW + 1.minute).ago)++ again = described_class.call(store: store, customer: customer, kind: Spree::DataRequest::ACCESS,+ confirm_by_email: true)++ expect(first.reload).to be_lapsed+ expect(again.value).not_to eq(first)+ expect(again.value).to be_awaiting_confirmation+ end++ # Staff have checked who they are dealing with, so their request proceeds+ # on its own row and does not wait on the customer's unconfirmed one.+ it 'does not hold up a request staff raise while it waits' do+ waiting = result.value++ staff_request = described_class.call(store: store, customer: customer, kind: Spree::DataRequest::ACCESS,+ requested_by: create(:admin_user))++ expect(staff_request.value).not_to eq(waiting)+ expect(staff_request.value).to be_pending+ expect(waiting.reload).to be_lapsed+ end++ it 'emails the current address once the account has moved to another' do+ waiting = result.value+ customer.update_columns(email: '[email protected]')++ again = described_class.call(store: store, customer: customer, kind: Spree::DataRequest::ACCESS,+ confirm_by_email: true)++ expect(waiting.reload).to be_lapsed+ expect(again.value.email).to eq('[email protected]')+ end+ end+describe 'a customer whose data has already been erased' dobefore { Spree::Customers::Anonymize.call(customer: customer, store: store) }diff --git a/spree/core/spec/workflows/spree/customers/anonymize_spec.rb b/spree/core/spec/workflows/spree/customers/anonymize_spec.rbindex 93894b2b5a..768d095511 100644--- a/spree/core/spec/workflows/spree/customers/anonymize_spec.rb+++ b/spree/core/spec/workflows/spree/customers/anonymize_spec.rb@@ -646,6 +646,16 @@ RSpec.describe Spree::Customers::Anonymize doexpect(data_request.reload).to be_completedexpect(data_request.requested_at).to be_presentend++ it 'voids the link of a request still waiting for confirmation' do+ waiting = create(:data_request, :awaiting_confirmation, store: store, customer: customer)+ token = waiting.generate_token_for(:confirmation)++ result++ expect(waiting.reload).to be_lapsed+ expect(Spree::DataRequest.find_by_token_for(:confirmation, token)).to be_nil+ endend# The access export discloses all three as this person's data, so leavingdiff --git a/spree/core/spec/workflows/spree/data_requests/fulfill_spec.rb b/spree/core/spec/workflows/spree/data_requests/fulfill_spec.rbindex 93c1628da4..3589f43a92 100644--- a/spree/core/spec/workflows/spree/data_requests/fulfill_spec.rb+++ b/spree/core/spec/workflows/spree/data_requests/fulfill_spec.rb@@ -20,6 +20,25 @@ RSpec.describe Spree::DataRequests::Fulfill doexpect(data_request.reload.export_file).not_to be_attachedend+ # Guest rows are matched by the account's address when the work runs, so a+ # request for an address the account has since left must not be answered.+ it 'refuses a request whose account has moved to another address' do+ data_request+ customer.update_columns(email: '[email protected]')++ expect(result).to be_failure+ expect(data_request.reload.export_file).not_to be_attached+ end++ it 'checks the address again under the lock the export is built in' do+ allow_any_instance_of(described_class).to receive(:ensure_addressed_to_customer)+ data_request+ customer.update_columns(email: '[email protected]')++ expect(result).to be_failure+ expect(data_request.reload.export_file).not_to be_attached+ end+it 'completes the request' doexpect(result).to be_successexpect(data_request.reload).to be_completed@@ -92,6 +111,14 @@ RSpec.describe Spree::DataRequests::Fulfill doexpect(data_request.reload.export_file).not_to be_attachedend+ it 'refuses a request whose account has moved to another address' do+ data_request+ customer.update_columns(email: '[email protected]')++ expect(described_class.call(data_request: data_request)).to be_failure+ expect(customer.reload.anonymized_at).to be_nil+ end+# Staff may have erased this person while their own request sat in the# queue. The outcome they asked for has happened, so the request is# answered — recording a failure would leave someone whose data IS gonediff --git a/spree/emails/app/mailers/spree/customer_mailer.rb b/spree/emails/app/mailers/spree/customer_mailer.rbindex 91aa350205..8049b58e83 100644--- a/spree/emails/app/mailers/spree/customer_mailer.rb+++ b/spree/emails/app/mailers/spree/customer_mailer.rb@@ -17,6 +17,24 @@ module Spreeendend+ # Asks the person to confirm a data request raised from their account+ # (`data_request.confirmation_requested`). The link goes to the validated+ # redirect URL when the storefront supplied one, falling back to the store's+ # storefront URL, with the confirmation token appended.+ def data_request_confirmation_email(data_request, confirmation_token, redirect_url: nil)+ @data_request = data_request+ @current_store = data_request.store+ @confirmation_url = append_token(redirect_url.presence || @current_store.storefront_url, confirmation_token)+ @expires_at = data_request.requested_at + Spree::DataRequest::CONFIRMATION_WINDOW++ with_store_locale(@current_store) do+ mail_template(+ { kind: data_request.kind, confirmation_url: @confirmation_url, expires_at: @expires_at.iso8601 },+ to: data_request.email, store_url: @current_store.storefront_url+ )+ end+ end+# The finished subject access export (GDPR Art. 15). The link is signed# and expires with the request, so the file is reachable by the person who# asked for it and not by anyone who later reads the mailbox.diff --git a/spree/emails/app/services/spree/emails/samples/data_request_confirmation.rb b/spree/emails/app/services/spree/emails/samples/data_request_confirmation.rbnew file mode 100644index 0000000000..d974bc6ac9--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/data_request_confirmation.rb@@ -0,0 +1,15 @@+module Spree+ module Emails+ module Samples+ class DataRequestConfirmation < Base+ def variables+ {+ kind: Spree::DataRequest::ACCESS,+ confirmation_url: placeholder_url('account/data-requests/confirm'),+ expires_at: Spree::DataRequest::CONFIRMATION_WINDOW.from_now.iso8601+ }+ end+ end+ end+ end+enddiff --git a/spree/emails/app/subscribers/spree/data_request_confirmation_email_subscriber.rb b/spree/emails/app/subscribers/spree/data_request_confirmation_email_subscriber.rbnew file mode 100644index 0000000000..a7301259ad--- /dev/null+++ b/spree/emails/app/subscribers/spree/data_request_confirmation_email_subscriber.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module Spree+ # Asks the person to confirm a request raised from their account, at the+ # address the request names, before Spree acts on it.+ class DataRequestConfirmationEmailSubscriber < Spree::Subscriber+ subscribes_to 'data_request.confirmation_requested'++ def handle(event)+ data_request = Spree::DataRequest.find_by_prefix_id(event.payload['id'])+ return unless data_request&.confirmable?+ return unless data_request.store.prefers_send_consumer_transactional_emails?++ CustomerMailer.data_request_confirmation_email(+ data_request,+ event.payload['confirmation_token'],+ redirect_url: event.payload['redirect_url']+ ).deliver_later+ end+ end+enddiff --git a/spree/emails/app/views/spree/customer_mailer/data_request_confirmation_email.liquid b/spree/emails/app/views/spree/customer_mailer/data_request_confirmation_email.liquidnew file mode 100644index 0000000000..8a237dc96b--- /dev/null+++ b/spree/emails/app/views/spree/customer_mailer/data_request_confirmation_email.liquid@@ -0,0 +1,22 @@+---+subject: "{{ store.name }} {% if kind == 'erasure' %}{{ 'customer_mailer.data_request_confirmation_email.erasure.subject' | t }}{% else %}{{ 'customer_mailer.data_request_confirmation_email.access.subject' | t }}{% endif %}"+---+<mj-section>+ <mj-column css-class="hero">+ {% if kind == 'erasure' %}+ <mj-text mj-class="heading">{{ 'customer_mailer.data_request_confirmation_email.erasure.subject' | t }}</mj-text>+ <mj-text mj-class="greeting">{{ 'customer_mailer.data_request_confirmation_email.greeting' | t }}</mj-text>+ <mj-text mj-class="lead">{{ 'customer_mailer.data_request_confirmation_email.erasure.instructions' | t }}</mj-text>+ {% else %}+ <mj-text mj-class="heading">{{ 'customer_mailer.data_request_confirmation_email.access.subject' | t }}</mj-text>+ <mj-text mj-class="greeting">{{ 'customer_mailer.data_request_confirmation_email.greeting' | t }}</mj-text>+ <mj-text mj-class="lead">{{ 'customer_mailer.data_request_confirmation_email.access.instructions' | t }}</mj-text>+ {% endif %}+ <mj-button href="{{ confirmation_url }}">{{ 'customer_mailer.data_request_confirmation_email.action' | t }}</mj-button>+ {% if expires_at %}+ {% assign expires_on = expires_at | date: 'long' %}+ <mj-text mj-class="note">{{ 'customer_mailer.data_request_confirmation_email.expiry_notice' | t: date: expires_on }}</mj-text>+ {% endif %}+ <mj-text mj-class="note" padding="16px 0 0">{{ 'customer_mailer.data_request_confirmation_email.ignore_notice' | t }}</mj-text>+ </mj-column>+</mj-section>diff --git a/spree/emails/config/locales/en.yml b/spree/emails/config/locales/en.ymlindex fd7eea3fbf..b6cdaefc54 100644--- a/spree/emails/config/locales/en.yml+++ b/spree/emails/config/locales/en.yml@@ -18,6 +18,17 @@ en:ignore_notice: If you did not request a copy of your data, please contact us.instructions: Your copy of the personal data we hold about you is ready. Use the button below to download it.subject: Your Data Is Ready to Download+ data_request_confirmation_email:+ access:+ instructions: We received a request for a copy of the personal data we hold about you. Once you confirm it, we will email you a link to download the file.+ subject: Confirm Your Data Request+ action: Review and Confirm+ erasure:+ instructions: We received a request to permanently erase the personal data we hold about you, including the names and addresses on your past orders. This cannot be undone.+ subject: Confirm Your Erasure Request+ expiry_notice: This link expires on %{date}.+ greeting: Hello,+ ignore_notice: If you did not make this request, you can ignore this email and nothing will happen.password_reset_email:action: Reset Passwordexpiry_notice: This password reset link will expire shortly. If you did not request this, no action is needed.diff --git a/spree/emails/lib/spree/emails/engine.rb b/spree/emails/lib/spree/emails/engine.rbindex 3f759a5b23..3bb0e2d4e1 100644--- a/spree/emails/lib/spree/emails/engine.rb+++ b/spree/emails/lib/spree/emails/engine.rb@@ -28,6 +28,7 @@ module Spree'spree/digital_asset_mailer/files_ready_email' => 'Spree::Emails::Samples::Downloads','spree/customer_mailer/password_reset_email' => 'Spree::Emails::Samples::PasswordReset','spree/customer_mailer/data_export_email' => 'Spree::Emails::Samples::DataExport',+ 'spree/customer_mailer/data_request_confirmation_email' => 'Spree::Emails::Samples::DataRequestConfirmation','spree/newsletter_mailer/email_confirmation' => 'Spree::Emails::Samples::NewsletterConfirmation','spree/company_mailer/invitation_email' => 'Spree::Emails::Samples::CompanyInvitation'}.each { |key, sample| Spree.editable_email_templates.register(key, kind: :email, sample: sample) }@@ -48,6 +49,7 @@ module SpreeSpree::NewsletterSubscriberEmailSubscriber,Spree::CustomerEmailSubscriber,Spree::DataRequestEmailSubscriber,+ Spree::DataRequestConfirmationEmailSubscriber,Spree::CompanyEmailSubscriber,Spree::DigitalAssetEmailSubscriber,Spree::SellerEmailSubscriberdiff --git a/spree/emails/lib/spree/emails/previews/customer_preview.rb b/spree/emails/lib/spree/emails/previews/customer_preview.rbindex 8f14d8b18a..864fa22f66 100644--- a/spree/emails/lib/spree/emails/previews/customer_preview.rb+++ b/spree/emails/lib/spree/emails/previews/customer_preview.rb@@ -12,6 +12,15 @@ class Spree::CustomerPreview < ActionMailer::Preview)end+ def data_request_confirmation_email+ data_request = Spree::DataRequest.new(+ store: Spree::PreviewData.store(locale), kind: Spree::DataRequest::ERASURE,+ email: Spree::PreviewData.customer.email, requested_at: Time.current+ )++ Spree::CustomerMailer.data_request_confirmation_email(data_request, 'preview-token')+ end+def data_export_emailSpree::CustomerMailer.data_export_email(Spree::DataRequest.access.with_status(:completed).last)enddiff --git a/spree/emails/spec/mailers/spree/customer_mailer_spec.rb b/spree/emails/spec/mailers/spree/customer_mailer_spec.rbindex 12ed2ceb01..23182d509d 100644--- a/spree/emails/spec/mailers/spree/customer_mailer_spec.rb+++ b/spree/emails/spec/mailers/spree/customer_mailer_spec.rb@@ -32,6 +32,46 @@ describe Spree::CustomerMailer, type: :mailer doendend+ describe '#data_request_confirmation_email' do+ let(:data_request) { create(:data_request, :awaiting_confirmation, store: store, customer: user) }+ let(:confirmation_token) { 'secret-confirmation-token' }++ it 'sends to the address the request names' do+ message = described_class.data_request_confirmation_email(data_request, confirmation_token)++ expect(message.to).to eq(['[email protected]'])+ expect(message.subject).to eq(+ "#{store.name} #{I18n.t('spree.customer_mailer.data_request_confirmation_email.access.subject')}"+ )+ end++ it 'links to the storefront URL with the token appended' do+ message = described_class.data_request_confirmation_email(data_request, confirmation_token)++ expect(message).to have_body_text("token=#{confirmation_token}")+ expect(message).to have_body_text(store.storefront_url.to_s)+ end++ it 'prefers the redirect URL the API validated' do+ message = described_class.data_request_confirmation_email(+ data_request, confirmation_token, redirect_url: 'https://storefront.example.com/account/data-requests/confirm'+ )++ expect(message).to have_body_text(+ "https://storefront.example.com/account/data-requests/confirm?token=#{confirmation_token}"+ )+ end++ it 'says plainly that an erasure cannot be undone' do+ data_request.update!(kind: Spree::DataRequest::ERASURE)++ message = described_class.data_request_confirmation_email(data_request, confirmation_token)++ expect(message.subject).to include(I18n.t('spree.customer_mailer.data_request_confirmation_email.erasure.subject'))+ expect(message).to have_body_text('This cannot be undone')+ end+ end+describe '#data_export_email' dolet(:data_request) { create(:data_request, store: store, customer: user) }diff --git a/spree/emails/spec/mailers/spree/rendered_emails_spec.rb b/spree/emails/spec/mailers/spree/rendered_emails_spec.rbindex 96ded7a08e..41768a9cc2 100644--- a/spree/emails/spec/mailers/spree/rendered_emails_spec.rb+++ b/spree/emails/spec/mailers/spree/rendered_emails_spec.rb@@ -38,6 +38,9 @@ describe 'rendered emails', type: :mailer do'refund' => Spree::ReturnMailer.refunded_email(create(:received_return, store: store)),'password reset' => Spree::CustomerMailer.password_reset_email(create(:user, first_name: payload), 'token', store),'data export' => Spree::CustomerMailer.data_export_email(create(:data_request, store: store)),+ 'data request confirmation' => Spree::CustomerMailer.data_request_confirmation_email(+ create(:data_request, :erasure, :awaiting_confirmation, store: store), 'token'+ ),'newsletter confirmation' => Spree::NewsletterMailer.email_confirmation(create(:newsletter_subscriber, store: store)),'company invitation' => Spree::CompanyMailer.invitation_email(create(:company_invitation, company: company)),'seller approved' => Spree::SellerMailer.approved_email(seller),diff --git a/spree/emails/spec/services/spree/emails/samples_spec.rb b/spree/emails/spec/services/spree/emails/samples_spec.rbindex 5483ab88d4..0150dade22 100644--- a/spree/emails/spec/services/spree/emails/samples_spec.rb+++ b/spree/emails/spec/services/spree/emails/samples_spec.rb@@ -12,7 +12,7 @@ describe 'editable email samples' doendit 'registers every customer email, the layout and the shared partials' do- expect(Spree.editable_email_templates.emails.size).to eq(11)+ expect(Spree.editable_email_templates.emails.size).to eq(12)expect(Spree.editable_email_templates['layouts/spree/base_mailer']).to be_presentexpect(Spree.editable_email_templates['spree/order_mailer/store_owner_notification_email']).to be_nilenddiff --git a/spree/emails/spec/subscribers/spree/data_request_confirmation_email_subscriber_spec.rb b/spree/emails/spec/subscribers/spree/data_request_confirmation_email_subscriber_spec.rbnew file mode 100644index 0000000000..4585bb0ff4--- /dev/null+++ b/spree/emails/spec/subscribers/spree/data_request_confirmation_email_subscriber_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::DataRequestConfirmationEmailSubscriber do+ let(:store) { @default_store }+ let(:customer) { create(:user, email: '[email protected]') }+ let(:subscriber) { described_class.new }+ let(:data_request) { create(:data_request, :awaiting_confirmation, store: store, customer: customer) }++ def mock_event(record, redirect_url: nil)+ double('Event', payload: { 'id' => record.prefixed_id, 'confirmation_token' => 'live-token',+ 'redirect_url' => redirect_url })+ end++ before do+ store.update!(preferences: store.preferences.merge(send_consumer_transactional_emails: true))+ end++ it 'emails the confirmation link to the address the request names' do+ expect(Spree::CustomerMailer).to receive(:data_request_confirmation_email).+ with(data_request, 'live-token', redirect_url: 'https://shop.example.com/confirm').+ and_return(double(deliver_later: true))++ subscriber.handle(mock_event(data_request, redirect_url: 'https://shop.example.com/confirm'))+ end++ it 'sends nothing once the request has been confirmed' do+ data_request.update!(status: 'pending')++ expect(Spree::CustomerMailer).not_to receive(:data_request_confirmation_email)++ subscriber.handle(mock_event(data_request))+ end++ it 'respects a store that does not send customer email' do+ store.update!(preferences: store.preferences.merge(send_consumer_transactional_emails: false))++ expect(Spree::CustomerMailer).not_to receive(:data_request_confirmation_email)++ subscriber.handle(mock_event(data_request))+ end++ describe 'through the registered subscribers', events: true do+ it 'emails the link when a customer opens a request' do+ perform_enqueued_jobs do+ expect {+ Spree::DataRequests::Create.call(store: store, customer: customer, kind: Spree::DataRequest::ACCESS,+ confirm_by_email: true)+ }.to change { ActionMailer::Base.deliveries.count }.by(1)+ end++ message = ActionMailer::Base.deliveries.last+ expect(message.to).to eq(['[email protected]'])+ expect(message.html_part.decoded).to include('token=')+ end+ end+end