Skip to content

About

Terraform module: add x402 payments to paths of an existing CloudFront distribution (Lambda@Edge)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

terraform-aws-x402-edge

Add x402 payments to paths of an existing CloudFront distribution

Terraform module that creates a pair of Lambda@Edge functions implementing the x402 payment protocol (v2, EVM exact scheme), plus the cache and origin request policies a paid route needs. It does not create or own a distribution: you attach its outputs to the cache behaviors you want to charge for, and the origin behind them (S3, ALB, Lambda Function URL, anything) stays unaware of payments.

What this is — and is not

This module retrofits x402 onto resources you already serve through CloudFront: attach two edge functions to cache behaviors you own, and paths that were free are now paid — no origin changes, no server to run.

That's a deliberate trade. The flow is inline in the CDN request path (verify at origin-request, settle at origin-response), with no shared state between the two phases. So it does one thing well — gate existing paths — and nothing more.

If you need to customize the payment flow — idempotency, spend caps, rate limiting, step-up challenges, the auth-capture authorize→capture→void lifecycle, anything that must remember state between verify and settle — you've outgrown the retrofit. That belongs in a stateful payment runtime: a different case (new APIs, not retrofits), a separate module. See the ROADMAP.

Features

  • Plugs into any distribution — outputs lambda_function_associations for your own ordered_cache_behavior blocks
  • Verify, then settle on success — origin-request verifies the payment or returns 402; origin-response settles only when the origin answered < 400, so clients are not charged for failures
  • No edge build step — the handler bundle ships prebuilt; your config is rendered to config.json and added to the deployment zip at plan time
  • Config changes are plain applies — changing a price, payee or route publishes a new function version
  • Safe defaults enforced — CachingDisabled for paid behaviors and an origin request policy that forwards payment-signature
  • Discovery metadata per route — description, MIME type, service name, tags, icon and x402 extensions (e.g. Bazaar)
  • Keyed facilitators — Coinbase CDP via an API key held in Secrets Manager (facilitator_auth), read at runtime and never baked into the zip
  • Signed offers & receipts (opt-in) — sign a verifiable offer per accepts[] into the 402 and a receipt into PAYMENT-RESPONSE (offer_receipt); default off, additive, signing key in Secrets Manager

Usage

provider "aws" {
  alias  = "us_east_1"
  region = "us-east-1"
}

module "x402" {
  source  = "ql4b/x402-edge/aws"
  version = "~> 1.0"

  providers = { aws = aws.us_east_1 }

  facilitator_url = "https://facilitator.payai.network"
  network         = "eip155:8453" # Base mainnet
  pay_to          = "0xYourReceivingWallet"
  public_host     = "api.example.com"

  routes = {
    "/api/premium/*" = {
      price       = "$0.01"
      description = "Premium data, paid per request"
      mime_type   = "application/json"
    }
  }

  namespace = "myorg"
  name      = "api"
}

Then, in your distribution, add one behavior per paid path:

ordered_cache_behavior {
  path_pattern             = "/api/premium/*"
  target_origin_id         = "api"
  viewer_protocol_policy   = "https-only"
  allowed_methods          = ["GET", "HEAD", "OPTIONS"]
  cached_methods           = ["GET", "HEAD"]
  cache_policy_id          = module.x402.cache_policy_id
  origin_request_policy_id = module.x402.origin_request_policy_id

  dynamic "lambda_function_association" {
    for_each = module.x402.lambda_function_associations
    content {
      event_type   = lambda_function_association.value.event_type
      lambda_arn   = lambda_function_association.value.lambda_arn
      include_body = lambda_function_association.value.include_body
    }
  }
}

Tip: Always pin to a version constraint (e.g. version = "~> 1.0"). Browse available versions on the Terraform Registry page.

Requirements

  • Terraform >= 1.4 (uses terraform_data for the region guard)
  • AWS provider >= 6.0 (uses aws_region.region)
  • The module's AWS provider must be in us-east-1 (Lambda@Edge requirement); the plan fails otherwise
  • Your distribution must be managed in Terraform (or you attach the associations yourself)

How it works

viewer -> CloudFront (paid behavior, CachingDisabled)
            origin-request  : no/invalid payment  -> 402 + PAYMENT-REQUIRED
                              valid payment        -> forward to origin
            origin           : your backend, unchanged
            origin-response : origin < 400         -> settle, add PAYMENT-RESPONSE
                              origin >= 400        -> pass through, no charge

A client that already knows the terms may send PAYMENT-SIGNATURE on its first request; the 402 round trip is optional.

sequenceDiagram
    autonumber
    actor C as Client or agent
    participant CF as CloudFront (paid behavior)
    participant V as origin-request fn (verify)
    participant O as Your origin
    participant S as origin-response fn (settle)
    participant F as x402 facilitator (and chain)

    Note over C,V: 1 - Challenge
    C->>CF: request, no payment
    CF->>V: check payment
    V-->>CF: 402 with price and terms
    CF-->>C: 402

    Note over C,V: 2 - Verify
    C->>CF: request + signed payment
    CF->>V: check payment
    V->>F: verify
    F-->>V: valid
    V->>CF: forward to origin

    Note over CF,O: 3 - Origin
    CF->>O: the verified request
    O-->>CF: response

    Note over CF,F: 4 - Settle
    CF->>S: origin answered below 400
    S->>F: settle on chain
    F-->>S: settled
    S-->>CF: response + receipt header
    CF-->>C: 200 + response + PAYMENT-RESPONSE
Loading

Each phase has its own diagram, with the optional steps (facilitator_auth, supported_json, offer_receipt, secret_replica_reads) marked, in docs/request-flow.md.

Lambda@Edge has no environment variables. The module renders facilitator_url, network, pay_to, public_host and routes into config.json and zips it next to the generic handler (assets/edge/index.js). The handler fails at cold start if the config is missing or invalid, rather than serving the origin unpaid. Inspect the rendered file with the config_json output.

Facilitators

Unauthenticated facilitators such as https://facilitator.payai.network and https://x402.org/facilitator work as-is: set facilitator_url and nothing else.

Coinbase CDP (facilitator_auth)

The CDP facilitator requires every verify, settle and supported call to carry a JWT signed with a CDP Secret API key. Store the key in Secrets Manager and pass its ARN — never the value:

aws secretsmanager create-secret --region us-east-1 --name x402/cdp \
  --secret-string '{"apiKeyId":"<CDP key id>","apiKeySecret":"<CDP key secret>"}'
module "x402_edge" {
  # ...
  facilitator_url = "https://api.cdp.coinbase.com/platform/v2/x402"
  facilitator_auth = {
    type       = "cdp"
    secret_arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:x402/cdp-AbCdEf"
    # cache_ttl_seconds = 300
  }
}
  • Only the ARN is in the zip. Lambda@Edge has no environment variables and config.json ends up in state and in the deployment package, so the key is read at runtime with secretsmanager:GetSecretValue (the module adds that grant to the edge role) and reused for cache_ttl_seconds. A rotated key is picked up after the TTL, without a redeploy.
  • Both key types work: Ed25519 (base64) and EC P-256 (PEM). JWTs are signed in the handler with node:crypto, bound to the single request (uris: ["POST api.cdp.coinbase.com/platform/v2/x402/verify"]) and valid for 120 seconds.
  • Fails closed. If the secret cannot be read or parsed, origin-request returns 503 with Retry-After and never forwards to the origin. A failure at settle time returns 402 and the client is not charged.
  • Cold start cost. Each new container makes one GetSecretValue call to the secret's region, then an authenticated GET /supported. bake_supported is not available with facilitator_auth (the plan-time fetch is unauthenticated); pass supported_json instead to serve /supported from config and skip that call (a deploy-time snapshot: update it and apply if the facilitator changes what it advertises). Each fetch logs one line with the execution region and latency (x402 facilitator secret fetch).
  • Replicas. The grant covers this secret name in any region, so adding Secrets Manager replicas needs no IAM change. Reads go to the region in the ARN unless secret_replica_reads = true, which tries a replica in the execution region first and falls back to the ARN's region. Replicate the secret to the edge regions you serve before turning it on.
  • KMS. A secret encrypted with a customer managed key also needs kms:Decrypt on that key; attach it to role_arn yourself.
  • No IP allowlisting. Lambda@Edge calls out from shared AWS ranges in many regions, so do not rely on facilitator-side IP allowlists for this key.

A complete deployment, including creating the key and the secret, is in examples/cdp.

Signed offers & receipts (opt-in)

An opt-in x402 "Signed Offers & Receipts" capability. When enabled (offer_receipt.enabled = true), the edge functions sign an offer per accepts[] entry into the 402 body extensions, and a receipt into the PAYMENT-RESPONSE header on a settled 200 — portable proof-of-interaction artifacts a client can verify, audit, or dispute.

Default is off: offer_receipt = null (the default) means config.json gets no offerReceipt block, no extra IAM is granted, and the 402 challenge and settlement response are byte-identical to before. Enabling is purely additive; existing ~> 1.2 consumers are unaffected until they set the variable and move to ~> 1.3.

module "x402_edge" {
  # ...
  offer_receipt = {
    enabled                = true
    signing_key_secret_arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:x402/offer-receipt-signing-key-AbCdEf"
    # signer_did           = "did:web:api.example.com"        # defaults to did:web:x402.cloudless.sh
    # signer_kid           = "did:web:api.example.com#key-1"  # must equal the did.json verificationMethod id
    # include_tx_hash      = false
    # offer_validity_seconds = 300
    # cache_ttl_seconds    = 300
  }
}
  • Dedicated signing key, in Secrets Manager, pre-existing. The signing key MUST be a DEDICATED secp256k1 key, separate from pay_to (signing identity is not the payment address). Store the hex private key (0x-prefixed, or a JSON {"privateKey": "0x..."}) in Secrets Manager and pass its ARN. The secret MUST exist before you enable the feature. Only the ARN is written to config.json; the value is read at runtime with secretsmanager:GetSecretValue (enabling adds exactly one such grant, region-wildcarded like facilitator_auth) and never enters Terraform state or the bundle.

    aws secretsmanager create-secret --region us-east-1 \
      --name x402/offer-receipt-signing-key \
      --secret-string '0x<64-hex-char dedicated signing key>'
  • You must host /.well-known/did.json yourself. The module signs only; it does NOT emit the DID document. For EIP-712 the verifier recovers the signer ADDRESS from the signature and checks it against the address published in your DID doc, so you MUST host one at https://<signer_did host>/.well-known/did.json binding the signer key's address:

    {
      "@context": [
        "https://www.w3.org/ns/did/v1",
        "https://w3id.org/security/suites/secp256k1recovery-2020/v2"
      ],
      "id": "did:web:api.example.com",
      "verificationMethod": [{
        "id": "did:web:api.example.com#key-1",          // must equal signer_kid
        "type": "EcdsaSecp256k1RecoveryMethod2020",
        "controller": "did:web:api.example.com",
        "blockchainAccountId": "eip155:8453:0x<signer address>"   // CAIP-10, your chainId + signer address
      }],
      "assertionMethod": ["did:web:api.example.com#key-1"]
    }

    signer_kid is metadata for EIP-712 (the verifier does not resolve it), but it MUST equal the verificationMethod.id published here, and blockchainAccountId MUST carry the signer key's address. If they do not match, clients reject the signatures.

  • Format. Only format = "eip712" is implemented on this surface.

  • Cold-start cost. Enabling adds one cached GetSecretValue for the signing key on the first invocation of a container (reused for cache_ttl_seconds); signing itself is local CPU, no hot-path network call. The committed bundle uses a lean ox secp256k1 signer (not viem) to limit size growth.

  • include_tx_hash. When true, the receipt's transaction field carries the settlement transaction hash (the same value as PAYMENT-RESPONSE transaction). When false it is "". The field is always part of the signed EIP-712 receipt, so verifiers must accept either.

  • Receipts are best effort. A paid exchange spans three invocations: the 402 that issues the signed offer, the verify of the paid retry (origin-request) and settle (origin-response). They can run different function versions, and so different config.json, when a deploy lands in between. Settlement uses the receipt settings (include_tx_hash, offer_validity_seconds) in force at verify, carried in the internal pending-settlement header. If none were carried (offer-receipt was off at verify), the settling function uses its own settings when the feature is on there. A receipt is signed whenever the settling function has the feature on; if it is off there, no receipt is returned, since only a function with the feature on holds the signing key and its grant. Payment and the resource never depend on the receipt: a missing receipt does not mean the payment failed.

  • Key rotation. The receipt is signed with the settling function's key and signer_kid. While rotating, keep both keys in did.json until every edge location runs the new version.

Routes

routes is keyed by x402 route pattern:

Pattern Matches
/api/data exactly /api/data
/api/* /api and anything under it
/items/[id], /items/:id one path segment
GET /api/data only that verb

Requests that match no route pass through to the origin. The route decides which requests require payment; the CloudFront behavior decides which requests run the functions. Keep them covering the same paths. Note one difference: x402's /api/* also matches /api, CloudFront's /api/* does not.

Extensions differ in shape between routes, so pass them as a JSON string:

routes = {
  "/v1/data" = {
    price = "$0.001"
    extensions_json = jsonencode({
      bazaar = {
        info = {
          input  = { type = "http", method = "GET" }
          output = { example = { ok = true } }
        }
      }
    })
  }
}

Constraints

Caching must stay disabled on paid behaviors. The origin-request function only runs on a cache miss, so a cached paid response would be served without verification. Use cache_policy_id.

payment-signature must reach the function. The function sees only the headers the origin request policy forwards. Use origin_request_policy_id, or your own policy that includes payment-signature. Add headers your origin needs with forwarded_headers. After verification the function removes payment-signature from the request, so a verified request reaches the origin without it (the payment travels in the internal x-x402-pending-settlement header instead). Keep that in mind for origins with a small request header limit, such as Lambda Function URLs (about 10 KB).

One function per event type. A behavior that already has origin-request or origin-response Lambda@Edge associations cannot also take these.

Behavior order matters. CloudFront uses the first matching behavior, so paid patterns must precede broader patterns that match the same paths.

Paths must be canonical. Route matching uses the URI as received, so a request whose path is not in canonical form is rejected with 400 before any route is matched or the origin is reached: dot-segments (., ..), empty segments (//), backslashes, control characters, malformed percent-escapes, and percent-encoded dots, slashes, backslashes or percent signs (including double encoding). This keeps route matching and the origin in agreement about which resource a request names.

Settlement costs gas. The payer only signs (EIP-3009) and needs no ETH; the facilitator submits the transfer on-chain and fronts the gas. Whether that is free or billed depends on the facilitator you choose.

Destroy is slow. CloudFront must remove the edge replicas before the functions can be deleted, which can take hours. Retry a destroy that fails on the functions.

Logs are regional. Each replica logs to /aws/lambda/us-east-1.<function> in the region nearest the viewer (see function_names).

Outputs

  • lambda_function_associations — origin-request and origin-response associations (qualified ARNs) for your paid behaviors
  • cache_policy_id — managed CachingDisabled policy
  • origin_request_policy_id — policy forwarding payment-signature
  • route_patterns — configured route keys
  • config_json — the rendered config.json

Handler

The bundle in assets/edge/index.js is built from handler/ (TypeScript, adapted from the x402-foundation cloudfront-lambda-edge example). To rebuild after changing the handler:

cd handler && npm ci && npm run typecheck && npm run build

Requirements

Name Version
terraform >= 1.4
archive >= 2.4
aws >= 6.0
http >= 3.4

Providers

Name Version
archive >= 2.4
aws >= 6.0
http >= 3.4
terraform n/a

Modules

Name Source Version
this cloudposse/label/null 0.25.0

Resources

Name Type
aws_cloudfront_origin_request_policy.this resource
aws_iam_role.edge resource
aws_iam_role_policy.facilitator_secret resource
aws_iam_role_policy.offer_receipt_secret resource
aws_iam_role_policy_attachment.edge_basic resource
aws_lambda_function.edge resource
terraform_data.region_guard resource
archive_file.edge data source
aws_cloudfront_cache_policy.disabled data source
aws_region.current data source
http_http.supported data source

Inputs

Name Description Type Default Required
facilitator_url Base URL of the x402 facilitator that verifies and settles payments (e.g. https://facilitator.payai.network or https://x402.org/facilitator). The facilitator must advertise the exact scheme on network. Facilitators that require an API key need facilitator_auth (Coinbase CDP: https://api.cdp.coinbase.com/platform/v2/x402). It submits settlements on-chain and fronts the gas; whether that is free or billed depends on the facilitator. string n/a yes
network EVM network for payments, as a CAIP-2 id (e.g. eip155:8453 for Base mainnet, eip155:84532 for Base Sepolia). The bundled handler registers only the EVM exact scheme, so non-EVM networks are rejected. string n/a yes
pay_to Receiving wallet address (the seller). Every paid route settles to this address. string n/a yes
routes Payment-gated routes, keyed by x402 route pattern. Patterns are /path,
/path/* (trailing wildcard; also matches /path itself), /a/[id] or
/a/:id, with an optional verb prefix (GET /path). Requests that match no
route pass through to the origin untouched.

Each paid path must also be covered by a CloudFront cache behavior that uses
this module's lambda_function_associations, cache_policy_id and
origin_request_policy_id — the route decides which requests require
payment; the behavior decides which requests run the edge functions.

extensions_json is a JSON string (use jsonencode) because extension
objects differ in shape between routes, which a Terraform map type cannot
hold. It is emitted verbatim as the challenge extensions.
map(object({
price = string # e.g. "$0.001" (USD, resolved to the network's USDC)
description = optional(string) # shown in the challenge resource
mime_type = optional(string) # media type of the paid response
service_name = optional(string) # provider metadata for discovery listings
tags = optional(list(string)) # provider metadata for discovery listings
icon_url = optional(string) # provider metadata for discovery listings
max_timeout_seconds = optional(number) # authorization validity window
extensions_json = optional(string) # jsonencode()d x402 extensions, e.g. { bazaar = {...} }
}))
n/a yes
additional_tag_map Additional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.
map(string) {} no
attributes ID element. Additional attributes (e.g. workers or cluster) to add to id,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the delimiter
and treated as a single ID element.
list(string) [] no
bake_supported Fetch the facilitator's /supported response at plan time and bake it into
config.json, so the edge functions do not call GET /supported on cold
start. That call is the single blocking network round trip that dominates
Lambda@Edge cold-start latency; verify and settle still reach the
facilitator at request time.

Default false keeps the live fetch (current behaviour). When true, the
plan performs an HTTP GET to the facilitator's /supported endpoint, so it
must be reachable and unauthenticated at plan time (the same constraint the
handler already has). If the facilitator later stops advertising the
configured network/scheme, verify fails at request time until the next
apply re-bakes the value — the 402 challenge is unaffected.
bool false no
context Single object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables as null to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.
any
{
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}
no
delimiter Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
string null no
descriptor_formats Describe additional descriptors to be output in the descriptors output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
{<br/> format = string<br/> labels = list(string)<br/>}
(Type is any so the map values can later be enhanced to provide additional options.)
format is a Terraform format string to be passed to the format() function.
labels is a list of labels, in order, to pass to format() function.
Label values will be normalized before being passed to format() so they will be
identical to how they appear in id.
Default is {} (descriptors output will be empty).
any {} no
enabled Set to false to prevent the module from creating any resources bool null no
environment ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' string null no
facilitator_auth Authenticate to a facilitator that requires an API key. Null (default) calls
the facilitator unauthenticated.

type = "cdp": Coinbase CDP. The secret must be a JSON SecretString
{"apiKeyId": "...", "apiKeySecret": "..."} holding a CDP Secret API key
(Ed25519 base64 or EC P-256 PEM). Each verify/settle/supported call carries
a JWT signed with it, bound to that request and valid for 120 seconds.

Only the ARN is written to config.json. The edge functions read the value
with secretsmanager:GetSecretValue on first use and reuse it for
cache_ttl_seconds, so a rotated key is picked up without a redeploy. If
the secret cannot be read, origin-request answers 503 and never forwards to
the origin. The grant covers this secret name in any region (for future
replica reads); the value is read from the region in the ARN. A secret
encrypted with a customer managed KMS key also needs kms:Decrypt on that
key, which this module does not grant.

Not compatible with bake_supported (the plan-time /supported fetch is
unauthenticated).
object({
type = string # "cdp" (Coinbase CDP API key)
secret_arn = string # full Secrets Manager secret ARN
cache_ttl_seconds = optional(number, 300) # how long a fetched value is reused
})
null no
forward_cookies Whether the created origin request policy forwards all cookies to the origin. bool false no
forward_query_strings Whether the created origin request policy forwards all query strings to the origin. bool true no
forwarded_headers Additional viewer headers the created origin request policy forwards to the origin, on top of payment-signature (which the edge function needs and is always included). Leave empty for S3 origins. list(string) [] no
id_length_limit Limit id to this many characters (minimum 6).
Set to 0 for unlimited length.
Set to null for keep the existing setting, which defaults to 0.
Does not affect id_full.
number null no
label_key_case Controls the letter case of the tags keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via the tags input.
Possible values: lower, title, upper.
Default value: title.
string null no
label_order The order in which the labels (ID elements) appear in the id.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.
list(string) null no
label_value_case Controls the letter case of ID elements (labels) as included in id,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via the tags input.
Possible values: lower, title, upper and none (no transformation).
Set this to title and set delimiter to "" to yield Pascal Case IDs.
Default value: lower.
string null no
labels_as_tags Set of labels (ID elements) to include as tags in the tags output.
Default is to include all labels.
Tags with empty values will not be included in the tags output.
Set to [] to suppress all generated tags.
Notes:
The value of the name tag, if included, will be the id, not the name.
Unlike other null-label inputs, the initial setting of labels_as_tags cannot be
changed in later chained modules. Attempts to change it will be silently ignored.
set(string)
[
"default"
]
no
memory_size Memory (MB) for both edge functions. number 256 no
name ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as a tag.
The "name" tag is set to the full id string. There is no tag with the value of the name input.
string null no
namespace ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique string null no
offer_receipt Opt-in x402 "Signed Offers & Receipts". Null (default) ⇒ the feature is
entirely off: config.json gets no offerReceipt block, no new IAM is
granted, and the 402 challenge and settlement PAYMENT-RESPONSE are
byte-identical to today. Enabling it (enabled = true) makes the edge
functions sign an offer per accepts[] entry into the 402 body
extensions and a receipt into the PAYMENT-RESPONSE header on a settled
200.

signing_key_secret_arn MUST reference a DEDICATED signing key, SEPARATE
from pay_to. The secret holds a hex secp256k1 private key (0x-prefixed, or
a JSON `{"privateKey"
"signingKey": "0x..."}). Only the ARN is written to<br/>config.json; the value is read from Secrets Manager at runtime (same<br/>SigV4/aws4fetch mechanism as facilitator_auth) and never enters Terraform<br/>state. The secret MUST pre-exist; enabling grants the edge role one extra<br/>secretsmanager:GetSecretValue on this ARN (region-wildcarded for future<br/>replica reads), and nothing else.<br/><br/>format = "eip712"(the only value implemented here) uses secp256k1; the<br/>verifier recovers the signer ADDRESS from the signature. The MODULE SIGNS<br/>ONLY — it does NOT emit/.well-known/did.json. The consumer MUST host that<br/>DID document themselves, listing the signer address as a<br/>verificationMethod(typeEcdsaSecp256k1RecoveryMethod2020,<br/>blockchainAccountId = "eip155::") for signer_did, so<br/>clients know which address to trust. signer_kid (default<br/>did:web:x402.cloudless.sh#key-1`) must equal that verificationMethod id;
it is metadata for EIP-712 (the verifier does not resolve it) but MUST match
the published DID doc.
object({
enabled = optional(bool, false) # master opt-in switch
signing_key_secret_arn = string # dedicated signing key secret, NOT pay_to
format = optional(string, "eip712") # only "eip712" is implemented on this surface
signer_did = optional(string) # e.g. "did:web:api.example.com"
signer_kid = optional(string) # verificationMethod id in the DID doc
include_tx_hash = optional(bool, false) # include the on-chain txHash in the receipt
offer_validity_seconds = optional(number, 300) # offer validUntil window
cache_ttl_seconds = optional(number, 300) # signing-key secret cache, mirrors facilitator_auth
})
null
public_host Public host name advertised in the challenge resource.url (e.g. api.example.com). Lambda@Edge only sees the *.cloudfront.net distribution domain, so set this when the distribution has a custom alias. Leave null to advertise the CloudFront domain. string null no
regex_replace_chars Terraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.
string null no
runtime Node.js runtime for both edge functions. The bundled handler targets Node.js 22. string "nodejs22.x" no
secret_replica_reads Read the Secrets Manager secrets (facilitator_auth, offer_receipt) from a
replica in the region the edge function is executing in, falling back to the
region in the secret ARN. Lambda@Edge runs near the viewer, so without a
replica a cold container far from the secret pays a cross-region round trip
(~1.2 s measured eu-central-1 to us-east-1, versus ~0.5 s in-region).

Default false: reads go to the ARN's region only. Turn it on only after you
have added Secrets Manager replicas for the edge regions you serve; with no
replica the extra attempt only adds a fast failed call before the fallback.
A failed replica read is logged and the replica is skipped for 15 minutes
in that container, so a missing replica costs one failed call, not one per
refresh.
Replicas share the secret's name and ARN suffix, so the existing IAM grant
(any region) already covers them. A secret encrypted with a customer
managed KMS key needs kms:Decrypt on the replica's key too.

Rotation: replicas sync from the primary; a value read from a replica can
briefly lag a rotation. Credentials still expire after cache_ttl_seconds.
bool false no
stage ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' string null no
supported_json Operator-supplied facilitator /supported response, as a JSON string,
written into config.json so the edge functions do not call GET /supported
on cold start. Unlike bake_supported there is no plan-time HTTP request,
so it works with an authenticated facilitator (facilitator_auth).

Pass the response body you fetched yourself, or trim it to the kinds this
deployment uses, e.g.
jsonencode({ kinds = [{ x402Version = 2, scheme = "exact", network = "eip155:8453" }], extensions = [], signers = {} }).
It must contain a non-empty kinds array.

Staleness is the trade: the value is a deploy-time snapshot. If the
facilitator later stops advertising the configured network/scheme, verify
fails at request time until you update this value and apply — the 402
challenge is unaffected. Mutually exclusive with bake_supported.
string null no
tags Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string) {} no
tenant ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for string null no
timeout Timeout (seconds) for both edge functions. Covers the facilitator call on verify and settle. Origin-facing Lambda@Edge events allow up to 30 seconds. number 5 no

Outputs

Name Description
cache_policy_id ID of the managed CachingDisabled cache policy. Paid behaviors must use it: a cache hit skips the origin-request function and would serve paid content unverified.
config_json The rendered config.json shipped in the edge zip, for inspection and debugging.
function_names Names of the edge functions, keyed by event type. Logs are written to /aws/lambda/us-east-1. in the region nearest each viewer.
lambda_function_associations Lambda@Edge associations for each paid cache behavior: origin-request (verify) and origin-response (settle), as qualified (versioned) ARNs. Use with a dynamic lambda_function_association block.
origin_request_function_qualified_arn Qualified ARN of the origin-request (verify) function.
origin_request_policy_id ID of the origin request policy that forwards payment-signature (plus forwarded_headers) to the edge function and origin. Paid behaviors must use it or an equivalent that forwards payment-signature.
origin_response_function_qualified_arn Qualified ARN of the origin-response (settle) function.
role_arn ARN of the edge functions' execution role.
route_patterns The configured x402 route patterns (keys of var.routes). Each must be covered by a paid cache behavior.

License

Apache 2.0 — see LICENCE for details.

About

Terraform module: add x402 payments to paths of an existing CloudFront distribution (Lambda@Edge)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages