Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: documents email through server mail without the Email integration (#2013)
Sid5532373ab315
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.mdindex dbd3499212..f4d73d4b21 100644--- a/.claude/rules/event-system.md+++ b/.claude/rules/event-system.md@@ -31,7 +31,7 @@ pg_cron 'event-queue-sweeper' (* * * * *, in-DB): if visible messages exist →The wake path (`20260721184852_event-queue-wake.sql`, rewired by `20261002170250_send-inngest-events-from-postgres.sql` and the managed files in `packages/database/src/event-system/functions/`) — the helpers live in the internal `util` schema, NOT `public`:- `util.send_inngest_event(name, data)` — SECURITY DEFINER; `net.http_post`s `{ name, data }` to the Vault secret `inngest_event_url` (`<base>/e/<eventKey>`). Error-swallowed and no-ops when the secret is unset — OLTP writes never fail on push failure. pg_net queues the request transactionally, so the event fires only after commit. Postgres calls no edge function.- `util.wake_event_queue()` — sends `carbon/event-queue.process` through it.-- `public.set_inngest_event_url(url)` writes the secret (refuses `anon`/`authenticated`). The URL carries the event key, so it lives in Vault, not in `config` (which has a SELECT policy). A no-op when the URL is unchanged (`20261003134512`). Both setters take one advisory lock (`20261003191518`), so concurrent writers (app registration, deploy, operator) serialize instead of failing on the Vault's unique name. The ERP keeps the KEY in it current whenever it registers with Inngest: a `PUT /api/inngest` (`apps/erp/app/routes/api+/inngest.ts`) calls `public.set_inngest_event_config(key, base)` before the registration handshake, in production. That PUT happens on every deploy (Vercel's Inngest integration, `ci/src/jobs.ts`) and on every boot of a long-lived host (`inngest-self-sync.server.ts`), inside a request, once per registration rather than once per instance. Not at module load: a serverless host froze those calls mid-connect. (`20261003142107`): it creates the URL from its own `INNGEST_BASE_URL` when none is stored, and otherwise rewrites only the `<eventKey>` segment — a stored address is never changed, since the database may reach Inngest somewhere the app does not. So a deployment needs no separate step. `ci/src/migrations.ts` calls the same function on every deploy for a workspace with an `inngest_event_key` (retried while PostgREST reloads its schema), so a changed `inngest_base_url` there needs `set_inngest_event_url` by hand. Set in full by `packages/database/src/seed.ts` (`resolveInngestEventUrl`), locally by `ensureConfigRow` in `packages/dev/src/services/migrations.ts` (`http://inngest:8288/e/NO_EVENT_KEY_SET`) and by `scripts/restore-database.sh` after it clears Vault on a local restore, and on self-host by `contrib/deploying/simple-docker-caddy/deploy.sh migrate` (`set_inngest_event_url`, reading the key from the erp task). In CI a workspace missing `inngest_event_key` or the service role key logs an error and fails the run, after seeding and scripts, which do not depend on it.+- `public.set_inngest_event_url(url)` writes the secret (refuses `anon`/`authenticated`). The URL carries the event key, so it lives in Vault, not in `config` (which has a SELECT policy). A no-op when the URL is unchanged (`20261003134512`). Both setters take one advisory lock (`20261003191518`), so concurrent writers (app registration, deploy, operator) serialize instead of failing on the Vault's unique name. The ERP keeps the KEY in it current whenever it registers with Inngest: a `PUT /api/inngest` (`apps/erp/app/routes/api+/inngest.ts`) calls `public.set_inngest_event_config(key, base)` before the registration handshake, in production. That PUT happens on every deploy (Vercel's Inngest integration, `ci/src/post-deploy.ts`) and on every boot of a long-lived host (`inngest-self-sync.server.ts`), inside a request, once per registration rather than once per instance. Not at module load: a serverless host froze those calls mid-connect. (`20261003142107`): it creates the URL from its own `INNGEST_BASE_URL` when none is stored, and otherwise rewrites only the `<eventKey>` segment — a stored address is never changed, since the database may reach Inngest somewhere the app does not. So a deployment needs no separate step. `ci/src/migrations.ts` calls the same function on every deploy for a workspace with an `inngest_event_key` (retried while PostgREST reloads its schema), so a changed `inngest_base_url` there needs `set_inngest_event_url` by hand. Set in full by `packages/database/src/seed.ts` (`resolveInngestEventUrl`), locally by `ensureConfigRow` in `packages/dev/src/services/migrations.ts` (`http://inngest:8288/e/NO_EVENT_KEY_SET`) and by `scripts/restore-database.sh` after it clears Vault on a local restore, and on self-host by `contrib/deploying/simple-docker-caddy/deploy.sh migrate` (`set_inngest_event_url`, reading the key from the erp task). In CI a workspace missing `inngest_event_key` or the service role key logs an error and fails the run, after seeding and scripts, which do not depend on it.- `dispatch_event_batch()` calls `util.wake_event_queue()` at most **once per transaction** via the txn-local GUC `carbon.event_wake_sent` (`set_config(..., true)`).- `util.sweep_event_queue()` — pg_cron job `event-queue-sweeper` re-wakes every minute while *visible* messages (`vt <= clock_timestamp()`) sit in `pgmq.q_event_system`.- **Why `util`, not `public`:** a public function is auto-exposed as a PostgREST RPC, and a non-superuser reference to a function that transitively calls `net.http_post` segfaults the backend (pg_net 0.20 / PG15) — a remote-DoS surface a `REVOKE` can't close because the crash precedes the privilege check. anon/authenticated have no `USAGE` on `util`, so the API can't reach it. The trigger and pg_cron call it as the owner (superuser), where the pg_net path is safe.diff --git a/.claude/rules/sst-deployment-infrastructure.md b/.claude/rules/sst-deployment-infrastructure.mdindex 162ce820be..9dd64840a1 100644--- a/.claude/rules/sst-deployment-infrastructure.md+++ b/.claude/rules/sst-deployment-infrastructure.md@@ -5,7 +5,7 @@ paths:- "ci/**"- ".github/workflows/deploy.yml"- ".github/workflows/build-images.yml"- - ".github/workflows/inngest.yml"+ - ".github/workflows/post-deploy.yml"- "Dockerfile"- "apps/erp/app/utils/inngest-self-sync.server.ts"- "apps/erp/app/entry.server.tsx"@@ -124,14 +124,19 @@ registration handshake, not Carbon-specific. Two independent triggers exist:app code that reads them for its own base-URL detection), but the adapterpath (`server/app.ts`, `@vercel/react-router` in `entry.server.tsx`) isstill live, so this stays inert there rather than retrying uselessly.-- **CI-triggered sync** (`.github/workflows/inngest.yml`, `ci/src/jobs.ts`):- called by `deploy.yml` (job `sync`) after its deploy job succeeds; also- runnable by hand. Reads every row in the+- **CI-triggered sync** (`.github/workflows/post-deploy.yml`, `ci/src/post-deploy.ts`):+ the one post-deploy step, whatever hosts the ERP. Called by `deploy.yml`+ (job `sync`) after its deploy job succeeds, run on a successful production+ deploy of the ERP's Vercel projects (`deployment_status`, environment+ `Production – carbon*`), and runnable by hand. Reads every row in the`workspaces` table and does the same `PUT .../api/inngest` against each`url_erp`. Redundant with boot self-sync today, but kept as anexternally-triggered backstop (e.g. if a task's own retries were exhaustedbefore the app was reachable). Only targets `url_erp`, never `url_mes` — MES- has no `/api/inngest` route to sync.+ has no `/api/inngest` route to sync. For a workspace with a `project_id`+ (hosted Supabase) it then copies the ERP's `/templates/*.html` into the+ project's Auth emails (`ci/src/auth-emails.ts`): hosted Auth cannot+ download templates the way self-hosted Auth does.Both hit the same handler (`apps/erp/app/routes/api+/inngest.ts`, `serve()`from `inngest/remix`) — the registration target URL is fixed by that route'sdiff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymlindex f19200089d..7124a74b23 100644--- a/.github/workflows/deploy.yml+++ b/.github/workflows/deploy.yml@@ -73,11 +73,12 @@ jobs:- name: Run deploymentrun: pnpm --filter ci ci:deploy- # Inngest learns the new function list once the new tasks serve it.+ # Inngest learns the new function list, and hosted Supabase the Auth+ # emails, once the new tasks serve them.sync:- name: Sync Inngest+ name: Post Deploy Syncneeds: deploy- uses: ./.github/workflows/inngest.yml+ uses: ./.github/workflows/post-deploy.ymlsecrets: inherit# One leg per AWS account (prod and govcloud); each deploys only its owndiff --git a/.github/workflows/functions.yml b/.github/workflows/functions.ymlindex 35d47e944f..916ff8aca9 100644--- a/.github/workflows/functions.yml+++ b/.github/workflows/functions.yml@@ -3,7 +3,7 @@ name: Deploy Self-Hosted Functionson:# Deploying edge functions to the self-hosted Supabase instance is independent# of the ECS app deploy, so trigger directly on pushes that touch the functions.- # (Sync Inngest Functions is the workflow that must wait for Deploy Apps.)+ # (Post Deploy Sync is the workflow that must wait for Deploy Apps.)push:branches: [main]paths: ["packages/database/supabase/functions/**"]diff --git a/.github/workflows/inngest.yml b/.github/workflows/inngest.ymldeleted file mode 100644index 736c0f347f..0000000000--- a/.github/workflows/inngest.yml+++ /dev/null@@ -1,35 +0,0 @@-name: Sync Inngest Functions--on:- # Called by deploy.yml after a successful deploy.- workflow_call:- workflow_dispatch:--permissions:- contents: read--jobs:- sync:- name: Sync Inngest- runs-on: ubuntu-latest-- steps:- - name: Checkout code- uses: actions/checkout@v7-- - uses: pnpm/action-setup@v6- - name: Setup Node.js- uses: actions/setup-node@v7- with:- node-version-file: .nvmrc- cache: pnpm-- - name: Install dependencies- run: pnpm install --frozen-lockfile-- - name: Sync Inngest functions- env:- SUPABASE_URL: ${{ secrets.SUPABASE_URL }}- SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}- SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}- run: pnpm --filter ci ci:jobsdiff --git a/.github/workflows/post-deploy.yml b/.github/workflows/post-deploy.ymlnew file mode 100644index 0000000000..bb734dfcdb--- /dev/null+++ b/.github/workflows/post-deploy.yml@@ -0,0 +1,55 @@+name: Post Deploy Sync++# What each workspace's freshly deployed ERP tells the services around it:+# Inngest its list of jobs, and a hosted Supabase project its Auth emails.+# The one place for that, whatever hosts the ERP: every host's deploy ends+# here.+on:+ # AWS: called by deploy.yml after a successful deploy.+ workflow_call:+ # Vercel, and any host that reports its deploys to GitHub: a production+ # ERP deploy that succeeded (the job's `if`).+ deployment_status:+ workflow_dispatch:++permissions:+ contents: read++# Several ERP projects finish within moments of each other, and each run+# syncs every workspace: one at a time, and a newer one replaces a run+# still waiting.+concurrency:+ group: post-deploy+ cancel-in-progress: false++jobs:+ sync:+ name: Post Deploy Sync+ # The ERP's Vercel projects are carbon, carbon-us and carbon-eu; MES,+ # docs and academy deploys, and previews, have nothing to sync.+ if: >-+ github.event_name != 'deployment_status' ||+ (github.event.deployment_status.state == 'success' &&+ startsWith(github.event.deployment.environment, 'Production – carbon'))+ runs-on: ubuntu-latest++ steps:+ - name: Checkout code+ uses: actions/checkout@v7++ - uses: pnpm/action-setup@v6+ - name: Setup Node.js+ uses: actions/setup-node@v7+ with:+ node-version-file: .nvmrc+ cache: pnpm++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Sync Inngest functions and Auth emails+ env:+ SUPABASE_URL: ${{ secrets.SUPABASE_URL }}+ SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}+ SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}+ run: pnpm --filter ci ci:post-deploydiff --git a/apps/academy/app/routes/_auth+/login.tsx b/apps/academy/app/routes/_auth+/login.tsxindex 12528ab36e..ff8318339e 100644--- a/apps/academy/app/routes/_auth+/login.tsx+++ b/apps/academy/app/routes/_auth+/login.tsx@@ -19,6 +19,7 @@ import {verifyBotProtection} from "@carbon/auth/auth.server";import { flash, getAuthSession } from "@carbon/auth/session.server";+import { markSignInBrowser } from "@carbon/auth/sign-in-browser.server";import { getUserByEmail } from "@carbon/auth/users.server";import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";import { Ratelimit, redis } from "@carbon/kv";@@ -119,7 +120,11 @@ export async function action({ request }: ActionFunctionArgs) {);}- return { success: true };+ // This browser asked: the email's link completes only here.+ return data(+ { success: true as const },+ { headers: { "Set-Cookie": await markSignInBrowser() } }+ );}export default function LoginRoute() {diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 813ed2185e..aec58442c8 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -5332,6 +5332,7 @@ export async function sendPostedSalesInvoice(}await trigger("send-email", {+ document: true,to: [seller.data.email, contact.email!],cc: args.cc?.length ? args.cc : undefined,from: seller.data.email,diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.tsindex 976c098020..99e93e1cba 100644--- a/apps/erp/app/modules/purchasing/purchasing.server.ts+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts@@ -477,6 +477,7 @@ export const finalizePurchasingRfqAndNotify = defineServiceFn({const body = `Hey ${email.firstName},\n\nPlease provide pricing and lead time(s) for the linked quote:`;const signature = `Thanks,\n${user.data.firstName} ${user.data.lastName}\n${company.data.name}`;await trigger("send-email", {+ document: true,to: [user.data.email, email.to],from: user.data.email,subject: `Supplier Quote ${email.quoteReadableId} from ${company.data.name}`,@@ -759,6 +760,7 @@ export const sendSupplierQuoteToSupplier = defineServiceFn({const signature = `Thanks,\n${user.data.firstName} ${user.data.lastName}\n${company.data.name}`;try {await trigger("send-email", {+ document: true,to: [user.data.email, contact.data.contact.email].filter(Boolean) as string[],@@ -2493,6 +2495,7 @@ export const finalizePurchaseOrderAndNotify = defineServiceFn({);}await trigger("send-email", {+ document: true,to: email.to,cc: cc?.length ? cc : undefined,from: email.from,diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 3cbdc82613..e725c36e07 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -6672,6 +6672,7 @@ export async function releaseApprovedPurchaseOrder([{ filename: pdf.fileName, path: pdf.path }]);await trigger("send-email", {+ document: true,to: email.to,cc: cc?.length ? cc : undefined,from: email.from,diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex f5d01b6577..57cf2ea48d 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -12223,6 +12223,7 @@ export async function emailQuote(}await trigger("send-email", {+ document: true,to: [user.data.email, customerContact.data.contact!.email!],cc: args.cc?.length ? args.cc : undefined,from: user.data.email,diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 7538a256d4..eee1876377 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -1242,6 +1242,7 @@ export async function sendSalesOrderEmail(args: {.createSignedUrl(documentFilePath, 3600);await trigger("send-email", {+ document: true,to: [seller.data.email, customer.data.contact.email!],cc: ccSelections?.length ? ccSelections : undefined,from: seller.data.email,diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsxindex b15dd490c0..5c1a5006e9 100644--- a/apps/erp/app/routes/_public+/login.tsx+++ b/apps/erp/app/routes/_public+/login.tsx@@ -260,7 +260,7 @@ export async function action({ request }: ActionFunctionArgs) {);}logAuthEvent("magic_link_sent", { actor: email, ip });- // This browser asked: the link completes here (MAGIC_LINK_SAME_BROWSER).+ // This browser asked: the email's link completes only here.return data({ success: true, mode: "login", email },{ headers: { "Set-Cookie": await markSignInBrowser() } }@@ -917,7 +917,7 @@ function OutlookIcon(props: React.SVGProps<SVGSVGElement>) {* The code from the sign-in email, as an alternative to its link. It is* the link's own one-time token: a mail scanner that only opens the link* leaves it usable, one that presses the link page's button spends both- * (MAGIC_LINK_SAME_BROWSER hides that button from it). A verified code+ * (the button shows only in the browser that asked). A verified code* yields the same session the link's redirect does, handed to /callback the* same way, so everything after — company, SSO, MFA — is one path for both.*/diff --git a/apps/erp/app/routes/_public+/magic-link.tsx b/apps/erp/app/routes/_public+/magic-link.tsxindex 644c5b7de2..cb69245099 100644--- a/apps/erp/app/routes/_public+/magic-link.tsx+++ b/apps/erp/app/routes/_public+/magic-link.tsx@@ -2,11 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import {- CONTROLLED_ENVIRONMENT,- MAGIC_LINK_SAME_BROWSER,- SUPABASE_URL-} from "@carbon/auth";+import { CONTROLLED_ENVIRONMENT, SUPABASE_URL } from "@carbon/auth";import { isSignInBrowser } from "@carbon/auth/sign-in-browser.server";import { Button, Heading } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";@@ -19,15 +15,15 @@ import {} from "react-router";/**- * Whether this page may offer to spend the link's token. With- * MAGIC_LINK_SAME_BROWSER, only in the browser that asked for the email:+ * Whether this page may offer to spend the link's token: only in the+ * browser that asked for the email (sign-in-browser.server.ts), because* mail security sandboxes (Microsoft Defender) open the link in a real* browser and press its button, and the person then finds it used. Nothing* here spends anything — the token is only used by the button.*/export async function loader({ request }: LoaderFunctionArgs) {return {- sameBrowser: !MAGIC_LINK_SAME_BROWSER || (await isSignInBrowser(request))+ sameBrowser: await isSignInBrowser(request)};}@@ -43,8 +39,21 @@ export default function ConfirmMagicLink() {return null;}+ // The app that asked for the email: the link carries Auth's RedirectTo,+ // its /callback. Anything else (Auth's bare Site URL when it refused the+ // app's address, an older email without it) finishes here instead. Auth's+ // /verify redirects only to its allow list either way.+ const redirectTo = (() => {+ const asked = params.get("redirect_to");+ try {+ if (asked && new URL(asked).pathname === "/callback") return asked;+ } catch {+ // not a URL+ }+ return `${window?.location.origin}/callback`;+ })();const getConfirmationURL = (token: string) => {- return `${SUPABASE_URL}/auth/v1/verify?token=${token}&type=magiclink&redirect_to=${window?.location.origin}/callback`;+ return `${SUPABASE_URL}/auth/v1/verify?token=${token}&type=magiclink&redirect_to=${encodeURIComponent(redirectTo)}`;};return (diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 39cd493563..5acf4a0348 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -21,10 +21,12 @@ import {updateCompanySession} from "@carbon/auth/session.server";import { getUserClaims } from "@carbon/auth/users.server";+import { withEmailDelivery } from "@carbon/ee";import { isApprovalRequired } from "@carbon/ee/approvals.server";import { isAuditLogEnabled } from "@carbon/ee/audit.server";import { getPlan } from "@carbon/ee/plan.server";import { getVapidDetails } from "@carbon/env/push.server";+import { SERVER_MAIL_CONFIGURED } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { getImplementationCheckStates } from "@carbon/onboarding/server";import type { PrintingSettings } from "@carbon/printing";@@ -223,6 +225,13 @@ export async function loader({ request }: LoaderFunctionArgs) {});const companies = read(shell.data?.companies);const integrations = read(shell.data?.companyIntegrations);+ // Whether documents can be emailed, settled once for every+ // `integrations.has("email")` (withEmailDelivery).+ const companyIntegrations = withEmailDelivery(+ integrations.data ?? [],+ companyId,+ SERVER_MAIL_CONFIGURED+ );const companySettings = read(shell.data?.companySettings ?? undefined);const savedViews = read(shell.data?.savedViews);const user = read(shell.data?.user ?? undefined);@@ -339,7 +348,7 @@ export async function loader({ request }: LoaderFunctionArgs) {companySettings: companySettings.data ?? null,customFields: customFields.data ?? [],defaults: defaults.data,- integrations: integrations.data ?? [],+ integrations: companyIntegrations,groups: groups.data ?? [],permissions: claims?.permissions,plan,diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 1257ab353d..e079499b9a 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -10,8 +10,10 @@ import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import {integrations as availableIntegrations,+ emailSettingsForm,getIntegrationConfigById,type IntegrationID,+ picksServerMail,resolveIntegrationTopology} from "@carbon/ee";import {@@ -67,6 +69,7 @@ import { requireFeature } from "@carbon/ee/plan.server";import { LEDGER_FAMILY_KEYS, type LedgerFamilyKey } from "@carbon/ee/sync";import { STRIPE_SECRET_KEY } from "@carbon/env";import { validationError, validator } from "@carbon/form";+import { SERVER_MAIL_CONFIGURED } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { Badge } from "@carbon/react";import {@@ -517,6 +520,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {dynamicOptions.reimbursementBankAccountId = assetOptions;}+ // Server mail is offered only where the server has mail settings.+ const emailForm = emailSettingsForm(integrationId, SERVER_MAIL_CONFIGURED);+ if (emailForm?.providerOptions) {+ dynamicOptions.provider = emailForm.providerOptions;+ }+const integrationData = await getIntegration(client,integrationId,@@ -526,7 +535,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (integrationData.error || !integrationData.data) {return {installed: false,- metadata: {},+ // A fresh Email install starts on server mail where the server has it.+ metadata: emailForm?.initialMetadata ?? {},dynamicOptions,syncActivity: null,accountMapping: null,@@ -1276,6 +1286,19 @@ async function installIntegration({ request, params }: ActionFunctionArgs) {// integration active but non-functional, so require one here. Scoped to// form-entered secrets — OAuth providers get their credentials via the// callback, so they are never blocked here.+ const usesServerMail = picksServerMail(integrationId, metadata);+ if (usesServerMail && !SERVER_MAIL_CONFIGURED) {+ return data(+ {},+ await flash(+ request,+ error(+ null,+ "This server has no mail settings. Ask your administrator to set them up, or pick Resend or Custom SMTP."+ )+ )+ );+ }const FORM_SECRET_INTEGRATIONS = new Set(["linear","mount",@@ -1286,7 +1309,7 @@ async function installIntegration({ request, params }: ActionFunctionArgs) {"sense"]);if (- FORM_SECRET_INTEGRATIONS.has(integrationId) ||+ (FORM_SECRET_INTEGRATIONS.has(integrationId) && !usesServerMail) ||integrationId === ONSHAPE_GOVERNMENT_INTEGRATION_ID) {const alreadyVaulted = existing.data?.secretRef != null;diff --git a/apps/erp/app/utils/inngest-self-sync.server.ts b/apps/erp/app/utils/inngest-self-sync.server.tsindex b8ac3916b3..7c1850eae4 100644--- a/apps/erp/app/utils/inngest-self-sync.server.ts+++ b/apps/erp/app/utils/inngest-self-sync.server.ts@@ -11,7 +11,7 @@ const MAX_ATTEMPTS = 10;const RETRY_DELAY_MS = 2_000;// A PUT to our own serve endpoint is Inngest's registration handshake — the-// same request `ci/src/jobs.ts` curls from CI after a deploy. Doing it here+// same request `ci/src/post-deploy.ts` curls from CI after a deploy. Doing it here// too means a freshly booted task (deploy, ECS reschedule, autoscale-out)// re-syncs itself immediately instead of waiting on that external job, which// only fires after a "Deploy Apps" success on `main`. `serveHost` (set fromdiff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsxindex daab37d550..563d5c28ac 100644--- a/apps/mes/app/routes/_public+/login.tsx+++ b/apps/mes/app/routes/_public+/login.tsx@@ -252,7 +252,7 @@ export async function action({ request }: ActionFunctionArgs) {);}- // This browser asked: the link completes here (MAGIC_LINK_SAME_BROWSER).+ // This browser asked: the email's link completes only here.return data({ success: true, email },{ headers: { "Set-Cookie": await markSignInBrowser() } }@@ -800,7 +800,7 @@ function OutlookIcon(props: React.SVGProps<SVGSVGElement>) {* The code from the sign-in email, as an alternative to its link. It is* the link's own one-time token: a mail scanner that only opens the link* leaves it usable, one that presses the link page's button spends both- * (MAGIC_LINK_SAME_BROWSER hides that button from it). A verified code+ * (the button shows only in the browser that asked). A verified code* yields the same session the link's redirect does, handed to /callback the* same way, so everything after — company, SSO, MFA — is one path for both.*/diff --git a/apps/starter/app/routes/_public+/login.tsx b/apps/starter/app/routes/_public+/login.tsxindex 33929a906e..60322c2512 100644--- a/apps/starter/app/routes/_public+/login.tsx+++ b/apps/starter/app/routes/_public+/login.tsx@@ -19,6 +19,7 @@ import {verifyBotProtection} from "@carbon/auth/auth.server";import { flash, getAuthSession } from "@carbon/auth/session.server";+import { markSignInBrowser } from "@carbon/auth/sign-in-browser.server";import { getUserByEmail } from "@carbon/auth/users.server";import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";import { Ratelimit, redis } from "@carbon/kv";@@ -125,7 +126,11 @@ export async function action({ request }: ActionFunctionArgs) {);}- return { success: true };+ // This browser asked: the email's link completes only here.+ return data(+ { success: true as const },+ { headers: { "Set-Cookie": await markSignInBrowser() } }+ );}export default function LoginRoute() {diff --git a/ci/package.json b/ci/package.jsonindex c53250bd13..4401076ef7 100644--- a/ci/package.json+++ b/ci/package.json@@ -13,7 +13,7 @@"ci:migrations": "tsx src/migrations.ts","ci:deploy": "tsx src/deploy.ts","ci:assembler": "tsx src/assembler.ts",- "ci:jobs": "tsx src/jobs.ts",+ "ci:post-deploy": "tsx src/post-deploy.ts","test": "tsx --test src/*.test.ts"},"devDependencies": {diff --git a/ci/src/auth-emails.test.ts b/ci/src/auth-emails.test.tsnew file mode 100644index 0000000000..52e9f09739--- /dev/null+++ b/ci/src/auth-emails.test.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import assert from "node:assert/strict";+import { test } from "node:test";+import { authEmailSettings, pushAuthEmails } from "./auth-emails";++const template = (file: string) =>+ `<html>${file} <a href="{{ .SiteURL }}/x?token={{ .TokenHash }}">{{ .Token }}</a></html>`;++function fakeFetch(answers: (url: string) => Response) {+ const calls: { url: string; init?: RequestInit }[] = [];+ const impl = (async (url: string, init?: RequestInit) => {+ calls.push({ url, init });+ return answers(url);+ }) as typeof fetch;+ return { impl, calls };+}++test("sends every template the ERP serves, with its subject, in one PATCH", async () => {+ const { impl, calls } = fakeFetch((url) =>+ url.startsWith("https://api.supabase.com")+ ? new Response("{}")+ : new Response(template(url.split("/").pop()!))+ );+ await pushAuthEmails("https://app.example.com/", "ref123", "tok", impl);++ const patch = calls.at(-1)!;+ assert.equal(patch.url, "https://api.supabase.com/v1/projects/ref123/config/auth");+ assert.equal(patch.init?.method, "PATCH");+ assert.equal((patch.init?.headers as Record<string, string>).Authorization, "Bearer tok");+ const body = JSON.parse(patch.init!.body as string);+ assert.equal(body.mailer_subjects_magic_link, "Your Carbon sign-in code");+ assert.match(body.mailer_templates_magic_link_content, /magic-link\.html/);+ assert.match(body.mailer_templates_email_change_content, /email-change\.html/);+ assert.equal(Object.keys(body).length, 10);+ assert.equal(calls[0]!.url, "https://app.example.com/templates/magic-link.html");+});++test("never stores a page that is not a template", async () => {+ const { impl, calls } = fakeFetch(() => new Response("<html>Sign in</html>"));+ await assert.rejects(authEmailSettings("https://app.example.com", impl, 0), /not an Auth template/);+ assert.ok(calls.every((c) => !c.url.startsWith("https://api.supabase.com")));+});++test("waits out a release that is not serving yet, then gives up", async () => {+ let n = 0;+ const { impl } = fakeFetch((url) =>+ ++n <= 2 ? new Response("", { status: 404 }) : new Response(template(url))+ );+ const settings = await authEmailSettings("https://app.example.com", impl, 0);+ assert.equal(Object.keys(settings).length, 10);++ const down = fakeFetch(() => new Response("", { status: 502 }));+ await assert.rejects(authEmailSettings("https://app.example.com", down.impl, 0), /answered 502/);+});diff --git a/ci/src/auth-emails.ts b/ci/src/auth-emails.tsnew file mode 100644index 0000000000..aa8a5bd822--- /dev/null+++ b/ci/src/auth-emails.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * Auth's emails for a hosted Supabase project.+ *+ * Self-hosted Auth downloads its templates from the ERP when it sends+ * (GOTRUE_MAILER_TEMPLATES_*). Hosted Supabase cannot: its emails are+ * project settings, and nothing set them, so Carbon Cloud sent Supabase's+ * stock "Your Magic Link" email, with no sign-in code in it. After each+ * deploy, this copies the templates the deployed ERP serves+ * (routes/templates.$file.ts) into the project, so the emails match the+ * release that reads their codes and links.+ *+ * Not reauthentication: Carbon has no screen for its code, so Auth keeps+ * its own (packages/documents/src/email/auth/index.tsx).+ */+const AUTH_EMAILS = [+ { file: "magic-link.html", name: "magic_link", subject: "Your Carbon sign-in code" },+ { file: "invite.html", name: "invite", subject: "You have been invited to Carbon" },+ { file: "confirmation.html", name: "confirmation", subject: "Confirm your email for Carbon" },+ { file: "recovery.html", name: "recovery", subject: "Reset your Carbon password" },+ { file: "email-change.html", name: "email_change", subject: "Confirm your new email for Carbon" }+] as const;++/** The Management API's settings for every Auth email, read from the ERP. */+export async function authEmailSettings(+ erpUrl: string,+ fetchImpl: typeof fetch = fetch,+ retryDelayMs = 10_000+): Promise<Record<string, string>> {+ const entries = await Promise.all(+ AUTH_EMAILS.map(async ({ file, name, subject }) => {+ const url = `${erpUrl.replace(/\/+$/, "")}/templates/${file}`;+ // A deploy can return before every task of the new release is serving.+ let response: Response | undefined;+ for (let attempt = 1; attempt <= 6; attempt++) {+ response = await fetchImpl(url);+ if (response.ok || attempt === 6) break;+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));+ }+ if (!response?.ok) {+ throw new Error(`GET ${url} answered ${response?.status}`);+ }+ const html = await response.text();+ // A page that is not a template (an error page, a sign-in redirect)+ // must never become the email.+ if (+ !html.includes("{{ .SiteURL }}") &&+ !html.includes("{{ .ConfirmationURL }}")+ ) {+ throw new Error(`GET ${url} is not an Auth template`);+ }+ return [+ [`mailer_subjects_${name}`, subject],+ [`mailer_templates_${name}_content`, html]+ ] as const;+ })+ );+ return Object.fromEntries(entries.flat());+}++/** Sets a hosted project's Auth emails to the ones its ERP serves. */+export async function pushAuthEmails(+ erpUrl: string,+ projectRef: string,+ accessToken: string,+ fetchImpl: typeof fetch = fetch+): Promise<void> {+ const settings = await authEmailSettings(erpUrl, fetchImpl);+ const response = await fetchImpl(+ `https://api.supabase.com/v1/projects/${projectRef}/config/auth`,+ {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json"+ },+ body: JSON.stringify(settings)+ }+ );+ if (!response.ok) {+ throw new Error(+ `PATCH config/auth for ${projectRef} answered ${response.status}: ${await response.text()}`+ );+ }+}diff --git a/ci/src/jobs.ts b/ci/src/jobs.tsdeleted file mode 100644index e6547566ae..0000000000--- a/ci/src/jobs.ts+++ /dev/null@@ -1,57 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { $ } from "execa";--import { client } from "./client";--type Workspace = {- id: number;- url_erp: string | null;-};--async function jobs(): Promise<void> {- console.log("✅ 🌱 Starting background jobs sync");-- const { data: workspaces, error } = await client- .from("workspaces")- .select("id, url_erp");-- if (error) {- console.error("🔴 🍳 Failed to fetch workspaces", error);- process.exit(1);- }-- let hasErrors = false;-- for (const workspace of workspaces as Workspace[]) {- const { id, url_erp } = workspace;-- if (!url_erp) {- console.log(`⏭️ Skipping workspace ${id} — no url_erp`);- continue;- }-- try {- console.log(`✅ 🔄 Syncing jobs for workspace ${id} (${url_erp})`);- await $`curl -X PUT https://${url_erp}/api/inngest`;- console.log(`✅ 🐓 Successfully synced jobs for workspace ${id}`);- } catch (err) {- console.error(`🔴 🍳 Failed to sync jobs for workspace ${id}`, err);- hasErrors = true;- }- }-- if (hasErrors) {- console.error("🔴 Jobs sync completed with errors");- process.exit(1);- }-- console.log("✅ All jobs synced successfully");-}--jobs().catch((error) => {- console.error("🔴 Unexpected error during jobs sync", error);- process.exit(1);-});diff --git a/ci/src/post-deploy.ts b/ci/src/post-deploy.tsnew file mode 100644index 0000000000..24ca6b87f8--- /dev/null+++ b/ci/src/post-deploy.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { $ } from "execa";++import { pushAuthEmails } from "./auth-emails";+import { client } from "./client";+import { SUPABASE_ACCESS_TOKEN } from "./env";++type Workspace = {+ id: number;+ url_erp: string | null;+ project_id: string | null;+ access_token: string | null;+};++/** One thing a workspace's freshly deployed ERP tells a service. */+type Step = { name: string; run: () => Promise<unknown> };++function stepsFor(workspace: Workspace): Step[] {+ const { id, url_erp, project_id, access_token } = workspace;+ if (!url_erp) return [];+ const steps: Step[] = [+ {+ name: `Inngest sync for workspace ${id} (${url_erp})`,+ // --fail: an HTTP error is a failed sync, not a successful curl.+ run: () => $`curl --fail --silent --show-error -X PUT https://${url_erp}/api/inngest`+ }+ ];+ // A hosted Supabase project keeps Auth's emails as settings: copy in the+ // ones this ERP serves now that it is deployed (auth-emails.ts).+ if (project_id) {+ steps.push({+ name: `Auth emails for workspace ${id}`,+ run: () =>+ pushAuthEmails(+ `https://${url_erp}`,+ project_id,+ access_token ?? SUPABASE_ACCESS_TOKEN+ )+ });+ }+ return steps;+}++/**+ * After a deploy, for every workspace's ERP: Inngest learns its jobs+ * (PUT /api/inngest), and a hosted Supabase project gets its Auth emails+ * (auth-emails.ts). No step waits on another, so all of them run at once,+ * and one that fails fails the run only after the rest have finished.+ */+async function postDeploy(): Promise<void> {+ console.log("✅ 🌱 Starting the post-deploy sync");++ const { data: workspaces, error } = await client+ .from("workspaces")+ .select("id, url_erp, project_id, access_token");++ if (error) {+ console.error("🔴 🍳 Failed to fetch workspaces", error);+ process.exit(1);+ }++ for (const { id, url_erp } of workspaces as Workspace[]) {+ if (!url_erp) console.log(`⏭️ Skipping workspace ${id} — no url_erp`);+ }++ const results = await Promise.all(+ (workspaces as Workspace[]).flatMap(stepsFor).map(async (step) => {+ try {+ await step.run();+ console.log(`✅ ${step.name}`);+ return true;+ } catch (err) {+ console.error(`🔴 ${step.name} failed`, err);+ return false;+ }+ })+ );++ if (results.includes(false)) {+ console.error("🔴 Post-deploy sync completed with errors");+ process.exit(1);+ }++ console.log("✅ Post-deploy sync completed");+}++postDeploy().catch((error) => {+ console.error("🔴 Unexpected error during the post-deploy sync", error);+ process.exit(1);+});diff --git a/docs/components/editorial/architecture-diagrams.tsx b/docs/components/editorial/architecture-diagrams.tsxindex 2bbd7d5332..5c815c871e 100644--- a/docs/components/editorial/architecture-diagrams.tsx+++ b/docs/components/editorial/architecture-diagrams.tsx@@ -308,7 +308,7 @@ function Runs() {{ label: "check.yml", sub: "lint, types, tests" },{ label: "deploy.yml", sub: "build and push images" },{ label: "supabase.yml", sub: "migrations, edge fns" },- { label: "inngest.yml", sub: "register jobs" },+ { label: "post-deploy.yml", sub: "jobs, Auth emails" },];const ww = 164;return (diff --git a/docs/content/docs/building/architecture.mdx b/docs/content/docs/building/architecture.mdxindex 9b4bf5e0e6..adc8e817ed 100644--- a/docs/content/docs/building/architecture.mdx+++ b/docs/content/docs/building/architecture.mdx@@ -670,9 +670,9 @@ Pushing to `main` triggers each Vercel project's Git-integrated build. AWS deplo| -------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- || `check.yml` | every pull request | Biome, typecheck, tests, translation and workflow-catalog checks; an edge-functions job fails any `../` import out of a function's directory, then runs `deno check` || `build-images.yml` | every merge to `main` | builds or re-tags every image, tagged with the commit; when the merge touched `apps/erp`, `apps/mes`, `packages` or `docs/content` and both app images succeeded, it calls `deploy.yml` |-| `deploy.yml` | called by `build-images.yml`, or run by hand | fans out `sst deploy` per workspace, then calls `inngest.yml` |+| `deploy.yml` | called by `build-images.yml`, or run by hand | fans out `sst deploy` per workspace, then calls `post-deploy.yml` || `supabase.yml` | merge touching `packages/database/supabase` | applies migrations and deploys edge functions, per workspace |-| `inngest.yml` | called by `deploy.yml` after it succeeds | calls `PUT /api/inngest` on each app so Inngest learns the current list of jobs |+| `post-deploy.yml` | after every ERP deploy: called by `deploy.yml` on AWS, or on a successful Vercel production deploy | calls `PUT /api/inngest` on each app so Inngest learns the current list of jobs, and copies each ERP's Auth emails into its hosted Supabase project |`check.yml` does not build application images, so a successful pull request can still fail during image build.Database and application deployments run without ordering, so migrations must remain compatible with the previous application version.diff --git a/docs/content/docs/integrations/email.mdx b/docs/content/docs/integrations/email.mdxindex 1e90e05069..525643b31f 100644--- a/docs/content/docs/integrations/email.mdx+++ b/docs/content/docs/integrations/email.mdx@@ -1,28 +1,32 @@---title: Email-description: Send outbound email through Carbon-managed Resend or your own SMTP server.+description: Send outbound email through this server's mail settings, Resend, or your own SMTP server.----Carbon uses email for transactional messages such as order confirmations and notifications. Email is available on **every plan** and supports Resend or SMTP delivery.+Carbon uses email for transactional messages such as order confirmations and notifications. Email is available on **every plan** and supports server mail, Resend, or SMTP delivery.++On a single-tenant deployment (`TENANT_TYPE=single`, a self-hosted Carbon) whose server has mail settings, every company can email quotes, orders, invoices and RFQs without installing this integration: they go out through the server's mail settings, from the server's address under the company's name. Install the integration to have replies go to your own address, or to use your own Resend or SMTP account. On Carbon Cloud, or a server without mail settings, install the integration with Resend or SMTP.++These settings apply to document emails only. Sign-in, security and notification emails always go out from the server's sender address.<Steps><Step>### Choose a provider- Select **Resend** or **SMTP**. The configuration fields change for the selected provider.+ Select **Server mail**, **Resend** or **SMTP**. Server mail is offered only on a single-tenant deployment (`TENANT_TYPE=single`, a self-hosted Carbon) whose server has mail settings (`SMTP_HOST`), and is the default there. Carbon Cloud does not offer it: pick Resend or SMTP. The configuration fields change for the selected provider.</Step><Step>### Fill in the provider fields- For **Resend**, enter the API key. For **SMTP**, enter the host, port, credentials, and TLS setting. Configure the **from address** for either provider.+ For **Resend**, enter the API key. For **SMTP**, enter the host, port, credentials, and TLS setting. Server mail needs no credentials. Configure the **from address** for any provider. With server mail, documents are sent from the server's address under your company's name, and replies go to the address you enter; leave it empty to have replies go only to the person who sent the document.</Step></Steps><FieldTable>- <Field name="Provider">**Resend** (Carbon-managed) or **SMTP** (your own server).</Field>- <Field name="From address">The address outbound mail is sent from.</Field>+ <Field name="Provider">**Server mail** (this server's mail settings), **Resend** (Carbon-managed) or **SMTP** (your own server).</Field>+ <Field name="From address">The address document emails are sent from. Optional with server mail, where documents are sent from the server's address under your company's name and replies go to this address.</Field><Field name="API key">*(Resend)* Your Resend API key.</Field><Field name="Host / Port">*(SMTP)* Your mail server and port (default `587`).</Field><Field name="Username / Password">*(SMTP)* Credentials for the SMTP server.</Field>diff --git a/docs/content/docs/integrations/index.mdx b/docs/content/docs/integrations/index.mdxindex 87cb4b848e..9bc3e68b54 100644--- a/docs/content/docs/integrations/index.mdx+++ b/docs/content/docs/integrations/index.mdx@@ -52,7 +52,7 @@ Available integrations depend on deployment configuration. **Xero**, **Jira**, aPull quotes and BOMs from Paperless Parts.</Card><Card title="Email" href="/docs/integrations/email">- Send outbound email through Resend or your own SMTP server.+ Send outbound email through server mail, Resend, or your own SMTP server.</Card><Card title="Assistant" href="/docs/integrations/assistant">Bring the Carbon Assistant into Slack.diff --git a/docs/content/docs/platform/self-hosting/environment-variables.mdx b/docs/content/docs/platform/self-hosting/environment-variables.mdxindex 9acdd00a25..e270c3f071 100644--- a/docs/content/docs/platform/self-hosting/environment-variables.mdx+++ b/docs/content/docs/platform/self-hosting/environment-variables.mdx@@ -12,6 +12,7 @@ Platform-wide behavior and edition.<EnvVars><EnvVar name="CARBON_EDITION" type="enum">One of `community`, `cloud`, `enterprise`, or `test`. Gates edition-specific features.</EnvVar><EnvVar name="CONTROLLED_ENVIRONMENT" type="boolean">Enables ITAR / controlled-environment restrictions: the US-Person certification gate, ITAR hostnames and branding, Slack and analytics disabled, and mandatory [two-factor authentication](/docs/reference/two-factor) that a company admin cannot turn off.</EnvVar>+<EnvVar name="TENANT_TYPE" type="enum">`single` when one customer owns the deployment, as a self-hosted install does; `multi` (the default) for Carbon Cloud. With `single`, companies can send documents through the server's own mail ([Server mail](/docs/integrations/email)).</EnvVar><EnvVar name="AUTH_PROVIDERS" type="enum[]">Allowed sign-in methods: `email`, `google`, `azure`, `passkey`, `sso` ([single sign-on](/docs/reference/single-sign-on), Enterprise edition only).</EnvVar><EnvVar name="DOMAIN" type="string">Base domain the apps are served from.</EnvVar><EnvVar name="ERP_URL" type="url">Public URL of the ERP app. Required for the MES: it sends shop-floor postings (material issues, completions, picking) to this address.</EnvVar>diff --git a/packages/auth/src/lib/sign-in-browser.server.ts b/packages/auth/src/lib/sign-in-browser.server.tsindex ddbd1bdc57..fc081bc18f 100644--- a/packages/auth/src/lib/sign-in-browser.server.ts+++ b/packages/auth/src/lib/sign-in-browser.server.ts@@ -10,7 +10,7 @@ import { authCookieName, getCookieDomain } from "../utils/cookie";/*** Marks the browser that asked for a sign-in email, so the link in it can- * refuse to complete anywhere else (MAGIC_LINK_SAME_BROWSER). A mail+ * refuse to complete anywhere else. A mail* security sandbox opening the link has no such cookie, so it is shown a* page with nothing to press and the one-time token survives for the* person. On the shared DOMAIN, like the session, so a link the MES asked@@ -20,7 +20,7 @@ import { authCookieName, getCookieDomain } from "../utils/cookie";* when: it proves "this browser asked", not who for.** Without DOMAIN the cookie is host-only, and a link the MES asked for could- * never complete on the ERP's host. The flag must never make sign-in+ * never complete on the ERP's host. Binding must never make sign-in* impossible, so then every browser counts as the one that asked.*/const MAX_AGE_SECONDS = 60 * 60;@@ -52,7 +52,7 @@ export async function isSignInBrowser(request: Request): Promise<boolean> {if (!warnedUnbound) {warnedUnbound = true;log.warn(- "MAGIC_LINK_SAME_BROWSER is on but DOMAIN is unset: the ERP and MES share no cookie, so sign-in links are not bound to the browser that asked."+ "DOMAIN is unset: the ERP and MES share no cookie, so sign-in links are not bound to the browser that asked.");}return true;diff --git a/packages/documents/src/email/auth/auth.test.tsx b/packages/documents/src/email/auth/auth.test.tsxindex c45dd457c4..62c3228aa8 100644--- a/packages/documents/src/email/auth/auth.test.tsx+++ b/packages/documents/src/email/auth/auth.test.tsx@@ -11,7 +11,7 @@ import { authEmails } from ".";const placeholders: Record<keyof typeof authEmails, string[]> = {"magic-link.html": ["{{ .Token }}",- 'href="{{ .SiteURL }}/magic-link?token={{ .TokenHash }}"'+ 'href="{{ .SiteURL }}/magic-link?token={{ .TokenHash }}&redirect_to={{ .RedirectTo }}"'],"invite.html": ['href="{{ .SiteURL }}/confirm-invite?token={{ .TokenHash }}"'diff --git a/packages/documents/src/email/auth/index.tsx b/packages/documents/src/email/auth/index.tsxindex 932e3c359e..f55f939b78 100644--- a/packages/documents/src/email/auth/index.tsx+++ b/packages/documents/src/email/auth/index.tsx@@ -8,6 +8,9 @@ import { AUTH_TOKEN, AuthEmail } from "./AuthEmail";const SITE_URL = "{{ .SiteURL }}";const TOKEN_HASH = "{{ .TokenHash }}";const CONFIRMATION_URL = "{{ .ConfirmationURL }}";+/** The requesting app's /callback (emailRedirectTo), so the MES or academy+ * signs in where it was asked, not on the ERP that hosts /magic-link. */+const REDIRECT_TO = "{{ .RedirectTo }}";const ONCE = "The code and the button are the same sign-in: use either, once.";const IGNORE = "If you didn't ask for this, you can ignore this email.";@@ -19,7 +22,7 @@ export const AuthMagicLinkEmail = () => (intro="Enter this code on the sign-in screen, or use the button below."showCodeaction={{- href: `${SITE_URL}/magic-link?token=${TOKEN_HASH}`,+ href: `${SITE_URL}/magic-link?token=${TOKEN_HASH}&redirect_to=${REDIRECT_TO}`,label: "Sign in"}}footnote={`${ONCE} ${IGNORE}`}diff --git a/packages/ee/src/email/config.tsx b/packages/ee/src/email/config.tsxindex bba60907c8..64297a98ea 100644--- a/packages/ee/src/email/config.tsx+++ b/packages/ee/src/email/config.tsx@@ -13,9 +13,9 @@ export const Email = defineIntegration({category: "Email",logo: HiEnvelope,description:- "Send transactional emails — quotes, purchase orders, invoices, and more — from your own domain. Pick Resend for a managed email API, or Custom SMTP to use your own mail server.",+ "Send transactional emails — quotes, purchase orders, invoices, and more. Use this server's mail settings, or pick Resend or Custom SMTP to send from your own account.",shortDescription:- "Deliver transactional emails via Resend or a custom SMTP server.",+ "Deliver transactional emails via this server's mail settings, Resend, or a custom SMTP server.",images: [],settingGroups: [@@ -38,6 +38,12 @@ export const Email = defineIntegration({required: true,value: "resend",listOptions: [+ {+ value: "server",+ label: "Server mail",+ description:+ "The default. Documents are sent from this server's address under your company's name, so no credentials are needed."+ },{value: "resend",label: "Resend",@@ -54,9 +60,10 @@ export const Email = defineIntegration({name: "fromEmail",label: "From email",description:- "The sender address your customers will see. Must be a domain you control.",+ "The sender address your customers will see. Must be a domain you control. With Server mail, documents are sent from this server's address under your company's name, and replies go to the address you enter here.",type: "text",- required: true,+ // Required for Resend and Custom SMTP; the schema enforces that.+ required: false,value: ""},// Resend group@@ -120,6 +127,11 @@ export const Email = defineIntegration({}],schema: z.discriminatedUnion("provider", [+ z.object({+ provider: z.literal("server"),+ // Empty means "use this server's sender address".+ fromEmail: z.union([z.string().email(), z.literal("")]).default("")+ }),z.object({provider: z.literal("resend"),fromEmail: z.string().email(),diff --git a/packages/ee/src/email/delivery.test.ts b/packages/ee/src/email/delivery.test.tsnew file mode 100644index 0000000000..88e83654a7--- /dev/null+++ b/packages/ee/src/email/delivery.test.ts@@ -0,0 +1,171 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { describe, expect, it } from "vitest";+import {+ documentSender,+ emailSettingsForm,+ picksServerMail,+ resolveEmailDelivery,+ withEmailDelivery+} from "./delivery";++const installed = (metadata: Record<string, unknown>) => ({+ active: true,+ metadata+});++describe("resolveEmailDelivery", () => {+ it("sends a company without the integration through server mail", () => {+ expect(resolveEmailDelivery(null, true)).toEqual({ provider: "server" });+ expect(resolveEmailDelivery({ active: false, metadata: {} }, true)).toEqual(+ { provider: "server" }+ );+ });++ it("cannot send without the integration or server mail", () => {+ expect(resolveEmailDelivery(undefined, false)).toBeNull();+ });++ it("keeps an installed Resend or SMTP provider either way", () => {+ for (const serverMail of [true, false]) {+ expect(+ resolveEmailDelivery(+ installed({ provider: "smtp", fromEmail: "[email protected]" }),+ serverMail+ )+ ).toEqual({ provider: "smtp", fromEmail: "[email protected]" });+ }+ });++ it("reads a legacy install without a provider as Resend", () => {+ expect(+ resolveEmailDelivery(installed({ fromEmail: "[email protected]" }), false)+ ).toEqual({ provider: "resend", fromEmail: "[email protected]" });+ });++ it("uses server mail with the company's From when set", () => {+ expect(+ resolveEmailDelivery(+ installed({ provider: "server", fromEmail: " [email protected] " }),+ true+ )+ ).toEqual({ provider: "server", fromEmail: "[email protected]" });+ });++ it("falls back to the server's From when the company sets none", () => {+ expect(+ resolveEmailDelivery(+ installed({ provider: "server", fromEmail: "" }),+ true+ )+ ).toEqual({ provider: "server", fromEmail: undefined });+ });++ it("cannot send through server mail the server does not have", () => {+ expect(+ resolveEmailDelivery(installed({ provider: "server" }), false)+ ).toBeNull();+ });+});++describe("documentSender", () => {+ const server = (fromEmail?: string) => ({+ provider: "server" as const,+ fromEmail+ });+ const serverFrom = "Carbon <[email protected]>";++ it("never sends from the company's address, even on the server's domain", () => {+ expect(documentSender(server("[email protected]"), "Acme", serverFrom)).toEqual({+ from: { name: "Acme", address: "[email protected]" },+ replyTo: "[email protected]"+ });+ expect(documentSender(server("[email protected]"), "Acme", serverFrom)).toEqual({+ from: { name: "Acme", address: "[email protected]" },+ replyTo: "[email protected]"+ });+ });++ it("keeps a name with quotes or brackets as data, not address syntax", () => {+ expect(+ documentSender(server(), 'Acme "Evil" <[email protected]>', serverFrom).from+ ).toEqual({ name: 'Acme "Evil" <[email protected]>', address: "[email protected]" });+ });++ it("falls back to the server's name without a company name", () => {+ expect(documentSender(server(), null, serverFrom)).toEqual({+ from: { name: "Carbon", address: "[email protected]" },+ replyTo: undefined+ });+ expect(+ documentSender(server(), " ", '"Carbon" <[email protected]>').from+ ).toEqual({ name: "Carbon", address: "[email protected]" });+ // A bare server address has no name to borrow: the server's From stands.+ expect(documentSender(server(), null, "[email protected]")).toEqual({+ from: undefined,+ replyTo: undefined+ });+ });++ it("never sets a sender for Resend or SMTP integrations, or no delivery", () => {+ expect(+ documentSender(+ { provider: "smtp", fromEmail: "[email protected]" },+ "Acme",+ serverFrom+ )+ ).toEqual({});+ expect(documentSender(null, "Acme", serverFrom)).toEqual({});+ });+});++describe("withEmailDelivery", () => {+ const slack = { id: "slack", active: true, metadata: {} };++ it("gives a company without Email server mail when the server has it", () => {+ const shell = withEmailDelivery([slack], "c1", true);+ expect(shell.find((i) => i.id === "email")).toMatchObject({+ active: true,+ companyId: "c1",+ metadata: { provider: "server" }+ });+ });++ it("offers no Email when nothing can send", () => {+ expect(withEmailDelivery([slack], "c1", false)).toEqual([slack]);+ });++ it("keeps an installed Email, inactive when its server mail cannot send", () => {+ const email = {+ id: "email",+ active: true,+ metadata: { provider: "server" }+ };+ const shell = withEmailDelivery([slack, email], "c1", false);+ expect(shell.find((i) => i.id === "email")).toMatchObject({+ active: false,+ metadata: { provider: "server" }+ });+ });+});++describe("Email settings form", () => {+ it("offers and starts on server mail only where the server has it", () => {+ expect(emailSettingsForm("email", true)?.initialMetadata).toEqual({+ provider: "server"+ });+ const without = emailSettingsForm("email", false);+ expect(without?.providerOptions?.map((o) => o.value)).not.toContain(+ "server"+ );+ expect(emailSettingsForm("slack", true)).toBeNull();+ });++ it("knows a save that picks server mail", () => {+ expect(picksServerMail("email", { provider: "server" })).toBe(true);+ expect(picksServerMail("email", { provider: "smtp" })).toBe(false);+ expect(picksServerMail("slack", { provider: "server" })).toBe(false);+ });+});diff --git a/packages/ee/src/email/delivery.ts b/packages/ee/src/email/delivery.tsnew file mode 100644index 0000000000..25e6d2e788--- /dev/null+++ b/packages/ee/src/email/delivery.ts@@ -0,0 +1,124 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { Email } from "./config";++export type EmailDelivery = {+ provider: "server" | "resend" | "smtp";+ /** The company's sender address; unset means the server's default. */+ fromEmail?: string;+};++/**+ * How a company's documents are emailed, or null when they cannot be.+ *+ * An installed Email integration wins. A company without one sends through+ * this server's mail settings when the server has them, so server-wide mail+ * works without every company entering the same credentials again. Server+ * mail chosen on a server without mail settings cannot send, so it is null.+ * Legacy installs without a `provider` are Resend, as they always were.+ */+export function resolveEmailDelivery(+ integration: { active: boolean; metadata: unknown } | null | undefined,+ serverMailConfigured: boolean+): EmailDelivery | null {+ if (!integration?.active) {+ return serverMailConfigured ? { provider: "server" } : null;+ }+ const metadata = (integration.metadata ?? {}) as Record<string, unknown>;+ const provider = (metadata.provider ?? "resend") as EmailDelivery["provider"];+ if (provider === "server" && !serverMailConfigured) return null;+ const fromEmail =+ typeof metadata.fromEmail === "string" && metadata.fromEmail.trim()+ ? metadata.fromEmail.trim()+ : undefined;+ return { provider, fromEmail };+}++/**+ * The From and Reply-To of a document email (quote, order, invoice, purchase+ * order, RFQ) under a company's delivery settings. Every other email —+ * sign-in, security, notifications — always goes from the server's address.+ *+ * On server mail the From address is always the server's own: one server can+ * host many companies, and none may send as another's mailbox or the server's+ * own on the same domain. The company is named in the From's display name+ * instead (the server's name when the company has none), and its address, if+ * set, is the Reply-To.+ */+export function documentSender(+ delivery: EmailDelivery | null,+ companyName: string | null | undefined,+ serverFrom: string+): { from?: { name: string; address: string }; replyTo?: string } {+ if (delivery?.provider !== "server") return {};+ const server = serverFrom.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/);+ const address = server?.[2] ?? serverFrom.trim();+ const name = companyName?.trim() || server?.[1]?.trim();+ return {+ from: name ? { name, address } : undefined,+ replyTo: delivery.fromEmail+ };+}++/**+ * A company's integrations as the ERP shell offers them, with Email settled+ * for every `integrations.has("email")`: a company without the Email+ * integration sends through this server's mail settings when the server has+ * them, and one whose delivery cannot send is not offered Email at all.+ */+export function withEmailDelivery<+ T extends { id: string; active: boolean; metadata: unknown }+>(integrations: T[], companyId: string, serverMailConfigured: boolean) {+ const installed = integrations.find((i) => i.id === Email.id);+ const active = resolveEmailDelivery(installed, serverMailConfigured) !== null;+ const others = integrations.filter((i) => i.id !== Email.id);+ if (!installed && !active) return others;+ return [+ ...others,+ {+ id: Email.id,+ companyId,+ metadata: { provider: "server" },+ secretRef: null,+ updatedAt: "",+ updatedBy: null,+ ...installed,+ active+ }+ ];+}++/**+ * The Email settings form on this server, or null for another integration.+ * Server mail is offered, and is where a fresh install starts, only when the+ * server has mail settings.+ */+export function emailSettingsForm(+ integrationId: string,+ serverMailConfigured: boolean+) {+ if (integrationId !== Email.id) return null;+ if (serverMailConfigured) {+ return {+ providerOptions: undefined,+ initialMetadata: { provider: "server" } as Record<string, unknown>+ };+ }+ return {+ providerOptions:+ Email.settings+ .find((setting) => setting.name === "provider")+ ?.listOptions?.filter((option) => option.value !== "server") ?? [],+ initialMetadata: {} as Record<string, unknown>+ };+}++/** Whether an integration's settings pick Email's Server mail. */+export function picksServerMail(+ integrationId: string,+ metadata: Record<string, unknown>+): boolean {+ return integrationId === Email.id && metadata.provider === "server";+}diff --git a/packages/ee/src/email/hooks.server.ts b/packages/ee/src/email/hooks.server.tsindex 1bb777d836..fec1d746e7 100644--- a/packages/ee/src/email/hooks.server.ts+++ b/packages/ee/src/email/hooks.server.ts@@ -2,6 +2,7 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.+import { SERVER_MAIL_CONFIGURED } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { Email } from "./config";@@ -13,6 +14,10 @@ const logger = getLogger("ee", "email");* Validates the stored credentials for the company's chosen delivery* provider without actually sending a message:*+ * - `server`: healthy when this server has mail settings. The company's From+ * cannot make it undeliverable: it is only ever the Reply-To beside the+ * server's own From (see `documentSender`), so the relay only ever sees its+ * own sender.* - `resend`: hits `GET https://api.resend.com/domains` with the API key.* A 2xx means the key is valid and has read access; a 401* `restricted_api_key` means a valid "Sending access" key, also healthy.@@ -41,6 +46,7 @@ export async function emailHealthcheck(if (!parsed.success) return false;const data = parsed.data;+ if (data.provider === "server") return SERVER_MAIL_CONFIGURED;try {if (data.provider === "resend") {diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.tsindex 9a46aa614f..3c2773595b 100644--- a/packages/ee/src/index.ts+++ b/packages/ee/src/index.ts@@ -21,6 +21,14 @@ import type { QuickInstallConnector } from "./types";import { Xero } from "./xero/config";export { Email } from "./email/config";+export type { EmailDelivery } from "./email/delivery";+export {+ documentSender,+ emailSettingsForm,+ picksServerMail,+ resolveEmailDelivery,+ withEmailDelivery+} from "./email/delivery";export { defineIntegration } from "./fns";export type {Integration,diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 8ceb7bf3f0..63cadd89af 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -119,15 +119,11 @@ export const CONTROLLED_ENVIRONMENT = parseBoolean(itarEnvironment, false);export const MAINTENANCE_MODE = parseBoolean(getEnv("MAINTENANCE_MODE"), false);-// A sign-in link completes only in the browser that asked for it. Mail-// security sandboxes (Microsoft Defender) open links in a real browser and-// press the page's button; without this they spend the one-time token, and-// the person's own click finds it used. Elsewhere the email's code still-// works. Server-only, like the other auth switches.-export const MAGIC_LINK_SAME_BROWSER = parseBoolean(- getEnv("MAGIC_LINK_SAME_BROWSER"),- false-);+// "single": one customer owns this deployment and everything in it (BYOC, a+// self-hosted install), so the server's own settings, such as its mail, are+// theirs to share across their companies. Anything else, unset included, is+// Carbon Cloud's "multi": many customers, one server.+export const SINGLE_TENANT = getEnv("TENANT_TYPE") === "single";export const SYSTEM_STATUS_URL = getEnv("SYSTEM_STATUS_URL");diff --git a/packages/env/src/schema.ts b/packages/env/src/schema.tsindex 0e87f49712..f94325ce40 100644--- a/packages/env/src/schema.ts+++ b/packages/env/src/schema.ts@@ -118,6 +118,12 @@ export const schema = define({description: "true for an ITAR / controlled deployment",browser: true},+ TENANT_TYPE: {+ group: "core",+ type: z.enum(["single", "multi"]),+ description:+ "single for a deployment one customer owns (BYOC, self-hosted); multi (default) for Carbon Cloud"+ },MAINTENANCE_MODE: {group: "core",description: "true answers every request except /health with a 503"@@ -238,11 +244,6 @@ export const schema = define({secret: true,required: "error"},- MAGIC_LINK_SAME_BROWSER: {- group: "auth",- description:- "true: a sign-in link completes only in the browser that asked for it; needs DOMAIN, ignored without it (false)"- },AUTH_COOKIE_SUFFIX: {group: "auth",description:diff --git a/packages/jobs/src/inngest/functions/notifications/send-email.test.ts b/packages/jobs/src/inngest/functions/notifications/send-email.test.tsnew file mode 100644index 0000000000..da38e4504a--- /dev/null+++ b/packages/jobs/src/inngest/functions/notifications/send-email.test.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { beforeEach, describe, expect, it, vi } from "vitest";++const sendEmail = vi.fn();+const integration = vi.fn();+const company = vi.fn();++vi.mock("@carbon/lib/email.server", () => ({+ DEFAULT_FROM: "Carbon <[email protected]>",+ SERVER_MAIL_CONFIGURED: true,+ sendEmail+}));++vi.mock("@carbon/auth/client.server", () => {+ const query = (maybeSingle: () => unknown) => {+ const q = { select: () => q, eq: () => q, maybeSingle };+ return q;+ };+ return {+ getCarbonServiceRole: () => ({+ from: (table: string) =>+ query(table === "company" ? company : integration)+ })+ };+});++// The real delivery rules, without the rest of @carbon/ee (it opens clients).+vi.mock("@carbon/ee", () => import("../../../../../ee/src/email/delivery"));++// The handler is all this test needs from the Inngest function.+vi.mock("../../client", () => ({+ inngest: {+ createFunction: (_config: unknown, _trigger: unknown, handler: unknown) =>+ handler+ }+}));++const { sendEmailFunction } = await import("./send-email");+const handler = sendEmailFunction as unknown as (ctx: unknown) => Promise<void>;++const send = (data: Record<string, unknown>) =>+ handler({+ event: {+ data: {+ to: "[email protected]",+ subject: "s",+ html: "h",+ text: "t",+ ...data+ }+ },+ step: { run: (_id: string, fn: () => unknown) => fn() },+ logger: { info: vi.fn(), error: vi.fn() }+ });++const companyFrom = (fromEmail: string, name: string | null = "Acme") => {+ integration.mockResolvedValue({+ data: { active: true, metadata: { provider: "server", fromEmail } },+ error: null+ });+ company.mockResolvedValue({ data: { name }, error: null });+};++const serverAs = (name: string) => ({ name, address: "[email protected]" });++describe("send-email From and Reply-To", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sendEmail.mockResolvedValue({ data: { id: "m1" }, error: null });+ });++ it("never sends a document from the company's address on the server's domain", async () => {+ companyFrom("[email protected]");+ await send({ companyId: "c1", document: true, from: "[email protected]" });+ expect(sendEmail).toHaveBeenCalledWith(+ expect.objectContaining({+ from: serverAs("Acme"),+ replyTo: "[email protected], [email protected]"+ })+ );+ });++ it("replies to the company's address on another domain too", async () => {+ companyFrom("[email protected]");+ await send({ companyId: "c1", document: true, from: "[email protected]" });+ expect(sendEmail).toHaveBeenCalledWith(+ expect.objectContaining({+ from: serverAs("Acme"),+ replyTo: "[email protected], [email protected]"+ })+ );+ });++ it("falls back to the server's name when the company has none", async () => {+ companyFrom("", null);+ await send({ companyId: "c1", document: true, from: "[email protected]" });+ expect(sendEmail).toHaveBeenCalledWith(+ expect.objectContaining({+ from: serverAs("Carbon"),+ replyTo: "[email protected]"+ })+ );+ });++ it("sends system mail from the server whatever the company sets", async () => {+ companyFrom("[email protected]");+ await send({ companyId: "c1" });+ expect(integration).not.toHaveBeenCalled();+ expect(company).not.toHaveBeenCalled();+ expect(sendEmail).toHaveBeenCalledWith(+ expect.objectContaining({ from: undefined, replyTo: undefined })+ );+ });+});diff --git a/packages/jobs/src/inngest/functions/notifications/send-email.ts b/packages/jobs/src/inngest/functions/notifications/send-email.tsindex 5ddf405ab7..ff0618ba26 100644--- a/packages/jobs/src/inngest/functions/notifications/send-email.ts+++ b/packages/jobs/src/inngest/functions/notifications/send-email.ts@@ -3,7 +3,12 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { sendEmail } from "@carbon/lib/email.server";+import { documentSender, resolveEmailDelivery } from "@carbon/ee";+import {+ DEFAULT_FROM,+ SERVER_MAIL_CONFIGURED,+ sendEmail+} from "@carbon/lib/email.server";import { NonRetriableError } from "inngest";import { inngest } from "../../client";import { emailDeliveryFailure } from "./delivery-failure";@@ -43,11 +48,55 @@ export const sendEmailFunction = inngest.createFunction(const result = await step.run("send-email", async () => {logger.info("Email Job");+ // Only document emails follow the company's Email settings; sign-in,+ // security and notification mail always goes from the server's address.+ let sender: ReturnType<typeof documentSender> = {};+ if (payload.document && payload.companyId) {+ const client = getCarbonServiceRole();+ const integration = await client+ .from("companyIntegration")+ .select("active, metadata")+ .eq("id", "email")+ .eq("companyId", payload.companyId)+ .maybeSingle();+ if (integration.error) {+ logger.error("Failed to read the company's Email integration", {+ companyId: payload.companyId,+ error: integration.error+ });+ throw integration.error;+ }+ const delivery = resolveEmailDelivery(+ integration.data,+ SERVER_MAIL_CONFIGURED+ );+ if (delivery?.provider === "server") {+ const company = await client+ .from("company")+ .select("name")+ .eq("id", payload.companyId)+ .maybeSingle();+ if (company.error) {+ logger.error("Failed to read the company's name", {+ companyId: payload.companyId,+ error: company.error+ });+ throw company.error;+ }+ sender = documentSender(delivery, company.data?.name, DEFAULT_FROM);+ }+ }+ // Replies reach the person who sent the document and the company's+ // address, which server mail never sends from.+ const replyTo = [...new Set([payload.from, sender.replyTo])]+ .filter(Boolean)+ .join(", ");const response = await sendEmail({+ from: sender.from,attachments: payload.attachments,cc: ccRecipients,html: payload.html,- replyTo: payload.from,+ replyTo: replyTo || undefined,subject: payload.subject,text: payload.text,to: toRecipientsdiff --git a/packages/lib/src/email.server.test.ts b/packages/lib/src/email.server.test.tsindex ff3d0aa0fb..6fa51196b2 100644--- a/packages/lib/src/email.server.test.ts+++ b/packages/lib/src/email.server.test.ts@@ -14,6 +14,9 @@ vi.mock("nodemailer", () => ({// The real @carbon/env throws at import on unrelated required vars; mirror just// the SMTP accessors, reading process.env lazily so vi.stubEnv applies.vi.mock("@carbon/env", () => ({+ get SINGLE_TENANT() {+ return process.env.TENANT_TYPE === "single";+ },get SMTP_FROM() {return process.env.SMTP_FROM || undefined;},@@ -156,6 +159,28 @@ describe("sendEmail", () => {);});+ it("reports server mail as configured by SMTP_HOST only", async () => {+ vi.stubEnv("TENANT_TYPE", "single");+ expect((await loadMailer()).SERVER_MAIL_CONFIGURED).toBe(false);+ // The legacy shared Resend account never carries companies' documents.+ vi.stubEnv("RESEND_API_KEY", "re_123");+ expect((await loadMailer()).SERVER_MAIL_CONFIGURED).toBe(false);+ vi.stubEnv("RESEND_API_KEY", "");+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ expect((await loadMailer()).SERVER_MAIL_CONFIGURED).toBe(true);+ });++ it("offers server mail only on a single-tenant deployment", async () => {+ // Multi-tenant (Carbon Cloud, and the default): the server's mail is+ // Carbon's, shared by every customer.+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ expect((await loadMailer()).SERVER_MAIL_CONFIGURED).toBe(false);+ vi.stubEnv("TENANT_TYPE", "multi");+ expect((await loadMailer()).SERVER_MAIL_CONFIGURED).toBe(false);+ vi.stubEnv("TENANT_TYPE", "single");+ expect((await loadMailer()).SERVER_MAIL_CONFIGURED).toBe(true);+ });+it("no-ops without error when nothing is configured", async () => {const { sendEmail } = await loadMailer();const result = await sendEmail({ to: "[email protected]", subject: "hi", text: "x" });diff --git a/packages/lib/src/email.server.ts b/packages/lib/src/email.server.tsindex 81fd753b4f..9b38ee2a48 100644--- a/packages/lib/src/email.server.ts+++ b/packages/lib/src/email.server.ts@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import {+ SINGLE_TENANT,SMTP_FROM,SMTP_HOST,SMTP_PASSWORD,@@ -16,8 +17,8 @@ import nodemailer from "nodemailer";const log = getLogger("lib", "email");export type SendEmailPayload = {- /** Defaults to DEFAULT_FROM (SMTP_FROM). */- from?: string;+ /** Defaults to DEFAULT_FROM (SMTP_FROM). An object's name is quoted for you. */+ from?: string | { name: string; address: string };to: string | string[];cc?: string | string[];bcc?: string | string[];@@ -39,6 +40,17 @@ export type SendEmailResult = {export const DEFAULT_FROM =SMTP_FROM ?? `Carbon <no-reply@${process.env.RESEND_DOMAIN ?? "carbon.ms"}>`;+/**+ * Whether companies can send their documents through this server's own mail+ * settings: only when the deployment is single-tenant (TENANT_TYPE=single)+ * and SMTP_HOST is set. On a multi-tenant one (Carbon Cloud) the server's+ * mail is Carbon's, shared by every customer, so a company there sends+ * documents only through an Email integration it set up itself. The legacy+ * RESEND_API_KEY fallback below still sends sign-in and system mail, but it+ * is a shared account, so it never carries a company's documents.+ */+export const SERVER_MAIL_CONFIGURED = SINGLE_TENANT && Boolean(SMTP_HOST);+/** Domain of the default from-address, e.g. "carbon.ms". */export const EMAIL_DOMAIN =DEFAULT_FROM.match(/@([^>\s]+)/)?.[1] ?? "carbon.ms";diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex 7f40f161a5..44e3a132ef 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -83,6 +83,10 @@ export type Events = {| { filename: string; path: string }>;companyId: string;+ // A quote, order, invoice, purchase order or RFQ to a customer or+ // supplier: only these follow the company's Email settings (its From+ // address). Everything else always goes from the server's address.+ document?: true;// Recurring notification emails only: after the provider accepts the// send, the send-email function bumps the delivery counters for these.tracking?: {