⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(auth): report invitation email delivery failures (#1798)
Tin Severef25ee2915c3
diff --git a/apps/api/src/auth-openapi.ts b/apps/api/src/auth-openapi.tsindex c696ed045..ac98c909a 100644--- a/apps/api/src/auth-openapi.ts+++ b/apps/api/src/auth-openapi.ts@@ -496,7 +496,8 @@ export function organizationRoutes(registry: OpenAPIHono["openAPIRegistry"]) {tags: ["Organization Management"],operationId: "inviteOrganizationMember",summary: "Invite Organization Member",- description: "Create an invitation to an organization",+ description:+ "Create or resend an invitation. Email delivery failures return 502; the invitation remains pending and can be resent after correcting SMTP settings.",request: {body: {required: true,@@ -524,6 +525,17 @@ export function organizationRoutes(registry: OpenAPIHono["openAPIRegistry"]) {},},responses: {+ 502: {+ description: "Invitation saved, but email delivery failed",+ content: {+ "application/json": {+ schema: z.object({+ code: z.literal("INVITATION_EMAIL_FAILED"),+ message: z.string(),+ }),+ },+ },+ },200: {description: "Success",content: {diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 4835d36b7..45470e9d3 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -646,6 +646,22 @@ export const auth = betterAuth({},hooks: {before: createAuthMiddleware(async (ctx) => {+ if (ctx.path === "/organization/invite-member") {+ // Better Auth swallows email failures in runInBackgroundOrAwait.+ // Invitation callers need the delivery result, including on resend.+ ctx.context.runInBackgroundOrAwait = async (promise) => {+ try {+ await promise;+ } catch {+ throw new APIError("BAD_GATEWAY", {+ code: "INVITATION_EMAIL_FAILED",+ message:+ "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation.",+ });+ }+ };+ }+if (isLoginFormDisabled && isLocalSignInPath(ctx.path)) {throw new APIError("FORBIDDEN", {message:diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex 53277d51e..80fbe9c7e 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -5257,7 +5257,7 @@],"operationId": "inviteOrganizationMember","summary": "Invite Organization Member",- "description": "Create an invitation to an organization",+ "description": "Create or resend an invitation. Email delivery failures return 502; the invitation remains pending and can be resent after correcting SMTP settings.","requestBody": {"required": true,"content": {@@ -5362,6 +5362,31 @@},"401": {"description": "Missing or invalid credentials"+ },+ "502": {+ "description": "Invitation saved, but email delivery failed",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "enum": [+ "INVITATION_EMAIL_FAILED"+ ]+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ]+ }+ }+ }}}}diff --git a/apps/web/src/components/team/invite-team-member-modal.test.tsx b/apps/web/src/components/team/invite-team-member-modal.test.tsxnew file mode 100644index 000000000..47dd37970--- /dev/null+++ b/apps/web/src/components/team/invite-team-member-modal.test.tsx@@ -0,0 +1,100 @@+import { QueryClientProvider } from "@tanstack/react-query";+import {+ act,+ cleanup,+ fireEvent,+ render,+ renderHook,+ screen,+ waitFor,+} from "@testing-library/react";+import type { PropsWithChildren } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import useInviteWorkspaceUser from "@/hooks/mutations/workspace-user/use-invite-workspace-user";+import { toast } from "@/lib/toast";+import queryClient from "@/query-client";+import InviteTeamMemberModal from "./invite-team-member-modal";++const { inviteMember } = vi.hoisted(() => ({ inviteMember: vi.fn() }));+vi.mock("@/lib/auth-client", () => ({+ authClient: { organization: { inviteMember } },+}));+vi.mock("react-i18next", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-i18next")>()),+ useTranslation: () => ({+ t: (key: string) =>+ key === "settings:invitationEmailFailed"+ ? "The invitation email could not be sent."+ : key,+ }),+}));+vi.mock("@/hooks/queries/workspace/use-active-workspace", () => ({+ default: () => ({ data: { id: "workspace" } }),+}));+vi.mock("@/hooks/use-workspace-permission", () => ({+ useWorkspacePermission: () => ({ canInviteUsers: () => true }),+}));+vi.mock("@/lib/toast", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+vi.mock("./invitation-link-field", () => ({ default: () => null }));+function wrapper({ children }: PropsWithChildren) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}+beforeEach(() => {+ vi.clearAllMocks();+ inviteMember.mockResolvedValue({+ data: null,+ error: { code: "INVITATION_EMAIL_FAILED", message: "Upstream failure" },+ });+});+afterEach(() => {+ cleanup();+ queryClient.clear();+});+describe("invitation email delivery errors", () => {+ it.each([false, true])(+ "rejects with a translated error when resend is %s",+ async (resend) => {+ const { result } = renderHook(useInviteWorkspaceUser, { wrapper });+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ await act(async () => {+ await expect(+ result.current.mutateAsync({+ workspaceId: "workspace",+ email: "[email protected]",+ role: "member",+ resend,+ }),+ ).rejects.toThrow("The invitation email could not be sent.");+ });+ expect(inviteMember).toHaveBeenCalledWith({+ organizationId: "workspace",+ email: "[email protected]",+ role: "member",+ resend,+ });+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: ["workspace-invites", "workspace"],+ });+ },+ );+ it("shows an error instead of a success notification in the invite modal", async () => {+ const onClose = vi.fn();+ render(<InviteTeamMemberModal open onClose={onClose} />, { wrapper });+ fireEvent.change(+ await screen.findByPlaceholderText("team:inviteModal.emailPlaceholder"),+ { target: { value: "[email protected]" } },+ );+ fireEvent.click(+ screen.getByRole("button", { name: "team:inviteModal.sendInvitation" }),+ );+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(+ "The invitation email could not be sent.",+ ),+ );+ expect(toast.success).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/hooks/mutations/workspace-user/use-invite-workspace-user.ts b/apps/web/src/hooks/mutations/workspace-user/use-invite-workspace-user.tsindex f850044cf..656f4dec1 100644--- a/apps/web/src/hooks/mutations/workspace-user/use-invite-workspace-user.ts+++ b/apps/web/src/hooks/mutations/workspace-user/use-invite-workspace-user.ts@@ -1,4 +1,5 @@import { useMutation } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";import { authClient } from "@/lib/auth-client";import queryClient from "@/query-client";@@ -10,6 +11,7 @@ type InviteWorkspaceUserRequest = {};function useInviteWorkspaceUser() {+ const { t } = useTranslation();return useMutation({mutationFn: async ({workspaceId,@@ -24,13 +26,16 @@ function useInviteWorkspaceUser() {resend,});+ if (error?.code === "INVITATION_EMAIL_FAILED") {+ throw new Error(t("settings:invitationEmailFailed"));+ }if (error) {throw new Error(error.message || "Failed to invite workspace member");}return data;},- onSuccess: (_, { workspaceId }) => {+ onSettled: (_, _error, { workspaceId }) => {queryClient.invalidateQueries({queryKey: ["workspace-invites", workspaceId],});diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex ac5af2b99..432763826 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex ef76d77b6..ea3e39763 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -1711,7 +1711,8 @@"loadError": "Kalender-Feeds oder Labels konnten nicht geladen werden. Bitte versuche es erneut.","deletedLabel": "Gelöschtes Label","permissionRequired": "Du benötigst die Berechtigung zum Teilen von Projekten, um Kalender-Feeds zu verwalten."- }+ },+ "invitationEmailFailed": "Einladung gespeichert, aber der E-Mail-Versand ist fehlgeschlagen. Prüfe die SMTP-Einstellungen und sende die Einladung erneut."},"navigation": {"commandPalette": {diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex 74ff98ef0..165bbecd0 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 2f523884f..85604d55f 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex 79d843a99..ec6cbef4a 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -1714,7 +1714,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex 9aaaf10ec..87a773d47 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -1714,7 +1714,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex 771051a81..8c7aec00e 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 241f6be2c..52b96f265 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -1708,7 +1708,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex 2a534e9cd..494debf9d 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -1714,7 +1714,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex 0453f2ec5..82e7b1c2b 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -1708,7 +1708,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex e07e81022..4ab7b20b8 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -1708,7 +1708,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 90d2d95dc..063e809b3 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 247be1257..5bf6914dd 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex ea4428742..dff753325 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -2194,7 +2194,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"tasks": {"title": "Zadania",diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex bb9ad2979..0da6258a1 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -1714,7 +1714,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex 4a4e9d331..7a5c14a86 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -1725,7 +1725,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/schema.json b/i18n/schema.jsonindex c2f0082c2..1ab36005e 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -6532,6 +6532,9 @@"deletedLabel","permissionRequired"]+ },+ "invitationEmailFailed": {+ "type": "string"}},"required": [@@ -6571,7 +6574,8 @@"externalLinks","security","securityPage",- "calendarFeeds"+ "calendarFeeds",+ "invitationEmailFailed"]},"navigation": {diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex a93779692..166fecb82 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -1711,7 +1711,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 5d51f0f25..2522d676e 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -1717,7 +1717,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex f7d3eb128..34fedd415 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -1708,7 +1708,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex ba292d5cf..f7300b2fd 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -1708,7 +1708,8 @@"loadError": "Could not load calendar feeds or labels. Please try again.","deletedLabel": "Deleted label","permissionRequired": "You need project-sharing permission to manage calendar feeds."- }+ },+ "invitationEmailFailed": "Invitation saved, but email delivery failed. Check SMTP settings and resend the invitation."},"navigation": {"commandPalette": {diff --git a/tests/api-integration/invitation-email-failure.test.ts b/tests/api-integration/invitation-email-failure.test.tsnew file mode 100644index 000000000..4eff771a1--- /dev/null+++ b/tests/api-integration/invitation-email-failure.test.ts@@ -0,0 +1,87 @@+import * as email from "@kaneo/email";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { resetTestDatabase } from "./helpers/database";++beforeEach(async () => {+ await resetTestDatabase();+});+const origin = "http://localhost:5173";+function post(path: string, body: unknown, cookie = "") {+ return createApp().app.request(`/api/auth${path}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Origin: origin,+ Cookie: cookie,+ },+ body: JSON.stringify(body),+ });+}+async function signedIn() {+ const response = await post("/sign-up/email", {+ name: "Account",+ email: "[email protected]",+ password: "original-password",+ });+ expect(response.status).toBe(200);+ return response.headers+ .getSetCookie()+ .map((value) => value.split(";")[0])+ .join("; ");+}++describe("invitation email failure reporting", () => {+ it("reports failed send and resend, keeps the pending invitation, and allows retry", async () => {+ const cookie = await signedIn();+ const created = await post(+ "/organization/create",+ { name: "Invites", slug: "invites" },+ cookie,+ );+ expect(created.status).toBe(200);+ const organization = await created.json();+ const send = vi+ .spyOn(email, "sendWorkspaceInvitationEmail")+ .mockRejectedValue(new Error("private SMTP error"));+ const body = {+ organizationId: organization.id,+ email: "[email protected]",+ role: "member",+ };+ const failed = await post("/organization/invite-member", body, cookie);+ expect(failed.status).toBe(502);+ expect(await failed.json()).toMatchObject({+ code: "INVITATION_EMAIL_FAILED",+ });+ expect(await db.select().from(schema.invitationTable)).toHaveLength(1);+ expect(+ (+ await post(+ "/organization/invite-member",+ { ...body, resend: true },+ cookie,+ )+ ).status,+ ).toBe(502);+ send.mockResolvedValue({ success: true });+ expect(+ (+ await post(+ "/organization/invite-member",+ { ...body, resend: true },+ cookie,+ )+ ).status,+ ).toBe(200);+ expect(await db.select().from(schema.invitationTable)).toHaveLength(1);+ // The strict invitation behavior must not replace the global background handler.+ await expect(+ (await auth.$context).runInBackgroundOrAwait(+ Promise.reject(new Error("background")),+ ),+ ).resolves.toBeUndefined();+ });+});