@stacksjs/ts-cloud-core 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +321 -0
  3. package/package.json +31 -0
  4. package/src/advanced-features.test.ts +465 -0
  5. package/src/aws/cloudformation.ts +421 -0
  6. package/src/aws/cloudfront.ts +158 -0
  7. package/src/aws/credentials.test.ts +132 -0
  8. package/src/aws/credentials.ts +545 -0
  9. package/src/aws/index.ts +87 -0
  10. package/src/aws/s3.test.ts +188 -0
  11. package/src/aws/s3.ts +1088 -0
  12. package/src/aws/signature.test.ts +670 -0
  13. package/src/aws/signature.ts +1155 -0
  14. package/src/backup/disaster-recovery.test.ts +726 -0
  15. package/src/backup/disaster-recovery.ts +500 -0
  16. package/src/backup/index.ts +34 -0
  17. package/src/backup/manager.test.ts +498 -0
  18. package/src/backup/manager.ts +432 -0
  19. package/src/cicd/circleci.ts +430 -0
  20. package/src/cicd/github-actions.ts +424 -0
  21. package/src/cicd/gitlab-ci.ts +255 -0
  22. package/src/cicd/index.ts +8 -0
  23. package/src/cli/history.ts +396 -0
  24. package/src/cli/index.ts +10 -0
  25. package/src/cli/progress.ts +458 -0
  26. package/src/cli/repl.ts +454 -0
  27. package/src/cli/suggestions.ts +327 -0
  28. package/src/cli/table.test.ts +319 -0
  29. package/src/cli/table.ts +332 -0
  30. package/src/cloudformation/builder.test.ts +327 -0
  31. package/src/cloudformation/builder.ts +378 -0
  32. package/src/cloudformation/builders/api-gateway.ts +449 -0
  33. package/src/cloudformation/builders/cache.ts +334 -0
  34. package/src/cloudformation/builders/cdn.ts +278 -0
  35. package/src/cloudformation/builders/compute.ts +485 -0
  36. package/src/cloudformation/builders/database.ts +392 -0
  37. package/src/cloudformation/builders/functions.ts +343 -0
  38. package/src/cloudformation/builders/messaging.ts +140 -0
  39. package/src/cloudformation/builders/monitoring.ts +300 -0
  40. package/src/cloudformation/builders/network.ts +264 -0
  41. package/src/cloudformation/builders/queue.ts +147 -0
  42. package/src/cloudformation/builders/security.ts +399 -0
  43. package/src/cloudformation/builders/storage.ts +285 -0
  44. package/src/cloudformation/index.ts +30 -0
  45. package/src/cloudformation/types.ts +173 -0
  46. package/src/compliance/aws-config.ts +543 -0
  47. package/src/compliance/cloudtrail.ts +376 -0
  48. package/src/compliance/compliance.test.ts +423 -0
  49. package/src/compliance/guardduty.ts +446 -0
  50. package/src/compliance/index.ts +66 -0
  51. package/src/compliance/security-hub.ts +456 -0
  52. package/src/containers/build-optimization.ts +416 -0
  53. package/src/containers/containers.test.ts +508 -0
  54. package/src/containers/image-scanning.ts +360 -0
  55. package/src/containers/index.ts +9 -0
  56. package/src/containers/registry.ts +293 -0
  57. package/src/containers/service-mesh.ts +520 -0
  58. package/src/database/database.test.ts +762 -0
  59. package/src/database/index.ts +9 -0
  60. package/src/database/migrations.ts +444 -0
  61. package/src/database/performance.ts +528 -0
  62. package/src/database/replicas.ts +534 -0
  63. package/src/database/users.ts +494 -0
  64. package/src/dependency-graph.ts +143 -0
  65. package/src/deployment/ab-testing.ts +582 -0
  66. package/src/deployment/blue-green.ts +452 -0
  67. package/src/deployment/canary.ts +500 -0
  68. package/src/deployment/deployment.test.ts +526 -0
  69. package/src/deployment/index.ts +61 -0
  70. package/src/deployment/progressive.ts +62 -0
  71. package/src/dns/dns.test.ts +641 -0
  72. package/src/dns/dnssec.ts +315 -0
  73. package/src/dns/index.ts +8 -0
  74. package/src/dns/resolver.ts +496 -0
  75. package/src/dns/routing.ts +593 -0
  76. package/src/email/advanced/analytics.ts +445 -0
  77. package/src/email/advanced/index.ts +11 -0
  78. package/src/email/advanced/rules.ts +465 -0
  79. package/src/email/advanced/scheduling.ts +352 -0
  80. package/src/email/advanced/search.ts +412 -0
  81. package/src/email/advanced/shared-mailboxes.ts +404 -0
  82. package/src/email/advanced/templates.ts +455 -0
  83. package/src/email/advanced/threading.ts +281 -0
  84. package/src/email/analytics.ts +467 -0
  85. package/src/email/bounce-handling.ts +425 -0
  86. package/src/email/email.test.ts +431 -0
  87. package/src/email/handlers/__tests__/inbound.test.ts +38 -0
  88. package/src/email/handlers/__tests__/outbound.test.ts +37 -0
  89. package/src/email/handlers/converter.ts +227 -0
  90. package/src/email/handlers/feedback.ts +228 -0
  91. package/src/email/handlers/inbound.ts +169 -0
  92. package/src/email/handlers/outbound.ts +178 -0
  93. package/src/email/index.ts +15 -0
  94. package/src/email/reputation.ts +303 -0
  95. package/src/email/templates.ts +352 -0
  96. package/src/errors/index.test.ts +434 -0
  97. package/src/errors/index.ts +416 -0
  98. package/src/health-checks/index.ts +40 -0
  99. package/src/index.ts +360 -0
  100. package/src/intrinsic-functions.ts +118 -0
  101. package/src/lambda/concurrency.ts +330 -0
  102. package/src/lambda/destinations.ts +345 -0
  103. package/src/lambda/dlq.ts +425 -0
  104. package/src/lambda/index.ts +11 -0
  105. package/src/lambda/lambda.test.ts +840 -0
  106. package/src/lambda/layers.ts +263 -0
  107. package/src/lambda/versions.ts +376 -0
  108. package/src/lambda/vpc.ts +399 -0
  109. package/src/local/config.ts +114 -0
  110. package/src/local/index.ts +6 -0
  111. package/src/local/mock-aws.ts +351 -0
  112. package/src/modules/ai.ts +340 -0
  113. package/src/modules/api.ts +478 -0
  114. package/src/modules/auth.ts +805 -0
  115. package/src/modules/cache.ts +417 -0
  116. package/src/modules/cdn.ts +1062 -0
  117. package/src/modules/communication.ts +1094 -0
  118. package/src/modules/compute.ts +3348 -0
  119. package/src/modules/database.ts +554 -0
  120. package/src/modules/deployment.ts +1079 -0
  121. package/src/modules/dns.ts +337 -0
  122. package/src/modules/email.ts +1538 -0
  123. package/src/modules/filesystem.ts +515 -0
  124. package/src/modules/index.ts +32 -0
  125. package/src/modules/messaging.ts +486 -0
  126. package/src/modules/monitoring.ts +2086 -0
  127. package/src/modules/network.ts +664 -0
  128. package/src/modules/parameter-store.ts +325 -0
  129. package/src/modules/permissions.ts +1081 -0
  130. package/src/modules/phone.ts +494 -0
  131. package/src/modules/queue.ts +1260 -0
  132. package/src/modules/redirects.ts +464 -0
  133. package/src/modules/registry.ts +699 -0
  134. package/src/modules/search.ts +401 -0
  135. package/src/modules/secrets.ts +416 -0
  136. package/src/modules/security.ts +731 -0
  137. package/src/modules/sms.ts +389 -0
  138. package/src/modules/storage.ts +1120 -0
  139. package/src/modules/workflow.ts +680 -0
  140. package/src/multi-account/config.ts +521 -0
  141. package/src/multi-account/index.ts +7 -0
  142. package/src/multi-account/manager.ts +427 -0
  143. package/src/multi-region/cross-region.ts +410 -0
  144. package/src/multi-region/index.ts +8 -0
  145. package/src/multi-region/manager.ts +483 -0
  146. package/src/multi-region/regions.ts +435 -0
  147. package/src/network-security/index.ts +48 -0
  148. package/src/observability/index.ts +9 -0
  149. package/src/observability/logs.ts +522 -0
  150. package/src/observability/metrics.ts +460 -0
  151. package/src/observability/observability.test.ts +782 -0
  152. package/src/observability/synthetics.ts +568 -0
  153. package/src/observability/xray.ts +358 -0
  154. package/src/phone/advanced/analytics.ts +349 -0
  155. package/src/phone/advanced/callbacks.ts +428 -0
  156. package/src/phone/advanced/index.ts +8 -0
  157. package/src/phone/advanced/ivr-builder.ts +504 -0
  158. package/src/phone/advanced/recording.ts +310 -0
  159. package/src/phone/handlers/__tests__/incoming-call.test.ts +40 -0
  160. package/src/phone/handlers/incoming-call.ts +117 -0
  161. package/src/phone/handlers/missed-call.ts +116 -0
  162. package/src/phone/handlers/voicemail.ts +179 -0
  163. package/src/phone/index.ts +9 -0
  164. package/src/presets/api-backend.ts +134 -0
  165. package/src/presets/data-pipeline.ts +204 -0
  166. package/src/presets/extend.test.ts +295 -0
  167. package/src/presets/extend.ts +297 -0
  168. package/src/presets/fullstack-app.ts +144 -0
  169. package/src/presets/index.ts +27 -0
  170. package/src/presets/jamstack.ts +135 -0
  171. package/src/presets/microservices.ts +167 -0
  172. package/src/presets/ml-api.ts +208 -0
  173. package/src/presets/nodejs-server.ts +104 -0
  174. package/src/presets/nodejs-serverless.ts +114 -0
  175. package/src/presets/realtime-app.ts +184 -0
  176. package/src/presets/static-site.ts +64 -0
  177. package/src/presets/traditional-web-app.ts +339 -0
  178. package/src/presets/wordpress.ts +138 -0
  179. package/src/preview/github.test.ts +249 -0
  180. package/src/preview/github.ts +297 -0
  181. package/src/preview/index.ts +37 -0
  182. package/src/preview/manager.test.ts +440 -0
  183. package/src/preview/manager.ts +326 -0
  184. package/src/preview/notifications.test.ts +582 -0
  185. package/src/preview/notifications.ts +341 -0
  186. package/src/queue/batch-processing.ts +402 -0
  187. package/src/queue/dlq-monitoring.ts +402 -0
  188. package/src/queue/fifo.ts +342 -0
  189. package/src/queue/index.ts +9 -0
  190. package/src/queue/management.ts +428 -0
  191. package/src/queue/queue.test.ts +429 -0
  192. package/src/resource-mgmt/index.ts +39 -0
  193. package/src/resource-naming.ts +62 -0
  194. package/src/s3/index.ts +523 -0
  195. package/src/schema/cloud-config.schema.json +554 -0
  196. package/src/schema/index.ts +68 -0
  197. package/src/security/certificate-manager.ts +492 -0
  198. package/src/security/index.ts +9 -0
  199. package/src/security/scanning.ts +545 -0
  200. package/src/security/secrets-manager.ts +476 -0
  201. package/src/security/secrets-rotation.ts +456 -0
  202. package/src/security/security.test.ts +738 -0
  203. package/src/sms/advanced/ab-testing.ts +389 -0
  204. package/src/sms/advanced/analytics.ts +336 -0
  205. package/src/sms/advanced/campaigns.ts +523 -0
  206. package/src/sms/advanced/chatbot.ts +224 -0
  207. package/src/sms/advanced/index.ts +10 -0
  208. package/src/sms/advanced/link-tracking.ts +248 -0
  209. package/src/sms/advanced/mms.ts +308 -0
  210. package/src/sms/handlers/__tests__/send.test.ts +40 -0
  211. package/src/sms/handlers/delivery-status.ts +133 -0
  212. package/src/sms/handlers/receive.ts +162 -0
  213. package/src/sms/handlers/send.ts +174 -0
  214. package/src/sms/index.ts +9 -0
  215. package/src/stack-diff.ts +389 -0
  216. package/src/static-site/index.ts +85 -0
  217. package/src/template-builder.ts +110 -0
  218. package/src/template-validator.ts +574 -0
  219. package/src/utils/cache.ts +291 -0
  220. package/src/utils/diff.ts +269 -0
  221. package/src/utils/hash.ts +227 -0
  222. package/src/utils/index.ts +8 -0
  223. package/src/utils/parallel.ts +294 -0
  224. package/src/validators/credentials.test.ts +274 -0
  225. package/src/validators/credentials.ts +233 -0
  226. package/src/validators/quotas.test.ts +434 -0
  227. package/src/validators/quotas.ts +217 -0
  228. package/test/ai.test.ts +327 -0
  229. package/test/api.test.ts +511 -0
  230. package/test/auth.test.ts +632 -0
  231. package/test/cache.test.ts +406 -0
  232. package/test/cdn.test.ts +247 -0
  233. package/test/compute.test.ts +861 -0
  234. package/test/database.test.ts +523 -0
  235. package/test/deployment.test.ts +499 -0
  236. package/test/dns.test.ts +270 -0
  237. package/test/email.test.ts +439 -0
  238. package/test/filesystem.test.ts +382 -0
  239. package/test/integration.test.ts +350 -0
  240. package/test/messaging.test.ts +514 -0
  241. package/test/monitoring.test.ts +634 -0
  242. package/test/network.test.ts +425 -0
  243. package/test/permissions.test.ts +488 -0
  244. package/test/queue.test.ts +484 -0
  245. package/test/registry.test.ts +306 -0
  246. package/test/security.test.ts +462 -0
  247. package/test/storage.test.ts +463 -0
  248. package/test/template-validator.test.ts +559 -0
  249. package/test/workflow.test.ts +592 -0
  250. package/tsconfig.json +16 -0
  251. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Email Conversion Lambda Handler
3
+ *
4
+ * Converts raw MIME emails to readable formats:
5
+ * - Converts raw MIME to HTML/text
6
+ * - Extracts and saves attachments separately
7
+ * - Generates email previews
8
+ * - Creates searchable metadata JSON
9
+ */
10
+
11
+ export const handler = `
12
+ const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
13
+ const s3 = new S3Client({});
14
+
15
+ exports.handler = async (event) => {
16
+ console.log('Email conversion event:', JSON.stringify(event, null, 2));
17
+
18
+ const bucket = process.env.EMAIL_BUCKET;
19
+
20
+ for (const record of event.Records) {
21
+ try {
22
+ const s3Event = record.s3 || {};
23
+ const key = decodeURIComponent(s3Event.object?.key?.replace(/\\+/g, ' ') || '');
24
+
25
+ // Only process raw.eml files in mailboxes
26
+ if (!key.endsWith('/raw.eml') || !key.startsWith('mailboxes/')) {
27
+ continue;
28
+ }
29
+
30
+ const basePath = key.replace('/raw.eml', '');
31
+
32
+ // Get raw email
33
+ const getResult = await s3.send(new GetObjectCommand({
34
+ Bucket: bucket,
35
+ Key: key,
36
+ }));
37
+
38
+ const rawEmail = await getResult.Body.transformToString();
39
+
40
+ // Parse email
41
+ const parsed = parseEmail(rawEmail);
42
+
43
+ // Save HTML version
44
+ if (parsed.html) {
45
+ await s3.send(new PutObjectCommand({
46
+ Bucket: bucket,
47
+ Key: \`\${basePath}/body.html\`,
48
+ Body: parsed.html,
49
+ ContentType: 'text/html',
50
+ }));
51
+ }
52
+
53
+ // Save text version
54
+ if (parsed.text) {
55
+ await s3.send(new PutObjectCommand({
56
+ Bucket: bucket,
57
+ Key: \`\${basePath}/body.txt\`,
58
+ Body: parsed.text,
59
+ ContentType: 'text/plain',
60
+ }));
61
+ }
62
+
63
+ // Save attachments
64
+ if (parsed.attachments && parsed.attachments.length > 0) {
65
+ for (let i = 0; i < parsed.attachments.length; i++) {
66
+ const attachment = parsed.attachments[i];
67
+ await s3.send(new PutObjectCommand({
68
+ Bucket: bucket,
69
+ Key: \`\${basePath}/attachments/\${attachment.filename}\`,
70
+ Body: Buffer.from(attachment.content, 'base64'),
71
+ ContentType: attachment.contentType,
72
+ }));
73
+ }
74
+
75
+ // Update metadata with attachment info
76
+ try {
77
+ const metaResult = await s3.send(new GetObjectCommand({
78
+ Bucket: bucket,
79
+ Key: \`\${basePath}/metadata.json\`,
80
+ }));
81
+ const metadata = JSON.parse(await metaResult.Body.transformToString());
82
+
83
+ metadata.attachments = parsed.attachments.map(a => ({
84
+ filename: a.filename,
85
+ contentType: a.contentType,
86
+ size: a.size,
87
+ }));
88
+ metadata.converted = true;
89
+ metadata.convertedAt = new Date().toISOString();
90
+
91
+ await s3.send(new PutObjectCommand({
92
+ Bucket: bucket,
93
+ Key: \`\${basePath}/metadata.json\`,
94
+ Body: JSON.stringify(metadata, null, 2),
95
+ ContentType: 'application/json',
96
+ }));
97
+ } catch (err) {
98
+ console.log('Could not update metadata:', err.message);
99
+ }
100
+ }
101
+
102
+ // Generate preview (first 200 chars of text)
103
+ const preview = (parsed.text || parsed.html?.replace(/<[^>]+>/g, '') || '')
104
+ .substring(0, 200)
105
+ .replace(/\\s+/g, ' ')
106
+ .trim();
107
+
108
+ await s3.send(new PutObjectCommand({
109
+ Bucket: bucket,
110
+ Key: \`\${basePath}/preview.txt\`,
111
+ Body: preview,
112
+ ContentType: 'text/plain',
113
+ }));
114
+
115
+ console.log(\`Converted email: \${key}\`);
116
+
117
+ } catch (error) {
118
+ console.error('Error converting email:', error);
119
+ }
120
+ }
121
+
122
+ return { statusCode: 200, body: 'OK' };
123
+ };
124
+
125
+ // Simple MIME parser
126
+ function parseEmail(rawEmail) {
127
+ const result = {
128
+ headers: {},
129
+ text: null,
130
+ html: null,
131
+ attachments: [],
132
+ };
133
+
134
+ // Split headers and body
135
+ const parts = rawEmail.split(/\\r?\\n\\r?\\n/);
136
+ const headerSection = parts[0];
137
+ const bodySection = parts.slice(1).join('\\n\\n');
138
+
139
+ // Parse headers
140
+ let currentHeader = '';
141
+ for (const line of headerSection.split(/\\r?\\n/)) {
142
+ if (line.match(/^[A-Za-z-]+:/)) {
143
+ const colonIndex = line.indexOf(':');
144
+ currentHeader = line.substring(0, colonIndex).toLowerCase();
145
+ result.headers[currentHeader] = line.substring(colonIndex + 1).trim();
146
+ } else if (currentHeader && (line.startsWith(' ') || line.startsWith('\\t'))) {
147
+ result.headers[currentHeader] += ' ' + line.trim();
148
+ }
149
+ }
150
+
151
+ // Check content type
152
+ const contentType = result.headers['content-type'] || 'text/plain';
153
+
154
+ if (contentType.includes('multipart/')) {
155
+ // Extract boundary
156
+ const boundaryMatch = contentType.match(/boundary="?([^";]+)"?/);
157
+ if (boundaryMatch) {
158
+ const boundary = boundaryMatch[1];
159
+ const mimeParts = bodySection.split('--' + boundary);
160
+
161
+ for (const part of mimeParts) {
162
+ if (part.trim() === '' || part.trim() === '--') continue;
163
+
164
+ const partParts = part.split(/\\r?\\n\\r?\\n/);
165
+ const partHeaders = partParts[0];
166
+ const partBody = partParts.slice(1).join('\\n\\n').trim();
167
+
168
+ const partContentType = (partHeaders.match(/Content-Type:\\s*([^;\\r\\n]+)/i) || [])[1] || '';
169
+ const partEncoding = (partHeaders.match(/Content-Transfer-Encoding:\\s*([^\\r\\n]+)/i) || [])[1] || '';
170
+ const partDisposition = (partHeaders.match(/Content-Disposition:\\s*([^;\\r\\n]+)/i) || [])[1] || '';
171
+
172
+ if (partDisposition.includes('attachment') || partContentType.includes('application/')) {
173
+ // Attachment
174
+ const filenameMatch = partHeaders.match(/filename="?([^"\\r\\n]+)"?/i);
175
+ const filename = filenameMatch ? filenameMatch[1] : \`attachment_\${result.attachments.length + 1}\`;
176
+
177
+ let content = partBody;
178
+ if (partEncoding.toLowerCase() === 'base64') {
179
+ content = partBody.replace(/\\s/g, '');
180
+ }
181
+
182
+ result.attachments.push({
183
+ filename,
184
+ contentType: partContentType.trim(),
185
+ content,
186
+ size: Buffer.from(content, 'base64').length,
187
+ });
188
+ } else if (partContentType.includes('text/html')) {
189
+ result.html = decodeContent(partBody, partEncoding);
190
+ } else if (partContentType.includes('text/plain')) {
191
+ result.text = decodeContent(partBody, partEncoding);
192
+ } else if (partContentType.includes('multipart/')) {
193
+ // Nested multipart - recursively parse
194
+ const nestedResult = parseEmail(partHeaders + '\\n\\n' + partBody);
195
+ if (nestedResult.html) result.html = nestedResult.html;
196
+ if (nestedResult.text) result.text = nestedResult.text;
197
+ result.attachments.push(...nestedResult.attachments);
198
+ }
199
+ }
200
+ }
201
+ } else if (contentType.includes('text/html')) {
202
+ result.html = bodySection;
203
+ } else {
204
+ result.text = bodySection;
205
+ }
206
+
207
+ return result;
208
+ }
209
+
210
+ function decodeContent(content, encoding) {
211
+ if (!encoding) return content;
212
+
213
+ encoding = encoding.toLowerCase().trim();
214
+
215
+ if (encoding === 'base64') {
216
+ return Buffer.from(content.replace(/\\s/g, ''), 'base64').toString('utf-8');
217
+ } else if (encoding === 'quoted-printable') {
218
+ return content
219
+ .replace(/=\\r?\\n/g, '')
220
+ .replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
221
+ }
222
+
223
+ return content;
224
+ }
225
+ `
226
+
227
+ export default handler
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Email Feedback Lambda Handler
3
+ *
4
+ * Processes SES bounce and complaint notifications:
5
+ * - Processes SES bounce notifications
6
+ * - Processes complaint notifications
7
+ * - Updates suppression list
8
+ * - Sends admin notifications
9
+ */
10
+
11
+ export const handler = `
12
+ const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
13
+ const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
14
+
15
+ const s3 = new S3Client({});
16
+ const sns = new SNSClient({});
17
+
18
+ exports.handler = async (event) => {
19
+ console.log('Email feedback event:', JSON.stringify(event, null, 2));
20
+
21
+ const bucket = process.env.EMAIL_BUCKET;
22
+ const adminTopicArn = process.env.ADMIN_TOPIC_ARN;
23
+
24
+ for (const record of event.Records) {
25
+ try {
26
+ const message = JSON.parse(record.Sns?.Message || record.body || '{}');
27
+ const notificationType = message.notificationType || message.eventType;
28
+
29
+ if (!notificationType) {
30
+ console.log('Unknown notification type, skipping');
31
+ continue;
32
+ }
33
+
34
+ const timestamp = new Date().toISOString();
35
+
36
+ if (notificationType === 'Bounce') {
37
+ await handleBounce(message, bucket, adminTopicArn, timestamp);
38
+ } else if (notificationType === 'Complaint') {
39
+ await handleComplaint(message, bucket, adminTopicArn, timestamp);
40
+ } else if (notificationType === 'Delivery') {
41
+ await handleDelivery(message, bucket, timestamp);
42
+ }
43
+
44
+ } catch (error) {
45
+ console.error('Error processing feedback:', error);
46
+ }
47
+ }
48
+
49
+ return { statusCode: 200, body: 'OK' };
50
+ };
51
+
52
+ async function handleBounce(message, bucket, adminTopicArn, timestamp) {
53
+ const bounce = message.bounce || {};
54
+ const mail = message.mail || {};
55
+
56
+ console.log(\`Processing bounce: \${bounce.bounceType} - \${bounce.bounceSubType}\`);
57
+
58
+ // Get bounced recipients
59
+ const bouncedRecipients = bounce.bouncedRecipients || [];
60
+
61
+ for (const recipient of bouncedRecipients) {
62
+ const email = recipient.emailAddress;
63
+
64
+ // Add to suppression list
65
+ await addToSuppressionList(bucket, email, 'bounce', {
66
+ type: bounce.bounceType,
67
+ subType: bounce.bounceSubType,
68
+ diagnosticCode: recipient.diagnosticCode,
69
+ action: recipient.action,
70
+ status: recipient.status,
71
+ timestamp,
72
+ originalMessageId: mail.messageId,
73
+ });
74
+
75
+ console.log(\`Added \${email} to suppression list (bounce)\`);
76
+ }
77
+
78
+ // Log bounce event
79
+ await logFeedbackEvent(bucket, 'bounces', {
80
+ type: 'bounce',
81
+ bounceType: bounce.bounceType,
82
+ bounceSubType: bounce.bounceSubType,
83
+ recipients: bouncedRecipients.map(r => r.emailAddress),
84
+ messageId: mail.messageId,
85
+ timestamp,
86
+ });
87
+
88
+ // Notify admin for hard bounces
89
+ if (bounce.bounceType === 'Permanent' && adminTopicArn) {
90
+ await sns.send(new PublishCommand({
91
+ TopicArn: adminTopicArn,
92
+ Subject: \`Email Bounce Alert: \${bounce.bounceSubType}\`,
93
+ Message: JSON.stringify({
94
+ type: 'bounce',
95
+ bounceType: bounce.bounceType,
96
+ bounceSubType: bounce.bounceSubType,
97
+ recipients: bouncedRecipients.map(r => ({
98
+ email: r.emailAddress,
99
+ diagnosticCode: r.diagnosticCode,
100
+ })),
101
+ originalSubject: mail.commonHeaders?.subject,
102
+ timestamp,
103
+ }, null, 2),
104
+ }));
105
+ }
106
+ }
107
+
108
+ async function handleComplaint(message, bucket, adminTopicArn, timestamp) {
109
+ const complaint = message.complaint || {};
110
+ const mail = message.mail || {};
111
+
112
+ console.log(\`Processing complaint: \${complaint.complaintFeedbackType}\`);
113
+
114
+ // Get complained recipients
115
+ const complainedRecipients = complaint.complainedRecipients || [];
116
+
117
+ for (const recipient of complainedRecipients) {
118
+ const email = recipient.emailAddress;
119
+
120
+ // Add to suppression list
121
+ await addToSuppressionList(bucket, email, 'complaint', {
122
+ feedbackType: complaint.complaintFeedbackType,
123
+ userAgent: complaint.userAgent,
124
+ timestamp,
125
+ originalMessageId: mail.messageId,
126
+ });
127
+
128
+ console.log(\`Added \${email} to suppression list (complaint)\`);
129
+ }
130
+
131
+ // Log complaint event
132
+ await logFeedbackEvent(bucket, 'complaints', {
133
+ type: 'complaint',
134
+ feedbackType: complaint.complaintFeedbackType,
135
+ recipients: complainedRecipients.map(r => r.emailAddress),
136
+ messageId: mail.messageId,
137
+ timestamp,
138
+ });
139
+
140
+ // Always notify admin for complaints
141
+ if (adminTopicArn) {
142
+ await sns.send(new PublishCommand({
143
+ TopicArn: adminTopicArn,
144
+ Subject: \`Email Complaint Alert: \${complaint.complaintFeedbackType || 'Unknown'}\`,
145
+ Message: JSON.stringify({
146
+ type: 'complaint',
147
+ feedbackType: complaint.complaintFeedbackType,
148
+ recipients: complainedRecipients.map(r => r.emailAddress),
149
+ originalSubject: mail.commonHeaders?.subject,
150
+ timestamp,
151
+ }, null, 2),
152
+ }));
153
+ }
154
+ }
155
+
156
+ async function handleDelivery(message, bucket, timestamp) {
157
+ const delivery = message.delivery || {};
158
+ const mail = message.mail || {};
159
+
160
+ console.log(\`Processing delivery confirmation for \${delivery.recipients?.join(', ')}\`);
161
+
162
+ // Log delivery event
163
+ await logFeedbackEvent(bucket, 'deliveries', {
164
+ type: 'delivery',
165
+ recipients: delivery.recipients,
166
+ messageId: mail.messageId,
167
+ processingTimeMillis: delivery.processingTimeMillis,
168
+ smtpResponse: delivery.smtpResponse,
169
+ timestamp,
170
+ });
171
+ }
172
+
173
+ async function addToSuppressionList(bucket, email, reason, details) {
174
+ const key = 'suppression/list.json';
175
+ let list = [];
176
+
177
+ try {
178
+ const result = await s3.send(new GetObjectCommand({
179
+ Bucket: bucket,
180
+ Key: key,
181
+ }));
182
+ list = JSON.parse(await result.Body.transformToString());
183
+ } catch {
184
+ // List doesn't exist yet
185
+ }
186
+
187
+ // Check if already in list
188
+ const existing = list.find(item => item.email === email);
189
+ if (existing) {
190
+ existing.lastUpdated = details.timestamp;
191
+ existing.count = (existing.count || 1) + 1;
192
+ } else {
193
+ list.push({
194
+ email,
195
+ reason,
196
+ addedAt: details.timestamp,
197
+ lastUpdated: details.timestamp,
198
+ count: 1,
199
+ details,
200
+ });
201
+ }
202
+
203
+ await s3.send(new PutObjectCommand({
204
+ Bucket: bucket,
205
+ Key: key,
206
+ Body: JSON.stringify(list, null, 2),
207
+ ContentType: 'application/json',
208
+ }));
209
+ }
210
+
211
+ async function logFeedbackEvent(bucket, type, event) {
212
+ const date = new Date();
213
+ const year = date.getFullYear();
214
+ const month = String(date.getMonth() + 1).padStart(2, '0');
215
+ const day = String(date.getDate()).padStart(2, '0');
216
+
217
+ const key = \`feedback/\${type}/\${year}/\${month}/\${day}/\${Date.now()}-\${Math.random().toString(36).substr(2)}.json\`;
218
+
219
+ await s3.send(new PutObjectCommand({
220
+ Bucket: bucket,
221
+ Key: key,
222
+ Body: JSON.stringify(event, null, 2),
223
+ ContentType: 'application/json',
224
+ }));
225
+ }
226
+ `
227
+
228
+ export default handler
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Inbound Email Lambda Handler
3
+ *
4
+ * Processes incoming emails from SES:
5
+ * - Parses raw MIME emails
6
+ * - Extracts metadata (from, to, subject, date, attachments)
7
+ * - Organizes by domain/account/sender structure
8
+ * - Supports + addressing (user+tag@domain.com)
9
+ * - Stores in S3 with proper structure
10
+ * - Triggers SNS notifications
11
+ */
12
+
13
+ export const handler = `
14
+ const { S3Client, GetObjectCommand, PutObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');
15
+ const s3 = new S3Client({});
16
+
17
+ exports.handler = async (event) => {
18
+ console.log('Inbound email event:', JSON.stringify(event, null, 2));
19
+
20
+ for (const record of event.Records) {
21
+ try {
22
+ // Handle SES notification via SNS
23
+ const sesNotification = JSON.parse(record.Sns?.Message || record.body || '{}');
24
+ const mail = sesNotification.mail || {};
25
+ const receipt = sesNotification.receipt || {};
26
+
27
+ const bucket = process.env.EMAIL_BUCKET;
28
+ const messageId = mail.messageId;
29
+
30
+ if (!messageId) {
31
+ console.log('No messageId found, skipping');
32
+ continue;
33
+ }
34
+
35
+ // Get the raw email from S3
36
+ const sourceKey = \`incoming/\${messageId}\`;
37
+ let rawEmail;
38
+
39
+ try {
40
+ const getResult = await s3.send(new GetObjectCommand({
41
+ Bucket: bucket,
42
+ Key: sourceKey,
43
+ }));
44
+ rawEmail = await getResult.Body.transformToString();
45
+ } catch (err) {
46
+ console.log('Could not retrieve raw email:', err.message);
47
+ continue;
48
+ }
49
+
50
+ // Parse email headers
51
+ const headers = {};
52
+ const headerSection = rawEmail.split('\\n\\n')[0];
53
+ let currentHeader = '';
54
+
55
+ for (const line of headerSection.split('\\n')) {
56
+ if (line.match(/^[A-Za-z-]+:/)) {
57
+ const colonIndex = line.indexOf(':');
58
+ currentHeader = line.substring(0, colonIndex).toLowerCase();
59
+ headers[currentHeader] = line.substring(colonIndex + 1).trim();
60
+ } else if (currentHeader && (line.startsWith(' ') || line.startsWith('\\t'))) {
61
+ headers[currentHeader] += ' ' + line.trim();
62
+ }
63
+ }
64
+
65
+ // Extract key metadata
66
+ const from = headers['from'] || '';
67
+ const to = headers['to'] || '';
68
+ const subject = headers['subject'] || '(no subject)';
69
+ const date = headers['date'] || new Date().toISOString();
70
+
71
+ // Parse sender email
72
+ const fromMatch = from.match(/<([^>]+)>/) || [null, from];
73
+ const fromEmail = fromMatch[1] || from;
74
+ const fromDomain = fromEmail.split('@')[1] || 'unknown';
75
+
76
+ // Parse recipient email (handle + addressing)
77
+ const toMatch = to.match(/<([^>]+)>/) || [null, to];
78
+ const toEmail = toMatch[1] || to;
79
+ const [localPart, toDomain] = toEmail.split('@');
80
+ const baseLocalPart = localPart.split('+')[0]; // Handle user+tag@domain.com
81
+ const tag = localPart.includes('+') ? localPart.split('+')[1] : null;
82
+
83
+ // Create timestamp-based path
84
+ const timestamp = new Date(date);
85
+ const year = timestamp.getFullYear();
86
+ const month = String(timestamp.getMonth() + 1).padStart(2, '0');
87
+ const day = String(timestamp.getDate()).padStart(2, '0');
88
+
89
+ // Organize by: domain/mailbox/year/month/day/sender/messageId
90
+ const destPath = \`mailboxes/\${toDomain}/\${baseLocalPart}/\${year}/\${month}/\${day}/\${fromDomain}/\${messageId}\`;
91
+
92
+ // Copy raw email to organized location
93
+ await s3.send(CopyObjectCommand({
94
+ Bucket: bucket,
95
+ CopySource: \`\${bucket}/\${sourceKey}\`,
96
+ Key: \`\${destPath}/raw.eml\`,
97
+ }));
98
+
99
+ // Create metadata JSON
100
+ const metadata = {
101
+ messageId,
102
+ from: fromEmail,
103
+ fromName: from.replace(/<[^>]+>/, '').trim(),
104
+ to: toEmail,
105
+ toName: to.replace(/<[^>]+>/, '').trim(),
106
+ subject,
107
+ date: timestamp.toISOString(),
108
+ receivedAt: new Date().toISOString(),
109
+ tag,
110
+ spamVerdict: receipt.spamVerdict?.status || 'UNKNOWN',
111
+ virusVerdict: receipt.virusVerdict?.status || 'UNKNOWN',
112
+ spfVerdict: receipt.spfVerdict?.status || 'UNKNOWN',
113
+ dkimVerdict: receipt.dkimVerdict?.status || 'UNKNOWN',
114
+ dmarcVerdict: receipt.dmarcVerdict?.status || 'UNKNOWN',
115
+ hasAttachments: rawEmail.includes('Content-Disposition: attachment'),
116
+ };
117
+
118
+ await s3.send(new PutObjectCommand({
119
+ Bucket: bucket,
120
+ Key: \`\${destPath}/metadata.json\`,
121
+ Body: JSON.stringify(metadata, null, 2),
122
+ ContentType: 'application/json',
123
+ }));
124
+
125
+ // Update inbox index
126
+ const indexKey = \`mailboxes/\${toDomain}/\${baseLocalPart}/inbox.json\`;
127
+ let inbox = [];
128
+
129
+ try {
130
+ const indexResult = await s3.send(new GetObjectCommand({
131
+ Bucket: bucket,
132
+ Key: indexKey,
133
+ }));
134
+ inbox = JSON.parse(await indexResult.Body.transformToString());
135
+ } catch {
136
+ // Index doesn't exist yet
137
+ }
138
+
139
+ inbox.unshift({
140
+ messageId,
141
+ from: fromEmail,
142
+ subject,
143
+ date: timestamp.toISOString(),
144
+ read: false,
145
+ path: destPath,
146
+ });
147
+
148
+ // Keep only last 1000 emails in index
149
+ inbox = inbox.slice(0, 1000);
150
+
151
+ await s3.send(new PutObjectCommand({
152
+ Bucket: bucket,
153
+ Key: indexKey,
154
+ Body: JSON.stringify(inbox, null, 2),
155
+ ContentType: 'application/json',
156
+ }));
157
+
158
+ console.log(\`Processed email: \${messageId} from \${fromEmail} to \${toEmail}\`);
159
+
160
+ } catch (error) {
161
+ console.error('Error processing email:', error);
162
+ }
163
+ }
164
+
165
+ return { statusCode: 200, body: 'OK' };
166
+ };
167
+ `
168
+
169
+ export default handler