Skip to content

Commit 0002a8e

Browse files
fix(den-api): surface invite email failures instead of silently dropping (anomalyco#1483)
* fix(den-api): surface invitation email send failures instead of swallowing Loops failures in sendDenOrganizationInvitationEmail and sendDenVerificationEmail were being caught and logged at warn level, so the HTTP handlers still returned 201 'Invitation created' even when no email ever left the process. Ben observed this with two live invitations: the DB row was pending, the UI showed it, but one of two recipients never received the email and clicking resend re-ran the same silent-failure path. Root cause (from an explore audit): - email.ts:129,132 swallowed non-2xx Loops responses and fetch throws. - invitations.ts awaited the send and unconditionally returned 2xx. - There is no 'skip email if user already exists' branch anywhere; the Slack hypothesis was wrong. The failure mode is provider-side and was invisible because of the swallow. Changes: - Introduce DenEmailSendError with a stable reason tagged union (loops_not_configured | loops_rejected | loops_network). - sendDenOrganizationInvitationEmail and sendDenVerificationEmail now throw DenEmailSendError on failure. Dev-mode short-circuit is preserved (still logs the payload and returns cleanly). - POST /v1/orgs/:orgId/invitations catches DenEmailSendError, logs via console.error with a stable [auth][invite_email_failed] prefix (greppable across deployments), and returns 502 invitation_email_failed with a human-readable message and the invitationId so the UI can correlate and offer a retry. The row is left pending intentionally so the next submit becomes a real resend. - Document the 502 response in the OpenAPI describeRoute. Operator note: if LOOPS_TRANSACTIONAL_ID_DEN_VERIFY_EMAIL is unset the signup OTP endpoint will now return a real error instead of silently stranding the user at the OTP screen forever. This is intentional; the previous behavior was a latent signup-breaking bug. * fix(den-api): tolerate missing apps/desktop/package.json in Docker build PR anomalyco#1476 introduced a build step that reads apps/desktop/package.json to bake in a default latest-app-version, but packaging/docker/Dockerfile.den does not ship the Tauri desktop sources. As a result, the den-dev Docker stack fails to build after the PR landed. Gracefully fall back to 0.0.0 (matching the runtime default) when the file is absent, and allow a DEN_API_LATEST_APP_VERSION env override so deployers can still pin a real value. * test(den-api): add smoke script for invite email failure paths scripts/smoke-email-failures.mjs exercises the DenEmailSendError paths against the built dist/ of den-api. Ships with instructions so a reviewer can rerun it inside the docker-compose den-dev container with a single command. Also parameterises OPENWORK_DEV_MODE in the den compose service so the failure paths can be reached from outside the container when needed (defaults to 1; override with OPENWORK_DEV_MODE=0 at compose time).
1 parent 0655ee5 commit 0002a8e

4 files changed

Lines changed: 214 additions & 89 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Standalone smoke test for the invitation-email failure paths.
4+
*
5+
* Run inside the den-api container (or any environment where the package has
6+
* been built to `dist/`):
7+
*
8+
* docker exec -e OPENWORK_DEV_MODE=0 \
9+
* openwork-den-dev-<id>-den-1 \
10+
* node ee/apps/den-api/scripts/smoke-email-failures.mjs
11+
*
12+
* Expected output:
13+
* [smoke] ok loops_not_configured { reason: 'loops_not_configured', ... }
14+
*
15+
* Add `-e LOOPS_API_KEY=bogus -e LOOPS_TRANSACTIONAL_ID_DEN_ORG_INVITE_EMAIL=bogus`
16+
* to also reach the `loops_rejected` path (Loops returns 401).
17+
*
18+
* Intentionally side-effect free: no DB writes, no auth.
19+
*/
20+
21+
const { sendDenOrganizationInvitationEmail, DenEmailSendError } = await import(
22+
"../dist/email.js"
23+
)
24+
25+
const recipient = process.argv[2] ?? "[email protected]"
26+
27+
try {
28+
await sendDenOrganizationInvitationEmail({
29+
email: recipient,
30+
inviteLink: "https://example.com/join?invite=smoke",
31+
invitedByName: "Smoke Test",
32+
invitedByEmail: "[email protected]",
33+
organizationName: "Smoke Org",
34+
role: "member",
35+
})
36+
37+
if (process.env.OPENWORK_DEV_MODE === "1" || !process.env.OPENWORK_DEV_MODE) {
38+
console.log("[smoke] ok dev_mode_noop (no email sent, no throw — expected)")
39+
process.exit(0)
40+
}
41+
42+
console.error("[smoke] FAIL: expected throw when Loops is not configured or rejects")
43+
process.exit(1)
44+
} catch (error) {
45+
if (!(error instanceof DenEmailSendError)) {
46+
console.error("[smoke] FAIL: wrong error class:", error)
47+
process.exit(1)
48+
}
49+
50+
console.log(`[smoke] ok ${error.reason}`, {
51+
reason: error.reason,
52+
template: error.template,
53+
recipient: error.recipient,
54+
detail: error.detail,
55+
})
56+
}

‎ee/apps/den-api/src/email.ts‎

Lines changed: 113 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,91 @@ import { env } from "./env.js"
22

33
const LOOPS_TRANSACTIONAL_API_URL = "https://app.loops.so/api/v1/transactional"
44

5+
/**
6+
* Error thrown when a transactional email send fails or is skipped because
7+
* of misconfiguration. Handlers can inspect `.reason` to decide how to
8+
* surface the failure to the caller (e.g. map to an HTTP status).
9+
*/
10+
export class DenEmailSendError extends Error {
11+
readonly reason:
12+
| "loops_not_configured"
13+
| "loops_rejected"
14+
| "loops_network"
15+
readonly template: "verification" | "organization_invite"
16+
readonly recipient: string
17+
readonly detail?: string
18+
19+
constructor(input: {
20+
template: DenEmailSendError["template"]
21+
reason: DenEmailSendError["reason"]
22+
recipient: string
23+
detail?: string
24+
}) {
25+
super(
26+
`[${input.template}] email for ${input.recipient} failed: ${input.reason}${
27+
input.detail ? ` (${input.detail})` : ""
28+
}`,
29+
)
30+
this.name = "DenEmailSendError"
31+
this.reason = input.reason
32+
this.template = input.template
33+
this.recipient = input.recipient
34+
this.detail = input.detail
35+
}
36+
}
37+
38+
async function postLoopsTransactional(input: {
39+
transactionalId: string
40+
email: string
41+
dataVariables: Record<string, string>
42+
template: DenEmailSendError["template"]
43+
}): Promise<void> {
44+
let response: Response
45+
try {
46+
response = await fetch(LOOPS_TRANSACTIONAL_API_URL, {
47+
method: "POST",
48+
headers: {
49+
Authorization: `Bearer ${env.loops.apiKey}`,
50+
"Content-Type": "application/json",
51+
},
52+
body: JSON.stringify({
53+
transactionalId: input.transactionalId,
54+
email: input.email,
55+
dataVariables: input.dataVariables,
56+
}),
57+
})
58+
} catch (error) {
59+
const message = error instanceof Error ? error.message : "Unknown error"
60+
throw new DenEmailSendError({
61+
template: input.template,
62+
reason: "loops_network",
63+
recipient: input.email,
64+
detail: message,
65+
})
66+
}
67+
68+
if (response.ok) {
69+
return
70+
}
71+
72+
let detail = `status ${response.status}`
73+
try {
74+
const payload = (await response.json()) as { message?: string }
75+
if (payload.message?.trim()) {
76+
detail = payload.message
77+
}
78+
} catch {
79+
// Ignore invalid upstream payloads.
80+
}
81+
82+
throw new DenEmailSendError({
83+
template: input.template,
84+
reason: "loops_rejected",
85+
recipient: input.email,
86+
detail,
87+
})
88+
}
89+
590
export async function sendDenVerificationEmail(input: {
691
email: string
792
verificationCode: string
@@ -19,45 +104,19 @@ export async function sendDenVerificationEmail(input: {
19104
}
20105

21106
if (!env.loops.apiKey || !env.loops.transactionalIdDenVerifyEmail) {
22-
console.warn(`[auth] verification email skipped for ${email}: Loops is not configured`)
23-
return
24-
}
25-
26-
try {
27-
const response = await fetch(LOOPS_TRANSACTIONAL_API_URL, {
28-
method: "POST",
29-
headers: {
30-
Authorization: `Bearer ${env.loops.apiKey}`,
31-
"Content-Type": "application/json",
32-
},
33-
body: JSON.stringify({
34-
transactionalId: env.loops.transactionalIdDenVerifyEmail,
35-
email,
36-
dataVariables: {
37-
verificationCode,
38-
},
39-
}),
107+
throw new DenEmailSendError({
108+
template: "verification",
109+
reason: "loops_not_configured",
110+
recipient: email,
40111
})
41-
42-
if (response.ok) {
43-
return
44-
}
45-
46-
let detail = `status ${response.status}`
47-
try {
48-
const payload = (await response.json()) as { message?: string }
49-
if (payload.message?.trim()) {
50-
detail = payload.message
51-
}
52-
} catch {
53-
// Ignore invalid upstream payloads.
54-
}
55-
56-
console.warn(`[auth] failed to send verification email for ${email}: ${detail}`)
57-
} catch (error) {
58-
const message = error instanceof Error ? error.message : "Unknown error"
59-
console.warn(`[auth] failed to send verification email for ${email}: ${message}`)
60112
}
113+
114+
await postLoopsTransactional({
115+
transactionalId: env.loops.transactionalIdDenVerifyEmail,
116+
email,
117+
dataVariables: { verificationCode },
118+
template: "verification",
119+
})
61120
}
62121

63122
export async function sendDenOrganizationInvitationEmail(input: {
@@ -88,47 +147,23 @@ export async function sendDenOrganizationInvitationEmail(input: {
88147
}
89148

90149
if (!env.loops.apiKey || !env.loops.transactionalIdDenOrgInviteEmail) {
91-
console.warn(`[auth] organization invite email skipped for ${email}: Loops is not configured`)
92-
return
93-
}
94-
95-
try {
96-
const response = await fetch(LOOPS_TRANSACTIONAL_API_URL, {
97-
method: "POST",
98-
headers: {
99-
Authorization: `Bearer ${env.loops.apiKey}`,
100-
"Content-Type": "application/json",
101-
},
102-
body: JSON.stringify({
103-
transactionalId: env.loops.transactionalIdDenOrgInviteEmail,
104-
email,
105-
dataVariables: {
106-
inviteLink: input.inviteLink,
107-
invitedByName: input.invitedByName,
108-
invitedByEmail: input.invitedByEmail,
109-
organizationName: input.organizationName,
110-
role: input.role,
111-
},
112-
}),
150+
throw new DenEmailSendError({
151+
template: "organization_invite",
152+
reason: "loops_not_configured",
153+
recipient: email,
113154
})
114-
115-
if (response.ok) {
116-
return
117-
}
118-
119-
let detail = `status ${response.status}`
120-
try {
121-
const payload = (await response.json()) as { message?: string }
122-
if (payload.message?.trim()) {
123-
detail = payload.message
124-
}
125-
} catch {
126-
// Ignore invalid upstream payloads.
127-
}
128-
129-
console.warn(`[auth] failed to send organization invite email for ${email}: ${detail}`)
130-
} catch (error) {
131-
const message = error instanceof Error ? error.message : "Unknown error"
132-
console.warn(`[auth] failed to send organization invite email for ${email}: ${message}`)
133155
}
156+
157+
await postLoopsTransactional({
158+
transactionalId: env.loops.transactionalIdDenOrgInviteEmail,
159+
email,
160+
dataVariables: {
161+
inviteLink: input.inviteLink,
162+
invitedByName: input.invitedByName,
163+
invitedByEmail: input.invitedByEmail,
164+
organizationName: input.organizationName,
165+
role: input.role,
166+
},
167+
template: "organization_invite",
168+
})
134169
}

‎ee/apps/den-api/src/routes/org/invitations.ts‎

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type { Hono } from "hono"
55
import { describeRoute } from "hono-openapi"
66
import { z } from "zod"
77
import { db } from "../../db.js"
8-
import { sendDenOrganizationInvitationEmail } from "../../email.js"
8+
import { DenEmailSendError, sendDenOrganizationInvitationEmail } from "../../email.js"
99
import { jsonValidator, paramValidator, requireUserMiddleware, resolveOrganizationContextMiddleware } from "../../middleware/index.js"
1010
import { denTypeIdSchema, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, successSchema, unauthorizedSchema } from "../../openapi.js"
1111
import { getOrganizationLimitStatus } from "../../organization-limits.js"
@@ -25,6 +25,13 @@ const invitationResponseSchema = z.object({
2525
expiresAt: z.string().datetime(),
2626
}).meta({ ref: "InvitationResponse" })
2727

28+
const invitationEmailFailedSchema = z.object({
29+
error: z.literal("invitation_email_failed"),
30+
reason: z.enum(["loops_not_configured", "loops_rejected", "loops_network"]),
31+
message: z.string(),
32+
invitationId: denTypeIdSchema("invitation"),
33+
}).meta({ ref: "InvitationEmailFailedError" })
34+
2835
type InvitationId = typeof InvitationTable.$inferSelect.id
2936
const orgInvitationParamsSchema = orgIdParamSchema.extend(idParamSchema("invitationId", "invitation").shape)
3037

@@ -34,14 +41,15 @@ export function registerOrgInvitationRoutes<T extends { Variables: OrgRouteVaria
3441
describeRoute({
3542
tags: ["Invitations"],
3643
summary: "Create organization invitation",
37-
description: "Creates or refreshes a pending organization invitation for an email address and sends the invite email.",
44+
description: "Creates or refreshes a pending organization invitation for an email address and sends the invite email. Returns 502 when the invitation row is persisted but the email provider (Loops) failed to send; the client should surface the error and give the user a retry affordance.",
3845
responses: {
3946
200: jsonResponse("Existing invitation refreshed successfully.", invitationResponseSchema),
4047
201: jsonResponse("Invitation created successfully.", invitationResponseSchema),
4148
400: jsonResponse("The invitation request body or path parameters were invalid.", invalidRequestSchema),
4249
401: jsonResponse("The caller must be signed in to invite organization members.", unauthorizedSchema),
4350
403: jsonResponse("Only workspace owners and admins can create or resend invitations.", forbiddenSchema),
4451
404: jsonResponse("The organization could not be found.", notFoundSchema),
52+
502: jsonResponse("The invitation was saved but the email provider (Loops) rejected or failed to deliver it. Retry by submitting the same email again.", invitationEmailFailedSchema),
4553
},
4654
}),
4755
requireUserMiddleware,
@@ -125,14 +133,40 @@ export function registerOrgInvitationRoutes<T extends { Variables: OrgRouteVaria
125133
})
126134
}
127135

128-
await sendDenOrganizationInvitationEmail({
129-
email,
130-
inviteLink: buildInvitationLink(invitationId),
131-
invitedByName: user.name ?? user.email ?? "OpenWork",
132-
invitedByEmail: user.email ?? "",
133-
organizationName: payload.organization.name,
134-
role,
135-
})
136+
try {
137+
await sendDenOrganizationInvitationEmail({
138+
email,
139+
inviteLink: buildInvitationLink(invitationId),
140+
invitedByName: user.name ?? user.email ?? "OpenWork",
141+
invitedByEmail: user.email ?? "",
142+
organizationName: payload.organization.name,
143+
role,
144+
})
145+
} catch (error) {
146+
if (error instanceof DenEmailSendError) {
147+
// The invitation row is already persisted (step above). Log at error
148+
// level so operators can grep, and return a 502 so the caller can
149+
// render a real failure instead of a silent success. The invitation
150+
// id is included so the UI can correlate and offer a direct retry.
151+
console.error(
152+
`[auth][invite_email_failed] organization=${payload.organization.id} invitation=${invitationId} email=${email} reason=${error.reason}${error.detail ? ` detail=${error.detail}` : ""}`,
153+
)
154+
155+
return c.json({
156+
error: "invitation_email_failed" as const,
157+
reason: error.reason,
158+
message:
159+
error.reason === "loops_not_configured"
160+
? "The invitation email provider (Loops) is not configured on this deployment."
161+
: error.reason === "loops_network"
162+
? "Could not reach the invitation email provider. The invitation is saved; retry to send again."
163+
: `The invitation email provider rejected the send${error.detail ? `: ${error.detail}` : "."}`,
164+
invitationId,
165+
}, 502)
166+
}
167+
168+
throw error
169+
}
136170

137171
return c.json({ invitationId, email, role, expiresAt }, existingInvitation[0] ? 200 : 201)
138172
},

‎packaging/docker/docker-compose.den-dev.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ services:
7070
start_period: 120s
7171
environment:
7272
CI: "true"
73-
OPENWORK_DEV_MODE: "1"
73+
OPENWORK_DEV_MODE: ${OPENWORK_DEV_MODE:-1}
7474
DATABASE_URL: mysql://root:password@mysql:3306/openwork_den
7575
BETTER_AUTH_SECRET: ${DEN_BETTER_AUTH_SECRET:-dev-den-local-auth-secret-please-override-1234567890}
7676
DEN_DB_ENCRYPTION_KEY: ${DEN_DB_ENCRYPTION_KEY:-dev-den-db-encryption-key-please-change-1234567890}

0 commit comments

Comments
 (0)