aperture

package module
v0.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 65 Imported by: 3 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

L402 (Lightning HTTP 402) API Key proxy

Aperture is your portal to the Lightning-Native Web. Aperture is used in production today by Lightning Loop, a non-custodial on/off ramp for the Lightning Network.

Aperture is a HTTP 402 reverse proxy that supports proxying requests for gRPC (HTTP/2) and REST (HTTP/1 and HTTP/2) backends using the L402 Protocol Standard. L402 is short for: the Lightning HTTP 402 protocol. L402 combines HTTP 402, macaroons, and the Lightning Network to create a new standard for authentication and paid services on the web.

L402 is a new standard protocol for authentication and paid APIs developed by Lightning Labs. L402 API keys can serve both as authentication, as well as a payment mechanism (one can view it as a ticket) for paid APIs. In order to obtain a token, we require the user to pay us over Lightning in order to obtain a preimage, which itself is a cryptographic component of the final L402 token

The implementation of the authentication token is chosen to be macaroons, as they allow us to package attributes and capabilities along with the token. This system allows one to automate pricing on the fly and allows for a number of novel constructs such as automated tier upgrades. In another light, this can be viewed as a global HTTP 402 reverse proxy at the load balancing level for web services and APIs.

Payment schemes

Aperture speaks two payment protocols, and a single 402 response can carry an offer for each so the buyer takes whichever door it understands.

L402 is the default and is described above: a macaroon plus the preimage of the invoice that paid for it.

The Payment HTTP Authentication Scheme (draft-httpauth-payment-00, co-authored by Stripe and Tempo) is enabled with --authenticator.enablempp. It supports two intents. A charge buys a single request, and a session (--authenticator.enablesessions) holds a deposit that many requests draw against, refunding whatever is left when the buyer closes it. Sessions and charge consumption records both need a real database, so --dbbackend must be sqlite or postgres; etcd is refused at startup.

A Payment credential cannot be presented after its challenge expires, which is 15 minutes after the challenge is minted unless --authenticator.mppchallengeexpiry says otherwise. On a metered service one payment buys a usage bundle that is spent down over many requests, so the expiry caps how long the bundle stays usable. Set it near the service timeout (for example 720h), as an L402 token on the same service already lasts that long. Single-use charges on other services stay single use.

Each Payment challenge binds its HMAC to the exact resource that Aperture priced. For a dynamic-price service, that resource includes the request path. A credential issued for one resource is refused when a client presents it for another.

A request authenticated with a Payment credential carries no L402 identity: Aperture removes any L402 it also presents, in Authorization or in the Macaroon and Grpc-Metadata-Macaroon headers, before rate limiting, metering or forwarding it, since nothing verified that token.

Public paths

authwhitelistpaths allows anonymous access within an authenticated service. L402 authentication is checked but not required. Successful requests retain the usual header-forwarding behavior. If authentication fails, Aperture removes Authorization, Macaroon, and Grpc-Metadata-Macaroon before forwarding the request anonymously. The same cleanup applies to anonymous freebie and zero-price fallbacks. On services with authentication enabled, Aperture always removes client-supplied Grpc-Metadata-Authorization; grpc-gateway would otherwise translate it into unvalidated authorization metadata.

Public paths only validate L402. They do not execute MPP payment actions, issue payment challenges, or incur metered charges. For dynamically priced services, a valid token for another resource in the same service can establish identity on a public path. Protected paths still require a token for the exact resource.

Credential cleanup removes the entire Authorization header, including Bearer and Basic values. Use service-level auth: "off" when the backend owns authentication; that setting bypasses both validation and credential removal.

On any authenticated request, Aperture removes L402 macaroons from the Macaroon and Grpc-Metadata-Macaroon headers unless the verified credential was read from that header, even ones naming the verified token, since nothing checked their signatures or caveats. Other macaroons, such as lnd's, are forwarded unchanged.

Request paths

Aperture first cleans the request path as the client escaped it: it drops empty segments and . segments, written plainly or percent-encoded, and keeps every other segment exactly as sent. It then matches services, whitelisted paths, prices and rate limits against the decoded form of the cleaned path, and forwards the escaped form, so a percent-encoded character reaches the backend as the client sent it. Decoding happens after cleaning, so separators introduced by decoding are preserved in the path used for matching.

A path with a .. segment is refused with 400, and so is one containing a character that some backends normalize in a way that would change which resource it names. A request target that is not an absolute path (anything other than OPTIONS *) is refused as well.

A percent-encoded separator such as %2F is a path separator to Aperture, but some backends (grpc-gateway, chi, Go's ServeMux and others) treat it as part of a single segment. Write service and whitelist patterns so they still match when a segment is encoded this way, for example by matching a prefix rather than counting segments. Dynamic-price tokens are named from the decoded path, so the encoded and decoded spellings of a path map to the same token.

Metered pricing

Aperture can sell one request per payment, or it can sell a prepaid bundle of usage and draw it down as requests flow. The second mode exists because a fixed price per request is the wrong unit for LLM inference: one completion costs the seller a few dozen upstream tokens and the next costs four thousand, and the seller only learns which after the response has been served.

Metering splits the two apart. The payment happens once, up front, for a bundle at a known price. The accounting happens per request, after the fact, from the usage the upstream actually reported. Aperture holds no pricing or balance state of its own; it calls out to a price server over gRPC (pricesrpc), configured per service with dynamicprice and metered: true. The reference price server, meterd, ships in this repo and keeps its state in a JSON file, which is enough for development. Production deployments embed meterd.Server behind their own Store and RateSource.

Streamed responses work the same way: aperture keeps a bounded tail of the response so it can read the usage out of the final SSE chunk, and applies writetimeout as a rolling idle window rather than an absolute deadline so a generation lives as long as it keeps flowing. Size that window to the worst gap between chunks, not to the total length of the stream.

docs/metering.md covers all of this in full: the bundle lifecycle, how L402 and each Payment intent attribute usage to a balance, what changes under streaming, and the configuration reference.

Installation / Setup

lnd

  • Make sure lnd ports are reachable.
  • No Lightning node? Aperture can create its invoices from a Wavelength wallet instead; see docs/wavelength.md.

aperture

  • Compilation requires Go 1.25 or later.
  • To build both aperture and aperturecli, run make build. To install them into your $GOPATH/bin, run make install.
  • Make sure port 8081 is reachable from outside (or whatever port you choose).
  • Make sure there is a valid tls.cert and tls.key file located in the ~/.aperture directory that is valid for the domain that aperture is running on. Aperture doesn't support creating its own certificate through Let's Encrypt yet. If there is no tls.cert and tls.key found, a self-signed pair will be created.
  • If Aperture is behind a TLS-terminating load balancer/ingress, make sure the load balancer's ALPN policy advertises h2 (for example, AWS NLB HTTP2Preferred or HTTP2Only). Some gRPC clients fail with missing selected ALPN property if no ALPN protocol is negotiated. On AWS NLB, the default ALPN policy is None, which does not negotiate ALPN. If you use TCP passthrough instead of TLS termination at the load balancer, Aperture negotiates ALPN directly.
  • Make sure all required configuration items are set in ~/.aperture/aperture.yaml, compare with sample-conf.yaml.
  • Start aperture without any command line parameters (./aperture), all configuration is done in the ~/.aperture/aperture.yaml file.

Upgrading

Changes that need attention when upgrading from an earlier version:

  • Payment credentials created by an older Aperture carry no resource binding and are refused after the upgrade, even if the invoice was paid. Clients must fetch and pay a fresh challenge. Account for outstanding Payment challenges when scheduling the upgrade.

  • Service names can no longer contain / or =. A slash could overlap the token namespace of another dynamic-price service, and an equal sign cannot be read back from the condition of a capabilities caveat. Startup fails on such a service, including one stored in the database, where the admin API cannot rename it once Aperture refuses to start. Rename it before upgrading.

  • A service's auth value must be on, off, true, false, or freebie N with N from 1 to 65535; anything else now fails startup. An unrecognized value such as no used to make the service free. The admin API used to accept and store a larger freebie count, so correct such a value before upgrading.

  • A dynamic-price token whose resource name (its service_name) contains a , may have been minted authorizing more than the one resource. Such tokens are no longer minted, but upgrading does not invalidate existing ones; revoke them. With a sqlite or postgres backend, list tokens with GET /api/admin/tokens and revoke each one whose service_name contains , with DELETE /api/admin/tokens/{token_id}. Only settled tokens are listed, and settlements are recorded only while the admin API is enabled; enabling it reconciles earlier payments at the next startup. Tokens minted without a transaction record, by the etcd backend or by versions before v0.5.0, cannot be found this way.

  • A dynamic-price service, or a static one whose price was not configured or was changed through the admin API, minted tokens without its timeout, capabilities and constraints, so with a timeout set they never expired. New tokens carry these restrictions, but existing ones do not; revoke them through the admin API as described above. A dynamic-price token's service_name is the service name followed by the request path.

  • On a service with a timeout, a resource name containing = cannot carry a readable timeout caveat, so no token is minted for it.

  • Services that share a name also share their tokens, so startup now fails if they set different timeout, capabilities or constraints.

  • Request paths are now cleaned as sent, with . segments and repeated slashes removed, before they are matched and forwarded, and percent-encoded characters keep their encoding. A path with a .. segment is refused with 400, and so is a request target that is not an absolute path (other than OPTIONS *).

  • A path containing a character that some backends normalize in a way that would change which resource it names is refused with 400.

  • The config file keys sqlite.dbfile, postgres.maxconnections and admin.corsorigin are now read. Earlier versions read other names for them and silently ignored these, so a deployment that sets one of them may behave differently after the upgrade. The old names are rejected at startup with an error that names the replacement:

    Old key New key
    sqlite.databasefilename sqlite.dbfile
    postgres.maxopenconnections postgres.maxconnections
    admin.corsorigins admin.corsorigin

    admin.corsorigin must be a list: a single string fails with string was used where sequence is expected. A leading ~/ in sqlite.dbfile is expanded to the home directory.

  • Because sqlite.dbfile was ignored, an existing database may sit at the default path (the aperture.db file in the aperture data directory, whose location depends on the platform) rather than at the configured one. If sqlite.dbfile names a missing file while a database exists at the default path, startup fails and the error message prints both paths. There are two supported ways to proceed: stop aperture and move the database, together with its -wal and -shm files, to the configured path, or unset sqlite.dbfile to keep using the default path. Do not create an empty file at the configured path to get past the check. The check only looks for the file, so an empty file starts a new database and the secrets of every L402 issued so far are lost.

  • postgres.requireSSL, from the old sample config, was never read, so aperture connected to postgres without SSL. Startup now fails on it; use postgres.requiressl, which requires SSL when set to true.

Admin API

Aperture ships with an optional gRPC and REST admin API for managing services at runtime, querying transaction history, and monitoring revenue. Enable it by adding an admin section to your config:

admin:
  enabled: true
  macaroonpath: "/path/to/admin.macaroon"  # defaults to ~/.aperture/admin.macaroon

On first startup Aperture generates a random root key and writes an admin macaroon to the configured path. All admin endpoints (except health) require this macaroon for authentication, passed as hex-encoded gRPC metadata or an HTTP header.

The admin API exposes ten RPCs covering the full lifecycle of the proxy:

RPC REST Description
GetHealth GET /api/admin/health Health check (no auth required)
GetInfo GET /api/admin/info Server info: network, listen address, TLS status
ListServices GET /api/admin/services List all proxied backend services
CreateService POST /api/admin/services Register a new service with pricing and auth
UpdateService PUT /api/admin/services/{name} Update service config (pricing, address, auth)
DeleteService DELETE /api/admin/services/{name} Remove a service
ListTransactions GET /api/admin/transactions Query L402 transactions with filters
ListTokens GET /api/admin/tokens List issued L402 tokens
RevokeToken DELETE /api/admin/tokens/{token_id} Revoke a token
GetStats GET /api/admin/stats Revenue statistics with per-service breakdown

Services created through the admin API are persisted to the database and survive restarts. Changes take effect immediately — the proxy's routing table is updated in-place, so you can adjust pricing or swap backends without downtime.

See docs/admin-api.md for full configuration details.

Dashboard

When built with the dashboard build tag (make build-withdashboard), Aperture embeds a Next.js web dashboard served at the root path. The dashboard provides a visual interface for everything the admin API exposes: service management, transaction history with filtering and pagination, revenue charts, and token administration.

The dashboard communicates with the admin API through a server-side proxy that injects the macaroon automatically, so no client-side credentials are needed. Access is restricted to loopback connections for security.

See docs/dashboard.md for setup and screenshots.

CLI (aperturecli)

aperturecli is a standalone command-line tool for the admin gRPC API. It connects directly over gRPC (not REST) and authenticates with the same admin macaroon.

# Install
make install

# Basic usage
aperturecli --insecure health
aperturecli --insecure services list
aperturecli --insecure services create --name myapi --address 127.0.0.1:8080 --price 100
aperturecli --insecure services update --name myapi --price 500
aperturecli --insecure stats

The CLI is designed to work well for both humans and AI agents. When stdout is a TTY it renders tables; when piped it emits JSON. Errors carry semantic exit codes (connection failure, auth failure, not found, etc.) and structured JSON on stderr, so scripts and agents can branch on the exit code without parsing error text.

A schema command dumps the full command tree as machine-readable JSON for agent discovery:

aperturecli schema --all

All mutating commands support --dry-run, which prints the request that would be sent without actually calling the server.

See docs/cli.md for the full command reference.

MCP Server

aperturecli also embeds an MCP (Model Context Protocol) server, started with aperturecli mcp serve. This exposes every admin RPC as a typed tool over stdio JSON-RPC, letting agent frameworks like Claude Code manage Aperture directly. Add it to your MCP config:

{
  "mcpServers": {
    "aperture": {
      "command": "aperturecli",
      "args": ["--insecure", "mcp", "serve"]
    }
  }
}

See docs/mcp-server.md for setup details.

Rate Limiting

Aperture supports optional per-endpoint rate limiting using a token bucket algorithm. Rate limits are configured per service and applied based on the client's L402 token ID for authenticated requests, or IP address for unauthenticated requests.

Anonymous requests still obey IP-based limits when the pricer returns zero, including after a service's freebie allowance is exhausted.

On whitelisted paths, verified L402 tokens get their own rate-limit bucket. Anonymous requests and services with auth: "off" keep IP-based limits.

Requests authenticated with a Payment credential are limited by IP address.

Challenge Rate Limiting

Every 402 response mints invoices at the seller's invoice backend before anyone has paid: one for L402, and up to three with MPP and sessions enabled. A client that never pays still holds those invoices until they expire, so an unauthenticated client would otherwise decide how many unpaid invoices the seller holds. That matters most for a backend that caps unpaid invoices, like a Wavelength wallet with 32 pending receive intents: about eleven probes fill the cap, and challenges then fail for every client until the invoices expire.

Aperture therefore limits the challenges it issues per client network (the same masked source address the service rate limits use), before any invoice is minted. A client over the limit gets 429 with Retry-After and no invoice. The limit is on by default at 10 challenges per hour per client network, so one network holds at most 30 unpaid invoices. It covers every service. Tune or disable it at the top level of aperture.yaml:

challengeratelimit:
  requests: 10   # Challenges per window per client network. 0 disables.
  per: 1h
  burst: 10      # Defaults to requests.

This bounds a single network, not a botnet spread over many networks. Raise requests for a seller with many honest buyers behind one NAT.

Behind a reverse proxy

By default Aperture identifies a client by the TCP peer address. Behind a reverse proxy on the same host that address is the proxy for every request, so all clients would share one bucket, and one scanner would use up the 10 challenges for every real buyer. The blocklist, the per-service rate limits and freebies are keyed the same way and have the same problem.

Set trustedproxies to the address of the proxy, as IPs or CIDRs, so that Aperture reads the client from X-Forwarded-For:

trustedproxies:
  - "127.0.0.1"

The header is only read when the TCP peer is one of the trusted proxies. It is then read from right to left. A proxy appends the address it saw to the end of the header, after any value the client sent, so the rightmost entry is the one the proxy vouches for and entries to its left can be forged. Entries that are themselves trusted proxies are skipped, and the first other entry that parses as an IP is the client. With no usable entry the peer address is used. The resolved address is the one the blocklist, rate limits, freebies and logs all see. The list is empty by default, which trusts no header, and Aperture logs a warning at startup if the challenge limit is on, it listens on a loopback address and trustedproxies is empty. Only list proxies that overwrite or append to X-Forwarded-For as described, and that are the only way to reach Aperture, since a header from any other peer in the list is believed.

Features
  • Token bucket algorithm: Allows controlled bursting while maintaining a steady-state request rate.
  • Per-client isolation: Each L402 token ID or IP address has independent rate limit buckets.
  • Path-based rules: Different endpoints can have different rate limits using regular expressions.
  • Multiple rules: All matching rules are evaluated; if any rule denies the request, it is rejected. This allows layering global and endpoint-specific limits.
  • Protocol-aware responses: Returns HTTP 429 with Retry-After header for REST requests, and gRPC ResourceExhausted status for gRPC requests.
Configuration

Rate limits are configured in the ratelimits section of each service:

services:
  - name: "myservice"
    hostregexp: "api.example.com"
    address: "127.0.0.1:8080"
    protocol: https

    ratelimits:
      # Global rate limit for all endpoints
      - requests: 100    # Requests allowed per time window
        per: 1s          # Time window duration (1s, 1m, 1h, etc.)
        burst: 100       # Max burst capacity (defaults to 'requests')

      # Stricter limit for expensive endpoints
      - pathregexp: '^/api/v1/expensive.*$'
        requests: 5
        per: 1m
        burst: 5

This example configures two rate limit rules using a token bucket algorithm. Each client gets a "bucket" of tokens that refills at the requests/per rate, up to the burst capacity. A request consumes one token; if no tokens are available, the request is rejected. This allows clients to make quick bursts of requests (up to burst) while enforcing a steady-state rate limit over time.

  1. Global limit: All endpoints are limited to 100 requests per second per client, with a burst capacity of 100.
  2. Endpoint-specific limit: Paths matching /api/v1/expensive.* have a stricter limit of 5 requests per minute with a burst of 5. Since both rules are evaluated, requests to expensive endpoints must satisfy both limits.
Configuration Options
Option Description Required
pathregexp Regular expression to match request paths. If omitted, matches all paths. No
requests Number of requests allowed per time window. Yes
per Time window duration (e.g., 1s, 1m, 1h). Yes
burst Maximum burst size. Defaults to requests if not set. No

Documentation

Index

Constants

View Source
const (
	// DefaultMsgRate is the default message rate for a given mailbox that
	// we'll allow. We'll allow one message every 500 milliseconds, or 2
	// messages per second.
	DefaultMsgRate = time.Millisecond * 500

	// DefaultMsgBurstAllowance is the default burst rate that we'll allow
	// for messages. If a new message is about to exceed the burst rate,
	// then we'll allow it up to this burst allowance.
	DefaultMsgBurstAllowance = 10

	// DefaultStaleTimeout is the time after which a mailbox will be torn
	// down if neither of its streams are occupied.
	DefaultStaleTimeout = time.Hour

	// DefaultBufSize is the default number of bytes that are read in a
	// single operation.
	DefaultBufSize = 4096
)
View Source
const Subsystem = "APER"

Variables

This section is empty.

Functions

func DashboardFS added in v0.5.0

func DashboardFS() (fs.FS, error)

DashboardFS returns nil when the dashboard is not embedded.

func DefaultSqliteConfig

func DefaultSqliteConfig() *aperturedb.SqliteConfig

DefaultSqliteConfig returns the default configuration for a sqlite backend.

func Main

func Main()

Main is the true entrypoint of Aperture.

func SetupLoggers

func SetupLoggers(root *build.SubLoggerManager, intercept signal.Interceptor)

SetupLoggers initializes all package-global logger variables.

func StartPrometheusExporter

func StartPrometheusExporter(cfg *PrometheusConfig,
	shutdown <-chan struct{}) error

StartPrometheusExporter registers all relevant metrics with the Prometheus library, then launches the HTTP server that Prometheus will hit to scrape our metrics.

Types

type AdminConfig added in v0.5.0

type AdminConfig struct {
	// Enabled determines whether the admin API is active.
	Enabled bool `long:"enabled" description:"Enable the admin API."`

	// MacaroonPath is the path where the admin macaroon will be written.
	// Defaults to admin.macaroon in the aperture data directory.
	MacaroonPath string `long:"macaroonpath" description:"Path to write the admin macaroon."`

	// CORSOrigins controls which origins are allowed to call the admin REST
	// API. If empty, CORS is disabled and browsers can only use same-origin.
	CORSOrigins []string `long:"corsorigin" description:"Allowed CORS origins for the admin REST API." yaml:"corsorigin"`

	// DashboardListen, when set, serves the embedded dashboard and its
	// credential-injecting /api/proxy/ path only on a separate listener
	// at this host:port, and not on the main listener. It must be a
	// loopback address unless DashboardAllowNonLoopback is set.
	DashboardListen string `` /* 206-byte string literal not displayed */

	// DashboardAllowNonLoopback lets DashboardListen bind a non-loopback
	// address and drops the loopback peer check on that listener. Anyone
	// who can reach such a listener gets admin access.
	DashboardAllowNonLoopback bool `` /* 198-byte string literal not displayed */
}

AdminConfig holds the configuration for the admin gRPC/REST API.

type Aperture

type Aperture struct {
	// contains filtered or unexported fields
}

Aperture is the main type of the aperture service. It holds all components that are required for the authenticating reverse proxy to do its job.

func NewAperture

func NewAperture(cfg *Config) *Aperture

NewAperture creates a new instance of the Aperture service.

func (*Aperture) Start

func (a *Aperture) Start(errChan chan error, shutdown <-chan struct{}) error

Start sets up the proxy server and starts it.

func (*Aperture) Stop

func (a *Aperture) Stop() error

Stop gracefully shuts down the Aperture service.

func (*Aperture) UpdateServices

func (a *Aperture) UpdateServices(services []*proxy.Service) error

UpdateServices instructs the proxy to re-initialize its internal configuration of backend services. This can be used to add or remove backends at run time or enable/disable authentication on the fly.

type AuthConfig

type AuthConfig struct {
	Network string `` /* 144-byte string literal not displayed */

	Disable bool `long:"disable" description:"Whether to disable auth."`

	// LndHost is the hostname of the LND instance to connect to.
	LndHost string `long:"lndhost" description:"Hostname of the LND instance to connect to"`

	// WavelengthGateway is the base URL of a Wavelength wallet daemon's
	// HTTP/JSON gateway to mint challenge invoices from, instead of an lnd
	// node. Invoices from that wallet are backed by an inbound swap, so a
	// seller configured this way needs no Lightning node, no channels and
	// no inbound liquidity in order to be paid.
	WavelengthGateway string `` /* 148-byte string literal not displayed */

	// WavelengthMacaroonPath is the path to the macaroon authorizing calls
	// to that gateway. A wallet daemon requires one unless it was started
	// with rpc.no-macaroons, which it refuses to accept on mainnet, so
	// leaving this empty only works against a daemon deliberately running
	// without authentication.
	WavelengthMacaroonPath string `long:"wavelengthmacaroonpath" description:"Path to the macaroon authorizing calls to the Wavelength wallet daemon's gateway"`

	TLSPath string `long:"tlspath" description:"Path to LND instance's tls certificate"`

	MacDir string `long:"macdir" description:"Directory containing LND instance's macaroons"`

	// The one-time-use passphrase used to set up the connection. This field
	// identifies the connection that will be used.
	Passphrase string `long:"passphrase" description:"the lnc passphrase"`

	// MailboxAddress is the address of the mailbox that the client will
	// use for the LNC connection.
	MailboxAddress string `long:"mailboxaddress" description:"the host:port of the mailbox server to be used"`

	// DevServer set to true to skip verification of the mailbox server's
	// tls cert.
	DevServer bool `long:"devserver" description:"set to true to skip verification of the server's tls cert."`

	// EnableMPP enables the Payment HTTP Authentication Scheme (MPP)
	// alongside the existing L402 scheme.
	EnableMPP bool `long:"enablempp" description:"Enable the Payment HTTP Authentication Scheme (MPP)"`

	// MPPRealm is the realm string used in MPP challenges. Defaults to
	// the server's listen address if empty.
	MPPRealm string `long:"mpprealm" description:"Realm string for MPP challenges"`

	// MPPChallengeExpiry is how long an MPP challenge, and the credential
	// that answers it, stays presentable. Metered sellers should set it
	// near their service timeout.
	MPPChallengeExpiry time.Duration `long:"mppchallengeexpiry" description:"How long an MPP challenge and its credential stay valid, e.g. 720h" default-mask:"15m"`

	// EnableSessions enables the MPP session intent, which provides
	// prepaid sessions with deposit, bearer, top-up, and close
	// operations.
	EnableSessions bool `long:"enablesessions" description:"Enable MPP session intent (requires payment sending capability)"`

	// SessionDepositMultiplier is the number of service units per deposit.
	// Defaults to 20 if not set.
	SessionDepositMultiplier int `long:"sessiondepositmultiplier" description:"Number of service units per session deposit" default-mask:"20"`

	// SessionIdleTimeout is the idle timeout for sessions in seconds.
	// Defaults to 300 (5 minutes) if not set.
	SessionIdleTimeout int `long:"sessionidletimeout" description:"Session idle timeout in seconds" default-mask:"300"`
}

type Config

type Config struct {
	// ListenAddr is the listening address that we should use to allow Aperture
	// to listen for requests.
	ListenAddr string `long:"listenaddr" description:"The interface we should listen on for client requests."`

	// ServerName can be set to a fully qualifying domain name that should
	// be used while creating a certificate through Let's Encrypt.
	ServerName string `long:"servername" description:"Server name (FQDN) to use for the TLS certificate."`

	// AutoCert can be set to true if aperture should try to create a valid
	// certificate through Let's Encrypt using ServerName.
	AutoCert bool `long:"autocert" description:"Automatically create a Let's Encrypt cert using ServerName."`

	// Insecure can be set to disable TLS on incoming connections.
	Insecure bool `long:"insecure" description:"Listen on an insecure connection, disabling TLS for incoming connections."`

	// StaticRoot is the folder where the static content served by the proxy
	// is located.
	StaticRoot string `long:"staticroot" description:"The folder where the static content is located."`

	// ServeStatic defines if static content should be served from the
	// directory defined by StaticRoot.
	ServeStatic bool `long:"servestatic" description:"Flag to enable or disable static content serving."`

	// DatabaseBackend is the database backend to be used by the server.
	DatabaseBackend string `` /* 145-byte string literal not displayed */

	// Sqlite is the configuration section for the SQLite database backend.
	Sqlite *aperturedb.SqliteConfig `group:"sqlite" namespace:"sqlite"`

	// Postgres is the configuration section for the Postgres database backend.
	Postgres *aperturedb.PostgresConfig `group:"postgres" namespace:"postgres"`

	// Etcd is the configuration section for the Etcd database backend.
	Etcd *EtcdConfig `group:"etcd" namespace:"etcd"`

	// Authenticator is the configuration section for connecting directly
	// to the LND node.
	Authenticator *AuthConfig `group:"authenticator" namespace:"authenticator"`

	Tor *TorConfig `group:"tor" namespace:"tor"`

	// Services is a list of JSON objects in string format, which specify
	// each backend service to Aperture.
	Services []*proxy.Service `long:"service" description:"Configurations for each Aperture backend service."`

	// HashMail is the configuration section for configuring the Lightning
	// Node Connect mailbox server.
	HashMail *HashMailConfig `group:"hashmail" namespace:"hashmail" description:"Configuration for the Lightning Node Connect mailbox server."`

	// Prometheus is the config for setting up an endpoint for a Prometheus
	// server to scrape metrics from.
	Prometheus *PrometheusConfig `` /* 129-byte string literal not displayed */

	// Admin is the configuration for the admin REST API.
	Admin *AdminConfig `group:"admin" namespace:"admin" description:"Configuration for the admin REST API."`

	// DebugLevel is a string defining the log level for the service either
	// for all subsystems the same or individual level by subsystem.
	DebugLevel string `long:"debuglevel" description:"Debug level for the Aperture application and its subsystems."`

	// ConfigFile points aperture to an alternative config file.
	ConfigFile string `long:"configfile" description:"Custom path to a config file."`

	// BaseDir is a custom directory to store all aperture flies.
	BaseDir string `long:"basedir" description:"Directory to place all of aperture's files in."`

	// Profile is the port on which the pprof profile will be served.
	Profile uint16 `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65535"`

	// IdleTimeout is the maximum amount of time a connection may be idle.
	IdleTimeout time.Duration `long:"idletimeout" description:"The maximum amount of time a connection may be idle before being closed."`

	// ReadTimeout is the maximum amount of time to wait for a request to
	// be fully read.
	ReadTimeout time.Duration `long:"readtimeout" description:"The maximum amount of time to wait for a request to be fully read."`

	// WriteTimeout is the maximum amount of time to wait for a response to
	// be fully written.
	WriteTimeout time.Duration `long:"writetimeout" description:"The maximum amount of time to wait for a response to be fully written."`

	// InvoiceBatchSize is the number of invoices to fetch in a single
	// request.
	InvoiceBatchSize int `long:"invoicebatchsize" description:"The number of invoices to fetch in a single request."`

	// StrictVerify is a flag that indicates whether we should verify the
	// invoice status strictly or not. If set to true, then this requires
	// all invoices to be read from disk at start up.
	StrictVerify bool `long:"strictverify" description:"Whether to verify the invoice status strictly or not."`

	// Logging controls various aspects of aperture logging.
	Logging *build.LogConfig `group:"logging" namespace:"logging"`

	// WsPingInterval is the interval at which WebSocket-level pings are
	// sent to connected clients. This keeps the underlying WebSocket
	// connection alive through intermediary proxies and load balancers.
	// Set to 0 to disable.
	WsPingInterval time.Duration `long:"wspinginterval" description:"Interval for WebSocket-level ping messages to keep connections alive through proxies."`

	// WsPongWait is the duration to wait for a pong response after
	// sending a WebSocket-level ping. If no pong is received within this
	// duration, the WebSocket connection is considered dead. Must be
	// strictly less than WsPingInterval when pings are enabled.
	WsPongWait time.Duration `long:"wspongwait" description:"Duration to wait for a WebSocket pong response before closing the connection."`

	// ChallengeRateLimit bounds the 402 challenges issued per client
	// network, since each one mints invoices before anything is paid.
	ChallengeRateLimit *proxy.ChallengeRateLimitConfig `group:"challengeratelimit" namespace:"challengeratelimit" description:"Limit on 402 challenges issued per client network."`

	// Blocklist is a list of IPs to deny access to.
	Blocklist []string `long:"blocklist" description:"List of IP addresses to block from accessing the proxy."`

	// TrustedProxies lists the reverse proxies in front of aperture, as
	// CIDRs or single IPs. The X-Forwarded-For header of a request from
	// one of them names the real client, which is then the address used by
	// the blocklist, rate limits and freebies. Empty means no proxy is
	// trusted and clients are identified by the TCP peer address.
	TrustedProxies []string `` /* 176-byte string literal not displayed */
}

func NewConfig

func NewConfig() *Config

NewConfig initializes a new Config variable.

type EtcdConfig

type EtcdConfig struct {
	Host     string `long:"host" description:"host:port of an active etcd instance"`
	User     string `long:"user" description:"user authorized to access the etcd host"`
	Password string `long:"password" description:"password of the etcd user"`
}

type HashMailConfig

type HashMailConfig struct {
	Enabled               bool          `long:"enabled"`
	MessageRate           time.Duration `long:"messagerate" description:"The average minimum time that should pass between each message."`
	MessageBurstAllowance int           `long:"messageburstallowance" description:"The burst rate we allow for messages."`
	StaleTimeout          time.Duration `long:"staletimeout" description:"The time after the last activity that a mailbox should be removed. Set to -1s to disable. "`
}

type PrometheusConfig

type PrometheusConfig struct {
	// Enabled, if true, then Prometheus metrics will be exported.
	Enabled bool `long:"enabled" description:"if true prometheus metrics will be exported"`

	// ListenAddr is the listening address that we should use to allow the
	// main Prometheus server to scrape our metrics.
	ListenAddr string `long:"listenaddr" description:"the interface we should listen on for prometheus"`
}

PrometheusConfig is the set of configuration data that specifies if Prometheus metric exporting is activated, and if so the listening address of the Prometheus server.

type TorConfig

type TorConfig struct {
	Control     string `long:"control" description:"The host:port of the Tor instance."`
	ListenPort  uint16 `` /* 226-byte string literal not displayed */
	VirtualPort uint16 `long:"virtualport" description:"The port through which the onion services created can be reached at."`
	V3          bool   `long:"v3" description:"Whether we should listen for client requests through a v3 onion service."`
}

Directories

Path Synopsis
Package adminrpc is a reverse proxy.
Package adminrpc is a reverse proxy.
Package cli provides the command-line interface for aperturecli.
Package cli provides the command-line interface for aperturecli.
cmd
aperture command
aperturecli command
Package main is the entry point for the aperturecli CLI.
Package main is the entry point for the aperturecli CLI.
gen-mpp-vectors command
Command gen-mpp-vectors writes the cross-implementation test vectors for the Payment HTTP Authentication Scheme.
Command gen-mpp-vectors writes the cross-implementation test vectors for the Payment HTTP Authentication Scheme.
meterd command
internal
Package mcpserver provides the Model Context Protocol server for aperturecli.
Package mcpserver provides the Model Context Protocol server for aperturecli.
Package meterd implements a reference token-metering price server for aperture's dynamicprice.metered mode.
Package meterd implements a reference token-metering price server for aperture's dynamicprice.metered mode.
mpp
mppvectors
Package mppvectors builds the cross-implementation test vectors for the Payment HTTP Authentication Scheme.
Package mppvectors builds the cross-implementation test vectors for the Payment HTTP Authentication Scheme.
Package pricesrpc is a reverse proxy.
Package pricesrpc is a reverse proxy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL