Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions MIGRATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@ Breaking changes and upgrade notes for downstream projects.

---

## Organizations: welcome email now sent after signup provisioning (2026-09-25)

Every successful signup that provisions a workspace — organizations enabled or
disabled — now fires a fire-and-forget `welcome` email to the new user. Never
sent on the A4 convergence path (existing membership) and never on the manual
"create another org" flow, so it fires exactly once per real new workspace.
Gated on `mailer.isConfigured()`: a disabled mailer, a synchronous throw, or a
rejected send can never break or delay the signup / OAuth redirect response.

**What you will see:** every new signup receives a welcome email once the
mailer is configured. To opt out, set `organizations.welcomeEmail.enabled:
false` in the project config (default `true`, fail-open — read with `?? true`
so an absent key never silently disables it). To customize the copy, edit the
same-named template at `config/templates/welcome.html` (`{{displayName}}`,
`{{appName}}`, `{{url}}`, `{{appContact}}`, and an optional
`{{#if orgName}}` block, omitted in B2C mode). No schema change, no migration
to run.

## Billing: public plans listing now requires a plan tag (2026-09-25)

`GET /api/billing/plans` no longer falls back to a Stripe product's raw id when
Expand Down
43 changes: 43 additions & 0 deletions config/templates/welcome.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{{appName}}</title>
</head>

<body>
<p>Hello {{displayName}},</p>
<p>
Welcome to {{appName}}{{#if orgName}} — your workspace <b>{{orgName}}</b> is ready{{/if}}.
</p>
<p>Here's where to pick things up:</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin: 24px 0">
<tr>
<td align="center" bgcolor="#1a1a1a" style="border-radius: 6px">
<a
href="{{url}}"
target="_blank"
rel="noopener noreferrer"
style="
display: inline-block;
padding: 12px 28px;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: bold;
line-height: 20px;
color: #ffffff;
text-decoration: none;
border-radius: 6px;
"
>Get started</a
>
</td>
</tr>
</table>
<p style="font-size: 13px; color: #9b9b9b">Button not working? <a href="{{url}}">{{url}}</a></p>
<p>The <b>{{appName}}</b> Team.</p>
<br />
<i style="color: #9b9b9b"
>Please do not reply to this email, you can contact us <a href="mailto:{{appContact}}">here</a>.</i
>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ const config = {
// is always auto-provisioned (same path as a mailer-not-configured env).
// emailVerified stays server-only; this policy only gates the existing checks.
emailVerification: { mode: 'strict' },
// Fail-open: read with `?? true` at the call site so an absent key (a
// downstream project that predates this option) never silently disables
// the welcome email — only an explicit `false` does.
welcomeEmail: { enabled: true },
roles: ['owner', 'admin', 'member'],
roleDescriptions: {
owner: 'Full control — manage organization settings, members, roles, and billing.',
Expand Down
61 changes: 59 additions & 2 deletions modules/organizations/services/organizations.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import mailer from '../../../lib/helpers/mailer/index.js';
import logger from '../../../lib/services/logger.js';
import policy from '../../../lib/middlewares/policy.js';
import serializeAbilities from '../../../lib/helpers/abilities.js';
import getBaseUrl from '../../../lib/helpers/getBaseUrl.js';
import OrganizationsRepository from '../repositories/organizations.repository.js';
import MembershipRepository from '../repositories/organizations.membership.repository.js';
import UserService from '../../users/services/users.service.js';
Expand Down Expand Up @@ -118,6 +119,57 @@ const createOrganizationForUser = async ({ name, slug, domain, user, slugGenerat
throw new Error('Failed to create organization: slug conflict after maximum retries');
};

/**
* Fire-and-forget welcome email sent once a fresh signup provisions a real
* workspace. Called from BOTH create branches of `handleSignupOrganization`
* (organizations enabled or disabled) — never from the A4 convergence path
* (existing membership, an early return above those branches) and never from
* the manual "create another org" flow (`organizations.crud.service.js`), so
* it fires exactly once per real new workspace with no dedup field needed.
* With strict email verification the send happens naturally after
* verification, since provisioning itself is deferred until then.
*
* Gated on `config.organizations.welcomeEmail.enabled` (default `true`,
* fail-open — read with `?? true` so an absent key on a downstream project
* never silently disables the email) and `mailer.isConfigured()`. Never
* awaited by the caller: a disabled toggle, a disabled mailer, a synchronous
* throw, or a rejected send must never break or delay the signup / OAuth
* redirect response.
* @param {Object} user - The newly signed-up user (id/_id, email, firstName, lastName).
* @param {string} [orgName] - Organization display name. Omitted in B2C mode
* (organizations disabled) — the template must not require it.
* @param {string} [orgId] - Organization id, for failure logging only (never
* passed to the template) — always in scope, including B2C mode.
* @returns {void}
*/
const sendWelcomeEmail = (user, orgName, orgId) => {
if (!(config.organizations?.welcomeEmail?.enabled ?? true)) return;
if (!mailer.isConfigured()) return;
const userId = user.id || user._id;
const onError = (err) => logger.warn('organizations: welcome email failed', {
userId: userId ? String(userId) : undefined,
...(orgId ? { orgId: String(orgId) } : {}),
message: err?.message,
stack: err?.stack,
});
try {
mailer.sendMail({
template: 'welcome',
to: user.email,
subject: `Welcome to ${config.app.title}`,
params: {
displayName: [user.firstName, user.lastName].filter(Boolean).join(' '),
url: getBaseUrl(),
appName: config.app.title,
appContact: config.app.contact,
...(orgName ? { orgName } : {}),
},
}).catch(onError);
} catch (err) {
onError(err);
}
};

/**
* Handle organization provisioning during the signup flow.
*
Expand Down Expand Up @@ -230,7 +282,10 @@ const handleSignupOrganization = async (user) => {
});

emitProvisioned(organization);
return buildResult(organization, membership);
const result = await buildResult(organization, membership);
Comment thread
PierreBrisorgueil marked this conversation as resolved.
// B2C mode — the workspace is a hidden default, never named to the user.
sendWelcomeEmail(user, undefined, organization._id);
return result;
}

// Case 2: Organizations enabled — always provision a workspace for the user.
Expand Down Expand Up @@ -285,8 +340,10 @@ const handleSignupOrganization = async (user) => {
});

emitProvisioned(organization);
const result = await buildResult(organization, membership);
sendWelcomeEmail(user, organization.name, organization._id);
return {
...(await buildResult(organization, membership)),
...result,
...(suggestedJoin ? { suggestedJoin } : {}),
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jest.unstable_mockModule('../../../lib/services/logger.js', () => ({

const mockIsConfigured = jest.fn();
jest.unstable_mockModule('../../../lib/helpers/mailer/index.js', () => ({
default: { isConfigured: mockIsConfigured, sendMail: jest.fn() },
default: { isConfigured: mockIsConfigured, sendMail: jest.fn().mockResolvedValue(null) },
}));

const mockOrganizationsRepositoryCreate = jest.fn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jest.unstable_mockModule('../lib/events.js', () => ({

const mockIsConfigured = jest.fn();
jest.unstable_mockModule('../../../lib/helpers/mailer/index.js', () => ({
default: { isConfigured: mockIsConfigured, sendMail: jest.fn() },
default: { isConfigured: mockIsConfigured, sendMail: jest.fn().mockResolvedValue(null) },
}));

const mockOrganizationsRepositoryCreate = jest.fn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { jest, describe, test, expect, beforeEach } from '@jest/globals';

const mockIsConfigured = jest.fn().mockReturnValue(false);
jest.unstable_mockModule('../../../lib/helpers/mailer/index.js', () => ({
default: { isConfigured: mockIsConfigured },
default: { isConfigured: mockIsConfigured, sendMail: jest.fn().mockResolvedValue(null) },
}));

const mockOrgCreate = jest.fn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ jest.unstable_mockModule('../../../lib/helpers/abilities.js', () => ({
}));

jest.unstable_mockModule('../../../lib/helpers/mailer/index.js', () => ({
default: { isConfigured: jest.fn().mockReturnValue(false) },
default: { isConfigured: jest.fn().mockReturnValue(false), sendMail: jest.fn().mockResolvedValue(null) },
}));

jest.unstable_mockModule('../../../config/index.js', () => ({
Expand Down
Loading
Loading