@aws/nx-plugin 1.0.0-rc.43 → 1.0.0-rc.45

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/LICENSE-THIRD-PARTY +121 -154
  2. package/generators.json +6 -0
  3. package/package.json +4 -4
  4. package/src/agentcore-gateway/files/cedar/policies/README.md +9 -0
  5. package/src/agentcore-gateway/files/cedar/policies/permit-all.cedar +15 -0
  6. package/src/agentcore-gateway/generator.js +12 -5
  7. package/src/agentcore-gateway/generator.js.map +1 -1
  8. package/src/agentcore-gateway/schema.d.js.map +1 -1
  9. package/src/agentcore-gateway/schema.d.ts +1 -1
  10. package/src/agentcore-gateway/schema.json +3 -2
  11. package/src/connection/generator.js +1 -1
  12. package/src/connection/generator.js.map +1 -1
  13. package/src/infra/app/__snapshots__/generator.spec.ts.snap +8 -8
  14. package/src/mcp-server/tools/general-guidance.js +1 -1
  15. package/src/mcp-server/tools/general-guidance.js.map +1 -1
  16. package/src/preset/__snapshots__/generator.spec.ts.snap +6 -3
  17. package/src/py/agent/__snapshots__/generator.constructs.spec.ts.snap +7 -7
  18. package/src/py/agent/__snapshots__/generator.frameworks.spec.ts.snap +6 -6
  19. package/src/py/agent/__snapshots__/generator.protocols.spec.ts.snap +2 -2
  20. package/src/py/agent/gateway-connection/generator.js +1 -1
  21. package/src/py/agent/gateway-connection/generator.js.map +1 -1
  22. package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +4 -8
  23. package/src/py/fast-api/__snapshots__/generator.terraform.spec.ts.snap +12 -12
  24. package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
  25. package/src/py/mcp-server/__snapshots__/generator.spec.ts.snap +4 -4
  26. package/src/py/rdb/__snapshots__/generator.spec.ts.snap +21 -5
  27. package/src/py/rdb/files/Dockerfile.create-db-user.template +4 -0
  28. package/src/py/rdb/files/Dockerfile.migration.template +4 -0
  29. package/src/sdk/ts.d.ts +2 -0
  30. package/src/sdk/ts.js +2 -0
  31. package/src/sdk/ts.js.map +1 -1
  32. package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +7 -7
  33. package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +12 -12
  34. package/src/ts/agent/__snapshots__/generator.spec.ts.snap +7 -3
  35. package/src/ts/agent/files/deploy/Dockerfile.template +5 -1
  36. package/src/ts/agent/gateway-connection/generator.js +1 -1
  37. package/src/ts/agent/gateway-connection/generator.js.map +1 -1
  38. package/src/ts/agent/generator.js +6 -0
  39. package/src/ts/agent/generator.js.map +1 -1
  40. package/src/ts/dcr-proxy/__snapshots__/generator.spec.ts.snap +982 -0
  41. package/src/ts/dcr-proxy/generator.d.ts +10 -0
  42. package/src/ts/dcr-proxy/generator.js +98 -0
  43. package/src/ts/dcr-proxy/generator.js.map +1 -0
  44. package/src/ts/dcr-proxy/schema.d.js +6 -0
  45. package/src/ts/dcr-proxy/schema.d.js.map +1 -0
  46. package/src/ts/dcr-proxy/schema.d.ts +13 -0
  47. package/src/ts/dcr-proxy/schema.json +44 -0
  48. package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +4 -8
  49. package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
  50. package/src/ts/mcp-server/__snapshots__/generator.spec.ts.snap +2 -2
  51. package/src/ts/mcp-server/files/Dockerfile.template +5 -1
  52. package/src/ts/mcp-server/generator.js +1 -0
  53. package/src/ts/mcp-server/generator.js.map +1 -1
  54. package/src/ts/nx-plugin/__snapshots__/generator.spec.ts.snap +2 -2
  55. package/src/ts/nx-plugin/files/mcp-server/resources/GENERAL_GUIDANCE.md.template +1 -1
  56. package/src/ts/nx-plugin/files/mcp-server/utils.ts.template +1 -1
  57. package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +11 -4
  58. package/src/ts/rdb/files/Dockerfile.template +7 -0
  59. package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +28 -28
  60. package/src/ts/react-website/cognito-auth/__snapshots__/generator.terraform.spec.ts.snap +2 -2
  61. package/src/utils/agent-core-constructs/agent-core-constructs.d.ts +1 -0
  62. package/src/utils/agent-core-constructs/agent-core-constructs.js +2 -0
  63. package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
  64. package/src/utils/agent-core-constructs/files/cdk/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.ts.template +38 -3
  65. package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +13 -3
  66. package/src/utils/agent-core-constructs/files/terraform/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.tf.template +22 -1
  67. package/src/utils/commands.js +1 -1
  68. package/src/utils/commands.js.map +1 -1
  69. package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.d.ts +38 -0
  70. package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js +93 -0
  71. package/src/utils/dcr-proxy-constructs/dcr-proxy-constructs.js.map +1 -0
  72. package/src/utils/dcr-proxy-constructs/files/cdk/app/dcr-proxies/__nameKebabCase__/__nameKebabCase__.ts.template +227 -0
  73. package/src/utils/dcr-proxy-constructs/files/project/src/handlers/authorization-server-metadata.ts.template +39 -0
  74. package/src/utils/dcr-proxy-constructs/files/project/src/handlers/authorize.ts.template +26 -0
  75. package/src/utils/dcr-proxy-constructs/files/project/src/handlers/mcp-proxy.ts.template +89 -0
  76. package/src/utils/dcr-proxy-constructs/files/project/src/handlers/protected-resource-metadata.ts.template +13 -0
  77. package/src/utils/dcr-proxy-constructs/files/project/src/handlers/register.ts.template +70 -0
  78. package/src/utils/dcr-proxy-constructs/files/project/src/handlers/token.ts.template +75 -0
  79. package/src/utils/dcr-proxy-constructs/files/terraform/app/dcr-proxies/__nameKebabCase__/__nameKebabCase__.tf.template +410 -0
  80. package/src/utils/docker.d.ts +4 -3
  81. package/src/utils/docker.js +11 -7
  82. package/src/utils/docker.js.map +1 -1
  83. package/src/utils/files/common/scripts/src/dynamodb/start-container.ts.template +1 -3
  84. package/src/utils/files/common/scripts/src/rdb/shared/start-container.ts.template +1 -3
  85. package/src/utils/format.d.ts +1 -1
  86. package/src/utils/format.js +3 -2
  87. package/src/utils/format.js.map +1 -1
  88. package/src/utils/init.js +4 -0
  89. package/src/utils/init.js.map +1 -1
  90. package/src/utils/versions.d.ts +53 -51
  91. package/src/utils/versions.js +53 -49
  92. package/src/utils/versions.js.map +1 -1
@@ -0,0 +1,227 @@
1
+ import * as url from 'node:url';
2
+ import { Construct } from 'constructs';
3
+ import { Duration, Stack } from 'aws-cdk-lib';
4
+ import * as apigwv2 from 'aws-cdk-lib/aws-apigatewayv2';
5
+ import * as integrations from 'aws-cdk-lib/aws-apigatewayv2-integrations';
6
+ import * as lambda from 'aws-cdk-lib/aws-lambda';
7
+ import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
8
+ import { HttpApi } from '../../../core/api/http-api<% if (esm) { %>.js<% } %>';
9
+ import {
10
+ HttpApiIntegration,
11
+ OperationDetails,
12
+ } from '../../../core/api/utils<% if (esm) { %>.js<% } %>';
13
+
14
+ export interface <%- nameClassName %>Props {
15
+ /**
16
+ * Cognito User Pool id (e.g. `us-east-1_abc123`).
17
+ */
18
+ readonly userPoolId: string;
19
+
20
+ /**
21
+ * Cognito User Pool App Client id.
22
+ */
23
+ readonly userPoolClientId: string;
24
+
25
+ /**
26
+ * ARN of the Secrets Manager secret holding the Cognito App Client secret.
27
+ * The token handler reads this at runtime to complete the token exchange;
28
+ * the secret is never exposed to the client. Create the secret in your own
29
+ * stack (from your App Client's generated secret) and pass its ARN here.
30
+ */
31
+ readonly cognitoClientSecretArn: string;
32
+
33
+ /**
34
+ * Base URL of the Cognito Hosted UI domain, without a trailing slash
35
+ * (e.g. `https://my-domain.auth.us-east-1.amazoncognito.com`). The proxy
36
+ * forwards `/authorize` and `/oauth/token` to this host.
37
+ */
38
+ readonly cognitoHostedUiBase: string;
39
+
40
+ /**
41
+ * Full URL of the upstream MCP server (e.g. AgentCore Runtime/Gateway
42
+ * endpoint). The proxy forwards requests on its `/mcp` path to this URL and
43
+ * rewrites the upstream `WWW-Authenticate` header so MCP clients discover
44
+ * this proxy as the protected-resource metadata host.
45
+ */
46
+ readonly upstreamUrl: string;
47
+ }
48
+
49
+ // The proxy operations wired to the shared HttpApi construct. The
50
+ // openid-configuration route reuses the authorization-server-metadata handler.
51
+ type <%- nameClassName %>Operation =
52
+ | 'protectedResourceMetadata'
53
+ | 'authServerMetadata'
54
+ | 'openIdConfiguration'
55
+ | 'register'
56
+ | 'authorize'
57
+ | 'token'
58
+ | 'mcp';
59
+
60
+ const OPERATIONS: Record<<%- nameClassName %>Operation, OperationDetails> = {
61
+ protectedResourceMetadata: {
62
+ path: '/.well-known/oauth-protected-resource',
63
+ method: 'GET',
64
+ },
65
+ authServerMetadata: {
66
+ path: '/.well-known/oauth-authorization-server',
67
+ method: 'GET',
68
+ },
69
+ openIdConfiguration: {
70
+ path: '/.well-known/openid-configuration',
71
+ method: 'GET',
72
+ },
73
+ register: { path: '/register', method: 'POST' },
74
+ authorize: { path: '/authorize', method: 'GET' },
75
+ token: { path: '/oauth/token', method: 'POST' },
76
+ mcp: { path: '/mcp', method: 'ANY' },
77
+ };
78
+
79
+ // Resolve a handler's rolldown bundle output directory, relative to this
80
+ // compiled construct file, back to the workspace root.
81
+ const asset = (bundlePathFromRoot: string): lambda.Code =>
82
+ lambda.Code.fromAsset(
83
+ url.fileURLToPath(
84
+ new URL(
85
+ `../../../../../../../${bundlePathFromRoot}`,
86
+ <% if (esm) { %>import.meta.url<% } else { %>require('url').pathToFileURL(__filename).href<% } %>,
87
+ ),
88
+ ),
89
+ );
90
+
91
+ /**
92
+ * OAuth Dynamic Client Registration (DCR) proxy for Amazon Cognito.
93
+ *
94
+ * Lets MCP clients (Claude Code, Kiro CLI, MCP Inspector, ...) authenticate
95
+ * against an Amazon Cognito User Pool while keeping the Hosted UI flow intact,
96
+ * supporting RFC 7591 Dynamic Client Registration, and never exposing the
97
+ * Cognito App Client secret to the client.
98
+ */
99
+ export class <%- nameClassName %> extends Construct {
100
+ readonly httpApi: HttpApi<
101
+ <%- nameClassName %>Operation,
102
+ Record<<%- nameClassName %>Operation, HttpApiIntegration>
103
+ >;
104
+ readonly proxyUrl: string;
105
+ readonly mcpUrl: string;
106
+ readonly metadataUrl: string;
107
+ readonly authServerMetadataUrl: string;
108
+ readonly tokenEndpoint: string;
109
+ readonly registrationEndpoint: string;
110
+
111
+ constructor(scope: Construct, id: string, props: <%- nameClassName %>Props) {
112
+ super(scope, id);
113
+
114
+ const region = Stack.of(this).region;
115
+
116
+ const clientSecret = secretsmanager.Secret.fromSecretCompleteArn(
117
+ this,
118
+ 'CognitoClientSecret',
119
+ props.cognitoClientSecretArn,
120
+ );
121
+
122
+ const cognitoIssuer = `https://cognito-idp.${region}.amazonaws.com/${props.userPoolId}`;
123
+
124
+ const baseEnv: Record<string, string> = {
125
+ COGNITO_CLIENT_ID: props.userPoolClientId,
126
+ COGNITO_CLIENT_SECRET_ARN: clientSecret.secretArn,
127
+ COGNITO_ISSUER: cognitoIssuer,
128
+ COGNITO_HOSTED_UI_BASE: props.cognitoHostedUiBase,
129
+ COGNITO_REGION: region,
130
+ };
131
+
132
+ // Lambda functions use their auto-created log group; access logging for the
133
+ // API is handled by the shared HttpApi construct's KMS-encrypted log group.
134
+ const makeFn = (
135
+ id_: string,
136
+ bundlePathFromRoot: string,
137
+ overrides?: Partial<lambda.FunctionProps>,
138
+ ): lambda.Function =>
139
+ new lambda.Function(this, id_, {
140
+ code: asset(bundlePathFromRoot),
141
+ handler: 'index.handler',
142
+ runtime: lambda.Runtime.NODEJS_22_X,
143
+ architecture: lambda.Architecture.ARM_64,
144
+ timeout: Duration.seconds(10),
145
+ memorySize: 256,
146
+ environment: baseEnv,
147
+ tracing: lambda.Tracing.ACTIVE,
148
+ ...overrides,
149
+ });
150
+
151
+ const protectedResourceFn = makeFn(
152
+ 'ProtectedResourceFn',
153
+ '<%- bundlePathsFromRoot['protected-resource-metadata'] %>',
154
+ );
155
+ const authServerFn = makeFn(
156
+ 'AuthServerFn',
157
+ '<%- bundlePathsFromRoot['authorization-server-metadata'] %>',
158
+ );
159
+ const registerFn = makeFn(
160
+ 'RegisterFn',
161
+ '<%- bundlePathsFromRoot['register'] %>',
162
+ );
163
+ const authorizeFn = makeFn(
164
+ 'AuthorizeFn',
165
+ '<%- bundlePathsFromRoot['authorize'] %>',
166
+ );
167
+ const tokenFn = makeFn('TokenFn', '<%- bundlePathsFromRoot['token'] %>');
168
+
169
+ clientSecret.grantRead(tokenFn);
170
+
171
+ // The MCP proxy Lambda buffers upstream responses, so it is given more time
172
+ // (up to the API Gateway HTTP API integration limit) and memory.
173
+ const mcpProxyFn = makeFn(
174
+ 'McpProxyFn',
175
+ '<%- bundlePathsFromRoot['mcp-proxy'] %>',
176
+ {
177
+ timeout: Duration.seconds(29),
178
+ memorySize: 512,
179
+ },
180
+ );
181
+
182
+ const int = (id_: string, fn: lambda.Function): HttpApiIntegration => ({
183
+ integration: new integrations.HttpLambdaIntegration(id_, fn),
184
+ });
185
+
186
+ this.httpApi = new HttpApi(this, 'HttpApi', {
187
+ apiName: `${id}-mcp-auth-proxy`,
188
+ description: 'MCP-compatible OAuth proxy for Amazon Cognito',
189
+ corsPreflight: {
190
+ allowOrigins: ['*'],
191
+ allowMethods: [
192
+ apigwv2.CorsHttpMethod.GET,
193
+ apigwv2.CorsHttpMethod.POST,
194
+ apigwv2.CorsHttpMethod.DELETE,
195
+ apigwv2.CorsHttpMethod.OPTIONS,
196
+ ],
197
+ allowHeaders: ['authorization', 'content-type', 'mcp-protocol-version'],
198
+ maxAge: Duration.minutes(10),
199
+ },
200
+ operations: OPERATIONS,
201
+ integrations: {
202
+ protectedResourceMetadata: int(
203
+ 'ProtectedResourceInt',
204
+ protectedResourceFn,
205
+ ),
206
+ authServerMetadata: int('AuthServerInt', authServerFn),
207
+ openIdConfiguration: int('OpenIdConfigInt', authServerFn),
208
+ register: int('RegisterInt', registerFn),
209
+ authorize: int('AuthorizeInt', authorizeFn),
210
+ token: int('TokenInt', tokenFn),
211
+ mcp: int('McpProxyInt', mcpProxyFn),
212
+ },
213
+ });
214
+
215
+ this.proxyUrl = this.httpApi.api.apiEndpoint;
216
+ this.mcpUrl = `${this.proxyUrl}/mcp`;
217
+ this.metadataUrl = `${this.proxyUrl}/.well-known/oauth-protected-resource`;
218
+ this.authServerMetadataUrl = `${this.proxyUrl}/.well-known/oauth-authorization-server`;
219
+ this.tokenEndpoint = `${this.proxyUrl}/oauth/token`;
220
+ this.registrationEndpoint = `${this.proxyUrl}/register`;
221
+
222
+ // Wire the MCP proxy handler's upstream + metadata URLs after the API is
223
+ // created so its endpoint is resolvable.
224
+ mcpProxyFn.addEnvironment('UPSTREAM_URL', props.upstreamUrl);
225
+ mcpProxyFn.addEnvironment('PROXY_METADATA_URL', this.metadataUrl);
226
+ }
227
+ }
@@ -0,0 +1,39 @@
1
+ import type { APIGatewayProxyHandlerV2 } from 'aws-lambda';
2
+
3
+ const COGNITO_ISSUER = process.env.COGNITO_ISSUER!;
4
+
5
+ let cached: Record<string, unknown> | undefined;
6
+
7
+ async function fetchUpstream(): Promise<Record<string, unknown>> {
8
+ if (cached) return cached;
9
+ const res = await fetch(`${COGNITO_ISSUER}/.well-known/openid-configuration`);
10
+ if (!res.ok) {
11
+ throw new Error(`Cognito discovery failed: ${res.status} ${res.statusText}`);
12
+ }
13
+ cached = (await res.json()) as Record<string, unknown>;
14
+ return cached;
15
+ }
16
+
17
+ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
18
+ const proxyUrl = `https://${event.requestContext.domainName}`;
19
+ const upstream = await fetchUpstream();
20
+
21
+ // Override the proxy-handled endpoints.
22
+ // jwks_uri is kept as Cognito's so JWT verification works directly against
23
+ // Cognito. issuer is kept as Cognito's so JWT.iss validation matches.
24
+ // authorization_endpoint points to the proxy so we can strip the RFC 8707
25
+ // `resource` parameter that some MCP clients send (Cognito rejects token
26
+ // exchange for unregistered resource server URLs).
27
+ const metadata = {
28
+ ...upstream,
29
+ authorization_endpoint: `${proxyUrl}/authorize`,
30
+ token_endpoint: `${proxyUrl}/oauth/token`,
31
+ registration_endpoint: `${proxyUrl}/register`,
32
+ };
33
+
34
+ return {
35
+ statusCode: 200,
36
+ headers: { 'content-type': 'application/json' },
37
+ body: JSON.stringify(metadata),
38
+ };
39
+ };
@@ -0,0 +1,26 @@
1
+ import type { APIGatewayProxyHandlerV2 } from 'aws-lambda';
2
+
3
+ const COGNITO_HOSTED_UI_BASE = process.env.COGNITO_HOSTED_UI_BASE!;
4
+
5
+ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
6
+ const params = new URLSearchParams(event.rawQueryString ?? '');
7
+
8
+ console.log('[authorize]', {
9
+ scope: params.get('scope'),
10
+ redirect_uri: params.get('redirect_uri'),
11
+ has_resource: params.has('resource'),
12
+ });
13
+
14
+ // RFC 8707 `resource` parameter binds the access token's `aud` claim to
15
+ // the given URL. Cognito accepts it at /authorize but rejects the token
16
+ // exchange with `invalid_grant` when the URL is not registered as a
17
+ // resource server. MCP clients send this unconditionally, so strip it.
18
+ params.delete('resource');
19
+
20
+ const target = `${COGNITO_HOSTED_UI_BASE}/oauth2/authorize?${params.toString()}`;
21
+ return {
22
+ statusCode: 302,
23
+ headers: { location: target },
24
+ body: '',
25
+ };
26
+ };
@@ -0,0 +1,89 @@
1
+ import type {
2
+ APIGatewayProxyHandlerV2,
3
+ APIGatewayProxyStructuredResultV2,
4
+ } from 'aws-lambda';
5
+
6
+ const UPSTREAM_URL = process.env.UPSTREAM_URL!;
7
+ const PROXY_METADATA_URL = process.env.PROXY_METADATA_URL!;
8
+
9
+ // Headers stripped when relaying requests/responses through the proxy:
10
+ // RFC 7230 hop-by-hop headers (scoped to a single connection, not the next
11
+ // hop), plus entity headers that fetch() re-derives from the actual body -
12
+ // forwarding stale values would corrupt the response.
13
+ const HOP_BY_HOP = new Set([
14
+ 'connection',
15
+ 'keep-alive',
16
+ 'proxy-authenticate',
17
+ 'proxy-authorization',
18
+ 'te',
19
+ 'trailers',
20
+ 'transfer-encoding',
21
+ 'upgrade',
22
+ 'content-length',
23
+ 'content-encoding',
24
+ 'host',
25
+ ]);
26
+
27
+ export const handler: APIGatewayProxyHandlerV2 = async (
28
+ event,
29
+ ): Promise<APIGatewayProxyStructuredResultV2> => {
30
+ const method = event.requestContext.http.method;
31
+ const qs = event.rawQueryString ? `?${event.rawQueryString}` : '';
32
+ const url = `${UPSTREAM_URL}${qs}`;
33
+
34
+ const fwdHeaders = new Headers();
35
+ for (const [k, v] of Object.entries(event.headers ?? {})) {
36
+ if (!v) continue;
37
+ if (HOP_BY_HOP.has(k.toLowerCase())) continue;
38
+ fwdHeaders.set(k, v);
39
+ }
40
+
41
+ const reqBody = event.body
42
+ ? event.isBase64Encoded
43
+ ? Buffer.from(event.body, 'base64')
44
+ : event.body
45
+ : undefined;
46
+
47
+ const upstream = await fetch(url, {
48
+ method,
49
+ headers: fwdHeaders,
50
+ body: reqBody as unknown as ArrayBuffer | string | undefined,
51
+ });
52
+
53
+ const respHeaders: Record<string, string> = {};
54
+ upstream.headers.forEach((v, k) => {
55
+ if (HOP_BY_HOP.has(k.toLowerCase())) return;
56
+ respHeaders[k] = v;
57
+ });
58
+
59
+ // Rewrite WWW-Authenticate so MCP clients discover this proxy
60
+ // as the protected-resource metadata host instead of the upstream.
61
+ const authKey = Object.keys(respHeaders).find(
62
+ (k) => k.toLowerCase() === 'www-authenticate',
63
+ );
64
+ if (authKey) {
65
+ respHeaders[authKey] = respHeaders[authKey].replace(
66
+ /resource_metadata="[^"]*"/i,
67
+ `resource_metadata="${PROXY_METADATA_URL}"`,
68
+ );
69
+ }
70
+
71
+ const buf = Buffer.from(await upstream.arrayBuffer());
72
+ const contentType = (
73
+ respHeaders['content-type'] ??
74
+ respHeaders['Content-Type'] ??
75
+ ''
76
+ ).toLowerCase();
77
+ const isText =
78
+ contentType.includes('json') ||
79
+ contentType.includes('text') ||
80
+ contentType.includes('xml') ||
81
+ contentType.includes('event-stream');
82
+
83
+ return {
84
+ statusCode: upstream.status,
85
+ headers: respHeaders,
86
+ body: isText ? buf.toString('utf-8') : buf.toString('base64'),
87
+ isBase64Encoded: !isText,
88
+ };
89
+ };
@@ -0,0 +1,13 @@
1
+ import type { APIGatewayProxyHandlerV2 } from 'aws-lambda';
2
+
3
+ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
4
+ const proxyUrl = `https://${event.requestContext.domainName}`;
5
+ return {
6
+ statusCode: 200,
7
+ headers: { 'content-type': 'application/json' },
8
+ body: JSON.stringify({
9
+ resource: `${proxyUrl}/mcp`,
10
+ authorization_servers: [proxyUrl],
11
+ }),
12
+ };
13
+ };
@@ -0,0 +1,70 @@
1
+ import type {
2
+ APIGatewayProxyHandlerV2,
3
+ APIGatewayProxyStructuredResultV2,
4
+ } from 'aws-lambda';
5
+
6
+ const COGNITO_CLIENT_ID = process.env.COGNITO_CLIENT_ID!;
7
+
8
+ interface RegisterRequest {
9
+ redirect_uris?: unknown;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ function jsonResponse(
14
+ statusCode: number,
15
+ body: unknown,
16
+ ): APIGatewayProxyStructuredResultV2 {
17
+ return {
18
+ statusCode,
19
+ headers: { 'content-type': 'application/json' },
20
+ body: JSON.stringify(body),
21
+ };
22
+ }
23
+
24
+ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
25
+ if (!event.body) {
26
+ return jsonResponse(400, {
27
+ error: 'invalid_client_metadata',
28
+ error_description: 'request body is required',
29
+ });
30
+ }
31
+
32
+ let req: RegisterRequest;
33
+ try {
34
+ req = JSON.parse(event.body) as RegisterRequest;
35
+ } catch {
36
+ return jsonResponse(400, {
37
+ error: 'invalid_client_metadata',
38
+ error_description: 'request body must be valid JSON',
39
+ });
40
+ }
41
+
42
+ const redirectUris = req.redirect_uris;
43
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0) {
44
+ return jsonResponse(400, {
45
+ error: 'invalid_redirect_uri',
46
+ error_description: 'redirect_uris is required and must be a non-empty array',
47
+ });
48
+ }
49
+
50
+ // The proxy fronts a single Cognito App Client, so Cognito performs the
51
+ // authoritative check: any redirect_uri forwarded to the Hosted UI must be
52
+ // registered as a callback URL on that App Client. The proxy only validates
53
+ // the request shape here and passes the URIs through unchanged.
54
+ for (const uri of redirectUris) {
55
+ if (typeof uri !== 'string') {
56
+ return jsonResponse(400, {
57
+ error: 'invalid_redirect_uri',
58
+ error_description: 'each redirect_uri must be a string',
59
+ });
60
+ }
61
+ }
62
+
63
+ return jsonResponse(201, {
64
+ client_id: COGNITO_CLIENT_ID,
65
+ redirect_uris: redirectUris,
66
+ token_endpoint_auth_method: 'none',
67
+ grant_types: ['authorization_code', 'refresh_token'],
68
+ response_types: ['code'],
69
+ });
70
+ };
@@ -0,0 +1,75 @@
1
+ import type { APIGatewayProxyHandlerV2 } from 'aws-lambda';
2
+ import {
3
+ SecretsManagerClient,
4
+ GetSecretValueCommand,
5
+ } from '@aws-sdk/client-secrets-manager';
6
+
7
+ const COGNITO_HOSTED_UI_BASE = process.env.COGNITO_HOSTED_UI_BASE!;
8
+ const COGNITO_CLIENT_ID = process.env.COGNITO_CLIENT_ID!;
9
+ const COGNITO_CLIENT_SECRET_ARN = process.env.COGNITO_CLIENT_SECRET_ARN!;
10
+ const COGNITO_REGION = process.env.COGNITO_REGION!;
11
+
12
+ const sm = new SecretsManagerClient({ region: COGNITO_REGION });
13
+ let cachedSecret: string | undefined;
14
+
15
+ async function getClientSecret(): Promise<string> {
16
+ if (cachedSecret) return cachedSecret;
17
+ const res = await sm.send(
18
+ new GetSecretValueCommand({ SecretId: COGNITO_CLIENT_SECRET_ARN }),
19
+ );
20
+ if (!res.SecretString) {
21
+ throw new Error('client_secret missing in Secrets Manager');
22
+ }
23
+ cachedSecret = res.SecretString;
24
+ return cachedSecret;
25
+ }
26
+
27
+ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
28
+ if (!event.body) {
29
+ return {
30
+ statusCode: 400,
31
+ headers: { 'content-type': 'application/json' },
32
+ body: JSON.stringify({
33
+ error: 'invalid_request',
34
+ error_description: 'request body is required',
35
+ }),
36
+ };
37
+ }
38
+
39
+ const rawBody = event.isBase64Encoded
40
+ ? Buffer.from(event.body, 'base64').toString('utf-8')
41
+ : event.body;
42
+
43
+ const params = new URLSearchParams(rawBody);
44
+
45
+ // Always force the real Cognito client_id and inject the server-side secret.
46
+ // DCR returned the same client_id to every caller, but we re-assert here
47
+ // to keep client_id/secret consistent regardless of what the caller sent.
48
+ params.set('client_id', COGNITO_CLIENT_ID);
49
+ params.set('client_secret', await getClientSecret());
50
+
51
+ // Cognito does not understand RFC 8707 `resource`; some MCP clients send it
52
+ // and Cognito has been observed to reject the exchange when present.
53
+ params.delete('resource');
54
+
55
+ const res = await fetch(`${COGNITO_HOSTED_UI_BASE}/oauth2/token`, {
56
+ method: 'POST',
57
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
58
+ body: params.toString(),
59
+ });
60
+
61
+ const responseBody = await res.text();
62
+ console.log('[token]', {
63
+ grant_type: params.get('grant_type'),
64
+ status: res.status,
65
+ ...(res.ok ? {} : { body: responseBody }),
66
+ });
67
+
68
+ return {
69
+ statusCode: res.status,
70
+ headers: {
71
+ 'content-type': res.headers.get('content-type') ?? 'application/json',
72
+ },
73
+ body: responseBody,
74
+ };
75
+ };