@anthusai/papyrus 1.0.0-next.4 → 1.0.0-next.41

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 (147) hide show
  1. package/amplify/auth/redirect-urls.js +54 -0
  2. package/amplify/auth/redirect-urls.ts +66 -0
  3. package/amplify/auth/resource.js +20 -5
  4. package/amplify/auth/resource.ts +27 -5
  5. package/amplify/data/resource.js +28 -70
  6. package/amplify/data/resource.ts +29 -70
  7. package/amplify/data/schema.js +33 -58
  8. package/amplify/data/schema.ts +34 -58
  9. package/amplify/functions/category-action/handler.ts +5 -3
  10. package/amplify/functions/console-chat-responder/py/execute_tactus_runner.py +0 -10
  11. package/amplify/functions/console-chat-responder/resource.js +0 -7
  12. package/amplify/functions/console-chat-responder/resource.ts +0 -8
  13. package/amplify/functions/console-chat-responder/src/main.rs +0 -9
  14. package/amplify/functions/content-actions/handler.py +45 -3
  15. package/amplify/functions/shared/reference-curation-metadata.ts +29 -0
  16. package/amplify/inbound-email/ses-intake.js +86 -0
  17. package/amplify/inbound-email/ses-intake.ts +110 -0
  18. package/amplify/rebuild-trigger-settings.js +22 -0
  19. package/amplify/rebuild-trigger-settings.ts +42 -0
  20. package/amplify/resolver-waves.js +26 -0
  21. package/amplify/resolver-waves.ts +34 -0
  22. package/amplify/site-backend-config.ts +36 -1
  23. package/amplify/site-backend-names.js +103 -0
  24. package/amplify/site-backend-names.ts +166 -0
  25. package/amplify/site-backend.js +93 -170
  26. package/amplify/site-backend.ts +126 -196
  27. package/amplify/storage/resource.js +3 -0
  28. package/amplify/storage/resource.ts +3 -0
  29. package/amplify/storage-backups/construct.js +31 -0
  30. package/amplify/storage-backups/construct.ts +47 -0
  31. package/app/%5F_preview/[[...path]]/route.ts +8 -0
  32. package/app/[year]/[month]/[day]/[articleSlug]/page.tsx +2 -0
  33. package/app/[year]/[month]/[day]/edition-route-page.tsx +2 -0
  34. package/app/api/media/[...path]/route.ts +5 -16
  35. package/app/api/revalidate/route.ts +8 -7
  36. package/app/articles/[slug]/page.tsx +6 -4
  37. package/app/blog-rhythm.css +278 -0
  38. package/app/globals.css +21 -0
  39. package/app/layout.tsx +16 -0
  40. package/app/newsroom/[section]/[...selection]/page.tsx +6 -5
  41. package/app/newsroom/[section]/page.tsx +4 -3
  42. package/app/newsroom/articles/[id]/page.tsx +15 -0
  43. package/app/newsroom/articles/page.tsx +13 -0
  44. package/app/newsroom/layout.tsx +4 -9
  45. package/app/page.tsx +18 -5
  46. package/app/robots.ts +2 -5
  47. package/bin/papyrus-app.mjs +12 -2
  48. package/bin/papyrus-infra.mjs +29 -3
  49. package/components/amplify-client-provider.tsx +4 -22
  50. package/components/archive-shell.tsx +2 -22
  51. package/components/article-video.tsx +247 -3
  52. package/components/blog-page-background.tsx +23 -6
  53. package/components/markus-ir-preview.tsx +300 -0
  54. package/components/news-desk-taxonomy-client.ts +51 -0
  55. package/components/newspaper.tsx +6 -2
  56. package/components/newsroom-access-gate.tsx +67 -0
  57. package/components/newsroom-article-editor.tsx +741 -0
  58. package/components/newsroom-articles-view.tsx +129 -0
  59. package/components/newsroom-client-shell.tsx +12 -0
  60. package/components/newsroom-ops-overview.tsx +28 -11
  61. package/components/newsroom-ops-shell.tsx +3 -1
  62. package/components/newsroom-references-view.tsx +83 -8
  63. package/components/papyrus-console-shell.tsx +4 -2
  64. package/components/pictogram-figure.tsx +9 -2
  65. package/components/presentation-header.tsx +135 -0
  66. package/components/presentation-rhythm-hrule.tsx +17 -0
  67. package/components/reference-cyclotron-status.tsx +109 -0
  68. package/components/reference-relevance-review.tsx +75 -0
  69. package/components/settings-page.tsx +2 -1
  70. package/components/topic-steering-workspace.tsx +54 -64
  71. package/components/use-blog-header-obstacles.ts +81 -0
  72. package/components/use-brand-fonts-ready.ts +28 -0
  73. package/components/use-rhythm-overlay.ts +29 -0
  74. package/infra/amplify-app-shell.js +228 -50
  75. package/infra/amplify-app-shell.ts +256 -53
  76. package/infra/build-specs.js +15 -5
  77. package/infra/build-specs.ts +18 -7
  78. package/infra/github-oidc-provider.js +24 -0
  79. package/infra/github-oidc-provider.ts +30 -0
  80. package/infra/index.js +1 -0
  81. package/infra/site-config.js +236 -11
  82. package/infra/site-config.ts +276 -15
  83. package/lib/amplify-outputs-path.ts +5 -1
  84. package/lib/blog-feature-solver.ts +459 -0
  85. package/lib/blog-rhythm.ts +134 -0
  86. package/lib/brand-fonts-watch.ts +43 -0
  87. package/lib/brand-fonts.ts +112 -0
  88. package/lib/cached-content-repository.ts +12 -0
  89. package/lib/category-repository.ts +42 -93
  90. package/lib/content-actions-demo.ts +190 -0
  91. package/lib/content-repository.ts +3 -0
  92. package/lib/content-source-context.ts +12 -2
  93. package/lib/content-types.ts +4 -0
  94. package/lib/edition-routes.ts +31 -29
  95. package/lib/graphql-content-repository.ts +61 -9
  96. package/lib/media-route-response.ts +45 -0
  97. package/lib/newspaper-layout.ts +3 -2
  98. package/lib/newsroom-articles.ts +325 -0
  99. package/lib/newsroom-base-path.ts +12 -3
  100. package/lib/newsroom-category-drilldown.ts +3 -2
  101. package/lib/newsroom-demo-articles.ts +90 -0
  102. package/lib/newsroom-forum-routes.ts +6 -4
  103. package/lib/newsroom-index-filters.ts +14 -10
  104. package/lib/newsroom-media-backend.ts +142 -0
  105. package/lib/newsroom-media.ts +182 -0
  106. package/lib/newsroom-nav.ts +3 -0
  107. package/lib/oauth-redirect-priority.ts +40 -0
  108. package/lib/papyrus-web-locations.ts +7 -6
  109. package/lib/presentation-footer.ts +3 -2
  110. package/lib/pretext-layout.ts +12 -3
  111. package/lib/reader-base-path.ts +24 -0
  112. package/lib/reader-static-params.ts +13 -0
  113. package/lib/reference-policy.ts +5 -0
  114. package/lib/relevance-decisions.ts +103 -0
  115. package/lib/relevance-status.ts +63 -0
  116. package/lib/renderer.ts +7 -0
  117. package/lib/revalidate-secret.ts +59 -0
  118. package/lib/robots-policy.ts +14 -0
  119. package/lib/root-route-redirect.ts +16 -0
  120. package/lib/semantic-graph.ts +7 -0
  121. package/lib/site-brand.ts +51 -0
  122. package/lib/staging-gated-path.ts +23 -0
  123. package/lib/staging-preview-object.ts +114 -0
  124. package/lib/video-mode.ts +42 -0
  125. package/lib/video-script.ts +77 -0
  126. package/middleware.ts +23 -18
  127. package/package.json +45 -1
  128. package/renderers/pretext/article-page.tsx +39 -3
  129. package/renderers/pretext/presentation-shared.tsx +113 -0
  130. package/renderers/pretext/presentation-shell.tsx +15 -102
  131. package/renderers/pretext/rhythm-article-page.tsx +165 -0
  132. package/renderers/pretext/rhythm-blog-presentation.tsx +279 -0
  133. package/renderers/pretext/rhythm-shell-style.ts +35 -0
  134. package/routes.manifest.json +45 -2
  135. package/scripts/videoml/build-browser-bundle.mjs +22 -0
  136. package/scripts/videoml/build-preview-bundle.mjs +50 -0
  137. package/scripts/videoml/bundle-common.mjs +129 -0
  138. package/scripts/videoml/preview/preview-entry.tsx +381 -0
  139. package/scripts/videoml/preview/preview-stage-fit.ts +28 -0
  140. package/scripts/videoml/preview/preview-timing.ts +42 -0
  141. package/scripts/videoml/preview.html +77 -0
  142. package/scripts/videoml/standard-entry.tsx +46 -0
  143. package/src/sync.mjs +30 -6
  144. package/src/with-papyrus.mjs +19 -2
  145. package/amplify/functions/graphql-jwt-authorizer/handler.ts +0 -193
  146. package/amplify/functions/graphql-jwt-authorizer/resource.js +0 -14
  147. package/amplify/functions/graphql-jwt-authorizer/resource.ts +0 -15
@@ -0,0 +1,46 @@
1
+ import React from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import {
4
+ ComposableRenderer,
5
+ RendererProvider,
6
+ interpolate,
7
+ spring,
8
+ useCurrentFrame,
9
+ useVideoConfig,
10
+ } from "@videoml/toolchain/renderer";
11
+ import { getComponent, listComponents, registerComponent } from "@videoml/toolchain/renderer/components/registry";
12
+
13
+ type RenderFrameRequest = {
14
+ script: unknown;
15
+ frame: number;
16
+ config: { fps: number; width: number; height: number; durationFrames: number };
17
+ inputProps?: Record<string, unknown>;
18
+ };
19
+
20
+ const root = document.getElementById("root");
21
+ let reactRoot: ReturnType<typeof createRoot> | null = null;
22
+
23
+ const videoApi = {
24
+ registerComponent,
25
+ getComponent,
26
+ listComponents,
27
+ ComposableRenderer,
28
+ RendererProvider,
29
+ useCurrentFrame,
30
+ useVideoConfig,
31
+ interpolate,
32
+ spring,
33
+ };
34
+
35
+ (window as unknown as { Babulus: typeof videoApi }).Babulus = videoApi;
36
+
37
+ (window as unknown as { renderFrame: (request: RenderFrameRequest) => Promise<void> }).renderFrame = (request) => {
38
+ if (!root) throw new Error("VideoML render shell has no #root element.");
39
+ reactRoot ??= createRoot(root);
40
+ reactRoot.render(
41
+ <RendererProvider frame={request.frame} config={request.config}>
42
+ <ComposableRenderer script={request.script as never} {...(request.inputProps ?? {})} />
43
+ </RendererProvider>,
44
+ );
45
+ return new Promise((resolve) => setTimeout(resolve, 100));
46
+ };
package/src/sync.mjs CHANGED
@@ -37,18 +37,42 @@ function shimFor(route) {
37
37
  return lines.join("\n") + "\n";
38
38
  }
39
39
 
40
- function middlewareShim(manifest) {
40
+ export function middlewareShim(manifest) {
41
41
  const matcher = manifest.middleware.matcher ?? '["/((?!_next/static|_next/image|favicon.ico|icon).*)"]';
42
42
  return [
43
43
  MARKER,
44
44
  `export { middleware } from "${PKG}/middleware";`,
45
- `export const config = { matcher: ${matcher} };`,
45
+ `export const config = { ${manifest.middleware.runtime ? `runtime: ${JSON.stringify(manifest.middleware.runtime)}, ` : ""}matcher: ${matcher} };`,
46
46
  "",
47
47
  ].join("\n");
48
48
  }
49
49
 
50
- export function sync({ root = process.cwd(), log = console.log } = {}) {
51
- const manifest = JSON.parse(fs.readFileSync(path.join(pkgRoot, "routes.manifest.json"), "utf8"));
50
+ const RESERVED_FIRST_SEGMENTS = new Set(["newsroom", "api", "_next", "_preview", "%5F_preview"]);
51
+
52
+ export function normalizeReaderBasePath(value) {
53
+ const trimmed = (value ?? "").trim().replace(/\/+$/, "");
54
+ if (!trimmed) return "";
55
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
56
+ }
57
+
58
+ export function readReaderBasePath(root) {
59
+ let text;
60
+ try {
61
+ text = fs.readFileSync(path.join(root, "papyrus.config.ts"), "utf8");
62
+ } catch {
63
+ return "";
64
+ }
65
+ const match = text.match(/\breaderBasePath\s*:\s*(["'`])([^"'`]*)\1/);
66
+ return normalizeReaderBasePath(match ? match[2] : "");
67
+ }
68
+
69
+ export function sync({ root = process.cwd(), log = console.log, manifest: manifestOverride, readerBasePath: readerBasePathOverride } = {}) {
70
+ const manifest = manifestOverride ?? JSON.parse(fs.readFileSync(path.join(pkgRoot, "routes.manifest.json"), "utf8"));
71
+ const readerBasePath = normalizeReaderBasePath(readerBasePathOverride ?? readReaderBasePath(root));
72
+ if (readerBasePath && RESERVED_FIRST_SEGMENTS.has(readerBasePath.split("/")[1])) {
73
+ throw new Error(`readerBasePath "${readerBasePath}" collides with a Papyrus-owned route (newsroom, api, _preview)`);
74
+ }
75
+ const readerRouteFile = (file) => (readerBasePath ? file.replace(/^app\//, `app${readerBasePath}/`) : file);
52
76
  const generated = [];
53
77
  const skipped = [];
54
78
  const write = (relPath, content) => {
@@ -61,7 +85,7 @@ export function sync({ root = process.cwd(), log = console.log } = {}) {
61
85
  fs.writeFileSync(dest, content);
62
86
  generated.push(relPath);
63
87
  };
64
- for (const route of manifest.routes) write(route.file, shimFor(route));
88
+ for (const route of manifest.routes) write(route.reader ? readerRouteFile(route.file) : route.file, shimFor(route));
65
89
  write("middleware.ts", middlewareShim(manifest));
66
90
 
67
91
  // Remove shims that are no longer in the manifest (e.g. after an upgrade).
@@ -81,7 +105,7 @@ export function sync({ root = process.cwd(), log = console.log } = {}) {
81
105
  const re = new RegExp(`${GITIGNORE_BEGIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${GITIGNORE_END}`);
82
106
  fs.writeFileSync(giFile, re.test(gi) ? gi.replace(re, block) : `${gi}${gi.endsWith("\n") || !gi ? "" : "\n"}${block}\n`);
83
107
 
84
- log(`papyrus-app sync: ${generated.length} shim(s) written, ${skipped.length} site-owned file(s) kept (${PKG}@${manifest.version})`);
108
+ log(`papyrus-app sync: ${generated.length} shim(s) written, ${skipped.length} site-owned file(s) kept (${PKG}@${manifest.version})${readerBasePath ? `, reader mounted at ${readerBasePath}` : ""}`);
85
109
  for (const rel of skipped) log(` site-owned: ${rel}`);
86
110
  return { generated, skipped };
87
111
  }
@@ -4,11 +4,12 @@ import { fileURLToPath } from "node:url";
4
4
 
5
5
  /**
6
6
  * Wrap a publication repo's Next config for Papyrus (SPIKE, PPY-82be6c).
7
- * - transpile the package (it ships TypeScript source),
7
+ * - transpile the package and the dependencies that ship TypeScript source (cyclotron),
8
8
  * - alias `papyrus-site` -> ./papyrus.config.ts,
9
9
  * `papyrus-amplify-outputs` -> ./amplify_outputs.json and
10
10
  * `papyrus-site-theme` -> ./publication/theme.css when it exists, else the shipped
11
11
  * empty lib/empty-theme.css (both webpack and turbopack),
12
+ * - trace the corpora/ YAML and amplify_outputs.json that the reader reads via fs at runtime,
12
13
  * - carry Papyrus's own server-external packages and image settings.
13
14
  */
14
15
  const SERVER_EXTERNAL = [
@@ -22,6 +23,21 @@ const SERVER_EXTERNAL = [
22
23
  "@aws-amplify/data-schema",
23
24
  ];
24
25
 
26
+ export const DEFAULT_TRANSPILE_PACKAGES = ["@anthusai/papyrus", "cyclotron"];
27
+
28
+ export function mergeTranspilePackages(existing = []) {
29
+ return [...new Set([...existing, ...DEFAULT_TRANSPILE_PACKAGES])];
30
+ }
31
+
32
+ export const RUNTIME_TRACED_FILES = ["./corpora/**/*", "./amplify_outputs.json"];
33
+
34
+ export function mergeOutputFileTracingIncludes(existing = {}) {
35
+ const merged = { ...existing };
36
+ const current = merged["/**"] ?? [];
37
+ merged["/**"] = [...new Set([...current, ...RUNTIME_TRACED_FILES])];
38
+ return merged;
39
+ }
40
+
25
41
  const EMPTY_THEME = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../lib/empty-theme.css");
26
42
 
27
43
  export function withPapyrus(nextConfig = {}, options = {}) {
@@ -39,8 +55,9 @@ export function withPapyrus(nextConfig = {}, options = {}) {
39
55
  return {
40
56
  distDir: process.env.NEXT_DIST_DIR || ".next",
41
57
  ...nextConfig,
42
- transpilePackages: [...new Set([...(nextConfig.transpilePackages ?? []), "@anthusai/papyrus"])],
58
+ transpilePackages: mergeTranspilePackages(nextConfig.transpilePackages),
43
59
  serverExternalPackages: [...new Set([...(nextConfig.serverExternalPackages ?? []), ...SERVER_EXTERNAL])],
60
+ outputFileTracingIncludes: mergeOutputFileTracingIncludes(nextConfig.outputFileTracingIncludes),
44
61
  images: nextConfig.images ?? { remotePatterns: [{ protocol: "https", hostname: "**" }] },
45
62
  experimental: { devtoolSegmentExplorer: false, ...nextConfig.experimental },
46
63
  turbopack: {
@@ -1,193 +0,0 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
2
- import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
3
-
4
- type AppSyncAuthorizerEvent = {
5
- authorizationToken?: string;
6
- };
7
-
8
- type JwtHeader = {
9
- alg?: string;
10
- typ?: string;
11
- };
12
-
13
- type JwtClaims = {
14
- iss?: string;
15
- sub?: string;
16
- aud?: string | string[];
17
- exp?: number;
18
- nbf?: number;
19
- iat?: number;
20
- scope?: string;
21
- scp?: string | string[];
22
- groups?: string | string[];
23
- roles?: string | string[];
24
- [key: string]: unknown;
25
- };
26
-
27
- export const handler = async (event: AppSyncAuthorizerEvent) => {
28
- try {
29
- const token = normalizeAuthorizationToken(event.authorizationToken);
30
- const jwtSecret = await getJwtSecret();
31
- const claims = verifyHs256Jwt(token, jwtSecret);
32
- assertExpectedIssuer(claims);
33
- assertExpectedAudience(claims);
34
- assertRequiredScope(claims);
35
-
36
- return {
37
- isAuthorized: true,
38
- resolverContext: {
39
- sub: claims.sub ?? "unknown",
40
- iss: claims.iss ?? "unknown",
41
- scope: getClaimValues(claims.scope).join(" "),
42
- },
43
- ttlOverride: 300,
44
- };
45
- } catch (error) {
46
- console.warn(`JWT authorizer rejected request: ${(error as Error).message}`);
47
- return {
48
- isAuthorized: false,
49
- ttlOverride: 0,
50
- };
51
- }
52
- };
53
-
54
- function normalizeAuthorizationToken(value: string | undefined): string {
55
- const token = value
56
- ?.replace(/^PapyrusJwt\s+/i, "")
57
- .replace(/^papyrus-jwt:/i, "")
58
- .replace(/^Bearer\s+/i, "")
59
- .trim();
60
- if (!token) throw new Error("Missing Authorization token.");
61
- return token;
62
- }
63
-
64
- function verifyHs256Jwt(token: string, jwtSecret: string): JwtClaims {
65
- const [encodedHeader, encodedPayload, encodedSignature] = token.split(".");
66
- if (!encodedHeader || !encodedPayload || !encodedSignature) {
67
- throw new Error("JWT must have header, payload, and signature.");
68
- }
69
-
70
- const header = decodeJson<JwtHeader>(encodedHeader);
71
- if (header.alg !== "HS256") {
72
- throw new Error(`Unsupported JWT alg ${header.alg ?? "unknown"}.`);
73
- }
74
-
75
- const claims = decodeJson<JwtClaims>(encodedPayload);
76
- const expectedSignature = createHmac("sha256", jwtSecret)
77
- .update(`${encodedHeader}.${encodedPayload}`)
78
- .digest("base64url");
79
-
80
- if (!constantTimeEqual(encodedSignature, expectedSignature)) {
81
- throw new Error("JWT signature verification failed.");
82
- }
83
-
84
- const now = Math.floor(Date.now() / 1000);
85
- if (typeof claims.exp === "number" && claims.exp <= now) {
86
- throw new Error("JWT is expired.");
87
- }
88
- if (typeof claims.nbf === "number" && claims.nbf > now) {
89
- throw new Error("JWT is not yet valid.");
90
- }
91
-
92
- return claims;
93
- }
94
-
95
- function decodeJson<T>(encoded: string): T {
96
- try {
97
- return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as T;
98
- } catch {
99
- throw new Error("JWT contains invalid base64url JSON.");
100
- }
101
- }
102
-
103
- let cachedJwtSecret: string | null = null;
104
- let ssmClient: SSMClient | null = null;
105
-
106
- async function getJwtSecret(): Promise<string> {
107
- if (cachedJwtSecret) return cachedJwtSecret;
108
-
109
- const directSecret = normalizeOptionalString(process.env.PAPYRUS_JWT_SECRET);
110
- if (directSecret && !isAmplifySecretPlaceholder(directSecret)) {
111
- cachedJwtSecret = directSecret;
112
- return directSecret;
113
- }
114
-
115
- const parameterName = resolveAmplifySsmSecretPath("PAPYRUS_JWT_SECRET");
116
- if (!parameterName) throw new Error("PAPYRUS_JWT_SECRET is not configured.");
117
- ssmClient ??= new SSMClient({});
118
- const response = await ssmClient.send(new GetParameterCommand({
119
- Name: parameterName,
120
- WithDecryption: true,
121
- }));
122
- const secret = normalizeOptionalString(response.Parameter?.Value);
123
- if (!secret) throw new Error(`SSM parameter ${parameterName} did not return a value.`);
124
- cachedJwtSecret = secret;
125
- return secret;
126
- }
127
-
128
- function isAmplifySecretPlaceholder(value: string): boolean {
129
- return /^<.*will be resolved.*>$/i.test(value);
130
- }
131
-
132
- function resolveAmplifySsmSecretPath(name: string): string | null {
133
- const rawConfig = normalizeOptionalString(process.env.AMPLIFY_SSM_ENV_CONFIG);
134
- if (!rawConfig) return null;
135
- try {
136
- const config = JSON.parse(rawConfig) as Record<string, { path?: string; sharedPath?: string } | undefined>;
137
- return normalizeOptionalString(config[name]?.path) ?? normalizeOptionalString(config[name]?.sharedPath);
138
- } catch {
139
- throw new Error("AMPLIFY_SSM_ENV_CONFIG contains invalid JSON.");
140
- }
141
- }
142
-
143
- function normalizeOptionalString(value: unknown): string | null {
144
- if (typeof value !== "string") return null;
145
- const trimmed = value.trim();
146
- return trimmed ? trimmed : null;
147
- }
148
-
149
- function assertExpectedIssuer(claims: JwtClaims): void {
150
- const expectedIssuer = process.env.PAPYRUS_JWT_ISSUER;
151
- if (expectedIssuer && claims.iss !== expectedIssuer) {
152
- throw new Error("JWT issuer is not authorized.");
153
- }
154
- }
155
-
156
- function assertExpectedAudience(claims: JwtClaims): void {
157
- const expectedAudience = process.env.PAPYRUS_JWT_AUDIENCE;
158
- if (!expectedAudience) return;
159
-
160
- const audiences = Array.isArray(claims.aud) ? claims.aud : claims.aud ? [claims.aud] : [];
161
- if (!audiences.includes(expectedAudience)) {
162
- throw new Error("JWT audience is not authorized.");
163
- }
164
- }
165
-
166
- function assertRequiredScope(claims: JwtClaims): void {
167
- const requiredScope = process.env.PAPYRUS_JWT_REQUIRED_SCOPE;
168
- if (!requiredScope) return;
169
-
170
- const values = new Set([
171
- ...getClaimValues(claims.scope),
172
- ...getClaimValues(claims.scp),
173
- ...getClaimValues(claims.groups),
174
- ...getClaimValues(claims.roles),
175
- ]);
176
-
177
- if (!values.has(requiredScope)) {
178
- throw new Error("JWT does not include the required authoring scope.");
179
- }
180
- }
181
-
182
- function getClaimValues(value: unknown): string[] {
183
- if (Array.isArray(value)) return value.flatMap(getClaimValues);
184
- if (typeof value === "string") return value.split(/[,\s]+/).filter(Boolean);
185
- return [];
186
- }
187
-
188
- function constantTimeEqual(left: string, right: string): boolean {
189
- const leftBuffer = Buffer.from(left);
190
- const rightBuffer = Buffer.from(right);
191
- if (leftBuffer.length !== rightBuffer.length) return false;
192
- return timingSafeEqual(leftBuffer, rightBuffer);
193
- }
@@ -1,14 +0,0 @@
1
- import { defineFunction, secret } from "@aws-amplify/backend";
2
- export const graphqlJwtAuthorizer = defineFunction({
3
- name: "papyrus-graphql-jwt-authorizer",
4
- entry: "./handler.ts",
5
- timeoutSeconds: 5,
6
- memoryMB: 256,
7
- resourceGroupName: "data",
8
- environment: {
9
- PAPYRUS_JWT_SECRET: secret("PAPYRUS_JWT_SECRET"),
10
- PAPYRUS_JWT_ISSUER: "papyrus-cli",
11
- PAPYRUS_JWT_AUDIENCE: "papyrus-authoring",
12
- PAPYRUS_JWT_REQUIRED_SCOPE: "papyrus:write",
13
- },
14
- });
@@ -1,15 +0,0 @@
1
- import { defineFunction, secret } from "@aws-amplify/backend";
2
-
3
- export const graphqlJwtAuthorizer = defineFunction({
4
- name: "papyrus-graphql-jwt-authorizer",
5
- entry: "./handler.ts",
6
- timeoutSeconds: 5,
7
- memoryMB: 256,
8
- resourceGroupName: "data",
9
- environment: {
10
- PAPYRUS_JWT_SECRET: secret("PAPYRUS_JWT_SECRET"),
11
- PAPYRUS_JWT_ISSUER: "papyrus-cli",
12
- PAPYRUS_JWT_AUDIENCE: "papyrus-authoring",
13
- PAPYRUS_JWT_REQUIRED_SCOPE: "papyrus:write",
14
- },
15
- });