# Security

How the UpDash Mail API protects keys, partner data and customer records, and what it guarantees about approvals. This page covers the Mail API's own controls. For the company's security program, SOC 2 and what is available on request, see [For a vendor review](vendor-review.md).

## API keys

| Property | Value |
| --- | --- |
| Format | `xm_test_` or `xm_live_` plus 32 base62 characters from a cryptographic random source |
| Stored | Only the SHA-256 hash of the full key and a 12-character display prefix (for example `xm_live_7Kq2`) |
| Created | By a partner's console admins in the [partner console](console.md#developers) (**Developers**, then **API keys**), by a key for every dealer through `POST /v1/keys` (limited keys only), or by Xcel with its admin tooling. At most 10 active keys for every dealer and 1,000 limited to some dealers, per mode |
| Dealers | Every dealer of the partner, or a list of 1 to 100 of its dealers set when the key is made and never changed. A live key cannot list a test dealer. See [Keys for one dealer](partners.md#keys-for-one-dealer). |
| Shown | Once, when it is created. Nobody can recover a lost key, Xcel included: create a new one and revoke the old one. |
| Sent as | `Authorization: Bearer <key>` on REST and MCP requests; on REST also HTTP Basic with the key as the user name and an empty password, as Lob and Stripe accept (`curl -u "$KEY:"`; a password is ignored); or pasted once on the MCP OAuth consent page (see below) |
| Failure | Malformed, unknown, revoked or mode-mismatched keys all get the same 401, Bearer or Basic, so a caller learns nothing about which |
| Logs | No log line holds the `Authorization` header, the key or a Basic password: a refused request logs its route and the code `unauthorized` |
| Revocation | A console admin revokes the key in the console (or Xcel does), which sets `revoked_at`; the key stops working on the next request, and so does every MCP OAuth token made from it |
| Usage | `last_used_at` is updated on each successful authentication |

Keys do not expire on their own. To rotate, create a new key in the console, switch your integration to it, then revoke the old one there.

Partners must keep keys server-side: never in a browser, a mobile app, a public repository or a chat transcript. Do not send the key to the signed upload URL; that URL carries its own token.

## OAuth for the MCP endpoint

MCP clients that cannot send a header connect by OAuth 2.1 ([MCP server](mcp.md#connect-by-oauth)). Consent is backed by an API key: the person pastes a partner key on Xcel's consent page, and the grant is bound to that key, its partner and its mode. The app never receives the key.

| Property | Value |
| --- | --- |
| Clients | Public only: no client secrets. Either registered dynamically (RFC 7591; at most 20 registrations per hour per address) or named by a Client ID Metadata Document URL (below). A client unused for 30 days is deleted with its codes and tokens. |
| Metadata documents | Fetched with the webhook rules: `https://` only, no credentials, local host names refused, every resolved address public, and the socket pinned to an address that passed, so DNS rebinding cannot redirect it. No redirects are followed; the fetch stops after 5 seconds or 5 KB. The document's `client_id` must equal its URL, it must not hold a client secret, and the client must be public. Fetches happen only on a cache miss and are limited to 30 per 15 minutes per address. A failure is never cached; a valid document is kept for its `Cache-Control` lifetime, between 5 minutes and 24 hours. The consent page shows the document's host as the publisher. |
| Client logos | Metadata documents only. Fetched once with the document under the same rules (PNG, JPEG, GIF or WebP, at most 100 KB; never SVG) and stored as a `data:` URL, so the consent page loads nothing remote and a logo cannot change after it is fetched. |
| Redirect URIs | `https://`, or `http://` on `localhost`, `127.0.0.1` or `[::1]`; no fragments, no credentials. Matched exactly, port included, at the authorize and token endpoints. An unknown client or an unregistered redirect URI gets an error page and is never redirected to. |
| PKCE | Required, `S256` only. A wrong verifier spends the code. |
| Codes | One use, 60 seconds. A code presented twice revokes every token the first use issued. |
| Access tokens | Opaque, 1 hour. Bound to `$API/api/mcp` (RFC 8707): each token records its resource, and the MCP route accepts only tokens for its own URL. `$API/mcp` is a second address of that route: a client may name it as the resource, and its token still records `$API/api/mcp`. The REST API never accepts them. |
| Refresh tokens | Opaque, 30 days, replaced on every use. A replaced refresh token presented again, or presented by another client, revokes its whole family (every token from the same consent). |
| Storage | Codes and tokens are stored only as SHA-256 hashes, with the partner, mode, client, key, scope, resource and expiry. The tables have row-level security and no grants, like every other table. Foreign keys tie each grant's partner and mode to its key's. |
| Dealers | A grant reaches what its key reaches, or fewer if the person names dealers on the consent page. A code passes this to its tokens and a refresh token to the next. Each use reads it inside the key's own list, so a token never reaches more than its key. |
| Scope | Exactly the mode of the key: `mail:test` or `mail:live`. A sandbox key never yields a live token (an app that asks for `mail:live` with one gets `mail:test`). A live token needs a live key, `mail:live` requested and the partner's live ordering on, checked again at every refresh. |
| Revocation | Revoking the API key revokes every token and code made from it in the same database transaction (a trigger on `api_keys`, so it holds however the key is revoked). Apps revoke a token family at `POST /oauth/revoke`. Code exchange, refresh and every access-token use also read the key and refuse a revoked one (revoking the token family), and a trigger on `oauth_codes` and `oauth_tokens` refuses a new code or token for a revoked key, locking the key row so an insert and a concurrent revocation are always ordered. A grant cannot outlive its key, even when a refresh races a revocation. |
| Issuer | `https://api.updash.com`. Authorization responses carry `iss` (RFC 9207), so a client can detect a mix-up. |

The consent page:

- Shows the name the app gave itself (marked as unverified; for a metadata document, also the host that publishes it and the stored logo), the host it sends the person back to and the scopes it asks for, and warns when that host is the person's own computer.
- Accepts only same-origin form posts, carrying a CSRF token that is bound to the exact authorization request and to the browser (an `HttpOnly`, `SameSite=Strict` cookie named after the token) and expires after 10 minutes.
- Limits key entry to 10 attempts per 15 minutes per key prefix and 30 per address, counted before the key is checked.
- Never echoes the pasted key back into the page, and logs only its 12-character prefix.
- Can narrow a grant to some of the dealers the key reaches. It cannot widen one: an unknown dealer, another partner's and one outside the key's list get the same refusal.
- Runs no scripts, loads nothing remote (images only from `data:` URLs), cannot be framed (`Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; img-src data:; form-action 'self' <the client's redirect URI>; frame-ancestors 'none'; base-uri 'none'`; `form-action` names the redirect because browsers apply it to the redirect that answers the form) and is served `noindex` and `no-store`.

Consent is backed by a pasted key today, not a console sign-in, so a person holding a limited key can grant only that key's dealers. An OAuth token can do what its key can do over MCP and nothing more. It never approves spend.

## Partner and mode scoping

- Authentication yields `{partner, mode}` from the key, or from the key behind an OAuth access token. No request field can change either.
- Every read and write of partner data is filtered by that scope. Creatives, audiences, quotes and approvals are reached only through a campaign loaded with it.
- Another partner's ids, or the other mode's ids, answer 404 `not_found`, never 403, so ids cannot be probed.
- Test and live data are disjoint: a test key never sees a live campaign and the reverse. Dealers are shared by a partner's two modes, so a test key can read them but its dealer writes only validate and change nothing. A partner's saved templates are shared by its two modes too, since a template is creative, not spend; no other partner sees them ([Your own templates](creative.md#your-own-templates)).
- The schema backs this with composite foreign keys: a campaign's dealer must belong to the campaign's partner, an approval's quote to the same campaign, and a submission's approval to the same campaign.

A credential can also be limited to some of its partner's dealers ([Keys for one dealer](partners.md#keys-for-one-dealer)):

- The list comes from the key or the token's grant, never from a request. `null` means every dealer, and only an explicit `null` does: a credential whose list is missing or cannot be read gets the 401 every bad key gets, and code that reads no list reaches no dealer.
- The check sits where campaigns and dealers are loaded and in each list query, so every route and MCP tool goes through it. A test fails when a new route or tool has not been classified.
- A dealer outside the list, and its campaigns, answer the same 404 as another partner's, so a limited key cannot learn that a dealer exists. A partner-wide action answers 403 `dealer_scope_forbidden`, which names no dealer.
- Idempotency records and submissions are kept per list of dealers, so a limited key cannot replay or detect another key's stored answer.
- Artwork uploaded without a campaign by a limited credential belongs to its key and its list of dealers, and it cannot read another's. A preview link carries that grant, signed.
- Saved templates answer `unknown_template`: they hold free HTML that may have been written for any dealer of the partner.
- An approver named with a limited credential always goes to Xcel's review on confirmation, and `domain_match` reads only that dealer's own website. Such a credential cannot change the website, which approver domain matching reads: `links.website` answers `dealer_scope_forbidden`. A key for every dealer can register an address at a website domain it set itself only when that website is the dealer's first, or has held its domain for 30 days; within 30 days of a move, the address waits for Xcel.
- A limited credential shares the partner's hourly ceiling: there is no budget per key, so one with ten dealers can spend all of it. A preview of the sample dealer counts against the credential's first dealer. At the partner's ceiling the 429 carries no figures and `GET /v1/account` gives no ceiling. When that 429 arrives still depends on what other dealers rendered.
- Review links and preview links carry their own token and are not affected. A preview link is opened with the limit of the key that made it.

## Who handles what

| Service | Used for |
| --- | --- |
| Vercel | Runs the API, the MCP server, the console and the review page. |
| Supabase | The database, and private file storage: audience files, proof PDFs and logos. Signed `upload_url`s point at a `*.supabase.co` host, so allow it if your network limits outbound traffic. |
| Mailgun | Approval, approver and console sign-in emails. |
| Stripe | Payments: the payer's bank account (ACH) or card, invoices and receipts. Card and bank numbers go straight to Stripe's own page; Xcel keeps only Stripe's ids, a label such as "Visa ending 4242", whether a card is credit or debit, and the billing address's state or country (for the card fee). Never customer rows. |
| Accutrace | Xcel ops run CASS and NCOA in it by hand, after submit. |
| Anthropic | Only when a creative request carries a `brief`: it gets the brief, the template's slot rules, and the dealer's name, city, state and disclosures, never customer rows. |
| OpenAI | Only when someone uses Make a photo with AI in the console: it gets what they typed about the picture, and the pictures it makes come back to it for a check. Never customer rows, dealer details or any other data. |
| Firecrawl | Only when someone uses **Fill from the website** on the console's Add dealers page: it gets the store's web address and reads that public page. Never customer rows or any other data. |
| UpDash (Xcel) | Live results, licensed vehicle photos and, when a dealer is linked, its profile. Mailing lists reach it for production ([UpDash production](vendor-review.md#updash-production)). |
| The printer Xcel uses | The mailable file of a live order, for production ([Print partners](vendor-review.md#print-partners)). |

Supabase encrypts all customer data at rest with AES-256 and in transit with TLS ([its security page](https://supabase.com/security)). [For a vendor review](vendor-review.md#on-request-under-nda) lists what is available on request. Ask your Xcel contact for the partner agreement.

## Database and storage access

- Row-level security is enabled on every table with no policies, and the `anon` and `authenticated` roles have no grants. Only the server, holding the Supabase service-role key, reads or writes.
- The service-role key never reaches a browser.
- Audience files and proof PDFs live in a private bucket with no storage policies. Partners upload through signed URLs that expire after 2 hours and cannot replace a file that already exists (`upsert` off), so a re-upload needs a new `upload_audience` call. Ops download files and PDFs through signed URLs that expire after 60 seconds, each a fresh redirect from a route that checks who is asking first and records them. The approver's review PDF is served by `/review/{token}/proof.pdf` itself, which checks the token. No API response or tool result holds a file URL.
- Submission is one database transaction: the submission row, the status change, the event and its webhook deliveries are written together or not at all. A row lock serializes two submits racing on one campaign, and a per-dealer advisory lock makes the dealer's monthly spend cap hold for two submits racing on one dealer.
- Idempotency records are keyed by partner, mode and key, so a sandbox request never replays a live response.

## Customer records (PII)

Customer rows are names, postal addresses, VINs, vehicle details and any custom columns the partner uploads.

- Rows never come back from the API or MCP, and never go in a JSON field or tool argument. The file goes to private storage one of three ways: a PUT to a signed URL (directly to storage), a link Xcel fetches once (`source_url`), or a `text/csv` request body to `POST /v1/campaigns/{id}/audience/import`, which the server writes to storage without logging it.
- Responses, MCP results, events, webhook payloads, error messages and server logs carry ids, counts, reason codes and row numbers only. Tests check that test names and addresses never appear in any of them.
- The one exception is the [partner console](console.md), a website for the partner's own staff: it shows the names and addresses of leads with results, from the stored mailing list, masked until a member or admin presses Reveal, and every reveal and export is logged (see [Partner console](#partner-console)).
- Error messages are written by the code and never quote a value from a file; parse errors name a row number.
- Logs are structured JSON with ids, codes and counts. Unknown errors are logged by class name, not message, because a database message can contain values.
- Proofs contain real rows, so they are never returned through the API, in HTML or PDF. Where PDFs are rendered, the review page shows only the PDF review proof, framed from `/review/{token}/proof.pdf` (the only route that may be framed, and only by this site) and downloadable with `?download=1`. Otherwise it shows the HTML preview in a sandboxed iframe with no scripts. Ops see the HTML preview on a page served with `Content-Security-Policy: sandbox` and download both PDFs from the dashboard.
- **The approver approves the layout and sample records that print.** `render_proof` prints the print-ready PDF once and draws the review proof's guides over those same pages, without rendering again. `request_approval` records the print file's sha256 in the approval, and approving, submitting and building the printer packet refuse a file that no longer matches (`proof_pdf_changed`). That file holds a few sample records: on a live order the printer merges every recipient's name and vehicle from the mailing list into the approved layout, and personalized handwriting prints in straight lines for now. The review page says so beside the proof. An artwork order's packet also carries the partner's clean art, which the run prints, and refuses it when the stored file no longer has the sha256 that preflight checked (`artwork_missing`).
- Partner HTML is parsed (HTML and CSS) and cleaned before it is stored: scripts, embedding elements, `on*` handlers, `javascript:` and remote URLs, `@import`, `@media print`, `@page` and `:has()` are removed, and each is a preflight error that blocks the proof ([Creative](creative.md#your-own-html)).
- PDF proofs are printed by headless Chromium on the server. The print browser runs no script (page JavaScript is off) and makes no network requests: every request but a `data:` URL is blocked, host names resolve to nothing (`--host-resolver-rules`), all traffic goes to a dead proxy, background services are off and DevTools runs over a pipe, so there is no debugging port. Fonts are embedded and the logo is fetched beforehand by the logo check (https, a pinned public address, no redirects, at most 2 MB) and inlined. Make logos, vehicle photos and QR codes are built on the server and inlined too, so nothing loads at print time. A print failure logs only the error class, never the HTML. Renders are limited per dealer and per partner ([Rate limits](api-reference.md#rate-limits)).
- Partner artwork is never opened by the print browser. It is fetched once with the SSRF-safe GET (https, no credentials, public addresses only, pinned, no redirects, 30 seconds idle, 50 MB cap for a PDF and 25 MB for an image) or read from its signed upload, and only the URL's host is stored. A PNG or JPEG (at most 64 megapixels) is recognized by its first bytes, never by its name or content type; a JPEG's header is read and its data embedded as sent, and a PNG is decoded once by sharp to flatten transparency. Each image is placed on a PDF page, so image art becomes an ordinary artwork PDF. pdf-lib parses each PDF, refusing encrypted and unreadable files; preflight reports JavaScript, form fields, attachments, links, launch actions and multimedia anywhere in the file as errors. The print file embeds each artwork page as a whole, untouched, and Chromium prints only the address overlay, so a PDF can neither run code nor make the server fetch anything at print time. Before printing, the stored file must still have the sha256 that preflight checked (`artwork_missing`).
- Every merge value is HTML-escaped. Logos must be `https://` or `data:image` URLs.
- The stored mailable file is kept raw, cell for cell, because it is data for the proof, Accutrace and the printer's merge software, and a `'` prefix would print on the piece. Only the columns the piece prints leave the system, inside the printer packet, as `mailable-audience-raw.csv`, which the runbook and the packet README say never to open in a spreadsheet. Every file made for people to open prefixes cells that start with `=`, `+`, `-`, `@`, a tab or a carriage return with `'`: the ops dashboard's audience downloads (copies named `*-spreadsheet-safe.csv`, each download logged on the campaign timeline as `ops.audience_file_downloaded`), the printer CSV and the packet's job ticket.
- Ask partners to send only the columns the creative uses, plus phone and email if they want responses and sales matched: UpDash's list import reads those to attribute responses to the piece. The API has no use for dates of birth, Social Security numbers or credit data, and a file with a date-of-birth column gets the warning `birth_date_columns_present`. The reconciliation report notes `contact_columns_present` when a file has email or phone columns, naming the columns, never a value; nothing strips them, so they are stored with the file until retention deletes it ([Column warnings](audiences.md#column-warnings)). Xcel's templates never print them or a record id; a creative whose own HTML or copy prints `external_id`, an id column or a contact column fails preflight with `audience_identifier_printed`, so it never reaches a proof; a saved template that prints one is refused. Results and webhooks never return them.
- An audience can come from a `source_url` Xcel fetches once with the SSRF-safe GET (https, no credentials, public addresses only, pinned, no redirects, 30 seconds idle, 50 MB cap, a CSV or generic content type only). The URL is never stored or logged, and errors never quote it, so a presigned link's token stays private; an idempotent retry is matched by the link's origin and path. A CSV sent as a request body is never logged. Either way the file lands in the same private storage as a signed upload, under the same retention.
- `column_map` and its refusals name the file's headers only when the first row looks like a header row; a first row that looks like a customer (an address, a ZIP, an email) is never echoed.
- Template preview links (`GET /preview/{token}`) need no key: the HMAC-signed token is the capability, lasts one hour and names one template, the partner and key, an optional dealer and the caller's copy. It never carries a recipient, so an opened link prints the fictional sample recipient. The copy is signed, not encrypted. The page is served under the proof pages' sandbox CSP with `noindex`, `no-store` and `no-referrer`, cannot be framed and stops working when the key is revoked. The page is rendered on the link's first opening in each format and stored for the link's hour, under the sha256 of the token, never the token itself; every opening serves that copy and counts against no render limit. Stored renders are deleted by the daily job once every link that could open them has expired.
- `external_ref` and `metadata` on a campaign are echoed on every response and webhook and kept with the order, outside the audience files' retention. The docs and field descriptions say to put ids and labels there, never customer data.
- A dealer's lasting do-not-mail list holds an HMAC-SHA256 per entry, never a name or an address: a database check refuses anything but a hash. The key is derived with HKDF from a secret held only on the server, apart from the credential that opens the table, and each hash covers the dealer and the mode, so a copy of the table does not say who is on it or link one person across dealers. The file it came from is not stored. No call returns an entry or tests one person ([When a person asks](audiences.md#when-a-person-asks)). A list the server cannot read refuses every upload for that dealer, rather than mail past it.
- Every mailable row gets a random row key (80 bits), written into the mailable file as `ResponseCode` for UpDash's list import. The `lead_keys` table maps each row key to the partner's `external_id` and the source row number, and holds nothing else from the row. Partners should use an opaque `external_id`, never an email, phone number or name; a value that looks like an email address or a formatted phone number is blanked at intake (`external_id_contact_info_blanked`), so it never reaches results or webhooks. A bare run of digits is kept.

## Results and dealer data

- Results come back from UpDash by row key: per lead, the response types and times, and matched sales or service (kind, date, new or used, gross and revenue in cents). UpDash sends no names or addresses, and the Mail API stores and returns none.
- **Matched sales and service carry the dealer's own figures from its dealer management system.** Xcel shares them with the partner under the partner agreement, and only on that partner's campaigns (the usual partner and mode scoping). The partner must treat them as the dealer's confidential data. Results webhooks carry ids and counts only; the figures are only in `get_campaign_results`.
- The UpDash client calls only the configured UpDash origin over https, resolves the host and pins the connection to public addresses (the webhook rules), follows no redirects, times out after 15 seconds and caps a response at 20 MB. The service key is sent only as a bearer token to that origin. Errors and logs carry the error kind and HTTP status, never a response body, and the poller logs counts only.
- Vehicle photos come from UpDash's `GET /api/vehicle_image` as image URLs on the UpDash site only (the base URL's registrable host), fetched through the same SSRF-safe GET as logos (public addresses, pinned, no redirects, at most 15 MB), decoded with a pixel cap and stored in the audience bucket. They are licensed for Xcel's templates only and never print in partner HTML.
- Xcel's server holds one service credential for UpDash's read endpoints. It is not limited to one partner, so it stays in the server's environment, never reaches a partner, and is rotated like the other secrets.

## Retention

| Item | Kept for |
| --- | --- |
| Audience files: original upload, suppression list, normalized mailable file, and the proof PDFs printed from that audience version | Until `retention_expires_at`: 90 days by default after the upload started, or sooner by `DELETE /v1/campaigns/{id}/audience/{audience_id}` |
| A dealer's lasting do-not-mail list (`dealer_suppressions`): keyed hashes only, per dealer and mode | Until the partner clears it, or the dealer is deleted |
| Audience counts and reconciliation report | Kept; they hold no customer values |
| Artwork uploads (`artwork-uploads/`: the files PUT to an artwork upload, and the art an artwork preview kept) | 7 days after each file arrived. They hold no customer data. |
| A campaign's artwork files, by sha256 under the campaign (the PDF that prints and, for PNG or JPEG art, each side's image as sent) | Outside the audience files' retention, since they hold no customer data: kept while the order is open, and deleted with its per-lead results, 365 days after it completes or is cancelled. A campaign never submitted loses its art 90 days after its last update, test or live; the campaign stays. |
| Renders preview links serve (`preview-renders/`, under the sha256 of the link's token) | Until the daily job after every link that could open them expired: two hours after each was stored. They print the fictional sample recipient only. |
| Campaigns, quotes, approvals, submissions, events | Kept |
| Row keys (row key, `external_id`, source row) and per-lead results (which hold the dealer's sales figures) | 365 days by default after the order completes or is cancelled, deleted in one transaction. Row keys of an audience version that was never submitted go with its files. |
| The `external_id` of a rejected row, in the audience's `rejected_rows` | With the audience's files. The row number and reason stay |
| Result totals (`campaign_results`) | Kept; they hold counts only |

A partner can delete a version's files before their date, through the same code as the job below, except the version an order in production prints ([Remove a list early](audiences.md#remove-a-list-early)). A daily job deletes the files of each audience past its retention date, with its proof PDFs, stamps `purged_at` and records an `audience.purged` event. If the audience is the current one of a live order still in production (`submitted` to `delivery_estimated`), the job moves its retention date out by 7 days instead, so ops never lose a file mid-job. Sandbox audiences are purged on schedule whatever the campaign's status. After the purge, ops can no longer download the files (410 `audience_purged`) and proofs fall back to fictional sample rows. The same job deletes the row keys and per-lead results of orders closed more than 365 days ago (a database function, one transaction per order), after their artwork files, and records `results.lead_data_purged` on the campaign's timeline; it is not sent to webhooks. It also deletes the art of every campaign never submitted and not updated for 90 days (the campaign row, its creatives and its events stay; a later update starts the 90 days again), artwork uploads 7 days after they arrived, and the renders of expired preview links.

## Approval guarantees

These hold for every live order:

1. **A human decides.** No REST endpoint, MCP tool or partner console page approves an order. The only path to `approved` is a decision on the review page.
2. **Only a registered approver gets the link.** No partner key can write a dealer's approvers. A partner names a person; Xcel emails them a confirm link (single use, 7 days, stored only as a SHA-256 hash; the email names the dealer and the partner that named them, and no order). When they confirm, the address is registered at once only if it is at the dealer's website domain (from the profile the partner keeps, and not moved from another domain in the last 30 days) or at a dealer-group domain Xcel listed for that partner, and never at a common free mail service (a list Xcel keeps); any other address waits until Xcel checks it with the dealership. Xcel can also register approvers with its admin tooling. Responses show them masked (`j***@dealer.com`).
3. **The link never reaches the caller.** It goes to the approver by email (Mailgun, click tracking off so the link is not rewritten). It is not returned to the API or MCP caller, not shown in the console and not logged. If email is not configured, the request is refused before an approval exists. If the send fails, the new approval is expired at once. A console member can resend a live link: a new token goes by email to the same registered approver (who must still be registered), the old link stops working, and the approval's bindings and expiry stay; at most 3 resends per approval per hour.
4. **The token is a capability.** It has 256 bits of entropy and is stored only as a SHA-256 hash. Whoever holds the link can decide as the approver it was issued to, so it must not be forwarded. The page is `noindex`, sends no referrer and accepts decisions only as same-origin form posts.
5. **The approval is bound.** It covers one campaign, one creative version, one audience version, one quote, a `max_spend_cents` ceiling and, where the proof was printed to PDF, the sha256 of the print-ready file the approver reviewed. A link issued to one approver refuses a decision recorded under another email.
6. **Submit re-checks everything.** The approval status and expiry, both versions, the quote and its expiry, the ceiling, the print file's hash, the dealer's monthly spend cap (again inside the submit transaction, under a per-dealer lock) and the partner's `ordering_enabled`. A caller's claim of approval is never an input. The approver's approve checks the cap too, so a link cannot approve an order that is already over it.
7. **Changes void approval.** A new creative or audience returns the campaign to `draft` and expires pending approvals.
8. **Profile changes cannot reach an approved order.** A creative records the dealer profile version it was made with (logo, colors, phone, name, address), and its proofs and print file use only that version. A profile change needs a new creative, which voids the approval (rule 7) and, where proofs print to PDF, produces a print file with a new sha256 that a new approval must bind.
9. **Live ordering is switched on per partner.** Until Xcel enables it, live submits are refused with `ordering_disabled`.
10. **Partner-created dealers wait for an approver.** A dealer a partner creates has no registered approver. Live `request_approval` and live submit are refused with `no_registered_approver` until one is registered (rule 2). A dealer a test key creates exists in test mode only and can never have an approver or a live order.
11. **A prescreened offer is attested.** On a prescreened credit offer the approver confirms, before Approve works, that the list is a prescreened list from the consumer reporting agency the piece names, and enters the list's date. The server checks both, the approval records them, and the database refuses an approved prescreened offer without them ([Prescreened offers](quotes-and-approvals.md#prescreened-offers)).

In the sandbox the link is returned as `review_url` with `sandbox_only: true` and the approver registry is skipped, so a developer can approve their own sandbox order. A sandbox key can also decide one through `POST /v1/test/campaigns/{id}/approval`, for automated tests; the route refuses a live key and checks the campaign's own mode, and it is not an MCP tool. Sandbox orders never print.

## AI-written copy

When a creative request carries a `brief`, the server calls Anthropic's Claude API (model `claude-sonnet-5-5` by default) with Xcel's own Anthropic key. Without the key, a brief is refused with 503 `ai_copy_unavailable` and nothing is sent.

| Sent to the model | Never sent |
| --- | --- |
| The template's code, name and description; the product name; the slots to write (name, label, kind, maximum length, whether required, description, and the sample when it has no figures) | Audience rows or any recipient value |
| The dealer's name, city and state (from the profile), and its disclosures | The dealer's street address, phone, logo or any other profile field; registered approvers |
| Whether the piece is a prescreened offer, and the rules for credit and lease figures | The campaign name, quotes, approvals, ids or keys |
| The brief as sent (`goal`, `offer`, `tone`, `audience`, `offer_terms`) | Your `copy`: slots you send are never asked for |
| The names of the recipient merge fields it may use (audience column names, without address fields or the VIN) | |
| On a repair call: its own first draft and the issue codes | |

The console's [Write it for me](console.md#help-with-the-words) sends the same as a brief: what the mailing is for, the tone, and the offer chosen or written. Its line rewrites (Shorter, Warmer, Spanish) send the template's name, the product, the dealer's name, the line's label and purpose, the recipient merge-field names, and that one line's words as the person typed them.

- Partners must not put customer data in a brief; the field descriptions say so. The server cannot tell a name in a brief from any other text.
- Xcel logs the model, latency and token counts of each call, and counts calls per partner, mode and UTC day. Prompts and answers are never logged, and the brief is not stored; the copy that results is stored in the creative like any other copy.
- The answer is checked in code before it is stored (see [AI-written copy](creative.md#ai-written-copy)): unknown keys and markup are dropped, and figures, credit and lease terms, pre-approval and guarantee language and merge fields are pattern-checked. The offer disclosure is formatted by the server from `offer_terms`, never written by the model.
- Limits per dealer and per partner (200 model calls per UTC day per dealer and 2,000 per partner by default, sandbox and live together; [Rate limits](api-reference.md#rate-limits)) bound cost and abuse; past either a brief gets 429 `ai_copy_rate_limited`. Calls are also counted per dealer and day, counts only.

## AI-made photos

**Make a photo with AI** in the console sends what the person typed about the picture, with Xcel's fixed rules (no vehicles, people, text or logos), to OpenAI's Image API (model `gpt-image-2.6-sunburst` by default), with Xcel's own OpenAI key. Each picture made is then sent, small, to an OpenAI vision model (`gpt-6.1-terra` by default), which says whether it shows a vehicle, a person, or text or a logo. A picture it does not clear is never offered; an answer that cannot be read counts as found. Without the key the console does not offer it, and nothing is sent.

- Nothing else is sent: no customer rows, recipient values, dealer details, orders or keys.
- Xcel logs the model, the shape, how many pictures were made and offered, and the time taken. Prompts and pictures are not logged. Pictures not saved wait in private storage until one is saved, or for a day.
- Each partner may make photos 25 times a UTC day by default, which bounds cost and abuse.

## Dealer profiles

- **Who can write.** A partner's live keys, live OAuth tokens and console members and admins in live mode write its own dealers' profiles; another partner's dealer answers 404. Test and live keys share the dealers a live key or Xcel created, so a write to one with a test key (or a `mail:test` token, or the console in test mode) only validates: the same checks run and nothing is stored, no version is made, no webhook is sent and no UpDash push is queued (`validated_only: true`). A test key's own test dealers are invisible to live keys and are written normally; they never get an approver or an UpDash link. Every version records the actor (key id, OAuth client, console user, `xcel_admin` or `updash_seed`) and its mode.
- **What partners cannot write.** Approvers, disclosures, the license number, the spend cap and `ordering_enabled` are refused anywhere in a profile request (`xcel_managed_field`), including as CSV columns. Only the admin CLI sets them; approvers a partner names register only through the confirmation above.
- **History is immutable.** A trigger refuses any update to a stored version, and writes are compare-and-set on the version under a row lock, so concurrent writers cannot both win.
- **Logos.** The type is judged from the file's bytes. SVG is parsed and rebuilt from an allowlist of elements and attributes: no script, event handlers, `foreignObject`, links, external or remote references (only `#id` references and inline PNG or JPEG images), CSS imports or at-rules; DOCTYPEs are dropped, so entities never expand. Animated files are refused. The sanitized SVG is drawn to a PNG by librsvg (through sharp), never by Chromium, and proofs and print files embed only that PNG, inline, so the print browser still runs no partner code and fetches nothing. PDF logos are checked for scripts, actions and attachments, but cannot be rasterized on this deployment and are refused. A logo URL is fetched with the SSRF-safe GET (public addresses only, pinned, no redirects, 8-second timeout, 3 MB cap). Files are stored in the private bucket by sha256.
- **Creative assets.** The same checks as a logo: the type from the file's bytes, SVG (signatures only) rebuilt by the same allowlist, a URL only through the SSRF-safe GET. Files live in the same private bucket, under the partner and dealer, and are shown only as short-lived console previews; the API returns metadata, never storage paths. Printing uses a rendition with no metadata, inline; Chromium never renders a partner's SVG, and a phone photo's location never reaches a proof or a printer. A delete makes a new profile version and removes no file, so an approved order cannot lose what it printed. A person's name and title are profile data like the contact's: they stay in the versions that had them, and never reach a log or a webhook.
- **Lead routing stays put.** `lead_routing` (CRM, ADF emails, a webhook URL) is stored and shown, never used to send anything and never pushed to UpDash, so a partner key cannot redirect a dealer's leads.
- **Events and logs.** `dealer.updated` and the version history carry field names, never values. Logs carry dealer ids, version numbers and counts.
- **UpDash pushes** send only the restricted fields UpDash keeps, and only those with a value, over the same pinned, no-redirect client as the results poller with the Xcel service key. UpDash decides what to store and answers with field names and reason codes, which are kept; its response bodies are never logged.

## Partner console

The [partner console](console.md) at `/console` is for a partner's own staff. It is built in this app; it does not use Supabase Auth.

| Property | Value |
| --- | --- |
| Accounts | One per partner and email, with a role (`admin`, `member` or `viewer`) and an optional dealer scope. A sandbox sign-up makes the first admin of a new company, for the sandbox alone. Live ordering stays off until Xcel turns it on. Admins invite the rest. |
| Sign-in | An email address and a password. One password per email address, for every partner console that address belongs to; an address in more than one picks the console after the password. A wrong password, an unknown address and an address with no password get the same answer and take the same time. |
| Passwords | Stored only as scrypt hashes (N = 2^17, r = 8, p = 1, a 16-byte random salt per hash, Node's own implementation), never in a log, an email or an error. At least 12 characters and at most 128; a password with the email address in it, or an easily guessed one, is refused. A hash made at a lower cost is replaced at the next sign-in. |
| Setting a password | Only with an emailed link through the same notifier as approval emails (Mailgun, click tracking off): its token has 256 bits, is stored only as a SHA-256 hash, works once and is bound to one user. A reset link lasts an hour; the link in an invitation or a sandbox welcome lasts 7 days. Opening it changes nothing; the link is spent only when a password is accepted. Changing a password while signed in needs the current one. Setting or changing a password ends every other session of that email address, in every console. |
| Attempts | Password tries are counted before the password is checked, so parallel guesses all count: 10 per email and 50 per network address in 15 minutes. Link requests: 5 per email and 30 per network address in 15 minutes, with the same answer whether or not the address has access, sent after the response. All counted in `console_rate_limits` under hashes, never the email or address. |
| Sessions | A random 256-bit cookie value, stored only as a SHA-256 hash. A session ends after 12 hours idle, 7 days after sign-in, at sign-out, or when the user is disabled (a trigger revokes every session and drops unused links in the same transaction). |
| Cookie | `__Host-xm_console`: HttpOnly, Secure, SameSite=Lax, Path=/, no Domain. |
| Form posts | Every POST is checked for the same origin (`Sec-Fetch-Site`, else `Origin`) before anything else, the sign-in forms included. The proxy checks it too and sets `Cache-Control: no-store` and `X-Robots-Tag: noindex` on every console page. |
| Roles | Checked on the server in every page and form route. Viewers read only and see per-lead data masked. Members also edit dealers, resend approval links, reveal and export lead data and download proofs. Admins also manage API keys, webhooks and the team, and always see every dealer. No role approves an order. |
| Scope | Every read and write is filtered by the user's partner, the console's mode and the user's dealer scope. Anything else, another partner's included, is a plain "not found". |
| Per-lead data | Names and addresses come from the stored mailing list (joined by row key), only while it is kept. Masked by default (initials, city and state; gross hidden). Reveal shows full values for 10 minutes to that user's session; the grant is the id of the audit event it wrote. Exports are spreadsheet-safe (`'` before a formula-like cell). |
| Audit | `console_audit_events`: sign-ins, password changes, reveals, exports, proof downloads, approval-link resends, key and webhook changes, team changes and retired templates, with the user, session, mode and campaign, and ids and counts only. Rows cannot be updated (a trigger refuses it). Xcel staff read it. |
| API keys | Admins create keys in the console's mode (at most 10 active for every dealer and 1,000 limited to some dealers, per mode). A new key is shown once, in the response to the form post itself, on a page that cannot be cached or framed; only its hash and prefix are stored, as with the admin CLI. Revoking a key also revokes its MCP OAuth tokens. |
| Errors and logs | Form outcomes come back as codes in the query string and are shown only from a fixed list; an unknown code is never echoed. Logs and audit events never hold a lead value, a profile value, an email address, a password, an emailed link or a key. |
| Dealer changes | Through the same dealer service as the API, with If-Match: a stale version is refused, never overwritten. In test mode they only validate. |

## Agreements signed online

Xcel sends each Order Form under the Master Services Agreement for signature through the Services ([Going live](going-live.md)).

| | |
| --- | --- |
| The link | Emailed to the signer Xcel names, and to no one else. Its token has 256 bits and is stored only as a SHA-256 hash; it works for 14 days, and a fresh link from Xcel ends the old one. Opening it signs nothing; a same-origin form post does. |
| The document | Frozen when it is sent, with its SHA-256. The sign form carries that hash, and a signature on any other text is refused. The page shows the document as text: no markup from the agreement is ever run. |
| The signature | The signer's typed name and title, two ticked confirmations (they agree for the company, and they may sign for it and agree to sign electronically), and the record: their email, network address, browser, the time and the document's hash. A signed agreement never changes. |
| What signing sets | Negotiated print prices (postage always follows the Price List) and the payment terms in the Order Form. Nothing else: live ordering stays Xcel's switch. |
| Payment | Added on Stripe's own page after signing; card and bank numbers go only to Stripe. |
| The copy | The same link opens the signed copy for a year, and the partner's console admins see it under **Agreements**. |

## Webhooks

- Each endpoint gets its own secret (`whsec_` plus 24 random bytes, base64url), shown once. The server stores it readable because it signs with it.
- Every delivery carries `X-Xcel-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256>` over `<t>.<raw body>`. Receivers should reject timestamps more than 5 minutes old.
- Live endpoints must be `https`; sandbox endpoints may be `http`. URLs with credentials are refused.
- Server-side request forgery protection: local host names (`localhost`, `*.localhost`, `*.local`, `*.internal`, `*.home.arpa`, `metadata`) and every non-public address are refused: private, loopback, link-local, carrier-grade NAT, documentation, multicast, reserved and cloud-metadata ranges, in IPv4 and IPv6, including IPv6 forms that embed an IPv4 address. The host is resolved and checked at registration and again before every delivery, and the outgoing connection is pinned to addresses that passed the check, which closes the DNS-rebinding gap.
- Redirects are not followed. Requests time out after 5 seconds. Response bodies are discarded and never stored.
- Fan-out is bounded: at most 5 active endpoints per partner and mode by default, and delivery runs claim live deliveries first, then take turns across partners, sending up to 4 at a time, so one partner's slow endpoints cannot starve the others.

See [Webhooks](webhooks.md) for verification code.

## Ops dashboard and internal routes

- `/ops` has one account per person. Only an address on the ops user table can sign in, and only the admin CLI, which needs the service-role key, can add one. A password try and a request for a link get the same answer, in the same time, whether or not the address is on the table.
- Sign-in has two steps. The first is the person's password, stored only as an scrypt hash (the same as the console's) and set or reset only with an emailed link: single use, valid for 15 minutes, stored only as a SHA-256 hash, and opening it spends nothing. The second is a code from an authenticator app (TOTP, RFC 6238), or one of ten one-time recovery codes. A right password alone reaches only the second step, and only for someone already enrolled: enrolling an authenticator starts only from a spent emailed link, and resetting it also clears the password. A person enrolls the app with a QR code or a key on their first sign-in. A TOTP code works only once.
- TOTP secrets are encrypted at rest with AES-256-GCM, each bound to its person. The key is derived with HKDF from the server's Supabase service-role key, so it is not in the database: a database dump or backup does not expose the secrets. Someone who holds the service-role key could read them. Recovery codes are shown once and stored only as SHA-256 hashes. Neither ever goes in a log, an event or an error.
- Password tries and link requests are rate limited per email and per address, and a wrong password and an unknown address answer the same. After five wrong codes a person is locked out for 15 minutes, and each further lockout doubles, up to a day. Only someone who opened an emailed link can reach the code form, so a lockout cannot show whether an address exists.
- An ops session ends after 30 minutes idle or 12 hours after sign-in, at sign-out, or at the next request after the person is disabled. The cookie is `__Host-xm_ops`: HttpOnly, Secure, SameSite=Lax. Only a hash of its value is stored, and the value changes when the second factor is done.
- The proxy checks access on every `/ops` path, and every `/ops` route handler and page checks it again itself (and the same-origin rule for posts), so the dashboard stays closed even if the proxy stopped covering a path. Only the sign-in pages are open.
- Before the first person enrolls, `/ops` also accepts one shared password (HTTP basic auth), so that a deploy cannot lock Xcel out of live production work, and every page says so. The first enrollment ends it: from then on the password is refused in the proxy and in every route and page, read from the database on each request. Resetting or disabling people does not bring it back. A failed read refuses the password, and never falls back to it.
- Every sensitive action in `/ops` records the person's address, taken from their session and never typed: status changes, cancellations, CASS and NCOA results, proof views and downloads, audience file downloads, printer exports and packets, the UpDash link and approver decisions. Sign-ins, wrong codes, lockouts and account changes are in an audit table whose rows cannot be changed or deleted. Partners see `ops` as the actor, never the person.
- Form posts to `/ops`, `/review`, `/agreements` and `/console` must be same-origin. Cross-site posts get 403.
- Ops, review, agreement and console pages are `noindex` and `Cache-Control: no-store`.
- Scheduled jobs require a secret bearer token and refuse everything when it is unset.
- The UpDash link (`POST /ops/campaigns/{id}/updash-link`) repeats the access and same-origin checks, accepts only a 32-hex key, and records `ops.updash_linked` (not sent to partner webhooks).
- The printer downloads are same-origin form posts: `POST /ops/printer-export` (job tickets as CSV, no customer rows) and `POST /ops/campaigns/{id}/printer-packet` (a zip that holds the mailable audience file). Both routes repeat the access and same-origin checks themselves, so they stay closed if the proxy ever stops covering them. Each download writes an event on the campaign (`ops.printer_export_downloaded`, `ops.printer_packet_downloaded`) with the person's address, the time and, for a packet, the audience version and row count; never row values. These events are not sent to partner webhooks.
- Export cells that start with `=`, `+`, `-`, `@`, a tab or a carriage return get a leading `'`, so a spreadsheet cannot run them.
- The daily ops digest email holds counts, dealer, partner and product names, quantities, totals, ids and `/ops` links. It never holds audience rows or approver addresses. The `ops_digest_runs` table keeps counts only, not recipients.
- Every response sets `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`, and every response but the review PDF sets `X-Frame-Options: DENY`; the review PDF sets `X-Frame-Options: SAMEORIGIN` and `Content-Security-Policy: frame-ancestors 'self'` so the review page can show it.
- Production refuses every request with 503 unless its public URL is `https://`, because review links, the OAuth issuer and the consent cookie's `Secure` flag come from it.

## Notes for dealers (FTC Safeguards Rule)

This section is information for dealers and their CDPs, not legal advice.

Car dealers that arrange financing or leases are financial institutions under the Gramm-Leach-Bliley Act, so the FTC Safeguards Rule (16 CFR Part 314) applies to their customer information. A mailing list drawn from a DMS or CDP is customer information. The rule requires the dealer to oversee service providers that handle it: choose providers that can safeguard it, require safeguards by contract, and assess them periodically. Xcel and the partner that sends the list are service providers for this purpose.

Facts a dealer's information security program can rely on:

| Safeguard | How the API provides it |
| --- | --- |
| Access control | Partner- and mode-scoped API keys, stored hashed; the database is reachable only by the server. |
| Data minimization | Only names, addresses and the columns the creative uses are needed (phone and email only to match responses and sales). Rows never pass through API responses, MCP results, webhooks or logs. |
| Encryption in transit | The API is served over HTTPS; live webhooks must be HTTPS. |
| Disposal | Audience files in the Mail API are deleted after 90 days by default. Files of a live order still in production are kept, a week at a time, until it leaves production. A live order's list also reaches UpDash for production, where [UpDash's own periods](vendor-review.md#updash-production) apply. |
| Change control on spend | Live orders need a human approval from a registered approver, bound to the exact proof, quantity and total. |
| Monitoring | Every status change is recorded as an event with its actor. |
| Results | Per-lead results name a lead by a random row key and the partner's own id, never by name or address. Matched sales figures come from the dealer's DMS and are shared with the partner under the partner agreement. |

What the dealer and partner should do:

- Send only the fields the mail piece needs. Never send SSNs, dates of birth, driver's license numbers, account numbers or credit data.
- Register as approvers only people who may commit the dealer's marketing spend, and tell Xcel when one leaves.
- If a key may be exposed, revoke it at once in the partner console (**Developers**) and tell Xcel.
- Under the 2023 amendment, financial institutions must notify the FTC within 30 days of discovering that unencrypted customer information of 500 or more consumers was acquired without authorization. Tell Xcel about suspected incidents so the facts are available in time.
