Skip to content
Open
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
21 changes: 21 additions & 0 deletions functions/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"jspdf": "^4.2.1",
"jspdf-autotable": "^5.0.2",
"luxon": "^3.7.2",
"nodemailer": "^8.0.3",
"openai": "^6.17.0",
"zod": "^3.25.76"
},
Expand All @@ -46,6 +47,7 @@
"@types/luxon": "^3.4.2",
"@types/mocha": "^10.0.7",
"@types/node": "^22",
"@types/nodemailer": "^7.0.11",
"@types/sinon": "^21.0.0",
"@typescript-eslint/eslint-plugin": "^8.54.0",
"@typescript-eslint/parser": "^8.54.0",
Expand All @@ -70,4 +72,4 @@
"serialize-javascript": "^7.0.4",
"http-proxy-agent": "^7.0.2"
}
}
}
42 changes: 42 additions & 0 deletions functions/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { defineSecret } from "firebase-functions/params";

enum SecretKey {
OPENAI_API_KEY = "OPENAI_API_KEY",
SMTP_HOST = "SMTP_HOST",
SMTP_PORT = "SMTP_PORT",
SMTP_USERNAME = "SMTP_USERNAME",
SMTP_PASSWORD = "SMTP_PASSWORD",
FEEDBACK_SENDER_EMAIL = "FEEDBACK_SENDER_EMAIL",
FEEDBACK_COORDINATOR_EMAIL = "FEEDBACK_COORDINATOR_EMAIL",
}

const openaiApiKey = defineSecret(SecretKey.OPENAI_API_KEY);
Expand All @@ -16,3 +22,39 @@ export const getOpenaiApiKey = (): string => openaiApiKey.value();
export const getOpenaiSecretKeys = (): string[] => [SecretKey.OPENAI_API_KEY];

export const openaiApiKeyParam: ReturnType<typeof defineSecret> = openaiApiKey;

const smtpHost = defineSecret(SecretKey.SMTP_HOST);
const smtpPort = defineSecret(SecretKey.SMTP_PORT);
const smtpUsername = defineSecret(SecretKey.SMTP_USERNAME);
const smtpPassword = defineSecret(SecretKey.SMTP_PASSWORD);
const feedbackSenderEmail = defineSecret(SecretKey.FEEDBACK_SENDER_EMAIL);
const feedbackCoordinatorEmail = defineSecret(
SecretKey.FEEDBACK_COORDINATOR_EMAIL,
);

export const getSmtpHost = (): string => smtpHost.value();

export const getSmtpPort = (): string => smtpPort.value();

export const getSmtpUsername = (): string => smtpUsername.value();

export const getSmtpPassword = (): string => smtpPassword.value();

export const getFeedbackSenderEmail = (): string => feedbackSenderEmail.value();

export const getFeedbackCoordinatorEmail = (): string =>
feedbackCoordinatorEmail.value();

export const smtpUsernameParam: ReturnType<typeof defineSecret> = smtpUsername;

export const smtpPasswordParam: ReturnType<typeof defineSecret> = smtpPassword;

export const feedbackEmailSecretParams: Array<ReturnType<typeof defineSecret>> =
[
smtpHost,
smtpPort,
smtpUsername,
smtpPassword,
feedbackSenderEmail,
feedbackCoordinatorEmail,
];
98 changes: 98 additions & 0 deletions functions/src/functions/onFeedbackCreated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// This source file is part of the MyHeart Counts project
//
// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md)
// SPDX-License-Identifier: MIT

import { logger } from "firebase-functions";
import { onDocumentCreated } from "firebase-functions/v2/firestore";
import { createTransport } from "nodemailer";
import type SMTPTransport from "nodemailer/lib/smtp-transport";
import {
feedbackEmailSecretParams,
getFeedbackCoordinatorEmail,
getFeedbackSenderEmail,
getSmtpHost,
getSmtpPassword,
getSmtpPort,
getSmtpUsername,
} from "../env.js";
import { defaultServiceAccount } from "./helpers.js";

const formatFeedbackEmail = (
feedbackId: string,
data: Record<string, unknown>,
): { subject: string; text: string } => {
const subject = `[MyHeartCounts] New Feedback Received (ID: ${feedbackId})`;

const { accountId, ...rest } = data;
const lines: string[] = [
`New feedback has been submitted.`,
``,
`Feedback ID: ${feedbackId}`,
`From user: ${typeof accountId === "string" ? accountId : "unknown"}`,
``,
`--- Feedback Content ---`,
];

for (const [key, value] of Object.entries(rest)) {
const formatted =
typeof value === "string" ? value : JSON.stringify(value, null, 2);
lines.push(`${key}: ${formatted}`);
}

return { subject, text: lines.join("\n") };
};

export const onFeedbackCreated = onDocumentCreated(
{
document: "feedback/{feedbackId}",
serviceAccount: defaultServiceAccount,
secrets: feedbackEmailSecretParams,
},
async (event) => {
const snapshot = event.data;
if (!snapshot) {
logger.warn("onFeedbackCreated: No data in event");
return;
}

const feedbackId = event.params.feedbackId;
const data = snapshot.data();
const { subject, text } = formatFeedbackEmail(feedbackId, data);

try {
// requireTLS/forceAuth make the transport fail loudly if the server does
// not offer STARTTLS or AUTH, instead of silently sending
// unauthenticated. forceAuth is supported by nodemailer at runtime but
// missing from @types/nodemailer, so the options object needs a cast.
const port = Number(getSmtpPort());
Comment thread
PaulGoldschmidt marked this conversation as resolved.
const transporter = createTransport({
host: getSmtpHost(),
port,
secure: port === 465,
requireTLS: true,
forceAuth: true,
logger: true,
auth: {
user: getSmtpUsername(),
pass: getSmtpPassword(),
},
} as SMTPTransport.Options);

await transporter.sendMail({
from: `"MyHeart Counts" <${getFeedbackSenderEmail()}>`,
to: getFeedbackCoordinatorEmail(),
subject,
text,
});

logger.info(
`Feedback notification sent for ${feedbackId} to ${getFeedbackCoordinatorEmail()}`,
);
} catch (error) {
logger.error(
`Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
);
}
Comment on lines +92 to +96

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Silent failure may cause lost notifications.

When email sending fails, the error is logged but not rethrown. This means Firebase considers the function successful and will not retry. Feedback notifications could be silently lost with only a log entry.

Consider whether this is intentional:

  • If notifications are critical: Rethrow the error so Firebase retries the function (with exponential backoff).
  • If best-effort is acceptable: Add alerting/monitoring on these error logs so failures are actionable.
Option A: Rethrow to enable retries
     } catch (error) {
       logger.error(
         `Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
       );
+      throw error; // Allow Firebase to retry
     }
Option B: Keep silent failure but document the decision
     } catch (error) {
+      // Intentionally not rethrowing: avoid duplicate emails on transient SMTP failures.
+      // Monitor these logs for persistent failures.
       logger.error(
         `Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
       );
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error) {
logger.error(
`Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
);
}
} catch (error) {
logger.error(
`Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
);
throw error; // Allow Firebase to retry
}
Suggested change
} catch (error) {
logger.error(
`Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
);
}
} catch (error) {
// Intentionally not rethrowing: avoid duplicate emails on transient SMTP failures.
// Monitor these logs for persistent failures.
logger.error(
`Failed to send feedback notification for ${feedbackId}: ${String(error)}`,
);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@functions/src/functions/onFeedbackCreated.ts` around lines 84 - 88, The catch
block in onFeedbackCreated currently only logs errors for send failures
(`logger.error(...)` referencing feedbackId) which prevents Firebase from
retrying; decide whether notifications are critical and either rethrow the error
(throw error) so Firebase will retry the function, or if you want best-effort
keep the swallow but add actionable monitoring (e.g., emit a metric/event or
call an alerting helper) and document the choice in onFeedbackCreated’s
comments; implement the chosen approach by modifying the catch block around the
email send call to either rethrow the caught error or invoke the
monitoring/alerting helper and leave a comment explaining the decision.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not a critcial component.

},
);
1 change: 1 addition & 0 deletions functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export * from "./functions/updateUserInformation.js";
export * from "./functions/planNudges.js";
export * from "./functions/planPosttrialNudges.js";
export * from "./functions/sendNudges.js";
export * from "./functions/onFeedbackCreated.js";
export * from "./functions/onUserQuestionnaireResponseWritten.js";
export * from "./functions/onUserDocumentSnapshot.js";
export * from "./functions/deleteHealthSamples.js";
Expand Down
Loading