@@ -17,6 +17,50 @@ function getCredentialsProvider(
1717 } ) ;
1818}
1919
20+ /**
21+ * Detects if LocalStack is being used by making a test request and checking for
22+ * the 'x-localstack' header in the response.
23+ * @see {@link https://github.com/localstack/localstack/pull/12769 }
24+ * @param awsConfiguration - AWS configuration to use for the test request
25+ * @returns true if LocalStack is detected (x-localstack header present), false otherwise
26+ */
27+ async function isLocalStackDetected (
28+ awsConfiguration : AwsConfiguration ,
29+ ) : Promise < boolean > {
30+ // Enable LocalStack response header to detect LocalStack
31+ process . env . LOCALSTACK_RESPONSE_HEADER_ENABLED = 'true' ;
32+
33+ const { STSClient, GetCallerIdentityCommand } = await import (
34+ '@aws-sdk/client-sts'
35+ ) ;
36+
37+ const client = new STSClient ( {
38+ region : awsConfiguration . region ,
39+ credentials : fromNodeProviderChain ( {
40+ clientConfig : { region : awsConfiguration . region } ,
41+ profile : awsConfiguration . profile ,
42+ roleArn : awsConfiguration . role ,
43+ } ) ,
44+ } ) ;
45+
46+ const command = new GetCallerIdentityCommand ( { } ) ;
47+ const response = await client . send ( command ) ;
48+
49+ // Check for x-localstack header in response metadata
50+ const headers = ( response . $metadata as any ) ?. httpHeaders ;
51+ if (
52+ headers &&
53+ ( 'x-localstack' in headers ||
54+ 'X-Localstack' in headers ||
55+ 'X-LOCALSTACK' in headers )
56+ ) {
57+ return true ;
58+ }
59+
60+ return false ;
61+ }
62+
2063export const AwsCredentials = {
2164 getCredentialsProvider,
65+ isLocalStackDetected,
2266} ;
0 commit comments