coss.com
One API key, one SDK, every communication primitive:
import { Coss } from "coss"; const coss = new Coss({ apiKey: process.env.COSS_API_KEY }); const { data, error } = await coss.email.send({ from: "Acme <hello@acme.dev>", to: "user@example.com", subject: "Welcome", html: "<p>Hi there</p>", });
Transactional email is the first product, delivered by Amazon SES (EMAIL_PROVIDER=ses) or a fake provider for local development (nothing leaves your machine). Development (sandbox) environments always use the fake provider, which simulates delivery events like the SES mailbox simulator. Live sends come from verified domains; every recipient gets a delivery status, and signed webhooks report email.delivered, email.bounced and the rest.
Stack
Bun workspaces · Turborepo · TypeScript 7 · Biome · Next.js 16 (dashboard) · Hono (public API) · Postgres + Drizzle · Valkey (rate limits) · Better Auth (organization, admin, API key plugins) · Tailwind v4 + coss ui · Fumadocs (coss.com and its docs: OpenAPI reference, Twoslash) · Expo + Expo Router (iOS app)
See AGENTS.md for the layout, conventions and guardrails.
Prerequisites
- Bun ≥ 1.4.2 and Node.js ≥ 24 (Next.js and the Better Auth CLI run on Node)
- PostgreSQL 18 (e.g. Postgres.app)
- Valkey 8 (or Redis) for the test suite, e.g. brew install valkey && brew services start valkey
- VS Code: install the recommended extensions (Biome, TypeScript Native Preview)
Setup
bun install createdb coss && createdb coss_test cp .env.example .env # then set DATABASE_URL, TEST_DATABASE_URL, BETTER_AUTH_SECRET and # WEBHOOK_SECRETS_KEY (each: openssl rand -base64 32) bun run db:migrate bun run db:seed # creates demo@coss.local (admin), org "acme" with the verified domain # acme.test, a project, and prints a dev API key bun run dev # dashboard http://localhost:3000/dashboard · API http://localhost:3001 · # site + docs http://localhost:3002 · worker
Then set up the shared build cache once per machine (Remote cache): without it everything works, but CI rebuilds what you already built.
db:migrate also installs the pgboss schema: sends return 202 with status: "queued" and the worker dispatches them moments later, so keep the worker running.
Send an email with the key printed by the seed:
curl -X POST http://localhost:3001/v1/emails \ -H "Authorization: Bearer $COSS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"from":"Acme <hello@acme.dev>","to":"user@example.com","subject":"Hello","text":"Hi!"}' # or with the SDK from this repo COSS_API_KEY=coss_test_... COSS_BASE_URL=http://localhost:3001 bun packages/sdk/examples/send-email.ts
The email shows up in the dashboard under the project's Development environment, with per-recipient status and events. Send to bounce@simulator.amazonses.com (or complaint@, suppressionlist@) to simulate failures. Add a webhook endpoint in the environment's Webhooks page (local http:// URLs are allowed outside production) and the worker delivers signed events to it. Auth emails (email verification, invitations, password resets) are printed to the dashboard's server console in development.
Concepts
- Organizations & members — Better Auth organization plugin (roles: owner, admin, member).
- Projects — belong to an organization; each gets two environments: production (mode live, keys coss_live_…) and development (mode sandbox, keys coss_test_…, never really sends).
- API keys — Better Auth API key plugin, owned by the organization and bound to one environment.
- Domains — owned by the organization and shared by its projects. Live keys can only send from verified domains (Easy DKIM + a send. MAIL FROM subdomain); sandbox keys accept any from.
- Recipients & events — each email has one recipient per distinct address, whose status follows delivery events: queued → sent → delivery_delayed → delivered, then bounced/suppressed/failed, complained.
- Attachments — up to 20 base64 files per send (25 MB combined), inline images via content_id (cid:). Only metadata is kept once the email is sent.
- Suppressions — per environment. Sends skip a suppressed recipient (status suppressed, event email.suppressed) and still deliver to the rest. An entry covers every email (scope *) or one category (the optional category of a send, e.g. marketing), so it can back an unsubscribe flow. Permanent bounces and complaints add * entries automatically (except for mailbox simulator addresses), one-click unsubscribes an entry for the email's category. coss.com keeps the only list: SES suppression is turned off.
- Scheduled sends — pass scheduled_at (ISO 8601 with an offset, up to 30 days ahead) and the email is stored as scheduled (event email.scheduled); the worker sends it when it is due, re-checking the domain and the suppression list. Until then POST /v1/emails/{id}/reschedule moves it to a new time (event email.rescheduled) and POST /v1/emails/{id}/cancel cancels it (canceled, event email.canceled).
- One-click unsubscribe (RFC 8058) — off by default; turned on per category with the tracking rules (or per send, tracking: { unsubscribe: true }). Emails with a category and a single recipient get List-Unsubscribe + List-Unsubscribe-Post headers pointing at the tracking host (/t/u/<token>); the one-click POST suppresses the recipient for that category (reason unsubscribe) and records email.unsubscribed.
- Open & click tracking — off by default. Turn it on per environment (a default plus per-category rules, in the dashboard) or per send (tracking: { opens, clicks }). coss.com adds an invisible image and rewrites HTML links to its own redirect (API_PUBLIC_URL/t/…) when it hands the email to the provider; the stored email keeps the original HTML. Opens and clicks show up as email.opened / email.clicked events, webhooks, counts on the email (tracking) and per-link click counts. Independent of SES's own tracking, which stays off. A verified domain can have a custom tracking domain (e.g. links.acme.com, a CNAME to track.cosslinks.com): emails from it are tracked through that hostname while it is active. coss.com registers it as a Cloudflare for SaaS custom hostname (TRACKING_DOMAIN_PROVIDER=cloudflare), which issues its certificate and proxies /t/* to the API.
- Webhooks — per environment, signed with Standard Webhooks headers and retried for about a day. Verify them with verifyWebhook from the SDK.
- Single sign-on — per organization, OpenID Connect or SAML 2.0 (Better Auth's SSO plugin), set up under the organization's Settings → Single sign-on. Its domains must be the organization's verified email domains: no second DNS check. People at those domains join as members on their first SSO sign-in, and existing accounts with a verified email are linked. Owners can require SSO: members and admins then need an SSO session from the organization's provider (owners keep password "break-glass" access). An SSO session also satisfies the organization's two-factor requirement — the IdP is responsible for MFA. Support recovers broken setups from /admin (unlink a user's SSO accounts, stop requiring SSO, disable a provider).
- Directory sync (SCIM 2.0) — per organization, under Settings → Directory sync (needs an active SSO provider). The IdP (Okta, Entra ID, JumpCloud…) provisions users at /api/auth/scim/v2 with an expiring bearer token: active users are members, members of groups mapped to admin are admins, and deactivating or deleting a user removes them from the organization and ends their SSO sessions there. While a directory is connected, only its active users (and owners) sign in with SSO. Owners are never changed by the directory. Support can disconnect a directory from /admin.
- Reputation guard — the worker watches each organization's live bounce and complaint rates (per recipient, over 7 days) and acts without a human: a warning at 4% bounces / 0.08% complaints, an automatic suspension of live sending at 8% / 0.3% (from 200 / 500 recipients). Suspended organizations get 403 account_suspended on live sends and can't create live keys; sandbox keys keep working. Customers see it in the dashboard (banner + Reputation page), via GET /v1/reputation, through account.* webhooks and by email to the organization's owners and admins (sent through coss.com itself, see "Deploying to AWS"). Only platform admins reinstate (/admin/organizations), where they can also suspend manually and override thresholds per organization.
- Content screening — right before a sampled live email reaches the provider, the worker asks an AI decision model (TypeSafe AI's Jev through the Vercel AI SDK and AI Gateway, swappable with SCREENING_MODEL) how likely it is spam, phishing, malware or fraud. Sampled: each organization's first 10 live emails, its 25th, 50th, 100th, 250th, 500th and 1000th, then 2% at random. At ≥ 0.95 the email fails with content_rejected and the organization is suspended (the reputation guard's content_screening trigger); at ≥ 0.70 it is sent but the organization is warned until the flag ages out of the window. In enforcement mode, classifier errors and timeouts (3 s) hold the email: it is tried (and screened) again every minute, and fails as content_screening_unavailable only if screening is still down an hour after it was due. coss.com's own notification organization always sends so an AI outage cannot stop account recovery. Admins see every verdict on the organization's reputation page and can tune thresholds and sampling, switch to shadow mode, or turn screening off per organization (e.g. for phishing-simulation senders). Locally SCREENING_CLASSIFIER=fake flags content containing [coss-test:phishing] (or spam, malware, fraud; [coss-test:spam:0.8] sets the score).
- Organization deletion — owners delete an organization from its Settings by typing its slug (not while it is suspended; platform admins can, from /admin, audited). Members, invitations, API keys, the SSO provider and the sessions it created go at once and scheduled emails never send; the worker then removes the organization's SES identities and tenant, deletes its data in batches and finally the organization, which frees its slug. A record of the deletion (who, when) is kept. There is no undo.
- Data retention — the worker deletes data once it passes its published period (packages/retention, shown at /docs/data-retention and in each organization's settings): emails with their events and links after 45 days, webhook deliveries after 30, screening verdicts after 90, standing history and the admin audit log after 2 years, expired sessions and invitations 7 days after expiry. Suppressions and configuration are kept until deleted.
- Platform admins — the console at /admin (promote with bun run admin:create --email …): search users and organizations; ban users (with a reason and duration — signs them out everywhere), grant/remove the admin role, revoke sessions, impersonate (with a reason, never other admins); suspend organizations (API keys get 403 organization_suspended, webhook deliveries are held until lifted, the dashboard turns read-only and membership changes are blocked; members never see the internal reason); revoke a single leaked API key. Every action is recorded in an append-only audit log (/admin/audit). Banning a user doesn't stop their organizations' keys — suspend the organization for that.
Commands
| Command | |
|---|---|
| bun run dev | Run dashboard + API + site + worker |
| bun run lint / bun run format | Biome check / fix |
| bun run typecheck | Type-check every package |
| bun run test | Run all tests (against coss_test) |
| bun run build | Build dashboard + site (standalone servers) + SDK |
| bun run db:generate / db:migrate / db:studio | Drizzle migrations |
| bun run auth:generate | Regenerate Better Auth tables after changing auth plugins (then db:generate + db:migrate) |
| bun run signals:update-disposable | Refresh the list of disposable email domains (refused at sign-up, flagged by risk assessments) |
| bun run ses:bootstrap | Create/update the shared AWS resources for EMAIL_PROVIDER=ses (see below) |
| bun run valkey:bootstrap | Create/update the ElastiCache Serverless for Valkey cache for rate limits (see below) |
| bun run ratelimit:set --org <slug> [--bucket … --limit … | --reset] | Show or change an organization's rate limits |
Remote cache (Turborepo on Vercel)
typecheck and build results are shared through Turborepo's Vercel Remote Cache (Vercel team cal) by everyone's machines, agents and CI. Turbo fingerprints each task's inputs (source, lockfile, turbo.json, NODE_ENV, NEXT_DEPLOYMENT_ID); when CI computes a fingerprint someone already built, it downloads that result instead of building again, so running bun run typecheck && bun run build before pushing makes CI's check and build jobs near-instant. On pull requests those two jobs check out the pushed commit (what you built), while the test job runs on GitHub's merge with main; main's own run covers the merged result. Any change to the inputs is a miss and CI runs the task itself, so nothing goes unchecked. Tests are never cached. Artifacts are HMAC-signed with a shared key; Turbo ignores (rebuilds) anything that doesn't verify.
One-time setup per machine (a laptop, or a box agents run on; every worktree on it picks it up):
- Be a member of the cal team on Vercel.
- Put the team and the signing key (password manager: "coss.com turbo remote cache signing key") in a private file
and load it from your shell profile (open a new shell afterwards). Turbo only reads the shell's environment, never .env:
mkdir -p ~/.config/coss && install -m 600 /dev/null ~/.config/coss/turbo.env cat > ~/.config/coss/turbo.env <<'SH' export TURBO_TEAM=cal export TURBO_REMOTE_CACHE_SIGNATURE_KEY='<signing key>' SH # first line of ~/.zshrc (macOS) or ~/.bashrc — above any "not interactive → return" guard, so agents' # non-interactive shells load it too: [ -f "$HOME/.config/coss/turbo.env" ] && . "$HOME/.config/coss/turbo.env"
- Log Turbo in (stores a token in Turbo's user config; the Vercel CLI's own login is not used):
bunx turbo login # pick the cal team if asked # headless box: create a token at https://vercel.com/account/tokens (scope: cal), then bunx turbo login --manual # Remote Cache URL: https://vercel.com/api (not https://vercel.com); # needs TURBO_TEAM=cal from step 2 in this shell
- Check it: bun run typecheck prints Remote caching enabled in its header. Remote caching disabled or Remote caching unavailable (Authentication failed …) means step 2 or 3 is missing; builds still work, unshared.
CI reads secrets.TURBO_TOKEN (a Vercel token scoped to cal), vars.TURBO_TEAM (cal) and secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY (gh secret list, gh variable list); without them it runs every task. Rotating the signing key means updating the GitHub secret and every machine's turbo.env (old artifacts then miss and are rebuilt). Anyone with a cal token and the key can upload results CI will accept: treat them like push access, and revoke a leaver's token (vercel.com/account/tokens, or remove them from the team).
Runtime settings (DATABASE_URL, secrets, URLs, …) are pass-through and never part of a fingerprint, which is what lets laptops and CI share results — see "Adding one" in AGENTS.md before adding a variable that changes build output.
iOS app
apps/mobile is the iOS companion app (Expo SDK 57). It needs Xcode with an iOS Simulator and the dashboard running (bun run dev):
bun run --cwd apps/mobile ios # generates ios/, builds, installs and opens the app on the Simulator bun run --cwd apps/mobile start # Metro only, once the app is installed
"Sign in with coss.com" opens the dashboard's sign-in in a browser sheet (demo@coss.local / coss-demo-password after db:seed). The app reads EXPO_PUBLIC_DASHBOARD_URL (default http://localhost:3000); on a physical device set it to your Mac's LAN address in apps/mobile/.env.local, and run the dashboard with BETTER_AUTH_URL on that address too. Signed-in devices are listed under Settings → Sessions. See apps/mobile/AGENTS.md.
API
- POST /v1/emails — send an email (Idempotency-Key header supported)
- POST /v1/emails/batch — send up to 100 emails at once, all or nothing (one Idempotency-Key for the batch)
- GET /v1/emails/{id} — retrieve an email, with its recipients' delivery status
- GET /v1/emails/{id}/events — list an email's delivery, open and click events
- GET /v1/emails/{id}/links — list an email's tracked links with their click counts
- POST /v1/emails/{id}/cancel — cancel a scheduled email (scheduled_at on send)
- POST|GET /v1/domains, GET|DELETE /v1/domains/{id}, POST /v1/domains/{id}/verify — sending domains (organization-wide, so every key of the organization sees the same ones)
- POST|GET /v1/webhook_endpoints, GET|PATCH|DELETE /v1/webhook_endpoints/{id} — webhook endpoints of the key's own environment; the signing secret is returned only when one is created
- POST /v1/suppressions — suppress an address (scope: * or a category)
- GET /v1/suppressions — list the environment's suppressions (address, scope, limit, after)
- GET /v1/suppressions/check?address=…&category=… — would a send skip this address?
- GET /v1/suppressions/{id} / DELETE /v1/suppressions/{id} — retrieve / remove an entry
- POST /v1/suppressions/import — add up to 1,000 entries at once (invalid ones are skipped and reported)
- GET /v1/suppressions/export — the whole list as CSV (scope, reason filters); it imports again as is
- GET /openapi.json — OpenAPI 3.1 document
- GET /v1/reputation — the organization's standing and latest rates
- GET /t/o/{token}, GET /t/c/{token}/{position} — public open-pixel and click-redirect endpoints that tracked emails link to (not part of the documented API)
Everything is also available in the dashboard, and through the SDK as coss.email, coss.domains, coss.webhookEndpoints and coss.reputation.
Requests are rate limited per API key by route class (reads, writes, sends; responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset), and sends count their distinct recipients against the organization's quota per second and per day (sandbox environments have a small daily quota of their own). Over a limit the API answers 429 rate_limit_error (rate_limited or quota_exceeded) with Retry-After. Defaults live in packages/ratelimit/src/buckets.ts; platform admins override them per organization on the organization's page in the admin console (/admin/organizations, recorded in the audit log) or with bun run ratelimit:set. The dashboard limits sign-in, sign-up, password reset and verification emails per client IP and per email address.
SMTP relay
apps/smtp lets anything that only speaks SMTP send through coss.com (Supabase Auth, WordPress, Rails, Laravel, Django, nodemailer, older