@stacksjs/ts-cloud-core 0.1.6 → 0.1.7

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 (225) hide show
  1. package/dist/advanced-features.test.d.ts +0 -0
  2. package/dist/aws/cloudformation.d.ts +69 -0
  3. package/dist/aws/cloudfront.d.ts +21 -0
  4. package/dist/aws/credentials.d.ts +66 -0
  5. package/dist/aws/credentials.test.d.ts +0 -0
  6. package/dist/aws/index.d.ts +73 -0
  7. package/dist/aws/s3.d.ts +130 -0
  8. package/dist/aws/s3.test.d.ts +0 -0
  9. package/dist/aws/signature.d.ts +101 -0
  10. package/dist/aws/signature.test.d.ts +0 -0
  11. package/dist/backup/disaster-recovery.d.ts +98 -0
  12. package/dist/backup/disaster-recovery.test.d.ts +0 -0
  13. package/dist/backup/index.d.ts +24 -0
  14. package/dist/backup/manager.d.ts +112 -0
  15. package/dist/backup/manager.test.d.ts +0 -0
  16. package/dist/cicd/circleci.d.ts +47 -0
  17. package/dist/cicd/github-actions.d.ts +55 -0
  18. package/dist/cicd/gitlab-ci.d.ts +46 -0
  19. package/dist/cicd/index.d.ts +3 -0
  20. package/dist/cli/history.d.ts +66 -0
  21. package/dist/cli/index.d.ts +5 -0
  22. package/dist/cli/progress.d.ts +97 -0
  23. package/dist/cli/repl.d.ts +76 -0
  24. package/dist/cli/suggestions.d.ts +67 -0
  25. package/dist/cli/table.d.ts +70 -0
  26. package/dist/cli/table.test.d.ts +0 -0
  27. package/dist/cloudformation/builder.d.ts +59 -0
  28. package/dist/cloudformation/builder.test.d.ts +0 -0
  29. package/dist/cloudformation/builders/api-gateway.d.ts +30 -0
  30. package/dist/cloudformation/builders/cache.d.ts +35 -0
  31. package/dist/cloudformation/builders/cdn.d.ts +34 -0
  32. package/dist/cloudformation/builders/compute.d.ts +66 -0
  33. package/dist/cloudformation/builders/database.d.ts +61 -0
  34. package/dist/cloudformation/builders/functions.d.ts +32 -0
  35. package/dist/cloudformation/builders/messaging.d.ts +17 -0
  36. package/dist/cloudformation/builders/monitoring.d.ts +36 -0
  37. package/dist/cloudformation/builders/network.d.ts +14 -0
  38. package/dist/cloudformation/builders/queue.d.ts +8 -0
  39. package/dist/cloudformation/builders/security.d.ts +31 -0
  40. package/dist/cloudformation/builders/storage.d.ts +8 -0
  41. package/dist/cloudformation/index.d.ts +24 -0
  42. package/dist/cloudformation/types.d.ts +132 -0
  43. package/dist/compliance/aws-config.d.ts +88 -0
  44. package/dist/compliance/cloudtrail.d.ts +96 -0
  45. package/dist/compliance/compliance.test.d.ts +0 -0
  46. package/dist/compliance/guardduty.d.ts +110 -0
  47. package/dist/compliance/index.d.ts +50 -0
  48. package/dist/compliance/security-hub.d.ts +110 -0
  49. package/dist/containers/build-optimization.d.ts +110 -0
  50. package/dist/containers/containers.test.d.ts +0 -0
  51. package/dist/containers/image-scanning.d.ts +96 -0
  52. package/dist/containers/index.d.ts +4 -0
  53. package/dist/containers/registry.d.ts +99 -0
  54. package/dist/containers/service-mesh.d.ts +206 -0
  55. package/dist/database/database.test.d.ts +0 -0
  56. package/dist/database/index.d.ts +4 -0
  57. package/dist/database/migrations.d.ts +102 -0
  58. package/dist/database/performance.d.ts +168 -0
  59. package/dist/database/replicas.d.ts +146 -0
  60. package/dist/database/users.d.ts +102 -0
  61. package/dist/dependency-graph.d.ts +19 -0
  62. package/dist/deployment/ab-testing.d.ts +114 -0
  63. package/dist/deployment/blue-green.d.ts +98 -0
  64. package/dist/deployment/canary.d.ts +103 -0
  65. package/dist/deployment/deployment.test.d.ts +0 -0
  66. package/dist/deployment/index.d.ts +45 -0
  67. package/dist/deployment/progressive.d.ts +34 -0
  68. package/dist/dns/dns.test.d.ts +0 -0
  69. package/dist/dns/dnssec.d.ts +75 -0
  70. package/dist/dns/index.d.ts +3 -0
  71. package/dist/dns/resolver.d.ts +150 -0
  72. package/dist/dns/routing.d.ts +217 -0
  73. package/dist/email/advanced/analytics.d.ts +78 -0
  74. package/dist/email/advanced/index.d.ts +7 -0
  75. package/dist/email/advanced/rules.d.ts +60 -0
  76. package/dist/email/advanced/scheduling.d.ts +63 -0
  77. package/dist/email/advanced/search.d.ts +76 -0
  78. package/dist/email/advanced/shared-mailboxes.d.ts +66 -0
  79. package/dist/email/advanced/templates.d.ts +39 -0
  80. package/dist/email/advanced/threading.d.ts +53 -0
  81. package/dist/email/analytics.d.ts +144 -0
  82. package/dist/email/bounce-handling.d.ts +120 -0
  83. package/dist/email/email.test.d.ts +0 -0
  84. package/dist/email/handlers/__tests__/inbound.test.d.ts +0 -0
  85. package/dist/email/handlers/__tests__/outbound.test.d.ts +0 -0
  86. package/dist/email/handlers/converter.d.ts +225 -0
  87. package/dist/email/handlers/feedback.d.ts +226 -0
  88. package/dist/email/handlers/inbound.d.ts +167 -0
  89. package/dist/email/handlers/outbound.d.ts +176 -0
  90. package/dist/email/index.d.ts +6 -0
  91. package/dist/email/reputation.d.ts +97 -0
  92. package/dist/email/templates.d.ts +82 -0
  93. package/dist/errors/index.d.ts +186 -0
  94. package/dist/errors/index.test.d.ts +0 -0
  95. package/dist/health-checks/index.d.ts +35 -0
  96. package/dist/index.d.ts +256 -0
  97. package/dist/index.js +63499 -0
  98. package/dist/intrinsic-functions.d.ts +37 -0
  99. package/dist/lambda/concurrency.d.ts +98 -0
  100. package/dist/lambda/destinations.d.ts +99 -0
  101. package/dist/lambda/dlq.d.ts +109 -0
  102. package/dist/lambda/index.d.ts +6 -0
  103. package/dist/lambda/lambda.test.d.ts +0 -0
  104. package/dist/lambda/layers.d.ts +81 -0
  105. package/dist/lambda/versions.d.ts +91 -0
  106. package/dist/lambda/vpc.d.ts +116 -0
  107. package/dist/local/config.d.ts +44 -0
  108. package/dist/local/index.d.ts +2 -0
  109. package/dist/local/mock-aws.d.ts +60 -0
  110. package/dist/modules/ai.d.ts +47 -0
  111. package/dist/modules/api.d.ts +98 -0
  112. package/dist/modules/auth.d.ts +165 -0
  113. package/dist/modules/cache.d.ts +73 -0
  114. package/dist/modules/cdn.d.ts +125 -0
  115. package/dist/modules/communication.d.ts +98 -0
  116. package/dist/modules/compute.d.ts +309 -0
  117. package/dist/modules/database.d.ts +105 -0
  118. package/dist/modules/deployment.d.ts +181 -0
  119. package/dist/modules/dns.d.ts +45 -0
  120. package/dist/modules/email.d.ts +217 -0
  121. package/dist/modules/filesystem.d.ts +94 -0
  122. package/dist/modules/index.d.ts +27 -0
  123. package/dist/modules/messaging.d.ts +108 -0
  124. package/dist/modules/monitoring.d.ts +127 -0
  125. package/dist/modules/network.d.ts +102 -0
  126. package/dist/modules/parameter-store.d.ts +33 -0
  127. package/dist/modules/permissions.d.ts +132 -0
  128. package/dist/modules/phone.d.ts +80 -0
  129. package/dist/modules/queue.d.ts +210 -0
  130. package/dist/modules/redirects.d.ts +59 -0
  131. package/dist/modules/registry.d.ts +73 -0
  132. package/dist/modules/search.d.ts +56 -0
  133. package/dist/modules/secrets.d.ts +80 -0
  134. package/dist/modules/security.d.ts +100 -0
  135. package/dist/modules/sms.d.ts +52 -0
  136. package/dist/modules/storage.d.ts +160 -0
  137. package/dist/modules/workflow.d.ts +205 -0
  138. package/dist/multi-account/config.d.ts +315 -0
  139. package/dist/multi-account/index.d.ts +2 -0
  140. package/dist/multi-account/manager.d.ts +100 -0
  141. package/dist/multi-region/cross-region.d.ts +114 -0
  142. package/dist/multi-region/index.d.ts +3 -0
  143. package/dist/multi-region/manager.d.ts +72 -0
  144. package/dist/multi-region/regions.d.ts +98 -0
  145. package/dist/network-security/index.d.ts +39 -0
  146. package/dist/observability/index.d.ts +4 -0
  147. package/dist/observability/logs.d.ts +129 -0
  148. package/dist/observability/metrics.d.ts +153 -0
  149. package/dist/observability/observability.test.d.ts +0 -0
  150. package/dist/observability/synthetics.d.ts +146 -0
  151. package/dist/observability/xray.d.ts +129 -0
  152. package/dist/phone/advanced/analytics.d.ts +66 -0
  153. package/dist/phone/advanced/callbacks.d.ts +50 -0
  154. package/dist/phone/advanced/index.d.ts +4 -0
  155. package/dist/phone/advanced/ivr-builder.d.ts +83 -0
  156. package/dist/phone/advanced/recording.d.ts +48 -0
  157. package/dist/phone/handlers/__tests__/incoming-call.test.d.ts +0 -0
  158. package/dist/phone/handlers/incoming-call.d.ts +115 -0
  159. package/dist/phone/handlers/missed-call.d.ts +114 -0
  160. package/dist/phone/handlers/voicemail.d.ts +177 -0
  161. package/dist/phone/index.d.ts +2 -0
  162. package/dist/presets/api-backend.d.ts +11 -0
  163. package/dist/presets/data-pipeline.d.ts +11 -0
  164. package/dist/presets/extend.d.ts +194 -0
  165. package/dist/presets/extend.test.d.ts +0 -0
  166. package/dist/presets/fullstack-app.d.ts +12 -0
  167. package/dist/presets/index.d.ts +24 -0
  168. package/dist/presets/jamstack.d.ts +12 -0
  169. package/dist/presets/microservices.d.ts +18 -0
  170. package/dist/presets/ml-api.d.ts +13 -0
  171. package/dist/presets/nodejs-server.d.ts +14 -0
  172. package/dist/presets/nodejs-serverless.d.ts +14 -0
  173. package/dist/presets/realtime-app.d.ts +11 -0
  174. package/dist/presets/static-site.d.ts +12 -0
  175. package/dist/presets/traditional-web-app.d.ts +16 -0
  176. package/dist/presets/wordpress.d.ts +12 -0
  177. package/dist/preview/github.d.ts +32 -0
  178. package/dist/preview/github.test.d.ts +0 -0
  179. package/dist/preview/index.d.ts +27 -0
  180. package/dist/preview/manager.d.ts +58 -0
  181. package/dist/preview/manager.test.d.ts +0 -0
  182. package/dist/preview/notifications.d.ts +55 -0
  183. package/dist/preview/notifications.test.d.ts +0 -0
  184. package/dist/queue/batch-processing.d.ts +87 -0
  185. package/dist/queue/dlq-monitoring.d.ts +95 -0
  186. package/dist/queue/fifo.d.ts +90 -0
  187. package/dist/queue/index.d.ts +4 -0
  188. package/dist/queue/management.d.ts +105 -0
  189. package/dist/queue/queue.test.d.ts +0 -0
  190. package/dist/resource-mgmt/index.d.ts +29 -0
  191. package/dist/resource-naming.d.ts +26 -0
  192. package/dist/s3/index.d.ts +173 -0
  193. package/dist/schema/index.d.ts +9 -0
  194. package/dist/security/certificate-manager.d.ts +121 -0
  195. package/dist/security/index.d.ts +4 -0
  196. package/dist/security/scanning.d.ts +147 -0
  197. package/dist/security/secrets-manager.d.ts +144 -0
  198. package/dist/security/secrets-rotation.d.ts +115 -0
  199. package/dist/security/security.test.d.ts +0 -0
  200. package/dist/sms/advanced/ab-testing.d.ts +54 -0
  201. package/dist/sms/advanced/analytics.d.ts +56 -0
  202. package/dist/sms/advanced/campaigns.d.ts +82 -0
  203. package/dist/sms/advanced/chatbot.d.ts +48 -0
  204. package/dist/sms/advanced/index.d.ts +6 -0
  205. package/dist/sms/advanced/link-tracking.d.ts +42 -0
  206. package/dist/sms/advanced/mms.d.ts +35 -0
  207. package/dist/sms/handlers/__tests__/send.test.d.ts +0 -0
  208. package/dist/sms/handlers/delivery-status.d.ts +131 -0
  209. package/dist/sms/handlers/receive.d.ts +160 -0
  210. package/dist/sms/handlers/send.d.ts +172 -0
  211. package/dist/sms/index.d.ts +2 -0
  212. package/dist/stack-diff.d.ts +34 -0
  213. package/dist/static-site/index.d.ts +49 -0
  214. package/dist/template-builder.d.ts +14 -0
  215. package/dist/template-validator.d.ts +24 -0
  216. package/dist/utils/cache.d.ts +55 -0
  217. package/dist/utils/diff.d.ts +48 -0
  218. package/dist/utils/hash.d.ts +58 -0
  219. package/dist/utils/index.d.ts +4 -0
  220. package/dist/utils/parallel.d.ts +60 -0
  221. package/dist/validators/credentials.d.ts +23 -0
  222. package/dist/validators/credentials.test.d.ts +0 -0
  223. package/dist/validators/quotas.d.ts +60 -0
  224. package/dist/validators/quotas.test.d.ts +0 -0
  225. package/package.json +4 -4
@@ -0,0 +1,225 @@
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
+ export declare const handler: `
11
+ const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
12
+ const s3 = new S3Client({});
13
+
14
+ exports.handler = async (event) => {
15
+ console.log('Email conversion event:', JSON.stringify(event, null, 2));
16
+
17
+ const bucket = process.env.EMAIL_BUCKET;
18
+
19
+ for (const record of event.Records) {
20
+ try {
21
+ const s3Event = record.s3 || {};
22
+ const key = decodeURIComponent(s3Event.object?.key?.replace(/\\+/g, ' ') || '');
23
+
24
+ // Only process raw.eml files in mailboxes
25
+ if (!key.endsWith('/raw.eml') || !key.startsWith('mailboxes/')) {
26
+ continue;
27
+ }
28
+
29
+ const basePath = key.replace('/raw.eml', '');
30
+
31
+ // Get raw email
32
+ const getResult = await s3.send(new GetObjectCommand({
33
+ Bucket: bucket,
34
+ Key: key,
35
+ }));
36
+
37
+ const rawEmail = await getResult.Body.transformToString();
38
+
39
+ // Parse email
40
+ const parsed = parseEmail(rawEmail);
41
+
42
+ // Save HTML version
43
+ if (parsed.html) {
44
+ await s3.send(new PutObjectCommand({
45
+ Bucket: bucket,
46
+ Key: \`\${basePath}/body.html\`,
47
+ Body: parsed.html,
48
+ ContentType: 'text/html',
49
+ }));
50
+ }
51
+
52
+ // Save text version
53
+ if (parsed.text) {
54
+ await s3.send(new PutObjectCommand({
55
+ Bucket: bucket,
56
+ Key: \`\${basePath}/body.txt\`,
57
+ Body: parsed.text,
58
+ ContentType: 'text/plain',
59
+ }));
60
+ }
61
+
62
+ // Save attachments
63
+ if (parsed.attachments && parsed.attachments.length > 0) {
64
+ for (let i = 0; i < parsed.attachments.length; i++) {
65
+ const attachment = parsed.attachments[i];
66
+ await s3.send(new PutObjectCommand({
67
+ Bucket: bucket,
68
+ Key: \`\${basePath}/attachments/\${attachment.filename}\`,
69
+ Body: Buffer.from(attachment.content, 'base64'),
70
+ ContentType: attachment.contentType,
71
+ }));
72
+ }
73
+
74
+ // Update metadata with attachment info
75
+ try {
76
+ const metaResult = await s3.send(new GetObjectCommand({
77
+ Bucket: bucket,
78
+ Key: \`\${basePath}/metadata.json\`,
79
+ }));
80
+ const metadata = JSON.parse(await metaResult.Body.transformToString());
81
+
82
+ metadata.attachments = parsed.attachments.map(a => ({
83
+ filename: a.filename,
84
+ contentType: a.contentType,
85
+ size: a.size,
86
+ }));
87
+ metadata.converted = true;
88
+ metadata.convertedAt = new Date().toISOString();
89
+
90
+ await s3.send(new PutObjectCommand({
91
+ Bucket: bucket,
92
+ Key: \`\${basePath}/metadata.json\`,
93
+ Body: JSON.stringify(metadata, null, 2),
94
+ ContentType: 'application/json',
95
+ }));
96
+ } catch (err) {
97
+ console.log('Could not update metadata:', err.message);
98
+ }
99
+ }
100
+
101
+ // Generate preview (first 200 chars of text)
102
+ const preview = (parsed.text || parsed.html?.replace(/<[^>]+>/g, '') || '')
103
+ .substring(0, 200)
104
+ .replace(/\\s+/g, ' ')
105
+ .trim();
106
+
107
+ await s3.send(new PutObjectCommand({
108
+ Bucket: bucket,
109
+ Key: \`\${basePath}/preview.txt\`,
110
+ Body: preview,
111
+ ContentType: 'text/plain',
112
+ }));
113
+
114
+ console.log(\`Converted email: \${key}\`);
115
+
116
+ } catch (error) {
117
+ console.error('Error converting email:', error);
118
+ }
119
+ }
120
+
121
+ return { statusCode: 200, body: 'OK' };
122
+ };
123
+
124
+ // Simple MIME parser
125
+ function parseEmail(rawEmail) {
126
+ const result = {
127
+ headers: {},
128
+ text: null,
129
+ html: null,
130
+ attachments: [],
131
+ };
132
+
133
+ // Split headers and body
134
+ const parts = rawEmail.split(/\\r?\\n\\r?\\n/);
135
+ const headerSection = parts[0];
136
+ const bodySection = parts.slice(1).join('\\n\\n');
137
+
138
+ // Parse headers
139
+ let currentHeader = '';
140
+ for (const line of headerSection.split(/\\r?\\n/)) {
141
+ if (line.match(/^[A-Za-z-]+:/)) {
142
+ const colonIndex = line.indexOf(':');
143
+ currentHeader = line.substring(0, colonIndex).toLowerCase();
144
+ result.headers[currentHeader] = line.substring(colonIndex + 1).trim();
145
+ } else if (currentHeader && (line.startsWith(' ') || line.startsWith('\\t'))) {
146
+ result.headers[currentHeader] += ' ' + line.trim();
147
+ }
148
+ }
149
+
150
+ // Check content type
151
+ const contentType = result.headers['content-type'] || 'text/plain';
152
+
153
+ if (contentType.includes('multipart/')) {
154
+ // Extract boundary
155
+ const boundaryMatch = contentType.match(/boundary="?([^";]+)"?/);
156
+ if (boundaryMatch) {
157
+ const boundary = boundaryMatch[1];
158
+ const mimeParts = bodySection.split('--' + boundary);
159
+
160
+ for (const part of mimeParts) {
161
+ if (part.trim() === '' || part.trim() === '--') continue;
162
+
163
+ const partParts = part.split(/\\r?\\n\\r?\\n/);
164
+ const partHeaders = partParts[0];
165
+ const partBody = partParts.slice(1).join('\\n\\n').trim();
166
+
167
+ const partContentType = (partHeaders.match(/Content-Type:\\s*([^;\\r\\n]+)/i) || [])[1] || '';
168
+ const partEncoding = (partHeaders.match(/Content-Transfer-Encoding:\\s*([^\\r\\n]+)/i) || [])[1] || '';
169
+ const partDisposition = (partHeaders.match(/Content-Disposition:\\s*([^;\\r\\n]+)/i) || [])[1] || '';
170
+
171
+ if (partDisposition.includes('attachment') || partContentType.includes('application/')) {
172
+ // Attachment
173
+ const filenameMatch = partHeaders.match(/filename="?([^"\\r\\n]+)"?/i);
174
+ const filename = filenameMatch ? filenameMatch[1] : \`attachment_\${result.attachments.length + 1}\`;
175
+
176
+ let content = partBody;
177
+ if (partEncoding.toLowerCase() === 'base64') {
178
+ content = partBody.replace(/\\s/g, '');
179
+ }
180
+
181
+ result.attachments.push({
182
+ filename,
183
+ contentType: partContentType.trim(),
184
+ content,
185
+ size: Buffer.from(content, 'base64').length,
186
+ });
187
+ } else if (partContentType.includes('text/html')) {
188
+ result.html = decodeContent(partBody, partEncoding);
189
+ } else if (partContentType.includes('text/plain')) {
190
+ result.text = decodeContent(partBody, partEncoding);
191
+ } else if (partContentType.includes('multipart/')) {
192
+ // Nested multipart - recursively parse
193
+ const nestedResult = parseEmail(partHeaders + '\\n\\n' + partBody);
194
+ if (nestedResult.html) result.html = nestedResult.html;
195
+ if (nestedResult.text) result.text = nestedResult.text;
196
+ result.attachments.push(...nestedResult.attachments);
197
+ }
198
+ }
199
+ }
200
+ } else if (contentType.includes('text/html')) {
201
+ result.html = bodySection;
202
+ } else {
203
+ result.text = bodySection;
204
+ }
205
+
206
+ return result;
207
+ }
208
+
209
+ function decodeContent(content, encoding) {
210
+ if (!encoding) return content;
211
+
212
+ encoding = encoding.toLowerCase().trim();
213
+
214
+ if (encoding === 'base64') {
215
+ return Buffer.from(content.replace(/\\s/g, ''), 'base64').toString('utf-8');
216
+ } else if (encoding === 'quoted-printable') {
217
+ return content
218
+ .replace(/=\\r?\\n/g, '')
219
+ .replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
220
+ }
221
+
222
+ return content;
223
+ }
224
+ `;
225
+ export default handler;
@@ -0,0 +1,226 @@
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
+ export declare const handler: `
11
+ const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
12
+ const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
13
+
14
+ const s3 = new S3Client({});
15
+ const sns = new SNSClient({});
16
+
17
+ exports.handler = async (event) => {
18
+ console.log('Email feedback event:', JSON.stringify(event, null, 2));
19
+
20
+ const bucket = process.env.EMAIL_BUCKET;
21
+ const adminTopicArn = process.env.ADMIN_TOPIC_ARN;
22
+
23
+ for (const record of event.Records) {
24
+ try {
25
+ const message = JSON.parse(record.Sns?.Message || record.body || '{}');
26
+ const notificationType = message.notificationType || message.eventType;
27
+
28
+ if (!notificationType) {
29
+ console.log('Unknown notification type, skipping');
30
+ continue;
31
+ }
32
+
33
+ const timestamp = new Date().toISOString();
34
+
35
+ if (notificationType === 'Bounce') {
36
+ await handleBounce(message, bucket, adminTopicArn, timestamp);
37
+ } else if (notificationType === 'Complaint') {
38
+ await handleComplaint(message, bucket, adminTopicArn, timestamp);
39
+ } else if (notificationType === 'Delivery') {
40
+ await handleDelivery(message, bucket, timestamp);
41
+ }
42
+
43
+ } catch (error) {
44
+ console.error('Error processing feedback:', error);
45
+ }
46
+ }
47
+
48
+ return { statusCode: 200, body: 'OK' };
49
+ };
50
+
51
+ async function handleBounce(message, bucket, adminTopicArn, timestamp) {
52
+ const bounce = message.bounce || {};
53
+ const mail = message.mail || {};
54
+
55
+ console.log(\`Processing bounce: \${bounce.bounceType} - \${bounce.bounceSubType}\`);
56
+
57
+ // Get bounced recipients
58
+ const bouncedRecipients = bounce.bouncedRecipients || [];
59
+
60
+ for (const recipient of bouncedRecipients) {
61
+ const email = recipient.emailAddress;
62
+
63
+ // Add to suppression list
64
+ await addToSuppressionList(bucket, email, 'bounce', {
65
+ type: bounce.bounceType,
66
+ subType: bounce.bounceSubType,
67
+ diagnosticCode: recipient.diagnosticCode,
68
+ action: recipient.action,
69
+ status: recipient.status,
70
+ timestamp,
71
+ originalMessageId: mail.messageId,
72
+ });
73
+
74
+ console.log(\`Added \${email} to suppression list (bounce)\`);
75
+ }
76
+
77
+ // Log bounce event
78
+ await logFeedbackEvent(bucket, 'bounces', {
79
+ type: 'bounce',
80
+ bounceType: bounce.bounceType,
81
+ bounceSubType: bounce.bounceSubType,
82
+ recipients: bouncedRecipients.map(r => r.emailAddress),
83
+ messageId: mail.messageId,
84
+ timestamp,
85
+ });
86
+
87
+ // Notify admin for hard bounces
88
+ if (bounce.bounceType === 'Permanent' && adminTopicArn) {
89
+ await sns.send(new PublishCommand({
90
+ TopicArn: adminTopicArn,
91
+ Subject: \`Email Bounce Alert: \${bounce.bounceSubType}\`,
92
+ Message: JSON.stringify({
93
+ type: 'bounce',
94
+ bounceType: bounce.bounceType,
95
+ bounceSubType: bounce.bounceSubType,
96
+ recipients: bouncedRecipients.map(r => ({
97
+ email: r.emailAddress,
98
+ diagnosticCode: r.diagnosticCode,
99
+ })),
100
+ originalSubject: mail.commonHeaders?.subject,
101
+ timestamp,
102
+ }, null, 2),
103
+ }));
104
+ }
105
+ }
106
+
107
+ async function handleComplaint(message, bucket, adminTopicArn, timestamp) {
108
+ const complaint = message.complaint || {};
109
+ const mail = message.mail || {};
110
+
111
+ console.log(\`Processing complaint: \${complaint.complaintFeedbackType}\`);
112
+
113
+ // Get complained recipients
114
+ const complainedRecipients = complaint.complainedRecipients || [];
115
+
116
+ for (const recipient of complainedRecipients) {
117
+ const email = recipient.emailAddress;
118
+
119
+ // Add to suppression list
120
+ await addToSuppressionList(bucket, email, 'complaint', {
121
+ feedbackType: complaint.complaintFeedbackType,
122
+ userAgent: complaint.userAgent,
123
+ timestamp,
124
+ originalMessageId: mail.messageId,
125
+ });
126
+
127
+ console.log(\`Added \${email} to suppression list (complaint)\`);
128
+ }
129
+
130
+ // Log complaint event
131
+ await logFeedbackEvent(bucket, 'complaints', {
132
+ type: 'complaint',
133
+ feedbackType: complaint.complaintFeedbackType,
134
+ recipients: complainedRecipients.map(r => r.emailAddress),
135
+ messageId: mail.messageId,
136
+ timestamp,
137
+ });
138
+
139
+ // Always notify admin for complaints
140
+ if (adminTopicArn) {
141
+ await sns.send(new PublishCommand({
142
+ TopicArn: adminTopicArn,
143
+ Subject: \`Email Complaint Alert: \${complaint.complaintFeedbackType || 'Unknown'}\`,
144
+ Message: JSON.stringify({
145
+ type: 'complaint',
146
+ feedbackType: complaint.complaintFeedbackType,
147
+ recipients: complainedRecipients.map(r => r.emailAddress),
148
+ originalSubject: mail.commonHeaders?.subject,
149
+ timestamp,
150
+ }, null, 2),
151
+ }));
152
+ }
153
+ }
154
+
155
+ async function handleDelivery(message, bucket, timestamp) {
156
+ const delivery = message.delivery || {};
157
+ const mail = message.mail || {};
158
+
159
+ console.log(\`Processing delivery confirmation for \${delivery.recipients?.join(', ')}\`);
160
+
161
+ // Log delivery event
162
+ await logFeedbackEvent(bucket, 'deliveries', {
163
+ type: 'delivery',
164
+ recipients: delivery.recipients,
165
+ messageId: mail.messageId,
166
+ processingTimeMillis: delivery.processingTimeMillis,
167
+ smtpResponse: delivery.smtpResponse,
168
+ timestamp,
169
+ });
170
+ }
171
+
172
+ async function addToSuppressionList(bucket, email, reason, details) {
173
+ const key = 'suppression/list.json';
174
+ let list = [];
175
+
176
+ try {
177
+ const result = await s3.send(new GetObjectCommand({
178
+ Bucket: bucket,
179
+ Key: key,
180
+ }));
181
+ list = JSON.parse(await result.Body.transformToString());
182
+ } catch {
183
+ // List doesn't exist yet
184
+ }
185
+
186
+ // Check if already in list
187
+ const existing = list.find(item => item.email === email);
188
+ if (existing) {
189
+ existing.lastUpdated = details.timestamp;
190
+ existing.count = (existing.count || 1) + 1;
191
+ } else {
192
+ list.push({
193
+ email,
194
+ reason,
195
+ addedAt: details.timestamp,
196
+ lastUpdated: details.timestamp,
197
+ count: 1,
198
+ details,
199
+ });
200
+ }
201
+
202
+ await s3.send(new PutObjectCommand({
203
+ Bucket: bucket,
204
+ Key: key,
205
+ Body: JSON.stringify(list, null, 2),
206
+ ContentType: 'application/json',
207
+ }));
208
+ }
209
+
210
+ async function logFeedbackEvent(bucket, type, event) {
211
+ const date = new Date();
212
+ const year = date.getFullYear();
213
+ const month = String(date.getMonth() + 1).padStart(2, '0');
214
+ const day = String(date.getDate()).padStart(2, '0');
215
+
216
+ const key = \`feedback/\${type}/\${year}/\${month}/\${day}/\${Date.now()}-\${Math.random().toString(36).substr(2)}.json\`;
217
+
218
+ await s3.send(new PutObjectCommand({
219
+ Bucket: bucket,
220
+ Key: key,
221
+ Body: JSON.stringify(event, null, 2),
222
+ ContentType: 'application/json',
223
+ }));
224
+ }
225
+ `;
226
+ export default handler;
@@ -0,0 +1,167 @@
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
+ export declare const handler: `
13
+ const { S3Client, GetObjectCommand, PutObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');
14
+ const s3 = new S3Client({});
15
+
16
+ exports.handler = async (event) => {
17
+ console.log('Inbound email event:', JSON.stringify(event, null, 2));
18
+
19
+ for (const record of event.Records) {
20
+ try {
21
+ // Handle SES notification via SNS
22
+ const sesNotification = JSON.parse(record.Sns?.Message || record.body || '{}');
23
+ const mail = sesNotification.mail || {};
24
+ const receipt = sesNotification.receipt || {};
25
+
26
+ const bucket = process.env.EMAIL_BUCKET;
27
+ const messageId = mail.messageId;
28
+
29
+ if (!messageId) {
30
+ console.log('No messageId found, skipping');
31
+ continue;
32
+ }
33
+
34
+ // Get the raw email from S3
35
+ const sourceKey = \`incoming/\${messageId}\`;
36
+ let rawEmail;
37
+
38
+ try {
39
+ const getResult = await s3.send(new GetObjectCommand({
40
+ Bucket: bucket,
41
+ Key: sourceKey,
42
+ }));
43
+ rawEmail = await getResult.Body.transformToString();
44
+ } catch (err) {
45
+ console.log('Could not retrieve raw email:', err.message);
46
+ continue;
47
+ }
48
+
49
+ // Parse email headers
50
+ const headers = {};
51
+ const headerSection = rawEmail.split('\\n\\n')[0];
52
+ let currentHeader = '';
53
+
54
+ for (const line of headerSection.split('\\n')) {
55
+ if (line.match(/^[A-Za-z-]+:/)) {
56
+ const colonIndex = line.indexOf(':');
57
+ currentHeader = line.substring(0, colonIndex).toLowerCase();
58
+ headers[currentHeader] = line.substring(colonIndex + 1).trim();
59
+ } else if (currentHeader && (line.startsWith(' ') || line.startsWith('\\t'))) {
60
+ headers[currentHeader] += ' ' + line.trim();
61
+ }
62
+ }
63
+
64
+ // Extract key metadata
65
+ const from = headers['from'] || '';
66
+ const to = headers['to'] || '';
67
+ const subject = headers['subject'] || '(no subject)';
68
+ const date = headers['date'] || new Date().toISOString();
69
+
70
+ // Parse sender email
71
+ const fromMatch = from.match(/<([^>]+)>/) || [null, from];
72
+ const fromEmail = fromMatch[1] || from;
73
+ const fromDomain = fromEmail.split('@')[1] || 'unknown';
74
+
75
+ // Parse recipient email (handle + addressing)
76
+ const toMatch = to.match(/<([^>]+)>/) || [null, to];
77
+ const toEmail = toMatch[1] || to;
78
+ const [localPart, toDomain] = toEmail.split('@');
79
+ const baseLocalPart = localPart.split('+')[0]; // Handle user+tag@domain.com
80
+ const tag = localPart.includes('+') ? localPart.split('+')[1] : null;
81
+
82
+ // Create timestamp-based path
83
+ const timestamp = new Date(date);
84
+ const year = timestamp.getFullYear();
85
+ const month = String(timestamp.getMonth() + 1).padStart(2, '0');
86
+ const day = String(timestamp.getDate()).padStart(2, '0');
87
+
88
+ // Organize by: domain/mailbox/year/month/day/sender/messageId
89
+ const destPath = \`mailboxes/\${toDomain}/\${baseLocalPart}/\${year}/\${month}/\${day}/\${fromDomain}/\${messageId}\`;
90
+
91
+ // Copy raw email to organized location
92
+ await s3.send(CopyObjectCommand({
93
+ Bucket: bucket,
94
+ CopySource: \`\${bucket}/\${sourceKey}\`,
95
+ Key: \`\${destPath}/raw.eml\`,
96
+ }));
97
+
98
+ // Create metadata JSON
99
+ const metadata = {
100
+ messageId,
101
+ from: fromEmail,
102
+ fromName: from.replace(/<[^>]+>/, '').trim(),
103
+ to: toEmail,
104
+ toName: to.replace(/<[^>]+>/, '').trim(),
105
+ subject,
106
+ date: timestamp.toISOString(),
107
+ receivedAt: new Date().toISOString(),
108
+ tag,
109
+ spamVerdict: receipt.spamVerdict?.status || 'UNKNOWN',
110
+ virusVerdict: receipt.virusVerdict?.status || 'UNKNOWN',
111
+ spfVerdict: receipt.spfVerdict?.status || 'UNKNOWN',
112
+ dkimVerdict: receipt.dkimVerdict?.status || 'UNKNOWN',
113
+ dmarcVerdict: receipt.dmarcVerdict?.status || 'UNKNOWN',
114
+ hasAttachments: rawEmail.includes('Content-Disposition: attachment'),
115
+ };
116
+
117
+ await s3.send(new PutObjectCommand({
118
+ Bucket: bucket,
119
+ Key: \`\${destPath}/metadata.json\`,
120
+ Body: JSON.stringify(metadata, null, 2),
121
+ ContentType: 'application/json',
122
+ }));
123
+
124
+ // Update inbox index
125
+ const indexKey = \`mailboxes/\${toDomain}/\${baseLocalPart}/inbox.json\`;
126
+ let inbox = [];
127
+
128
+ try {
129
+ const indexResult = await s3.send(new GetObjectCommand({
130
+ Bucket: bucket,
131
+ Key: indexKey,
132
+ }));
133
+ inbox = JSON.parse(await indexResult.Body.transformToString());
134
+ } catch {
135
+ // Index doesn't exist yet
136
+ }
137
+
138
+ inbox.unshift({
139
+ messageId,
140
+ from: fromEmail,
141
+ subject,
142
+ date: timestamp.toISOString(),
143
+ read: false,
144
+ path: destPath,
145
+ });
146
+
147
+ // Keep only last 1000 emails in index
148
+ inbox = inbox.slice(0, 1000);
149
+
150
+ await s3.send(new PutObjectCommand({
151
+ Bucket: bucket,
152
+ Key: indexKey,
153
+ Body: JSON.stringify(inbox, null, 2),
154
+ ContentType: 'application/json',
155
+ }));
156
+
157
+ console.log(\`Processed email: \${messageId} from \${fromEmail} to \${toEmail}\`);
158
+
159
+ } catch (error) {
160
+ console.error('Error processing email:', error);
161
+ }
162
+ }
163
+
164
+ return { statusCode: 200, body: 'OK' };
165
+ };
166
+ `;
167
+ export default handler;