Skip to content

About

Plugin SDK for Hostpanel: contracts for payment, provisioning, registrar, fulfilment, identity and hosted plugins. MIT licensed.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Hostpanel.Sdk

Plugin contracts for a hostpanel host. A plugin compiles against this package, implements one or more of the contracts below, and ships as its own assembly plus a plugin.json manifest.

NuGet License: MIT

Hostpanel | Product site | Documentation | Write a plugin | Plugin marketplace | Discord

License

This package is MIT licensed (see LICENSE in the package). You decide how to license your plugin: it may be free or paid, open source or closed source. The hostpanel host (innovayse/hostpanel) is AGPL-3.0-or-later; compiling against this package does not put your plugin under the AGPL.

Referencing the package

Pin the version you build against, so a new SDK release never changes your plugin by surprise:

dotnet add package Hostpanel.Sdk --version 3.9.0

or, in the plugin's .csproj:

<ItemGroup>
  <!-- ExcludeAssets="runtime" keeps Hostpanel.Sdk.dll out of the plugin's output: the host already
       loads it, and a second copy in the plugin folder breaks every cast (see "Shipping" below). -->
  <PackageReference Include="Hostpanel.Sdk" Version="3.9.0" ExcludeAssets="runtime" />
</ItemGroup>

A version still being built on develop ships as a prerelease, X.Y.Z-preview.N, published from a vX.Y.Z-preview.N tag. Pin it the same way (Version="2.1.0-preview.1") to build against an API that is not released yet, and move to X.Y.Z once it is. NuGet never picks a prerelease for you.

The package targets net8.0, so a plugin can target net8.0 or later. The version follows the contract: a new minor version adds members, a new major version removes or renames them. The manifest's sdkVersion field is the plugin contract level the host checks, not the package version: see "Manifest" below for the value to declare. It does not move with the package, so a plugin built on package 3.12.0 declares the same sdkVersion as one built on 3.0.0. To require a host that fills a member added in a later package version, set minHostVersion in the manifest to the first host release that does.

Upgrading from 1.x? Version 2.0.0 moves types into one namespace per area and renames a few members. The migration table in CHANGELOG.md lists every move and rename. A plugin built against 1.x cannot load in a 2.0.0 host: it must be rebuilt against 2.0.0.

Plugin types

PluginType Contract What it is for
Provisioning IProvisioningPlugin, ProvisioningProviderBase Hosting accounts on a server or control panel. IProvisioningPanelPlugin adds the account operations (see "Provisioning panel plugins") and IVirtualServerPlugin the operations of a virtual server or cloud platform (see "Virtual server plugins"); the marker and the base class give settings access.
Payment IPaymentPlugin, PaymentGatewayBase A payment gateway: start a payment, read its status, refund it.
Registrar IRegistrarPlugin, RegistrarProviderBase A domain registrar. IRegistrarOperationsPlugin adds the domain operations (see "Registrar plugins"); the marker and the base class give settings access.
Identity IClientResolver Decides which client a signed-in principal acts for and what it may do there. At most one identity plugin may be enabled.
Fulfilment IFulfilmentPlugin Delivers digital products once an invoice is paid, and is asked before a refund moves money back. Every enabled fulfilment plugin sees every digital invoice.
Hosted IHostedPlugin A background worker the host starts after its own services are up and stops on shutdown. A plugin of another type may implement it too.
App IPluginEndpoints Answers the routes its manifest declares and adds pages and slot content, without web framework types or user tokens.
Tax ITaxPlugin Calculates the tax due on the lines of an invoice (see "Tax plugins").

Fulfilment plugins

IFulfilmentPlugin delivers digital products. When a payment is recorded for an invoice with at least one digital line, the host writes a fulfilment row in the same transaction as the payment and delivers it to every enabled fulfilment plugin in the background.

  • At least once. A delivery is retried with back-off until the plugin returns normally; throw to fail an attempt and have it retried. The same paid invoice can therefore reach you more than once, so every method must be idempotent on InvoiceId: delivering twice must leave the same result as once.
  • OnInvoicePaidAsync runs when a paid invoice has a digital line. OnInvoiceRefundedAsync runs after the money moved back, to reverse the fulfilment. OnSubscriptionLapsedAsync runs when a renewal invoice passes its grace period unpaid.
  • OnServicePlanChangedAsync (since 3.12.0) runs when a client's service moved to another plan or changed quantity. The context carries the service, the line before and after (Previous, Current), the Kind (Upgrade, Downgrade, QuantityChange; check Enum.IsDefined, a newer host may add one) and an IdempotencyKey that is the same on every redelivery of one change. It has a default body that does nothing, so a plugin that does not override it is not affected; one that relies on it sets minHostVersion to the first host release that sends it.
  • AdviseRefundAsync runs before a refund moves money, with the amount the administrator asked for. Return a RefundAdvice: MaxRefundableAmount is the most that may still be refunded in the invoice's currency (return the requested amount to allow it in full) and Reason is a short sentence for the administrator. The host takes the smallest cap across all plugins. A cap of zero or less refuses the refund, a smaller positive cap reduces it and your reason is written to the refund's notes. If the call throws or does not answer in time the refund is refused: the host cannot tell whether you would have capped it.

Identity plugins

IClientResolver decides which client a signed-in principal acts for. When one is enabled, every client-portal route calls ResolveAsync with the caller's ClaimsPrincipal instead of using the host's default rule (the client whose owner equals the principal's subject). Return null when the principal acts for no account; the host then answers that there is no client profile. Otherwise return a ClientAccess:

  • Account is an ExternalAccount: a Provider name you choose and never change (for example crm), the account's Id in that system, and optionally a DisplayName and a Currency for a client created on the first order. The host stores the pair on its own client row, unique per provider, and creates the row when needed; the plugin never touches persistence.
  • CanPurchase and CanManagePaymentMethods map to the host's client permissions. Every admitted principal can read services, domains, open support tickets and emails. CanPurchase adds placing orders and viewing and paying invoices. CanManagePaymentMethods adds viewing invoices, which is the permission that guards the saved payment method actions. A plugin cannot grant any other permission.

At most one identity plugin may be enabled: two enabled at once is a configuration error and is refused, not resolved by picking one.

Hosted plugins

IHostedPlugin is a background worker. The host calls StartAsync once per process, after its own services are up, and StopAsync when it begins to stop (the token is cancelled when the shutdown grace period ends). Return from StartAsync once the worker is running; do not block on its loop. A plugin of another type may implement IHostedPlugin too and is then started the same way. A plugin that throws while starting or stopping is logged with its id and never stops the host or the other plugins.

App plugins

An app plugin (PluginType.App, value 6) answers requests. It implements IPluginEndpoints (namespace Hostpanel.Sdk.Plugins.Endpoints, one method, HandleAsync(PluginCall, CancellationToken)) and declares its routes in the manifest api block. The host matches the request to a declared route, checks the caller's permission and only then calls the plugin, so the plugin sees no HTTP request, no token and no web framework type.

  • PluginCall carries the matched route template, route values, query, body, language, the verified slot Context and the call-bound Host and Store. PluginCaller holds an opaque ClientRef and UserRef (stable for your plugin, different for every other plugin) and the permission names of the caller.
  • Ids: a client area call carries only the opaque ClientRef and UserRef, never a host client or user id. An admin call carries real host ids in Context (clientId, serviceId), because an administrator is staff. PluginClientService.Id and PluginClientInvoice.Id are host ids of the caller's own records.
  • Reply with PluginReply.Json (status 200, 201, 202 or 203), NoContent, Problem(status, code) or Stream(events). Problem refuses 401 and 407, which the host answers itself: refuse a caller with 403. An exception is reported as a plugin failure without its detail; return Problem for an expected failure.
  • A stream is a sequence of PluginEvent values the host forwards as server-sent events. A PluginEvent refuses a null Data and a Name or Id containing a carriage return or line feed. Cancellation reaches the stream through its enumerator: when the caller disconnects the host cancels the token it passes to GetAsyncEnumerator, so an iterator method needs a parameter marked [EnumeratorCancellation] and must pass it to every awaited call. The token given to HandleAsync is not used for the stream. call.Host and call.Store stay valid until the stream ends, and not after.
  • IPluginHostApi gives read-only facts about the call's client: profile, services and invoices (each list is at most the 50 most recent). It is bound to that client, so no method takes a client id. IPluginStore is your own text key and value storage, scoped to your plugin and the call's client. The host refuses a client area call without a client, so the store is never plugin wide there; only an admin call outside any client has a plugin wide store. A plugin that needs data outside a routed call (a payment plugin remembering a gateway order id between CreatePaymentAsync, GetStatusAsync and RefundAsync, or a cursor read by a webhook) may also take IPluginStore in its constructor. The host provides it when it activates the plugin: it is plugin wide, scoped to your plugin id and to no client, with the same key rules, size limits and removal semantics as the call store (it is the same data as the call store of an admin call outside any client). It never reaches another plugin's or a client's values. Keep client data in call.Store, which is bound to the call's client.
  • Optional: implement IPluginStatus to report health, and IPluginMigrations to bring data kept outside the host up to date before the first call.
  • Hosting access: IPluginHostApi also carries IssueSshAccessAsync and RevokeSshAccessAsync for the ssh kind. The optional IPluginHostSshSourceApi (since 3.16.0) adds an allowedFrom list of addresses or CIDR ranges the issued key may be used from. Websites and databases arrive on a separate interface, IPluginHostHostingApi, which extends it, so a plugin checks call.Host is IPluginHostHostingApi hosting and does without when the host is older than 3.9.0. Declare the kinds in the manifest's hostAccess (PluginHostAccess.Ssh, Websites, Databases, ServiceConnection; PluginHostAccess.All lists them). GetHostingCapabilitiesAsync(serviceId) says what the service's account supports (PluginHostingCapabilities: the three flags and the PHP versions). EnsureWebsiteAsync(serviceId, PluginWebsiteSpec) is safe to repeat for a host name; the document root is relative to the account home, and DocumentRootMayBeLink asks for the pool settings that let the plugin switch the root through a symbolic link. EnsureDatabaseAsync(serviceId, label) returns the password once, on creation (PluginDatabase.Password, null afterwards), so store it at once; it prints as ***. RemoveWebsiteAsync and RemoveDatabaseAsync remove what this plugin created. A refusal is a PluginHostAccessException; PluginHostAccessFailure.InvalidRequest and Conflict are new in 3.9.0.
  • Reading one gateway order now (since 3.11.0): a payment plugin's callback, a webhook or a return from the gateway's page, can ask the host to read that order through IPluginHostPaymentApi, which extends IPluginHostApi the same way. Check call.Host is IPluginHostPaymentApi payment and call payment.RequestOrderReadAsync(gatewayOrderId, ct). The host then calls your GetStatusAsync for that order and records what it answers. The host may ignore the request (an unknown or settled order, a request that comes too often, or a host older than 3.11.0 that lacks the interface) and never reports whether it read anything, so the plugin must work without it. A callback never marks a payment paid itself.
  • Reaching the server of one of the client's services (since 3.11.0): a plugin route on a service tab can check call.Host is IPluginHostServiceConnectionApi connection and call connection.ResolveServiceConnectionAsync(serviceId, ct). It answers the PanelAccountContext a provisioning operation receives, the server with its stored credentials and the service with ProvisioningRef, so the route can talk to the panel itself. It is allowed on a client area call for a product bound to the plugin, and only when the manifest's hostAccess declares serviceConnection (PluginHostAccess.ServiceConnection); the host shows declared kinds to the operator at install, the same rule as ssh, websites and databases. Another client's service answers like a missing one; a refusal is a PluginHostAccessException. The credentials are secrets: send them only to your own panel and never log or return them.

Slots

A slot is a place in a host page where a plugin adds content (ui.slots in the manifest). PluginSlots is the stable, versioned list; PluginSlots.Version is 1.0. A widget may declare only the context keys its slot offers; the host checks them with PluginSlot.Offers(key). The context values are host ids (see "Ids" above).

Slot id Area Context keys
client.dashboard.cards client none (the caller's client is implied)
client.service.tabs client serviceId
admin.client.panels admin clientId
admin.service.panels admin serviceId, clientId

Versioning rule: adding a slot or a context key is a minor change; removing or changing one is a major change.

Endpoints on any plugin type

An app plugin implements IPluginEndpoints and the host serves its client and admin routes, pages, menus and slots. Any other plugin type can have the same by also implementing IPluginEndpoints and listing endpoints (PluginCapabilities.Endpoints) in the manifest's capabilities. The host then serves the declared api routes and the ui pages, menus and slots of that plugin exactly as it does for an app plugin, while the plugin keeps its own type's contract: a Fulfilment plugin that grants credits on a paid invoice can also give the client a screen, and both sides see the same ClientRef. Without the capability a plugin that is not an app plugin has its api and ui blocks refused, and a declared capability whose class does not implement IPluginEndpoints is refused when the plugin is activated.

Credentials and redirects

SDK 3.7.0 requires a host not to follow redirects for any HTTP client it gives to a plugin, the client of IPanelTransport included. A 3xx answer then reaches your code as it is. That is deliberate: a client that followed a redirect would send your authorization header, and for some handlers your request body, to whatever address the answer names, which may be another host or an unintended path. So decide for yourself. Send an API key or token only to the host you built the address for, and when a 3xx answer names a new address, check its scheme, host and port (and that it is https) before you send a new request to it, with the credential again only if they are the same. A host older than the requirement may still follow redirects, so on such a host also check the final address of every response with PluginHttp.EnsureFinalHost (see "Calling a gateway or a panel" below). In the plugin's own tests, run PluginHttpContract.AssertRedirectIsNotFollowedAsync(() => transport.CreateClient()) against the transport double you test with: it starts a local listener that answers a redirect and checks that the client returns the 3xx answer and makes no second request. The host's address guard may refuse a loopback address, so run it with a transport double and not behind that guard.

Calling a gateway or a panel

The steps every plugin that talks to a gateway or a panel repeats are in PluginHttp (Hostpanel.Sdk.Plugins.Http), so a mistake does not depend on the author. Build one with a TimeProvider (TimeProvider.System in production, a fake clock in tests), send on the client the host's transport gave you, check where the answer came from, and read the body with a limit (the redirect rule that goes with it is in "Credentials and redirects" above). Both calls have a deadline, and the deadline of the read covers a body that arrives too slowly:

var http = new PluginHttp(TimeProvider.System);
var origin = new Uri("https://api.gateway.example/");
using var response = await http.SendAsync(client, request, TimeSpan.FromSeconds(15), ct);
PluginHttp.EnsureFinalHost(response, origin);
var body = await http.ReadBoundedAsync(response, 64 * 1024, TimeSpan.FromSeconds(15), ct);
  • SendAsync wraps a refused or dropped connection and a TLS error in one PluginHttpException (PluginHttpFault.Transport) with a fixed message and no inner exception: the inner message can contain the address you called and its query string. A call that does not finish before its deadline is PluginHttpFault.TimedOut. A cancellation by the caller's token stays an OperationCanceledException.
  • EnsureFinalHost takes the Uri you built the request for and throws PluginHttpFault.UnexpectedHost when the response came from another scheme, host or port. Hosts compare without regard to case, and an IPv6 address is compared with its brackets, as Uri.Host writes it, which is why it takes a Uri and not a host text.
  • ReadBoundedAsync refuses a declared Content-Length over the limit before it reads, stops reading at the limit when there is none (PluginHttpFault.TooLarge), and gives up at its deadline (PluginHttpFault.TimedOut).

De-duplicating webhooks with the advanced store

A plugin that handles webhooks must remember which events it handled, expire old markers and keep two processes from handling one event. IPluginStoreAdvanced extends IPluginStore with exactly that, and the store the host gives a plugin implements it when the host supports it, so test for it and fall back to what you do today otherwise. The interface is new, so the change is source and binary compatible. The limits (PluginStoreLimits) are the host's: at most 1000 keys in the store, 200 keys per list and a time to live of at most 30 days. A write of a new key past the quota throws PluginStoreQuotaException, and a write with a time to live out of range throws ArgumentOutOfRangeException; neither writes anything. A plain SetAsync replaces the value and clears its expiry.

// Exactly one process gets true for an event id; the marker removes itself after a day.
var first = call.Store is IPluginStoreAdvanced advanced
    ? await advanced.SetIfAbsentAsync("event:" + eventId, "handled", TimeSpan.FromDays(1), ct)
    : await MarkOnceWithTheOldStoreAsync(call.Store, "event:" + eventId, ct);
if (!first)
{
    return PluginReply.NoContent();
}

// The fallback keeps what plugins do today: read, then write. Two processes can both pass, so the handler of the
// event must also be safe to run twice.
static async Task<bool> MarkOnceWithTheOldStoreAsync(IPluginStore store, string key, CancellationToken ct)
{
    if (await store.GetAsync(key, ct) is not null)
    {
        return false;
    }

    await store.SetAsync(key, "handled", ct);
    return true;
}

ListKeysAsync("event:", 100, ct) lists what is stored under a prefix, in ordinal order. A prefix follows the rules of a key, is case sensitive, and there is no paging, which replaces a shared index key that two processes can overwrite. In the plugin's own tests, run the PluginStoreContract checks against InMemoryPluginStore, a store that keeps the promises and whose clock you move with AdvanceAsync: AssertSetIfAbsentIsAtomicAsync, AssertExpiredKeyReadsAsAbsentAsync, AssertPlainSetClearsTimeToLiveAsync, AssertTimeToLiveBoundsAsync and AssertListKeysHonoursPrefixAndLimitAsync; each throws PluginContractViolationException naming the promise that was broken.

Logging and secrets

The SDK records print their secret members as ***, and that text is public as SecretMask.Text in Hostpanel.Sdk.Plugins.Diagnostics. Use it in your own settings object and in any diagnostic line about a gateway answer instead of a literal of your own, so every mask in a log is the same and a search for it finds them all. It makes a log readable and is not a security boundary: never write a secret, a token, an address or a payer detail to a log, a result or an exception message in the first place.

The masking is generated, so no record lists its members by hand. Mark a secret or personal member with [property: SecretMember] on the parameter of a positional record and declare the record partial; a source generator that ships in this package (under analyzers/dotnet/cs, no reference to add) writes the PrintMembers that the generated ToString calls. It prints every member as the compiler would, shows *** for each marked one and null for a marked one that is not set. Use the same attribute for your own settings and context records. A record that is not partial, or that is nested in a type that is not, fails the build (HPSDK001) instead of printing the secret. A test of this package fails when a record has a hand written PrintMembers or a string member named after a credential that is not marked. Besides credentials, the printed form of PaymentInstruction.CustomerRef and PayerEmail, CredentialCustomerContext and PanelClientRef (Email, Name), StoredChargeInstruction (CustomerRef, MethodRef), PluginClientProfile.Email and the ClientRef of the four fulfilment contexts show ***.

Callbacks

A plugin can receive requests from outside the panels, for example a gateway telling it a payment changed. Declare the routes under api.callbacks in plugin.json (a list like api.client, PluginApi.Callbacks); the host calls IPluginEndpoints.HandleAsync with PluginCall.Area set to PluginArea.Callback. A callback route has no permission and is not streaming, because there is no signed-in caller; it may set a rateLimit. PluginApi.CallbackProblems() lists the entries that break this. The host forwards request headers in PluginCall.Headers (empty on other calls), and the plugin must verify the sender itself, for example by a signature over PluginCall.Body. Answer with PluginReply.Raw(status, bytes, contentType) when the sender expects a fixed plain answer such as OK; the status is 200 to 599 except 401 and 407.

Redirects on callback routes

A public callback route that a gateway or a browser lands on, such as the return address after a payment, can send the payer on to a page of the host with PluginReply.Redirect(location, status). The status is 301, 302, 303, 307 or 308 and 303 by default. The location is either a host relative path (one leading slash, never two, and never under the API path) or an absolute https URL without user info. It has no control character (a line break, a tab, a null, DEL or a C1 control), no leading or trailing white space and no backslash. The factory refuses anything else, and the host validates the address again before it answers, treating a bad one as a plugin fault like any other bad reply. The plugin never writes the Location header itself, and a raw reply cannot fake a redirect: raw replies are limited to media types without markup. Never build the location from the request, such as a next query parameter: an address the caller chose is an open redirect. Use a fixed path, or one assembled from values you looked up yourself. The reply kind needs a host of 3.7.0 or later.

Refunds, cancelling and idempotency

The host calls IPaymentPlugin.RefundAsync(RefundInstruction, ct). RefundInstruction.RefundId is a stable id the host stores before the first call and reuses on every retry of the same refund (after a timeout, a crash or an exception). Override that overload and pass the id to the gateway as its idempotency key, or record it yourself when the gateway has none: a repeated id must never refund twice and should answer the same reference. A plugin that only implements RefundAsync(gatewayOrderId, amountMinor, ct) keeps working, without that protection.

RefundInstruction.TransactionId (since 3.11.0) is the transaction id your plugin reported in GatewayPaymentStatus.TransactionId when the payment became paid, so a refund that needs it does not have to read the order again or keep the id in your own store. It is null when the host holds none, so keep a fallback for that, and a plugin that relies on it sets minHostVersion to the first host release that fills it.

Since 3.11.0 the older RefundAsync(gatewayOrderId, amountMinor, ct) has a default body that throws NotSupportedException, so a plugin that overrides the RefundInstruction overload does not carry a dead method. A plugin that overrides neither overload refuses the refund.

A gateway with no idempotency key can use RefundInstruction.AlreadyRefundedMinor instead of storage: it is what the host has already recorded as refunded through that gateway order before this RefundId. If the gateway reports a refunded total of at least AlreadyRefundedMinor + AmountMinor, the refund already happened (a retry), so skip it and answer the earlier reference; otherwise send it.

A plugin that can void a payment which was created but not settled also implements IPaymentCancelPlugin (CancelPaymentAsync). It is optional; a repeated cancel answers AlreadyCancelled, and a payment that can no longer be cancelled answers NotCancellable (a refund is the way back) instead of throwing.

Money in minor units

PluginMoney (Hostpanel.Sdk.Plugins.Payment, since 3.11.0) holds the conversions every payment plugin needs, so none carries its own copy. The contract speaks minor units; a gateway often wants decimal text.

var digits = PluginMoney.GetMinorUnitDigits("051");           // 2; "AMD" or "amd" give the same answer
var text = PluginMoney.ToDecimalText(1234, "USD");            // "12.34"; 1234 for "JPY" is "1234"
var minor = PluginMoney.ToMinorUnits("12.3", "USD");          // 1230
  • A currency is its ISO 4217 numeric code (what IPaymentPlugin.CurrencyCode returns) or its three letter code in any case. TryGetMinorUnitDigits answers false for a code that is not listed (precious metals, funds and test codes have no minor unit); GetMinorUnitDigits throws ArgumentException. Yen, won and a few others have 0 digits, the dinars of Bahrain, Kuwait and a few more have 3, CLF and UYW have 4, the rest have 2.
  • ToDecimalText(amountMinor, currencyOrDigits) always writes a dot, no group separator and exactly the currency's fraction digits, whatever the culture of the process, and it uses whole numbers only, so nothing is rounded. A negative amount keeps its sign ("-0.05").
  • ToMinorUnits(text, currencyOrDigits) accepts an optional minus sign, digits and an optional dot with digits. Fewer fraction digits than the currency has are padded; more are accepted only when they are zero ("12.500" is 1250 for two digits), because anything else would lose part of the amount. Anything else, including white space, a plus sign, a comma or an exponent, is a FormatException; an amount that does not fit a long is an OverflowException. Neither message repeats the text.

Provisioning panel plugins

A hosting control panel is a provisioning plugin that also implements IProvisioningPanelPlugin, which extends the IProvisioningPlugin marker. The marker and ProvisioningProviderBase do not change, so a provisioning plugin built on 3.0.0 compiles and loads as before, with no panel operations. List provisioningPanel in the manifest's capabilities; the list must agree with the code. One plugin serves every server of its panel type: each call carries the server as a PanelServerConnection with the credentials the host stores, so keep no per-server state.

Operation Context Result Repeat
CreateAccountAsync PanelCreateAccountContext PanelCreateResult An account already held under the same user name is AlreadyApplied with the same ProvisioningRef
SuspendAccountAsync PanelSuspendContext PanelActionResult Already suspended is a success
UnsuspendAccountAsync PanelAccountContext PanelActionResult Already active is a success
TerminateAccountAsync PanelTerminateContext PanelActionResult Already gone is AlreadyApplied, never NotFound
ChangePackageAsync PanelChangePackageContext PanelActionResult Already on the package is a success
ChangePasswordAsync PanelChangePasswordContext PanelActionResult Sets it again and succeeds
CreateSsoLinkAsync PanelSsoContext PanelSsoResult Issues a new link each time
GetUsageAsync PanelAccountContext PanelUsageResult Read only
TestConnectionAsync PanelTestConnectionContext PanelConnectionTestResult Never throws for an unreachable panel
ListAccountsAsync PanelListAccountsContext PanelAccountListResult Read only, paged by NextCursor
  • Outcomes, not exceptions. Every operation answers a PanelOperationOutcome (Succeeded, AlreadyApplied, NotFound, Refused, NotSupported, and since 3.11.0 Pending); the test answers a PanelConnectionOutcome. The values start at 1 and 0 is not valid. A refusal carries a PanelRefusalReason and the host turns it into a sentence in the caller's language. Throw only when you do not know what happened, for example when the panel could not be reached: the host then retries, which is safe because of the next point.

  • Idempotency. The host retries after a lost answer. It chooses the user name of a create and stores it before the first call, so the create is keyed by PanelCreateAccountContext.Username. When the panel refuses a repeat, look the account up and answer from what you find instead of repeating the refusal.

  • No panel text, no secrets. A result never contains the panel's own error text (it can carry a user name, a domain or an address) or a secret. Log the detail and answer a reason. AccessHash, ApiToken, Password, NewPassword and the single sign on link print as ***; do not undo that in your own logs.

  • Packages and references. PanelPackage.Name is the name as the panel knows it. PanelService.ProvisioningRef is exactly what your CreateAccountAsync returned; it is null only for the create.

  • Usage is in bytes, and every figure is optional: report what the panel has.

  • Network. Take an IPanelTransport in the constructor and send every request on CreateClient(). Never create your own HttpClient: only the transport is routed through the host's outbound address guard, private route map, timeouts and no retry rule. The client has no base address; build it from PanelServerConnection (UseSsl; a null Port means your own default port) and set the authorization header per request.

  • Server modules. List the module ids the plugin serves in serverModules of plugin.json (ASCII letters, digits, dash, dot, underscore, at most 50, no duplicates). PluginServerModules.Validate checks the list.

  • Addresses. PanelAccount.ControlPanelUrl and PanelCreateResult.ControlPanelUrl are the account's control panel login page when the panel tells it; they are not sign-in links. PanelAccount.IpAddress (since 3.15.0, an init property, null when the panel does not say) is the IP address the account is served on, in text form.

  • Reading one account. A panel that can read a single account also implements IProvisioningPanelAccountPlugin, which extends IProvisioningPanelPlugin; the interface it extends does not change, so a panel plugin built earlier loads and runs as before and is not asked. List provisioningPanelAccount (PluginCapabilities.ProvisioningPanelAccount) in the manifest's capabilities; it needs provisioningPanel as well. GetAccountAsync(PanelAccountContext, CancellationToken) is a read, so a repeat is safe. It answers Succeeded with the PanelAccount (its ProvisioningRef is the one that was asked for), NotFound for an account the panel does not hold, NotSupported or Refused with a PanelRefusalReason. ProvisioningContract.AssertAccountIsWellFormedAsync checks the promise in the plugin's own tests. A plugin that uses it sets minHostVersion to the first host release that calls it.

  • The old panel area is obsolete. IHostingPanelApiClient, IHostingPanelV7ApiClient and the types beside them (Hostpanel.Sdk.Plugins.HostingPanel) are marked [Obsolete]; move to IProvisioningPanelPlugin. The area is removed in 4.0.0.

  • Listing is for reconciliation: following NextCursor to the end returns every account once, and a panel that returns everything at once answers null as the cursor.

  • Pending (since 3.11.0). A panel that accepts a create, a suspend, a terminate, a package change or a password change and finishes it in the background answers PanelOperationOutcome.Pending through PanelActionResult.Pending() or PanelCreateResult.Pending(provisioningRef). The host repeats the same call later; the repeat answers Pending until the work is done and then Succeeded or AlreadyApplied. A pending create already carries its ProvisioningRef. A host built before 3.11.0 treats the unknown value as an unfinished call.

  • Connection roles (since 3.11.0). The host builds the RegistrarConnection from the settings the admin saved for the plugin, and each plugin names its settings differently, so a setting says which member it fills in connectionRole (RegistrarConnectionRole: accountName, apiKey, apiUrl, clientIp, testMode). The member is optional and null by default, and a plugin without roles loads and runs as before. The package checker refuses a role on a plugin that is not a registrar plugin, the same role on two settings, an apiKey on a setting that is not secret, an apiUrl on one that is not url, a testMode on one that is not boolean, and a registrar plugin that declares any role without declaring both accountName and apiKey:

    "settings": [
      { "key": "username", "label": "settings.username", "type": "text", "required": true, "connectionRole": "accountName" },
      { "key": "apiKey", "label": "settings.apiKey", "type": "secret", "required": true, "connectionRole": "apiKey" },
      { "key": "apiUrl", "label": "settings.apiUrl", "type": "url", "connectionRole": "apiUrl" },
      { "key": "sandbox", "label": "settings.sandbox", "type": "boolean", "connectionRole": "testMode" }
    ]
  • Optional members (since 3.11.0). They are init members with a null or default value, so every constructor keeps its shape and a plugin sets or reads them with an object initializer. PanelUsage adds InodesUsed, InodesLimit, MailboxesUsed, MailboxesLimit, DatabasesUsed, DatabasesLimit, DomainsUsed and DomainsLimit. PanelSsoContext.TargetPath is the page of the control panel the link opens on (a path that starts with a slash; a plugin that cannot map it opens the landing page). PanelCreateAccountContext.Level and PanelListAccountsContext.Level are a PanelAccountLevel (User or Reseller), and null means an ordinary account; a panel with no resellers refuses a reseller create with PanelRefusalReason.Other. PanelChangePackageContext.ProductOptions carries the per product choices the host stores next to the package; ignore a key you do not know.

  • Addresses. PanelServerAddress.BaseUrl(server, defaultPort) and BaseUri build the base address of a server from its saved scheme, host name and port (your default when none is saved), with the brackets an IPv6 literal needs. They refuse a host name that carries a path, a query, credentials or white space with an ArgumentException, so use them instead of a copy of your own.

The optional interfaces and capabilities of a panel plugin:

Interface Capability What it adds
IProvisioningPanelPlugin provisioningPanel The operations above
IProvisioningPanelLoginPlugin provisioningPanelLogin Login details and the panel password
IProvisioningPanelPackagesPlugin provisioningPanelPackages (needs provisioningPanel) ListPackagesAsync: the packages of a server with their limits (PanelPackageDetails), read only
IProvisioningPanelAccountPlugin provisioningPanelAccount (needs provisioningPanel) GetAccountAsync: one account by its reference (PanelAccount), read only

In the plugin's own tests, run the ProvisioningContract checks against a stub of your panel: AssertCreateIsIdempotentAsync, AssertSuspendIsIdempotentAsync, AssertUnsuspendIsIdempotentAsync, AssertTerminateIsIdempotentAsync, AssertChangePackageIsIdempotentAsync, AssertChangePasswordIsIdempotentAsync, AssertUnknownAccountIsNotFoundAsync, AssertTestConnectionAnswersAsync, AssertListAccountsIsCompleteAsync, AssertPackagesAreWellFormedAsync, AssertAccountIsWellFormedAsync and AssertHidesSecrets. Each throws PluginContractViolationException naming the promise that was broken. The idempotency checks accept Pending.

Login details and a panel password

A panel that can tell the host how a client signs in to an account also implements IProvisioningPanelLoginPlugin, which extends IProvisioningPanelPlugin; the interface it extends does not change, so a panel plugin built earlier loads and runs as before and is not asked. List provisioningPanelLogin (PluginCapabilities.ProvisioningPanelLogin) in the manifest's capabilities. GetLoginDetailsAsync(PanelAccountContext, CancellationToken) is a read, so a repeat is safe. It answers Succeeded with a PanelLoginDetails (Username, Password, Domain, ServerIp, LoginUrl), NotFound for an account the panel does not hold, NotSupported for a panel with no sign-in page to show, or Refused with a PanelRefusalReason. Password is null unless the panel reveals one and prints as ***; LoginUrl is the absolute http or https address of the sign-in page, never a single sign on link, which carries a credential.

PanelServerConnection.Password is the password of the panel user for a panel that signs in with a user name and a password. It is null for a panel that uses an access key or a token, and prints as ***. A host that does not fill it leaves it null, so a plugin that reads it sets minHostVersion to the first host release that does.

ProvisioningContract.AssertLoginDetailsAreReadableAsync and AssertUnknownAccountLoginIsNotFoundAsync check these promises in the plugin's own tests.

An SSH key agent profile

The host keeps one SSH key agent as shared infrastructure for the servers of panel plugins. A panel plugin that wants its servers served by it ships its own agent profile in its package and names it in the manifest's sshAgentProfile, for example "sshAgentProfile": "examplepanel". The id is lower case letters and digits in words joined by single hyphens, at most 32 characters (PluginSshAgentLayout.IsValidProfileId), and generic-linux is the host's own and cannot be named. Only a plugin that declares the provisioningPanel capability may name one. A manifest that breaks this is refused by PluginManifestChecker.Validate with PluginManifestRule.SshAgentProfileInvalid or SshAgentProfileNotAllowed.

The package carries the profile at agent/profile.conf (PluginSshAgentLayout.ProfileFile) and, when the profile needs them, one file per helper directly in agent/helpers (PluginSshAgentLayout.HelperDirectory):

  • the profile is at most 8 KiB, in the agent's [agent] section format with one key = value per line, sets only keys the agent defines, has provider equal to the id in sshAgentProfile, leaves binding empty (the host fills it per server) and keeps account_check_command and helper_dir inside /usr/local/libexec/hostpanel-ssh-key-agent;
  • a package carries at most 32 helpers of at most 64 KiB each, named by PluginSshAgentLayout.IsValidHelperName (a letter or digit, then letters, digits, dots, underscores or hyphens, at most 64 characters);
  • nothing on the way to these files is a link.

PluginAgentPackageChecker.Check(packageDirectory, manifest.SshAgentProfile) in Hostpanel.Sdk.Packaging checks all of it and hands back the bytes it checked, or a PluginAgentRule with a detail that names a package path or a profile key and never a value from the file; run it in your release pipeline before you publish. Without sshAgentProfile (the default, null) the plugin's servers have no SSH key agent profile. A host that does not read the field ignores it, so a plugin that needs it sets minHostVersion to the first host release that does.

The earlier agentProfile member and PluginAgentProfiles (a fixed list of profile names) are deprecated and will be removed in 4.0.0; they still read and validate as before.

Panels with a self signed certificate

Many hosting panels answer on a private port with a self signed certificate. Whether to trust one is the operator's decision, made per server with the setting "accept a self signed certificate", never the plugin's: a plugin may not create its own handler to accept a certificate. Ask for the client of the server you are talking to with transport.CreateClient(server) instead of CreateClient(). A host that supports the setting returns a client that accepts the certificate of that one host name and port and of nothing else, and keeps every other rule of the transport (address guard, timeouts, no retry). A 3.7.0 host that does not know the setting returns the plain client, because the default body of the method calls CreateClient(). A host older than 3.7.0 has no such member and the call throws MissingMethodException, so a plugin that uses it sets minHostVersion to 3.7.0. In the plugin's own tests, start a SelfSignedListener, describe it as a PanelServerConnection (its HostName and Port), and run PanelTransportContract.AssertSelfSignedIsRefusedByDefaultAsync and AssertSelfSignedIsAcceptedForTheServerOnlyAsync against the transport you test with. The second check also proves that the allowance stops at the server's own host name and port. The host's address guard may refuse a loopback address, so the listener is for the tests of a plugin, with a transport double, and not for a transport behind that guard.

The account id of a server

A panel that scopes every API call with an organisation, reseller or tenant id next to the credentials reads it from PanelServerConnection.AccountId. Do not ask the operator to type it into the user name or to join it to the user name with a separator. Set serverAccountIdLabel in plugin.json (for example "Reseller ID") to turn on a field of the server form with that label, shown only for servers that use your plugin; without the label the field stays off and AccountId is null. The label is 1 to 60 characters with no control character, and it is a literal shown as it is or a text key defined in the manifest's locales, like the other labels; PluginManifestChecker reports AccountIdLabelInvalid for a bad one. The id is not a secret, so it prints in ToString; AccessHash and ApiToken stay masked.

Registrar plugins

A domain registrar is a registrar plugin that also implements IRegistrarOperationsPlugin, which extends the IRegistrarPlugin marker. The marker and RegistrarProviderBase do not change, so a registrar plugin built on an earlier version compiles and loads as before, with no operations. List registrarOperations in the manifest's capabilities; the list must agree with the code. One plugin serves one registrar account: each call carries it as a RegistrarConnection (account name, ApiKey, optional ApiUrl and ClientIp, TestMode), so keep no state between calls.

Operation Context Result Repeat
CheckAvailabilityAsync RegistrarAvailabilityContext ValueResult<RegistrarAvailability, RegistrarRefusalReason> Read only
RegisterAsync RegistrarRegisterContext ValueResult<RegistrarOrder, RegistrarRefusalReason> A domain the account already holds is AlreadyApplied with the same RegistrarRef
TransferAsync RegistrarTransferContext ValueResult<RegistrarOrder, RegistrarRefusalReason> A transfer already under way or complete is AlreadyApplied
RenewAsync RegistrarRenewContext ValueResult<RegistrarOrder, RegistrarRefusalReason> An expiry already at or past CurrentExpiresAt plus the years is AlreadyApplied
CheckDomainActiveAsync RegistrarDomainContext ValueResult<RegistrarOrder, RegistrarRefusalReason> Read only, for an order that answered RequiresPolling
CancelTransferAsync, InitiateOutgoingTransferAsync RegistrarDomainContext OperationResult<RegistrarRefusalReason> Already cancelled or prepared is a success
GetEppCodeAsync RegistrarDomainContext ValueResult<RegistrarEppCode, RegistrarRefusalReason> Read only; the code prints as ***
SetNameserversAsync RegistrarNameserversContext OperationResult<RegistrarRefusalReason> The same list is a success
SetAutoRenewAsync, SetWhoisPrivacyAsync, SetRegistrarLockAsync RegistrarFlagContext OperationResult<RegistrarRefusalReason> The state already wanted is a success
GetContactAsync RegistrarDomainContext ValueResult<RegistrarContact, RegistrarRefusalReason> Read only
SetContactAsync RegistrarContactContext OperationResult<RegistrarRefusalReason> The same contact is a success
GetDnsRecordsAsync RegistrarDomainContext ValueResult<IReadOnlyList<RegistrarDnsRecord>, RegistrarRefusalReason> Read only
AddDnsRecordAsync RegistrarDnsRecordContext OperationResult<RegistrarRefusalReason> The same record is a success
UpdateDnsRecordAsync RegistrarDnsRecordUpdateContext OperationResult<RegistrarRefusalReason> The updated content already there is a success
DeleteDnsRecordAsync RegistrarDnsRecordRemovalContext OperationResult<RegistrarRefusalReason> A record already gone is AlreadyApplied, never NotFound
GetTldPricingAsync RegistrarPricingContext ValueResult<IReadOnlyList<RegistrarTldPricing>, RegistrarRefusalReason> Read only
SetEmailForwardingAsync RegistrarFlagContext OperationResult<RegistrarRefusalReason> Optional interface; the state already wanted is a success
AddEmailForwardingRuleAsync, UpdateEmailForwardingRuleAsync RegistrarEmailForwardingRuleContext OperationResult<RegistrarRefusalReason> Optional interface; the same rule is a success
DeleteEmailForwardingRuleAsync RegistrarEmailForwardingRemovalContext OperationResult<RegistrarRefusalReason> Optional interface; a rule already gone is AlreadyApplied
SetDnsManagementAsync RegistrarFlagContext OperationResult<RegistrarRefusalReason> Optional interface; the state already wanted is a success
GetWhoisAsync RegistrarWhoisContext ValueResult<RegistrarWhois, RegistrarRefusalReason> Optional interface; read only
TestConnectionAsync RegistrarTestConnectionContext PanelConnectionTestResult Never throws for an unreachable registrar
  • Outcomes, not exceptions. Every operation answers a PanelOperationOutcome (Succeeded, AlreadyApplied, NotFound, Refused, NotSupported), the same one the provisioning contracts use; the test answers a PanelConnectionOutcome. A refusal carries a RegistrarRefusalReason. Throw only when you do not know what happened, for example when the registrar could not be reached: the host then retries, which is safe because of the idempotency column above. A purchase is a success only when the registrar did it; a registrar that is not configured refuses.

  • No registrar text, no secrets. A result never contains the registrar's own error text (it can carry a domain or a contact detail) or a secret. ApiKey and the authorization code print as ***; do not undo that in your own logs.

  • Orders. RegistrarOrder.RequiresPolling is true while the registrar has accepted an order but not finished it, as a transfer in usually is; the host then calls CheckDomainActiveAsync until it is false. ExpiresAt is null when the registrar does not say, and the host extends the expiry it holds.

  • Network. Take an IPanelTransport in the constructor and send every request on CreateClient(); never create your own HttpClient. The client has no base address, so build it from RegistrarConnection.ApiUrl or your own default, and honour TestMode by calling the sandbox API and never the live one.

  • Optional operations are separate interfaces. E-mail forwarding (IRegistrarEmailForwardingPlugin: SetEmailForwardingAsync, AddEmailForwardingRuleAsync, UpdateEmailForwardingRuleAsync, DeleteEmailForwardingRuleAsync), the DNS management switch (IRegistrarDnsManagementPlugin: SetDnsManagementAsync) and the WHOIS lookup (IRegistrarWhoisPlugin: GetWhoisAsync) extend IRegistrarOperationsPlugin, each with its own capability (registrarEmailForwarding, registrarDnsManagement, registrarWhois). A host treats a plugin that does not implement one as NotSupported for it. New operations always arrive as new interfaces, never as members of an existing one. Since 3.11.0 there are six more:

    Interface Capability Operations
    IRegistrarChildNameserversPlugin registrarChildNameservers CreateChildNameserverAsync, UpdateChildNameserverAsync, DeleteChildNameserverAsync (a host already gone is AlreadyApplied)
    IRegistrarDnssecPlugin registrarDnssec GetDnssecAsync, SetDnssecAsync (the whole list of RegistrarDsRecord; an empty list turns DNSSEC off)
    IRegistrarRestorePlugin registrarRestore RestoreDomainAsync from redemption, charged once
    IRegistrarDomainListPlugin registrarDomainList ListDomainsAsync, paged by RegistrarDomainPage.NextCursor, for import
    IRegistrarSuggestionsPlugin registrarSuggestions GetSuggestionsAsync: at most Limit names, each with an optional RegistrarPremiumPrice
    IRegistrarBalancePlugin registrarBalance GetBalanceAsync: a RegistrarBalance of currency and amount
  • Optional members (since 3.11.0). They are init members with a default, so every constructor keeps its shape and a plugin that ignores them behaves as before. A registration, a transfer and a contact change carry RoleContacts (the administrative, technical and billing contacts; read them with AdminOr(registrant), TechnicalOr and BillingOr, which fall back to the registrant in one place) and ExtendedAttributes (the registry specific attributes of a top level domain, by the registry's own key). A registration and a transfer also carry Agreement, the end user's address and the moment they accepted the terms, for a registrar that records consent. RegistrarTransferContext.Years is 1 by default. RegistrarDnsRecord has Proxied and Comment, and RegistrarDnsRecordType.Caa is a record type. A RegistrarAvailability may say why a name cannot be registered or what makes it special in Reason (RegistrarAvailabilityReason) and carry a PremiumPrice; null means the registrar did not say. The extended attributes and the agreement address are personal data and print as ***.

  • Domain fields (since 3.17.0). A registry that needs more than the standard contact says so in the manifest, so the host knows what to ask for and the order can be placed. domainFields is a block of manifest version 2 for registrar plugins only (PluginManifest.DomainFields, empty when absent). Each entry is a PluginDomainFieldSet: zones (lower case ASCII suffixes without a leading dot, such as com, co.uk or the punycode xn--p1ai; a domain belongs to a zone when it ends with a dot and the zone, and the longest zone wins), holder (PluginDomainHolder: any, the default, individual or organization), operations (PluginDomainOperations flags, written as a comma separated list of register, transfer and contactChange; all three when absent) and fields. A set with no fields states that its zones need none, which overrides a shorter zone. Each PluginDomainField has key (the registry's own name, passed back unchanged as the key of ExtendedAttributes), label, description and placeholder (text keys of the manifest locales, or plain text), type (PluginDomainFieldType: text, textarea, select, date, number, url), required, pattern (a regular expression the whole value must match), minLength, maxLength and, for a select, options (value and label). A date travels as yyyy-MM-dd.

    "manifestVersion": 2,
    "domainFields": [
      { "zones": ["us"], "holder": "organization", "operations": "register, transfer",
        "fields": [
          { "key": "nexus", "label": "domain.nexus", "type": "select", "required": true,
            "options": [ { "value": "c11", "label": "domain.nexus.c11" }, { "value": "c21", "label": "domain.nexus.c21" } ] },
          { "key": "taxId", "label": "domain.taxId", "type": "text", "pattern": "[0-9]{9}", "minLength": 9, "maxLength": 9 }
        ] }
    ]

    PluginDomainFieldRules is the one implementation of the rules, for the host and for a plugin's own tests. Match(manifest, domainName, holder, operation) answers the fields of one domain (case is ignored, a unicode name is read as punycode, and a holder of any matches only the sets written for any holder). Validate(fields, attributes) answers a PluginDomainFieldViolation (the key and a PluginDomainFieldViolationReason: Unknown, Required, Pattern, Length, Option or Format) for each value that is refused, and an empty list when they are acceptable. The package checker refuses the block on any other plugin type, a key or zone that is not well formed, a key twice in a set, a zone named twice by sets that apply to the same registrant and operation, options on a field that is not a select (or a select without them), a pattern that is invalid, over 200 characters or runs too long, and bad length bounds; every label, description, placeholder and option label that is a text key needs an en text. A plugin that declares the block sets minHostVersion to the first host release that asks for the fields.

  • DNS records have no registrar id on the host side. RegistrarDnsRecordUpdateContext carries the record as it is now and the content it should have, and RegistrarDnsRecordRemovalContext carries the whole record; find the record by type, host and value, and use RegistrarDnsRecord.Id only when it is given. A delete of a record that is gone is AlreadyApplied; a delete on a domain the registrar does not hold is NotFound.

  • Personal data. RegistrarContact and the registrant of RegistrarWhois print masked, so a context or a result that holds them does not leak them into a log line.

In the plugin's own tests, run the RegistrarContract checks against a stub of your registrar: AssertRegisterIsIdempotentAsync, AssertTransferIsIdempotentAsync, AssertRenewIsIdempotentAsync, AssertSetNameserversIsIdempotentAsync, AssertSetAutoRenewIsIdempotentAsync, AssertSetWhoisPrivacyIsIdempotentAsync, AssertSetRegistrarLockIsIdempotentAsync, AssertSetContactIsIdempotentAsync, AssertAddDnsRecordIsIdempotentAsync, AssertUpdateDnsRecordIsIdempotentAsync, AssertDeleteDnsRecordIsIdempotentAsync, AssertCancelTransferIsIdempotentAsync, AssertInitiateOutgoingTransferIsIdempotentAsync, the matching checks for the optional interfaces (AssertSetEmailForwardingIsIdempotentAsync, AssertAddEmailForwardingRuleIsIdempotentAsync, AssertUpdateEmailForwardingRuleIsIdempotentAsync, AssertDeleteEmailForwardingRuleIsIdempotentAsync, AssertSetDnsManagementIsIdempotentAsync, AssertWhoisAnswersAsync, and since 3.11.0 AssertCreateChildNameserverIsIdempotentAsync, AssertUpdateChildNameserverIsIdempotentAsync, AssertDeleteChildNameserverIsIdempotentAsync, AssertSetDnssecIsIdempotentAsync, AssertRestoreIsIdempotentAsync), AssertReadsAnswerValuesAsync, AssertOptionalReadsAnswerValuesAsync (the DNSSEC, domain list, suggestion and balance reads), AssertUnknownDomainIsNotFoundAsync, AssertTestConnectionAnswersAsync and AssertHidesSecrets. Each throws PluginContractViolationException naming the promise that was broken.

Virtual server plugins

A virtual server or cloud platform is a provisioning plugin that also implements IVirtualServerPlugin, which extends the IProvisioningPlugin marker. It is a capability of the provisioning type and not a new plugin type: a virtual server is a service provisioned on a server the host knows, like a hosting account, and the plugin type values do not change. The marker, ProvisioningProviderBase and IProvisioningPanelPlugin do not change either. List virtualServer in the manifest's capabilities and the module ids the plugin serves in serverModules; the lists must agree with the code. The vocabulary is the one of the panel contract: the platform arrives as a PanelServerConnection, the service as a PanelService whose ProvisioningRef is what CreateServerAsync returned, and the answers are PanelActionResult and ValueResult<T, PanelRefusalReason>.

Operation Context Result Repeat
CreateServerAsync VirtualServerCreateContext ValueResult<VirtualServerInstance, PanelRefusalReason> A server already held under the same Name is AlreadyApplied with the same ProvisioningRef
StartServerAsync, StopServerAsync PanelAccountContext PanelActionResult Already running or stopped is a success; starting a suspended server is Refused with AccessDenied
RebootServerAsync PanelAccountContext PanelActionResult Restarts again each time
SuspendServerAsync PanelSuspendContext PanelActionResult Already suspended is a success
UnsuspendServerAsync PanelAccountContext PanelActionResult Not suspended is a success
TerminateServerAsync PanelTerminateContext PanelActionResult Already gone is AlreadyApplied, never NotFound
RebuildServerAsync VirtualServerRebuildContext ValueResult<VirtualServerRootPassword, PanelRefusalReason> Erases the disk again each time
ChangePlanAsync PanelChangePackageContext PanelActionResult Already on the plan is a success
ResetRootPasswordAsync PanelChangePasswordContext ValueResult<VirtualServerRootPassword, PanelRefusalReason> Sets it again and succeeds
CreateConsoleSessionAsync PanelAccountContext ValueResult<VirtualServerConsole, PanelRefusalReason> Issues a new address each time
GetServerUsageAsync PanelAccountContext ValueResult<VirtualServerUsage, PanelRefusalReason> Read only
ListImagesAsync, ListPlansAsync VirtualServerCatalogContext ValueResult<IReadOnlyList<...>, PanelRefusalReason> Read only
ListServersAsync PanelListAccountsContext PanelAccountListResult Optional interface IVirtualServerListPlugin (capability virtualServerList); read only, paged by NextCursor, a server is a PanelAccount
TestServerConnectionAsync PanelTestConnectionContext PanelConnectionTestResult Never throws for an unreachable platform
  • Outcomes, idempotency, secrets and network follow the panel contract: outcomes instead of exceptions, a stable create keyed by the name the host stores before the first call, no platform text in a result, and every request on the IPanelTransport client. PanelRefusalReason gains ImageUnknown and NameInvalid for this contract; the plan name travels in PanelPackage.Name and is a name ListPlansAsync returned.

  • Passwords. The host sends the root password to set. A platform that cannot set one generates it and answers it in VirtualServerInstance.GeneratedPassword or VirtualServerRootPassword.GeneratedPassword; both print as ***. The console address in VirtualServerConsole.Url is a credential and prints as *** too.

  • Usage is in bytes, and every figure is optional: report what the platform has.

  • Suspension. A platform with no suspension of its own powers the server off and keeps the client from starting it in whatever way the platform allows; UnsuspendServerAsync lifts that and does not power the server on.

  • Optional members (since 3.11.0). VirtualServerCreateContext.ProductOptions carries the per product choices the host stores next to the plan (a region, backups, an IPv6 address); ignore a key you do not know and refuse a value you do not accept with PanelRefusalReason.Other. VirtualServerRebuildContext.SshPublicKey is a key to authorize after the rebuild, which erases the earlier ones. VirtualServerInstance.PasswordUnknown is true for a repeated create whose generated password the host never received: answer AlreadyApplied with no GeneratedPassword, and the host offers a root password reset. An operation the platform finishes in the background answers Pending, as for a panel.

  • Optional interfaces (since 3.11.0). Each extends IVirtualServerPlugin, and its capability needs virtualServer as well:

    Interface Capability Operations
    IVirtualServerListPlugin virtualServerList ListServersAsync for reconciliation
    IVirtualServerSnapshotPlugin virtualServerSnapshots List, create (idempotent on the name the host chooses), restore and delete a snapshot
    IVirtualServerBackupPlugin virtualServerBackups The same four operations for backups
    IVirtualServerFirewallPlugin virtualServerFirewall GetFirewallRulesAsync and SetFirewallRulesAsync, which replaces the whole set of VirtualServerFirewallRule

    The console is not a separate interface: CreateConsoleSessionAsync is a member of IVirtualServerPlugin. A plugin that lists the capability virtualServerConsole (which needs virtualServer as well) promises that it supports it, so the host shows the console action up front. A plugin without it may still answer NotSupported when the call is made.

    Snapshots and backups are listed as VirtualServerRestorePoint. A delete of a restore point that is gone is AlreadyApplied, never NotFound, and a restore replaces the server's disk, so the host sends it only on the client's explicit request. A firewall rule has ports only for TCP and UDP, between 1 and 65535, and a range does not run backwards.

In the plugin's own tests, run the VirtualServerContract checks against a stub of your platform: AssertCreateIsIdempotentAsync, AssertStartIsIdempotentAsync, AssertStopIsIdempotentAsync, AssertSuspendIsIdempotentAsync, AssertUnsuspendIsIdempotentAsync, AssertTerminateIsIdempotentAsync, AssertChangePlanIsIdempotentAsync, AssertSuspendedServerIsNotStartedAsync, AssertUnknownServerIsNotFoundAsync, AssertReadsAnswerValuesAsync, AssertCatalogIsWellFormedAsync, AssertListServersIsCompleteAsync, AssertTestConnectionAnswersAsync and AssertHidesSecrets; since 3.11.0 also AssertLostPasswordIsReportedAsync, AssertCreateSnapshotIsIdempotentAsync, AssertDeleteSnapshotIsIdempotentAsync, AssertSnapshotsAreWellFormedAsync, AssertCreateBackupIsIdempotentAsync, AssertDeleteBackupIsIdempotentAsync, AssertBackupsAreWellFormedAsync, AssertSetFirewallRulesIsIdempotentAsync and AssertFirewallRulesAreWellFormedAsync. Each throws PluginContractViolationException naming the promise that was broken.

Choosing the session kind

CreatePaymentAsync answers a PaymentSession, and a session is exactly one PaymentSessionKind:

Kind When What the plugin fills
Redirect (1) the gateway has a hosted page the payer opens with a plain GET (the default) RedirectUrl
FormPost (2) the hosted page is opened with a POST that carries a token or other fields FormPost, and the same address as RedirectUrl
BrowserStep (3) the payer completes a step in the browser (a card field that produces a nonce) before the payment can be charged RedirectUrl (the page of the step) and Kind

Choose the redirect whenever the gateway offers one, because it needs no form and no wait. Kind is optional and Redirect by default. Kind and FormPost always agree, and a session whose pair contradicts is refused, in the constructor and in a with expression, whatever the order: FormPost is required with Kind.FormPost and allowed with nothing else, and a value that is not defined is refused. The constructor without a Kind derives it (a form gives FormPost, none gives Redirect). To change a session between FormPost and another kind, build a new session; a with expression cannot, because each change is checked on its own. RedirectUrl is never empty.

For a form post the plugin only describes the form. The host renders the page and applies its own rules: the action must be an absolute https URL without user info or line breaks, field names are not empty, names and values are encoded as attribute text, no script from the plugin is ever included, and the page has a button that submits the form for a payer whose browser runs no script. The form keeps within PaymentFormPostLimits (at most 64 fields, names up to 128 and values up to 8192 characters, an action up to 2048). A session that breaks a rule is a failed payment.

For a browser step the flow is:

  1. CreatePaymentAsync answers new PaymentSession(orderId, stepPageUrl, null, PaymentSessionKind.BrowserStep).
  2. The host sends the payer to the page; the payer completes the step with the gateway's own page or script, which puts the result (a nonce, a payer id) in the query of the return address.
  3. The host waits for that return request instead of reading the status, calls IPaymentReturnPlugin.CompleteAsync with its parameters (see the next section), and only then reads the status.

A plugin that answers BrowserStep therefore implements IPaymentReturnPlugin and lists paymentReturn in its manifest. The SDK cannot see the plugin class from a session, so the host, not the SDK, checks that the plugin implements the interface; a session of this kind from a plugin without it is a failed payment. A host older than 3.7.0 does not know the kind and treats the session as a redirect.

Completing a payment from the return request

Some gateways finish a payment with a value only the payer's browser has when it comes back. A plugin that needs it implements IPaymentReturnPlugin beside IPaymentPlugin and lists paymentReturn (PluginCapabilities.PaymentReturn) in capabilities; the host checks for the interface at run time, so a plugin without it is unchanged. The host calls CompleteAsync(gatewayOrderId, returnParameters, ct) with the query parameters of the return request (and the posted fields of a browser step) before it reads the status, and the plugin answers the status the payment is in. The host picks the names that reach the plugin and keeps within PaymentReturnLimits (at most 32 parameters, names up to 64 and values up to 2048 characters); it never passes credentials, cookies or headers. Names are compared ordinally, and when a name arrives more than once the first value wins. The set is read only and comes from the payer's browser, so treat it as untrusted input. CompleteAsync is idempotent: a payer who returns twice must not be charged twice.

The plugin never serves a page. The browser gets the value from the gateway: from its hosted page, or from the gateway's own script on the page that PaymentSession.RedirectUrl names. It then comes back to the host's return address with the value in the query, and the host passes it on.

  • A nonce style gateway (the browser obtains a payment method nonce from the gateway): CompleteAsync reads the nonce parameter, charges the order at the gateway with it once, and answers Paid or Declined.
  • A payer id style gateway (the return address carries the payer id and a token): CompleteAsync reads both, asks the gateway to execute the approved payment, and answers its status. A return without them answers Pending.

Saving the method during a payment

To let a payer save the method they pay with, the host sets PaymentInstruction.SavePaymentMethod to true. A plugin that supports it asks the gateway to store the method and, when GetStatusAsync reports the payment as paid, returns it in GatewayPaymentStatus.SavedMethod (a SavedMethod: token reference, brand, last four digits and expiry). A plugin that does not support it ignores the flag and leaves SavedMethod null; the host treats that as "not saved" and the payment itself is unaffected. Both members are optional, so a plugin that never saves methods needs no change.

The host also sets PaymentInstruction.CustomerRef on a saving payment: the gateway customer it got from IStoredCredentialPlugin.EnsureCustomerAsync. A plugin attaches the stored method to that customer, so the later stored charge for the same reference finds it. It is optional and null when no method is saved.

The payer's e-mail address

Some gateways refuse to create a payment without an e-mail address. The host sets PaymentInstruction.PayerEmail to the address of the client the invoice belongs to when it knows one, and leaves it null otherwise, so null is a normal value: a plugin that needs an address answers a refusal the host can show, and never invents or fixes one. The address is personal data. Send it only to your own gateway, never write it to a log, and do not undo that the record prints it as ***. A plugin that does not read it needs no change.

Payer details, invoice lines and the callback address

Since 3.11.0 PaymentInstruction carries optional members for gateways that ask for more than an amount. Every one is null when the host does not know it, and a plugin that does not read them needs no change.

Member What it is Printed as
BillingCountry The client's billing country, ISO 3166-1 alpha-2 as it is
PayerName, PayerPhone, ClientTaxId Personal data of the payer, for a gateway that requires them ***
DueAt When the invoice falls due, for a gateway that shows or enforces a deadline as it is
Lines The invoice lines as PaymentInvoiceLine(Description, Quantity, UnitAmountMinor); compared by reference as it is
CallbackBaseUrl The absolute public base URL of the plugin's api.callbacks routes, no trailing slash as it is

Append a declared callback route to CallbackBaseUrl to tell the gateway where to notify, so the plugin never has to guess its own public address; it is null on a host that does not fill it, and then the plugin keeps its own setting. It is on the instruction because CreatePaymentAsync is the one call that has no PluginCall, so no host API. A plugin that relies on any of these members sets minHostVersion to the first host release that fills them.

Stored credential plugins

A payment plugin may also implement IStoredCredentialPlugin to keep payment methods at the gateway and charge them later without the payer present. The interface extends IPaymentPlugin, so the implementing class must be a payment plugin too, and IPaymentPlugin itself does not change. In the plugin's own tests, call StoredCredentialContract.AssertCompleteSaveMethodIsIdempotentAsync(plugin, sessionId) to check that CompleteSaveMethodAsync answers the same result on every call for one session. The host checks for the interface at run time; a disabled plugin, or one without the interface, has no such capability. List storedCredentials in the manifest's capabilities so the admin and the client portal know without activating the plugin; the list must agree with the code.

  • Outcomes. ChargeAsync answers a StoredChargeOutcome. Succeeded means the money is taken: set TransactionId and report the amount and currency so the host can refuse a mismatch. Declined is final. ActionRequired means the payer must authenticate; set ActionUrl. Pending is accepted but not settled: the host never treats it as paid and resolves it later through FindChargeAsync.
  • A refusal is an outcome, not an exception. Throw only when the outcome is unknown, for example when the gateway could not be reached.
  • Idempotency. The host creates the IdempotencyKey once per attempt and stores it before calling you. A retry of the same attempt reuses it, so a repeated ChargeAsync with the same key must never charge twice: pass the key to the gateway, or look it up yourself first when the gateway has no native idempotency. The key is opaque ASCII, at most 64 characters.
  • FindChargeAsync answers whether a key ever charged. It is the recovery path after a timeout or a crash. Found = false is trusted only when the lookup itself succeeded; if it cannot be answered, throw.
  • Saving a method. BeginSaveMethodAsync returns a SaveMethodMode; the values start at 1 and 0 is not valid, as for StoredChargeOutcome. SaveMethodContext.ReturnUrl is always an absolute address: a Redirect plugin sends the payer back to it, an EmbeddedToken plugin ignores it. With EmbeddedToken your own front end part mounts its card field with ClientToken; with Redirect the payer goes to RedirectUrl and comes back. The host calls CompleteSaveMethodAsync in both modes, and may call it more than once for a session, so it must be idempotent per SessionId: every call answers the same method and never stores it twice. An abandoned or expired session answers Saved = false and does not throw. Resolve the result from the SessionId alone, the host passes nothing else. The consent wording and the tick box stay in the host.
  • ActionRequired. Set ActionUrl. After the payer authenticates, the host resolves the final outcome with FindChargeAsync and the same idempotency key, so report the settled outcome there. While the charge still waits for the payer, FindChargeAsync returns ActionRequired with the ActionUrl, so the host can offer it again.
  • The instruction. StoredChargeInstruction.AmountMinor is positive, and the host checks AcceptsCurrency before it calls ChargeAsync.
  • A SavedMethod that is not a card leaves Brand and Last4 null, and a method that does not expire reports ExpiryMonth and ExpiryYear as 0. Since 3.11.0 SavedMethod.Kind says what the method is (SavedMethodKind.Card, BankAccount, Mandate or Wallet; Card when a plugin sets nothing, which is what every earlier plugin means), and SavedMethod.HasExpiry is true only when both the month and the year are set. A host built on an earlier version ignores Kind and shows every method as a card.
  • The host stores no methods: it lists them live through ListMethodsAsync and keeps only its consent link to a MethodRef.

Tax plugins

A tax plugin implements ITaxPlugin and tells the host what tax is due on the lines of an invoice, so the rate comes from a tax service instead of a number typed by hand. Its manifest type is Tax; a plugin of another type that also offers tax implements the same interface and lists tax (PluginCapabilities.Tax) in capabilities. The plugin keeps its credentials and settings itself, like a payment plugin.

CalculateTaxAsync takes a TaxCalculationRequest and answers a TaxCalculationResult. The request holds the currency, whether the line amounts already include tax, the seller and the buyer (TaxParty: a TaxAddress, whether it is a business, the tax number) and the lines (TaxLine: an id, the line total with discounts already taken off, the quantity, the product's tax category and whether it is a digital service). The result has one of three outcomes (TaxOutcome):

Outcome Meaning Carries
Calculated every line was calculated one TaxLineResult per requested line (LineId, Rate as a percentage, Amount, Jurisdiction) and Total, their sum
Refused the service declined, for example for an address it does not cover a TaxRefusalReason
Unavailable the service could not be reached or is rate limited nothing; the host tries again later
  • No guessed rate, no zero tax by accident. A line the service cannot rate makes the whole calculation Refused. A failed or unreachable service is Unavailable, never a calculation of zero tax. A rate of 0 is a real answer for an exempt or reverse charged supply and comes with an amount of 0.
  • Amounts follow the rate. The amount is the line total times the rate when prices exclude tax, and the part of the line total that is tax at that rate when they include it, rounded the way the service rounds. Rates are between 0 and 100, amounts are never negative, and every jurisdiction names an ISO 3166-1 alpha-2 country.
  • Outcomes, not exceptions. A refusal and an unavailable service are answers, and the plugin does not throw for them; when nothing can be said, answer Unavailable. A request keeps within TaxLimits (at most 500 lines, line ids and tax numbers up to 64 characters, address fields up to 128, a three letter upper case currency and a two letter upper case country).
  • No personal data in a result. Tax numbers and address details print as *** on the request; do not undo that in your own logs, and never put the service's own text, an address or a tax number in a result.

In the plugin's own tests, run the TaxContract checks against a stub of your service: AssertCalculationIsWellFormedAsync, AssertCalculationIsRepeatableAsync, AssertUncalculableRequestIsRefusedAsync, AssertUnreachableServiceIsUnavailableAsync and AssertHidesSecrets. Each throws PluginContractViolationException naming the promise that was broken. The amount check allows a tolerance for the service's rounding, one hundredth by default; pass the smallest unit of the currency for one with another number of decimals.

Manifest

plugin.json sits beside the plugin assembly and declares id, name, version, author, description, type, category, entryPoint (the full type name the host creates) and sdkVersion, plus optional fields (the settings an administrator fills in), color, showInIntegrations, integrationsCategory and capabilities (the optional capabilities the plugin implements: storedCredentials for a payment plugin; provisioningPanel, provisioningPanelLogin, provisioningPanelPackages, provisioningPanelAccount, virtualServer, virtualServerList, virtualServerSnapshots, virtualServerBackups, virtualServerFirewall and virtualServerConsole for a provisioning plugin; registrarOperations, registrarEmailForwarding, registrarDnsManagement, registrarWhois, registrarChildNameservers, registrarDnssec, registrarRestore, registrarDomainList, registrarSuggestions and registrarBalance for a registrar plugin; endpoints and tax for any type), minHostVersion and maxHostVersion (the range of host versions the plugin runs on, each a semantic version such as 2.1.0; a missing bound means no limit, and the lower may not be above the upper) and changelog (notes for this version, at most 4000 characters). The id is lower-case letters and digits, words joined by single hyphens.

Manifest version 2

manifestVersion names the format of the manifest. It is 1 when absent, and a version 1 manifest reads exactly as before. Version 2 declares everything a plugin offers up front, so the host can check it before any plugin code runs. Every block is optional and an absent or null block reads as empty.

Member What it declares
settings Typed settings an administrator fills in; supersedes fields. Each has key, label, type (text, url, select, secret, number, boolean, textarea) and optional required, description, default (always text, for example "30" or "true"), placeholder, min and max (for number) and options (value and label, for select).
locales Texts per locale code: { "en": { "menu.reports": "Reports" } }. A label or title may be a key of it.
api.client, api.admin The routes the plugin answers, one list per panel. Each has method (get, post, put, patch, delete), path, an optional rateLimit (default, strict, heavy; absent means default) and streaming (true for a route that replies with a stream of events). A client route may have a permission; an admin route never has one, so its Permission reads as null.
ui.client, ui.admin What the plugin adds to each panel: menus (id, label, page, optional icon and order) and pages (id, path, title, view, optional permission on the client panel).
ui.slots Content for the slots the host offers: id (the widget id, unique within the plugin), slot, view and optional title, order (lowest first), permission (client slots only), productIds (show only for services of these products; empty means every product) and contextKeys (the slot context the widget needs, for example serviceId).
domainFields Registrar plugins only: the extra registrant fields a zone needs, per set of zones, holder, operations and fields (see "Registrar plugins").
externalOrigins The web origins the plugin's pages may load content from or link to.

A version 2 manifest declares "sdkVersion": "1.0". The host accepts exactly that value today and skips or refuses a plugin that declares another, whatever package version it was built with; the value moves only when the host starts to support a new contract level.

fields stays readable. PluginManifest.GetSettings() answers one list whichever format a manifest uses: the settings when there are any, otherwise each field converted to a setting (secret and password become secret, an unknown type becomes text).

{
  "manifestVersion": 2,
  "sdkVersion": "1.0",
  "settings": [
    { "key": "baseUrl", "label": "setting.baseUrl", "type": "url", "required": true },
    { "key": "mode", "label": "setting.mode", "type": "select",
      "options": [ { "value": "live", "label": "Live" }, { "value": "test", "label": "Test" } ] }
  ],
  "api": {
    "client": [ { "method": "get", "path": "/invoices/{id}", "permission": "Any" },
                { "method": "post", "path": "/chat", "rateLimit": "strict", "streaming": true } ],
    "admin": [ { "method": "get", "path": "/status" } ]
  },
  "ui": {
    "client": {
      "menus": [ { "id": "reports", "label": "menu.reports", "page": "reports" } ],
      "pages": [ { "id": "reports", "path": "/reports", "title": "menu.reports", "view": "views/reports.json" } ]
    },
    "slots": [ { "id": "summary", "slot": "client.dashboard.cards", "view": "views/card.json", "order": 10 } ]
  },
  "externalOrigins": [ "https://example.com" ]
}

The package only reads and carries the declared surface; checking it and acting on it is the host's job.

View documents

The view member of a page or slot names a JSON file of the package. The document is declarative: it describes what a page shows and the plugin routes it calls, and the panel renders it. The shape is described by PluginViews.

{
  "schema": 1,
  "blocks": [
    { "kind": "header", "title": "pages.site",
      "actions": [ { "kind": "action", "label": "actions.publish", "confirm": "actions.publishConfirm",
                     "route": { "method": "post", "path": "/services/{serviceId}/site/publish" } } ] },
    { "kind": "table", "source": { "route": { "method": "get", "path": "/services/{serviceId}/site" } },
      "columns": [ { "label": "columns.name" } ] }
  ]
}
  • Document. An object with schema (PluginViews.SchemaVersion, today 1) and blocks, an array of blocks.

  • Block. Any object in the document that has a kind member: the top-level blocks, the blocks of a tab, the actions of a header. kind is one of PluginViews.BlockKinds (header, text, stat, table, form, action, link, badge, empty, alert, tabs, chat, progress, split, preview). Every other member is the block's own data.

  • Labels. A string under a member of PluginViews.LabelProperties (title, label, confirm, placeholder, text), at any depth, is a label: a key of the manifest locales or plain text, like a menu label. The host replaces it with its text in the caller's language, English when that language lacks the key, before the document reaches a panel, so a panel never sees a key.

  • Route references. An object under a member of PluginViews.RouteProperties (route, send, history), at any depth, names one route of the plugin as a PluginViewRoute: { "method": "post", "path": "/services/{serviceId}/site/publish" }. Routes have no ids, so a view names a route by method and the path template exactly as api declares it. The area is the one of the page or slot that shows the view (a client page uses api.client, an admin page api.admin, a slot the area of the slot). Each {parameter} is filled from the page path parameter or the slot context key of the same name.

  • Open an address. An action that has a route can carry "openUrlFrom": "url" (since 3.10.0, PluginViews.OpenUrlFromProperty): the name of a field of the route's JSON reply that holds an absolute URL, which the host opens in a new tab. The value is a simple field name, 1 to 64 letters, digits or underscores (PluginViews.IsOpenUrlFieldName), never a dotted path. It is refused on an action with no route and on one that also has navigate. The host decides which addresses it opens.

The host checks every view document when it loads a plugin and when one is installed, before any plugin code runs: the file exists (PLUGIN_VIEW_MISSING), is a JSON object (PLUGIN_VIEW_INVALID), has a supported schema (PLUGIN_VIEW_SCHEMA_UNSUPPORTED), uses only known block kinds (PLUGIN_VIEW_BLOCK_KIND_UNKNOWN), every label that looks like a key exists in the en locale (PLUGIN_LABEL_KEY_MISSING) and every route reference names a route declared in the area (PLUGIN_VIEW_ROUTE_UNDECLARED). A plugin that fails one is refused.

How the host builds a plugin

The host creates the entryPoint type once the plugin is enabled in the admin panel and every required field has a value. The constructor receives an IConfiguration holding only this plugin's settings, under integration:{id}:{key}, and may also ask for host services such as ILogger<T>.

A minimal plugin

A hosted plugin that logs a heartbeat. The project:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Hostpanel.Sdk" Version="3.9.0" ExcludeAssets="runtime" />
    <None Include="plugin.json" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>
</Project>

The plugin:

using Hostpanel.Sdk.Plugins.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Example.Heartbeat;

/// <summary>Logs a heartbeat at the interval the administrator set.</summary>
public sealed class HeartbeatPlugin : IHostedPlugin, IDisposable
{
    /// <summary>The seconds between two heartbeats.</summary>
    private readonly TimeSpan _interval;

    /// <summary>Where the heartbeat is written.</summary>
    private readonly ILogger<HeartbeatPlugin> _logger;

    /// <summary>Stops the loop when the host stops the plugin.</summary>
    private readonly CancellationTokenSource _stopping = new();

    /// <summary>The running loop, awaited on stop.</summary>
    private Task _loop = Task.CompletedTask;

    /// <summary>Builds the plugin from its own settings.</summary>
    /// <param name="configuration">This plugin's settings only.</param>
    /// <param name="logger">The host's logger.</param>
    public HeartbeatPlugin(IConfiguration configuration, ILogger<HeartbeatPlugin> logger)
    {
        var seconds = int.TryParse(configuration["integration:heartbeat:interval_seconds"], out var value) ? value : 60;
        _interval = TimeSpan.FromSeconds(Math.Max(seconds, 1));
        _logger = logger;
    }

    /// <inheritdoc />
    public Task StartAsync(CancellationToken ct)
    {
        _loop = RunAsync(_stopping.Token);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public async Task StopAsync(CancellationToken ct)
    {
        await _stopping.CancelAsync();
        await _loop.WaitAsync(ct);
    }

    /// <inheritdoc />
    public void Dispose()
    {
        _stopping.Dispose();
    }

    /// <summary>Writes a heartbeat every interval until stopped.</summary>
    /// <param name="ct">Cancelled when the plugin is stopped.</param>
    /// <returns>A task that completes when the loop ends.</returns>
    private async Task RunAsync(CancellationToken ct)
    {
        using var timer = new PeriodicTimer(_interval);
        try
        {
            while (await timer.WaitForNextTickAsync(ct))
            {
                _logger.LogInformation("Heartbeat");
            }
        }
        catch (OperationCanceledException)
        {
            // Stopping is the normal way out of the loop.
        }
    }
}

The manifest, plugin.json:

{
  "id": "heartbeat",
  "name": "Heartbeat",
  "version": "1.0.0",
  "author": "You",
  "description": "Logs a heartbeat.",
  "type": "Hosted",
  "category": "Utilities",
  "entryPoint": "Example.Heartbeat.HeartbeatPlugin",
  "sdkVersion": "1.0",
  "fields": [
    { "key": "interval_seconds", "label": "Seconds between heartbeats", "type": "text", "required": false }
  ]
}

Shipping

Zip the plugin's own assembly, its own dependencies and plugin.json with the manifest at the root of the archive, and upload it in the admin panel under Plugins, or place the folder in the host's plugins/<id>/ folder. Never ship Hostpanel.Sdk.dll or a host assembly inside the plugin: the host refuses such an archive, and a second copy of the SDK on disk would make every cast fail.

The SDK version in the manifest

Building a plugin writes the version of the referenced Hostpanel.Sdk package into plugin.json as sdkPackageVersion (for example "sdkPackageVersion": "3.13.0"): the package ships build/Hostpanel.Sdk.targets, which NuGet imports into the plugin's project, and the build sets the member in the project's plugin.json, so there is nothing to keep in step by hand. Commit the changed file. Set the MSBuild property HostpanelStampSdkPackageVersion to false to switch it off. It is not sdkVersion, which names the manifest contract and stays 1.0.

The build changes only the top level sdkPackageVersion member of plugin.json: the byte order mark, the line endings and the layout stay as they were, and a file that is not a JSON object fails the build. In a project with several TargetFrameworks only the build of the first framework writes the file. A project that resolves more than one Hostpanel.Sdk reference fails the build, because the version to write would be ambiguous. The value is only the major, minor and patch numbers, so a prerelease suffix is ignored, and the member name must be written as plain sdkPackageVersion, without escapes, for the build to recognise it.

PluginManifestChecker.Validate fails with PluginManifestRule.MinHostVersionBelowSdk when minHostVersion is missing or lower than the first host release that ships an SDK at least that new (PluginSdkHostReleases), or when no host release ships an SDK that new yet, and with SdkPackageVersionInvalid when the value is not a version. A manifest without the member is not checked.

Checking and signing a package

The checks a host runs on an uploaded package (the plugin.sig signature, plugin id and version rules, reserved assembly names, archive guards, icon safety and the structural manifest rules) are published as a second package, Hostpanel.Sdk.Packaging (MIT, net9.0, same version as this package), so you can run the same code in your release pipeline before you publish: PluginSigner.Sign(packageDirectory, keyId, privateKey) writes the signature, and PluginManifestChecker, PluginIconChecker, PluginAgentPackageChecker and PluginAssemblyNames answer the same questions the host will. See Hostpanel.Sdk.Packaging/README.md.

Versioning

The package follows semantic versioning: a patch release fixes, a minor release adds members, a major release removes or renames them. A version is published by raising <Version> in Directory.Build.props (one version for Hostpanel.Sdk and Hostpanel.Sdk.Packaging): the publish workflow pushes a version the feed does not have yet and skips one it already has, so a change that keeps the version publishes nothing. Each release is listed in CHANGELOG.md.

Contributing

Issues and pull requests are welcome in innovayse/hostpanel-sdk; see CONTRIBUTING.md there. A change the host has to support as well (a new contract, a new manifest field, a new plugin type) also needs a pull request in innovayse/hostpanel, which includes this repository as a git submodule at backend/src/Hostpanel.Sdk and moves it to the new commit.

Questions and chat: Discord. To list a finished plugin for operators, see Publishing a plugin and the plugin marketplace.

About

Plugin SDK for Hostpanel: contracts for payment, provisioning, registrar, fulfilment, identity and hosted plugins. MIT licensed.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages