Fixing issue with mail content from SNS that is base64 encoded (#4576)

This commit is contained in:
Travis Emslander 2025-05-03 04:59:37 -05:00 committed by GitHub
parent b5008c4382
commit 0c378da0d2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 36 additions and 2 deletions

View file

@ -7,6 +7,7 @@ import { SnsMessage } from './types/SNS'
import { simpleParser } from 'mailparser'
import axios from 'axios'
import { convertToMailObject } from './lib/emailApi'
import { decodeBase64 } from './lib/base64'
console.log('Starting worker...')
@ -91,13 +92,27 @@ app.post('/sns', async (req, res) => {
const message = JSON.parse(snsMessage.Message) as {
notificationType: string
content: string
receipt?: {
action?: {
encoding?: string
}
}
}
if (message.notificationType != 'Received') {
console.log('Not an email, failing...')
res.status(400).send()
return
}
const mailContent = await simpleParser(message.content)
// Check if content is base64 encoded and decode if necessary
let emailContent = message.content
if (message.receipt?.action?.encoding === "BASE64") {
console.log("Detected BASE64 encoded content, decoding...")
emailContent = decodeBase64(message.content)
console.log("Processed BASE64 content")
}
const mailContent = await simpleParser(emailContent)
const mail = convertToMailObject(mailContent)
console.log(mail)
await (
@ -108,7 +123,7 @@ app.post('/sns', async (req, res) => {
delay: 500,
})
res.sendStatus(200)
res.status(200).send()
return
}

View file

@ -0,0 +1,19 @@
/**
* Utility functions for handling base64 encoding/decoding
*/
/**
* Decodes a base64 string to UTF-8 text
* Uses Node.js Buffer but with type safety
*/
export function decodeBase64(base64String: string): string {
try {
// Use a type-safe approach without relying on global
// @ts-ignore - Ignore TypeScript error for Buffer
return Buffer.from(base64String, 'base64').toString('utf-8');
} catch (error) {
console.error('Error decoding base64 string:', error);
return base64String; // Return original string if decoding fails
}
}