@anthusai/papyrus 5.20.0 → 5.21.0

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 (54) hide show
  1. package/amplify/functions/content-actions/handler.py +17 -2
  2. package/amplify/plugins/newsletter/config.js +195 -0
  3. package/amplify/plugins/newsletter/config.ts +240 -0
  4. package/amplify/plugins/newsletter/function/handler.py +6 -0
  5. package/amplify/plugins/newsletter/function/requirements.txt +5 -0
  6. package/amplify/plugins/newsletter/ops/handler.py +12 -0
  7. package/amplify/plugins/newsletter/ops/resource.js +27 -0
  8. package/amplify/plugins/newsletter/ops/resource.ts +37 -0
  9. package/amplify/plugins/newsletter/papyrus.plugin.js +260 -0
  10. package/amplify/plugins/newsletter/papyrus.plugin.ts +308 -0
  11. package/amplify/plugins/newsletter/schema.js +56 -0
  12. package/amplify/plugins/newsletter/schema.ts +61 -0
  13. package/amplify/plugins/newsletter/secure-string-parameter.js +107 -0
  14. package/amplify/plugins/newsletter/secure-string-parameter.ts +120 -0
  15. package/amplify/plugins/newsletter/sending.js +140 -0
  16. package/amplify/plugins/newsletter/sending.ts +186 -0
  17. package/amplify/plugins/reader-steering/config.js +52 -1
  18. package/amplify/plugins/reader-steering/config.ts +91 -1
  19. package/amplify/plugins/reader-steering/function/ai_moderation.py +230 -0
  20. package/amplify/plugins/reader-steering/function/handler.py +829 -10
  21. package/amplify/plugins/reader-steering/function/moderation-prompt.md +27 -0
  22. package/amplify/plugins/reader-steering/function/moderation.py +316 -0
  23. package/amplify/plugins/reader-steering/function/resource.js +1 -1
  24. package/amplify/plugins/reader-steering/function/resource.ts +1 -1
  25. package/amplify/plugins/reader-steering/papyrus.plugin.js +40 -4
  26. package/amplify/plugins/reader-steering/papyrus.plugin.ts +43 -4
  27. package/amplify/plugins/reader-steering/schema.js +101 -1
  28. package/amplify/plugins/reader-steering/schema.ts +101 -1
  29. package/amplify/plugins/registry.js +2 -0
  30. package/amplify/plugins/registry.ts +2 -0
  31. package/amplify/plugins/types.ts +2 -0
  32. package/app/api/newsletter/confirm/route.ts +13 -0
  33. package/app/api/newsletter/preferences/route.ts +13 -0
  34. package/app/api/newsletter/subscribe/route.ts +9 -0
  35. package/app/api/newsletter/unsubscribe/route.ts +13 -0
  36. package/app/api/reader/comment/delete/route.ts +9 -0
  37. package/app/api/reader/comment/edit/route.ts +9 -0
  38. package/app/api/reader/comment/route.ts +9 -0
  39. package/app/api/reader/report/route.ts +9 -0
  40. package/app/api/reader/submit/route.ts +9 -0
  41. package/components/moderation-panel.tsx +248 -0
  42. package/components/newsletter-panel.tsx +474 -0
  43. package/components/newsletter-sections.tsx +163 -0
  44. package/components/newsroom-organizer.css +14 -0
  45. package/components/topic-steering-workspace.tsx +42 -5
  46. package/lib/newsletter-api.ts +391 -0
  47. package/lib/newsletter-client.ts +46 -0
  48. package/lib/newsletter-fixture.ts +184 -0
  49. package/lib/newsletter-model.ts +202 -0
  50. package/lib/newsletter-pages.ts +264 -0
  51. package/lib/reader-api.ts +7 -5
  52. package/lib/reader-moderation.ts +220 -0
  53. package/package.json +19 -1
  54. package/routes.manifest.json +103 -1
@@ -0,0 +1,260 @@
1
+ import { Duration, RemovalPolicy, Stack } from "aws-cdk-lib";
2
+ import { Alarm, ComparisonOperator, MathExpression, Metric, TreatMissingData } from "aws-cdk-lib/aws-cloudwatch";
3
+ import { SnsAction } from "aws-cdk-lib/aws-cloudwatch-actions";
4
+ import { AttributeType, BillingMode, ProjectionType, Table, TableEncryption } from "aws-cdk-lib/aws-dynamodb";
5
+ import { ArnPrincipal, Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
6
+ import { Key } from "aws-cdk-lib/aws-kms";
7
+ import { Topic } from "aws-cdk-lib/aws-sns";
8
+ import { LambdaSubscription } from "aws-cdk-lib/aws-sns-subscriptions";
9
+ import { Architecture, Function as LambdaFunction, Runtime } from "aws-cdk-lib/aws-lambda";
10
+ import { execFileSync } from "node:child_process";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { SecureStringParameter } from "./secure-string-parameter.js";
14
+ import { pythonLambdaCode } from "../../functions/shared/python-bundle.js";
15
+ import { resolveNewsletterConfig } from "./config.js";
16
+ import { newsletterOps } from "./ops/resource.js";
17
+ import { NEWSLETTER_MUTATIONS, NEWSLETTER_QUERIES, newsletterSchemaDefinitions } from "./schema.js";
18
+ import { functionArn, newsletterFunctionName, wireSending } from "./sending.js";
19
+ export { resolveNewsletterConfig };
20
+ export const NEWSLETTER_OUTPUT_KEY = "newsletter";
21
+ /** Set on the site's content-actions function: it invokes this function (`item-published`) after a real publish. Unset: no alerts. */
22
+ export const NEWSLETTER_FUNCTION_ENV = "PAPYRUS_NEWSLETTER_FUNCTION";
23
+ export const NEWSLETTER_HANDLER = "papyrus_content.newsletter.handler.handler";
24
+ /** `boto3` is bundled because the runtime's copy may predate SESv2 `Simple.Headers` (List-Unsubscribe). */
25
+ export const NEWSLETTER_REQUIREMENTS = ["PyYAML>=6.0.2,<7", "citeproc-py>=0.8.2,<1", "anthus-markus==0.7.0", "Pillow>=11.3,<12", "boto3>=1.35.8,<2"];
26
+ /** Relative to `amplify/functions/`, which is where the shared bundler looks for a function's `handler.py`. */
27
+ const FUNCTION_DIRECTORY = "../plugins/newsletter/function";
28
+ export const newsletterManifest = {
29
+ name: "newsletter",
30
+ contract: 1,
31
+ models: [],
32
+ queries: NEWSLETTER_QUERIES,
33
+ mutations: NEWSLETTER_MUTATIONS,
34
+ guest: { mutations: [] },
35
+ newsroomPanels: [],
36
+ staticAssets: ["_plugins/papyrus-newsletter@1.js"],
37
+ };
38
+ let codeForTests;
39
+ /** Synthesis tests swap the bundled Python asset (a pip install) for inline code. Pass nothing to restore it. */
40
+ export function overrideNewsletterCodeForTests(code) {
41
+ codeForTests = code;
42
+ }
43
+ export function newsletterKeyParameterName(siteId) {
44
+ return `/papyrus/${siteId}/newsletter-key`;
45
+ }
46
+ /** The SES identity ARN and configuration set ARN the function may send through. */
47
+ export function newsletterSesResources(stack, config) {
48
+ return [
49
+ `arn:${stack.partition}:ses:${stack.region}:${stack.account}:identity/${config.sendingDomain}`,
50
+ `arn:${stack.partition}:ses:${stack.region}:${stack.account}:configuration-set/${config.configurationSet}`,
51
+ ];
52
+ }
53
+ export const BOUNCE_RATE_THRESHOLD = 0.04;
54
+ export const COMPLAINT_RATE_THRESHOLD = 0.0008;
55
+ export const ALARM_MINIMUM_SENDS = 50;
56
+ export function newsletterAlarmTopicName(siteId) {
57
+ return `papyrus-newsletter-alarms-${siteId}`;
58
+ }
59
+ /** The two alarm names; the function pauses sending only for these (python: `events.alarm_names`). */
60
+ export function newsletterAlarmNames(siteId) {
61
+ return { bounce: `papyrus-newsletter-${siteId}-bounce-rate`, complaint: `papyrus-newsletter-${siteId}-complaint-rate` };
62
+ }
63
+ /** What the function reads from its environment. Lists carry only what it needs to name them in the email. */
64
+ export function newsletterEnvironment(config, tableName, keyParameter) {
65
+ return {
66
+ TABLE_NAME: tableName,
67
+ KEY_PARAMETER: keyParameter,
68
+ SITE_ID: config.siteId,
69
+ SITE_ORIGIN: config.siteOrigin,
70
+ SENDING_DOMAIN: config.sendingDomain,
71
+ FROM_ADDRESS: config.fromAddress,
72
+ FROM_NAME: config.fromName,
73
+ CONFIGURATION_SET: config.configurationSet,
74
+ ITEM_URL_STYLE: config.itemUrlStyle,
75
+ INSTANT_ALERTS: config.instantAlerts ? "true" : "false",
76
+ LISTS_JSON: JSON.stringify(config.lists.map((list) => ({
77
+ id: list.id,
78
+ name: list.name,
79
+ description: list.description,
80
+ kind: list.kind,
81
+ // A roundup's issue type, archive section and time zone are what drafting needs; its schedule stays in the stack.
82
+ ...(list.kind === "roundup" ? { issueType: list.issueType, archivePath: list.archivePath, timezone: list.schedule.timezone } : {}),
83
+ // An alert's rule and approval decide which published items raise an alert and whether an admin approves it.
84
+ ...(list.kind === "alert" ? { rule: list.rule, approval: list.approval } : {}),
85
+ }))),
86
+ THEME_JSON: JSON.stringify(config.theme),
87
+ ALARM_NAMES: Object.values(newsletterAlarmNames(config.siteId)).join(","),
88
+ };
89
+ }
90
+ export const newsletterPlugin = {
91
+ manifest: newsletterManifest,
92
+ resolveConfig: resolveNewsletterConfig,
93
+ functions: () => ({ newsletterOps }),
94
+ schemaDefinitions: newsletterSchemaDefinitions,
95
+ publicSettings: (config) => ({
96
+ contract: newsletterManifest.contract,
97
+ fromName: config.fromName,
98
+ lists: config.lists.map((list) => ({
99
+ id: list.id,
100
+ name: list.name,
101
+ description: list.description,
102
+ kind: list.kind,
103
+ // The panel needs the item type to open an issue in the editor and the archive path to show where it lands.
104
+ ...(list.kind === "roundup" ? { issueType: list.issueType, archivePath: list.archivePath } : {}),
105
+ })),
106
+ theme: config.theme,
107
+ }),
108
+ wire(backend, config, context) {
109
+ const stack = Stack.of(context.createStack("newsletter"));
110
+ const key = new Key(stack, "NewsletterKey", {
111
+ description: `Encrypts the ${config.siteId} newsletter subscriber table`,
112
+ enableKeyRotation: true,
113
+ removalPolicy: RemovalPolicy.RETAIN,
114
+ });
115
+ const table = new Table(stack, "NewsletterTable", {
116
+ partitionKey: { name: "pk", type: AttributeType.STRING },
117
+ sortKey: { name: "sk", type: AttributeType.STRING },
118
+ billingMode: BillingMode.PAY_PER_REQUEST,
119
+ timeToLiveAttribute: "expiresAt",
120
+ encryption: TableEncryption.CUSTOMER_MANAGED,
121
+ encryptionKey: key,
122
+ // Point-in-time recovery stays off so that erasing a subscriber is real erasure.
123
+ pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: false },
124
+ removalPolicy: RemovalPolicy.RETAIN,
125
+ });
126
+ table.addGlobalSecondaryIndex({
127
+ indexName: "byList",
128
+ partitionKey: { name: "gsiList", type: AttributeType.STRING },
129
+ sortKey: { name: "sk", type: AttributeType.STRING },
130
+ projectionType: ProjectionType.KEYS_ONLY,
131
+ });
132
+ // Sparse: only send-ledger rows carry `gsiHid`, so erasing a subscriber finds their rows with one query, not a scan.
133
+ table.addGlobalSecondaryIndex({
134
+ indexName: "byHid",
135
+ partitionKey: { name: "gsiHid", type: AttributeType.STRING },
136
+ projectionType: ProjectionType.KEYS_ONLY,
137
+ });
138
+ const keyParameter = new SecureStringParameter(stack, "NewsletterKeyParameter", {
139
+ parameterName: newsletterKeyParameterName(config.siteId),
140
+ description: `Root key for ${config.siteId} newsletter subscriber hashing and link signing (HKDF-derived)`,
141
+ });
142
+ const functionDirectory = path.dirname(fileURLToPath(import.meta.url));
143
+ // One bundle serves the `newsletter` function and the send worker; they differ in handler, timeout and IAM.
144
+ const code = codeForTests ?? pythonLambdaCode({
145
+ functionDir: FUNCTION_DIRECTORY,
146
+ modules: ["papyrus_content"],
147
+ requirements: NEWSLETTER_REQUIREMENTS,
148
+ noDeps: true,
149
+ checkoutExtras: (outputDir) => installRequirements(path.join(functionDirectory, "function", "requirements.txt"), outputDir),
150
+ }, [
151
+ "bash",
152
+ "-c",
153
+ [
154
+ "set -euo pipefail",
155
+ "mkdir -p /asset-output/papyrus_content",
156
+ "cp amplify/plugins/newsletter/function/handler.py /asset-output/handler.py",
157
+ "cp -R src/papyrus_content/. /asset-output/papyrus_content/",
158
+ "python3 -m pip install -r amplify/plugins/newsletter/function/requirements.txt -t /asset-output --no-cache-dir",
159
+ ].join(" && "),
160
+ ]);
161
+ const environment = newsletterEnvironment(config, table.tableName, keyParameter.parameterName);
162
+ const lambda = new LambdaFunction(stack, "NewsletterFunction", {
163
+ functionName: newsletterFunctionName(config.siteId),
164
+ runtime: Runtime.PYTHON_3_12,
165
+ architecture: Architecture.ARM_64,
166
+ handler: NEWSLETTER_HANDLER,
167
+ // Starting a send pages the whole list and queues it, so this is longer than a signup needs.
168
+ timeout: Duration.seconds(120),
169
+ memorySize: 512,
170
+ description: `Newsletter for ${config.siteId}: subscriptions, roundup drafts, approval and starting sends`,
171
+ environment,
172
+ code,
173
+ });
174
+ table.grantReadWriteData(lambda); // includes the table key's encrypt and decrypt
175
+ lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["ssm:GetParameter"], resources: [keyParameter.parameterArn] }));
176
+ lambda.addToRolePolicy(new PolicyStatement({
177
+ effect: Effect.ALLOW,
178
+ actions: ["ses:SendEmail", "ses:SendRawEmail"],
179
+ resources: newsletterSesResources(stack, config),
180
+ conditions: { StringEquals: { "ses:FromAddress": config.fromAddress } },
181
+ }));
182
+ wireSending({
183
+ stack,
184
+ config,
185
+ context,
186
+ backend,
187
+ table,
188
+ lambda,
189
+ environment,
190
+ keyParameterArn: keyParameter.parameterArn,
191
+ sesResources: newsletterSesResources(stack, config),
192
+ code,
193
+ });
194
+ // The SES configuration set's own sending switch, for the alarm pause. Nothing else of SES is writable.
195
+ lambda.addToRolePolicy(new PolicyStatement({
196
+ effect: Effect.ALLOW,
197
+ actions: ["ses:PutConfigurationSetSendingOptions"],
198
+ resources: [newsletterSesResources(stack, config)[1]],
199
+ }));
200
+ // Lifting a suppression after a deliberate re-subscribe. IAM has no resource-level scope for the account list.
201
+ lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["ses:DeleteSuppressedDestination"], resources: ["*"] }));
202
+ // SES delivery events: the topic belongs to the sending stack and is named literally.
203
+ const eventTopic = Topic.fromTopicArn(stack, "SesEventTopic", `arn:${stack.partition}:sns:${stack.region}:${stack.account}:${config.eventTopicName}`);
204
+ eventTopic.addSubscription(new LambdaSubscription(lambda));
205
+ // Bounce and complaint rate alarms over the CloudWatch event destination, 24 h period, at least 50 sends.
206
+ const alarmTopic = new Topic(stack, "AlarmTopic", { topicName: newsletterAlarmTopicName(config.siteId) });
207
+ alarmTopic.addSubscription(new LambdaSubscription(lambda));
208
+ const metric = (metricName) => new Metric({
209
+ namespace: "AWS/SES",
210
+ metricName,
211
+ dimensionsMap: { "ses:configuration-set": config.configurationSet },
212
+ statistic: "Sum",
213
+ period: Duration.hours(24),
214
+ });
215
+ const names = newsletterAlarmNames(config.siteId);
216
+ for (const [id, alarmName, metricName, threshold] of [
217
+ ["BounceRateAlarm", names.bounce, "Bounce", BOUNCE_RATE_THRESHOLD],
218
+ ["ComplaintRateAlarm", names.complaint, "Complaint", COMPLAINT_RATE_THRESHOLD],
219
+ ]) {
220
+ const rate = new MathExpression({
221
+ expression: `IF(sent >= ${ALARM_MINIMUM_SENDS}, FILL(events, 0) / sent, 0)`,
222
+ usingMetrics: { sent: metric("Send"), events: metric(metricName) },
223
+ period: Duration.hours(24),
224
+ label: `${metricName} rate`,
225
+ });
226
+ const alarm = new Alarm(stack, id, {
227
+ alarmName,
228
+ alarmDescription: `${metricName} rate above ${threshold * 100}% of sends in 24 hours (at least ${ALARM_MINIMUM_SENDS} sends): pauses ${config.siteId} newsletter sending`,
229
+ metric: rate,
230
+ threshold,
231
+ evaluationPeriods: 1,
232
+ comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,
233
+ treatMissingData: TreatMissingData.NOT_BREACHING,
234
+ });
235
+ alarm.addAlarmAction(new SnsAction(alarmTopic));
236
+ }
237
+ // The publish path tells this function about a real publish. The ARN is spelled out (not referenced) so the content-actions
238
+ // stack does not depend on this one, and the grant is for this one function only.
239
+ const contentActions = context.contentActionsLambda;
240
+ contentActions.addEnvironment(NEWSLETTER_FUNCTION_ENV, newsletterFunctionName(config.siteId));
241
+ contentActions.addToRolePolicy(new PolicyStatement({
242
+ effect: Effect.ALLOW,
243
+ actions: ["lambda:InvokeFunction"],
244
+ resources: [functionArn(Stack.of(contentActions), newsletterFunctionName(config.siteId))],
245
+ }));
246
+ lambda.addPermission("InvokeFromCmsCompute", {
247
+ principal: new ArnPrincipal(config.computeRoleArn),
248
+ action: "lambda:InvokeFunction",
249
+ });
250
+ backend.addOutput({ custom: { [NEWSLETTER_OUTPUT_KEY]: { actionsFunction: lambda.functionName } } });
251
+ },
252
+ };
253
+ function installRequirements(requirementsPath, outputDir) {
254
+ // Same wheels and platform as the other Python functions: a Lambda on arm64 with CPython 3.12.
255
+ execFileSync("python3", [
256
+ "-m", "pip", "install", "-r", requirementsPath, "-t", outputDir, "--no-cache-dir",
257
+ "--platform", "manylinux2014_aarch64", "--implementation", "cp", "--python-version", "3.12",
258
+ "--only-binary=:all:", "--ignore-requires-python",
259
+ ], { stdio: "inherit" });
260
+ }
@@ -0,0 +1,308 @@
1
+ import { Duration, RemovalPolicy, Stack } from "aws-cdk-lib";
2
+ import { Alarm, ComparisonOperator, MathExpression, Metric, TreatMissingData } from "aws-cdk-lib/aws-cloudwatch";
3
+ import { SnsAction } from "aws-cdk-lib/aws-cloudwatch-actions";
4
+ import { AttributeType, BillingMode, ProjectionType, Table, TableEncryption } from "aws-cdk-lib/aws-dynamodb";
5
+ import { ArnPrincipal, Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
6
+ import { Key } from "aws-cdk-lib/aws-kms";
7
+ import { Topic } from "aws-cdk-lib/aws-sns";
8
+ import { LambdaSubscription } from "aws-cdk-lib/aws-sns-subscriptions";
9
+ import { Architecture, type Code, Function as LambdaFunction, Runtime } from "aws-cdk-lib/aws-lambda";
10
+ import { execFileSync } from "node:child_process";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { SecureStringParameter } from "./secure-string-parameter";
14
+ import { pythonLambdaCode } from "../../functions/shared/python-bundle";
15
+ import type { PapyrusPlugin, PluginManifest, PluginWiringContext } from "../types";
16
+ import { resolveNewsletterConfig, type NewsletterConfig } from "./config";
17
+ import { newsletterOps } from "./ops/resource";
18
+ import { NEWSLETTER_MUTATIONS, NEWSLETTER_QUERIES, newsletterSchemaDefinitions } from "./schema";
19
+ import { functionArn, newsletterFunctionName, wireSending } from "./sending";
20
+
21
+ export { resolveNewsletterConfig };
22
+ export type { NewsletterConfig };
23
+
24
+ export const NEWSLETTER_OUTPUT_KEY = "newsletter";
25
+ /** Set on the site's content-actions function: it invokes this function (`item-published`) after a real publish. Unset: no alerts. */
26
+ export const NEWSLETTER_FUNCTION_ENV = "PAPYRUS_NEWSLETTER_FUNCTION";
27
+ export const NEWSLETTER_HANDLER = "papyrus_content.newsletter.handler.handler";
28
+ /** `boto3` is bundled because the runtime's copy may predate SESv2 `Simple.Headers` (List-Unsubscribe). */
29
+ export const NEWSLETTER_REQUIREMENTS = ["PyYAML>=6.0.2,<7", "citeproc-py>=0.8.2,<1", "anthus-markus==0.7.0", "Pillow>=11.3,<12", "boto3>=1.35.8,<2"];
30
+ /** Relative to `amplify/functions/`, which is where the shared bundler looks for a function's `handler.py`. */
31
+ const FUNCTION_DIRECTORY = "../plugins/newsletter/function";
32
+
33
+ export const newsletterManifest: PluginManifest = {
34
+ name: "newsletter",
35
+ contract: 1,
36
+ models: [],
37
+ queries: NEWSLETTER_QUERIES,
38
+ mutations: NEWSLETTER_MUTATIONS,
39
+ guest: { mutations: [] },
40
+ newsroomPanels: [],
41
+ staticAssets: ["_plugins/papyrus-newsletter@1.js"],
42
+ };
43
+
44
+ let codeForTests: Code | undefined;
45
+
46
+ /** Synthesis tests swap the bundled Python asset (a pip install) for inline code. Pass nothing to restore it. */
47
+ export function overrideNewsletterCodeForTests(code?: Code): void {
48
+ codeForTests = code;
49
+ }
50
+
51
+ export function newsletterKeyParameterName(siteId: string): string {
52
+ return `/papyrus/${siteId}/newsletter-key`;
53
+ }
54
+
55
+ /** The SES identity ARN and configuration set ARN the function may send through. */
56
+ export function newsletterSesResources(stack: Stack, config: Pick<NewsletterConfig, "sendingDomain" | "configurationSet">): string[] {
57
+ return [
58
+ `arn:${stack.partition}:ses:${stack.region}:${stack.account}:identity/${config.sendingDomain}`,
59
+ `arn:${stack.partition}:ses:${stack.region}:${stack.account}:configuration-set/${config.configurationSet}`,
60
+ ];
61
+ }
62
+
63
+ export const BOUNCE_RATE_THRESHOLD = 0.04;
64
+ export const COMPLAINT_RATE_THRESHOLD = 0.0008;
65
+ export const ALARM_MINIMUM_SENDS = 50;
66
+
67
+ export function newsletterAlarmTopicName(siteId: string): string {
68
+ return `papyrus-newsletter-alarms-${siteId}`;
69
+ }
70
+
71
+ /** The two alarm names; the function pauses sending only for these (python: `events.alarm_names`). */
72
+ export function newsletterAlarmNames(siteId: string): { bounce: string; complaint: string } {
73
+ return { bounce: `papyrus-newsletter-${siteId}-bounce-rate`, complaint: `papyrus-newsletter-${siteId}-complaint-rate` };
74
+ }
75
+
76
+ /** What the function reads from its environment. Lists carry only what it needs to name them in the email. */
77
+ export function newsletterEnvironment(config: NewsletterConfig, tableName: string, keyParameter: string): Record<string, string> {
78
+ return {
79
+ TABLE_NAME: tableName,
80
+ KEY_PARAMETER: keyParameter,
81
+ SITE_ID: config.siteId,
82
+ SITE_ORIGIN: config.siteOrigin,
83
+ SENDING_DOMAIN: config.sendingDomain,
84
+ FROM_ADDRESS: config.fromAddress,
85
+ FROM_NAME: config.fromName,
86
+ CONFIGURATION_SET: config.configurationSet,
87
+ ITEM_URL_STYLE: config.itemUrlStyle,
88
+ INSTANT_ALERTS: config.instantAlerts ? "true" : "false",
89
+ LISTS_JSON: JSON.stringify(
90
+ config.lists.map((list) => ({
91
+ id: list.id,
92
+ name: list.name,
93
+ description: list.description,
94
+ kind: list.kind,
95
+ // A roundup's issue type, archive section and time zone are what drafting needs; its schedule stays in the stack.
96
+ ...(list.kind === "roundup" ? { issueType: list.issueType, archivePath: list.archivePath, timezone: list.schedule.timezone } : {}),
97
+ // An alert's rule and approval decide which published items raise an alert and whether an admin approves it.
98
+ ...(list.kind === "alert" ? { rule: list.rule, approval: list.approval } : {}),
99
+ })),
100
+ ),
101
+ THEME_JSON: JSON.stringify(config.theme),
102
+ ALARM_NAMES: Object.values(newsletterAlarmNames(config.siteId)).join(","),
103
+ };
104
+ }
105
+
106
+ export const newsletterPlugin: PapyrusPlugin<NewsletterConfig, { newsletterOps: typeof newsletterOps }> = {
107
+ manifest: newsletterManifest,
108
+ resolveConfig: resolveNewsletterConfig,
109
+ functions: () => ({ newsletterOps }),
110
+ schemaDefinitions: newsletterSchemaDefinitions,
111
+ publicSettings: (config) => ({
112
+ contract: newsletterManifest.contract,
113
+ fromName: config.fromName,
114
+ lists: config.lists.map((list) => ({
115
+ id: list.id,
116
+ name: list.name,
117
+ description: list.description,
118
+ kind: list.kind,
119
+ // The panel needs the item type to open an issue in the editor and the archive path to show where it lands.
120
+ ...(list.kind === "roundup" ? { issueType: list.issueType, archivePath: list.archivePath } : {}),
121
+ })),
122
+ theme: config.theme,
123
+ }),
124
+ wire(backend, config, context: PluginWiringContext) {
125
+ const stack = Stack.of(context.createStack("newsletter"));
126
+
127
+ const key = new Key(stack, "NewsletterKey", {
128
+ description: `Encrypts the ${config.siteId} newsletter subscriber table`,
129
+ enableKeyRotation: true,
130
+ removalPolicy: RemovalPolicy.RETAIN,
131
+ });
132
+ const table = new Table(stack, "NewsletterTable", {
133
+ partitionKey: { name: "pk", type: AttributeType.STRING },
134
+ sortKey: { name: "sk", type: AttributeType.STRING },
135
+ billingMode: BillingMode.PAY_PER_REQUEST,
136
+ timeToLiveAttribute: "expiresAt",
137
+ encryption: TableEncryption.CUSTOMER_MANAGED,
138
+ encryptionKey: key,
139
+ // Point-in-time recovery stays off so that erasing a subscriber is real erasure.
140
+ pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: false },
141
+ removalPolicy: RemovalPolicy.RETAIN,
142
+ });
143
+ table.addGlobalSecondaryIndex({
144
+ indexName: "byList",
145
+ partitionKey: { name: "gsiList", type: AttributeType.STRING },
146
+ sortKey: { name: "sk", type: AttributeType.STRING },
147
+ projectionType: ProjectionType.KEYS_ONLY,
148
+ });
149
+
150
+ // Sparse: only send-ledger rows carry `gsiHid`, so erasing a subscriber finds their rows with one query, not a scan.
151
+ table.addGlobalSecondaryIndex({
152
+ indexName: "byHid",
153
+ partitionKey: { name: "gsiHid", type: AttributeType.STRING },
154
+ projectionType: ProjectionType.KEYS_ONLY,
155
+ });
156
+
157
+ const keyParameter = new SecureStringParameter(stack, "NewsletterKeyParameter", {
158
+ parameterName: newsletterKeyParameterName(config.siteId),
159
+ description: `Root key for ${config.siteId} newsletter subscriber hashing and link signing (HKDF-derived)`,
160
+ });
161
+
162
+ const functionDirectory = path.dirname(fileURLToPath(import.meta.url));
163
+ // One bundle serves the `newsletter` function and the send worker; they differ in handler, timeout and IAM.
164
+ const code = codeForTests ?? pythonLambdaCode(
165
+ {
166
+ functionDir: FUNCTION_DIRECTORY,
167
+ modules: ["papyrus_content"],
168
+ requirements: NEWSLETTER_REQUIREMENTS,
169
+ noDeps: true,
170
+ checkoutExtras: (outputDir) => installRequirements(path.join(functionDirectory, "function", "requirements.txt"), outputDir),
171
+ },
172
+ [
173
+ "bash",
174
+ "-c",
175
+ [
176
+ "set -euo pipefail",
177
+ "mkdir -p /asset-output/papyrus_content",
178
+ "cp amplify/plugins/newsletter/function/handler.py /asset-output/handler.py",
179
+ "cp -R src/papyrus_content/. /asset-output/papyrus_content/",
180
+ "python3 -m pip install -r amplify/plugins/newsletter/function/requirements.txt -t /asset-output --no-cache-dir",
181
+ ].join(" && "),
182
+ ],
183
+ );
184
+ const environment = newsletterEnvironment(config, table.tableName, keyParameter.parameterName);
185
+ const lambda = new LambdaFunction(stack, "NewsletterFunction", {
186
+ functionName: newsletterFunctionName(config.siteId),
187
+ runtime: Runtime.PYTHON_3_12,
188
+ architecture: Architecture.ARM_64,
189
+ handler: NEWSLETTER_HANDLER,
190
+ // Starting a send pages the whole list and queues it, so this is longer than a signup needs.
191
+ timeout: Duration.seconds(120),
192
+ memorySize: 512,
193
+ description: `Newsletter for ${config.siteId}: subscriptions, roundup drafts, approval and starting sends`,
194
+ environment,
195
+ code,
196
+ });
197
+
198
+ table.grantReadWriteData(lambda); // includes the table key's encrypt and decrypt
199
+ lambda.addToRolePolicy(
200
+ new PolicyStatement({ effect: Effect.ALLOW, actions: ["ssm:GetParameter"], resources: [keyParameter.parameterArn] }),
201
+ );
202
+ lambda.addToRolePolicy(
203
+ new PolicyStatement({
204
+ effect: Effect.ALLOW,
205
+ actions: ["ses:SendEmail", "ses:SendRawEmail"],
206
+ resources: newsletterSesResources(stack, config),
207
+ conditions: { StringEquals: { "ses:FromAddress": config.fromAddress } },
208
+ }),
209
+ );
210
+ wireSending({
211
+ stack,
212
+ config,
213
+ context,
214
+ backend,
215
+ table,
216
+ lambda,
217
+ environment,
218
+ keyParameterArn: keyParameter.parameterArn,
219
+ sesResources: newsletterSesResources(stack, config),
220
+ code,
221
+ });
222
+
223
+ // The SES configuration set's own sending switch, for the alarm pause. Nothing else of SES is writable.
224
+ lambda.addToRolePolicy(
225
+ new PolicyStatement({
226
+ effect: Effect.ALLOW,
227
+ actions: ["ses:PutConfigurationSetSendingOptions"],
228
+ resources: [newsletterSesResources(stack, config)[1]],
229
+ }),
230
+ );
231
+ // Lifting a suppression after a deliberate re-subscribe. IAM has no resource-level scope for the account list.
232
+ lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["ses:DeleteSuppressedDestination"], resources: ["*"] }));
233
+
234
+ // SES delivery events: the topic belongs to the sending stack and is named literally.
235
+ const eventTopic = Topic.fromTopicArn(
236
+ stack,
237
+ "SesEventTopic",
238
+ `arn:${stack.partition}:sns:${stack.region}:${stack.account}:${config.eventTopicName}`,
239
+ );
240
+ eventTopic.addSubscription(new LambdaSubscription(lambda));
241
+
242
+ // Bounce and complaint rate alarms over the CloudWatch event destination, 24 h period, at least 50 sends.
243
+ const alarmTopic = new Topic(stack, "AlarmTopic", { topicName: newsletterAlarmTopicName(config.siteId) });
244
+ alarmTopic.addSubscription(new LambdaSubscription(lambda));
245
+ const metric = (metricName: string) =>
246
+ new Metric({
247
+ namespace: "AWS/SES",
248
+ metricName,
249
+ dimensionsMap: { "ses:configuration-set": config.configurationSet },
250
+ statistic: "Sum",
251
+ period: Duration.hours(24),
252
+ });
253
+ const names = newsletterAlarmNames(config.siteId);
254
+ for (const [id, alarmName, metricName, threshold] of [
255
+ ["BounceRateAlarm", names.bounce, "Bounce", BOUNCE_RATE_THRESHOLD],
256
+ ["ComplaintRateAlarm", names.complaint, "Complaint", COMPLAINT_RATE_THRESHOLD],
257
+ ] as const) {
258
+ const rate = new MathExpression({
259
+ expression: `IF(sent >= ${ALARM_MINIMUM_SENDS}, FILL(events, 0) / sent, 0)`,
260
+ usingMetrics: { sent: metric("Send"), events: metric(metricName) },
261
+ period: Duration.hours(24),
262
+ label: `${metricName} rate`,
263
+ });
264
+ const alarm = new Alarm(stack, id, {
265
+ alarmName,
266
+ alarmDescription: `${metricName} rate above ${threshold * 100}% of sends in 24 hours (at least ${ALARM_MINIMUM_SENDS} sends): pauses ${config.siteId} newsletter sending`,
267
+ metric: rate,
268
+ threshold,
269
+ evaluationPeriods: 1,
270
+ comparisonOperator: ComparisonOperator.GREATER_THAN_THRESHOLD,
271
+ treatMissingData: TreatMissingData.NOT_BREACHING,
272
+ });
273
+ alarm.addAlarmAction(new SnsAction(alarmTopic));
274
+ }
275
+
276
+ // The publish path tells this function about a real publish. The ARN is spelled out (not referenced) so the content-actions
277
+ // stack does not depend on this one, and the grant is for this one function only.
278
+ const contentActions = context.contentActionsLambda;
279
+ contentActions.addEnvironment(NEWSLETTER_FUNCTION_ENV, newsletterFunctionName(config.siteId));
280
+ contentActions.addToRolePolicy(
281
+ new PolicyStatement({
282
+ effect: Effect.ALLOW,
283
+ actions: ["lambda:InvokeFunction"],
284
+ resources: [functionArn(Stack.of(contentActions), newsletterFunctionName(config.siteId))],
285
+ }),
286
+ );
287
+
288
+ lambda.addPermission("InvokeFromCmsCompute", {
289
+ principal: new ArnPrincipal(config.computeRoleArn),
290
+ action: "lambda:InvokeFunction",
291
+ });
292
+
293
+ backend.addOutput({ custom: { [NEWSLETTER_OUTPUT_KEY]: { actionsFunction: lambda.functionName } } });
294
+ },
295
+ };
296
+
297
+ function installRequirements(requirementsPath: string, outputDir: string): void {
298
+ // Same wheels and platform as the other Python functions: a Lambda on arm64 with CPython 3.12.
299
+ execFileSync(
300
+ "python3",
301
+ [
302
+ "-m", "pip", "install", "-r", requirementsPath, "-t", outputDir, "--no-cache-dir",
303
+ "--platform", "manylinux2014_aarch64", "--implementation", "cp", "--python-version", "3.12",
304
+ "--only-binary=:all:", "--ignore-requires-python",
305
+ ],
306
+ { stdio: "inherit" },
307
+ );
308
+ }
@@ -0,0 +1,56 @@
1
+ import { a } from "@aws-amplify/backend";
2
+ import { newsletterOps } from "./ops/resource.js";
3
+ const staff = ["editor", "admin"];
4
+ const admins = ["admin"];
5
+ /** The newsroom's newsletter operations, all JSON in and out. The function checks the groups again from the identity claims. */
6
+ export const NEWSLETTER_QUERIES = [
7
+ "newsletterIssues",
8
+ "newsletterIssue",
9
+ "newsletterPreview",
10
+ "newsletterOverview",
11
+ "newsletterIssueDeliveries",
12
+ "newsletterSubscribers",
13
+ "newsletterExport",
14
+ ];
15
+ export const NEWSLETTER_MUTATIONS = [
16
+ "newsletterApproveIssue",
17
+ "newsletterCancelIssue",
18
+ "newsletterStopIssue",
19
+ "newsletterTestSend",
20
+ "newsletterCreateDraft",
21
+ "newsletterErase",
22
+ "newsletterResume",
23
+ ];
24
+ /**
25
+ * Who AppSync admits to each operation. Approve, cancel, stop, the subscriber list, the export, erasure and resume are admin
26
+ * only; everything else (counts, issues, preview, test send, new draft, delivery history with masked addresses) is editors and admins.
27
+ */
28
+ export const NEWSLETTER_OPERATION_GROUPS = {
29
+ newsletterIssues: staff,
30
+ newsletterIssue: staff,
31
+ newsletterPreview: staff,
32
+ newsletterTestSend: staff,
33
+ newsletterCreateDraft: staff,
34
+ newsletterApproveIssue: admins,
35
+ newsletterCancelIssue: admins,
36
+ newsletterStopIssue: admins,
37
+ newsletterOverview: staff,
38
+ newsletterIssueDeliveries: staff,
39
+ newsletterSubscribers: admins,
40
+ newsletterExport: admins,
41
+ newsletterErase: admins,
42
+ newsletterResume: admins,
43
+ };
44
+ /**
45
+ * The newsletter plugin adds no GraphQL model: subscriber records are personal data kept in the plugin's own DynamoDB
46
+ * table, never readable through the content API. It adds fourteen operations for the newsroom's Newsletter panel.
47
+ */
48
+ export function newsletterSchemaDefinitions() {
49
+ const handler = a.handler.function(newsletterOps);
50
+ const query = (name) => a.query().arguments({ input: a.json() }).returns(a.json()).authorization((allow) => [allow.groups(NEWSLETTER_OPERATION_GROUPS[name])]).handler(handler);
51
+ const mutation = (name) => a.mutation().arguments({ input: a.json() }).returns(a.json()).authorization((allow) => [allow.groups(NEWSLETTER_OPERATION_GROUPS[name])]).handler(handler);
52
+ return {
53
+ ...Object.fromEntries(NEWSLETTER_QUERIES.map((name) => [name, query(name)])),
54
+ ...Object.fromEntries(NEWSLETTER_MUTATIONS.map((name) => [name, mutation(name)])),
55
+ };
56
+ }