Plugin Development Guide
A plugin adds a feature to Blazor Blueprint without editing the host: its own pages, navigation, settings, data, background sweeps, SignalR hubs and REST endpoints, discovered at startup and installed per organisation. This page is the contract every plugin is written against.
The repository ships one plugin, the ExamplePlugin in Plugins/ExamplePlugin/: a reference implementation that uses most extension points once, minimally. Treat it as the ground truth for anything below; its CLAUDE.md explains each choice.
Removing the example plugin. Delete its line from Plugins/Plugins.props, delete Plugins/ExamplePlugin/, remove its two projects from the solution, and update the relational migrations, which include its tables (scripts/check-migration-drift.sh fails until you do):
- Before your first deployment, run
scripts/regen-migrations.sh --i-have-never-deployedand commit the regeneratedMigrations/folders. - After it, never regenerate — databases that applied the old
InitialCreatewould fail to migrate. Add a named migration (Relational Migrations) for both providers and both contexts, and delete itsDropTablecalls (scripts/check-additive-migrations.shrefuses drops, since old instances may still run during a rolling deploy). The tables, or the MongoDBplugin_exampleplugin_*collections, stay unused until you drop them by hand.
Plugins are fully-trusted, in-process code
A plugin runs in the host process with unrestricted DI access: no sandbox, no signing, no capability enforcement. It can read every tenant’s data and the platform secrets. Per-plugin load contexts isolate private dependencies, not execution, and the manifest’s Capabilities are a declaration for review, not a boundary.
That suits an operator-curated deployment, where you choose the DLLs and read their source. It is not safe for a marketplace or customer-uploaded plugins, which would need process or container isolation. The layers under Installing and enabling control availability, not security.
Quick start
1. Create the project
A plugin is a Razor Class Library. In this repository plugins live at Plugins/{Name}/{AssemblyName}/, the same shape as the run-time drop-in folder:
# From the repository rootmkdir -p Plugins/MyPlugin && cd Plugins/MyPlugindotnet new razorclasslib -n Acme.MyPlugincd ../..dotnet sln add Plugins/MyPlugin/Acme.MyPlugin/Acme.MyPlugin.csprojName the assembly what you like; the attribute in the next step is what makes it a plugin.
2. Set up the .csproj
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup>
<!-- Declares this assembly a plugin. The id prefixes its tables and collections. --> <ItemGroup> <AssemblyAttribute Include="BlazorBlueprint.Domain.Attributes.PluginAssemblyAttribute"> <_Parameter1>myplugin</_Parameter1> </AssemblyAttribute> </ItemGroup>
<!-- The plugin's own default configuration (see "Configuration"). --> <ItemGroup> <Content Update="myplugin.plugin.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup>
<ItemGroup> <FrameworkReference Include="Microsoft.AspNetCore.App" /> </ItemGroup>
<!-- Host assemblies: compile against them, never ship them. --> <ItemGroup> <ProjectReference Include="..\..\..\Core\BlazorBlueprint.Application\BlazorBlueprint.Application.csproj" ExcludeAssets="runtime" PrivateAssets="all" /> <ProjectReference Include="..\..\..\Core\BlazorBlueprint.Domain\BlazorBlueprint.Domain.csproj" ExcludeAssets="runtime" PrivateAssets="all" /> <!-- Only if your pages use the shared UI components, or you map a hub / implement IWebPluginConfigurator --> <ProjectReference Include="..\..\..\Web\BlazorBlueprint.Web.Shared\BlazorBlueprint.Web.Shared.csproj" ExcludeAssets="runtime" PrivateAssets="all" /> <!-- Only if your plugin serves REST controllers --> <ProjectReference Include="..\..\..\Services\BlazorBlueprint.Api.Shared\BlazorBlueprint.Api.Shared.csproj" ExcludeAssets="runtime" PrivateAssets="all" /> </ItemGroup>
</Project>dotnet add reference writes neither attribute on the host references, and both matter: ExcludeAssets="runtime" keeps host assemblies out of your output (Dependency versions), and PrivateAssets="all" out of your NuGet dependencies. The example plugin’s .csproj shows the finished shape.
Inside this repository a plugin inherits Directory.Build.props (warnings are errors) and Directory.Packages.props (central versions — a <PackageReference> takes no Version; add it there).
3. Write the plugin class
using BlazorBlueprint.Application.Interfaces;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;
namespace Acme.MyPlugin;
public sealed class MyPluginEntry : IPlugin{ public const string PluginId = "Acme.Plugins.MyPlugin"; // slug = "myplugin"
public PluginManifest Manifest { get; } = new() { Id = PluginId, Name = "My Plugin", Version = "1.0.0", Description = "What it does, in one line.", Author = "Acme", Icon = "PuzzlePiece", Capabilities = [PluginCapability.TenantData], SubscriptionPlanFeatures = [], // sells nothing through plans; see "Plan features" };
public Task RegisterServicesAsync(IServiceCollection services, IConfiguration configuration) { services.AddScoped<IMyService, MyService>(); return Task.CompletedTask; }}The class is MyPluginEntry, not MyPlugin: a class named like the last segment of its namespace is shadowed by it everywhere else.
That is a complete plugin, which can be enabled per organisation at Admin → Apps. It gets a launcher tile and sidebar group once it has a page: add one with @page "/plugin/myplugin" (the dashboard address the tile opens). A plugin with no pages — a webhook handler, a sweep, an API — stays out of both, which is correct.
4. Add it to the plugin list
One line in Plugins/Plugins.props — not in any host’s .csproj:
<ItemGroup> <ProjectReference Include="$(MSBuildThisFileDirectory)MyPlugin\Acme.MyPlugin\Acme.MyPlugin.csproj" /></ItemGroup>Plugins.props is imported by all four hosts that need the plugin — Web, InternalApi, BackgroundWorker and DbMigrator. Missing any one fails silently: controllers 404 under Full, sweeps never run, or tables reach no migration.
If the plugin has entities and you deploy PostgreSQL or SQL Server in migrations mode, generate a migration once it is referenced — see Relational migrations. MongoDB needs nothing.
Two build “successes” that render raw HTML
Shared Razor components live in BlazorBlueprint.Web.Shared (a plugin cannot reference the host Web project), and every component namespace your pages use must be in the plugin’s own _Imports.razor. Miss either and the build succeeds with warning RZ10012, rendering the component as inert markup. If a plugin page looks like raw HTML, grep the build output for RZ10012.
The plugin contract
IPlugin and the opt-in interfaces
IPlugin (Core/BlazorBlueprint.Application/Interfaces/IPlugin.cs) asks for a manifest and a service registration method:
public interface IPlugin{ PluginManifest Manifest { get; } string Id => Manifest.Id; // shortcut string Slug => Manifest.Slug; // shortcut: last dot-segment of Id, lower-cased
// Runs in every plugin-aware host: Web, InternalApi and BackgroundWorker. Task RegisterServicesAsync(IServiceCollection services, IConfiguration configuration);}Everything else is an opt-in interface the host probes for (is IPluginXxx), so the class declaration is the plugin’s table of contents. There is no base class. The example plugin implements all of them (ExamplePluginEntry : IPlugin, IPluginUiContributor, IPluginProvisioner, IPluginBackgroundServices, IPluginStartup, IWebPluginConfigurator); a real plugin implements only what it does.
| Interface | Members | Implement it when |
|---|---|---|
IPluginUiContributor |
GetAdminPages, GetPlatformPages, GetLayoutComponents, GetRoutes (all defaulted) |
the plugin has pages (and their sidebar rows) or layout widgets |
IPluginProvisioner |
SeedPlatformDefaultsAsync, SetupForOrganisationAsync, TeardownForOrganisationAsync (all defaulted) |
it seeds data, or owns something outside its tenant rows that must stop when it is removed |
IPluginBackgroundServices |
RegisterBackgroundServicesAsync |
it ships a recurring sweep |
IPluginStartup |
OnStartupAsync |
it has once-per-process startup work — rare, and it must be cheap. Runs in the Web host, InternalApi and BackgroundWorker, with no tenant set; a throw is logged and skipped |
IWebPluginConfigurator |
ConfigureWebAppAsync(WebApplication) |
it maps minimal endpoints or middleware (Web host only; in BlazorBlueprint.Web.Shared/Plugins/). If it throws, the plugin is disabled but what it already mapped stays mapped — validate first, register last |
The first four live in BlazorBlueprint.Application.Interfaces.
The manifest
PluginManifest (Core/BlazorBlueprint.Application/Interfaces/PluginManifest.cs) has six required fields; the compiler refuses a manifest without them. Capabilities and SubscriptionPlanFeatures may be [] but must be stated, because operators review the first and build plans from the second.
| Property | Default | Notes |
|---|---|---|
Id |
required | Stable unique id, e.g. Acme.Plugins.Billing. Its last dot-segment, lower-cased, is the slug (billing) that keys /plugin/{slug} URLs, the launcher, nav and gating. Two plugins whose ids share a last segment collide. |
Name |
required | Display name on tiles, nav and the Apps pages. |
Version |
required | This build’s version, e.g. "1.0.0". |
Description |
required | One line, on the launcher tile and management card. |
Capabilities |
required, [] allowed |
What the plugin touches, for operator review: TenantData, PlatformData, BackgroundJobs, Payments, Sms, InboundEmail, OutboundWebhooks, Ai, FileStorage, PublicRoutes, ChromeSuppression. Not enforced. |
SubscriptionPlanFeatures |
required, [] allowed |
Features sold through plans; each SubscriptionPlanFeature(Key, Name, Description) is a checkbox in the plan editor. Keys must start with {slug}., be unique ignoring case, and have a name, or the plugin is disabled at boot. See Plan features. |
Author |
"" |
|
Category |
"General" |
Grouping label. |
Icon |
"PuzzlePiece" |
A FluentUI icon name; unknown or blank falls back to the puzzle piece. |
IsPremium |
false |
Gate the WHOLE plugin behind a subscription plan when billing is on. Overridable by config. |
Scope |
PluginScope.Tenant |
PlatformOnly limits the plugin to the platform organisation. Overridable by config. |
Dependencies |
[] |
Ids of plugins this one needs. If one is missing or disabled, this plugin is disabled with a warning. |
MinHostVersion |
null |
Oldest host version this plugin works on. See Dependency versions. |
NavigationMode |
Inline |
Inline puts the app’s rows in the main sidebar; Focused replaces the sidebar with the app’s own on its pages. Plugins:{id}:NavigationMode overrides it. |
Plan features
A plan feature is part of your plugin that an organisation gets only when its subscription plan grants it — an export, an AI action, publishing to the web. Declare each in the manifest:
SubscriptionPlanFeatures =[ new SubscriptionPlanFeature("billing.invoices", "Invoicing", "Create and send invoices."),],The operator grants Invoicing with a checkbox at Platform → Plans. Pick the key once: renaming it ungrants it on every plan. Gate on it with one helper, used by every check:
// Allowed when billing is not live (no plan applies), or for the platform organisation;// otherwise the organisation's plan decides.public async Task<bool> IsAllowedAsync(string organisationId, CancellationToken ct = default){ if (!await billingGate.IsLiveAsync(ct)) return true; // ISubscriptionBillingGate if (organisationId == await platformOrganisation.GetIdAsync(ct)) return true; // IPlatformOrganisationAccessor return await entitlements.HasFeatureAsync(organisationId, "billing.invoices", ct); // IEntitlementService}- Ask
ISubscriptionBillingGatewhether billing is live; never read the billing switches yourself, or you will disagree with the host when an operator pauses billing. - Enforce in the service, not only the page, so a direct call or stale tab cannot get round it.
- Anything served publicly needs ONE choke point that every public surface (page, feed, sitemap) calls.
- Fail closed if the entitlement read throws.
The example plugin gates a panel on its Access page with exampleplugin.advanced.
Plan feature or premium? A premium plugin (IsPremium, or Plugins:{id}:RequiresSubscription) is all-or-nothing, hidden and blocked by the host for organisations whose plan lacks it. Use plan features when part of the plugin must stay reachable regardless of plan — data the organisation must keep control of when its plan lapses, or a free tier with paid extras.
When billing goes live, features no plan grants are lost at once, and the seeded example plans grant nothing — grant them in a plan first.
Assembly identity
The PluginAssembly attribute (Core/BlazorBlueprint.Domain/Attributes/PluginAssemblyAttribute.cs) is the only thing that makes an assembly a plugin.
- The id must equal the manifest’s slug (
Acme.Plugins.Billing→billing). The host refuses to boot on a mismatch: the id prefixes tables, the slug routes and gates, and the schema gate matches one against the other. - Pick it once. It prefixes every table and collection (
plugin_{id}_{Entity}); changing it later renames nothing, so the plugin reads empty tables.
If the assembly holding the IPlugin class lacks the attribute, the host logs an error and disables that plugin. The rest of the site runs. An entity in a second assembly without it fails at first use instead, so a multi-project plugin should declare the same id once in a Directory.Build.props covering all its projects.
Which process runs what
The same plugin assembly is loaded by several hosts, in two deployment shapes — Full (Web + InternalApi + BackgroundWorker + Redis) and Lite (Web only, no Redis); see Deployment. Getting this wrong fails no build; it produces work that runs twice, or an endpoint that exists on one shape only.
- Services run everywhere.
RegisterServicesAsyncis called by the Web host, the InternalApi and the BackgroundWorker. - Sweeps run in exactly one process: the BackgroundWorker under Full, the Web host under Lite (
BackgroundServices:RunInProcess). Register hosted services only inRegisterBackgroundServicesAsync, or a sweep fires twice. [EndpointAudience]decides which process serves a controller or hub, and each runs in exactly one.External(browsers, webhooks, anything outside) is always the Web host.Server(only your own server calls it) is the InternalApi under Full and the Web host under Lite (Services:InternalApi:Enabled). An endpoint declaring nothing isServer. Under Lite aServerendpoint is on the public port and is protected only by its authentication, so don’t read it as unreachable.[EndpointScope]says which tenant it acts for and demands a token issued by your server, on any audience. A wrong attribute breaks that endpoint and never the site: nothing refuses a boot or disables a plugin over one. AServercontroller with no[EndpointScope]is refused at request time, as a hub with none is, and both are logged at startup.- Never branch on the shape yourself. No
if (lite), noIConnectionMultiplexer(Lite has no Redis), no assuming the InternalApi is reachable. For a typed client’s base address, askEndpointHosting(BlazorBlueprint.Api.Shared). - Register a typed client for your service API only where a service token can be minted —
services.Any(d => d.ServiceType == typeof(IJwtTokenApiClient)). Only the Web host registers it; elsewhere the client resolves to a handler nothing supplies and throws on first use.
ExamplePluginEntry.RegisterServicesAsync shows a typed API client registered for both shapes. ConfigureWebAppAsync runs only in the Web host; SeedPlatformDefaultsAsync at boot in the Web host and BackgroundWorker once initial setup has run; SetupForOrganisationAsync wherever an organisation is created or the plugin enabled.
Pages, routes and navigation
Route conventions
| Path | For | Layout |
|---|---|---|
/plugin/{slug} |
The dashboard — what the launcher tile and your sidebar’s Overview row link to | MainLayout, with your app’s group open in the sidebar |
/plugin/{slug}/{page} |
Everyday member-facing pages, including any anonymous ones | MainLayout, with your app’s group open in the sidebar |
/admin/plugin/{slug}/{page} |
Settings and configuration for one organisation | AdminLayout |
/admin/plugin/{slug} |
Host-generated settings hub — a card grid built from GetAdminPages(). Don’t declare a page here |
AdminLayout |
/platform/plugin/{slug}/{page} |
Deployment-wide settings, platform admins only | Platform layout |
Write paths literally, in kebab-case. Pages under /plugin/{slug}/* must not link to /admin/plugin/{slug}/* — name admin pages in copy instead. The host adds the one sanctioned link, a role-gated “Settings” row in your sidebar group.
Declaring pages: IPluginUiContributor
Routing comes from each component’s @page. IPluginUiContributor returns metadata: which admin and platform pages to list, which roles each route is for, and which pages appear in the sidebar (PluginRoute.Nav).
using BlazorBlueprint.Application.Interfaces;using BlazorBlueprint.Domain.Constants;
public sealed class MyPluginEntry : IPlugin, IPluginUiContributor{ // ... Manifest, RegisterServicesAsync ...
// Admin nav "App settings" group, and the cards in the /admin/plugin/myplugin hub. // GetPlatformPages() has the same shape, with RequiredRole = ApplicationRoleConstants.PLATFORMADMIN. public IEnumerable<PluginAdminPage> GetAdminPages() => [ new() { Title = "My Plugin settings", Route = "/admin/plugin/myplugin/settings", Icon = "Settings", RequiredRole = PluginRoles.AdminRolesFor(MyPluginRoles.Admin), Order = 10, }, ];
// Member-facing routes, who should SEE them, and their sidebar rows. public IEnumerable<PluginRoute> GetRoutes() => [ new() { Route = "/plugin/myplugin/reports", ComponentType = typeof(Web.Pages.Reports), RequiredRole = PluginRoles.UserRolesFor(MyPluginRoles.Admin, ApplicationRoleConstants.MEMBER), // PluginNavLink(Title, Icon = null, Section = null, Order = 0) Nav = new("Reports", "DocumentText", Section: "Insights", Order: 10), }, ];}A RequiredRole here filters what is shown — nav row, hub card, tile. Access control is the @attribute on the page (see Authorization); build both from the same role constant. Null means different things: on a PluginAdminPage it is administrators only; on a PluginRoute it is any signed-in user.
Declare member roles on your routes, or members can’t see the tile
The launcher tile is gated by the union of every non-null RequiredRole across your admin pages and routes. With role-less member routes and one admin page, only administrators see the tile. Declare PluginRoles.UserRolesFor(...) on the routes members should find.
GetLayoutComponents returns LayoutComponentRegistration(Type ComponentType, LayoutComponentSlot Slot) records, rendered by MainLayout:
HeaderandFooterrender only on paths your ownIPluginChromeProviderclaims (see Taking over the page chrome).Floatingcomponents (position: fixedoverlays such as a chat widget) render on everyMainLayoutpage except/admin,/platform,/org,/account/manageand error or status pages. Every enabled plugin’s render together, so render nothing on paths you do not own.
Settings pages need @rendermode InteractiveServer. Without one the page is static SSR: @bind-Value never posts back and @onclick is never wired, so Save silently does nothing.
Navigation
There is one sidebar: the organisation’s own links, then an Apps section with a group per app the viewer can open, in launcher order. Being installed, with a page at or beneath /plugin/{slug}, puts your plugin there. Its rows:
- An Overview row for
/plugin/{slug}, gated like your tile (or by your ownGetRoutes()entry for that address). - A row per route with a
Nav, grouped bySection(in order of first appearance) and sorted byOrder. Parameterised routes cannot carry one; duplicate addresses make one row. - A row shows to holders of its
RequiredRole(plus both administrator tiers), and to everyone when yourIPublicRouteAllowListmakes its path public. - “Admin → Settings” when you have admin pages, and your platform pages in the platform organisation.
Dynamic rows that depend on data, such as recent items, come from an optional IPluginSectionNavProvider:
public sealed class MyPluginSectionNavProvider : IPluginSectionNavProvider{ public string PluginSlug => "myplugin"; public bool IsDynamic => true; // re-queried on navigation rather than cached for the circuit
public async Task<IReadOnlyList<PluginSectionNavItem>> GetItemsAsync(PluginNavContext context, CancellationToken cancellationToken = default) { // Read the viewer from the context, never IAppUserService: this runs on a circuit click, with no HttpContext. if (!PluginRoles.Admits(context.User, PluginRoles.UserRolesFor(MyPluginRoles.Admin, ApplicationRoleConstants.MEMBER))) { return []; }
// PluginSectionNavItem(Label, Href, Icon, RequiredRole = null, Section = null) return (await _reports.GetRecentAsync(3, cancellationToken)) .Select(r => new PluginSectionNavItem(r.Title, $"/plugin/myplugin/reports/{r.Id}", "Document", Section: "Insights")) .ToList(); }}
// In RegisterServicesAsync:services.AddScoped<IPluginSectionNavProvider, MyPluginSectionNavProvider>();A provider row whose Href matches a route row exactly (query string included) replaces it — label and gate — so a provider can narrow a row as well as relabel it. Other rows go after the last row of their Section, or at the end. SuppressedHrefs(context) hides route rows for a viewer. A provider that throws leaves your route rows unchanged.
Navigation mode
By default (PluginNavigationMode.Inline) your pages keep the main sidebar with your group open. Set NavigationMode = PluginNavigationMode.Focused for an app that is a workspace of its own (a chat, a document tree): on /plugin/{slug}/* your rows replace the sidebar, headed by an “All apps” row (signed-in viewers only). Operators can override it with Plugins:{id}:NavigationMode (Inline or Focused).
Neither mode is a layout of your own, and you need none. A page that should look like a separate site takes over the chrome with an IPluginChromeProvider.
Public routes
The application is members-only for every organisation. Two middleware walls run before endpoint resolution — signed-out visitors go to sign-in, non-members are refused — and neither sees [AllowAnonymous]. A page on the platform host or an organisation subdomain is reachable without membership only if an IPublicRouteAllowList says so. These are per-item links a member hands out (a scan redirect, a customer portal), not websites:
public sealed class MyPluginPublicRoutes : PrefixPublicRouteAllowList // BlazorBlueprint.Application.Services.Plugins{ public MyPluginPublicRoutes() : base("/plugin/myplugin/portal/") { } // keep the trailing slash public override string PluginId => MyPluginEntry.PluginId;}
// In RegisterServicesAsync:services.AddSingleton<IPublicRouteAllowList, MyPluginPublicRoutes>();- The route is public only while your plugin is installed, available and (if premium) in the organisation’s plan; a throwing provider or failed lookup leaves it walled.
- Matching is a case-insensitive
StartsWith, hence the trailing slash ("/l"would claim/login). A prefix shorter than three characters, not starting with/, or containing{,},*,?,#or a space is silently dropped — write a path prefix, never a route template. - To make the bare dashboard public, implement
IPublicRouteAllowListdirectly, asExamplePublicRouteAllowListdoes. - Also put
[AllowAnonymous]on the pages and declarePluginCapability.PublicRoutes. OverrideDescribeRoutes()to list the routes on the organisation’s/Admin/Pagesscreen.
A route whose path carries a secret must be redacted from analytics. Query strings are always dropped from page views, but a path token would reach the analytics provider verbatim. Register an IAnalyticsRedactionProvider; braced segments are replaced by their names, and a template also matches beneath /org/{name}/:
public sealed class MyPluginRedactions : IAnalyticsRedactionProvider{ public IReadOnlyList<string> RedactedRouteTemplates => ["/plugin/myplugin/portal/{code}"];}
services.AddSingleton<IAnalyticsRedactionProvider, MyPluginRedactions>();See Privacy → Nothing non-essential loads before consent and Privacy → A members-only application.
Public pages on customer hostnames
A plugin that publishes a website on an organisation’s own domain does it through IPublicPageProvider. The organisation connects a hostname it owns (www.acme.com) to one of the plugin’s targets, and the host routes it to the plugin; see Architecture → Custom domains and sites.
public interface IPublicPageProvider{ string SourceKey { get; } // opaque, persisted on every SiteDomain — never change it string PluginId { get; } // your Manifest.Id: uninstalled, unavailable or not entitled → not served string DisplayName { get; } // what a target is, e.g. "Website" IReadOnlyList<string> SiteRoutePrefixes { get; } // extra paths served on your hostnames (/search, /category/, /feed.xml)
Task<IReadOnlyList<PublicPageTarget>> ListTargetsAsync(CancellationToken ct = default); Task<IReadOnlyList<PublicUrl>> ListPublicUrlsAsync(string targetKey, CancellationToken ct = default); Task<RenderFragment?> TryRenderAsync(string targetKey, string slug, CancellationToken ct = default); Task<SiteDocumentHead?> GetDocumentHeadAsync(string targetKey, CancellationToken ct = default);}
// In RegisterServicesAsync:services.AddScoped<IPublicPageProvider, MyPublicPageProvider>();- Targets (
PublicPageTarget(Key, Title)) — one website each, with its own slug space.ListTargetsAsyncruns in the organisation’s context and is all hostnames may point at. Code that acts on a target having disappeared should askIPublicUrlRegistry.ListTargetListingAsyncand treat targets of providers inUnavailableProviderKeysas unknown, not gone. - Pages.
ListPublicUrlsAsync(PublicUrl(Slug, Title, LastModified), empty slug for home) feeds/Admin/Pagesand the sitemap — keep it cheap, and callIPublicUrlRegistryInvalidator.Invalidate(organisationId)after publishing changes.TryRenderAsyncreturnsnullfor a404. - Member-chosen slugs must pass
IReservedPublicPaths.IsReserved(slug)(host segments and every mapped route), plus your own non-slug routes. - Every visitor is anonymous: the session cookie never reaches a customer domain, and application paths redirect to the platform. Anything not your slug or in
SiteRoutePrefixesis a404, including undeclared/api/*. A declared API (a form post, say) must sit beneath/api/plugin/{your plugin id}/, or be at least three segments deep with every endpoint under it yours; other declarations are ignored with a warning. - The document head is the site’s.
GetDocumentHeadAsyncreturns aSiteDocumentHead: name, description, favicon, social image, language, analytics id, cookie banner (SiteCookieBanner, with the site’s own policy URLs), administrator-pasted head and body code (rendered unencoded),AllowIndexingand an optionalRobotsTxt. Returnnullfor a target you would not render. - Links back into the application are absolute, built with
IOrganisationPublicUrlResolver.ResolveAsynconhttps://+IPlatformHostname.Host(never the request’s origin), asExamplePublicRoutes.AbsolutePublicPageUrlAsyncdoes; a relative/plugin/…link loses the organisation. - Internal links use
ISiteRouteContext.Current.PathBase— empty on a customer hostname,/preview/{token}in a preview link.Current(aSiteRoute) isnullon application hosts. - Your website owes its own legal pages and a “Cookie settings” control; the host’s
/legal/*is not served there.
Shared components (BlazorBlueprint.Web.Shared.Components) give your own site editor the host’s flows; render them in an interactive page that includes <ConsoleStyles />, and pass the session’s current organisation (any other OrganisationId is refused):
<DomainConnectPanel OrganisationId ProviderKey TargetKey />— add, verify, retarget, make primary and remove hostnames, showing the DNS records (ownership TXT at_bb-verify.{hostname}; take record names fromISiteDomainService.GetDnsRecordsAsyncif you write a zone yourself). Without the keys it lists every hostname of the organisation.<SitePreviewLinksPanel OrganisationId ProviderKey TargetKey />— preview links for a target with no domain yet.<DnsRecordsTable Records Caption />— records to publish, with copy buttons.<HostnameStatusChip Text Tone Title />— a hostname state badge;HostnameStatusChip.For(siteDomain)derives the host’s own states.
A members-only in-app preview can borrow the site’s document head by registering IInAppSitePreview, which calls ISiteRouteContext.Set(new SiteRoute(…, IsPreview: true, PathBase: …)) for your preview paths before <head> renders.
When you delete a target, call ISiteDomainService.RemoveForTargetAsync and ISitePreviewLinkService.RevokeForTargetAsync. Deleting the organisation releases everything.
Taking over the page chrome
Register an IPluginChromeProvider when some pages should stand alone — a public site, a portal, a one-time link. For paths where OwnsChromeAsync(requestPath) returns true, the host:
- hides its header and sidebar;
- stops emitting its page meta (description, Open Graph, canonical, JSON-LD) — emit your own through
HeadContent; - renders your plugin’s
HeaderandFooterlayout components only; - hides the platform footer only if you register a
Footercomponent.
Your Footer then owes the platform footer’s obligations on every page you own: the deployment’s legal-policy links (LegalPolicyLinks.GetAsync) and a cookie-settings control. To mirror the operator’s Platform → Footer content, read IPlatformFooterService.GetContentAsync. See Privacy.
The path has any /org/{name} prefix removed. The method runs on every render, so keep it cheap; a throw counts as false. A claim counts only while your plugin is enabled for the organisation; if two plugins claim a path, the first registered wins. The provider and layout components must carry your [PluginAssembly] id, or the chrome is hidden with nothing to replace it.
Static assets
Your JS and CSS belong in your plugin’s own wwwroot, served at /_content/{YourAssembly}/… — never the host’s.
<script type="module" src="/_content/Acme.MyPlugin/my-page.js"></script><link rel="stylesheet" href="/_content/Acme.MyPlugin/my-page.css" />Anything that stores non-essential data in the browser must gate on the consent API — see Privacy.
Authorization
A plugin declares one role name and composes nothing. The host adds the two administrator tiers — ORGANISATIONADMIN and PLATFORMADMIN — at every call site:
public static class MyPluginRoles{ public const string Admin = "MyPluginAdmin";}@attribute [AuthorizePluginAdmin(MyPluginRoles.Admin)] @* an admin page *@@attribute [AuthorizePluginUser(MyPluginRoles.Admin, ApplicationRoleConstants.MEMBER)] @* a member page *@@attribute [AuthorizePlatformAdmin] @* a /platform/plugin/* page *@@attribute [AuthorizeOrganisationMember] @* any active member of this org *@RequiredRole = PluginRoles.AdminRolesFor(MyPluginRoles.Admin) // admin page / route metadataRequiredRole = PluginRoles.UserRolesFor(MyPluginRoles.Admin, ApplicationRoleConstants.MEMBER)PluginRoles.IsModerator(user, MyPluginRoles.Admin) // a check in codeThe attributes are in BlazorBlueprint.Application.Authorization; PluginRoles and ApplicationRoleConstants in BlazorBlueprint.Domain.Constants.
- Never write
[Authorize(Roles = MyPluginRoles.Admin)]orIsInRole(admin) || IsInRole(ORGANISATIONADMIN): your admin role is granted only to whoever enabled the plugin, so a bare check refuses later admins. - Bare
[Authorize]admits any signed-in user, including other organisations’ members;[AuthorizeOrganisationMember]admits active members andPLATFORMADMIN. - A
/platform/plugin/*page must carry[AuthorizePlatformAdmin]. - A minimal endpoint you map in
ConfigureWebAppAsyncis anonymous unless you chain.RequireAuthorization(...)— the Web host has no fallback policy. Pass the attribute your pages use:.RequireAuthorization(new AuthorizePluginUserAttribute(MyPluginRoles.Admin, ApplicationRoleConstants.MEMBER)), asExampleItemPdfEndpointdoes. - For role tiers (admin, sales, field-work), build named constants on
PluginRoles.AdministratorTiers.
A Member file is readable by every member who has its id (FileVisibility.Member is the upload default; /api/files/{id} checks only membership). To restrict files, register an IStoredFileReadAuthorizer (BlazorBlueprint.Application.Interfaces.Storage):
public sealed class MyFileReadAuthorizer : IStoredFileReadAuthorizer{ public string OwnerTypePrefix => "myplugin"; // "myplugin" and every "myplugin.*" owner type
public Task<bool> CanReadAsync(StoredFile file, ClaimsPrincipal user, CancellationToken ct = default) => Task.FromResult(file.OwnerType != "myplugin.export" || PluginRoles.IsModerator(user, MyPluginRoles.Admin));}
services.AddScoped<IStoredFileReadAuthorizer, MyFileReadAuthorizer>();Every matching authorizer must allow (matching ignores case); a refusal or exception answers 404. Public files are never asked.
Data
Entities and repositories
Plugin entities derive from BaseEntity (BlazorBlueprint.Domain.Entities.Common) and are discovered from your declared assembly — no DbContext, mapping, migration or registration of your own.
- Tenant data:
IRepository<T>reads and writes the current organisation’s database. It needs a tenant context — present on requests, and set for you byForEachOrganisationAsync, job handlers and the hub filter. - Platform data: an
IPlatformScopedEntitylives in the platform database, viaIPlatformRepository<T>. If its rows carry anOrganisationId, register anIOrganisationCascadeContributorto delete, retain or anonymise them when that organisation is deleted.
IRepository<T> exposes no IQueryable; for server-side GROUP BY / SUM, ship one aggregator per backend that injects the backend directly. See Architecture.
- Never query or index an
[Encrypted]field — its ciphertext is non-deterministic. Keep a plain mirror or hash of only what you need. See Security. UpdateAsyncwrites only what you changed, pinned onVersion: it merges onto a newer row unless someone changed the same fields, then throwsConcurrencyException.UpdateConflictMode.Strictrefuses on any change. An entity you built or deserialised is written whole.PatchAsyncchanges a row without reading it:PatchAsync(x => x.Id == id && x.Status == Pending, p => p.Set(x => x.Status, Processing))is one atomic write;Matchedfalse means another writer won. AlsoIncrement,PatchReturn.AfterandPatchManyAsync. A patch never stampsUpdatedAt.- A state change that triggers a side effect is a guarded patch, never a save — two saves of
SentoverPendingboth succeed and the email goes out twice. Act only whenMatched; useIncrementfor counters. - A row a job holds for a while implements
IClaimable:repo.TryClaimAsync(id, TimeSpan.FromMinutes(5)), thenrepo.ReleaseClaimAsync(id, claimedUntil); a crashed job holds it only until the claim lapses. - Make schema changes additive. Two versions share the database during a rolling deploy; renaming or repurposing a field needs both to understand both spellings.
Indexes
Declare secondary indexes once, backend-neutral, with an IIndexSpecProvider (BlazorBlueprint.Application.Persistence.Indexing):
using BlazorBlueprint.Application.Persistence; // AddPluginIndexSpecs<T>using BlazorBlueprint.Application.Persistence.Indexing;using Index = BlazorBlueprint.Application.Persistence.Indexing.Index;
public sealed class MyPluginIndexSpecs : IIndexSpecProvider{ public IReadOnlyDictionary<Type, IndexSpec[]> TenantIndexes { get; } = new Dictionary<Type, IndexSpec[]> { [typeof(Ticket)] = [ Index.Idx(Index.Asc(nameof(Ticket.Status)), Index.Desc(nameof(Ticket.CreatedAt))), Index.Unique(Index.Asc(nameof(Ticket.OrganisationId)), Index.Asc(nameof(Ticket.Reference))) with { Filter = Index.NonEmpty(nameof(Ticket.Reference)) }, ], };}
// In RegisterServicesAsync:services.AddPluginIndexSpecs<MyPluginIndexSpecs>();Factories: Asc, Desc, Idx, Unique, Multikey (array column plus optional scalar tail); filters NotNull, NonEmpty, BoolEqual. Platform-scoped entities go in PlatformIndexes. Give the provider no constructor dependencies — the DbMigrator constructs it by reflection without running RegisterServicesAsync.
Relational backends render specs into their schema. On MongoDB, apply tenant indexes from your setup service’s PreInstallAsync, before seeding, so a unique index can refuse duplicates. The appliers are empty on relational backends, so the code is a no-op there:
protected override async Task PreInstallAsync(Organisation organisation, CancellationToken ct){ foreach (var applier in _indexAppliers) // IEnumerable<IPluginIndexApplier> { await applier.ApplyAsync(organisation.DatabaseName, _indexSpecs.TenantIndexes, ct); // your provider, injected }}Platform indexes are applied on every boot; the DbMigrator reconciles tenant indexes for organisations that already had the plugin.
Settings
Per-organisation settings live in the organisation’s OrganisationPlugins document under your plugin id. Mark the class [PluginSettings], or MongoDB reads it back as a raw document and saves appear to revert:
using BlazorBlueprint.Domain.Attributes;
[PluginSettings]public sealed class MyPluginSettings{ public bool Enabled { get; set; } = true; public int RefreshSeconds { get; set; } = 30;}Derive a scoped service from PluginSettingsServiceBase<TSettings> (BlazorBlueprint.Application.Services.Plugins). It caches, clones on read, evicts only your key on save, and writes one organisation audit row per save:
public sealed class MyPluginSettingsService : PluginSettingsServiceBase<MyPluginSettings>, IMyPluginSettingsService{ public MyPluginSettingsService( IInstalledPluginsService installedPlugins, ICurrentOrganisationService currentOrg, IAppCache cache) : base(installedPlugins, currentOrg, cache) { }
protected override string PluginId => MyPluginEntry.PluginId; protected override string CacheKeyPrefix => "myplugin:settings";
protected override MyPluginSettings Clone(MyPluginSettings s) => new() { Enabled = s.Enabled, RefreshSeconds = s.RefreshSeconds };
protected override void OnBeforeSave(MyPluginSettings s) => s.RefreshSeconds = Math.Clamp(s.RefreshSeconds, 5, 3600);
public Task<MyPluginSettings> GetAsync(CancellationToken ct = default) => GetCurrentSettingsAsync(ct); public Task SaveAsync(MyPluginSettings s, CancellationToken ct = default) => PersistCurrentAsync(s, ct);}- A missing slot reads as
new TSettings(), but a save throws when the plugin is not installed for the organisation. - The organisation-id primitives (
GetSettingsAsync,PersistAsync) still throw unless the scope’s tenant is that organisation — work across organisations from a scope pinned to each. - On MongoDB, choose the class’s name and namespace once: the stored value is tagged with the full type name, so moving it makes saved settings read as defaults.
- A document over 1 MiB is never cached (HybridCache’s payload cap): every read reloads it. Trim unbounded fields in
PrepareForCacheand read the full document withLoadUncachedAsync.
Deployment-wide settings go in the single PlatformPluginInstall row via IPlatformPluginSettingsService.GetAsync<T>(pluginId) / SaveAsync<T>(pluginId, settings), seeded in SeedPlatformDefaultsAsync and edited from a /platform/plugin/{slug}/* page (see ExamplePlatformSettings).
Per-organisation setup
SeedPlatformDefaultsAsyncwrites platform-wide rows (your platform settings, anApiModelfor AI). It runs at every boot, so it must be idempotent.SetupForOrganisationAsyncwrites what one organisation owns, on creation (if the plugin auto-installs) and when an admin enables it. Idempotent too, and never seeds a platform row.TeardownForOrganisationAsyncruns, best-effort, on disable and on organisation deletion, while settings and tenant context still exist. Stop what you own outside your tenant rows (scheduled work, a third-party webhook). Do not delete the organisation’s content — re-enabling should restore a working app, and a deletion whose archive step fails leaves the organisation running.
Implement setup with a service derived from PluginOrganisationSetupBase (BlazorBlueprint.Application.Services.Plugins): PreInstallAsync → seed role definitions → grant the installing user your admin role → write default settings if none exist → PostInstallAsync, returning false on any exception.
public sealed class MyPluginSetupService : PluginOrganisationSetupBase{ public MyPluginSetupService( ILogger<MyPluginSetupService> logger, IInstalledPluginsService installedPlugins, IRoleDefinitionService roleDefinitions, IOrganisationMembershipService memberships) : base(logger, installedPlugins, roleDefinitions, memberships) { }
protected override string PluginId => MyPluginEntry.PluginId; protected override string PluginDisplayName => "My Plugin"; protected override string AdminRoleName => MyPluginRoles.Admin;
protected override IReadOnlyList<PluginRoleDescriptor> RoleDefinitions => [new(MyPluginRoles.Admin, "Configures My Plugin for this organisation.")];
protected override object BuildDefaultPluginSettings() => new MyPluginSettings();}// On the plugin class (IPluginProvisioner). Register MyPluginSetupService as scoped.public Task<bool> SetupForOrganisationAsync( Organisation organisation, string? adminUserId, IServiceProvider services, CancellationToken cancellationToken = default) => services.GetRequiredService<MyPluginSetupService>() .SetupNewOrganisationAsync(organisation, adminUserId, cancellationToken);adminUserId is null when no person triggered the setup; then nobody holds your admin role, and organisation administrators still pass. Resolve from the services you are handed — the caller’s scope, carrying the organisation’s tenant. A fresh scope would write into the wrong database. TeardownForOrganisationAsync(Organisation, IServiceProvider, CancellationToken) takes the same scope.
Match the signatures exactly. Every hook has a default, so a wrong-parameter lookalike compiles while the default runs. The host detects lookalikes at boot and disables the plugin, naming the method.
Configuration
The plugin’s own defaults file
A plugin ships defaults in a {slug}.plugin.json marked CopyToOutputDirectory. Each host adds it as the lowest-precedence configuration source, so appsettings.json, environment variables and the command line override it; no host file needs a block for the plugin. Everything lives under Plugins:{full plugin id}:
{ "Plugins": { "Acme.Plugins.MyPlugin": { "AutoInstall": true, // set the plugin up for every newly created organisation "Disabled": false, // kill switch: services not registered, plugin fully inert "PlatformOnly": false, // overrides Manifest.Scope "RequiresSubscription": false, // overrides Manifest.IsPremium (only enforced when billing is on)
"BackgroundServices": { "MyPluginRetention": { "Enabled": true, "ProcessingIntervalInSeconds": 21600, "MaxAgeInDays": 365 } } } }}| Key | Absent means | Effect |
|---|---|---|
AutoInstall |
false |
true runs SetupForOrganisationAsync for each new organisation. Existing organisations enable it by hand. |
Disabled |
false |
true skips RegisterServicesAsync and ConfigureWebAppAsync: the plugin is absent everywhere, its pages, API and hubs 404, and its handlers never run. Data is kept. Takes a restart. |
PlatformOnly |
the manifest’s Scope |
true hides the plugin from every tenant organisation. |
RequiresSubscription |
the manifest’s IsPremium |
true gates the plugin behind plans that include it. See Billing. |
NavigationMode |
the manifest’s NavigationMode |
Inline or Focused; an unrecognised value is ignored. |
Read overridable values through the host’s helpers — plugin.IsPlatformOnly(configuration), plugin.RequiresSubscription(configuration) (PluginScopeExtensions) and plugin.EffectiveNavigationMode(configuration) — never from the manifest, which would ignore the operator.
Only two kinds of key are read from the file: anything under Plugins:, and your own outbound client under ApiClients:{name} (not ApiClients:Default, nor a client the host registers). Anything else is silently dropped.
The example plugin ships AutoInstall: true in its own file.
Put tunables (cadences, retention, limits) in the JSON, but not a policy the plugin is unsafe without — a JSON file can silently go missing from a publish. A non-idempotent provider’s “never retry” belongs in code, as AddApiClient’s codeDefaults (see Configuration). Keep C# property initialisers as the floor, matching the JSON.
Each HTTP attempt by an AddApiClient client is counted on Platform → API Usage as “Other (apps)” (while Security:Audit:StoreApiUsage is on). services.SetApiClientUsageKind("my-client", null) leaves a client uncounted, or pass a kind such as ApiUsageKind.Sms; ApiUsageAttribution.Begin(payer: ApiUsagePayer.Organisation) (or Platform) records whose account a call used.
Background work
Register sweeps in IPluginBackgroundServices, never RegisterServicesAsync. Derive per-tenant sweeps from PeriodicTenantSweepService (BlazorBlueprint.Application.BackgroundServices), which owns the loop, cancellation and tenant scoping:
public sealed class MyPluginRetentionSweep : PeriodicTenantSweepService{ private readonly IConfigurationSection _config;
public MyPluginRetentionSweep( IServiceScopeFactory scopeFactory, ILogger<MyPluginRetentionSweep> logger, IConfiguration configuration) : base(scopeFactory, logger) => _config = configuration.GetSection($"Plugins:{MyPluginEntry.PluginId}:BackgroundServices:MyPluginRetention");
protected override bool IsEnabled => _config.GetValue("Enabled", true); protected override TimeSpan Interval => TimeSpan.FromSeconds(_config.GetValue("ProcessingIntervalInSeconds", 21600)); protected override bool RunsWhilePluginUnavailable => true; // a retention sweep keeps deleting while the plugin is off
protected override Task TickAsync(CancellationToken cancellationToken) => ForEachOrganisationAsync(async (sp, org, ct) => { // The tenant context is already set on sp for this organisation. var cutoff = DateTime.UtcNow.AddDays(-_config.GetValue("MaxAgeInDays", 365)); var events = sp.GetRequiredService<IRepository<MyEvent>>();
// In batches, up to a budget per tick: one delete over a large backlog (the first run, or // one after an outage) can time out on every tick and never prune anything. for (var deleted = 0L; deleted < 50_000;) { var batch = await events.DeleteManyAsync(e => e.CreatedAt < cutoff, limit: 1000, ct); deleted += batch; if (batch < 1000) break; } }, cancellationToken, includeDeactivated: true); // retention must reach deactivated organisations too}
// On the plugin class:public Task RegisterBackgroundServicesAsync(IServiceCollection services, IConfiguration configuration){ services.AddHostedService<MyPluginRetentionSweep>(); return Task.CompletedTask;}ForEachOrganisationAsyncgives each organisation its own tenant scope and logs and skips one that throws. UseincludeDeactivated: truefor retention, the defaultfalsefor sweeps that generate work.- It visits every organisation; a sweep that sends or creates should first check
IInstalledPluginsService.IsPluginInstalledAsync(org.Id, MyPluginEntry.PluginId). A scope you open yourself needs its tenant set. - A sweep stops with its plugin (disabled, refused at boot, or off at Platform → Apps) and resumes on its own. Retention sweeps override
RunsWhilePluginUnavailable => true. - Every replica runs every sweep. Make
TickAsyncsafe to run twice concurrently, or (if it sends, charges or inserts) overrideRequiresLeaderLock => true. The lease is keyed on the full type name, so moving the class changes it. - A sweep that is not per-organisation loops with
SweepCadence.RunPeriodicAsync(tick, () => interval, name, logger, stoppingToken), which catches per tick, and wraps a tick that must run on one replica inSweepLeaderLock.RunGuardedAsync(…, SweepLeaderLock.LeaseFor(interval), …)— never a longer lease. A hosted service of your own whoseExecuteAsyncthrows is logged at Error and stays stopped until the process restarts, with health still green. - Writing a row per anonymous request owes a retention sweep and a per-organisation ceiling on top of any per-visitor limit. The example’s public form allows 5 an hour per visitor and 100 per organisation (
IRateLimitStore). See Privacy.
Queued jobs and incoming webhooks
A job is a record deriving from ApiJob<TResult> (plain data; under Full it travels on a Redis stream to the BackgroundWorker) or LocalApiJob<TResult> (unserialisable; runs in the calling process). Its handler derives from ApiCallHandler<TJob, TResult> and is found in your assembly with no registration. Submit with IOutboundApiDispatcher.SendAsync(job), or SendAsync(job, organisationId) without an ambient tenant. See ExampleDemoJob, ExampleDurableJob, ExampleLocalJob and the example’s Jobs page.
- Three outcomes: succeeded, failed, or unknown (threw
JobOutcomeUnknownException, timed out, or was cancelled mid-call — the work may have happened).ApiResponse.Match(succeeded, failed, unknown)forces all three; an unset response counts as unknown. Never re-send on unknown what costs money or reaches a person. - Enums travel by name; a number is refused. Add members freely, never rename or remove one. Start your own outcome enums with an
Unset = 0treated as a refusal. MaxAge(default 15 minutes) discards a job left waiting longer, e.g. through a worker outage; money-moving handlers returnNeverDiscard.Timeout(default 60 seconds) is how long a caller waits, and must be less thanMaxAge.- The tenant is set for you from the submitting organisation; a job for a deleted or deactivated organisation fails.
ITenantIndependentJobHandler(BlazorBlueprint.Application.Interfaces.Messaging) is for clean-up that must outlive the organisation; it runs with the tenant cleared. - Fire-and-forget work owes
OnDiscardedAsync(payloadJson, reason, mayAlreadyHaveRun, ct), to give your row a terminal state without calling the provider (recordmayAlreadyHaveRunas unknown). Under Full itsMaxAgemust exceed the reclaim window (Messaging:ClaimIdleMsplus two passes — ten minutes as shipped), or the host refuses to start. RedeliverAfterThrownFailure => truere-runs a fire-and-forget handler after a throw or unknown outcome — only for repeatable work. Otherwise it is dead-lettered.
To receive email, register an IInboundEmailConsumer (DisplayName, ReceiveAsync(InboundEmailMessage, …)) — one per plugin. The host owns the mailbox and its webhook, resolves the organisation, applies the sender check, and calls the one consumer the organisation chose at Admin → Inbound Email (or its only one) in that organisation’s scope, while your plugin is installed and entitled. Be idempotent per (organisation, DedupeKey): a throwing consumer is called again under Full.
An incoming webhook handler derives from InboundWebhookHandler<TCredentials>, registered as IInboundWebhookHandler, and receives /api/webhooks/organisation/{organisationId}/{ProviderName} after signature verification:
- Sign the timestamp with the body.
ExampleHmacInboundWebhookHandlerverifies HMAC-SHA256 over{timestamp}.{raw body}and refuses timestamps more than five minutes off; the host’s duplicate check is time-limited, so a body-only signature can be replayed later. FindCandidatesAsyncmust return the sameIdfor the same stored row every time — the handler runs later (in the worker under Full) against the row with the carried id. Credentials built fresh with new ids get every event dead-lettered.- Make the handler safe to run more than once. If it throws, under Full the host re-runs it after
Messaging:ClaimIdleMs, up toMessaging:MaxDeliveryAttemptstimes; a returned failure is final. Lite does not re-run. - Scope. The default
WebhookScope.Organisationis dispatched only while the organisation has your plugin installed and entitled (otherwise401, and queued events are dead-lettered) — which is what stops a sender still configured after an uninstall.Scope => WebhookScope.Platformreceives/api/webhooks/platform/{ProviderName}under the platform organisation, with no per-organisation check: check any organisation named in the payload yourself. - Listing. Give it a unique letters-only
ProviderName, aDisplayName,DescriptionandSettingsHref; the Webhooks → Incoming pages list it with its address and delivery counts. Names are compared ignoring case: one clashing with any other handler (the host’s included), or a platform-scope handler namedbilling, stops every host from starting.
Both stop with the plugin: while it is disabled or off at Platform → Apps, its webhooks answer 401 and its queued work is refused.
Outgoing webhook events are declared in an IOutboundWebhookEventCatalog and offered to organisations that have your plugin. Fire with IOutboundWebhookEventBus.PublishAsync inside the organisation, or IOrgScopedOutboundWebhookPublisher.PublishForOrganisationAsync from a platform-scoped path; deployment-wide events declare Scope = WebhookScope.Platform and fire through IPlatformOutboundWebhookPublisher.PublishForPlatformAsync. Envelopes over 256 KB are refused, so send identifiers and essential fields.
SignalR hubs
A hub declares everything on the class, as a controller does, and the host finds it and maps it in the process that serves it. You call no MapHub and register nothing:
[EndpointAudience(EndpointAudience.Server)] // BlazorBlueprint.Domain.Attributes and .Enums[EndpointScope(EndpointScope.Organisation)][Route("/hubs/plugin/myplugin")] // Microsoft.AspNetCore.Mvcpublic sealed class MyHub : Hub{}Use /hubs/plugin/{slug}. Under /plugin/{slug}/ the plugin gate 404s a server-side connection, which carries no cookie; under /api/plugin/ a long-polling handshake reaches the wrong tenant resolver. A route with fewer than two segments is logged and not served, and so is one with a [controller] token, which means nothing on a hub. It is MVC’s [Route], as on a controller, and the host reads it itself: a hub is served at one route, its own rather than a base class’s. In a file using Microsoft.AspNetCore.Components, name it in full, since that namespace has a [Route] for pages, which leaves the hub unserved with a warning. A plugin’s hub outside /hubs/plugin/{slug} is logged at startup too, and still served.
Which process serves it follows rule 3 above. A Server hub runs in the InternalApi under Full and the Web host under Lite. Everything Web and the worker send through IHubContext reaches it over the Redis backplane, so Full without Redis refuses to start outside Development. Per-process state in a hub stays in that process, so never read a hub’s static state from a page: share it through IDistributedCache.
External is for a hub a browser must reach directly. It stays on the Web host’s public port, because the InternalApi publishes none.
Every hub refuses a connection without a valid hub token, whichever audience it declares. A page’s CircuitHubDialer presents one for you. A cookie never admits a connection and the handshake never names the tenant, so JavaScript that opens a hub itself gets its token from your server code, and a fresh one for each reconnect, because a token lasts two minutes. Under Lite, and for an External hub under Full, that token is the hub’s only protection.
Template code that should move the same way goes in BlazorBlueprint.Api.Shared, the one template assembly both hosts load. A controller or hub in the Web or InternalApi project stays in that project’s process whatever it declares.
Because the path skips the walls, the hub must declare its tenancy or it is refused at connect:
[EndpointScope(EndpointScope.Organisation)] // one organisation, active members only[EndpointScope(EndpointScope.Organisation, SkipMembershipCheck = true)] // one organisation, visitors allowed (a public widget)[EndpointScope(EndpointScope.Platform)] // deployment-wide, platform admins, no tenantThe hub filter checks membership, security stamp and the plugin gate at connect (and every 60 seconds after), and sets the tenant on every invocation.
- Never accept an
organisationIdor user id as a hub method parameter. ReadHubConnectionTenant.OrganisationId(Context)andHubConnectionTenant.UserId(Context)(null for a visitor). - Open background scopes with
scopeFactory.CreateTenantScope(Context), neverCreateScope(), which has no tenant. - Cap per-connection work on a
SkipMembershipCheckhub. The rate limiter sees only connection opens, never messages. The example’s live hub caps push loops per process and per organisation (LiveHubinexampleplugin.plugin.json). - Use
[Authorize]and the attributes from Authorization for role checks, on the hub or on a method, as on a controller. On the hub it refuses at connect, and on a method it refuses that call. It adds to the checks above: a visitor is refused, and a platform admin still has to pass[EndpointScope]. On such a hubContext.Useris who the token names, with their roles in that organisation; on any other it is not, so readHubConnectionTenant. - Roles are read when a connection opens. Every 60 seconds a connection whose roles have changed is ended, and its client reconnects with the new ones. Over long polling it closes instead, so handle
Closedif your page must keep working.
A hub connection opened by an InteractiveServer page is a server-side call
It runs in the server process, with no cookie and no user. Build it with CircuitHubDialer (BlazorBlueprint.Web.Shared.Hubs), which reads the path from [Route], never your own HubConnectionBuilder:
_hub = HubDialer.ToOrganisationHub<YourHub>(organisationId, userId); // userId null for a visitorif (_hub is null){ return; // the address is unknown; already logged}
_hub.On<string>("Updated", value => InvokeAsync(() => Apply(value)));await _hub.StartAsync();- The address follows the hub’s declaration:
Services:InternalApi:Urlfor a hub the InternalApi serves, otherwise one the server is listening on (ASPNETCORE_URLS), neverNavigationManager.BaseUri: on Blazor Server the browser supplies that, so your token would go to a host the client chose. For any other call to itself, useServerSelfAddress.Resolve. - The token is re-minted on every reconnect and bound to that hub, the session’s stamp and the organisation.
ToPlatformHub<YourHub>does the same for a platform hub.
LiveDemo.razor.cs in the example plugin shows it.
REST controllers
A plugin’s service controllers are [EndpointAudience(EndpointAudience.Server)], live under /api/plugin/{slug}/…, authenticate with the internal service JWT, and run in the InternalApi under Full or the Web host under Lite (rule 3 above). The InternalApi publishes no port, so a browser- or provider-facing endpoint is [EndpointAudience(EndpointAudience.External)], which stays on the Web host and may use any route. It leaves out [EndpointScope] and uses its own authentication, because a scope demands the service JWT, which is never for an outside caller. A scoped controller on the Web host under Full is refused: that host has no bearer scheme.
Declare the route and attributes yourself on a plain ControllerBase: the same three a hub declares. OrganisationApiController and PlatformApiController add nothing you need, and their default route, api/[controller], is outside the prefix the plugin gates key on. As in the example’s CachingApiController:
using BlazorBlueprint.Domain.Attributes; // EndpointAudience, EndpointScopeusing BlazorBlueprint.Domain.Enums; // EndpointScope, EndpointAudience
[ApiController][EndpointAudience(EndpointAudience.Server)][EndpointScope(EndpointScope.Organisation)][Route("api/plugin/myplugin/reports")]public sealed class MyPluginReportsController : ControllerBase{ [HttpGet] public IActionResult Get() => Ok(); // IRepository<T> reads here are scoped to the calling organisation}- You need no
[Authorize]: with a scope, a caller with no valid service token gets401on both hosts. If you add one, nameApiContractNames.BearerScheme, as a bare[Authorize]uses the Web host’s cookie and refuses the service token. - Never use a person’s role attribute here. The caller is a service, so
[AuthorizePluginAdmin]and the like always refuse on a service controller. On a hub, whose caller is a person, they work. - Declare a scope: a
Servercontroller with no[EndpointScope]is refused with a 500,[AllowAnonymous]or not, and logged at startup. If anything outside your server calls it, it isExternal. - Stay under your prefix: a service controller routed outside
api/plugin/{slug}/is logged at startup, as the plugin gates don’t apply there. - An organisation-scoped endpoint answers only while the plugin is loaded, available, enabled for the caller and (if premium) in its plan; a platform-scoped one only checks loaded, enabled and available.
The token flow is in the API reference; ExampleApiClient is the typed client for CachingApiController.
Shipping a plugin
The assembly is the same whichever way it reaches a host; the build-time support differs.
Project reference (this repository)
Add it to Plugins/Plugins.props, as in the quick start. This is the full-capability path: static web assets, build-time dependency checks, a working debugger, and the plugin’s tables in the committed migrations.
NuGet package
CopyToOutputDirectory does not travel in a package, so without extra work consumers silently get no defaults file. As in the example plugin’s .csproj:
- pack the
*.plugin.jsontobuildTransitive/; - pack
Plugins/build/PluginPackage.targetsasbuildTransitive/{PackageId}.targets(NuGet auto-imports that path), which copies the JSON to the host’s output; - keep
PrivateAssets="all"on the host project references.
A plugin’s wwwroot packs and resolves at /_content/{Assembly}/… with no extra work.
Drop-in folder
Copy the plugin into a sub-folder of the Plugins/ folder beside each running host:
Plugins/└── MyPlugin/ ├── Acme.MyPlugin.dll ├── myplugin.plugin.json └── [private dependencies]- Every host needs its own copy: Web, InternalApi (controllers under Full), BackgroundWorker (sweeps, seeding, jobs) and DbMigrator (schema and MongoDB indexes). In
Developmentthe Web host also readsWeb/BlazorBlueprint.Web/Plugins/when run from source. - The sub-folder is mandatory; a loose DLL is ignored silently.
- Copy the plugin and its private dependencies only; anything the host ships resolves from the host.
- Discovered once, at startup — restart after adding.
- No static web assets: the
/_content/manifest is built with the host, so a drop-in plugin’s CSS and JS 404. A plugin with awwwrootneeds a project or package reference. - On PostgreSQL or SQL Server its tables do not exist yet and no migration can add them: set
Database:AllowPluginSchemaDropIn, and they are created on a tenant’s first request or when the DbMigrator runs (Relational migrations).
The shipped compose files run containers read_only: true, so add a read-only bind mount to each service that needs the plugin — and treat write access to that directory as write access to the application:
volumes: - ./plugins:/app/Plugins:roDependency versions
For anything the host ships there is exactly one copy in the process — the host’s (two same-named assemblies would be different CLR types). A drop-in folder’s load context isolates private dependencies only.
- Reference host assemblies with
ExcludeAssets="runtime" PrivateAssets="all". - Don’t depend on a different major version of anything the host ships; you get the host’s, and a missing API fails with
MissingMethodExceptionat the point of use. - Treat the host’s
Directory.Packages.propsas the shared version contract. Only the reference path catches conflicts at build time.
The host skips (and logs) a plugin whose MinHostVersion is newer than it, or that was compiled against newer BlazorBlueprint.* assemblies. Older plugins are not rejected but can fail at run time — rebuild against each release you take. The host version is the repository’s VERSION file; keep upstream’s value on each merge.
Installing and enabling
A plugin must pass three layers to appear in an organisation:
- Loaded — present and not
Disabledin configuration. A process-level kill switch that always wins. - Platform policy — Platform → Apps stores two flags per plugin, outranking configuration once changed (the page cannot reset them):
- Available — off hides the plugin from every organisation, 404s all its routes (including any its assembly maps outside the plugin prefixes), refuses its hubs, stops dispatching its webhooks and jobs and pauses its sweeps. Data is kept. On by default.
- AutoInstall — from configuration until changed.
- Per-organisation — Admin → Apps. Enable runs
SetupForOrganisationAsync; Disable runsTeardownForOrganisationAsyncand removes the plugin’s entry fromOrganisationPlugins— its settings go with it; entity rows are kept.
For an organisation without the plugin, a member navigating to its page lands on /apps/not-enabled; other requests 404, hubs are refused and circuits are ended. Routes outside the plugin prefixes are attributed to your plugin by the code behind them and checked the same way — for anonymous callers too, against the resolved organisation. On the platform host that is the platform organisation, so a callback there needs your plugin installed for it (or use a platform-scope IInboundWebhookHandler).
A plugin missing from one organisation: check its Admin → Apps. Missing everywhere: check Available, then configuration. Premium plugins also need an entitled plan.
From code: IPluginCatalog.IsPluginEnabledForOrganisationAsync(pluginId, organisationId, services) applies the nav’s checks (pass your scope, or it answers false). IPluginInstallation.UninstallPluginForOrganisationAsync does what Disable does and returns Uninstalled, NotInstalled, Busy (an install is in progress — retry) or Failed.
Upgrading a plugin
Installing needs no extra step on MongoDB; on a relational backend it needs a migration or Database:AllowPluginSchemaDropIn. Upgrading to a version that changes the plugin’s schema needs the DbMigrator or a migration, and nothing stops you deploying without it.
| Backend | Upgrading a changed schema |
|---|---|
| MongoDB | A new index is not created for organisations that already had the previous version until the DbMigrator reconciles indexes. Until then a new unique index enforces nothing — quietly. |
| PostgreSQL / SQL Server | A new table is created by the additive pass or a new migration. A new column needs a new named migration (never regenerate the set) — the additive pass cannot ALTER; until it is applied, the schema gate takes the plugin offline for that organisation. A new index is not detected at run time on any backend. |
Run the DbMigrator whenever a plugin’s version changes. It is idempotent and exits non-zero if any organisation fails. See Relational migrations. Missing tables or columns degrade only that plugin.
Logging and telemetry
A plugin logs through ILogger<T> and inherits the host’s console and OpenTelemetry setup, inside the current request, circuit, job or sweep scope.
- Templates are constants (
_logger.LogWarning("Booking {BookingId} could not be confirmed", id), never$"…"). Log ids, never names, addresses, phone numbers or typed text. - Conditions an anonymous caller can trigger go through a
LogThrottle(BlazorBlueprint.Application.Services.Common): onestatic readonlythrottle per condition, keyed per item (capped) when one item can be hit constantly. - Never log another system’s text verbatim: use
ProviderResponseSummary.Of(…)for provider bodies andLogRedaction.Emails(…)for messages that may quote an address (a job’sErrorMessage, say). - Scopes:
LogScope.Of("Key", value, …), not aDictionary. - A meter or ActivitySource named
BlazorBlueprint.Plugins.{YourName}is exported automatically. Tag with closed sets, never organisation or user ids; each metric is capped atTelemetry:MaxSeriesPerMetricseries. - Sweeps and jobs are already measured, on the Background Sweeps and Messaging & Jobs dashboards.
- Audit through
IUserAuditService/IPlatformAuditService, never your own table.
Host primitives
Services the host registers for plugins. Inject them rather than building your own.
Email. Ask IEmailDeliverability.CanSendAsync(organisationId) (or CanSendToAsync(organisationId, recipient), which also checks the suppression list) before promising anyone an email or creating anything whose only way out is one. Then IEmailOutbox.QueueAsync(new EmailMessage { To, Subject, HtmlBody, TextBody }) — queued, not sent; the outbox sweep delivers it. Email ships disabled, and mail queued while it is unconfigured is discarded, not held.
Another organisation’s data. ForEachOrganisationAsync (sweeps), job handlers and the hub filter set the tenant for you. If you must set one yourself, use ITenantContextSetter only in a child scope: resolve the organisation by id from IPlatformRepository<Organisation>, SetTenant(organisation.DatabaseName, organisation.Id), do the work, ClearTenant() in a finally. Never set it mid-request on the caller’s scope. In this repository TenantContextSetterContractTests fails on a new SetTenant/ClearTenant call under Plugins/ until its file is added to PermittedPluginCallers.
AI. Go through IPluginAiDispatcher, never a provider or HttpClient of your own. Your platform settings class implements IPluginAiPlatformSettings (ModelId), and SeedPlatformDefaultsAsync calls PluginPlatformDefaults.SeedAiModelAsync<TSettings>(services, pluginId, modelName) to seed one ApiModel named after the plugin. ResolveModelAsync<TSettings> returning null means AI is off for this deployment. RunChatCompletionAsync<TSettings> returns the answer, and SubmitChatCompletionAsync<TSettings> queues it for your result handler. Put per-task instructions in system prompts, not extra models. A plugin that moderates also calls PluginPlatformDefaults.SeedModerationModelAsync(services), which seeds one model shared across plugins, and ResolveModerationTargetAsync to find where to send a check; null means moderation can’t run.
Fire-and-forget requests. IApiRequestDispatcher.SubmitAsync(new ApiRequestJob { RequestType, OrganisationId, PluginId, CallbackKey, PayloadJson }) runs your IApiRequestProcessor (one per RequestType; prefix it with your slug, because the first registration wins a clash). The answer goes to your one IApiRequestResultHandler (matched by PluginId) as an ApiRequestResult with IsSuccess and OutcomeUnknown. Register both in RegisterServicesAsync, since under Full the worker runs them. Write your tracking row before submitting — in-process, the answer can arrive before SubmitAsync returns — and use its id as CallbackKey. If SubmitAsync throws JobNotPublishedException, the job definitely never left and is safe to resend. Treat any other exception as an unknown outcome (ExampleBackgroundRequests).
Files. Store and read files only through IFileService (UploadAsync, OpenReadAsync, GetPageForOwnerAsync, DeleteAsync), or the <FileUpload> component, which uses it. Never inject IFileStorage, IFileStorageFactory or the tenant file store: they write raw bytes, skipping the StoredFile row, the size cap, the content checks and the encryption. The example plugin’s convention suite fails on any of its own source naming them — copy that test (ExamplePluginConventionTests) into your plugin’s tests to get the same guard. Link a file by StoredFile.Id, and pass arguments after ownerId by name.
UploadAsync takes an optional serveMode:
- Leave it
null(the default) for almost everything: the file follows the platform’s Platform → Storage serve mode at each download. FileServeMode.Proxy— always stream it through the app, encrypted while encryption is on, whatever the platform setting. Use it for documents and anything sensitive.FileServeMode.Direct— hand the browser a short-lived signed URL, so large media (video) skips the app. The browser fetches the stored bytes, so the file is stored without the app’s encryption; say so in your plugin’s documentation, or offer your own setting for it. Honoured only for aMemberfile on Azure Blob or S3; elsewhere, and for aPublicfile, it is recorded asnull.
Code that copies a file passes the source’s StoredFile.ServeMode. A plugin cannot turn encryption on: with Security:Encryption:Enabled off, every file is stored plain whatever it asks. The row records how each file was stored (StoredFile.Encrypted, ServeMode); reads follow it, so a later settings change never breaks a file. See Security → Stored files.
Idempotent inserts. Back “create once” with a unique index and catch DuplicateKeyException (BlazorBlueprint.Application.Exceptions) as “another writer already did it”.
Untrusted markdown renders through IMarkdownRenderer.ToHtml(markdown), which escapes raw HTML and sanitises the output, so it is safe for MarkupString.
Operator- or user-supplied URLs you call. Check IUrlSafetyValidator.ValidateAsync(url) (IsAllowed, Reason) when the URL is saved and again before every call, because DNS can change in between.
In-app notifications. Derive from PluginNotifierBase and call FanOutAsync(recipientUserIds, userId => (title, message), link). It drops the actor, duplicates and anyone no longer a member, and writes the rest in one batched insert. Recipient lists built from your own rows outlive membership, so the ex-member filter is a privacy control.
Absolute links. IOrganisationUrlResolver.ResolveAbsoluteUrlAsync(path, organisationId) returns the link on the organisation’s own address (subdomain or platform host). It never uses the request, so a page and a job agree. Null means no platform address is set: send no link.
Dates. Times are stored in UTC. ITenantTimeZoneAccessor.GetAsync() gives the organisation’s time zone, cached per scope; convert with TenantTime.ToLocal / ToUtc.
Is my plugin servable here? Anything you show outside your own routes (a floating widget, a page on a customer hostname) must ask IPluginAccessGate.EvaluateAsync("/plugin/{slug}", null, requestServices) == PluginAccessVerdict.Allow as well as checking your own setting. Otherwise it stays up when the operator switches the plugin off (ExamplePublicRoutes.IsServableAsync).
Budgets for costly actions. Count anything that spends the operator’s money or capacity per press (AI, SMS, email, jobs, test webhooks, notifications) in IRateLimitStore.IncrementAsync(key, window). Use two keys: a per-organisation key, and a per-user key that names no organisation, so creating a second organisation buys no second budget. Never use IMemoryCache, which gives each replica its own count (ExampleUsageLimits).
Shared UI (BlazorBlueprint.Web.Shared.Components):
<PageHead Title Description NoIndex />— the page title with the site suffix; setNoIndexon private pages.<ConsoleStyles />— once per page; thebb-pa-*classes the host’s admin pages use.<ConsoleSubpage Open Title BackLabel OnClose>— a form or detail view shown in place of the screen, at the same address, with a “Back to …” link; everything else in thebb-pa-pagehides while it is open, so it fits a phone. One open at a time; a picker inside the form is an expanding section of that form. With a<Footer>(a sticky action bar), wrap the body in<ChildContent>.<ConsoleConfirm Open Title Tone For OnCancel>— an inline confirmation card (“Delete this?”) with its buttons in<Actions>; place it under the page header.Toneisdanger(default),warningorinfo. PassFor(the row it is about) so asking about another row brings the card back into view, and your Cancel handler asOnCancelso it cancels itself when a subpage opens; leaveOnCancelout for a card that must survive that, such as a secret shown once. Closing either view returns the person to the control they used and their scroll position. The console has no modal pop-ups.<FileUpload OwnerType OwnerId Accept Visibility Scope ServeMode OnUploaded />— stores throughIFileService(ServeModeas above).<UnsavedChangesLock Dirty="IsDirty" />— warns before someone leaves a form with unsaved changes, by a link, Back, closing the tab or refreshing. Give itIsDirty() => FormSnapshot.IsDirty(_model, _snapshot), and set_snapshot = FormSnapshot.Of(_model)after loading and after every save, before any redirect. Pass separate fields as one anonymous object. A save that then usesNavigateTo(url, forceLoad: true)first awaits the lock’sSyncAsync(), through@ref.IToastNotificationService.ShowSuccess/ShowError/ShowInfo. Show an exception’sMessageonly forPluginValidationExceptionorUserFacingException, which are written for the user; anything else gets your own sentence.
Under a chrome takeover, read what the host would have rendered from IEffectiveOrganisationSettingsService: GetSiteSettingsAsync() for the organisation’s own name (SiteHeader) and theme, never Organisation.Name (a routing key); GetEffectiveCookieConsentSettingsAsync() and GetEffectiveOrganisationIdForBrandingAsync() (for LegalPolicyLinks.GetAsync) for the deployment’s consent banner and policies (ExamplePublicFooter).
Extension points at a glance
Registered in RegisterServicesAsync unless noted. None needs a host edit.
| Extension point | Contributes |
|---|---|
| The opt-in interfaces (on the plugin class) | Pages and layout components, setup and teardown, sweeps, startup work, hubs and endpoints |
ApiCallHandler<TJob, TResult> (found in your assembly) |
A queued job handler |
IInboundWebhookHandler |
A signature-verified provider callback (organisation or platform scope) |
IInboundEmailConsumer |
The app an organisation’s inbound email goes to |
IOutboundWebhookEventCatalog |
Outgoing webhook events organisations can subscribe to |
IPluginSectionNavProvider |
Dynamic rows in your app’s sidebar group |
IPublicRouteAllowList |
Routes on the application hosts reachable by visitors and non-members |
IPublicPageProvider |
A website served on an organisation’s own hostnames |
IAnalyticsRedactionProvider |
Route templates whose path secrets are redacted from analytics |
IInAppSitePreview |
A members-only in-app site preview with the site’s document head |
IPluginChromeProvider |
Taking pages over from the platform header, sidebar, page meta and footer |
IIndexSpecProvider (via AddPluginIndexSpecs<T>()) |
Secondary indexes |
IOrganisationCascadeContributor |
Cleanup of platform-scoped rows when an organisation is deleted |
IOrganisationDeletionGuard |
Objections to deleting an organisation (GetBlockersAsync → OrganisationDeletionBlocker(Reason, ActionHref?)), which a platform admin must explicitly override (matched by Reason — keep it stable). A throw objects. Keep it read-only and quick |
SubscriptionPlanFeatures (on the manifest) |
Plan features the operator can grant — see Plan features |
IPaymentSourceDescriber |
What each of your payments was for (“Invoice INV-0042”, with a link) on Payments Received. Override DescribeManyAsync to describe a page in one query |
IStoredFileReadAuthorizer |
Who may read your Member files — see Authorization |
IPlatformPaymentEventHandler |
For selling through the operator’s account (CreatePlatformCheckoutJob, IPlatformBillingService.ChargeStoredAsync): told when a charge is paid, refunded, disputed, a dispute is won, or failed (not always final — a Paid may follow a retried card). The host confirms and reconciles charges; you need no webhook of your own |
Taking money. Stamp PluginId and ExternalReferenceId on every PaymentInitiation or PlatformStoredChargeRequest; the host then records the charge on the organisation’s Payments Received page (its own provider) or on /Platform/Billing and the organisation’s billing history (the operator’s account), with no ledger code in the plugin. Refund with IPaymentService.RefundAsync — from a button, use the overload taking expectedRefundedMicros (the total the page showed) so a retried click is not refunded twice — or RefundPlatformPaymentJob for the operator’s account. Each holds one account per provider, so a plugin never picks one; IPlatformApiIntegrationService.FindForProviderAsync names the platform’s if you need to record it. Payment events arrive through IPaymentEventHandler (an organisation’s account) or IPlatformPaymentEventHandler (the operator’s). Both must be idempotent per event — a repaired webhook replays what it missed.
Shared building blocks to use rather than re-implement: PluginSettingsServiceBase<T>, PluginOrganisationSetupBase, PeriodicTenantSweepService, PrefixPublicRouteAllowList, PluginRoles, LegalPolicyLinks, the host primitives, and the host services listed under Architecture (payments, SMS, files, PDFs, webhooks, AI).