@anthusai/papyrus 5.110.0 → 5.112.0-next.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 (92) hide show
  1. package/amplify/auth/resource.js +3 -0
  2. package/amplify/auth/resource.ts +3 -0
  3. package/amplify/auth/tenant-session-claims.js +27 -0
  4. package/amplify/auth/tenant-session-claims.ts +31 -0
  5. package/amplify/cost-attribution.js +12 -0
  6. package/amplify/cost-attribution.ts +12 -0
  7. package/amplify/data/resource.js +79 -0
  8. package/amplify/data/resource.ts +82 -0
  9. package/amplify/data/schema.js +82 -1
  10. package/amplify/data/schema.ts +85 -1
  11. package/amplify/functions/assignment-action/handler.ts +14 -9
  12. package/amplify/functions/automation-view/wire.js +2 -1
  13. package/amplify/functions/automation-view/wire.ts +2 -1
  14. package/amplify/functions/category-action/handler.ts +24 -18
  15. package/amplify/functions/category-action/message-hashtags.js +2 -1
  16. package/amplify/functions/category-action/message-hashtags.ts +2 -1
  17. package/amplify/functions/category-action/reference-links.js +3 -2
  18. package/amplify/functions/category-action/reference-links.ts +3 -2
  19. package/amplify/functions/console-chat-responder/resource.js +2 -1
  20. package/amplify/functions/console-chat-responder/resource.ts +2 -1
  21. package/amplify/functions/content-actions/handler.py +54 -22
  22. package/amplify/functions/content-actions/resource.js +4 -0
  23. package/amplify/functions/content-actions/resource.ts +5 -0
  24. package/amplify/functions/editorial-checks/handler.py +5 -1
  25. package/amplify/functions/editorial-checks/schema.js +10 -2
  26. package/amplify/functions/editorial-checks/schema.ts +10 -2
  27. package/amplify/functions/editorial-checks/wire.js +2 -1
  28. package/amplify/functions/editorial-checks/wire.ts +2 -1
  29. package/amplify/functions/image-service/wire.js +2 -1
  30. package/amplify/functions/image-service/wire.ts +2 -1
  31. package/amplify/functions/monitoring-view/wire.js +2 -1
  32. package/amplify/functions/monitoring-view/wire.ts +2 -1
  33. package/amplify/functions/newsroom-summary/handler.ts +16 -12
  34. package/amplify/functions/shared/tenant-context.js +98 -0
  35. package/amplify/functions/shared/tenant-context.ts +33 -0
  36. package/amplify/functions/shared/tenant-scoped-client.ts +80 -0
  37. package/amplify/functions/tenant-claims/claims.ts +90 -0
  38. package/amplify/functions/tenant-claims/environment.js +7 -0
  39. package/amplify/functions/tenant-claims/environment.ts +7 -0
  40. package/amplify/functions/tenant-claims/handler.ts +56 -0
  41. package/amplify/functions/tenant-claims/resource.js +12 -0
  42. package/amplify/functions/tenant-claims/resource.ts +13 -0
  43. package/amplify/plugins/newsletter/sending.js +2 -1
  44. package/amplify/plugins/newsletter/sending.ts +2 -1
  45. package/amplify/plugins/notifications/papyrus.plugin.js +2 -1
  46. package/amplify/plugins/notifications/papyrus.plugin.ts +2 -1
  47. package/amplify/plugins/reader-steering/schema.js +15 -3
  48. package/amplify/plugins/reader-steering/schema.ts +15 -3
  49. package/amplify/plugins/signup/papyrus.plugin.js +2 -1
  50. package/amplify/plugins/signup/papyrus.plugin.ts +2 -1
  51. package/amplify/plugins/signup/schema.js +1 -0
  52. package/amplify/plugins/signup/schema.ts +1 -0
  53. package/amplify/shared-stack/alarms.js +53 -0
  54. package/amplify/shared-stack/alarms.ts +109 -0
  55. package/amplify/shared-stack/define.js +15 -0
  56. package/amplify/shared-stack/define.ts +17 -0
  57. package/amplify/shared-stack/deny.js +27 -0
  58. package/amplify/shared-stack/deny.ts +28 -0
  59. package/amplify/shared-stack/inline-policy.js +53 -0
  60. package/amplify/shared-stack/inline-policy.ts +65 -0
  61. package/amplify/shared-stack/isolation.js +161 -0
  62. package/amplify/shared-stack/isolation.ts +204 -0
  63. package/amplify/shared-stack/names.js +95 -0
  64. package/amplify/shared-stack/names.ts +133 -0
  65. package/amplify/shared-stack/settings.js +70 -0
  66. package/amplify/shared-stack/settings.ts +95 -0
  67. package/amplify/site-api-access.js +13 -0
  68. package/amplify/site-api-access.ts +14 -0
  69. package/amplify/site-backend-config.js +7 -1
  70. package/amplify/site-backend-config.ts +8 -2
  71. package/amplify/site-backend.js +65 -13
  72. package/amplify/site-backend.ts +75 -19
  73. package/components/news-desk-taxonomy-client.ts +5 -0
  74. package/components/newsroom-article-editor.tsx +7 -3
  75. package/components/newsroom-board-view.tsx +4 -2
  76. package/components/newsroom-organizer.css +2 -2
  77. package/components/use-newsroom-desk-sections.ts +31 -0
  78. package/infra/amplify-app-shell.js +4 -1
  79. package/infra/amplify-app-shell.ts +4 -1
  80. package/infra/build-specs.js +4 -1
  81. package/infra/build-specs.ts +5 -1
  82. package/infra/cost-tags.test.js +1 -1
  83. package/infra/cost-tags.test.ts +1 -1
  84. package/infra/shared-stack-deny.js +80 -0
  85. package/infra/shared-stack-deny.test.js +56 -0
  86. package/infra/shared-stack-deny.test.ts +66 -0
  87. package/infra/shared-stack-deny.ts +86 -0
  88. package/lib/newsroom-sections.ts +14 -0
  89. package/lib/tenant-keys.js +16 -0
  90. package/lib/tenant-keys.ts +19 -0
  91. package/package.json +2 -1
  92. package/routes.manifest.json +1 -1
@@ -30,6 +30,7 @@ export const editorialChecksSchemaDefinitions = {
30
30
  source: a.string().required(),
31
31
  })
32
32
  .disableOperations(["subscriptions"])
33
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).queryField("listEditorialPoliciesByTenant")])
33
34
  .authorization((allow) => [allow.group("editor").to(["read"]), allow.group("admin")]),
34
35
  EditorialCheckSettings: a
35
36
  .model({
@@ -38,6 +39,7 @@ export const editorialChecksSchemaDefinitions = {
38
39
  settings: a.json().required(),
39
40
  })
40
41
  .disableOperations(["subscriptions"])
42
+ .secondaryIndexes((index) => [index("tenantId").sortKeys(["id"]).queryField("listEditorialCheckSettingsByTenant")])
41
43
  .authorization((allow) => [allow.group("editor").to(["read"]), allow.group("admin")]),
42
44
  EditorialFeedback: a
43
45
  .model({
@@ -54,7 +56,10 @@ export const editorialChecksSchemaDefinitions = {
54
56
  text: a.string(),
55
57
  })
56
58
  .disableOperations(["subscriptions"])
57
- .secondaryIndexes((index) => [index("itemId").queryField("listEditorialFeedbackByItem")])
59
+ .secondaryIndexes((index) => [
60
+ index("itemId").queryField("listEditorialFeedbackByItem"),
61
+ index("tenantId").sortKeys(["id"]).queryField("listEditorialFeedbackByTenant"),
62
+ ])
58
63
  .authorization((allow) => [allow.group("editor").to(["create", "read"]), allow.group("admin")]),
59
64
  EditorialCheckRun: a
60
65
  .model({
@@ -73,7 +78,10 @@ export const editorialChecksSchemaDefinitions = {
73
78
  checkedAt: a.datetime().required(),
74
79
  })
75
80
  .disableOperations(["subscriptions"])
76
- .secondaryIndexes((index) => [index("lineageId").sortKeys(["versionNumber"]).queryField("listEditorialCheckRunsByLineage")])
81
+ .secondaryIndexes((index) => [
82
+ index("lineageId").sortKeys(["versionNumber"]).queryField("listEditorialCheckRunsByLineage"),
83
+ index("tenantId").sortKeys(["id"]).queryField("listEditorialCheckRunsByTenant"),
84
+ ])
77
85
  .authorization((allow) => [allow.group("editor").to(["read"]), allow.group("admin")]),
78
86
  listEditorialStarterPacks: a
79
87
  .query()
@@ -1,6 +1,7 @@
1
1
  import { secret } from "@aws-amplify/backend";
2
2
  import { Stack } from "aws-cdk-lib";
3
3
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
4
+ import { connectToSiteApi } from "../../site-api-access.js";
4
5
  /** The model operations the function performs with its own role. The two context reads are its least-privilege access to private policy. */
5
6
  export const EDITORIAL_CHECKS_FUNCTION_FIELDS = [
6
7
  "Query/fields/listKnowledgeCorporaByRoleAndName",
@@ -40,7 +41,7 @@ export function editorialChecksSecretParameters(region, account, appId) {
40
41
  export function wireEditorialChecks(backend) {
41
42
  const lambda = backend.editorialChecks.resources.lambda;
42
43
  const stack = Stack.of(lambda);
43
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
44
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
44
45
  for (const name of EDITORIAL_CHECKS_SECRETS)
45
46
  backend.editorialChecks.addEnvironment(name, secret(name));
46
47
  lambda.addToRolePolicy(new PolicyStatement({
@@ -2,6 +2,7 @@ import { secret } from "@aws-amplify/backend";
2
2
  import { Stack } from "aws-cdk-lib";
3
3
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
4
4
  import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
5
+ import { connectToSiteApi } from "../../site-api-access";
5
6
 
6
7
  /** The model operations the function performs with its own role. The two context reads are its least-privilege access to private policy. */
7
8
  export const EDITORIAL_CHECKS_FUNCTION_FIELDS = [
@@ -45,7 +46,7 @@ export function editorialChecksSecretParameters(region: string, account: string,
45
46
  export function wireEditorialChecks(backend: any): void {
46
47
  const lambda = backend.editorialChecks.resources.lambda as LambdaFunction;
47
48
  const stack = Stack.of(lambda);
48
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
49
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
49
50
  for (const name of EDITORIAL_CHECKS_SECRETS) backend.editorialChecks.addEnvironment(name, secret(name));
50
51
  lambda.addToRolePolicy(
51
52
  new PolicyStatement({
@@ -1,4 +1,5 @@
1
1
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
2
+ import { connectToSiteApi } from "../../site-api-access.js";
2
3
  /**
3
4
  * What the function reads and writes with its own role, through the site's own API (`allow.resource(imageService)` in the schema grants query and
4
5
  * mutate; the function calls no other service). Today: the doctrine and Story `Item` records it reads by index and the new profile version it writes,
@@ -25,7 +26,7 @@ export const IMAGE_SERVICE_BUCKET_ACTIONS = ["s3:GetObject", "s3:PutObject"];
25
26
  /** The function's environment: the site's own API. It holds no secret and calls no provider in this step. */
26
27
  export function wireImageService(backend) {
27
28
  const lambda = backend.imageService.resources.lambda;
28
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
29
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
29
30
  // Read and write of the guideline documents, on the payload prefix of Item versions only (the role, not a bucket policy, as the other functions do it,
30
31
  // so the storage and data stacks do not depend on each other).
31
32
  const bucket = backend.storage.resources.bucket;
@@ -1,5 +1,6 @@
1
1
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
2
2
  import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
3
+ import { connectToSiteApi } from "../../site-api-access";
3
4
 
4
5
  /**
5
6
  * What the function reads and writes with its own role, through the site's own API (`allow.resource(imageService)` in the schema grants query and
@@ -29,7 +30,7 @@ export const IMAGE_SERVICE_BUCKET_ACTIONS = ["s3:GetObject", "s3:PutObject"];
29
30
  /** The function's environment: the site's own API. It holds no secret and calls no provider in this step. */
30
31
  export function wireImageService(backend: any): void {
31
32
  const lambda = backend.imageService.resources.lambda as LambdaFunction;
32
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
34
  // Read and write of the guideline documents, on the payload prefix of Item versions only (the role, not a bucket policy, as the other functions do it,
34
35
  // so the storage and data stacks do not depend on each other).
35
36
  const bucket = backend.storage.resources.bucket;
@@ -1,5 +1,6 @@
1
1
  import { Stack } from "aws-cdk-lib";
2
2
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
3
+ import { connectToSiteApi } from "../../site-api-access.js";
3
4
  /** The monitoring stack writes the table's name here (infra/monitoring/papyrus-monitoring.yaml). */
4
5
  export const MONITORING_TABLE_PARAMETER = "/papyrus/monitoring/table-name";
5
6
  /** Reads only: a single item or a key-range query. No Scan, no writes, no other table. */
@@ -23,7 +24,7 @@ export function wireMonitoringView(backend, emailMonitorId = "hn") {
23
24
  const lambda = backend.monitoringView.resources.lambda;
24
25
  const stack = Stack.of(lambda);
25
26
  lambda.addEnvironment("PAPYRUS_USER_POOL_ISSUER", `https://cognito-idp.${stack.region}.amazonaws.com/${backend.auth.resources.userPool.userPoolId}`);
26
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
27
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
27
28
  lambda.addEnvironment("PAPYRUS_MONITORING_TABLE_PARAMETER", MONITORING_TABLE_PARAMETER);
28
29
  lambda.addEnvironment("PAPYRUS_EMAIL_MONITOR_ID", emailMonitorId);
29
30
  lambda.addToRolePolicy(new PolicyStatement({
@@ -1,6 +1,7 @@
1
1
  import { Stack } from "aws-cdk-lib";
2
2
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
3
3
  import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
4
+ import { connectToSiteApi } from "../../site-api-access";
4
5
 
5
6
  /** The monitoring stack writes the table's name here (infra/monitoring/papyrus-monitoring.yaml). */
6
7
  export const MONITORING_TABLE_PARAMETER = "/papyrus/monitoring/table-name";
@@ -29,7 +30,7 @@ export function wireMonitoringView(backend: any, emailMonitorId = "hn"): void {
29
30
  const lambda = backend.monitoringView.resources.lambda as LambdaFunction;
30
31
  const stack = Stack.of(lambda);
31
32
  lambda.addEnvironment("PAPYRUS_USER_POOL_ISSUER", `https://cognito-idp.${stack.region}.amazonaws.com/${backend.auth.resources.userPool.userPoolId}`);
32
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
34
  lambda.addEnvironment("PAPYRUS_MONITORING_TABLE_PARAMETER", MONITORING_TABLE_PARAMETER);
34
35
  lambda.addEnvironment("PAPYRUS_EMAIL_MONITOR_ID", emailMonitorId);
35
36
  lambda.addToRolePolicy(
@@ -2,12 +2,13 @@ import { getAmplifyDataClientConfig } from "@aws-amplify/backend/function/runtim
2
2
  import { Amplify } from "aws-amplify";
3
3
  import { generateClient } from "aws-amplify/data";
4
4
  import type { Schema } from "../../data/resource";
5
+ import { actingFor, buildEventTenantContext, currentTenantContext } from "../shared/tenant-context";
6
+ import { newsroomSummaryPayloadId, tenantScopedClient } from "../shared/tenant-scoped-client";
5
7
  import { putJsonModelPayload, readJsonModelPayload } from "../shared/model-payloads";
6
8
 
7
9
  type DataClient = ReturnType<typeof generateClient<Schema>>;
8
10
  type DataClientErrors = Array<{ message?: string | null } | string | null> | null | undefined;
9
11
 
10
- const NEWSROOM_SUMMARY_PAYLOAD_ID = "knowledge-raw-payload-newsroom-summary-current";
11
12
  const NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND = "knowledgeRawPayload";
12
13
  const SUMMARY_STALE_AFTER_MS = 15 * 60 * 1000;
13
14
  let clientPromise: Promise<DataClient> | null = null;
@@ -15,16 +16,19 @@ let clientPromise: Promise<DataClient> | null = null;
15
16
  export const handler = async (
16
17
  event: Parameters<Schema["getNewsroomSummary"]["functionHandler"]>[0] | Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0],
17
18
  ) => {
18
- const fieldName = typeof event.info?.fieldName === "string" ? event.info.fieldName : "getNewsroomSummary";
19
- if (fieldName === "updateNewsroomSummary" || "delta" in event.arguments) {
20
- return updateNewsroomSummary(event as Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0]);
21
- }
22
- return getNewsroomSummary();
19
+ const context = buildEventTenantContext(event); // one context per call; a shared stack refuses before any read
20
+ return actingFor(context, () => {
21
+ const fieldName = typeof event.info?.fieldName === "string" ? event.info.fieldName : "getNewsroomSummary";
22
+ if (fieldName === "updateNewsroomSummary" || "delta" in event.arguments) {
23
+ return updateNewsroomSummary(event as Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0]);
24
+ }
25
+ return getNewsroomSummary();
26
+ });
23
27
  };
24
28
 
25
29
  async function getNewsroomSummary() {
26
30
  const client = await getDataClient();
27
- const response = await client.models.KnowledgeRawPayload.get({ id: NEWSROOM_SUMMARY_PAYLOAD_ID });
31
+ const response = await client.models.KnowledgeRawPayload.get({ id: newsroomSummaryPayloadId(currentTenantContext()) });
28
32
  assertNoDataErrors(response.errors, "get Newsroom summary snapshot");
29
33
  const payload = await readNewsroomSummaryPayload(client);
30
34
  return summaryFromPayload(normalizeSummaryPayload(payload, response.data?.updatedAt ?? new Date().toISOString()));
@@ -33,7 +37,7 @@ async function getNewsroomSummary() {
33
37
  async function updateNewsroomSummary(event: Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0]) {
34
38
  const client = await getDataClient();
35
39
  const now = new Date().toISOString();
36
- const response = await client.models.KnowledgeRawPayload.get({ id: NEWSROOM_SUMMARY_PAYLOAD_ID });
40
+ const response = await client.models.KnowledgeRawPayload.get({ id: newsroomSummaryPayloadId(currentTenantContext()) });
37
41
  assertNoDataErrors(response.errors, "get Newsroom summary snapshot");
38
42
  const currentPayload = normalizeSummaryPayload(await readNewsroomSummaryPayload(client), now);
39
43
  const delta = parseJsonObject(event.arguments.delta);
@@ -54,7 +58,7 @@ async function getDataClient(): Promise<DataClient> {
54
58
  return generateClient<Schema>();
55
59
  })();
56
60
  }
57
- return clientPromise;
61
+ return tenantScopedClient(await clientPromise, currentTenantContext());
58
62
  }
59
63
 
60
64
  async function upsertNewsroomSummaryPayload(
@@ -64,7 +68,7 @@ async function upsertNewsroomSummaryPayload(
64
68
  now: string,
65
69
  ): Promise<void> {
66
70
  const input = {
67
- id: NEWSROOM_SUMMARY_PAYLOAD_ID,
71
+ id: newsroomSummaryPayloadId(currentTenantContext()),
68
72
  ownerType: "newsroom",
69
73
  ownerId: "newsroom",
70
74
  payloadKind: "summary-snapshot",
@@ -79,7 +83,7 @@ async function upsertNewsroomSummaryPayload(
79
83
  }
80
84
  await putJsonModelPayload(
81
85
  client as any,
82
- { ownerKind: NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND, ownerId: NEWSROOM_SUMMARY_PAYLOAD_ID, importRunId: input.importRunId },
86
+ { ownerKind: NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND, ownerId: newsroomSummaryPayloadId(currentTenantContext()), importRunId: input.importRunId },
83
87
  "raw_payload",
84
88
  "summary-snapshot",
85
89
  payload,
@@ -91,7 +95,7 @@ async function readNewsroomSummaryPayload(client: DataClient): Promise<Record<st
91
95
  return readJsonModelPayload(
92
96
  client as any,
93
97
  NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND,
94
- NEWSROOM_SUMMARY_PAYLOAD_ID,
98
+ newsroomSummaryPayloadId(currentTenantContext()),
95
99
  "raw_payload",
96
100
  "summary-snapshot",
97
101
  );
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The tenant a function call acts for, built once from an AppSync resolver event's identity.
3
+ * A signed-in caller carries one tenant in its token claims (docs/plans/tenant-claims-spike-1.md); an IAM caller names it
4
+ * explicitly. A shared stack refuses a call that cannot name exactly one tenant; a dedicated stack acts for its fixed
5
+ * site tenant. The tenant never comes from the request body and is never guessed.
6
+ * Python twin: src/papyrus_content/tenant_context.py; both read features_backend/fixtures/tenant-context/vectors.json.
7
+ */
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { isSharedStack, tenantIdFromEnvironment, validateTenantId } from "../../../lib/tenant-keys.js";
10
+ export const ROLE_CLAIMS = [
11
+ ["admin", "papyrus_tenant_admin"],
12
+ ["editor", "papyrus_tenant_editor"],
13
+ ["curator", "papyrus_tenant_curator"],
14
+ ["member", "papyrus_tenant_member"],
15
+ ];
16
+ export class TenantContextRefusal extends Error {
17
+ reason;
18
+ constructor(reason, message) {
19
+ super(message);
20
+ this.reason = reason;
21
+ this.name = "TenantContextRefusal";
22
+ }
23
+ }
24
+ function checked(tenantId) {
25
+ if (typeof tenantId !== "string")
26
+ throw new TenantContextRefusal("invalid_tenant", "A tenant id must be a string.");
27
+ try {
28
+ return validateTenantId(tenantId);
29
+ }
30
+ catch (error) {
31
+ throw new TenantContextRefusal("invalid_tenant", error.message);
32
+ }
33
+ }
34
+ function claimed(claims) {
35
+ const named = ROLE_CLAIMS.filter(([, claim]) => claims[claim] !== undefined && claims[claim] !== null && claims[claim] !== "");
36
+ const tenants = new Set(named.map(([, claim]) => checked(claims[claim])));
37
+ if (tenants.size > 1) {
38
+ throw new TenantContextRefusal("multiple_tenants", "The claims name more than one tenant; a session acts for one tenant at a time.");
39
+ }
40
+ return { tenant: [...tenants][0] ?? null, roles: named.map(([role]) => role) };
41
+ }
42
+ function isRecord(value) {
43
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44
+ }
45
+ export function buildTenantContext(identity, options = {}) {
46
+ const environment = options.environment ?? process.env;
47
+ const explicitTenant = options.explicitTenant ?? null;
48
+ const isUser = isRecord(identity) && isRecord(identity.claims);
49
+ const isIam = isRecord(identity) && !isUser && ("userArn" in identity || "accountId" in identity);
50
+ if (!isUser && !isIam) {
51
+ throw new TenantContextRefusal("unsupported_identity", "The call carries neither a user pool identity nor an IAM identity.");
52
+ }
53
+ const shared = isSharedStack(environment);
54
+ const mode = shared ? "shared" : "dedicated";
55
+ if (isUser && explicitTenant !== null) {
56
+ throw new TenantContextRefusal("explicit_tenant_for_user", "A signed-in caller's tenant comes from its claims, never from an argument.");
57
+ }
58
+ if (isIam && shared && !explicitTenant) {
59
+ throw new TenantContextRefusal("iam_without_tenant", "An IAM call on a shared stack must name its tenant.");
60
+ }
61
+ const { tenant, roles } = isUser ? claimed(identity.claims) : { tenant: null, roles: [] };
62
+ const requested = isIam && explicitTenant ? checked(explicitTenant) : tenant;
63
+ if (shared) {
64
+ if (requested === null)
65
+ throw new TenantContextRefusal("no_tenant_claim", "The caller's token carries no tenant claim.");
66
+ return { tenantId: requested, roles, mode, operator: isIam };
67
+ }
68
+ const fixed = tenantIdFromEnvironment(environment) ?? null;
69
+ if (requested !== null && requested !== fixed) {
70
+ throw new TenantContextRefusal("foreign_tenant", "The call names a tenant other than this stack's fixed tenant.");
71
+ }
72
+ return { tenantId: fixed, roles, mode, operator: isIam };
73
+ }
74
+ export function isIamIdentity(identity) {
75
+ return isRecord(identity) && !isRecord(identity.claims) && ("userArn" in identity || "accountId" in identity);
76
+ }
77
+ /**
78
+ * The one context of an AppSync field event. A signed-in caller's tenant is its role claim and nothing in the arguments is read for it. An IAM
79
+ * caller (the platform operator or a worker) names the tenant as the `tenantId` argument; an operation without that argument cannot be called by
80
+ * IAM on a shared stack, which refuses it before any read.
81
+ */
82
+ export function buildEventTenantContext(event, environment = process.env) {
83
+ const identity = event.identity;
84
+ const named = isIamIdentity(identity) ? event.arguments?.tenantId : undefined;
85
+ return buildTenantContext(identity, { explicitTenant: (named ?? null), environment });
86
+ }
87
+ const acting = new AsyncLocalStorage();
88
+ /** Run one call for `context`: everything it awaits reads the tenant from `currentTenantContext()`, never from the environment. */
89
+ export function actingFor(context, call) {
90
+ return acting.run(context, call);
91
+ }
92
+ export function currentTenantContext() {
93
+ const context = acting.getStore();
94
+ if (!context) {
95
+ throw new TenantContextRefusal("unsupported_identity", "No tenant context: a handler builds one from the event before it reads or writes anything.");
96
+ }
97
+ return context;
98
+ }
@@ -5,6 +5,7 @@
5
5
  * site tenant. The tenant never comes from the request body and is never guessed.
6
6
  * Python twin: src/papyrus_content/tenant_context.py; both read features_backend/fixtures/tenant-context/vectors.json.
7
7
  */
8
+ import { AsyncLocalStorage } from "node:async_hooks";
8
9
  import { isSharedStack, tenantIdFromEnvironment, validateTenantId } from "../../../lib/tenant-keys";
9
10
 
10
11
  export const ROLE_CLAIMS = [
@@ -97,3 +98,35 @@ export function buildTenantContext(identity: Identity, options: TenantContextOpt
97
98
  }
98
99
  return { tenantId: fixed, roles, mode, operator: isIam };
99
100
  }
101
+
102
+ export function isIamIdentity(identity: Identity): boolean {
103
+ return isRecord(identity) && !isRecord(identity.claims) && ("userArn" in identity || "accountId" in identity);
104
+ }
105
+
106
+ type FieldEvent = { identity?: unknown; arguments?: Record<string, unknown> | null };
107
+
108
+ /**
109
+ * The one context of an AppSync field event. A signed-in caller's tenant is its role claim and nothing in the arguments is read for it. An IAM
110
+ * caller (the platform operator or a worker) names the tenant as the `tenantId` argument; an operation without that argument cannot be called by
111
+ * IAM on a shared stack, which refuses it before any read.
112
+ */
113
+ export function buildEventTenantContext(event: FieldEvent, environment: Record<string, string | undefined> = process.env): TenantContext {
114
+ const identity = event.identity as Identity;
115
+ const named = isIamIdentity(identity) ? event.arguments?.tenantId : undefined;
116
+ return buildTenantContext(identity, { explicitTenant: (named ?? null) as string | null, environment });
117
+ }
118
+
119
+ const acting = new AsyncLocalStorage<TenantContext>();
120
+
121
+ /** Run one call for `context`: everything it awaits reads the tenant from `currentTenantContext()`, never from the environment. */
122
+ export function actingFor<T>(context: TenantContext, call: () => T): T {
123
+ return acting.run(context, call);
124
+ }
125
+
126
+ export function currentTenantContext(): TenantContext {
127
+ const context = acting.getStore();
128
+ if (!context) {
129
+ throw new TenantContextRefusal("unsupported_identity", "No tenant context: a handler builds one from the event before it reads or writes anything.");
130
+ }
131
+ return context;
132
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The Amplify data client of one call, scoped to the tenant its context names (TypeScript twin of PapyrusGraphQLAuthoringClient(tenant_id=...)).
3
+ * On a SHARED stack every model that carries a `tenantId` answers only with the caller's tenant's rows: a `get` of another tenant's id returns
4
+ * nothing (so the handler says "not found"), an index query or list drops foreign rows, a create is stamped with the caller's tenant (a payload that
5
+ * names another is refused), and an update or delete first reads the row and refuses one that is not the caller's. On a DEDICATED stack the client
6
+ * is returned as it is: its single tenant is the whole backend.
7
+ */
8
+ import { TENANT_FIELD_MODELS, TENANT_MODELS, tenantScopedValue } from "../../../lib/tenant-keys";
9
+ import type { TenantContext } from "./tenant-context";
10
+
11
+ type Row = Record<string, any>;
12
+ type Result = { data?: Row | Row[] | null; errors?: unknown; nextToken?: string | null };
13
+ type Model = Record<string, (...args: any[]) => Promise<Result>>;
14
+ type ScopableClient = { models: Record<string, any> };
15
+
16
+ const MUTATORS = new Set(["create", "update", "delete"]);
17
+
18
+ function belongs(tenantId: string, row: Row | null | undefined): boolean {
19
+ return !row || row.tenantId === tenantId;
20
+ }
21
+
22
+ function scopedModel(name: string, model: Model, tenantId: string): Model {
23
+ return new Proxy(model, {
24
+ get(target, member: string) {
25
+ const operation = target[member];
26
+ if (typeof operation !== "function") return operation;
27
+ if (member === "get") {
28
+ return async (...args: any[]): Promise<Result> => {
29
+ const result = await operation.apply(target, args);
30
+ return !result.data || Array.isArray(result.data) || belongs(tenantId, result.data) ? result : { ...result, data: null };
31
+ };
32
+ }
33
+ if (member === "create") {
34
+ return async (input: Row, ...rest: any[]): Promise<Result> => {
35
+ if (input.tenantId !== undefined && input.tenantId !== null && input.tenantId !== tenantId) {
36
+ throw new Error(`${name} cannot be created for another tenant.`);
37
+ }
38
+ return operation.call(target, { ...input, tenantId }, ...rest);
39
+ };
40
+ }
41
+ if (MUTATORS.has(member)) {
42
+ return async (input: Row, ...rest: any[]): Promise<Result> => {
43
+ const current = await target.get({ id: input.id });
44
+ if (!current.data || Array.isArray(current.data) || !belongs(tenantId, current.data)) throw new Error(`${name} ${input.id} was not found.`);
45
+ if (input.tenantId !== undefined && input.tenantId !== null && input.tenantId !== tenantId) throw new Error(`${name} cannot move to another tenant.`);
46
+ return operation.call(target, input, ...rest);
47
+ };
48
+ }
49
+ return async (...args: any[]): Promise<Result> => {
50
+ const result = await operation.apply(target, args);
51
+ return Array.isArray(result.data) ? { ...result, data: result.data.filter((row) => belongs(tenantId, row)) } : result;
52
+ };
53
+ },
54
+ });
55
+ }
56
+
57
+ export function tenantScopedClient<Client extends ScopableClient>(client: Client, context: TenantContext): Client {
58
+ if (context.mode !== "shared") return client;
59
+ const tenantId = context.tenantId;
60
+ if (!tenantId) throw new Error("A shared stack's call has a tenant before it has a client.");
61
+ const models = new Proxy(client.models, {
62
+ get(target, name: string) {
63
+ const model = target[name];
64
+ return TENANT_MODELS.has(name) || TENANT_FIELD_MODELS.has(name) ? scopedModel(name, model, tenantId) : model;
65
+ },
66
+ });
67
+ return { ...client, models } as Client;
68
+ }
69
+
70
+ /** A record id that is the same for every tenant today (a singleton such as the Newsroom summary), as this stack stores it. */
71
+ export function scopedRecordId(context: TenantContext, id: string): string {
72
+ return context.mode === "shared" && context.tenantId ? tenantScopedValue(context.tenantId, id) : id;
73
+ }
74
+
75
+ const NEWSROOM_SUMMARY_BASE_ID = "knowledge-raw-payload-newsroom-summary-current";
76
+
77
+ /** The id of the call's tenant's Newsroom summary snapshot: the one record id every tenant would otherwise share. */
78
+ export function newsroomSummaryPayloadId(context: TenantContext): string {
79
+ return scopedRecordId(context, NEWSROOM_SUMMARY_BASE_ID);
80
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The tenant claims a session token carries (PPY-0bb0fd, docs/multi-tenancy.md "Session claims").
3
+ *
4
+ * One claim per role the person holds on the one tenant the session acts for, each holding the tenant id. The role names and
5
+ * claim names are the ones `shared/tenant-context.ts` reads, so a token built here is exactly what that builder accepts.
6
+ */
7
+ import { isSharedStack, tenantIdFromEnvironment, validateTenantId } from "../../../lib/tenant-keys";
8
+ import { TENANCY_MODELS_ENVIRONMENT_VARIABLE } from "./environment";
9
+ import { ROLE_CLAIMS, type TenantRole } from "../shared/tenant-context";
10
+
11
+ /** A membership counts only while its status is this value (src/papyrus_content/tenant_records.py). */
12
+ export const ACTIVE_MEMBERSHIP_STATUS = "active";
13
+
14
+ /** The Cognito groups a dedicated stack maps to a role claim; there is no group for `member`. */
15
+ const GROUP_ROLES: readonly TenantRole[] = ["admin", "editor", "curator"];
16
+
17
+ export type Row = Record<string, unknown>;
18
+ export type TenancyModel = "TenantMembership" | "TenantSelection";
19
+ /** Reads one row of a tenancy model by its id (a GetItem), or null when there is none. */
20
+ export type ItemReader = (model: TenancyModel, id: string) => Promise<Row | null>;
21
+
22
+ export type ClaimEnvironment = {
23
+ shared: boolean;
24
+ /** A dedicated stack's fixed tenant; null when it has none, and always null on a shared stack. */
25
+ fixedTenantId: string | null;
26
+ /** Whether the TenantMembership and TenantSelection models are deployed on this stack. */
27
+ tenancyModels: boolean;
28
+ };
29
+
30
+ export function claimEnvironment(environment: Record<string, string | undefined>): ClaimEnvironment {
31
+ const shared = isSharedStack(environment);
32
+ return {
33
+ shared,
34
+ fixedTenantId: shared ? null : tenantIdFromEnvironment(environment) ?? null,
35
+ tenancyModels: environment[TENANCY_MODELS_ENVIRONMENT_VARIABLE]?.trim() === "true",
36
+ };
37
+ }
38
+
39
+ function validTenantId(value: unknown): string | null {
40
+ if (typeof value !== "string") return null;
41
+ try {
42
+ return validateTenantId(value);
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /** The role an active membership row of this person and tenant grants, or null. The row's own fields must agree with the key. */
49
+ export function membershipRole(row: Row | null, tenantId: string, userSub: string): TenantRole | null {
50
+ if (!row || row.status !== ACTIVE_MEMBERSHIP_STATUS || row.tenantId !== tenantId || row.userSub !== userSub) return null;
51
+ return ROLE_CLAIMS.find(([role]) => role === row.role)?.[0] ?? null;
52
+ }
53
+
54
+ /**
55
+ * The tenant this session acts for. A shared stack takes the person's stored selection (the Google flow cannot pass one, so
56
+ * the choice is written first and read here); a stored value that is not a tenant id selects nothing. A dedicated stack acts
57
+ * for its fixed tenant whatever was selected.
58
+ */
59
+ export async function sessionTenant(environment: ClaimEnvironment, userSub: string, read: ItemReader): Promise<string | null> {
60
+ if (!environment.shared) return environment.fixedTenantId;
61
+ if (!environment.tenancyModels) return null;
62
+ const selection = await read("TenantSelection", userSub);
63
+ return validTenantId(selection?.selectedTenantId);
64
+ }
65
+
66
+ /** Roles a person holds on a dedicated stack through their Cognito groups. A shared stack never reads groups for a tenant. */
67
+ export function rolesFromGroups(groups: readonly string[]): TenantRole[] {
68
+ return GROUP_ROLES.filter((role) => groups.includes(role));
69
+ }
70
+
71
+ /**
72
+ * Every claim for one sign-in or refresh: `{papyrus_tenant_<role>: tenantId}` for each role held on the session's tenant, or
73
+ * nothing when the person has no tenant, no active membership there and (on a dedicated stack) no matching group.
74
+ */
75
+ export async function buildTenantClaims(
76
+ environment: ClaimEnvironment,
77
+ person: { userSub: string; groups: readonly string[] },
78
+ read: ItemReader,
79
+ ): Promise<Record<string, string>> {
80
+ const tenantId = await sessionTenant(environment, person.userSub, read);
81
+ if (tenantId === null) return {};
82
+ const roles = new Set<TenantRole>(environment.shared ? [] : rolesFromGroups(person.groups));
83
+ if (environment.tenancyModels) {
84
+ const role = membershipRole(await read("TenantMembership", `${tenantId}#${person.userSub}`), tenantId, person.userSub);
85
+ if (role) roles.add(role);
86
+ }
87
+ const claims: Record<string, string> = {};
88
+ for (const [role, claim] of ROLE_CLAIMS) if (roles.has(role)) claims[claim] = tenantId;
89
+ return claims;
90
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Set to "true" by the site backend when the `tenancy` model group is deployed (a bootstrap deploy leaves it out), which is
3
+ * when TenantMembership and TenantSelection exist to be read. Without it the function reads no table.
4
+ * Its own file because the backend definition (amplify/auth/tenant-session-claims.ts) needs it and the package compiles that
5
+ * side separately from the handler side (packages/papyrus/scripts/stage.mjs).
6
+ */
7
+ export const TENANCY_MODELS_ENVIRONMENT_VARIABLE = "PAPYRUS_TENANT_RECORDS_DEPLOYED";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Set to "true" by the site backend when the `tenancy` model group is deployed (a bootstrap deploy leaves it out), which is
3
+ * when TenantMembership and TenantSelection exist to be read. Without it the function reads no table.
4
+ * Its own file because the backend definition (amplify/auth/tenant-session-claims.ts) needs it and the package compiles that
5
+ * side separately from the handler side (packages/papyrus/scripts/stage.mjs).
6
+ */
7
+ export const TENANCY_MODELS_ENVIRONMENT_VARIABLE = "PAPYRUS_TENANT_RECORDS_DEPLOYED";
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Cognito pre-token-generation trigger, event version 2 (PPY-0bb0fd). On every sign-in and refresh it adds the tenant role
3
+ * claims (claims.ts) to the access token and the ID token, beside the person's Cognito groups, which it never touches.
4
+ * It reads only the TenantSelection and TenantMembership rows of this stack, never Prospectus. A failed read fails the
5
+ * token request: a guessed answer would grant or withhold access without anyone knowing.
6
+ */
7
+ import { getLambdaDataClient, LAMBDA_DATA_AUTH_MODE } from "../shared/lambda-data-client";
8
+ import { buildTenantClaims, claimEnvironment, type ItemReader, type Row } from "./claims";
9
+
10
+ export type PreTokenGenerationV2Event = {
11
+ request: {
12
+ userAttributes: Record<string, string>;
13
+ groupConfiguration?: { groupsToOverride?: string[] };
14
+ };
15
+ response: {
16
+ claimsAndScopeOverrideDetails?: {
17
+ idTokenGeneration?: { claimsToAddOrOverride?: Record<string, string> };
18
+ accessTokenGeneration?: { claimsToAddOrOverride?: Record<string, string> };
19
+ };
20
+ };
21
+ };
22
+
23
+ export function createHandler(read: ItemReader, environment: () => Record<string, string | undefined> = () => process.env) {
24
+ return async function handler<Event extends PreTokenGenerationV2Event>(event: Event): Promise<Event> {
25
+ const userSub = event.request.userAttributes.sub;
26
+ if (!userSub) throw new Error("The token event carries no sub, so no tenant can be chosen for it.");
27
+ const claims = await buildTenantClaims(
28
+ claimEnvironment(environment()),
29
+ { userSub, groups: event.request.groupConfiguration?.groupsToOverride ?? [] },
30
+ read,
31
+ );
32
+ if (Object.keys(claims).length > 0) {
33
+ event.response.claimsAndScopeOverrideDetails = {
34
+ ...event.response.claimsAndScopeOverrideDetails,
35
+ idTokenGeneration: { claimsToAddOrOverride: claims },
36
+ accessTokenGeneration: { claimsToAddOrOverride: claims },
37
+ };
38
+ }
39
+ return event;
40
+ };
41
+ }
42
+
43
+ /**
44
+ * One GetItem through the stack's own data API with the function's IAM role (the same wiring as manage-user-role). The function
45
+ * sits in the auth stack, which the data API's user pool depends on, so it cannot name the tables directly without a cycle
46
+ * between the two stacks; the schema grants it query access instead (`functionGrants` in amplify/data/schema.ts).
47
+ */
48
+ const readDataItem: ItemReader = async (model, id) => {
49
+ const client = await getLambdaDataClient();
50
+ const options = { authMode: LAMBDA_DATA_AUTH_MODE };
51
+ const { data, errors } = model === "TenantSelection" ? await client.models.TenantSelection.get({ id }, options) : await client.models.TenantMembership.get({ id }, options);
52
+ if (errors?.length) throw new Error(`Reading ${model} ${id} failed: ${errors.map((error: { message?: string }) => error.message).join("; ")}`);
53
+ return (data as Row | null | undefined) ?? null;
54
+ };
55
+
56
+ export const handler = createHandler(readDataItem);
@@ -0,0 +1,12 @@
1
+ import { defineFunction } from "@aws-amplify/backend";
2
+ /**
3
+ * Cognito's pre-token-generation trigger (PPY-0bb0fd). `amplify/auth/tenant-session-claims.ts` rewires it to event version 2
4
+ * (so the claims land on the access token) and gives it read access to two tenancy tables.
5
+ */
6
+ export const tenantClaims = defineFunction({
7
+ name: "papyrus-tenant-claims",
8
+ entry: "./handler.ts",
9
+ timeoutSeconds: 5,
10
+ memoryMB: 256,
11
+ resourceGroupName: "auth",
12
+ });
@@ -0,0 +1,13 @@
1
+ import { defineFunction } from "@aws-amplify/backend";
2
+
3
+ /**
4
+ * Cognito's pre-token-generation trigger (PPY-0bb0fd). `amplify/auth/tenant-session-claims.ts` rewires it to event version 2
5
+ * (so the claims land on the access token) and gives it read access to two tenancy tables.
6
+ */
7
+ export const tenantClaims = defineFunction({
8
+ name: "papyrus-tenant-claims",
9
+ entry: "./handler.ts",
10
+ timeoutSeconds: 5,
11
+ memoryMB: 256,
12
+ resourceGroupName: "auth",
13
+ });