API Reference
StreamSec.Mobile.Acme
ACME (RFC 8555) Client Unit
Feature notes: TLS implementation notes (RFC map) · ACME (RFC 8555) implementation notes
Classes, interfaces and records
classeAcmeError
inherits from Exception
constructor CreateProblem(aStatus: Integer; const aType, aDetail: string);
Wraps an RFC 7807 problem document as an exception. The client raises this through ProblemFor when a server response reports failure, and directly for its own pre-flight and protocol checks; applications catch it to react to a specific error, and rarely construct it themselves.
function IsBadNonce: Boolean;
True when the failure is a rejected nonce (RFC 8555 s6.5). PostSigned already retries these transparently with a fresh nonce, so a caller seldom tests it.
function IsPermanent: Boolean;
True for ACME problem types a retry cannot fix without operator or configuration action - a bad CSR/key/signature/revocation-reason, a rejected or unsupported identifier, a malformed request, a CAA prohibition, an EAB/contact problem, a missing account, or userActionRequired.
Full description »
property ErrorType: string read fErrorType;
The URN from the ACME error registry, e.g. ...:error:rateLimited.
property Detail: string read fDetail;
The human-readable "detail" from the problem document: the CA's explanation of why the request failed, suitable for logging or showing an operator.
property Status: Integer read fStatus;
The HTTP status code of the failing ACME response (0 for the client's own internally-raised errors, which carry no server status).
recordtAcmeChallenge
One challenge the CA offers for an authorization, decoded from its "challenges" array and reached through tAcmeAuthorization.Challenges. Kind is the validation method (http-01/dns-01/tls-alpn-01); Url is the challenge resource to POST-trigger once the response is published (TriggerChallenge); Token seeds the key authorization the response must present (KeyAuthorization for http-01/tls-alpn-01, Dns01Value for dns-01); Status is the CA's current view of this challenge.
Kind : tAcmeChallengeKind;
Url : string;
Token : string;
Status: tAcmeStatus;
classtAcmeAuthorization
function IndexOfKind(aKind: tAcmeChallengeKind): Integer;
Returns the index into Challenges of the first challenge of aKind, or -1 when the authorization offers no such method - use it to pick, e.g., dns-01 for a wildcard before triggering it.
function ChallengeCount: Integer;
Number of challenges the CA offers for this identifier.
property Challenges: tAcmeChallengeArray read fChallenges;
The set of challenges the CA will accept for this identifier; an application iterates it to select one it can answer (AuthorizeAll does this internally).
classtAcmeOrder
constructor Create;
Internal: NewOrder/ParseOrder create the object; an application receives it and frees it.
destructor Destroy; override;
Frees the identifier and authorization-URL lists.
property Identifiers: TStringList read fIdentifiers;
The DNS names this order certifies, as echoed back by the CA.
property AuthorizationUrls: TStringList read fAuthorizationUrls;
One authorization URL per identifier; AuthorizeAll walks these, or LoadAuthorization one to inspect and answer its challenges by hand.
recordtAcmeDirectory
The ACME directory (RFC 8555 s7.1.1): the CA's endpoint map, fetched once from DirectoryUrl and exposed read-only through the Directory property. An application seldom reads it directly - the client drives the endpoints - but it is useful for discovery. NewNonce/NewAccount/NewOrder/RevokeCert/KeyChange are the resource URLs the flow uses; RenewalInfo is the RFC 9773 ARI endpoint (empty when the CA supports no ARI); TermsOfService and Website come from the directory's "meta" block (the Subscriber Agreement URL to show a user before setting TermsOfServiceAgreed, and the CA's home page); ExternalAccountRequired is True when the CA will not create an account without external account binding (see ExternalAccountKid/ExternalAccountMacKey).
NewNonce : string;
NewAccount : string;
NewOrder : string;
RevokeCert : string;
KeyChange : string;
RenewalInfo : string;
TermsOfService : string;
Website : string;
ExternalAccountRequired: Boolean;
recordtAcmeRenewalInfo
Renewal information from RFC 9773 (ARI): the CA-suggested window in which to renew a certificate. HasWindow is False when the CA does not support ARI or does not recognise the certificate. WindowStart/WindowEnd are UTC. A renewal agent picks a random moment inside [WindowStart, WindowEnd] - the spread is the point of ARI: it stops a fleet renewing in lockstep and lets a CA move everyone's window earlier during a mass revocation. RetryAfterSeconds is when to re-query (RFC 9773 gives it dual min/max meaning), clamped to a sane range.
HasWindow : Boolean;
WindowStart : TDateTime;
WindowEnd : TDateTime;
ExplanationURL : string;
RetryAfterSeconds: Integer;
inherits from TComponent
constructor Create(aOwner: TComponent); override;
Create initializes the client with empty Contact/Domains lists and the default PollInterval/PollTimeout; drop it on a form or create it with an owner, then set the properties and call ObtainCertificate (managed) or the step methods (manual).
» member page
destructor Destroy; override;
Destroy releases the cached JWS account key, the internal HTTP client and the Contact/Domains lists; an owned instance is freed automatically with its owner.
» member page
procedure Cancel;
Cancel may be called from a service-control thread. ResetCancel is used before restarting a stopped worker; call it only while the client is idle.
» member page
procedure ResetCancel;
property HttpClient: tHttpClient read fHttp;
Configure request timeout, verified TLS engine and source binding on the owned HTTP client. It is exclusively used by this ACME client.
» member page
procedure FetchDirectory;
FetchDirectory GETs the DirectoryUrl document and caches the CA's resource URLs (newNonce, newAccount, newOrder, revokeCert, renewalInfo) plus its "meta" (termsOfService URL, website, externalAccountRequired).
Full description »
function FetchNonce: string;
FetchNonce performs the HEAD on newNonce and stores the result. Callers do not normally need it; PostSigned fetches one when its store is dry.
» member page
procedure RegisterAccount(aOnlyReturnExisting: Boolean = False);
Manual-flow STEP 1 (managed ObtainCertificate calls it for you). Creates the Let's Encrypt account for AccountKey or, if one already exists for that key, adopts it - the server returns the same URL either way.
Full description »
function KeyAuthorization(const aToken: string): string;
KeyAuthorization is token || '.' || base64url(SHA-256(canonical JWK)), the value an http-01 challenge serves verbatim.
» member page
function Dns01Value(const aToken: string): string;
Dns01Value is base64url(SHA-256(key authorization)) - the TXT record content for _acme-challenge, which is hashed where http-01 is not.
» member page
function NewOrder(aIdentifiers: TStrings): tAcmeOrder; overload;
Manual-flow STEP 2 (managed ObtainCertificate calls it for you). Places the order for aIdentifiers (the domain names to certify) against the registered account and returns the order with its authorizations to work through.
» member page
function NewOrder(aIdentifiers: TStrings; const aReplacesLeafDer: tBytes): tAcmeOrder; overload;
This overload sets the RFC 9773 "replaces" field to the certificate the order renews (aReplacesLeafDer = the DER of the leaf being replaced). An ARI-aware CA uses it to correlate the renewal; SHOULD be set whenever there is a clear predecessor.
» member page
procedure RefreshOrder(aOrder: tAcmeOrder);
RefreshOrder re-fetches the order (POST-as-GET) and updates its Status, Expires, FinalizeUrl, CertificateUrl and AuthorizationUrls in place. WaitForOrder loops on it; a manual flow calls it directly to re-read an order's server-side state.
» member page
function LoadAuthorization(const aUrl: string): tAcmeAuthorization;
LoadAuthorization fetches one authorization (a URL from an order's AuthorizationUrls) and returns it with its identifier, status, wildcard flag and the list of offered challenges. In a manual flow use it to decide which challenge to answer; AuthorizeAll and WaitForAuthorization call it internally. The caller OWNS the returned object and must free it.
» member page
procedure TriggerChallenge(const aChallengeUrl: string);
TriggerChallenge POSTs an empty JSON object to a challenge URL to tell the CA the response is now in place and validation may begin (RFC 8555 s7.5.1). In a manual flow call it AFTER the http-01/dns-01/tls-alpn-01 response is published, then poll with WaitForAuthorization.
» member page
function WaitForAuthorization(const aUrl: string): tAcmeStatus;
WaitForAuthorization polls one authorization until it leaves "pending" and returns the reached status (acsValid, or acsInvalid when the challenge failed), honouring the server's Retry-After and otherwise PollInterval and raising after PollTimeout. The manual-flow counterpart to the wait AuthorizeAll performs for you.
» member page
function WaitForOrder(aOrder: tAcmeOrder): tAcmeStatus;
WaitForOrder polls the order (via RefreshOrder) until it leaves pending/processing and returns the reached status - "ready" once every authorization is valid, "valid" after finalize completes. Managed ObtainCertificate calls it after AuthorizeAll and again after FinalizeOrder; a manual flow calls it at the same two points.
» member page
procedure AuthorizeAll(aOrder: tAcmeOrder);
Manual-flow STEP 3 (managed ObtainCertificate calls it for you). Walks every authorization the order lists, publishes a challenge through the matching event (OnHttp01/Dns01/TlsAlpn01Challenge, or the built-in tls-alpn-01 responder in managed mode), triggers it and waits for Let's Encrypt to validate. Raises if any identifier cannot be authorized.
» member page
procedure FinalizeOrder(aOrder: tAcmeOrder; const aCsrDer: tBytes);
Manual-flow STEP 4 (managed ObtainCertificate calls it for you). Submits the CSR (aCsrDer - DER-encoded PKCS#10 over CertificateKey, covering the order's domains; build it with StreamSec.DSI.Pkcs10Generator) to finalize the order. The order then moves to "valid" and the certificate becomes downloadable.
» member page
function DownloadCertificate(aOrder: tAcmeOrder; aAlternate: Integer = 0): string;
Manual-flow STEP 5 (managed ObtainCertificate calls it for you). Downloads the issued PEM chain, leaf first, once the order is valid. aAlternate selects one of the alternate chains the server advertises through Link rel="alternate", where 0 is the default chain (for Let's Encrypt, chain to ISRG Root X1).
» member page
procedure RevokeCertificate(const aCertDer: tBytes; aReason: Integer = 0);
RevokeCertificate asks the CA to revoke an already-issued leaf (aCertDer = its DER) with an optional RFC 5280 CRL reason code (0 = unspecified). It is signed with the account key, so it works for a certificate this account holds; call it when the key is compromised or the certificate is being retired.
» member page
procedure DeactivateAuthorization(const aUrl: string);
DeactivateAuthorization POSTs status "deactivated" for an authorization URL, telling the CA to drop that cached domain authorization so a later order must re-validate the name. Optional cleanup; use it to relinquish an authorization you do not want the CA to reuse.
» member page
function AriCertIdentifier(const aLeafDer: tBytes): string;
AriCertIdentifier builds the RFC 9773 s4.1 certificate identifier for a leaf: base64url(AKI keyIdentifier) '.' base64url(serialNumber content octets), both unpadded. This is the path segment for GetRenewalInfo and the value of the newOrder "replaces" field. Raises if the leaf carries no Authority Key Identifier.
» member page
function GetRenewalInfo(const aLeafDer: tBytes; out aInfo: tAcmeRenewalInfo): Boolean;
GetRenewalInfo queries the CA's renewalInfo resource for aLeafDer and, on success, fills aInfo with the suggested renewal window (RFC 9773). Returns False - rather than raising - when the CA advertises no renewalInfo or does not recognise the certificate, so a caller can simply fall back to a fixed renewal fraction.
» member page
function ObtainCertificate: string; overload;
THE single call for requesting an HTTPS server certificate from Let's Encrypt in managed mode. Set the properties first - AccountKey, DirectoryUrl, TermsOfServiceAgreed, (Contact), CertificateKey, Domains, TLSServer, PfxFileName - then call this once.
Full description »
function ObtainCertificate(aDomains: TStrings; aCertKey: TComponent): string; overload;
function ObtainCertificate(aDomains: TStrings; aCertKey: TComponent; const aReplacesLeafDer: tBytes): string; overload;
As above, but naming the certificate this order REPLACES: aReplacesLeafDer is the DER of the leaf being renewed, passed to newOrder as the RFC 9773 "replaces" field so an ARI-aware CA can correlate the renewal with what it is superseding.
Full description »
property AlpnTarget: iAcmeAlpnTLS read AcmeTarget;
The server this client provisions - TLSServer or AsyncTLSServer, whichever is set - as the interface BOTH implement, or nil in host-driven mode.
Full description »
property Directory: tAcmeDirectory read fDirectory;
Directory exposes the CA resource map cached by FetchDirectory - the endpoint URLs plus "meta" (termsOfService URL, website, externalAccountRequired). Read it to show the subscriber-agreement link or to check whether the CA demands external account binding before you register. Empty until FetchDirectory has run.
» member page
property AccountUrl: string read fAccountUrl write fAccountUrl;
AccountUrl is the account resource URL the CA returns from RegisterAccount; it is sent as the JWS "kid" that identifies the account on every later signed request. It is writable so an application that persisted it across runs can restore it and post to protected resources without re-registering.
» member page
property AccountKey: TComponent read fKeyComponent write SetKeyComponent;
When requesting an HTTPS server certificate from Let's Encrypt, set this to the ACCOUNT key - a TstRSAKey, TstECDSAKey or TstEdDSAKey (RSA-2048/3072 or P-256/384 are all accepted).
Full description »
property DirectoryUrl: string read fDirectoryUrl write fDirectoryUrl;
When requesting an HTTPS server certificate from Let's Encrypt, set this to Let's Encrypt's ACME directory URL - while developing use STAGING, 'https://acme-staging-v02.api.letsencrypt.org/directory' (lenient rate limits, certificates from an untrusted test root); switch to PRODUCTION, 'https://a...
Full description »
property Contact: TStringList read fContact write SetContact;
When requesting an HTTPS server certificate from Let's Encrypt, optionally add one or more 'mailto:you@example.com' addresses here before the account is registered; Let's Encrypt sends certificate-expiry and account/security notices to them. Recommended (use a real, deliverable mailbox); leave the list empty to register with no contact.
» member page
property TermsOfServiceAgreed: Boolean read fAgreeTerms write fAgreeTerms default False;
When requesting an HTTPS server certificate from Let's Encrypt, this MUST be set to True before the account is registered - it records that you accept Let's Encrypt's Subscriber Agreement (whose URL is published in the directory's "meta" termsOfService field).
Full description »
property PollInterval: Integer read fPollInterval write fPollInterval default cAcmeDefaultPollInterval;
Milliseconds between polls while waiting for Let's Encrypt to validate a challenge or finalize an order, used only when the server sends no Retry-After hint (which is always honoured in preference). The default suits Let's Encrypt; rarely needs changing.
» member page
property PollTimeout: Integer read fPollTimeout write fPollTimeout default cAcmeDefaultPollTimeout;
Milliseconds after which waiting for a challenge to validate or an order to finalize gives up and raises an eAcmeError. Increase it for a slow or heavily loaded CA.
» member page
property UserAgent: string read fUserAgent write SetUserAgent;
Optional User-Agent header added to every ACME request - Let's Encrypt asks clients to identify themselves (product/version). Leave empty to send the library's default.
» member page
property ExternalAccountKid: string read fEabKid write fEabKid;
External account binding (RFC 8555 s7.3.4), for CAs that tie an ACME account to an existing customer account. LEAVE BOTH EMPTY for Let's Encrypt - it does NOT use EAB. They are needed only for CAs that require it (ZeroSSL, Google Trust Services, ...), where both values come from the CA's console: the key id verbatim, and the MAC key in the base64url form the CA displays.
» member page
property ExternalAccountMacKey: string read fEabMacKey write fEabMacKey;
property OnHttp01Challenge: tAcmeChallengeEvent read fOnHttp01 write fOnHttp01;
Challenge events for the HOST-DRIVEN flow (TLSServer NOT set). When requesting an HTTPS server certificate from Let's Encrypt you normally use tls-alpn-01 in managed mode (set TLSServer instead - then none of these are needed).
Full description »
property OnDns01Challenge: tAcmeChallengeEvent read fOnDns01 write fOnDns01;
property OnTlsAlpn01Challenge: tAcmeChallengeEvent read fOnTlsAlpn01 write fOnTlsAlpn01;
property OnCleanupChallenge: tAcmeCleanupEvent read fOnCleanup write fOnCleanup;
Fires after each challenge (whether it validated or failed) so a host-driven flow can tear the response down - delete the TXT record, remove the challenge file, or drop the acme-tls/1 certificate. Not needed in managed mode.
» member page
property OnProgress: tAcmeProgressEvent read fOnProgress write fOnProgress;
Fires with a short human-readable message at each step of a request (fetching directory, registering account, answering the challenge, finalizing, ...). Wire it to your log to watch an issuance progress.
» member page
property TLSServer: TsmCustomTLSInternalServer read fTLSServer write SetTLSServer;
When requesting an HTTPS server certificate from Let's Encrypt the easy way, set this to your live TsmSimpleTLSInternalServer to switch on MANAGED mode: the component then answers the tls-alpn-01 challenge on this very server (no OnTlsAlpn01Challenge handler needed) and installs the issued (and l...
Full description »
property AsyncTLSServer: TsmAsyncTLSServer read fAsyncTLSServer write SetAsyncTLSServer;
Managed mode against a sharded TsmAsyncTLSServer: the same contract as TLSServer, but every challenge, CA add and certificate swap is fanned out to ALL of the server's engine shards - the CA's validation connection is round-robined onto an arbitrary one, and a renewed leaf must reach every one.
Full description »
property CertificateKey: TComponent read fCertKey write SetCertificateKey;
When requesting an HTTPS server certificate from Let's Encrypt, set this to the CERTIFICATE key - the key pair the leaf is issued FOR (a TstRSAKey or TstECDSAKey; RSA-2048+ or P-256/384). It is used for the tls-alpn-01 challenge certificate, the CSR, and the served identity. It is DISTINCT from AccountKey and disposable - you may generate a fresh one for every issuance.
» member page
property Domains: TStringList read fDomains write SetDomains;
When requesting an HTTPS server certificate from Let's Encrypt, list the domain name(s) the certificate must cover - the public, DNS-resolvable names you control.
Full description »
property PfxFileName: string read fPfxFileName write fPfxFileName;
In managed mode, PfxFileName is where the live identity (issued leaf + chain + CertificateKey) is persisted as a PKCS#12 after each issuance/renewal, and PfxPassword protects it. Point a server at the same file (ImportFromPFX) at startup so a restart keeps the Let's Encrypt certificate without re-issuing.
» member page
property PfxPassword: string read fPfxPassword write fPfxPassword;
Types (enumerations, sets, aliases)
enumtAcmeStatus
The RFC 8555 resource state shared by orders, authorizations and challenges;
acsUnknown stands in for any status string this client does not recognise.
tAcmeStatus = (acsUnknown, acsPending, acsReady, acsProcessing, acsValid,
acsInvalid, acsDeactivated, acsExpired, acsRevoked);
enumtAcmeChallengeKind
The challenge validation methods this client understands; ackUnknown stands in for any challenge "type" the CA offers that is none of these.
tAcmeChallengeKind = (ackUnknown, ackHttp01, ackDns01, ackTlsAlpn01);
arraytAcmeChallengeArray
The challenges of one authorization, as exposed by tAcmeAuthorization.Challenges.
tAcmeChallengeArray = array of tAcmeChallenge;
proctAcmeChallengeEvent
A challenge event hands the application everything it needs to publish the response. Set aHandled to False to decline this challenge kind, which lets the client try another one the authorization offers.
tAcmeChallengeEvent = procedure(Sender: TObject;
const aIdentifier: string;
const aToken: string;
const aKeyAuthorization: string;
var aHandled: Boolean) of object;
proctAcmeCleanupEvent
Signature of OnCleanupChallenge - see that property for when it fires and what to tear down for aIdentifier/aToken.
tAcmeCleanupEvent = procedure(Sender: TObject;
const aIdentifier: string;
const aToken: string) of object;
proctAcmeProgressEvent
Signature of OnProgress - aMessage is a short human-readable step description.
tAcmeProgressEvent = procedure(Sender: TObject;
const aMessage: string) of object;
Routines