Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat: add custom email headers by KMKoushik · Pull Request #260 · usesend/useSend · GitHub
Skip to content

feat: add custom email headers - #260

Merged
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers
Sep 28, 2025
Merged

feat: add custom email headers#260
KMKoushik merged 3 commits into
mainfrom
codex/add-support-for-custom-email-headers

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 26, 2025

Copy link
Copy Markdown
Member

Summary

  • add a headers column to the email table and include a migration so custom API headers persist with each message
  • store sanitized header maps on email records, drop header payloads from queue jobs, and hydrate SES requests from the persisted data
  • extract a reusable sanitizeHeader helper and reuse it inside the existing custom header sanitizer

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68d056e6c4848329b99dbf5b5562800a

Summary by CodeRabbit

  • New Features

    • Add support for custom email headers in single and batch sends; headers accepted as string maps and forwarded (system headers auto-managed).
  • Documentation

    • Node.js and Python guides updated with headers examples and notes; OpenAPI updated to document the optional headers field.
  • SDKs

    • JavaScript SDK bumped to v1.5.4; Python SDK bumped to v0.2.5 with headers added to types.
  • Chores

    • Database migration adds a nullable headers column to emails.

@vercel

vercelBot commented Sep 26, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 28, 2025 11:26am

@coderabbitai

coderabbitaiBot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change adds optional custom email headers across the system. Public APIs (OpenAPI, SDK typings, zod schema, Python and Node docs) now accept headers?: Record<string, string>. Backend adds sanitization and header-building utilities, updates SES sendRawEmail to accept and apply headers (merging with defaults and reserved headers), and propagates headers through services and queue processing. The Prisma Email model gains a nullable headers field with a migration; headers are persisted as JSON and cleared after sending. SDK versions updated.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 66.67% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly identifies the primary change—adding support for custom email headers—using clear language and following conventional commit style without extraneous details.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-support-for-custom-email-headers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 26, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:4f237f7
Status: ✅ Deploy successful!
Preview URL:https://58d50daa.usesend.pages.dev
Branch Preview URL:https://codex-add-support-for-custom.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
apps/docs/get-started/nodejs.mdx (1)

66-67: Clarify which system headers useSend may add

The note understates which headers are system-managed. SES integration also sets List-Unsubscribe (when unsubUrl is present), In-Reply-To/References (when replying), Precedence (bulk), and an internal reference header. Suggest clarifying to avoid surprises.

Apply this wording tweak:

- > Custom headers are forwarded as-is. useSend only manages the `X-Usesend-Email-ID` and `References` headers.+ > Custom headers are forwarded as-is and merged with system headers. useSend reserves `X-Usesend-Email-ID` and `References`, and may also add `List-Unsubscribe`, `In-Reply-To`, `Precedence`, or an internal reference header when applicable.
apps/web/src/server/service/email-queue-service.ts (1)

401-407: Avoid any: narrow headers without casting to any

Minor type hygiene: you can avoid (email as any) by narrowing through unknown.

Apply:

- const headers = (email as any)?.headers;+ const headers = (email?.headers ?? undefined) as unknown;

Or, if you want stricter typing, leverage Prisma.JsonValue in a follow-up.

apps/web/src/server/public-api/schemas/email-schema.ts (1)

22-28: Harden schema against header injection and abuse

Good addition. Consider aligning validation with sanitizer and capping payload size.

Proposed refinement:

- headers: z- .record(z.string().min(1))- .optional()- .openapi({- description:- "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",- }),+ headers: z+ .record(+ z+ .string()+ .min(1)+ .refine((v) => !/[\r\n]/.test(v), "Header values must not contain CR or LF")+ .max(1024)+ )+ .optional()+ .superRefine((h, ctx) => {+ const count = Object.keys(h ?? {}).length;+ if (count > 50) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Up to 50 headers allowed" });+ }+ })+ .openapi({+ description:+ "Custom headers to include with the message. All headers are forwarded except `X-Usesend-Email-ID` and `References`, which useSend manages.",+ }),

Optionally also restrict header names with a token regex in the sanitizer (see utils/email-headers.ts comment).

apps/web/src/server/utils/email-headers.ts (2)

27-35: Validate header-name token format

Prevent invalid names (e.g., containing colon or spaces) by enforcing RFC-like token characters.

Apply:

+const VALID_HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
...
- if (!name || RESERVED_EMAIL_HEADERS.has(name.toLowerCase())) {+ if (+ !name ||+ RESERVED_EMAIL_HEADERS.has(name.toLowerCase()) ||+ !VALID_HEADER_NAME.test(name)+ ) {
return undefined;
}

52-55: Deduplicate headers case-insensitively

Prevent duplicates like "X-Id" and "x-id".

Apply:

- return sanitizedEntries.reduce((acc, { name, value }) => {- acc[name] = value;- return acc;- }, {} as Record<string, string>);+ const seen = new Set<string>();+ return sanitizedEntries.reduce((acc, { name, value }) => {+ const key = name.toLowerCase();+ if (seen.has(key)) return acc;+ seen.add(key);+ acc[name] = value;+ return acc;+ }, {} as Record<string, string>);
apps/web/src/server/service/email-service.ts (1)

718-744: Reduce duplication and strengthen typing for emailCreateData

You repeat the create payload assembly (suppressed/normal/bulk). Extract a small helper to build the object once and reuse. Also prefer Prisma.EmailCreateInput over Record<string, unknown> + any to catch schema drift at compile time.

I can draft a helper like buildEmailCreateData(...) returning Prisma.EmailCreateInput if helpful.

apps/web/src/server/aws/ses.ts (1)

232-239: Align override behavior for X-Usesend-Email-ID.

You always set X-Usesend-Email-ID, but conditionally set X-Unsend-Email-ID. For consistency (and clearer intent), either:

  • Treat X-Usesend-Email-ID as reserved (always set, cannot be overridden), or
  • Mirror the guard and only set it when not supplied by the caller.

Currently sanitized headers will overwrite defaults anyway due to spread order, but adding the guard clarifies intent and saves work.

Apply this diff if you choose the “don’t override user value” route:

 if (emailId) {
- defaultHeaders["X-Usesend-Email-ID"] = emailId;+ if (!sanitizedHeaderNames.has("x-usesend-email-id")) {+ defaultHeaders["X-Usesend-Email-ID"] = emailId;+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10fc285 and 6623409.

📒 Files selected for processing (14)
  • apps/docs/get-started/nodejs.mdx (1 hunks)
  • apps/docs/get-started/python.mdx (1 hunks)
  • apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/src/server/aws/ses.ts (4 hunks)
  • apps/web/src/server/public-api/schemas/email-schema.ts (1 hunks)
  • apps/web/src/server/service/email-queue-service.ts (4 hunks)
  • apps/web/src/server/service/email-service.ts (8 hunks)
  • apps/web/src/server/utils/email-headers.ts (1 hunks)
  • apps/web/src/types/index.ts (1 hunks)
  • packages/python-sdk/pyproject.toml (1 hunks)
  • packages/python-sdk/usesend/types.py (2 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/types/schema.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • packages/sdk/types/schema.d.ts
  • apps/web/src/server/aws/ses.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/types/index.ts
  • apps/web/src/server/public-api/schemas/email-schema.ts
  • apps/web/src/server/utils/email-headers.ts
  • apps/web/src/server/service/email-service.ts
  • apps/web/src/server/service/email-queue-service.ts
  • apps/web/src/server/aws/ses.ts
🧬 Code graph analysis (3)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/service/email-queue-service.ts (1)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/aws/ses.ts (2)
apps/web/src/server/utils/email-headers.ts (1)
  • sanitizeCustomHeaders (37-56)
apps/web/src/server/nanoid.ts (1)
  • nanoid (8-11)
🔇 Additional comments (25)
packages/python-sdk/pyproject.toml (1)

3-3: Version bump aligns Python SDK with new headers feature

0.2.4 cleanly captures the newly added headers support in the types and docs.

packages/sdk/package.json (1)

3-3: JS SDK patch release makes sense

1.5.3 is an appropriate patch increment for exposing the headers field downstream.

apps/web/prisma/migrations/20250207121500_add_email_headers/migration.sql (1)

1-2: Migration cleanly adds nullable JSONB column

Adding headers as nullable keeps existing rows valid while enabling persistence of sanitized maps.

apps/web/src/types/index.ts (1)

13-13: Optional headers record fits EmailContent

Typing this as Record<string, string> matches the sanitization contract and keeps the field opt-in.

apps/docs/get-started/python.mdx (1)

44-52: Docs accurately reflect Python SDK headers usage

Example payload and explanatory note clearly communicate the new capability.

apps/web/prisma/schema.prisma (1)

262-262: Schema change mirrors migration

Adding headers Json? keeps Prisma in sync with the database and matches the optional semantics.

packages/python-sdk/usesend/types.py (2)

197-198: TypedDict update captures optional headers

NotRequired[Dict[str, str]] slots neatly alongside the other optional fields and reflects sanitized inputs.


222-223: Batch item typing stays consistent

Mirroring the single-send shape ensures batch requests can include headers without special casing.

packages/sdk/types/schema.d.ts (2)

305-307: OpenAPI schema now advertises headers

The optional string map mirrors backend validation, so generated clients stay accurate.


372-374: Batch definition gets the same headers map

Ensures parity between single and batch payloads for client generators.

apps/docs/get-started/nodejs.mdx (1)

60-63: Example with headers looks good

The example payload correctly demonstrates the new headers field.

apps/web/src/server/service/email-queue-service.ts (3)

14-14: LGTM: sanitizeCustomHeaders is correctly imported

Import placement and alias usage fit the project conventions.


409-410: LGTM: re-sanitizing persisted headers before send

Idempotent and safe; protects against legacy rows or manual data edits.


428-428: Verified sendRawEmail forwards headers
Signature now includes headers and all call sites (including email‐queue‐service) pass headers: customHeaders.

apps/web/src/server/utils/email-headers.ts (1)

7-7: LGTM: CR/LF check blocks header injection

The injection guard is appropriate.

apps/web/src/server/service/email-service.ts (5)

134-152: LGTM: persist sanitized headers for suppressed emails

Headers are sanitized and saved when all TO recipients are suppressed.


252-277: LGTM: persist sanitized headers for normal path

Conditional inclusion avoids empty JSONB writes.


553-580: LGTM: sanitize and persist headers for suppressed emails in bulk

Consistent with single-send path.


655-665: LGTM: sanitize per-email in bulk

Sanitization is done before record creation, per item.


70-75: Confirm TS SDK EmailContent headers

Apps/web (apps/web/src/types/index.ts) and the Python SDK (EmailCreate/EmailBatchItem in packages/python-sdk/usesend/types.py) already declare an optional headers?: Record<string,string>; ensure the TS SDK’s EmailContent type likewise defines headers?: Record<string,string>.

apps/web/src/server/aws/ses.ts (5)

221-225: LGTM: defensive set for presence checks.

Computing a lowercase set of sanitized header names is a clean way to avoid unintended overrides.


226-231: LGTM: generate X-Entity-Ref-ID when not provided.

Good defaulting without overriding user headers.


250-253: LGTM: bulk precedence header.

Reasonable default when isBulk is true.


283-285: LGTM: merge order prioritizes sanitized headers over defaults.

Spreading sanitized after defaults ensures user-provided headers win. Good.


205-218: API surface update approved.headers is passed separately as Record<string, string | null | undefined>, matching sanitizeCustomHeaders. No changes to EmailContent needed.

Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/aws/ses.ts Outdated
Comment threadapps/web/src/server/service/email-queue-service.ts
@KMKoushikKMKoushik changed the title fix: persist sanitized email headersfeat: add custom email headersSep 28, 2025
@KMKoushik
KMKoushikforce-pushed the codex/add-support-for-custom-email-headers branch from 6623409 to dc7ec13CompareSeptember 28, 2025 11:21

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/server/service/email-service.ts (1)

545-568: Apply the same header sanitization in bulk flows

Both the suppressed-email records and the main bulk create path still stringify headers directly. That bypasses the sanitizer and means bulk sends can persist or emit forbidden headers.

@@
const {
...
apiKeyId,
inReplyToId,
+ headers,
} = originalContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
apiId: apiKeyId,
inReplyToId,
- headers: originalContent.headers- ? JSON.stringify(originalContent.headers)- : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
@@
const {
...
apiKeyId,
headers,
} = content;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
latestStatus: scheduledAtDate ? "SCHEDULED" : "QUEUED",
apiId: apiKeyId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 704-726

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc7ec13 and 4f237f7.

📒 Files selected for processing (1)
  • apps/web/src/server/service/email-service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript with 2-space indentation and semicolons (enforced by Prettier)
ESLint must pass with zero warnings using @usesend/eslint-config
Do not use dynamic imports (avoid import() and dynamic loading)

Files:

  • apps/web/src/server/service/email-service.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code and docs with Prettier 3

Files:

  • apps/web/src/server/service/email-service.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/web/**/*.{ts,tsx}: In apps/web, use the "/" alias for src imports (e.g., import { x } from "/utils/x")
Prefer using tRPC for API calls unless explicitly instructed otherwise

Files:

  • apps/web/src/server/service/email-service.ts
🧠 Learnings (2)
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project, Prisma's findUnique method works with composite where clauses including id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts

Applied to files:

  • apps/web/src/server/service/email-service.ts
📚 Learning: 2025-09-10T12:33:42.667Z
Learnt from: KMKoushik
PR: usesend/useSend#224
File: apps/web/src/server/public-api/api/emails/get-email.ts:63-74
Timestamp: 2025-09-10T12:33:42.667Z
Learning: In the useSend project using Prisma Client 6.6.0, findUnique works with composite where clauses containing id, teamId, and optional domainId fields in apps/web/src/server/public-api/api/emails/get-email.ts, as confirmed by the project maintainer KMKoushik.

Applied to files:

  • apps/web/src/server/service/email-service.ts
🧬 Code graph analysis (1)
apps/web/src/server/service/email-service.ts (1)
apps/web/src/server/service/domain-service.ts (1)
  • validateDomainFromEmail (85-128)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Comment on lines +74 to 76
headers,
} = emailContent;
let subject = subjectFromApiCall;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Sanitize headers before persisting single email records

We never call sanitizeCustomHeaders here, so both the SUPPRESSED branch and the main create path are storing raw, unsanitized header maps. That lets disallowed/unsafe headers slip into persistence and SES, undoing the protections this PR is supposed to provide. Please sanitize once and reuse the sanitized payload wherever we persist headers.

@@
const {
...
inReplyToId,
headers,
} = emailContent;
+ const sanitizedHeaders = headers+ ? sanitizeCustomHeaders(headers)+ : undefined;
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});
@@
const email = await db.email.create({
data: {
...
apiId: apiKeyId,
inReplyToId,
- headers: headers ? JSON.stringify(headers) : undefined,+ headers: sanitizedHeaders+ ? JSON.stringify(sanitizedHeaders)+ : undefined,
},
});

Also applies to: 137-151, 249-272

🤖 Prompt for AI Agents
In apps/web/src/server/service/email-service.ts around lines 74-76 (and also
apply same change to 137-151 and 249-272), the code assigns headers from
emailContent and proceeds to persist/send without calling sanitizeCustomHeaders;
call sanitizeCustomHeaders once immediately after extracting headers to produce
sanitizedHeaders, replace all uses of the raw headers in both the SUPPRESSED
branch and the main create/send paths with sanitizedHeaders, and ensure that the
sanitizedHeaders object is what gets persisted to the database and passed to SES
so disallowed/unsafe headers cannot be stored or sent.

@KMKoushik
KMKoushik merged commit 890ad72 into mainSep 28, 2025
7 checks passed
@KMKoushik
KMKoushik deleted the codex/add-support-for-custom-email-headers branch September 28, 2025 11:33
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik