{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "World ID Bot Prevention 0.6.2. Keys and verification state stay in your AWS account.",
  "Metadata": {
    "AWS::CloudFormation::Interface": {
      "ParameterGroups": [
        {
          "Label": {
            "default": "World ID"
          },
          "Parameters": [
            "InstallationId",
            "AppId",
            "RpId",
            "RpSigningKeyArn",
            "Credentials"
          ]
        },
        {
          "Label": {
            "default": "Website to protect"
          },
          "Parameters": [
            "DistributionId",
            "WebAclArn"
          ]
        },
        {
          "Label": {
            "default": "Protection"
          },
          "Parameters": [
            "Rollout",
            "AlwaysVerifiedPaths",
            "SdkInjection"
          ]
        },
        {
          "Label": {
            "default": "Alarms"
          },
          "Parameters": [
            "NotificationEmail"
          ]
        },
        {
          "Label": {
            "default": "Advanced: keep the defaults unless you need a change"
          },
          "Parameters": [
            "WindowSeconds",
            "ApiRate",
            "VerifyRate",
            "RequestsPerMinute",
            "ApiConcurrency",
            "PermissionsBoundaryArn",
            "WorldIdEnvironment",
            "HostsRevision",
            "AttachmentMode"
          ]
        }
      ],
      "ParameterLabels": {
        "InstallationId": {
          "default": "Installation ID"
        },
        "AppId": {
          "default": "World ID app ID"
        },
        "RpId": {
          "default": "World ID RP ID"
        },
        "RpSigningKeyArn": {
          "default": "RP signing key ARN"
        },
        "Credentials": {
          "default": "Credential that visitors verify with"
        },
        "DistributionId": {
          "default": "CloudFront distribution ID"
        },
        "WebAclArn": {
          "default": "Web ACL ARN (optional)"
        },
        "Rollout": {
          "default": "After installation"
        },
        "AlwaysVerifiedPaths": {
          "default": "Always-verified paths (optional)"
        },
        "SdkInjection": {
          "default": "Insert the AWS WAF script"
        },
        "NotificationEmail": {
          "default": "Alarm email (optional)"
        },
        "WindowSeconds": {
          "default": "Session lifetime in seconds"
        },
        "ApiRate": {
          "default": "API requests per IP address in 5 minutes"
        },
        "VerifyRate": {
          "default": "Proof submissions per IP address per minute"
        },
        "RequestsPerMinute": {
          "default": "Verifications per minute for the installation"
        },
        "ApiConcurrency": {
          "default": "Reserved API concurrency"
        },
        "PermissionsBoundaryArn": {
          "default": "IAM permissions boundary (optional)"
        },
        "WorldIdEnvironment": {
          "default": "World ID environment"
        },
        "HostsRevision": {
          "default": "Hostname refresh value"
        },
        "AttachmentMode": {
          "default": "Attachment mode"
        }
      }
    },
    "WorldId": {
      "release": "1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c",
      "version": "0.6.2",
      "priority_behavior": "AWS WAF Bot Control (priority 0) and World ID (priority 1) run first. If priority 0 or 1 is occupied, customer rules below the first two consecutive free priorities shift up by two. Their relative order and all other settings remain unchanged; uninstall leaves current customer priorities intact."
    }
  },
  "Parameters": {
    "InstallationId": {
      "Type": "String",
      "AllowedPattern": "[0-9a-f]{12}",
      "ConstraintDescription": "the 12-character installation ID from your registration email",
      "Description": "Your installation ID, from the registration page and your registration email. It names this installation's resources, and World bills the RP below to its subscription. Do not change it after installation."
    },
    "AppId": {
      "Type": "String",
      "AllowedPattern": "app_[A-Za-z0-9_]{1,64}",
      "ConstraintDescription": "a Developer Portal app ID, such as app_a1b2c3d4",
      "Description": "The ID of your World ID 4.0 app in Developer Portal; it starts with app_. You can create it after you subscribe; the World ID team helps you."
    },
    "RpId": {
      "Type": "String",
      "AllowedPattern": "rp_[0-9a-f]{1,16}",
      "ConstraintDescription": "a Developer Portal RP ID, such as rp_0123abcd",
      "Description": "The ID of your app's RP in Developer Portal; it starts with rp_ and is registered with this KMS key's signer address. Use this RP for this website only: World binds it to your installation when the stack is created and bills its verifications. Changing it later needs support."
    },
    "RpSigningKeyArn": {
      "Type": "String",
      "AllowedPattern": "arn:aws:kms:us-east-1:[0-9]{12}:key/(?:mrk-[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})",
      "ConstraintDescription": "the key ARN (not an alias) of a KMS key in this account in us-east-1",
      "Description": "Key ARN of the KMS key that signs requests to World ID. In AWS KMS, open the key and copy the ARN from General configuration; an alias does not work. The key must be an asymmetric ECC_SECG_P256K1 sign and verify key in this account in us-east-1, and its signer address must be registered for your RP in Developer Portal. The private key never leaves KMS."
    },
    "Credentials": {
      "Type": "String",
      "AllowedValues": [
        "proof_of_human",
        "selfie"
      ],
      "Default": "proof_of_human",
      "Description": "proof_of_human: Proof of Human. selfie: Proof of Presence | Selfie Check; the World ID team must enable it for your app before you choose it."
    },
    "DistributionId": {
      "Type": "String",
      "AllowedPattern": "[A-Z0-9]{8,32}",
      "ConstraintDescription": "a CloudFront distribution ID, such as E2ABCDEF123456",
      "Description": "ID of the CloudFront distribution to protect, from the CloudFront Distributions list. The distribution must be in this account. Its behaviors must not have a viewer-request CloudFront Function or a viewer Lambda@Edge function. If CloudFormation, CDK or Terraform manages the distribution or its Web ACL, use the setup script in resources-only mode instead: the next deployment of that code would remove the protection. Do not change it after installation."
    },
    "WebAclArn": {
      "Type": "String",
      "AllowedPattern": "(?:|arn:aws:wafv2:us-east-1:[0-9]{12}:global/webacl/[A-Za-z0-9_-]{1,128}/[a-f0-9-]{36})",
      "ConstraintDescription": "empty, or the ARN of a global (CloudFront) Web ACL in this account in us-east-1",
      "Default": "",
      "Description": "If the distribution already has a Web ACL, enter its ARN from AWS WAF > Web ACLs > Global (CloudFront); that Web ACL must protect only this distribution. Otherwise leave it empty: the stack creates a dedicated Web ACL and attaches it to the distribution. The stack adds its two rules after your rules and does not change them."
    },
    "Rollout": {
      "Type": "String",
      "AllowedValues": [
        "enforce",
        "count"
      ],
      "Default": "enforce",
      "Description": "enforce: visitors who match the protection policy must verify with World ID. count: monitor only; AWS WAF counts the requests that it would challenge, and no visitor is challenged."
    },
    "AlwaysVerifiedPaths": {
      "Type": "String",
      "Default": "",
      "AllowedPattern": "(?:|[*]|/(?:[a-z0-9._~-]*[a-z0-9_~-][a-z0-9._~-]*|[.]{3,})(?:/(?:[a-z0-9._~-]*[a-z0-9_~-][a-z0-9._~-]*|[.]{3,}))*(?:,/(?:[a-z0-9._~-]*[a-z0-9_~-][a-z0-9._~-]*|[.]{3,})(?:/(?:[a-z0-9._~-]*[a-z0-9_~-][a-z0-9._~-]*|[.]{3,}))*){0,7})",
      "MaxLength": 1031,
      "ConstraintDescription": "empty, *, or up to eight comma-separated lowercase paths without spaces or trailing slashes, such as /account,/checkout",
      "Description": "Paths where every visitor must verify. Leave empty to challenge only the requests that AWS WAF Bot Control labels as likely bots. Enter up to eight lowercase paths, separated by commas and without spaces, such as /account,/checkout. A path includes its subpaths and the path with an extension: /account includes /account/settings and /account.json, but not /accounting. Matching ignores letter case. Enter * to verify every visitor on the whole website. Clients that never run JavaScript are challenged only on these paths. To test the installation, add a path that no visitor uses, such as /wid-test, and complete a verification there."
    },
    "SdkInjection": {
      "Type": "String",
      "AllowedValues": [
        "true",
        "false"
      ],
      "Default": "true",
      "Description": "true: CloudFront inserts the AWS WAF script into your HTML pages. Most Bot Control labels need the token that this script sets. CloudFront then fetches responses uncompressed from your origin, and your Content Security Policy must allow https://*.awswaf.com. false: your pages already load the AWS WAF script."
    },
    "NotificationEmail": {
      "Type": "String",
      "Default": "",
      "AllowedPattern": "(?:|[^ @]+@[^ @]+\\.[^ @]+)",
      "ConstraintDescription": "empty, or an email address",
      "Description": "Email address for verification API alarms. After deployment, confirm the subscription in the email from Amazon SNS."
    },
    "WindowSeconds": {
      "Type": "String",
      "AllowedPattern": "[6-9][0-9]{2}|[1-7][0-9]{4}|[1-9][0-9]{3}|8[0-5][0-9]{3}|86[0-3][0-9]{2}|86400",
      "ConstraintDescription": "a whole number from 600 to 86400",
      "Default": "86400",
      "Description": "How long a verified session lasts, from 600 to 86400 seconds. It is also the verification window."
    },
    "ApiRate": {
      "Type": "Number",
      "MinValue": 10,
      "MaxValue": 2000000000,
      "Default": 5000,
      "Description": "Maximum World ID API requests from one IP address in 5 minutes. Visitors behind one shared IP address, such as a company network, share this limit."
    },
    "VerifyRate": {
      "Type": "Number",
      "MinValue": 10,
      "MaxValue": 2000000000,
      "Default": 100,
      "Description": "Maximum proof submissions from one IP address per minute. This limit stops one IP address from using up the installation's verifications per minute."
    },
    "RequestsPerMinute": {
      "Type": "String",
      "AllowedPattern": "[1-9][0-9]{0,5}|1000000",
      "ConstraintDescription": "a whole number from 1 to 1000000",
      "Default": "1200",
      "Description": "Maximum verifications per minute for the whole installation. Visitors above this limit get HTTP 429 until the next minute."
    },
    "ApiConcurrency": {
      "Type": "String",
      "AllowedPattern": "0|[1-9][0-9]{0,2}|1000",
      "ConstraintDescription": "a whole number from 0 to 1000",
      "Default": "0",
      "Description": "Lambda concurrency to reserve for the verification API. 0 reserves none."
    },
    "PermissionsBoundaryArn": {
      "Type": "String",
      "Default": "",
      "AllowedPattern": "(?:|arn:aws:iam::[0-9]{12}:policy/[A-Za-z0-9+=,.@_/-]+)",
      "ConstraintDescription": "empty, or the ARN of a managed policy in this account",
      "Description": "If your account requires a permissions boundary on new IAM roles, enter the ARN of the boundary policy. The stack sets it on its three execution roles."
    },
    "WorldIdEnvironment": {
      "Type": "String",
      "AllowedValues": [
        "production",
        "sandbox"
      ],
      "Default": "production",
      "Description": "Keep production. sandbox accepts World ID simulator proofs and blocks no bots; use it only for tests."
    },
    "HostsRevision": {
      "Type": "String",
      "Default": "initial",
      "AllowedPattern": "initial|[a-f0-9]{64}",
      "ConstraintDescription": "initial, or 64 lowercase hexadecimal characters",
      "Description": "Keep the current value. After you add a hostname to the distribution, enter any new 64-character hexadecimal value: the stack then reads the hostnames again and accepts verifications from them."
    },
    "AttachmentMode": {
      "Type": "String",
      "Default": "automatic",
      "AllowedValues": [
        "automatic",
        "resources-only"
      ],
      "Description": "Keep the current value. automatic: the stack attaches World ID to the distribution and Web ACL. resources-only: your infrastructure code attaches it (setup script only). You cannot change it after installation."
    }
  },
  "Conditions": {
    "AutomaticAttachment": {
      "Fn::Equals": [
        {
          "Ref": "AttachmentMode"
        },
        "automatic"
      ]
    },
    "CreateWebAcl": {
      "Fn::And": [
        {
          "Fn::Equals": [
            {
              "Ref": "WebAclArn"
            },
            ""
          ]
        },
        {
          "Condition": "AutomaticAttachment"
        }
      ]
    },
    "HasAlwaysPaths": {
      "Fn::Not": [
        {
          "Fn::Equals": [
            {
              "Ref": "AlwaysVerifiedPaths"
            },
            ""
          ]
        }
      ]
    },
    "WholeSite": {
      "Fn::Equals": [
        {
          "Ref": "AlwaysVerifiedPaths"
        },
        "*"
      ]
    },
    "Enforce": {
      "Fn::Equals": [
        {
          "Ref": "Rollout"
        },
        "enforce"
      ]
    },
    "HasPermissionsBoundary": {
      "Fn::Not": [
        {
          "Fn::Equals": [
            {
              "Ref": "PermissionsBoundaryArn"
            },
            ""
          ]
        }
      ]
    },
    "Notify": {
      "Fn::Not": [
        {
          "Fn::Equals": [
            {
              "Ref": "NotificationEmail"
            },
            ""
          ]
        }
      ]
    },
    "ReserveApi": {
      "Fn::Not": [
        {
          "Fn::Equals": [
            {
              "Ref": "ApiConcurrency"
            },
            "0"
          ]
        }
      ]
    }
  },
  "Rules": {
    "Region": {
      "Assertions": [
        {
          "Assert": {
            "Fn::Equals": [
              {
                "Ref": "AWS::Region"
              },
              "us-east-1"
            ]
          },
          "AssertDescription": "Deploy in us-east-1, where the CloudFront and WAF resources live"
        }
      ]
    },
    "ResourcesOnlyWebAcl": {
      "RuleCondition": {
        "Fn::Equals": [
          {
            "Ref": "AttachmentMode"
          },
          "resources-only"
        ]
      },
      "Assertions": [
        {
          "Assert": {
            "Fn::Not": [
              {
                "Fn::Equals": [
                  {
                    "Ref": "WebAclArn"
                  },
                  ""
                ]
              }
            ]
          },
          "AssertDescription": "Resources-only installations need the ARN of the Web ACL that your infrastructure code attaches"
        }
      ]
    }
  },
  "Resources": {
    "CookieSecret": {
      "Type": "AWS::SecretsManager::Secret",
      "DeletionPolicy": "RetainExceptOnCreate",
      "UpdateReplacePolicy": "Retain",
      "Properties": {
        "Name": {
          "Fn::Sub": [
            "wid-customer/${AWS::StackName}-${StackIdPrefix}",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "GenerateSecretString": {
          "SecretStringTemplate": "{}",
          "GenerateStringKey": "placeholder"
        }
      }
    },
    "Setup": {
      "Type": "Custom::WorldIdCustomerSetup",
      "Properties": {
        "ServiceToken": {
          "Fn::GetAtt": [
            "CustomerSetup",
            "Arn"
          ]
        },
        "InstallationId": {
          "Ref": "InstallationId"
        },
        "AppId": {
          "Ref": "AppId"
        },
        "RpId": {
          "Ref": "RpId"
        },
        "CookieSecretArn": {
          "Ref": "CookieSecret"
        },
        "DistributionId": {
          "Ref": "DistributionId"
        },
        "AssetBucket": {
          "Ref": "AssetsBucket"
        },
        "Release": "1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c",
        "AssetVersion": "a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8",
        "HostsRevision": {
          "Ref": "HostsRevision"
        },
        "AttachmentMode": {
          "Ref": "AttachmentMode"
        },
        "ServiceTimeout": 300
      }
    },
    "ApiPolicy": {
      "Type": "AWS::CloudFront::OriginRequestPolicy",
      "Properties": {
        "OriginRequestPolicyConfig": {
          "Name": {
            "Fn::Sub": "${AWS::StackName}-wid-api"
          },
          "CookiesConfig": {
            "CookieBehavior": "whitelist",
            "Cookies": [
              "__Host-wid_c"
            ]
          },
          "HeadersConfig": {
            "HeaderBehavior": "whitelist",
            "Headers": [
              "Origin",
              "Content-Type"
            ]
          },
          "QueryStringsConfig": {
            "QueryStringBehavior": "none"
          }
        }
      }
    },
    "AssetsPolicy": {
      "Type": "AWS::CloudFront::CachePolicy",
      "Properties": {
        "CachePolicyConfig": {
          "Name": {
            "Fn::Sub": "${AWS::StackName}-wid-assets"
          },
          "DefaultTTL": 300,
          "MaxTTL": 3600,
          "MinTTL": 0,
          "ParametersInCacheKeyAndForwardedToOrigin": {
            "EnableAcceptEncodingGzip": true,
            "EnableAcceptEncodingBrotli": true,
            "CookiesConfig": {
              "CookieBehavior": "none"
            },
            "HeadersConfig": {
              "HeaderBehavior": "none"
            },
            "QueryStringsConfig": {
              "QueryStringBehavior": "none"
            }
          }
        }
      }
    },
    "ProtectedPaths": {
      "Type": "AWS::WAFv2::RegexPatternSet",
      "Properties": {
        "Scope": "CLOUDFRONT",
        "RegularExpressionList": {
          "Fn::If": [
            "WholeSite",
            [
              "^/"
            ],
            {
              "Fn::If": [
                "HasAlwaysPaths",
                {
                  "Fn::Split": [
                    ",",
                    {
                      "Fn::Sub": [
                        "^${Paths}([/.]|$)",
                        {
                          "Paths": {
                            "Fn::Join": [
                              "([/.]|$),^",
                              {
                                "Fn::Split": [
                                  ",",
                                  {
                                    "Fn::Join": [
                                      "\\.",
                                      {
                                        "Fn::Split": [
                                          ".",
                                          {
                                            "Ref": "AlwaysVerifiedPaths"
                                          }
                                        ]
                                      }
                                    ]
                                  }
                                ]
                              }
                            ]
                          }
                        }
                      ]
                    }
                  ]
                },
                [
                  "^[^/]"
                ]
              ]
            }
          ]
        }
      }
    },
    "WebAcl": {
      "Type": "AWS::WAFv2::WebACL",
      "Condition": "CreateWebAcl",
      "Properties": {
        "Name": {
          "Fn::Sub": "wid-${InstallationId}-acl"
        },
        "Scope": "CLOUDFRONT",
        "DefaultAction": {
          "Allow": {}
        },
        "VisibilityConfig": {
          "CloudWatchMetricsEnabled": true,
          "MetricName": {
            "Fn::Sub": "wid-${InstallationId}-acl"
          },
          "SampledRequestsEnabled": false
        },
        "Description": "Web ACL the World ID Bot Prevention installer protects this distribution with"
      }
    },
    "RuleGroup": {
      "Type": "AWS::WAFv2::RuleGroup",
      "Properties": {
        "Name": {
          "Fn::Sub": "${AWS::StackName}-wid"
        },
        "Scope": "CLOUDFRONT",
        "Capacity": 300,
        "VisibilityConfig": {
          "CloudWatchMetricsEnabled": true,
          "MetricName": {
            "Fn::Sub": "${AWS::StackName}-wid"
          },
          "SampledRequestsEnabled": false
        },
        "Rules": [
          {
            "Action": {
              "Block": {}
            },
            "Name": "BlockAmbiguousPath",
            "Priority": 0,
            "Statement": {
              "RegexMatchStatement": {
                "FieldToMatch": {
                  "UriPath": {}
                },
                "RegexString": "(^|/)\\.{1,2}([/;]|$)|//|\\\\|%(2[5def]|3[0-9]|[46][1-9a-f]|[57][0-9a]|5[cf]|7e|u)",
                "TextTransformations": [
                  {
                    "Priority": 0,
                    "Type": "LOWERCASE"
                  }
                ]
              }
            },
            "VisibilityConfig": {
              "CloudWatchMetricsEnabled": true,
              "MetricName": "WorldId-BlockAmbiguousPath",
              "SampledRequestsEnabled": true
            }
          },
          {
            "Action": {
              "Block": {}
            },
            "Name": "BlockForgedMarker",
            "Priority": 1,
            "Statement": {
              "ByteMatchStatement": {
                "FieldToMatch": {
                  "Headers": {
                    "MatchPattern": {
                      "IncludedHeaders": [
                        "x-amzn-waf-wid"
                      ]
                    },
                    "MatchScope": "KEY",
                    "OversizeHandling": "CONTINUE"
                  }
                },
                "PositionalConstraint": "EXACTLY",
                "SearchString": "x-amzn-waf-wid",
                "TextTransformations": [
                  {
                    "Priority": 0,
                    "Type": "LOWERCASE"
                  }
                ]
              }
            },
            "VisibilityConfig": {
              "CloudWatchMetricsEnabled": true,
              "MetricName": "WorldId-BlockForgedMarker",
              "SampledRequestsEnabled": true
            }
          },
          {
            "Name": "PolicyTrigger",
            "Action": {
              "Count": {}
            },
            "RuleLabels": [
              {
                "Name": "wid:policy"
              }
            ],
            "Statement": {
              "Fn::If": [
                "HasAlwaysPaths",
                {
                  "AndStatement": {
                    "Statements": [
                      {
                        "NotStatement": {
                          "Statement": {
                            "ByteMatchStatement": {
                              "FieldToMatch": {
                                "UriPath": {}
                              },
                              "PositionalConstraint": "STARTS_WITH",
                              "SearchString": "/__wid/api/",
                              "TextTransformations": [
                                {
                                  "Priority": 0,
                                  "Type": "NONE"
                                }
                              ]
                            }
                          }
                        }
                      },
                      {
                        "NotStatement": {
                          "Statement": {
                            "ByteMatchStatement": {
                              "FieldToMatch": {
                                "UriPath": {}
                              },
                              "PositionalConstraint": "STARTS_WITH",
                              "SearchString": "/__wid/assets/",
                              "TextTransformations": [
                                {
                                  "Priority": 0,
                                  "Type": "NONE"
                                }
                              ]
                            }
                          }
                        }
                      },
                      {
                        "OrStatement": {
                          "Statements": [
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:maximum"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:coordinated_activity:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:coordinated_activity:medium"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:ip:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:ip:medium"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:asn:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:asn:medium"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:country:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:country:medium"
                              }
                            },
                            {
                              "RegexPatternSetReferenceStatement": {
                                "Arn": {
                                  "Fn::GetAtt": [
                                    "ProtectedPaths",
                                    "Arn"
                                  ]
                                },
                                "FieldToMatch": {
                                  "UriPath": {}
                                },
                                "TextTransformations": [
                                  {
                                    "Priority": 0,
                                    "Type": "LOWERCASE"
                                  }
                                ]
                              }
                            },
                            {
                              "ByteMatchStatement": {
                                "FieldToMatch": {
                                  "UriPath": {}
                                },
                                "PositionalConstraint": "CONTAINS",
                                "SearchString": ";",
                                "TextTransformations": [
                                  {
                                    "Priority": 0,
                                    "Type": "NONE"
                                  }
                                ]
                              }
                            }
                          ]
                        }
                      }
                    ]
                  }
                },
                {
                  "AndStatement": {
                    "Statements": [
                      {
                        "NotStatement": {
                          "Statement": {
                            "ByteMatchStatement": {
                              "FieldToMatch": {
                                "UriPath": {}
                              },
                              "PositionalConstraint": "STARTS_WITH",
                              "SearchString": "/__wid/api/",
                              "TextTransformations": [
                                {
                                  "Priority": 0,
                                  "Type": "NONE"
                                }
                              ]
                            }
                          }
                        }
                      },
                      {
                        "NotStatement": {
                          "Statement": {
                            "ByteMatchStatement": {
                              "FieldToMatch": {
                                "UriPath": {}
                              },
                              "PositionalConstraint": "STARTS_WITH",
                              "SearchString": "/__wid/assets/",
                              "TextTransformations": [
                                {
                                  "Priority": 0,
                                  "Type": "NONE"
                                }
                              ]
                            }
                          }
                        }
                      },
                      {
                        "OrStatement": {
                          "Statements": [
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:maximum"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:coordinated_activity:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:coordinated_activity:medium"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:ip:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:ip:medium"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:asn:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:asn:medium"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:country:high"
                              }
                            },
                            {
                              "LabelMatchStatement": {
                                "Scope": "LABEL",
                                "Key": "awswaf:managed:aws:bot-control:targeted:aggregate:volumetric:session:token_reuse:country:medium"
                              }
                            }
                          ]
                        }
                      }
                    ]
                  }
                }
              ]
            },
            "VisibilityConfig": {
              "CloudWatchMetricsEnabled": true,
              "SampledRequestsEnabled": false,
              "MetricName": "WorldId-PolicyTrigger"
            },
            "Priority": 2
          },
          {
            "Action": {
              "Count": {
                "CustomRequestHandling": {
                  "InsertHeaders": [
                    {
                      "Name": "wid",
                      "Value": "1"
                    }
                  ]
                }
              }
            },
            "Name": "FlagByLabel",
            "Priority": 3,
            "Statement": {
              "AndStatement": {
                "Statements": [
                  {
                    "NotStatement": {
                      "Statement": {
                        "ByteMatchStatement": {
                          "FieldToMatch": {
                            "UriPath": {}
                          },
                          "PositionalConstraint": "STARTS_WITH",
                          "SearchString": "/__wid/api/",
                          "TextTransformations": [
                            {
                              "Priority": 0,
                              "Type": "NONE"
                            }
                          ]
                        }
                      }
                    }
                  },
                  {
                    "NotStatement": {
                      "Statement": {
                        "ByteMatchStatement": {
                          "FieldToMatch": {
                            "UriPath": {}
                          },
                          "PositionalConstraint": "STARTS_WITH",
                          "SearchString": "/__wid/assets/",
                          "TextTransformations": [
                            {
                              "Priority": 0,
                              "Type": "NONE"
                            }
                          ]
                        }
                      }
                    }
                  },
                  {
                    "LabelMatchStatement": {
                      "Scope": "LABEL",
                      "Key": "wid:policy"
                    }
                  }
                ]
              }
            },
            "VisibilityConfig": {
              "CloudWatchMetricsEnabled": true,
              "MetricName": "WorldId-FlagByLabel",
              "SampledRequestsEnabled": true
            }
          },
          {
            "Action": {
              "Block": {
                "CustomResponse": {
                  "ResponseCode": 429
                }
              }
            },
            "Name": "ApiRate",
            "Priority": 4,
            "Statement": {
              "RateBasedStatement": {
                "AggregateKeyType": "IP",
                "EvaluationWindowSec": 300,
                "Limit": {
                  "Ref": "ApiRate"
                },
                "ScopeDownStatement": {
                  "ByteMatchStatement": {
                    "FieldToMatch": {
                      "UriPath": {}
                    },
                    "PositionalConstraint": "STARTS_WITH",
                    "SearchString": "/__wid/api/",
                    "TextTransformations": [
                      {
                        "Priority": 0,
                        "Type": "NONE"
                      }
                    ]
                  }
                }
              }
            },
            "VisibilityConfig": {
              "CloudWatchMetricsEnabled": true,
              "MetricName": "WorldId-ApiRate",
              "SampledRequestsEnabled": true
            }
          },
          {
            "Action": {
              "Block": {
                "CustomResponse": {
                  "ResponseCode": 429
                }
              }
            },
            "Name": "VerifyRate",
            "Priority": 5,
            "Statement": {
              "RateBasedStatement": {
                "AggregateKeyType": "IP",
                "EvaluationWindowSec": 60,
                "Limit": {
                  "Ref": "VerifyRate"
                },
                "ScopeDownStatement": {
                  "ByteMatchStatement": {
                    "FieldToMatch": {
                      "UriPath": {}
                    },
                    "PositionalConstraint": "EXACTLY",
                    "SearchString": "/__wid/api/verify",
                    "TextTransformations": [
                      {
                        "Priority": 0,
                        "Type": "NONE"
                      }
                    ]
                  }
                }
              }
            },
            "VisibilityConfig": {
              "CloudWatchMetricsEnabled": true,
              "MetricName": "WorldId-VerifyRate",
              "SampledRequestsEnabled": true
            }
          }
        ]
      }
    },
    "InstallerRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "lambda.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "Installation",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "cloudfront:GetDistribution",
                    "cloudfront:UpdateDistribution"
                  ],
                  "Resource": {
                    "Fn::Sub": "arn:aws:cloudfront::${AWS::AccountId}:distribution/${DistributionId}"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "cloudfront:ListDistributionsByWebACLId",
                  "Resource": "*"
                },
                {
                  "Effect": "Allow",
                  "Action": "wafv2:GetWebACL",
                  "Resource": {
                    "Fn::If": [
                      "CreateWebAcl",
                      {
                        "Fn::GetAtt": [
                          "WebAcl",
                          "Arn"
                        ]
                      },
                      {
                        "Ref": "WebAclArn"
                      }
                    ]
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "wafv2:CheckCapacity",
                  "Resource": "*"
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "wafv2:GetRuleGroup",
                    "wafv2:UpdateRuleGroup"
                  ],
                  "Resource": [
                    {
                      "Fn::GetAtt": [
                        "RuleGroup",
                        "Arn"
                      ]
                    },
                    {
                      "Fn::GetAtt": [
                        "ProtectedPaths",
                        "Arn"
                      ]
                    }
                  ]
                },
                {
                  "Effect": "Allow",
                  "Action": "wafv2:UpdateWebACL",
                  "Resource": [
                    {
                      "Fn::If": [
                        "CreateWebAcl",
                        {
                          "Fn::GetAtt": [
                            "WebAcl",
                            "Arn"
                          ]
                        },
                        {
                          "Ref": "WebAclArn"
                        }
                      ]
                    },
                    {
                      "Fn::GetAtt": [
                        "RuleGroup",
                        "Arn"
                      ]
                    },
                    {
                      "Fn::Sub": "arn:aws:wafv2:us-east-1:${AWS::AccountId}:global/rulegroup/*"
                    },
                    {
                      "Fn::Sub": "arn:aws:wafv2:us-east-1:${AWS::AccountId}:global/ipset/*"
                    },
                    {
                      "Fn::Sub": "arn:aws:wafv2:us-east-1:${AWS::AccountId}:global/regexpatternset/*"
                    },
                    {
                      "Fn::Sub": "arn:aws:wafv2:us-east-1:${AWS::AccountId}:global/managedruleset/*"
                    }
                  ]
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "cloudformation:DescribeStackResource",
                    "cloudformation:DescribeStacks"
                  ],
                  "Resource": {
                    "Ref": "AWS::StackId"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "cloudformation:DescribeStackResources",
                  "Resource": "*"
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "InstallerLogs",
                      "Arn"
                    ]
                  }
                }
              ]
            }
          }
        ],
        "PermissionsBoundary": {
          "Fn::If": [
            "HasPermissionsBoundary",
            {
              "Ref": "PermissionsBoundaryArn"
            },
            {
              "Ref": "AWS::NoValue"
            }
          ]
        }
      },
      "Condition": "AutomaticAttachment"
    },
    "InstallerLogs": {
      "Type": "AWS::Logs::LogGroup",
      "DeletionPolicy": "Retain",
      "UpdateReplacePolicy": "Retain",
      "Properties": {
        "LogGroupName": {
          "Fn::Sub": [
            "/aws/lambda/${AWS::StackName}-${StackIdPrefix}-wid-installer",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "RetentionInDays": 365
      },
      "Condition": "AutomaticAttachment"
    },
    "Installer": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "FunctionName": {
          "Fn::Sub": "${AWS::StackName}-wid-installer"
        },
        "Runtime": "nodejs24.x",
        "Handler": "index.handler",
        "Timeout": 900,
        "MemorySize": 256,
        "Architectures": [
          "arm64"
        ],
        "Role": {
          "Fn::GetAtt": [
            "InstallerRole",
            "Arn"
          ]
        },
        "Code": {
          "S3Bucket": "world-id-bot-prevention-production-releases-558948635617",
          "S3Key": "releases/1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c/customer-installer.zip"
        },
        "Environment": {
          "Variables": {
            "WID_INSTALLER_CONFIG": {
              "Fn::Sub": [
                "{\"stack_id\":\"${AWS::StackId}\",\"installation_id\":\"${InstallationId}\",\"distribution_id\":\"${DistributionId}\",\"web_acl_arn\":\"${WebAclArn}\",\"web_acl_owned\":${WebAclOwned},\"rule_group_arn\":\"${RuleGroupArn}\",\"rule_names\":[\"BlockAmbiguousPath\",\"BlockForgedMarker\",\"PolicyTrigger\",\"FlagByLabel\",\"ApiRate\",\"VerifyRate\"],\"viewer_arn\":\"${ViewerArn}\",\"rules_revision\":\"e4d54d59c1a7122437a83c560596c01fca6297967a1a987a9b9790db64f9075d\",\"api_rate\":\"${ApiRate}\",\"api_domain\":\"${CustomerApiDomain}\",\"assets_domain\":\"${AssetsBucket.RegionalDomainName}\",\"api_policy_id\":\"${ApiPolicy}\",\"assets_policy_id\":\"${AssetsPolicy}\",\"rollout\":\"${Rollout}\",\"api_oac_id\":\"${ApiOac}\",\"assets_oac_id\":\"${AssetsOac}\",\"asset_version\":\"a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8\",\"sdk_injection\":${SdkInjection}}",
                {
                  "RuleGroupArn": {
                    "Fn::GetAtt": [
                      "RuleGroup",
                      "Arn"
                    ]
                  },
                  "WebAclArn": {
                    "Fn::If": [
                      "CreateWebAcl",
                      {
                        "Fn::GetAtt": [
                          "WebAcl",
                          "Arn"
                        ]
                      },
                      {
                        "Ref": "WebAclArn"
                      }
                    ]
                  },
                  "WebAclOwned": {
                    "Fn::If": [
                      "CreateWebAcl",
                      true,
                      false
                    ]
                  },
                  "ViewerArn": {
                    "Fn::If": [
                      "Enforce",
                      {
                        "Fn::GetAtt": [
                          "ViewerEnforce",
                          "FunctionARN"
                        ]
                      },
                      {
                        "Fn::GetAtt": [
                          "ViewerCount",
                          "FunctionARN"
                        ]
                      }
                    ]
                  },
                  "CustomerApiDomain": {
                    "Fn::Select": [
                      2,
                      {
                        "Fn::Split": [
                          "/",
                          {
                            "Fn::GetAtt": [
                              "ApiUrl",
                              "FunctionUrl"
                            ]
                          }
                        ]
                      }
                    ]
                  }
                }
              ]
            }
          }
        },
        "LoggingConfig": {
          "LogGroup": {
            "Ref": "InstallerLogs"
          }
        }
      },
      "Condition": "AutomaticAttachment"
    },
    "Installation": {
      "Type": "Custom::WorldIdInstallation",
      "DependsOn": [
        "Setup",
        "ApiPermission",
        "ApiInvokePermission",
        "AssetsPolicyPermission",
        "ProtectedPaths"
      ],
      "Properties": {
        "ServiceToken": {
          "Fn::GetAtt": [
            "Installer",
            "Arn"
          ]
        },
        "Configuration": {
          "Fn::Sub": [
            "{\"stack_id\":\"${AWS::StackId}\",\"installation_id\":\"${InstallationId}\",\"distribution_id\":\"${DistributionId}\",\"web_acl_arn\":\"${WebAclArn}\",\"web_acl_owned\":${WebAclOwned},\"rule_group_arn\":\"${RuleGroupArn}\",\"rule_names\":[\"BlockAmbiguousPath\",\"BlockForgedMarker\",\"PolicyTrigger\",\"FlagByLabel\",\"ApiRate\",\"VerifyRate\"],\"viewer_arn\":\"${ViewerArn}\",\"rules_revision\":\"e4d54d59c1a7122437a83c560596c01fca6297967a1a987a9b9790db64f9075d\",\"api_rate\":\"${ApiRate}\",\"api_domain\":\"${CustomerApiDomain}\",\"assets_domain\":\"${AssetsBucket.RegionalDomainName}\",\"api_policy_id\":\"${ApiPolicy}\",\"assets_policy_id\":\"${AssetsPolicy}\",\"rollout\":\"${Rollout}\",\"api_oac_id\":\"${ApiOac}\",\"assets_oac_id\":\"${AssetsOac}\",\"asset_version\":\"a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8\",\"sdk_injection\":${SdkInjection}}",
            {
              "RuleGroupArn": {
                "Fn::GetAtt": [
                  "RuleGroup",
                  "Arn"
                ]
              },
              "WebAclArn": {
                "Fn::If": [
                  "CreateWebAcl",
                  {
                    "Fn::GetAtt": [
                      "WebAcl",
                      "Arn"
                    ]
                  },
                  {
                    "Ref": "WebAclArn"
                  }
                ]
              },
              "WebAclOwned": {
                "Fn::If": [
                  "CreateWebAcl",
                  true,
                  false
                ]
              },
              "ViewerArn": {
                "Fn::If": [
                  "Enforce",
                  {
                    "Fn::GetAtt": [
                      "ViewerEnforce",
                      "FunctionARN"
                    ]
                  },
                  {
                    "Fn::GetAtt": [
                      "ViewerCount",
                      "FunctionARN"
                    ]
                  }
                ]
              },
              "CustomerApiDomain": {
                "Fn::Select": [
                  2,
                  {
                    "Fn::Split": [
                      "/",
                      {
                        "Fn::GetAtt": [
                          "ApiUrl",
                          "FunctionUrl"
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "ProtectionPolicy": {
          "Paths": {
            "Ref": "AlwaysVerifiedPaths"
          }
        },
        "Release": "1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c",
        "ServiceTimeout": 3600
      },
      "Condition": "AutomaticAttachment"
    },
    "KeyRingStore": {
      "Type": "AWS::CloudFront::KeyValueStore",
      "Properties": {
        "Name": {
          "Fn::Sub": [
            "${AWS::StackName}-${StackIdPrefix}-wid",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "Comment": "World ID session key ring; the installation cookie secret is the source"
      }
    },
    "ViewerCount": {
      "Type": "AWS::CloudFront::Function",
      "DependsOn": [
        "Setup"
      ],
      "Properties": {
        "Name": {
          "Fn::Sub": [
            "${AWS::StackName}-${StackIdPrefix}-wid-count",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "AutoPublish": true,
        "FunctionCode": "import cf from\"cloudfront\";import crypto from\"crypto\";var MARKER=\"x-amzn-waf-wid\",SESSION_COOKIE=\"__Host-wid_s\",NEED_COOKIE=\"__Host-wid_need\",SESSION_LABEL=\"wid-session-v1\",KEY_RING_KEY=\"key_ring\",ambiguousPath=new RegExp(\"(^|/)\\\\.{1,2}([/;]|$)|//|\\\\\\\\|%(2[5def]|3[0-9]|[46][1-9a-f]|[57][0-9a]|5[cf]|7e|u)\",\"i\"),B64URL=/^[A-Za-z0-9_-]*$/,B64=/^[A-Za-z0-9+/]{43}=$/,INT=/^(0|[1-9][0-9]{0,15})$/,KID=/^[A-Za-z0-9_-]{1,32}$/;function single(entry){return entry===void 0||entry.multiValue!==void 0&&entry.multiValue.length>1?null:entry.value}function sameTag(a,b){if(a.length!==b.length)return!1;let diff=0;for(let i=0;i<a.length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0}function decode(s){if(!B64URL.test(s)||s.length%4===1)return null;let bytes=Buffer.from(s,\"base64url\");return bytes.toString(\"base64url\")===s?bytes.toString(\"utf8\"):null}function validSession(ring,value,host,now){let parts=value.split(\".\");if(parts.length!==2||parts[1].length!==43)return!1;let payload=decode(parts[0]);if(payload===null)return!1;let fields=payload.split(\"|\"),kid=fields[1];if(fields.length!==5||kid===void 0||!KID.test(kid))return!1;let key=Object.prototype.hasOwnProperty.call(ring.keys,kid)?ring.keys[kid]:void 0;if(typeof key!=\"string\")return!1;let tag=crypto.createHmac(\"sha256\",key).update(`${SESSION_LABEL}|${payload}`).digest(\"base64url\");return sameTag(tag,parts[1])&&fields[0]===\"s\"&&fields[2]===host&&INT.test(fields[3])&&Number(fields[3])>now}function respond(statusCode,statusDescription,headers,data){return headers[\"cache-control\"]={value:\"no-store\"},{statusCode:statusCode,statusDescription:statusDescription,headers:headers,body:{encoding:\"text\",data:data}}}function json(statusCode,statusDescription,error,headers){return headers[\"content-type\"]={value:\"application/json\"},headers[\"x-content-type-options\"]={value:\"nosniff\"},respond(statusCode,statusDescription,headers,JSON.stringify({error:error}))}function isTopLevelNavigation(req){let mode=single(req.headers[\"sec-fetch-mode\"]),dest=single(req.headers[\"sec-fetch-dest\"]);if(mode!==null||dest!==null)return mode===\"navigate\"&&dest===\"document\";let accept=single(req.headers.accept);return accept!==null&&accept.toLowerCase().indexOf(\"text/html\")>=0}async function handler(event){let req=event.request,flagged=req.headers[MARKER]!==void 0;return delete req.headers[MARKER],req;if(ambiguousPath.test(req.uri))return json(400,\"Bad Request\",\"ambiguous_path\",{});if(!flagged&&req.cookies[NEED_COOKIE]===void 0)return req;let ring;try{if(ring=await cf.kvs().get(KEY_RING_KEY,{format:\"json\"}),!ring||typeof ring.current!=\"string\"||!KID.test(ring.current)||typeof ring.keys!=\"object\"||ring.keys===null||Array.isArray(ring.keys)||!Object.prototype.hasOwnProperty.call(ring.keys,ring.current))throw new Error(\"invalid key ring\");for(let kid in ring.keys){let key=ring.keys[kid];if(!KID.test(kid)||typeof key!=\"string\"||!B64.test(key))throw new Error(\"invalid key ring\")}}catch(_error){return console.log(\"wid key_ring_unavailable\"),json(503,\"Service Unavailable\",\"unavailable\",{\"retry-after\":{value:\"5\"}})}let host=single(req.headers.host),session=single(req.cookies[SESSION_COOKIE]);if(host!==null&&session!==null&&validSession(ring,session,host,Math.floor(Date.now()/1e3)))return req;let headers={\"x-wid\":{value:\"challenge\"}};if(isTopLevelNavigation(req)){headers[\"content-type\"]={value:\"text/html; charset=utf-8\"},headers[\"x-content-type-options\"]={value:\"nosniff\"},headers[\"x-frame-options\"]={value:\"DENY\"},headers[\"referrer-policy\"]={value:\"no-referrer\"};let method=/^[A-Z]{3,7}$/.test(req.method)?req.method:\"GET\";return respond(403,\"Forbidden\",headers,`<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https://bridge.worldcoin.org; base-uri 'none'; form-action 'none'\">\n<meta name=\"robots\" content=\"noindex\">\n<title>Verify you are human</title>\n<link rel=\"stylesheet\" href=\"/__wid/assets/a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8/challenge.css\">\n</head>\n<body>\n<main id=\"wid-root\" data-method=\"WIDMETH\"></main>\n<noscript>JavaScript is required to verify with World ID.</noscript>\n<script src=\"/__wid/assets/a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8/loader.js\"></script>\n</body>\n</html>\n`.replace('data-method=\"WIDMETH\"',`data-method=\"${method}\"`))}let response=json(403,\"Forbidden\",\"wid_challenge\",headers);return response.cookies={},response.cookies[NEED_COOKIE]={value:\"1\",attributes:\"Max-Age=300; Path=/; Secure; HttpOnly; SameSite=Lax\"},response}",
        "FunctionConfig": {
          "Comment": "World ID session check (count) 1757196eabd6",
          "Runtime": "cloudfront-js-2.0",
          "KeyValueStoreAssociations": [
            {
              "KeyValueStoreARN": {
                "Fn::GetAtt": [
                  "KeyRingStore",
                  "Arn"
                ]
              }
            }
          ]
        }
      }
    },
    "ViewerEnforce": {
      "Type": "AWS::CloudFront::Function",
      "DependsOn": [
        "Setup"
      ],
      "Properties": {
        "Name": {
          "Fn::Sub": [
            "${AWS::StackName}-${StackIdPrefix}-wid-enforce",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "AutoPublish": true,
        "FunctionCode": "import cf from\"cloudfront\";import crypto from\"crypto\";var MARKER=\"x-amzn-waf-wid\",SESSION_COOKIE=\"__Host-wid_s\",NEED_COOKIE=\"__Host-wid_need\",SESSION_LABEL=\"wid-session-v1\",KEY_RING_KEY=\"key_ring\",ambiguousPath=new RegExp(\"(^|/)\\\\.{1,2}([/;]|$)|//|\\\\\\\\|%(2[5def]|3[0-9]|[46][1-9a-f]|[57][0-9a]|5[cf]|7e|u)\",\"i\"),B64URL=/^[A-Za-z0-9_-]*$/,B64=/^[A-Za-z0-9+/]{43}=$/,INT=/^(0|[1-9][0-9]{0,15})$/,KID=/^[A-Za-z0-9_-]{1,32}$/;function single(entry){return entry===void 0||entry.multiValue!==void 0&&entry.multiValue.length>1?null:entry.value}function sameTag(a,b){if(a.length!==b.length)return!1;let diff=0;for(let i=0;i<a.length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0}function decode(s){if(!B64URL.test(s)||s.length%4===1)return null;let bytes=Buffer.from(s,\"base64url\");return bytes.toString(\"base64url\")===s?bytes.toString(\"utf8\"):null}function validSession(ring,value,host,now){let parts=value.split(\".\");if(parts.length!==2||parts[1].length!==43)return!1;let payload=decode(parts[0]);if(payload===null)return!1;let fields=payload.split(\"|\"),kid=fields[1];if(fields.length!==5||kid===void 0||!KID.test(kid))return!1;let key=Object.prototype.hasOwnProperty.call(ring.keys,kid)?ring.keys[kid]:void 0;if(typeof key!=\"string\")return!1;let tag=crypto.createHmac(\"sha256\",key).update(`${SESSION_LABEL}|${payload}`).digest(\"base64url\");return sameTag(tag,parts[1])&&fields[0]===\"s\"&&fields[2]===host&&INT.test(fields[3])&&Number(fields[3])>now}function respond(statusCode,statusDescription,headers,data){return headers[\"cache-control\"]={value:\"no-store\"},{statusCode:statusCode,statusDescription:statusDescription,headers:headers,body:{encoding:\"text\",data:data}}}function json(statusCode,statusDescription,error,headers){return headers[\"content-type\"]={value:\"application/json\"},headers[\"x-content-type-options\"]={value:\"nosniff\"},respond(statusCode,statusDescription,headers,JSON.stringify({error:error}))}function isTopLevelNavigation(req){let mode=single(req.headers[\"sec-fetch-mode\"]),dest=single(req.headers[\"sec-fetch-dest\"]);if(mode!==null||dest!==null)return mode===\"navigate\"&&dest===\"document\";let accept=single(req.headers.accept);return accept!==null&&accept.toLowerCase().indexOf(\"text/html\")>=0}async function handler(event){let req=event.request,flagged=req.headers[MARKER]!==void 0;if(delete req.headers[MARKER],ambiguousPath.test(req.uri))return json(400,\"Bad Request\",\"ambiguous_path\",{});if(!flagged&&req.cookies[NEED_COOKIE]===void 0)return req;let ring;try{if(ring=await cf.kvs().get(KEY_RING_KEY,{format:\"json\"}),!ring||typeof ring.current!=\"string\"||!KID.test(ring.current)||typeof ring.keys!=\"object\"||ring.keys===null||Array.isArray(ring.keys)||!Object.prototype.hasOwnProperty.call(ring.keys,ring.current))throw new Error(\"invalid key ring\");for(let kid in ring.keys){let key=ring.keys[kid];if(!KID.test(kid)||typeof key!=\"string\"||!B64.test(key))throw new Error(\"invalid key ring\")}}catch(_error){return console.log(\"wid key_ring_unavailable\"),json(503,\"Service Unavailable\",\"unavailable\",{\"retry-after\":{value:\"5\"}})}let host=single(req.headers.host),session=single(req.cookies[SESSION_COOKIE]);if(host!==null&&session!==null&&validSession(ring,session,host,Math.floor(Date.now()/1e3)))return req;let headers={\"x-wid\":{value:\"challenge\"}};if(isTopLevelNavigation(req)){headers[\"content-type\"]={value:\"text/html; charset=utf-8\"},headers[\"x-content-type-options\"]={value:\"nosniff\"},headers[\"x-frame-options\"]={value:\"DENY\"},headers[\"referrer-policy\"]={value:\"no-referrer\"};let method=/^[A-Z]{3,7}$/.test(req.method)?req.method:\"GET\";return respond(403,\"Forbidden\",headers,`<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https://bridge.worldcoin.org; base-uri 'none'; form-action 'none'\">\n<meta name=\"robots\" content=\"noindex\">\n<title>Verify you are human</title>\n<link rel=\"stylesheet\" href=\"/__wid/assets/a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8/challenge.css\">\n</head>\n<body>\n<main id=\"wid-root\" data-method=\"WIDMETH\"></main>\n<noscript>JavaScript is required to verify with World ID.</noscript>\n<script src=\"/__wid/assets/a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8/loader.js\"></script>\n</body>\n</html>\n`.replace('data-method=\"WIDMETH\"',`data-method=\"${method}\"`))}let response=json(403,\"Forbidden\",\"wid_challenge\",headers);return response.cookies={},response.cookies[NEED_COOKIE]={value:\"1\",attributes:\"Max-Age=300; Path=/; Secure; HttpOnly; SameSite=Lax\"},response}",
        "FunctionConfig": {
          "Comment": "World ID session check (enforce) 1757196eabd6",
          "Runtime": "cloudfront-js-2.0",
          "KeyValueStoreAssociations": [
            {
              "KeyValueStoreARN": {
                "Fn::GetAtt": [
                  "KeyRingStore",
                  "Arn"
                ]
              }
            }
          ]
        }
      }
    },
    "ApiLogs": {
      "Type": "AWS::Logs::LogGroup",
      "DeletionPolicy": "RetainExceptOnCreate",
      "UpdateReplacePolicy": "Retain",
      "Properties": {
        "LogGroupName": {
          "Fn::Sub": [
            "/aws/lambda/${AWS::StackName}-${StackIdPrefix}-wid-api",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "RetentionInDays": 365
      }
    },
    "SetupLogs": {
      "Type": "AWS::Logs::LogGroup",
      "DeletionPolicy": "RetainExceptOnCreate",
      "UpdateReplacePolicy": "Retain",
      "Properties": {
        "LogGroupName": {
          "Fn::Sub": [
            "/aws/lambda/${AWS::StackName}-${StackIdPrefix}-wid-setup",
            {
              "StackIdPrefix": {
                "Fn::Select": [
                  0,
                  {
                    "Fn::Split": [
                      "-",
                      {
                        "Fn::Select": [
                          2,
                          {
                            "Fn::Split": [
                              "/",
                              {
                                "Ref": "AWS::StackId"
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        "RetentionInDays": 365
      }
    },
    "UsageTable": {
      "Type": "AWS::DynamoDB::Table",
      "DeletionPolicy": "RetainExceptOnCreate",
      "UpdateReplacePolicy": "Retain",
      "Properties": {
        "BillingMode": "PAY_PER_REQUEST",
        "DeletionProtectionEnabled": false,
        "PointInTimeRecoverySpecification": {
          "PointInTimeRecoveryEnabled": true
        },
        "SSESpecification": {
          "SSEEnabled": true
        },
        "AttributeDefinitions": [
          {
            "AttributeName": "pk",
            "AttributeType": "S"
          }
        ],
        "KeySchema": [
          {
            "AttributeName": "pk",
            "KeyType": "HASH"
          }
        ],
        "TimeToLiveSpecification": {
          "AttributeName": "ttl",
          "Enabled": true
        }
      }
    },
    "AssetsBucket": {
      "Type": "AWS::S3::Bucket",
      "DeletionPolicy": "RetainExceptOnCreate",
      "UpdateReplacePolicy": "Retain",
      "Properties": {
        "BucketEncryption": {
          "ServerSideEncryptionConfiguration": [
            {
              "ServerSideEncryptionByDefault": {
                "SSEAlgorithm": "AES256"
              }
            }
          ]
        },
        "VersioningConfiguration": {
          "Status": "Enabled"
        },
        "PublicAccessBlockConfiguration": {
          "BlockPublicAcls": true,
          "BlockPublicPolicy": true,
          "IgnorePublicAcls": true,
          "RestrictPublicBuckets": true
        },
        "OwnershipControls": {
          "Rules": [
            {
              "ObjectOwnership": "BucketOwnerEnforced"
            }
          ]
        }
      }
    },
    "AssetsPolicyPermission": {
      "Type": "AWS::S3::BucketPolicy",
      "Properties": {
        "Bucket": {
          "Ref": "AssetsBucket"
        },
        "PolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "cloudfront.amazonaws.com"
              },
              "Action": "s3:GetObject",
              "Resource": {
                "Fn::Sub": "${AssetsBucket.Arn}/*"
              },
              "Condition": {
                "StringEquals": {
                  "AWS:SourceArn": {
                    "Fn::Sub": "arn:aws:cloudfront::${AWS::AccountId}:distribution/${DistributionId}"
                  }
                }
              }
            },
            {
              "Effect": "Deny",
              "Principal": "*",
              "Action": "s3:*",
              "Resource": [
                {
                  "Fn::GetAtt": [
                    "AssetsBucket",
                    "Arn"
                  ]
                },
                {
                  "Fn::Sub": "${AssetsBucket.Arn}/*"
                }
              ],
              "Condition": {
                "Bool": {
                  "aws:SecureTransport": "false"
                }
              }
            }
          ]
        }
      }
    },
    "ApiOac": {
      "Type": "AWS::CloudFront::OriginAccessControl",
      "Properties": {
        "OriginAccessControlConfig": {
          "Name": {
            "Fn::Sub": "${AWS::StackName}-wid-api"
          },
          "OriginAccessControlOriginType": "lambda",
          "SigningBehavior": "always",
          "SigningProtocol": "sigv4"
        }
      }
    },
    "AssetsOac": {
      "Type": "AWS::CloudFront::OriginAccessControl",
      "Properties": {
        "OriginAccessControlConfig": {
          "Name": {
            "Fn::Sub": "${AWS::StackName}-wid-assets"
          },
          "OriginAccessControlOriginType": "s3",
          "SigningBehavior": "always",
          "SigningProtocol": "sigv4"
        }
      }
    },
    "ApiRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "lambda.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "Api",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "dynamodb:PutItem",
                    "dynamodb:UpdateItem"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "UsageTable",
                      "Arn"
                    ]
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "secretsmanager:GetSecretValue",
                  "Resource": {
                    "Ref": "CookieSecret"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "kms:Sign",
                    "kms:GetPublicKey"
                  ],
                  "Resource": {
                    "Ref": "RpSigningKeyArn"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "ApiLogs",
                      "Arn"
                    ]
                  }
                }
              ]
            }
          }
        ],
        "PermissionsBoundary": {
          "Fn::If": [
            "HasPermissionsBoundary",
            {
              "Ref": "PermissionsBoundaryArn"
            },
            {
              "Ref": "AWS::NoValue"
            }
          ]
        }
      }
    },
    "CustomerApi": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "FunctionName": {
          "Fn::Sub": "${AWS::StackName}-wid-api"
        },
        "Runtime": "nodejs24.x",
        "Handler": "index.handler",
        "Timeout": 30,
        "MemorySize": 256,
        "Architectures": [
          "arm64"
        ],
        "Role": {
          "Fn::GetAtt": [
            "ApiRole",
            "Arn"
          ]
        },
        "Code": {
          "S3Bucket": "world-id-bot-prevention-production-releases-558948635617",
          "S3Key": "releases/1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c/customer-api.zip"
        },
        "Environment": {
          "Variables": {
            "WID_CUSTOMER_CONFIG": {
              "Fn::Sub": [
                "{\"installation_id\":\"${InstallationId}\",\"app_id\":\"${AppId}\",\"rp_id\":\"${RpId}\",\"hosts\":${HostsJson},\"environment\":\"${WorldIdEnvironment}\",\"window_seconds\":${WindowSeconds},\"requests_per_minute\":${RequestsPerMinute},\"credentials\":[\"${Credentials}\"],\"nullifier_table\":{\"name\":\"${UsageTable}\",\"region\":\"us-east-1\"},\"secrets\":{\"region\":\"us-east-1\",\"key_ring_id\":\"${CookieSecret}\",\"signing_key_id\":\"${RpSigningKeyArn}\"}}",
                {
                  "HostsJson": {
                    "Fn::GetAtt": [
                      "Setup",
                      "HostsJson"
                    ]
                  }
                }
              ]
            }
          }
        },
        "LoggingConfig": {
          "LogGroup": {
            "Ref": "ApiLogs"
          }
        },
        "ReservedConcurrentExecutions": {
          "Fn::If": [
            "ReserveApi",
            {
              "Ref": "ApiConcurrency"
            },
            {
              "Ref": "AWS::NoValue"
            }
          ]
        }
      }
    },
    "ApiUrl": {
      "Type": "AWS::Lambda::Url",
      "Properties": {
        "TargetFunctionArn": {
          "Fn::GetAtt": [
            "CustomerApi",
            "Arn"
          ]
        },
        "AuthType": "AWS_IAM"
      }
    },
    "ApiPermission": {
      "Type": "AWS::Lambda::Permission",
      "Properties": {
        "FunctionName": {
          "Ref": "CustomerApi"
        },
        "Action": "lambda:InvokeFunctionUrl",
        "Principal": "cloudfront.amazonaws.com",
        "SourceArn": {
          "Fn::Sub": "arn:aws:cloudfront::${AWS::AccountId}:distribution/${DistributionId}"
        },
        "FunctionUrlAuthType": "AWS_IAM"
      }
    },
    "ApiInvokePermission": {
      "Type": "AWS::Lambda::Permission",
      "Properties": {
        "FunctionName": {
          "Ref": "CustomerApi"
        },
        "Action": "lambda:InvokeFunction",
        "Principal": "cloudfront.amazonaws.com",
        "SourceArn": {
          "Fn::Sub": "arn:aws:cloudfront::${AWS::AccountId}:distribution/${DistributionId}"
        },
        "InvokedViaFunctionUrl": true
      }
    },
    "SetupRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "lambda.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "Setup",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "secretsmanager:GetSecretValue",
                    "secretsmanager:PutSecretValue"
                  ],
                  "Resource": {
                    "Ref": "CookieSecret"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "cloudfront:GetDistribution",
                  "Resource": {
                    "Fn::Sub": "arn:aws:cloudfront::${AWS::AccountId}:distribution/${DistributionId}"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "cloudformation:DescribeStackResource",
                    "cloudformation:DescribeStacks"
                  ],
                  "Resource": {
                    "Ref": "AWS::StackId"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "s3:ListBucketVersions",
                  "Resource": {
                    "Fn::GetAtt": [
                      "AssetsBucket",
                      "Arn"
                    ]
                  },
                  "Condition": {
                    "StringLike": {
                      "s3:prefix": "__wid/assets/*"
                    }
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "s3:DeleteObjectVersion",
                  "Resource": {
                    "Fn::Sub": "${AssetsBucket.Arn}/__wid/assets/*"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "s3:ListBucket",
                  "Resource": "arn:aws:s3:::world-id-bot-prevention-production-releases-558948635617",
                  "Condition": {
                    "StringLike": {
                      "s3:prefix": "releases/1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c/*"
                    }
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": "s3:GetObject",
                  "Resource": "arn:aws:s3:::world-id-bot-prevention-production-releases-558948635617/releases/1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c/*"
                },
                {
                  "Effect": "Allow",
                  "Action": "s3:PutObject",
                  "Resource": {
                    "Fn::Sub": "${AssetsBucket.Arn}/__wid/assets/a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8/*"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "cloudfront-keyvaluestore:DescribeKeyValueStore",
                    "cloudfront-keyvaluestore:PutKey"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "KeyRingStore",
                      "Arn"
                    ]
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "SetupLogs",
                      "Arn"
                    ]
                  }
                }
              ]
            }
          }
        ],
        "PermissionsBoundary": {
          "Fn::If": [
            "HasPermissionsBoundary",
            {
              "Ref": "PermissionsBoundaryArn"
            },
            {
              "Ref": "AWS::NoValue"
            }
          ]
        }
      }
    },
    "CustomerSetup": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "FunctionName": {
          "Fn::Sub": "${AWS::StackName}-wid-setup"
        },
        "Runtime": "nodejs24.x",
        "Handler": "index.handler",
        "Timeout": 180,
        "MemorySize": 256,
        "Architectures": [
          "arm64"
        ],
        "Role": {
          "Fn::GetAtt": [
            "SetupRole",
            "Arn"
          ]
        },
        "Code": {
          "S3Bucket": "world-id-bot-prevention-production-releases-558948635617",
          "S3Key": "releases/1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c/customer-setup.zip"
        },
        "Environment": {
          "Variables": {
            "WID_CUSTOMER_SETUP_CONFIG": {
              "Fn::Sub": "{\"stack_id\":\"${AWS::StackId}\",\"installation_id\":\"${InstallationId}\",\"app_id\":\"${AppId}\",\"rp_id\":\"${RpId}\",\"world_url\":\"https://botpreventionaws.worldcoin.org\",\"kms_key_arn\":\"${RpSigningKeyArn}\",\"web_acl_arn\":\"${WebAclArn}\",\"secret_arn\":\"${CookieSecret}\",\"kvs_arn\":\"${KeyRingStore.Arn}\",\"distribution_id\":\"${DistributionId}\",\"source_bucket\":\"world-id-bot-prevention-production-releases-558948635617\",\"asset_prefix\":\"releases/1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c/assets/\",\"destination_bucket\":\"${AssetsBucket}\",\"release\":\"1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c\",\"asset_version\":\"a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8\",\"release_files\":{\"assets/challenge.css\":\"d36a5fedf5ec0e8fc1c965963cdd0f08cae16f6ba2535be1bbaf5fec22f0d3d5\",\"assets/loader.js\":\"1b117f7868e499a3aa4a98e862721c9382284eb2069577d0411cfa3e867d957e\",\"assets/widget.79e804ad24613b963577.css\":\"79e804ad24613b9635774d8c7df8d16e0f01157750a4ee1fe7ce7dbb5d08cf15\",\"customer-installer.zip\":\"3c754af1af2dfb9599991eca74a6b95e1f0c5c7d5c6031510cf75365e7569043\",\"customer-api.zip\":\"1cb1a273e74ab4fcb44a886e448a23d10f4ba3c4a281835fdcba1900866c314e\",\"customer-setup.zip\":\"3e7ef3517af81010f55229e6a7abdd81ef07664abdaacd1b878ab994406763c8\",\"viewer-count.js\":\"d781c0def81046ab89c056a69fac2d91efc64037a3c5ce024ec81dc024bb5b3b\",\"viewer-enforce.js\":\"970161209a4230286c9fec117a30fe27a18cb88c98cf1d9f161c7f1ace38bc95\",\"template-revision.json\":\"9090f7f62246b198d09192c34b0d134d7a7718ca72ed47147a43c69af0803b23\"}}"
            }
          }
        },
        "LoggingConfig": {
          "LogGroup": {
            "Ref": "SetupLogs"
          }
        }
      }
    },
    "AlarmTopic": {
      "Type": "AWS::SNS::Topic",
      "Condition": "Notify",
      "Properties": {}
    },
    "AlarmEmail": {
      "Type": "AWS::SNS::Subscription",
      "Condition": "Notify",
      "Properties": {
        "TopicArn": {
          "Ref": "AlarmTopic"
        },
        "Protocol": "email",
        "Endpoint": {
          "Ref": "NotificationEmail"
        }
      }
    },
    "ApiErrors": {
      "Type": "AWS::CloudWatch::Alarm",
      "Properties": {
        "AlarmDescription": "World ID customer api failures; inspect customer logs",
        "AlarmActions": {
          "Fn::If": [
            "Notify",
            [
              {
                "Ref": "AlarmTopic"
              }
            ],
            []
          ]
        },
        "OKActions": {
          "Fn::If": [
            "Notify",
            [
              {
                "Ref": "AlarmTopic"
              }
            ],
            []
          ]
        },
        "Namespace": "AWS/Lambda",
        "MetricName": "Errors",
        "Dimensions": [
          {
            "Name": "FunctionName",
            "Value": {
              "Ref": "CustomerApi"
            }
          }
        ],
        "Statistic": "Sum",
        "Period": 300,
        "EvaluationPeriods": 1,
        "Threshold": 1,
        "ComparisonOperator": "GreaterThanOrEqualToThreshold",
        "TreatMissingData": "notBreaching"
      }
    },
    "VerifyRefusedMetric": {
      "Type": "AWS::Logs::MetricFilter",
      "Properties": {
        "LogGroupName": {
          "Ref": "ApiLogs"
        },
        "FilterPattern": "\"verify_admission_exhausted\"",
        "MetricTransformations": [
          {
            "MetricNamespace": "WorldId",
            "MetricName": {
              "Fn::Sub": "VerifyRefused-${InstallationId}"
            },
            "MetricValue": "1",
            "DefaultValue": 0
          }
        ]
      }
    },
    "VerifyRefused": {
      "Type": "AWS::CloudWatch::Alarm",
      "Properties": {
        "AlarmDescription": "World ID verifications refused because RequestsPerMinute is used up; check for a flood or raise the limit",
        "AlarmActions": {
          "Fn::If": [
            "Notify",
            [
              {
                "Ref": "AlarmTopic"
              }
            ],
            []
          ]
        },
        "OKActions": {
          "Fn::If": [
            "Notify",
            [
              {
                "Ref": "AlarmTopic"
              }
            ],
            []
          ]
        },
        "Namespace": "WorldId",
        "MetricName": {
          "Fn::Sub": "VerifyRefused-${InstallationId}"
        },
        "Statistic": "Sum",
        "Period": 300,
        "EvaluationPeriods": 1,
        "Threshold": 1,
        "ComparisonOperator": "GreaterThanOrEqualToThreshold",
        "TreatMissingData": "notBreaching"
      }
    }
  },
  "Outputs": {
    "InstallationId": {
      "Value": {
        "Ref": "InstallationId"
      }
    },
    "WorldIdApp": {
      "Value": {
        "Fn::Sub": "${AppId} ${RpId}"
      }
    },
    "Website": {
      "Condition": "AutomaticAttachment",
      "Value": {
        "Fn::Sub": [
          "https://${Domain}",
          {
            "Domain": {
              "Fn::GetAtt": [
                "Installation",
                "DistributionDomain"
              ]
            }
          }
        ]
      }
    },
    "Rollout": {
      "Value": {
        "Ref": "Rollout"
      }
    },
    "WorldIdEnvironment": {
      "Description": "World ID verification environment; sandbox accepts simulator proofs and blocks no bots",
      "Value": {
        "Ref": "WorldIdEnvironment"
      }
    },
    "TrafficMetricsUrl": {
      "Description": "Open AWS WAF, choose Global (CloudFront), select WebAclName, then Traffic overview. See RuleGroupName for World ID Bot Prevention rule metrics.",
      "Value": "https://console.aws.amazon.com/wafv2/homev2"
    },
    "WebAclArn": {
      "Value": {
        "Fn::If": [
          "CreateWebAcl",
          {
            "Fn::GetAtt": [
              "WebAcl",
              "Arn"
            ]
          },
          {
            "Ref": "WebAclArn"
          }
        ]
      }
    },
    "WebAclName": {
      "Value": {
        "Fn::If": [
          "CreateWebAcl",
          {
            "Fn::Sub": "wid-${InstallationId}-acl"
          },
          {
            "Fn::Select": [
              2,
              {
                "Fn::Split": [
                  "/",
                  {
                    "Ref": "WebAclArn"
                  }
                ]
              }
            ]
          }
        ]
      }
    },
    "RuleGroupName": {
      "Value": {
        "Fn::Sub": "${AWS::StackName}-wid"
      }
    },
    "InstallerLogGroupName": {
      "Condition": "AutomaticAttachment",
      "Value": {
        "Ref": "InstallerLogs"
      }
    },
    "ApiLogGroupName": {
      "Description": "Verification API logs: outcome codes for /start and /verify",
      "Value": {
        "Ref": "ApiLogs"
      }
    },
    "SetupLogGroupName": {
      "Value": {
        "Ref": "SetupLogs"
      }
    },
    "CookieSecretArn": {
      "Value": {
        "Ref": "CookieSecret"
      }
    },
    "KeyRingStoreArn": {
      "Value": {
        "Fn::GetAtt": [
          "KeyRingStore",
          "Arn"
        ]
      }
    },
    "Cleanup": {
      "Value": {
        "Fn::If": [
          "AutomaticAttachment",
          "Uninstall detaches World ID from CloudFront and WAF, deletes the session check functions and their key store, and retains keys, replay state, assets and the API, setup and installer logs. A failed first create removes its new resources, including the replay-state table, and retains installer logs. Retained log events expire after 365 days.",
          "Detach World ID through the owning website stack before deleting this resource stack."
        ]
      }
    },
    "AttachmentMode": {
      "Value": {
        "Ref": "AttachmentMode"
      }
    },
    "IntegrationConfig": {
      "Value": {
        "Fn::Sub": [
          "{\"stack_id\":\"${AWS::StackId}\",\"installation_id\":\"${InstallationId}\",\"distribution_id\":\"${DistributionId}\",\"web_acl_arn\":\"${WebAclArn}\",\"web_acl_owned\":${WebAclOwned},\"rule_group_arn\":\"${RuleGroupArn}\",\"rule_names\":[\"BlockAmbiguousPath\",\"BlockForgedMarker\",\"PolicyTrigger\",\"FlagByLabel\",\"ApiRate\",\"VerifyRate\"],\"viewer_arn\":\"${ViewerArn}\",\"rules_revision\":\"e4d54d59c1a7122437a83c560596c01fca6297967a1a987a9b9790db64f9075d\",\"api_rate\":\"${ApiRate}\",\"api_domain\":\"${CustomerApiDomain}\",\"assets_domain\":\"${AssetsBucket.RegionalDomainName}\",\"api_policy_id\":\"${ApiPolicy}\",\"assets_policy_id\":\"${AssetsPolicy}\",\"rollout\":\"${Rollout}\",\"api_oac_id\":\"${ApiOac}\",\"assets_oac_id\":\"${AssetsOac}\",\"asset_version\":\"a99e497ba18e62209732d59a21fe4c0f2c5b42326d7c302b2c245292e5943ef8\",\"sdk_injection\":${SdkInjection}}",
          {
            "RuleGroupArn": {
              "Fn::GetAtt": [
                "RuleGroup",
                "Arn"
              ]
            },
            "WebAclArn": {
              "Fn::If": [
                "CreateWebAcl",
                {
                  "Fn::GetAtt": [
                    "WebAcl",
                    "Arn"
                  ]
                },
                {
                  "Ref": "WebAclArn"
                }
              ]
            },
            "WebAclOwned": {
              "Fn::If": [
                "CreateWebAcl",
                true,
                false
              ]
            },
            "ViewerArn": {
              "Fn::If": [
                "Enforce",
                {
                  "Fn::GetAtt": [
                    "ViewerEnforce",
                    "FunctionARN"
                  ]
                },
                {
                  "Fn::GetAtt": [
                    "ViewerCount",
                    "FunctionARN"
                  ]
                }
              ]
            },
            "CustomerApiDomain": {
              "Fn::Select": [
                2,
                {
                  "Fn::Split": [
                    "/",
                    {
                      "Fn::GetAtt": [
                        "ApiUrl",
                        "FunctionUrl"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        ]
      }
    },
    "UsageTableName": {
      "Value": {
        "Ref": "UsageTable"
      }
    },
    "AssetsBucketName": {
      "Value": {
        "Ref": "AssetsBucket"
      }
    },
    "Release": {
      "Value": "1757196eabd645373f29529fb1e5c10c0e8084cc58ef8fa3426ccab1bb8f594c"
    },
    "Version": {
      "Value": "0.6.2"
    }
  }
}
